construct-hub 0.2.57 → 0.2.58
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.gitattributes +0 -1
- package/.jsii +2 -2
- package/lib/backend/catalog-builder/catalog-builder.bundle/index.js +1 -1
- package/lib/backend/catalog-builder/catalog-builder.bundle/index.js.map +1 -1
- package/lib/backend/catalog-builder/catalog-builder.lambda.js +2 -2
- package/lib/backend/ingestion/ingestion.bundle/index.js +3 -3
- package/lib/backend/ingestion/ingestion.bundle/index.js.map +1 -1
- package/lib/backend/ingestion/ingestion.lambda.js +4 -4
- package/lib/backend/package-stats/package-stats.bundle/index.js +1 -1
- package/lib/backend/package-stats/package-stats.bundle/index.js.map +1 -1
- package/lib/backend/package-stats/package-stats.lambda.js +2 -2
- package/lib/backend/transliterator/transliterator.bundle/index.js +1 -1
- package/lib/backend/transliterator/transliterator.bundle/index.js.map +1 -1
- package/lib/backend/transliterator/transliterator.ecstask.js +2 -2
- package/lib/construct-hub.js +1 -1
- package/lib/package-sources/code-artifact.js +1 -1
- package/lib/package-sources/npmjs.js +1 -1
- package/lib/package-tag/index.js +2 -2
- package/lib/spdx-license.js +1 -1
- package/lib/webapp/index.js +10 -4
- package/package.json +1 -2
- package/lib/webapp/cache-invalidator/constants.d.ts +0 -4
- package/lib/webapp/cache-invalidator/constants.js +0 -5
- package/lib/webapp/cache-invalidator/handler.bundle/index.js +0 -1404
- package/lib/webapp/cache-invalidator/handler.bundle/index.js.map +0 -7
- package/lib/webapp/cache-invalidator/handler.d.ts +0 -7
- package/lib/webapp/cache-invalidator/handler.js +0 -19
- package/lib/webapp/cache-invalidator/handler.lambda.d.ts +0 -3
- package/lib/webapp/cache-invalidator/handler.lambda.js +0 -42
- package/lib/webapp/cache-invalidator/index.d.ts +0 -34
- package/lib/webapp/cache-invalidator/index.js +0 -57
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../../node_modules/aws-embedded-metrics/lib/Constants.js", "../../../../node_modules/aws-embedded-metrics/lib/environment/Environments.js", "../../../../node_modules/aws-embedded-metrics/lib/config/EnvironmentConfigurationProvider.js", "../../../../node_modules/aws-embedded-metrics/lib/config/Configuration.js", "../../../../node_modules/aws-embedded-metrics/lib/utils/Logger.js", "../../../../node_modules/aws-embedded-metrics/lib/logger/MetricValues.js", "../../../../node_modules/aws-embedded-metrics/lib/logger/MetricsContext.js", "../../../../node_modules/aws-embedded-metrics/lib/logger/MetricsLogger.js", "../../../../node_modules/aws-embedded-metrics/lib/serializers/LogSerializer.js", "../../../../node_modules/aws-embedded-metrics/lib/sinks/ConsoleSink.js", "../../../../node_modules/aws-embedded-metrics/lib/sinks/connections/TcpClient.js", "../../../../node_modules/aws-embedded-metrics/lib/sinks/connections/UdpClient.js", "../../../../node_modules/aws-embedded-metrics/lib/sinks/AgentSink.js", "../../../../node_modules/aws-embedded-metrics/lib/environment/DefaultEnvironment.js", "../../../../node_modules/aws-embedded-metrics/lib/utils/Fetch.js", "../../../../node_modules/aws-embedded-metrics/lib/environment/ECSEnvironment.js", "../../../../node_modules/aws-embedded-metrics/lib/environment/EC2Environment.js", "../../../../node_modules/aws-embedded-metrics/lib/environment/LambdaEnvironment.js", "../../../../node_modules/aws-embedded-metrics/lib/environment/LocalEnvironment.js", "../../../../node_modules/aws-embedded-metrics/lib/environment/EnvironmentDetector.js", "../../../../node_modules/aws-embedded-metrics/lib/logger/MetricsLoggerFactory.js", "../../../../node_modules/aws-embedded-metrics/lib/logger/MetricScope.js", "../../../../node_modules/aws-embedded-metrics/lib/logger/Unit.js", "../../../../node_modules/aws-embedded-metrics/lib/index.js", "../../../../node_modules/@sindresorhus/is/dist/index.js", "../../../../node_modules/p-cancelable/index.js", "../../../../node_modules/defer-to-connect/dist/source/index.js", "../../../../node_modules/@szmarczak/http-timer/dist/source/index.js", "../../../../node_modules/cacheable-lookup/source/index.js", "../../../../node_modules/normalize-url/index.js", "../../../../node_modules/wrappy/wrappy.js", "../../../../node_modules/once/once.js", "../../../../node_modules/end-of-stream/index.js", "../../../../node_modules/pump/index.js", "../../../../node_modules/get-stream/buffer-stream.js", "../../../../node_modules/get-stream/index.js", "../../../../node_modules/http-cache-semantics/index.js", "../../../../node_modules/lowercase-keys/index.js", "../../../../node_modules/responselike/src/index.js", "../../../../node_modules/mimic-response/index.js", "../../../../node_modules/clone-response/src/index.js", "../../../../node_modules/json-buffer/index.js", "../../../../node_modules/keyv/src/index.js", "../../../../node_modules/cacheable-request/src/index.js", "../../../../node_modules/decompress-response/node_modules/mimic-response/index.js", "../../../../node_modules/decompress-response/index.js", "../../../../node_modules/quick-lru/index.js", "../../../../node_modules/http2-wrapper/source/agent.js", "../../../../node_modules/http2-wrapper/source/incoming-message.js", "../../../../node_modules/http2-wrapper/source/utils/url-to-options.js", "../../../../node_modules/http2-wrapper/source/utils/proxy-events.js", "../../../../node_modules/http2-wrapper/source/utils/is-request-pseudo-header.js", "../../../../node_modules/http2-wrapper/source/utils/errors.js", "../../../../node_modules/http2-wrapper/source/client-request.js", "../../../../node_modules/resolve-alpn/index.js", "../../../../node_modules/http2-wrapper/source/utils/calculate-server-name.js", "../../../../node_modules/http2-wrapper/source/auto.js", "../../../../node_modules/http2-wrapper/source/index.js", "../../../../node_modules/got/dist/source/core/utils/is-form-data.js", "../../../../node_modules/got/dist/source/core/utils/get-body-size.js", "../../../../node_modules/got/dist/source/core/utils/proxy-events.js", "../../../../node_modules/got/dist/source/core/utils/unhandle.js", "../../../../node_modules/got/dist/source/core/utils/timed-out.js", "../../../../node_modules/got/dist/source/core/utils/url-to-options.js", "../../../../node_modules/got/dist/source/core/utils/options-to-url.js", "../../../../node_modules/got/dist/source/core/utils/weakable-map.js", "../../../../node_modules/got/dist/source/core/utils/get-buffer.js", "../../../../node_modules/got/dist/source/core/utils/dns-ip-version.js", "../../../../node_modules/got/dist/source/core/utils/is-response-ok.js", "../../../../node_modules/got/dist/source/utils/deprecation-warning.js", "../../../../node_modules/got/dist/source/as-promise/normalize-arguments.js", "../../../../node_modules/got/dist/source/core/calculate-retry-delay.js", "../../../../node_modules/got/dist/source/core/index.js", "../../../../node_modules/got/dist/source/as-promise/types.js", "../../../../node_modules/got/dist/source/as-promise/parse-body.js", "../../../../node_modules/got/dist/source/as-promise/index.js", "../../../../node_modules/got/dist/source/as-promise/create-rejection.js", "../../../../node_modules/got/dist/source/utils/deep-freeze.js", "../../../../node_modules/got/dist/source/types.js", "../../../../node_modules/got/dist/source/create.js", "../../../../node_modules/got/dist/source/index.js", "../../../../node_modules/shimmer/index.js", "../../../../node_modules/emitter-listener/listener.js", "../../../../node_modules/cls-hooked/context.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/logger.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/segments/attributes/captured_exception.js", "../../../../node_modules/atomic-batcher/index.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/daemon_config.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/segment_emitter.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/segments/attributes/trace_id.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/utils.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/segments/segment_utils.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/segments/attributes/remote_request_data.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/segments/attributes/subsegment.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/segments/segment.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/context_utils.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/middleware/incoming_request_data.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/middleware/sampling/local_reservoir.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/middleware/sampling/local_sampler.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/middleware/sampling/reservoir.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/middleware/sampling/sampling_rule.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/middleware/sampling/service_connector.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/middleware/sampling/rule_cache.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/middleware/sampling/rule_poller.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/middleware/sampling/target_poller.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/middleware/sampling/default_sampler.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/middleware/mw_utils.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/env/aws_lambda.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/segments/plugins/plugin.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/segments/plugins/ec2_plugin.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/segments/plugins/ecs_plugin.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/segments/plugins/elastic_beanstalk_plugin.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/patchers/call_capturer.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/segments/attributes/aws.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/capture.js", "../../../../node_modules/aws-xray-sdk-core/node_modules/semver/semver.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/patchers/aws_p.js", "../../../../node_modules/@aws-sdk/service-error-classification/dist-cjs/constants.js", "../../../../node_modules/@aws-sdk/service-error-classification/dist-cjs/index.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/patchers/aws3_p.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/patchers/http_p.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/patchers/promise_p.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/database/sql_data.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/aws-xray.js", "../../../../node_modules/aws-xray-sdk-core/dist/lib/index.js", "../../../../src/backend/package-stats/package-stats.lambda.ts", "../../../../src/backend/shared/aws.lambda-shared.ts", "../../../../src/backend/shared/env.lambda-shared.ts", "../../../../src/backend/catalog-builder/client.lambda-shared.ts", "../../../../src/backend/package-stats/constants.ts", "../../../../src/backend/package-stats/npm-downloads.lambda-shared.ts"],
|
4
|
-
"sourcesContent": ["\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Constants;\n(function (Constants) {\n Constants[Constants[\"MAX_DIMENSIONS\"] = 9] = \"MAX_DIMENSIONS\";\n Constants[\"DEFAULT_NAMESPACE\"] = \"aws-embedded-metrics\";\n Constants[Constants[\"MAX_METRICS_PER_EVENT\"] = 100] = \"MAX_METRICS_PER_EVENT\";\n Constants[\"DEFAULT_AGENT_HOST\"] = \"0.0.0.0\";\n Constants[Constants[\"DEFAULT_AGENT_PORT\"] = 25888] = \"DEFAULT_AGENT_PORT\";\n})(Constants = exports.Constants || (exports.Constants = {}));\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Environments;\n(function (Environments) {\n Environments[\"Local\"] = \"Local\";\n Environments[\"Lambda\"] = \"Lambda\";\n Environments[\"Agent\"] = \"Agent\";\n Environments[\"EC2\"] = \"EC2\";\n Environments[\"ECS\"] = \"ECS\";\n Environments[\"Unknown\"] = \"\";\n})(Environments || (Environments = {}));\nexports.default = Environments;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Constants_1 = require(\"../Constants\");\nconst Environments_1 = require(\"../environment/Environments\");\nconst ENV_VAR_PREFIX = 'AWS_EMF';\nvar ConfigKeys;\n(function (ConfigKeys) {\n ConfigKeys[\"LOG_GROUP_NAME\"] = \"LOG_GROUP_NAME\";\n ConfigKeys[\"LOG_STREAM_NAME\"] = \"LOG_STREAM_NAME\";\n ConfigKeys[\"ENABLE_DEBUG_LOGGING\"] = \"ENABLE_DEBUG_LOGGING\";\n ConfigKeys[\"SERVICE_NAME\"] = \"SERVICE_NAME\";\n ConfigKeys[\"SERVICE_TYPE\"] = \"SERVICE_TYPE\";\n ConfigKeys[\"AGENT_ENDPOINT\"] = \"AGENT_ENDPOINT\";\n ConfigKeys[\"ENVIRONMENT_OVERRIDE\"] = \"ENVIRONMENT\";\n ConfigKeys[\"NAMESPACE\"] = \"NAMESPACE\";\n})(ConfigKeys || (ConfigKeys = {}));\nclass EnvironmentConfigurationProvider {\n getConfiguration() {\n return {\n agentEndpoint: this.getEnvVariable(ConfigKeys.AGENT_ENDPOINT),\n debuggingLoggingEnabled: this.tryGetEnvVariableAsBoolean(ConfigKeys.ENABLE_DEBUG_LOGGING, false),\n logGroupName: this.getEnvVariable(ConfigKeys.LOG_GROUP_NAME),\n logStreamName: this.getEnvVariable(ConfigKeys.LOG_STREAM_NAME),\n serviceName: this.getEnvVariable(ConfigKeys.SERVICE_NAME) || this.getEnvVariableWithoutPrefix(ConfigKeys.SERVICE_NAME),\n serviceType: this.getEnvVariable(ConfigKeys.SERVICE_TYPE) || this.getEnvVariableWithoutPrefix(ConfigKeys.SERVICE_TYPE),\n environmentOverride: this.getEnvironmentOverride(),\n namespace: this.getEnvVariable(ConfigKeys.NAMESPACE) || Constants_1.Constants.DEFAULT_NAMESPACE,\n };\n }\n getEnvVariableWithoutPrefix(configKey) {\n return process.env[configKey];\n }\n getEnvVariable(configKey) {\n return process.env[`${ENV_VAR_PREFIX}_${configKey}`];\n }\n tryGetEnvVariableAsBoolean(configKey, fallback) {\n const configValue = this.getEnvVariable(configKey);\n return !configValue ? fallback : configValue.toLowerCase() === 'true';\n }\n getEnvironmentOverride() {\n const overrideValue = this.getEnvVariable(ConfigKeys.ENVIRONMENT_OVERRIDE);\n const environment = Environments_1.default[overrideValue];\n if (environment === undefined) {\n return Environments_1.default.Unknown;\n }\n return environment;\n }\n}\nexports.EnvironmentConfigurationProvider = EnvironmentConfigurationProvider;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst EnvironmentConfigurationProvider_1 = require(\"./EnvironmentConfigurationProvider\");\nconst Configuration = new EnvironmentConfigurationProvider_1.EnvironmentConfigurationProvider().getConfiguration();\nexports.default = Configuration;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Configuration_1 = require(\"../config/Configuration\");\nconst LOG = (...args) => {\n if (Configuration_1.default.debuggingLoggingEnabled) {\n console.log(...args);\n }\n};\nexports.LOG = LOG;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass MetricValues {\n constructor(value, unit) {\n this.values = [value];\n this.unit = unit || 'None';\n }\n /**\n * Appends the provided value to the current metric\n * @param value\n */\n addValue(value) {\n this.values.push(value);\n }\n}\nexports.MetricValues = MetricValues;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Configuration_1 = require(\"../config/Configuration\");\nconst Logger_1 = require(\"../utils/Logger\");\nconst MetricValues_1 = require(\"./MetricValues\");\nclass MetricsContext {\n /**\n * Constructor used to create child instances.\n * You should not use this constructor directly.\n * Instead, use createCopyWithContext() or empty().\n *\n * The reason for this is to avoid unexpected behavior when creating\n * MetricsContexts with defaultDimensions and existing dimensions.\n *\n * @param properties\n * @param dimensions\n */\n constructor(namespace, properties, dimensions, defaultDimensions, shouldUseDefaultDimensions, timestamp) {\n this.metrics = new Map();\n this.meta = {};\n this.shouldUseDefaultDimensions = true;\n this.namespace = namespace || Configuration_1.default.namespace;\n this.properties = properties || {};\n this.dimensions = dimensions || [];\n this.timestamp = timestamp;\n this.meta.Timestamp = MetricsContext.resolveMetaTimestamp(timestamp);\n this.defaultDimensions = defaultDimensions || {};\n if (shouldUseDefaultDimensions != undefined) {\n this.shouldUseDefaultDimensions = shouldUseDefaultDimensions;\n }\n }\n /**\n * Use this to create a new, empty context.\n */\n static empty() {\n return new MetricsContext();\n }\n static resolveMetaTimestamp(timestamp) {\n if (timestamp instanceof Date) {\n return timestamp.getTime();\n }\n else if (timestamp) {\n return timestamp;\n }\n else {\n return Date.now();\n }\n }\n setNamespace(value) {\n this.namespace = value;\n }\n setProperty(key, value) {\n this.properties[key] = value;\n }\n setTimestamp(timestamp) {\n this.timestamp = timestamp;\n this.meta.Timestamp = MetricsContext.resolveMetaTimestamp(timestamp);\n }\n /**\n * Sets default dimensions for the Context.\n * A dimension set will be created with just the default dimensions\n * and all calls to putDimensions will be prepended with the defaults.\n */\n setDefaultDimensions(dimensions) {\n Logger_1.LOG(`Received default dimensions`, dimensions);\n this.defaultDimensions = dimensions;\n }\n /**\n * Adds a new set of dimensions. Any time a new dimensions set\n * is added, the set is first prepended by the default dimensions.\n *\n * @param dimensions\n */\n putDimensions(incomingDimensionSet) {\n if (this.dimensions.length === 0) {\n this.dimensions.push(incomingDimensionSet);\n return;\n }\n for (let i = 0; i < this.dimensions.length; i++) {\n const existingDimensionSet = this.dimensions[i];\n // check for duplicate dimensions when putting\n // this is an O(n^2) operation, but since we never expect to have more than\n // 10 dimensions, this is acceptable for almost all cases.\n // This makes re-using loggers much easier.\n const existingDimensionSetKeys = Object.keys(existingDimensionSet);\n const incomingDimensionSetKeys = Object.keys(incomingDimensionSet);\n if (existingDimensionSetKeys.length !== incomingDimensionSetKeys.length) {\n this.dimensions.push(incomingDimensionSet);\n return;\n }\n for (let j = 0; j < existingDimensionSetKeys.length; j++) {\n if (!incomingDimensionSetKeys.includes(existingDimensionSetKeys[j])) {\n // we're done now because we know that the dimensions keys are not identical\n this.dimensions.push(incomingDimensionSet);\n return;\n }\n }\n }\n }\n /**\n * Overwrite all dimensions.\n *\n * @param dimensionSets\n */\n setDimensions(dimensionSets) {\n this.shouldUseDefaultDimensions = false;\n this.dimensions = dimensionSets;\n }\n /**\n * Get the current dimensions.\n */\n getDimensions() {\n // caller has explicitly called setDimensions\n if (this.shouldUseDefaultDimensions === false) {\n return this.dimensions;\n }\n // if there are no default dimensions, return the custom dimensions\n if (Object.keys(this.defaultDimensions).length === 0) {\n return this.dimensions;\n }\n // if default dimensions have been provided, but no custom dimensions, use the defaults\n if (this.dimensions.length === 0) {\n return [this.defaultDimensions];\n }\n // otherwise, merge the dimensions\n // we do this on the read path because default dimensions\n // may get updated asynchronously by environment detection\n return this.dimensions.map(custom => {\n return Object.assign(Object.assign({}, this.defaultDimensions), custom);\n });\n }\n putMetric(key, value, unit) {\n const currentMetric = this.metrics.get(key);\n if (currentMetric) {\n currentMetric.addValue(value);\n }\n else {\n this.metrics.set(key, new MetricValues_1.MetricValues(value, unit));\n }\n }\n /**\n * Creates an independently flushable context.\n */\n createCopyWithContext() {\n return new MetricsContext(this.namespace, Object.assign({}, this.properties), Object.assign([], this.dimensions), this.defaultDimensions, this.shouldUseDefaultDimensions, this.timestamp);\n }\n}\nexports.MetricsContext = MetricsContext;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Configuration_1 = require(\"../config/Configuration\");\nconst MetricsContext_1 = require(\"./MetricsContext\");\n/**\n * An async metrics logger.\n * Use this interface to publish logs to CloudWatch Logs\n * and extract metrics to CloudWatch Metrics asynchronously.\n */\nclass MetricsLogger {\n constructor(resolveEnvironment, context) {\n this.configureContextForEnvironment = (context, environment) => {\n const defaultDimensions = {\n // LogGroup name will entirely depend on the environment since there\n // are some cases where the LogGroup cannot be configured (e.g. Lambda)\n LogGroup: environment.getLogGroupName(),\n ServiceName: Configuration_1.default.serviceName || environment.getName(),\n ServiceType: Configuration_1.default.serviceType || environment.getType(),\n };\n context.setDefaultDimensions(defaultDimensions);\n environment.configureContext(context);\n };\n this.resolveEnvironment = resolveEnvironment;\n this.context = context || MetricsContext_1.MetricsContext.empty();\n }\n /**\n * Flushes the current context state to the configured sink.\n */\n flush() {\n return __awaiter(this, void 0, void 0, function* () {\n // resolve the environment and get the sink\n // MOST of the time this will run synchonrously\n // This only runs asynchronously if executing for the\n // first time in a non-lambda environment\n const environment = yield this.resolveEnvironment();\n this.configureContextForEnvironment(this.context, environment);\n const sink = environment.getSink();\n // accept and reset the context\n yield sink.accept(this.context);\n this.context = this.context.createCopyWithContext();\n });\n }\n /**\n * Set a property on the published metrics.\n * This is stored in the emitted log data and you are not\n * charged for this data by CloudWatch Metrics.\n * These values can be values that are useful for searching on,\n * but have too high cardinality to emit as dimensions to\n * CloudWatch Metrics.\n *\n * @param key Property name\n * @param value Property value\n */\n setProperty(key, value) {\n this.context.setProperty(key, value);\n return this;\n }\n /**\n * Adds a dimension.\n * This is generally a low cardinality key-value pair that is part of the metric identity.\n * CloudWatch treats each unique combination of dimensions as a separate metric, even if the metrics have the same metric name.\n *\n * @param dimension\n * @param value\n * @see [CloudWatch Dimensions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension)\n */\n putDimensions(dimensions) {\n this.context.putDimensions(dimensions);\n return this;\n }\n /**\n * Overwrite all dimensions on this MetricsLogger instance.\n *\n * @param dimensionSets\n * @see [CloudWatch Dimensions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension)\n */\n setDimensions(...dimensionSets) {\n this.context.setDimensions(dimensionSets);\n return this;\n }\n /**\n * Put a metric value.\n * This value will be emitted to CloudWatch Metrics asyncronously and does not contribute to your\n * account TPS limits. The value will also be available in your CloudWatch Logs\n * @param key\n * @param value\n * @param unit\n */\n putMetric(key, value, unit) {\n this.context.putMetric(key, value, unit);\n return this;\n }\n /**\n * Set the CloudWatch namespace that metrics should be published to.\n * @param value\n */\n setNamespace(value) {\n this.context.setNamespace(value);\n return this;\n }\n /**\n * Set the timestamp of metrics emitted in this context.\n *\n * If not set, the timestamp will default to new Date() at the point\n * the context is constructed.\n *\n * If set, timestamp will preserved across calls to flush().\n *\n * @param timestamp\n */\n setTimestamp(timestamp) {\n this.context.setTimestamp(timestamp);\n return this;\n }\n /**\n * Creates a new logger using the same contextual data as\n * the previous logger. This allows you to flush the instances\n * independently.\n */\n new() {\n return new MetricsLogger(this.resolveEnvironment, this.context.createCopyWithContext());\n }\n}\nexports.MetricsLogger = MetricsLogger;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Constants_1 = require(\"../Constants\");\n/**\n * Serializes the provided context to the CWL Structured\n * Logs format with Embedded Metric Filters.\n */\nclass LogSerializer {\n /**\n * Retrieve the current context as a JSON string\n */\n serialize(context) {\n const dimensionKeys = [];\n let dimensionProperties = {};\n context.getDimensions().forEach(d => {\n // we can only take the first 9 defined dimensions\n // the reason we do this in the serializer is because\n // it is possible that other sinks or formats can\n // support more dimensions\n // in the future it may make sense to introduce a higher-order\n // representation for sink-specific validations\n const keys = Object.keys(d).slice(0, Constants_1.Constants.MAX_DIMENSIONS);\n dimensionKeys.push(keys);\n dimensionProperties = Object.assign(Object.assign({}, dimensionProperties), d);\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const createBody = () => {\n return Object.assign(Object.assign(Object.assign({}, dimensionProperties), context.properties), { _aws: Object.assign(Object.assign({}, context.meta), { CloudWatchMetrics: [\n {\n Dimensions: dimensionKeys,\n Metrics: [],\n Namespace: context.namespace,\n },\n ] }) });\n };\n const eventBatches = [];\n let currentBody = createBody();\n const currentMetricsInBody = () => currentBody._aws.CloudWatchMetrics[0].Metrics.length;\n const shouldSerialize = () => currentMetricsInBody() === Constants_1.Constants.MAX_METRICS_PER_EVENT;\n // converts the body to JSON and pushes it into the batches\n const serializeCurrentBody = () => {\n eventBatches.push(JSON.stringify(currentBody));\n currentBody = createBody();\n };\n for (const [key, metric] of context.metrics) {\n // if there is only one metric value, unwrap it to make querying easier\n const metricValue = metric.values.length === 1 ? metric.values[0] : metric.values;\n currentBody[key] = metricValue;\n currentBody._aws.CloudWatchMetrics[0].Metrics.push({ Name: key, Unit: metric.unit });\n if (shouldSerialize()) {\n serializeCurrentBody();\n }\n }\n if (eventBatches.length === 0 || currentMetricsInBody() > 0) {\n serializeCurrentBody();\n }\n return eventBatches;\n }\n}\nexports.LogSerializer = LogSerializer;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst LogSerializer_1 = require(\"../serializers/LogSerializer\");\n/**\n * A sink that flushes log data to stdout.\n * This is the preferred sink for Lambda functions.\n */\nclass ConsoleSink {\n constructor(serializer) {\n this.name = 'ConsoleSink';\n this.serializer = serializer || new LogSerializer_1.LogSerializer();\n }\n accept(context) {\n // tslint:disable-next-line\n const events = this.serializer.serialize(context);\n events.forEach(event => console.log(event));\n return Promise.resolve();\n }\n}\nexports.ConsoleSink = ConsoleSink;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst net = require(\"net\");\nconst Logger_1 = require(\"../../utils/Logger\");\nclass TcpClient {\n constructor(endpoint) {\n this.endpoint = endpoint;\n this.socket = new net.Socket({ allowHalfOpen: true, writable: false })\n .setEncoding('utf8')\n .setKeepAlive(true)\n .setTimeout(5000) // idle timeout\n .on('timeout', () => this.disconnect('idle timeout'))\n .on('end', () => this.disconnect('end'))\n .on('data', data => Logger_1.LOG('TcpClient received data.', data));\n }\n warmup() {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n yield this.establishConnection();\n }\n catch (err) {\n Logger_1.LOG('Failed to connect', err);\n }\n });\n }\n sendMessage(message) {\n return __awaiter(this, void 0, void 0, function* () {\n // ensure the socket is open and writable\n yield this.waitForOpenConnection();\n yield new Promise((resolve, reject) => {\n const onSendError = (err) => {\n Logger_1.LOG('Failed to write', err);\n reject(err);\n };\n const wasFlushedToKernel = this.socket.write(message, (err) => {\n if (!err) {\n Logger_1.LOG('Write succeeded');\n resolve();\n }\n else {\n onSendError(err);\n }\n });\n if (!wasFlushedToKernel) {\n Logger_1.LOG('TcpClient data was not flushed to kernel buffer and was queued in memory.');\n }\n });\n });\n }\n disconnect(eventName) {\n Logger_1.LOG('TcpClient disconnected due to:', eventName);\n this.socket.removeAllListeners();\n this.socket.destroy();\n this.socket.unref();\n }\n waitForOpenConnection() {\n return __awaiter(this, void 0, void 0, function* () {\n if (!this.socket.writeable || this.socket.readyState !== 'open') {\n yield this.establishConnection();\n }\n });\n }\n establishConnection() {\n return __awaiter(this, void 0, void 0, function* () {\n yield new Promise((resolve, reject) => {\n const onError = (e) => {\n // socket is already open, no need to connect\n if (e.message.includes('EISCONN')) {\n resolve();\n return;\n }\n Logger_1.LOG('TCP Client received error', e);\n this.disconnect(e.message);\n reject(e);\n };\n const onConnect = () => {\n this.socket.removeListener('error', onError);\n Logger_1.LOG('TcpClient connected.', this.endpoint);\n resolve();\n };\n // TODO: convert this to a proper state machine\n switch (this.socket.readyState) {\n case 'open':\n resolve();\n break;\n case 'opening':\n // the socket is currently opening, we will resolve\n // or fail the current promise on the connect or\n // error events\n this.socket.once('connect', onConnect);\n this.socket.once('error', onError);\n break;\n default:\n Logger_1.LOG('opening connection with socket in state: ', this.socket.readyState);\n this.socket.connect(this.endpoint.port, this.endpoint.host, onConnect).once('error', onError);\n break;\n }\n });\n });\n }\n}\nexports.TcpClient = TcpClient;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst dgram = require(\"dgram\");\nconst Logger_1 = require(\"../../utils/Logger\");\nclass UdpClient {\n constructor(endpoint) {\n this.endpoint = endpoint;\n }\n // No warm up for UDP\n warmup() {\n return Promise.resolve();\n }\n sendMessage(message) {\n return __awaiter(this, void 0, void 0, function* () {\n const client = dgram.createSocket('udp4');\n client.send(message, this.endpoint.port, this.endpoint.host, (error) => {\n if (error) {\n Logger_1.LOG(error);\n }\n client.close();\n });\n return Promise.resolve();\n });\n }\n}\nexports.UdpClient = UdpClient;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst url = require(\"url\");\nconst Configuration_1 = require(\"../config/Configuration\");\nconst LogSerializer_1 = require(\"../serializers/LogSerializer\");\nconst Logger_1 = require(\"../utils/Logger\");\nconst TcpClient_1 = require(\"./connections/TcpClient\");\nconst UdpClient_1 = require(\"./connections/UdpClient\");\nconst TCP = 'tcp:';\nconst UDP = 'udp:';\nconst defaultTcpEndpoint = {\n host: '0.0.0.0',\n port: 25888,\n protocol: TCP,\n};\nconst parseEndpoint = (endpoint) => {\n try {\n if (!endpoint) {\n return defaultTcpEndpoint;\n }\n const parsedUrl = url.parse(endpoint);\n if (!parsedUrl.hostname || !parsedUrl.port || !parsedUrl.protocol) {\n Logger_1.LOG(`Failed to parse the provided agent endpoint. Falling back to the default TCP endpoint.`, parsedUrl);\n return defaultTcpEndpoint;\n }\n if (parsedUrl.protocol !== TCP && parsedUrl.protocol !== UDP) {\n Logger_1.LOG(`The provided agent endpoint protocol '${parsedUrl.protocol}' is not supported. Please use TCP or UDP. Falling back to the default TCP endpoint.`, parsedUrl);\n return defaultTcpEndpoint;\n }\n return {\n host: parsedUrl.hostname,\n port: Number(parsedUrl.port),\n protocol: parsedUrl.protocol,\n };\n }\n catch (e) {\n Logger_1.LOG('Failed to parse the provided agent endpoint', e);\n return defaultTcpEndpoint;\n }\n};\n/**\n * A sink that flushes to the CW Agent.\n * This sink instance should be re-used to avoid\n * leaking connections.\n */\nclass AgentSink {\n constructor(logGroupName, logStreamName, serializer) {\n this.name = 'AgentSink';\n this.logGroupName = logGroupName;\n this.logStreamName = logStreamName;\n this.serializer = serializer || new LogSerializer_1.LogSerializer();\n this.endpoint = parseEndpoint(Configuration_1.default.agentEndpoint);\n this.socketClient = this.getSocketClient(this.endpoint);\n Logger_1.LOG('Using socket client', this.socketClient.constructor.name);\n }\n accept(context) {\n return __awaiter(this, void 0, void 0, function* () {\n if (this.logGroupName) {\n context.meta.LogGroupName = this.logGroupName;\n }\n if (this.logStreamName) {\n context.meta.LogStreamName = this.logStreamName;\n }\n const events = this.serializer.serialize(context);\n Logger_1.LOG(`Sending {} events to socket.`, events.length);\n for (let index = 0; index < events.length; index++) {\n const event = events[index];\n const message = event + '\\n';\n const bytes = Buffer.from(message);\n yield this.socketClient.sendMessage(bytes);\n }\n });\n }\n getSocketClient(endpoint) {\n Logger_1.LOG('Getting socket client for connection.', endpoint);\n const client = endpoint.protocol === TCP ? new TcpClient_1.TcpClient(endpoint) : new UdpClient_1.UdpClient(endpoint);\n client.warmup();\n return client;\n }\n}\nexports.AgentSink = AgentSink;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Configuration_1 = require(\"../config/Configuration\");\nconst AgentSink_1 = require(\"../sinks/AgentSink\");\nconst Logger_1 = require(\"../utils/Logger\");\nclass DefaultEnvironment {\n probe() {\n return Promise.resolve(true);\n }\n getName() {\n if (!Configuration_1.default.serviceName) {\n Logger_1.LOG('Unknown ServiceName.');\n return 'Unknown';\n }\n return Configuration_1.default.serviceName;\n }\n getType() {\n if (!Configuration_1.default.serviceType) {\n Logger_1.LOG('Unknown ServiceType.');\n return 'Unknown';\n }\n return Configuration_1.default.serviceType;\n }\n getLogGroupName() {\n // if the caller explicitly overrides logGroupName to\n // be empty, we should honor that rather than providing\n // the default behavior.\n if (Configuration_1.default.logGroupName === '') {\n return '';\n }\n return Configuration_1.default.logGroupName ? Configuration_1.default.logGroupName : `${this.getName()}-metrics`;\n }\n configureContext() {\n // no-op\n }\n getSink() {\n if (!this.sink) {\n this.sink = new AgentSink_1.AgentSink(this.getLogGroupName(), Configuration_1.default.logStreamName);\n }\n return this.sink;\n }\n}\nexports.DefaultEnvironment = DefaultEnvironment;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst http = require(\"http\");\nconst SOCKET_TIMEOUT = 1000;\n/**\n * Fetch JSON data from an remote HTTP endpoint and de-serialize to the provided type.\n * There are no guarantees the response will conform to the contract defined by T.\n * It is up to the consumer to ensure the provided T captures all possible response types\n * from the provided endpoint.\n *\n * @param url - currently only supports HTTP\n */\nconst fetch = (url) => {\n return new Promise((resolve, reject) => {\n const request = http\n .get(url, { timeout: 2000 }, (response) => {\n if (!response.statusCode) {\n reject(`Received undefined response status code from '${url}'`);\n return;\n }\n if (response.statusCode < 200 || response.statusCode > 299) {\n reject(new Error('Failed to load page, status code: ' + response.statusCode));\n return;\n }\n // using similar approach to node-fetch\n // https://github.com/bitinn/node-fetch/blob/6a5d192034a0f438551dffb6d2d8df2c00921d16/src/body.js#L217\n const body = [];\n let bodyBytes = 0;\n response.on('data', (chunk) => {\n bodyBytes += chunk.length;\n body.push(chunk);\n });\n response.on('end', () => {\n let responseString;\n try {\n const buffer = Buffer.concat(body, bodyBytes);\n responseString = buffer.toString();\n const parsedJson = JSON.parse(responseString);\n resolve(parsedJson);\n }\n catch (e) {\n reject(`Failed to parse response from '${url}' as JSON. Received: ${responseString}`);\n }\n });\n })\n .on('error', (err) => {\n reject(err);\n });\n request.on('socket', socket => {\n socket.on('timeout', () => {\n request.abort();\n reject(`Socket timeout while connecting to '${url}'`);\n });\n socket.setTimeout(SOCKET_TIMEOUT);\n });\n });\n};\nexports.fetch = fetch;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Configuration_1 = require(\"../config/Configuration\");\nconst AgentSink_1 = require(\"../sinks/AgentSink\");\nconst Fetch_1 = require(\"../utils/Fetch\");\nconst Logger_1 = require(\"../utils/Logger\");\nconst os = require(\"os\");\nconst Constants_1 = require(\"../Constants\");\n// formats image names into something more readable for a metric name\n// e.g. <account-id>.dkr.ecr.<region>.amazonaws.com/<image-name>:latest -> <image-name>:latest\nconst formatImageName = (imageName) => {\n if (imageName) {\n const splitImageName = imageName.split('/');\n return splitImageName[splitImageName.length - 1];\n }\n return imageName;\n};\nclass ECSEnvironment {\n probe() {\n return __awaiter(this, void 0, void 0, function* () {\n if (!process.env.ECS_CONTAINER_METADATA_URI) {\n return Promise.resolve(false);\n }\n if (process.env.FLUENT_HOST && !Configuration_1.default.agentEndpoint) {\n this.fluentBitEndpoint = `tcp://${process.env.FLUENT_HOST}:${Constants_1.Constants.DEFAULT_AGENT_PORT}`;\n Configuration_1.default.agentEndpoint = this.fluentBitEndpoint;\n Logger_1.LOG(`Using FluentBit configuration. Endpoint: ${this.fluentBitEndpoint}`);\n }\n try {\n this.metadata = yield Fetch_1.fetch(process.env.ECS_CONTAINER_METADATA_URI);\n if (this.metadata) {\n this.metadata.FormattedImageName = formatImageName(this.metadata.Image);\n Logger_1.LOG(`Successfully collected ECS Container metadata.`);\n }\n }\n catch (e) {\n Logger_1.LOG('Failed to collect ECS Container Metadata.');\n Logger_1.LOG(e);\n }\n // return true regardless of whether or not metadata collection\n // succeeded. we know that this is supposed to be an ECS environment\n // just from the environment variable\n return true;\n });\n }\n getName() {\n var _a;\n if (Configuration_1.default.serviceName) {\n return Configuration_1.default.serviceName;\n }\n return ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.FormattedImageName) ? this.metadata.FormattedImageName : 'Unknown';\n }\n getType() {\n return 'AWS::ECS::Container';\n }\n getLogGroupName() {\n // FireLens / fluent-bit does not need the log group to be included\n // since configuration of the LogGroup is handled by the\n // fluent bit config file\n if (this.fluentBitEndpoint) {\n return '';\n }\n return Configuration_1.default.logGroupName || this.getName();\n }\n configureContext(context) {\n var _a, _b, _c, _d, _e;\n this.addProperty(context, 'containerId', os.hostname());\n this.addProperty(context, 'createdAt', (_a = this.metadata) === null || _a === void 0 ? void 0 : _a.CreatedAt);\n this.addProperty(context, 'startedAt', (_b = this.metadata) === null || _b === void 0 ? void 0 : _b.StartedAt);\n this.addProperty(context, 'image', (_c = this.metadata) === null || _c === void 0 ? void 0 : _c.Image);\n this.addProperty(context, 'cluster', (_d = this.metadata) === null || _d === void 0 ? void 0 : _d.Labels['com.amazonaws.ecs.cluster']);\n this.addProperty(context, 'taskArn', (_e = this.metadata) === null || _e === void 0 ? void 0 : _e.Labels['com.amazonaws.ecs.task-arn']);\n // we override the standard default dimensions here because in the\n // FireLens / fluent-bit case, we don't need the LogGroup\n if (this.fluentBitEndpoint) {\n context.setDefaultDimensions({\n ServiceName: Configuration_1.default.serviceName || this.getName(),\n ServiceType: Configuration_1.default.serviceType || this.getType(),\n });\n }\n }\n getSink() {\n if (!this.sink) {\n const logGroupName = this.fluentBitEndpoint ? '' : this.getLogGroupName();\n this.sink = new AgentSink_1.AgentSink(logGroupName);\n }\n return this.sink;\n }\n addProperty(context, key, value) {\n if (value) {\n context.setProperty(key, value);\n }\n }\n}\nexports.ECSEnvironment = ECSEnvironment;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Configuration_1 = require(\"../config/Configuration\");\nconst AgentSink_1 = require(\"../sinks/AgentSink\");\nconst Fetch_1 = require(\"../utils/Fetch\");\nconst Logger_1 = require(\"../utils/Logger\");\nconst endpoint = 'http://169.254.169.254/latest/dynamic/instance-identity/document';\nclass EC2Environment {\n probe() {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n this.metadata = yield Fetch_1.fetch(endpoint);\n if (this.metadata) {\n return true;\n }\n return false;\n }\n catch (e) {\n Logger_1.LOG(e);\n return false;\n }\n });\n }\n getName() {\n if (!Configuration_1.default.serviceName) {\n Logger_1.LOG('Unknown ServiceName.');\n return 'Unknown';\n }\n return Configuration_1.default.serviceName;\n }\n getType() {\n if (this.metadata) {\n return 'AWS::EC2::Instance';\n }\n // this will only happen if probe() is not called first\n return 'Unknown';\n }\n getLogGroupName() {\n return Configuration_1.default.logGroupName ? Configuration_1.default.logGroupName : `${this.getName()}-metrics`;\n }\n configureContext(context) {\n if (this.metadata) {\n context.setProperty('imageId', this.metadata.imageId);\n context.setProperty('instanceId', this.metadata.instanceId);\n context.setProperty('instanceType', this.metadata.instanceType);\n context.setProperty('privateIP', this.metadata.privateIp);\n context.setProperty('availabilityZone', this.metadata.availabilityZone);\n }\n }\n getSink() {\n if (!this.sink) {\n this.sink = new AgentSink_1.AgentSink(this.getLogGroupName(), Configuration_1.default.logStreamName);\n }\n return this.sink;\n }\n}\nexports.EC2Environment = EC2Environment;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst ConsoleSink_1 = require(\"../sinks/ConsoleSink\");\nclass LambdaEnvironment {\n probe() {\n return Promise.resolve(process.env.AWS_LAMBDA_FUNCTION_NAME ? true : false);\n }\n getName() {\n return process.env.AWS_LAMBDA_FUNCTION_NAME || 'Unknown';\n }\n getType() {\n return 'AWS::Lambda::Function';\n }\n getLogGroupName() {\n return this.getName();\n }\n configureContext(context) {\n this.addProperty(context, 'executionEnvironment', process.env.AWS_EXECUTION_ENV);\n this.addProperty(context, 'memorySize', process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE);\n this.addProperty(context, 'functionVersion', process.env.AWS_LAMBDA_FUNCTION_VERSION);\n this.addProperty(context, 'logStreamId', process.env.AWS_LAMBDA_LOG_STREAM_NAME);\n const trace = this.getSampledTrace();\n if (trace) {\n this.addProperty(context, 'traceId', trace);\n }\n }\n getSink() {\n if (!this.sink) {\n this.sink = new ConsoleSink_1.ConsoleSink();\n }\n return this.sink;\n }\n addProperty(context, key, value) {\n if (value) {\n context.setProperty(key, value);\n }\n }\n getSampledTrace() {\n // only collect traces which have been sampled\n if (process.env._X_AMZN_TRACE_ID && process.env._X_AMZN_TRACE_ID.includes('Sampled=1')) {\n return process.env._X_AMZN_TRACE_ID;\n }\n }\n}\nexports.LambdaEnvironment = LambdaEnvironment;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Configuration_1 = require(\"../config/Configuration\");\nconst Logger_1 = require(\"../utils/Logger\");\nconst ConsoleSink_1 = require(\"../sinks/ConsoleSink\");\nclass LocalEnvironment {\n probe() {\n // probe is not intended to be used in the LocalEnvironment\n // To use the local environment you should set the environment\n // override\n return Promise.resolve(false);\n }\n getName() {\n if (!Configuration_1.default.serviceName) {\n Logger_1.LOG('Unknown ServiceName.');\n return 'Unknown';\n }\n return Configuration_1.default.serviceName;\n }\n getType() {\n if (!Configuration_1.default.serviceType) {\n Logger_1.LOG('Unknown ServiceType.');\n return 'Unknown';\n }\n return Configuration_1.default.serviceType;\n }\n getLogGroupName() {\n return Configuration_1.default.logGroupName ? Configuration_1.default.logGroupName : `${this.getName()}-metrics`;\n }\n configureContext() {\n // no-op\n }\n getSink() {\n if (!this.sink) {\n this.sink = new ConsoleSink_1.ConsoleSink();\n }\n return this.sink;\n }\n}\nexports.LocalEnvironment = LocalEnvironment;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Logger_1 = require(\"../utils/Logger\");\nconst DefaultEnvironment_1 = require(\"./DefaultEnvironment\");\nconst ECSEnvironment_1 = require(\"./ECSEnvironment\");\nconst EC2Environment_1 = require(\"./EC2Environment\");\nconst LambdaEnvironment_1 = require(\"./LambdaEnvironment\");\nconst Configuration_1 = require(\"../config/Configuration\");\nconst Environments_1 = require(\"./Environments\");\nconst LocalEnvironment_1 = require(\"./LocalEnvironment\");\nconst lambdaEnvironment = new LambdaEnvironment_1.LambdaEnvironment();\nconst ecsEnvironment = new ECSEnvironment_1.ECSEnvironment();\nconst ec2Environment = new EC2Environment_1.EC2Environment();\nconst defaultEnvironment = new DefaultEnvironment_1.DefaultEnvironment();\n// ordering of this array matters\n// both Lambda and ECS can be determined from environment variables\n// making the entire detection process fast an cheap\n// EC2 can only be determined by making a remote HTTP request\nconst environments = [lambdaEnvironment, ecsEnvironment, ec2Environment];\nlet environment = undefined;\nconst getEnvironmentFromOverride = () => {\n // short-circuit environment detection and use override\n switch (Configuration_1.default.environmentOverride) {\n case Environments_1.default.Agent:\n return defaultEnvironment;\n case Environments_1.default.EC2:\n return ec2Environment;\n case Environments_1.default.Lambda:\n return lambdaEnvironment;\n case Environments_1.default.ECS:\n return ecsEnvironment;\n case Environments_1.default.Local:\n return new LocalEnvironment_1.LocalEnvironment();\n case Environments_1.default.Unknown:\n default:\n return undefined;\n }\n};\nconst discoverEnvironment = () => __awaiter(void 0, void 0, void 0, function* () {\n Logger_1.LOG(`Discovering environment`);\n for (const envUnderTest of environments) {\n Logger_1.LOG(`Testing: ${envUnderTest.constructor.name}`);\n try {\n if (yield envUnderTest.probe()) {\n return envUnderTest;\n }\n }\n catch (e) {\n Logger_1.LOG(`Failed probe: ${envUnderTest.constructor.name}`);\n }\n }\n return defaultEnvironment;\n});\nconst _resolveEnvironment = () => __awaiter(void 0, void 0, void 0, function* () {\n Logger_1.LOG('Resolving environment');\n if (environment) {\n return environment;\n }\n if (Configuration_1.default.environmentOverride) {\n Logger_1.LOG('Environment override supplied', Configuration_1.default.environmentOverride);\n // this will be falsy if an invalid configuration value is provided\n environment = getEnvironmentFromOverride();\n if (environment) {\n return environment;\n }\n else {\n Logger_1.LOG('Invalid environment provided. Falling back to auto-discovery.', Configuration_1.default.environmentOverride);\n }\n }\n environment = yield discoverEnvironment(); // eslint-disable-line require-atomic-updates\n return environment;\n});\n// pro-actively begin resolving the environment\n// this will allow us to kick off any async tasks\n// at module load time to reduce any blocking that\n// may occur on the initial flush()\nconst environmentPromise = _resolveEnvironment();\nconst resolveEnvironment = () => __awaiter(void 0, void 0, void 0, function* () {\n return environmentPromise;\n});\nexports.resolveEnvironment = resolveEnvironment;\n// this method is used for testing to bypass the cached environmentPromise result\nconst cleanResolveEnvironment = () => __awaiter(void 0, void 0, void 0, function* () {\n yield environmentPromise;\n environment = undefined;\n return yield _resolveEnvironment();\n});\nexports.cleanResolveEnvironment = cleanResolveEnvironment;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst __1 = require(\"..\");\nconst EnvironmentDetector_1 = require(\"../environment/EnvironmentDetector\");\nconst MetricsContext_1 = require(\"./MetricsContext\");\nconst createMetricsLogger = () => {\n const context = MetricsContext_1.MetricsContext.empty();\n const logger = new __1.MetricsLogger(EnvironmentDetector_1.resolveEnvironment, context);\n return logger;\n};\nexports.createMetricsLogger = createMetricsLogger;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Logger_1 = require(\"../utils/Logger\");\nconst MetricsLoggerFactory_1 = require(\"./MetricsLoggerFactory\");\n/**\n * An asynchronous wrapper that provides a metrics instance.\n */\nconst metricScope = (handler) => {\n const wrappedHandler = (...args) => __awaiter(void 0, void 0, void 0, function* () {\n const metrics = MetricsLoggerFactory_1.createMetricsLogger();\n try {\n return yield handler(metrics)(...args);\n }\n finally {\n try {\n yield metrics.flush();\n }\n catch (e) {\n Logger_1.LOG('Failed to flush metrics', e);\n }\n }\n });\n return wrappedHandler;\n};\nexports.metricScope = metricScope;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Unit;\n(function (Unit) {\n Unit[\"Seconds\"] = \"Seconds\";\n Unit[\"Microseconds\"] = \"Microseconds\";\n Unit[\"Milliseconds\"] = \"Milliseconds\";\n Unit[\"Bytes\"] = \"Bytes\";\n Unit[\"Kilobytes\"] = \"Kilobytes\";\n Unit[\"Megabytes\"] = \"Megabytes\";\n Unit[\"Gigabytes\"] = \"Gigabytes\";\n Unit[\"Terabytes\"] = \"Terabytes\";\n Unit[\"Bits\"] = \"Bits\";\n Unit[\"Kilobits\"] = \"Kilobits\";\n Unit[\"Megabits\"] = \"Megabits\";\n Unit[\"Gigabits\"] = \"Gigabits\";\n Unit[\"Terabits\"] = \"Terabits\";\n Unit[\"Percent\"] = \"Percent\";\n Unit[\"Count\"] = \"Count\";\n Unit[\"BytesPerSecond\"] = \"Bytes/Second\";\n Unit[\"KilobytesPerSecond\"] = \"Kilobytes/Second\";\n Unit[\"MegabytesPerSecond\"] = \"Megabytes/Second\";\n Unit[\"GigabytesPerSecond\"] = \"Gigabytes/Second\";\n Unit[\"TerabytesPerSecond\"] = \"Terabytes/Second\";\n Unit[\"BitsPerSecond\"] = \"Bits/Second\";\n Unit[\"KilobitsPerSecond\"] = \"Kilobits/Second\";\n Unit[\"MegabitsPerSecond\"] = \"Megabits/Second\";\n Unit[\"GigabitsPerSecond\"] = \"Gigabits/Second\";\n Unit[\"TerabitsPerSecond\"] = \"Terabits/Second\";\n Unit[\"CountPerSecond\"] = \"Count/Second\";\n Unit[\"None\"] = \"None\";\n})(Unit = exports.Unit || (exports.Unit = {}));\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar MetricsLogger_1 = require(\"./logger/MetricsLogger\");\nexports.MetricsLogger = MetricsLogger_1.MetricsLogger;\nvar ConsoleSink_1 = require(\"./sinks/ConsoleSink\");\nexports.LocalSink = ConsoleSink_1.ConsoleSink;\nvar AgentSink_1 = require(\"./sinks/AgentSink\");\nexports.AgentSink = AgentSink_1.AgentSink;\nvar MetricScope_1 = require(\"./logger/MetricScope\");\nexports.metricScope = MetricScope_1.metricScope;\nvar MetricsLoggerFactory_1 = require(\"./logger/MetricsLoggerFactory\");\nexports.createMetricsLogger = MetricsLoggerFactory_1.createMetricsLogger;\nvar Unit_1 = require(\"./logger/Unit\");\nexports.Unit = Unit_1.Unit;\nconst Configuration_1 = require(\"./config/Configuration\");\nexports.Configuration = Configuration_1.default;\n", "\"use strict\";\n/// <reference lib=\"es2018\"/>\n/// <reference lib=\"dom\"/>\n/// <reference types=\"node\"/>\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst typedArrayTypeNames = [\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array',\n 'BigInt64Array',\n 'BigUint64Array'\n];\nfunction isTypedArrayName(name) {\n return typedArrayTypeNames.includes(name);\n}\nconst objectTypeNames = [\n 'Function',\n 'Generator',\n 'AsyncGenerator',\n 'GeneratorFunction',\n 'AsyncGeneratorFunction',\n 'AsyncFunction',\n 'Observable',\n 'Array',\n 'Buffer',\n 'Object',\n 'RegExp',\n 'Date',\n 'Error',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'ArrayBuffer',\n 'SharedArrayBuffer',\n 'DataView',\n 'Promise',\n 'URL',\n 'FormData',\n 'URLSearchParams',\n 'HTMLElement',\n ...typedArrayTypeNames\n];\nfunction isObjectTypeName(name) {\n return objectTypeNames.includes(name);\n}\nconst primitiveTypeNames = [\n 'null',\n 'undefined',\n 'string',\n 'number',\n 'bigint',\n 'boolean',\n 'symbol'\n];\nfunction isPrimitiveTypeName(name) {\n return primitiveTypeNames.includes(name);\n}\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction isOfType(type) {\n return (value) => typeof value === type;\n}\nconst { toString } = Object.prototype;\nconst getObjectType = (value) => {\n const objectTypeName = toString.call(value).slice(8, -1);\n if (/HTML\\w+Element/.test(objectTypeName) && is.domElement(value)) {\n return 'HTMLElement';\n }\n if (isObjectTypeName(objectTypeName)) {\n return objectTypeName;\n }\n return undefined;\n};\nconst isObjectOfType = (type) => (value) => getObjectType(value) === type;\nfunction is(value) {\n if (value === null) {\n return 'null';\n }\n switch (typeof value) {\n case 'undefined':\n return 'undefined';\n case 'string':\n return 'string';\n case 'number':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'function':\n return 'Function';\n case 'bigint':\n return 'bigint';\n case 'symbol':\n return 'symbol';\n default:\n }\n if (is.observable(value)) {\n return 'Observable';\n }\n if (is.array(value)) {\n return 'Array';\n }\n if (is.buffer(value)) {\n return 'Buffer';\n }\n const tagType = getObjectType(value);\n if (tagType) {\n return tagType;\n }\n if (value instanceof String || value instanceof Boolean || value instanceof Number) {\n throw new TypeError('Please don\\'t use object wrappers for primitive types');\n }\n return 'Object';\n}\nis.undefined = isOfType('undefined');\nis.string = isOfType('string');\nconst isNumberType = isOfType('number');\nis.number = (value) => isNumberType(value) && !is.nan(value);\nis.bigint = isOfType('bigint');\n// eslint-disable-next-line @typescript-eslint/ban-types\nis.function_ = isOfType('function');\nis.null_ = (value) => value === null;\nis.class_ = (value) => is.function_(value) && value.toString().startsWith('class ');\nis.boolean = (value) => value === true || value === false;\nis.symbol = isOfType('symbol');\nis.numericString = (value) => is.string(value) && !is.emptyStringOrWhitespace(value) && !Number.isNaN(Number(value));\nis.array = (value, assertion) => {\n if (!Array.isArray(value)) {\n return false;\n }\n if (!is.function_(assertion)) {\n return true;\n }\n return value.every(assertion);\n};\nis.buffer = (value) => { var _a, _b, _c, _d; return (_d = (_c = (_b = (_a = value) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.isBuffer) === null || _c === void 0 ? void 0 : _c.call(_b, value)) !== null && _d !== void 0 ? _d : false; };\nis.nullOrUndefined = (value) => is.null_(value) || is.undefined(value);\nis.object = (value) => !is.null_(value) && (typeof value === 'object' || is.function_(value));\nis.iterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.iterator]); };\nis.asyncIterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.asyncIterator]); };\nis.generator = (value) => is.iterable(value) && is.function_(value.next) && is.function_(value.throw);\nis.asyncGenerator = (value) => is.asyncIterable(value) && is.function_(value.next) && is.function_(value.throw);\nis.nativePromise = (value) => isObjectOfType('Promise')(value);\nconst hasPromiseAPI = (value) => {\n var _a, _b;\n return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a.then) &&\n is.function_((_b = value) === null || _b === void 0 ? void 0 : _b.catch);\n};\nis.promise = (value) => is.nativePromise(value) || hasPromiseAPI(value);\nis.generatorFunction = isObjectOfType('GeneratorFunction');\nis.asyncGeneratorFunction = (value) => getObjectType(value) === 'AsyncGeneratorFunction';\nis.asyncFunction = (value) => getObjectType(value) === 'AsyncFunction';\n// eslint-disable-next-line no-prototype-builtins, @typescript-eslint/ban-types\nis.boundFunction = (value) => is.function_(value) && !value.hasOwnProperty('prototype');\nis.regExp = isObjectOfType('RegExp');\nis.date = isObjectOfType('Date');\nis.error = isObjectOfType('Error');\nis.map = (value) => isObjectOfType('Map')(value);\nis.set = (value) => isObjectOfType('Set')(value);\nis.weakMap = (value) => isObjectOfType('WeakMap')(value);\nis.weakSet = (value) => isObjectOfType('WeakSet')(value);\nis.int8Array = isObjectOfType('Int8Array');\nis.uint8Array = isObjectOfType('Uint8Array');\nis.uint8ClampedArray = isObjectOfType('Uint8ClampedArray');\nis.int16Array = isObjectOfType('Int16Array');\nis.uint16Array = isObjectOfType('Uint16Array');\nis.int32Array = isObjectOfType('Int32Array');\nis.uint32Array = isObjectOfType('Uint32Array');\nis.float32Array = isObjectOfType('Float32Array');\nis.float64Array = isObjectOfType('Float64Array');\nis.bigInt64Array = isObjectOfType('BigInt64Array');\nis.bigUint64Array = isObjectOfType('BigUint64Array');\nis.arrayBuffer = isObjectOfType('ArrayBuffer');\nis.sharedArrayBuffer = isObjectOfType('SharedArrayBuffer');\nis.dataView = isObjectOfType('DataView');\nis.directInstanceOf = (instance, class_) => Object.getPrototypeOf(instance) === class_.prototype;\nis.urlInstance = (value) => isObjectOfType('URL')(value);\nis.urlString = (value) => {\n if (!is.string(value)) {\n return false;\n }\n try {\n new URL(value); // eslint-disable-line no-new\n return true;\n }\n catch (_a) {\n return false;\n }\n};\n// TODO: Use the `not` operator with a type guard here when it's available.\n// Example: `is.truthy = (value: unknown): value is (not false | not 0 | not '' | not undefined | not null) => Boolean(value);`\nis.truthy = (value) => Boolean(value);\n// Example: `is.falsy = (value: unknown): value is (not true | 0 | '' | undefined | null) => Boolean(value);`\nis.falsy = (value) => !value;\nis.nan = (value) => Number.isNaN(value);\nis.primitive = (value) => is.null_(value) || isPrimitiveTypeName(typeof value);\nis.integer = (value) => Number.isInteger(value);\nis.safeInteger = (value) => Number.isSafeInteger(value);\nis.plainObject = (value) => {\n // From: https://github.com/sindresorhus/is-plain-obj/blob/main/index.js\n if (toString.call(value) !== '[object Object]') {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === null || prototype === Object.getPrototypeOf({});\n};\nis.typedArray = (value) => isTypedArrayName(getObjectType(value));\nconst isValidLength = (value) => is.safeInteger(value) && value >= 0;\nis.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length);\nis.inRange = (value, range) => {\n if (is.number(range)) {\n return value >= Math.min(0, range) && value <= Math.max(range, 0);\n }\n if (is.array(range) && range.length === 2) {\n return value >= Math.min(...range) && value <= Math.max(...range);\n }\n throw new TypeError(`Invalid range: ${JSON.stringify(range)}`);\n};\nconst NODE_TYPE_ELEMENT = 1;\nconst DOM_PROPERTIES_TO_CHECK = [\n 'innerHTML',\n 'ownerDocument',\n 'style',\n 'attributes',\n 'nodeValue'\n];\nis.domElement = (value) => {\n return is.object(value) &&\n value.nodeType === NODE_TYPE_ELEMENT &&\n is.string(value.nodeName) &&\n !is.plainObject(value) &&\n DOM_PROPERTIES_TO_CHECK.every(property => property in value);\n};\nis.observable = (value) => {\n var _a, _b, _c, _d;\n if (!value) {\n return false;\n }\n // eslint-disable-next-line no-use-extend-native/no-use-extend-native\n if (value === ((_b = (_a = value)[Symbol.observable]) === null || _b === void 0 ? void 0 : _b.call(_a))) {\n return true;\n }\n if (value === ((_d = (_c = value)['@@observable']) === null || _d === void 0 ? void 0 : _d.call(_c))) {\n return true;\n }\n return false;\n};\nis.nodeStream = (value) => is.object(value) && is.function_(value.pipe) && !is.observable(value);\nis.infinite = (value) => value === Infinity || value === -Infinity;\nconst isAbsoluteMod2 = (remainder) => (value) => is.integer(value) && Math.abs(value % 2) === remainder;\nis.evenInteger = isAbsoluteMod2(0);\nis.oddInteger = isAbsoluteMod2(1);\nis.emptyArray = (value) => is.array(value) && value.length === 0;\nis.nonEmptyArray = (value) => is.array(value) && value.length > 0;\nis.emptyString = (value) => is.string(value) && value.length === 0;\n// TODO: Use `not ''` when the `not` operator is available.\nis.nonEmptyString = (value) => is.string(value) && value.length > 0;\nconst isWhiteSpaceString = (value) => is.string(value) && !/\\S/.test(value);\nis.emptyStringOrWhitespace = (value) => is.emptyString(value) || isWhiteSpaceString(value);\nis.emptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length === 0;\n// TODO: Use `not` operator here to remove `Map` and `Set` from type guard:\n// - https://github.com/Microsoft/TypeScript/pull/29317\nis.nonEmptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length > 0;\nis.emptySet = (value) => is.set(value) && value.size === 0;\nis.nonEmptySet = (value) => is.set(value) && value.size > 0;\nis.emptyMap = (value) => is.map(value) && value.size === 0;\nis.nonEmptyMap = (value) => is.map(value) && value.size > 0;\n// `PropertyKey` is any value that can be used as an object key (string, number, or symbol)\nis.propertyKey = (value) => is.any([is.string, is.number, is.symbol], value);\nis.formData = (value) => isObjectOfType('FormData')(value);\nis.urlSearchParams = (value) => isObjectOfType('URLSearchParams')(value);\nconst predicateOnArray = (method, predicate, values) => {\n if (!is.function_(predicate)) {\n throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`);\n }\n if (values.length === 0) {\n throw new TypeError('Invalid number of values');\n }\n return method.call(values, predicate);\n};\nis.any = (predicate, ...values) => {\n const predicates = is.array(predicate) ? predicate : [predicate];\n return predicates.some(singlePredicate => predicateOnArray(Array.prototype.some, singlePredicate, values));\n};\nis.all = (predicate, ...values) => predicateOnArray(Array.prototype.every, predicate, values);\nconst assertType = (condition, description, value, options = {}) => {\n if (!condition) {\n const { multipleValues } = options;\n const valuesMessage = multipleValues ?\n `received values of types ${[\n ...new Set(value.map(singleValue => `\\`${is(singleValue)}\\``))\n ].join(', ')}` :\n `received value of type \\`${is(value)}\\``;\n throw new TypeError(`Expected value which is \\`${description}\\`, ${valuesMessage}.`);\n }\n};\nexports.assert = {\n // Unknowns.\n undefined: (value) => assertType(is.undefined(value), 'undefined', value),\n string: (value) => assertType(is.string(value), 'string', value),\n number: (value) => assertType(is.number(value), 'number', value),\n bigint: (value) => assertType(is.bigint(value), 'bigint', value),\n // eslint-disable-next-line @typescript-eslint/ban-types\n function_: (value) => assertType(is.function_(value), 'Function', value),\n null_: (value) => assertType(is.null_(value), 'null', value),\n class_: (value) => assertType(is.class_(value), \"Class\" /* class_ */, value),\n boolean: (value) => assertType(is.boolean(value), 'boolean', value),\n symbol: (value) => assertType(is.symbol(value), 'symbol', value),\n numericString: (value) => assertType(is.numericString(value), \"string with a number\" /* numericString */, value),\n array: (value, assertion) => {\n const assert = assertType;\n assert(is.array(value), 'Array', value);\n if (assertion) {\n value.forEach(assertion);\n }\n },\n buffer: (value) => assertType(is.buffer(value), 'Buffer', value),\n nullOrUndefined: (value) => assertType(is.nullOrUndefined(value), \"null or undefined\" /* nullOrUndefined */, value),\n object: (value) => assertType(is.object(value), 'Object', value),\n iterable: (value) => assertType(is.iterable(value), \"Iterable\" /* iterable */, value),\n asyncIterable: (value) => assertType(is.asyncIterable(value), \"AsyncIterable\" /* asyncIterable */, value),\n generator: (value) => assertType(is.generator(value), 'Generator', value),\n asyncGenerator: (value) => assertType(is.asyncGenerator(value), 'AsyncGenerator', value),\n nativePromise: (value) => assertType(is.nativePromise(value), \"native Promise\" /* nativePromise */, value),\n promise: (value) => assertType(is.promise(value), 'Promise', value),\n generatorFunction: (value) => assertType(is.generatorFunction(value), 'GeneratorFunction', value),\n asyncGeneratorFunction: (value) => assertType(is.asyncGeneratorFunction(value), 'AsyncGeneratorFunction', value),\n // eslint-disable-next-line @typescript-eslint/ban-types\n asyncFunction: (value) => assertType(is.asyncFunction(value), 'AsyncFunction', value),\n // eslint-disable-next-line @typescript-eslint/ban-types\n boundFunction: (value) => assertType(is.boundFunction(value), 'Function', value),\n regExp: (value) => assertType(is.regExp(value), 'RegExp', value),\n date: (value) => assertType(is.date(value), 'Date', value),\n error: (value) => assertType(is.error(value), 'Error', value),\n map: (value) => assertType(is.map(value), 'Map', value),\n set: (value) => assertType(is.set(value), 'Set', value),\n weakMap: (value) => assertType(is.weakMap(value), 'WeakMap', value),\n weakSet: (value) => assertType(is.weakSet(value), 'WeakSet', value),\n int8Array: (value) => assertType(is.int8Array(value), 'Int8Array', value),\n uint8Array: (value) => assertType(is.uint8Array(value), 'Uint8Array', value),\n uint8ClampedArray: (value) => assertType(is.uint8ClampedArray(value), 'Uint8ClampedArray', value),\n int16Array: (value) => assertType(is.int16Array(value), 'Int16Array', value),\n uint16Array: (value) => assertType(is.uint16Array(value), 'Uint16Array', value),\n int32Array: (value) => assertType(is.int32Array(value), 'Int32Array', value),\n uint32Array: (value) => assertType(is.uint32Array(value), 'Uint32Array', value),\n float32Array: (value) => assertType(is.float32Array(value), 'Float32Array', value),\n float64Array: (value) => assertType(is.float64Array(value), 'Float64Array', value),\n bigInt64Array: (value) => assertType(is.bigInt64Array(value), 'BigInt64Array', value),\n bigUint64Array: (value) => assertType(is.bigUint64Array(value), 'BigUint64Array', value),\n arrayBuffer: (value) => assertType(is.arrayBuffer(value), 'ArrayBuffer', value),\n sharedArrayBuffer: (value) => assertType(is.sharedArrayBuffer(value), 'SharedArrayBuffer', value),\n dataView: (value) => assertType(is.dataView(value), 'DataView', value),\n urlInstance: (value) => assertType(is.urlInstance(value), 'URL', value),\n urlString: (value) => assertType(is.urlString(value), \"string with a URL\" /* urlString */, value),\n truthy: (value) => assertType(is.truthy(value), \"truthy\" /* truthy */, value),\n falsy: (value) => assertType(is.falsy(value), \"falsy\" /* falsy */, value),\n nan: (value) => assertType(is.nan(value), \"NaN\" /* nan */, value),\n primitive: (value) => assertType(is.primitive(value), \"primitive\" /* primitive */, value),\n integer: (value) => assertType(is.integer(value), \"integer\" /* integer */, value),\n safeInteger: (value) => assertType(is.safeInteger(value), \"integer\" /* safeInteger */, value),\n plainObject: (value) => assertType(is.plainObject(value), \"plain object\" /* plainObject */, value),\n typedArray: (value) => assertType(is.typedArray(value), \"TypedArray\" /* typedArray */, value),\n arrayLike: (value) => assertType(is.arrayLike(value), \"array-like\" /* arrayLike */, value),\n domElement: (value) => assertType(is.domElement(value), \"HTMLElement\" /* domElement */, value),\n observable: (value) => assertType(is.observable(value), 'Observable', value),\n nodeStream: (value) => assertType(is.nodeStream(value), \"Node.js Stream\" /* nodeStream */, value),\n infinite: (value) => assertType(is.infinite(value), \"infinite number\" /* infinite */, value),\n emptyArray: (value) => assertType(is.emptyArray(value), \"empty array\" /* emptyArray */, value),\n nonEmptyArray: (value) => assertType(is.nonEmptyArray(value), \"non-empty array\" /* nonEmptyArray */, value),\n emptyString: (value) => assertType(is.emptyString(value), \"empty string\" /* emptyString */, value),\n nonEmptyString: (value) => assertType(is.nonEmptyString(value), \"non-empty string\" /* nonEmptyString */, value),\n emptyStringOrWhitespace: (value) => assertType(is.emptyStringOrWhitespace(value), \"empty string or whitespace\" /* emptyStringOrWhitespace */, value),\n emptyObject: (value) => assertType(is.emptyObject(value), \"empty object\" /* emptyObject */, value),\n nonEmptyObject: (value) => assertType(is.nonEmptyObject(value), \"non-empty object\" /* nonEmptyObject */, value),\n emptySet: (value) => assertType(is.emptySet(value), \"empty set\" /* emptySet */, value),\n nonEmptySet: (value) => assertType(is.nonEmptySet(value), \"non-empty set\" /* nonEmptySet */, value),\n emptyMap: (value) => assertType(is.emptyMap(value), \"empty map\" /* emptyMap */, value),\n nonEmptyMap: (value) => assertType(is.nonEmptyMap(value), \"non-empty map\" /* nonEmptyMap */, value),\n propertyKey: (value) => assertType(is.propertyKey(value), 'PropertyKey', value),\n formData: (value) => assertType(is.formData(value), 'FormData', value),\n urlSearchParams: (value) => assertType(is.urlSearchParams(value), 'URLSearchParams', value),\n // Numbers.\n evenInteger: (value) => assertType(is.evenInteger(value), \"even integer\" /* evenInteger */, value),\n oddInteger: (value) => assertType(is.oddInteger(value), \"odd integer\" /* oddInteger */, value),\n // Two arguments.\n directInstanceOf: (instance, class_) => assertType(is.directInstanceOf(instance, class_), \"T\" /* directInstanceOf */, instance),\n inRange: (value, range) => assertType(is.inRange(value, range), \"in range\" /* inRange */, value),\n // Variadic functions.\n any: (predicate, ...values) => {\n return assertType(is.any(predicate, ...values), \"predicate returns truthy for any value\" /* any */, values, { multipleValues: true });\n },\n all: (predicate, ...values) => assertType(is.all(predicate, ...values), \"predicate returns truthy for all values\" /* all */, values, { multipleValues: true })\n};\n// Some few keywords are reserved, but we'll populate them for Node.js users\n// See https://github.com/Microsoft/TypeScript/issues/2536\nObject.defineProperties(is, {\n class: {\n value: is.class_\n },\n function: {\n value: is.function_\n },\n null: {\n value: is.null_\n }\n});\nObject.defineProperties(exports.assert, {\n class: {\n value: exports.assert.class_\n },\n function: {\n value: exports.assert.function_\n },\n null: {\n value: exports.assert.null_\n }\n});\nexports.default = is;\n// For CommonJS default export support\nmodule.exports = is;\nmodule.exports.default = is;\nmodule.exports.assert = exports.assert;\n", "'use strict';\n\nclass CancelError extends Error {\n\tconstructor(reason) {\n\t\tsuper(reason || 'Promise was canceled');\n\t\tthis.name = 'CancelError';\n\t}\n\n\tget isCanceled() {\n\t\treturn true;\n\t}\n}\n\nclass PCancelable {\n\tstatic fn(userFn) {\n\t\treturn (...arguments_) => {\n\t\t\treturn new PCancelable((resolve, reject, onCancel) => {\n\t\t\t\targuments_.push(onCancel);\n\t\t\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\t\t\tuserFn(...arguments_).then(resolve, reject);\n\t\t\t});\n\t\t};\n\t}\n\n\tconstructor(executor) {\n\t\tthis._cancelHandlers = [];\n\t\tthis._isPending = true;\n\t\tthis._isCanceled = false;\n\t\tthis._rejectOnCancel = true;\n\n\t\tthis._promise = new Promise((resolve, reject) => {\n\t\t\tthis._reject = reject;\n\n\t\t\tconst onResolve = value => {\n\t\t\t\tif (!this._isCanceled || !onCancel.shouldReject) {\n\t\t\t\t\tthis._isPending = false;\n\t\t\t\t\tresolve(value);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst onReject = error => {\n\t\t\t\tthis._isPending = false;\n\t\t\t\treject(error);\n\t\t\t};\n\n\t\t\tconst onCancel = handler => {\n\t\t\t\tif (!this._isPending) {\n\t\t\t\t\tthrow new Error('The `onCancel` handler was attached after the promise settled.');\n\t\t\t\t}\n\n\t\t\t\tthis._cancelHandlers.push(handler);\n\t\t\t};\n\n\t\t\tObject.defineProperties(onCancel, {\n\t\t\t\tshouldReject: {\n\t\t\t\t\tget: () => this._rejectOnCancel,\n\t\t\t\t\tset: boolean => {\n\t\t\t\t\t\tthis._rejectOnCancel = boolean;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn executor(onResolve, onReject, onCancel);\n\t\t});\n\t}\n\n\tthen(onFulfilled, onRejected) {\n\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\treturn this._promise.then(onFulfilled, onRejected);\n\t}\n\n\tcatch(onRejected) {\n\t\treturn this._promise.catch(onRejected);\n\t}\n\n\tfinally(onFinally) {\n\t\treturn this._promise.finally(onFinally);\n\t}\n\n\tcancel(reason) {\n\t\tif (!this._isPending || this._isCanceled) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._isCanceled = true;\n\n\t\tif (this._cancelHandlers.length > 0) {\n\t\t\ttry {\n\t\t\t\tfor (const handler of this._cancelHandlers) {\n\t\t\t\t\thandler();\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthis._reject(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (this._rejectOnCancel) {\n\t\t\tthis._reject(new CancelError(reason));\n\t\t}\n\t}\n\n\tget isCanceled() {\n\t\treturn this._isCanceled;\n\t}\n}\n\nObject.setPrototypeOf(PCancelable.prototype, Promise.prototype);\n\nmodule.exports = PCancelable;\nmodule.exports.CancelError = CancelError;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction isTLSSocket(socket) {\n return socket.encrypted;\n}\nconst deferToConnect = (socket, fn) => {\n let listeners;\n if (typeof fn === 'function') {\n const connect = fn;\n listeners = { connect };\n }\n else {\n listeners = fn;\n }\n const hasConnectListener = typeof listeners.connect === 'function';\n const hasSecureConnectListener = typeof listeners.secureConnect === 'function';\n const hasCloseListener = typeof listeners.close === 'function';\n const onConnect = () => {\n if (hasConnectListener) {\n listeners.connect();\n }\n if (isTLSSocket(socket) && hasSecureConnectListener) {\n if (socket.authorized) {\n listeners.secureConnect();\n }\n else if (!socket.authorizationError) {\n socket.once('secureConnect', listeners.secureConnect);\n }\n }\n if (hasCloseListener) {\n socket.once('close', listeners.close);\n }\n };\n if (socket.writable && !socket.connecting) {\n onConnect();\n }\n else if (socket.connecting) {\n socket.once('connect', onConnect);\n }\n else if (socket.destroyed && hasCloseListener) {\n listeners.close(socket._hadError);\n }\n};\nexports.default = deferToConnect;\n// For CommonJS default export support\nmodule.exports = deferToConnect;\nmodule.exports.default = deferToConnect;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst defer_to_connect_1 = require(\"defer-to-connect\");\nconst util_1 = require(\"util\");\nconst nodejsMajorVersion = Number(process.versions.node.split('.')[0]);\nconst timer = (request) => {\n if (request.timings) {\n return request.timings;\n }\n const timings = {\n start: Date.now(),\n socket: undefined,\n lookup: undefined,\n connect: undefined,\n secureConnect: undefined,\n upload: undefined,\n response: undefined,\n end: undefined,\n error: undefined,\n abort: undefined,\n phases: {\n wait: undefined,\n dns: undefined,\n tcp: undefined,\n tls: undefined,\n request: undefined,\n firstByte: undefined,\n download: undefined,\n total: undefined\n }\n };\n request.timings = timings;\n const handleError = (origin) => {\n const emit = origin.emit.bind(origin);\n origin.emit = (event, ...args) => {\n // Catches the `error` event\n if (event === 'error') {\n timings.error = Date.now();\n timings.phases.total = timings.error - timings.start;\n origin.emit = emit;\n }\n // Saves the original behavior\n return emit(event, ...args);\n };\n };\n handleError(request);\n const onAbort = () => {\n timings.abort = Date.now();\n // Let the `end` response event be responsible for setting the total phase,\n // unless the Node.js major version is >= 13.\n if (!timings.response || nodejsMajorVersion >= 13) {\n timings.phases.total = Date.now() - timings.start;\n }\n };\n request.prependOnceListener('abort', onAbort);\n const onSocket = (socket) => {\n timings.socket = Date.now();\n timings.phases.wait = timings.socket - timings.start;\n if (util_1.types.isProxy(socket)) {\n return;\n }\n const lookupListener = () => {\n timings.lookup = Date.now();\n timings.phases.dns = timings.lookup - timings.socket;\n };\n socket.prependOnceListener('lookup', lookupListener);\n defer_to_connect_1.default(socket, {\n connect: () => {\n timings.connect = Date.now();\n if (timings.lookup === undefined) {\n socket.removeListener('lookup', lookupListener);\n timings.lookup = timings.connect;\n timings.phases.dns = timings.lookup - timings.socket;\n }\n timings.phases.tcp = timings.connect - timings.lookup;\n // This callback is called before flushing any data,\n // so we don't need to set `timings.phases.request` here.\n },\n secureConnect: () => {\n timings.secureConnect = Date.now();\n timings.phases.tls = timings.secureConnect - timings.connect;\n }\n });\n };\n if (request.socket) {\n onSocket(request.socket);\n }\n else {\n request.prependOnceListener('socket', onSocket);\n }\n const onUpload = () => {\n var _a;\n timings.upload = Date.now();\n timings.phases.request = timings.upload - ((_a = timings.secureConnect) !== null && _a !== void 0 ? _a : timings.connect);\n };\n const writableFinished = () => {\n if (typeof request.writableFinished === 'boolean') {\n return request.writableFinished;\n }\n // Node.js doesn't have `request.writableFinished` property\n return request.finished && request.outputSize === 0 && (!request.socket || request.socket.writableLength === 0);\n };\n if (writableFinished()) {\n onUpload();\n }\n else {\n request.prependOnceListener('finish', onUpload);\n }\n request.prependOnceListener('response', (response) => {\n timings.response = Date.now();\n timings.phases.firstByte = timings.response - timings.upload;\n response.timings = timings;\n handleError(response);\n response.prependOnceListener('end', () => {\n timings.end = Date.now();\n timings.phases.download = timings.end - timings.response;\n timings.phases.total = timings.end - timings.start;\n });\n response.prependOnceListener('aborted', onAbort);\n });\n return timings;\n};\nexports.default = timer;\n// For CommonJS default export support\nmodule.exports = timer;\nmodule.exports.default = timer;\n", "'use strict';\nconst {\n\tV4MAPPED,\n\tADDRCONFIG,\n\tALL,\n\tpromises: {\n\t\tResolver: AsyncResolver\n\t},\n\tlookup: dnsLookup\n} = require('dns');\nconst {promisify} = require('util');\nconst os = require('os');\n\nconst kCacheableLookupCreateConnection = Symbol('cacheableLookupCreateConnection');\nconst kCacheableLookupInstance = Symbol('cacheableLookupInstance');\nconst kExpires = Symbol('expires');\n\nconst supportsALL = typeof ALL === 'number';\n\nconst verifyAgent = agent => {\n\tif (!(agent && typeof agent.createConnection === 'function')) {\n\t\tthrow new Error('Expected an Agent instance as the first argument');\n\t}\n};\n\nconst map4to6 = entries => {\n\tfor (const entry of entries) {\n\t\tif (entry.family === 6) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tentry.address = `::ffff:${entry.address}`;\n\t\tentry.family = 6;\n\t}\n};\n\nconst getIfaceInfo = () => {\n\tlet has4 = false;\n\tlet has6 = false;\n\n\tfor (const device of Object.values(os.networkInterfaces())) {\n\t\tfor (const iface of device) {\n\t\t\tif (iface.internal) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (iface.family === 'IPv6') {\n\t\t\t\thas6 = true;\n\t\t\t} else {\n\t\t\t\thas4 = true;\n\t\t\t}\n\n\t\t\tif (has4 && has6) {\n\t\t\t\treturn {has4, has6};\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {has4, has6};\n};\n\nconst isIterable = map => {\n\treturn Symbol.iterator in map;\n};\n\nconst ttl = {ttl: true};\nconst all = {all: true};\n\nclass CacheableLookup {\n\tconstructor({\n\t\tcache = new Map(),\n\t\tmaxTtl = Infinity,\n\t\tfallbackDuration = 3600,\n\t\terrorTtl = 0.15,\n\t\tresolver = new AsyncResolver(),\n\t\tlookup = dnsLookup\n\t} = {}) {\n\t\tthis.maxTtl = maxTtl;\n\t\tthis.errorTtl = errorTtl;\n\n\t\tthis._cache = cache;\n\t\tthis._resolver = resolver;\n\t\tthis._dnsLookup = promisify(lookup);\n\n\t\tif (this._resolver instanceof AsyncResolver) {\n\t\t\tthis._resolve4 = this._resolver.resolve4.bind(this._resolver);\n\t\t\tthis._resolve6 = this._resolver.resolve6.bind(this._resolver);\n\t\t} else {\n\t\t\tthis._resolve4 = promisify(this._resolver.resolve4.bind(this._resolver));\n\t\t\tthis._resolve6 = promisify(this._resolver.resolve6.bind(this._resolver));\n\t\t}\n\n\t\tthis._iface = getIfaceInfo();\n\n\t\tthis._pending = {};\n\t\tthis._nextRemovalTime = false;\n\t\tthis._hostnamesToFallback = new Set();\n\n\t\tif (fallbackDuration < 1) {\n\t\t\tthis._fallback = false;\n\t\t} else {\n\t\t\tthis._fallback = true;\n\n\t\t\tconst interval = setInterval(() => {\n\t\t\t\tthis._hostnamesToFallback.clear();\n\t\t\t}, fallbackDuration * 1000);\n\n\t\t\t/* istanbul ignore next: There is no `interval.unref()` when running inside an Electron renderer */\n\t\t\tif (interval.unref) {\n\t\t\t\tinterval.unref();\n\t\t\t}\n\t\t}\n\n\t\tthis.lookup = this.lookup.bind(this);\n\t\tthis.lookupAsync = this.lookupAsync.bind(this);\n\t}\n\n\tset servers(servers) {\n\t\tthis.clear();\n\n\t\tthis._resolver.setServers(servers);\n\t}\n\n\tget servers() {\n\t\treturn this._resolver.getServers();\n\t}\n\n\tlookup(hostname, options, callback) {\n\t\tif (typeof options === 'function') {\n\t\t\tcallback = options;\n\t\t\toptions = {};\n\t\t} else if (typeof options === 'number') {\n\t\t\toptions = {\n\t\t\t\tfamily: options\n\t\t\t};\n\t\t}\n\n\t\tif (!callback) {\n\t\t\tthrow new Error('Callback must be a function.');\n\t\t}\n\n\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\tthis.lookupAsync(hostname, options).then(result => {\n\t\t\tif (options.all) {\n\t\t\t\tcallback(null, result);\n\t\t\t} else {\n\t\t\t\tcallback(null, result.address, result.family, result.expires, result.ttl);\n\t\t\t}\n\t\t}, callback);\n\t}\n\n\tasync lookupAsync(hostname, options = {}) {\n\t\tif (typeof options === 'number') {\n\t\t\toptions = {\n\t\t\t\tfamily: options\n\t\t\t};\n\t\t}\n\n\t\tlet cached = await this.query(hostname);\n\n\t\tif (options.family === 6) {\n\t\t\tconst filtered = cached.filter(entry => entry.family === 6);\n\n\t\t\tif (options.hints & V4MAPPED) {\n\t\t\t\tif ((supportsALL && options.hints & ALL) || filtered.length === 0) {\n\t\t\t\t\tmap4to6(cached);\n\t\t\t\t} else {\n\t\t\t\t\tcached = filtered;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcached = filtered;\n\t\t\t}\n\t\t} else if (options.family === 4) {\n\t\t\tcached = cached.filter(entry => entry.family === 4);\n\t\t}\n\n\t\tif (options.hints & ADDRCONFIG) {\n\t\t\tconst {_iface} = this;\n\t\t\tcached = cached.filter(entry => entry.family === 6 ? _iface.has6 : _iface.has4);\n\t\t}\n\n\t\tif (cached.length === 0) {\n\t\t\tconst error = new Error(`cacheableLookup ENOTFOUND ${hostname}`);\n\t\t\terror.code = 'ENOTFOUND';\n\t\t\terror.hostname = hostname;\n\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (options.all) {\n\t\t\treturn cached;\n\t\t}\n\n\t\treturn cached[0];\n\t}\n\n\tasync query(hostname) {\n\t\tlet cached = await this._cache.get(hostname);\n\n\t\tif (!cached) {\n\t\t\tconst pending = this._pending[hostname];\n\n\t\t\tif (pending) {\n\t\t\t\tcached = await pending;\n\t\t\t} else {\n\t\t\t\tconst newPromise = this.queryAndCache(hostname);\n\t\t\t\tthis._pending[hostname] = newPromise;\n\n\t\t\t\ttry {\n\t\t\t\t\tcached = await newPromise;\n\t\t\t\t} finally {\n\t\t\t\t\tdelete this._pending[hostname];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tcached = cached.map(entry => {\n\t\t\treturn {...entry};\n\t\t});\n\n\t\treturn cached;\n\t}\n\n\tasync _resolve(hostname) {\n\t\tconst wrap = async promise => {\n\t\t\ttry {\n\t\t\t\treturn await promise;\n\t\t\t} catch (error) {\n\t\t\t\tif (error.code === 'ENODATA' || error.code === 'ENOTFOUND') {\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t};\n\n\t\t// ANY is unsafe as it doesn't trigger new queries in the underlying server.\n\t\tconst [A, AAAA] = await Promise.all([\n\t\t\tthis._resolve4(hostname, ttl),\n\t\t\tthis._resolve6(hostname, ttl)\n\t\t].map(promise => wrap(promise)));\n\n\t\tlet aTtl = 0;\n\t\tlet aaaaTtl = 0;\n\t\tlet cacheTtl = 0;\n\n\t\tconst now = Date.now();\n\n\t\tfor (const entry of A) {\n\t\t\tentry.family = 4;\n\t\t\tentry.expires = now + (entry.ttl * 1000);\n\n\t\t\taTtl = Math.max(aTtl, entry.ttl);\n\t\t}\n\n\t\tfor (const entry of AAAA) {\n\t\t\tentry.family = 6;\n\t\t\tentry.expires = now + (entry.ttl * 1000);\n\n\t\t\taaaaTtl = Math.max(aaaaTtl, entry.ttl);\n\t\t}\n\n\t\tif (A.length > 0) {\n\t\t\tif (AAAA.length > 0) {\n\t\t\t\tcacheTtl = Math.min(aTtl, aaaaTtl);\n\t\t\t} else {\n\t\t\t\tcacheTtl = aTtl;\n\t\t\t}\n\t\t} else {\n\t\t\tcacheTtl = aaaaTtl;\n\t\t}\n\n\t\treturn {\n\t\t\tentries: [\n\t\t\t\t...A,\n\t\t\t\t...AAAA\n\t\t\t],\n\t\t\tcacheTtl\n\t\t};\n\t}\n\n\tasync _lookup(hostname) {\n\t\ttry {\n\t\t\tconst entries = await this._dnsLookup(hostname, {\n\t\t\t\tall: true\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\tentries,\n\t\t\t\tcacheTtl: 0\n\t\t\t};\n\t\t} catch (_) {\n\t\t\treturn {\n\t\t\t\tentries: [],\n\t\t\t\tcacheTtl: 0\n\t\t\t};\n\t\t}\n\t}\n\n\tasync _set(hostname, data, cacheTtl) {\n\t\tif (this.maxTtl > 0 && cacheTtl > 0) {\n\t\t\tcacheTtl = Math.min(cacheTtl, this.maxTtl) * 1000;\n\t\t\tdata[kExpires] = Date.now() + cacheTtl;\n\n\t\t\ttry {\n\t\t\t\tawait this._cache.set(hostname, data, cacheTtl);\n\t\t\t} catch (error) {\n\t\t\t\tthis.lookupAsync = async () => {\n\t\t\t\t\tconst cacheError = new Error('Cache Error. Please recreate the CacheableLookup instance.');\n\t\t\t\t\tcacheError.cause = error;\n\n\t\t\t\t\tthrow cacheError;\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (isIterable(this._cache)) {\n\t\t\t\tthis._tick(cacheTtl);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync queryAndCache(hostname) {\n\t\tif (this._hostnamesToFallback.has(hostname)) {\n\t\t\treturn this._dnsLookup(hostname, all);\n\t\t}\n\n\t\tlet query = await this._resolve(hostname);\n\n\t\tif (query.entries.length === 0 && this._fallback) {\n\t\t\tquery = await this._lookup(hostname);\n\n\t\t\tif (query.entries.length !== 0) {\n\t\t\t\t// Use `dns.lookup(...)` for that particular hostname\n\t\t\t\tthis._hostnamesToFallback.add(hostname);\n\t\t\t}\n\t\t}\n\n\t\tconst cacheTtl = query.entries.length === 0 ? this.errorTtl : query.cacheTtl;\n\t\tawait this._set(hostname, query.entries, cacheTtl);\n\n\t\treturn query.entries;\n\t}\n\n\t_tick(ms) {\n\t\tconst nextRemovalTime = this._nextRemovalTime;\n\n\t\tif (!nextRemovalTime || ms < nextRemovalTime) {\n\t\t\tclearTimeout(this._removalTimeout);\n\n\t\t\tthis._nextRemovalTime = ms;\n\n\t\t\tthis._removalTimeout = setTimeout(() => {\n\t\t\t\tthis._nextRemovalTime = false;\n\n\t\t\t\tlet nextExpiry = Infinity;\n\n\t\t\t\tconst now = Date.now();\n\n\t\t\t\tfor (const [hostname, entries] of this._cache) {\n\t\t\t\t\tconst expires = entries[kExpires];\n\n\t\t\t\t\tif (now >= expires) {\n\t\t\t\t\t\tthis._cache.delete(hostname);\n\t\t\t\t\t} else if (expires < nextExpiry) {\n\t\t\t\t\t\tnextExpiry = expires;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (nextExpiry !== Infinity) {\n\t\t\t\t\tthis._tick(nextExpiry - now);\n\t\t\t\t}\n\t\t\t}, ms);\n\n\t\t\t/* istanbul ignore next: There is no `timeout.unref()` when running inside an Electron renderer */\n\t\t\tif (this._removalTimeout.unref) {\n\t\t\t\tthis._removalTimeout.unref();\n\t\t\t}\n\t\t}\n\t}\n\n\tinstall(agent) {\n\t\tverifyAgent(agent);\n\n\t\tif (kCacheableLookupCreateConnection in agent) {\n\t\t\tthrow new Error('CacheableLookup has been already installed');\n\t\t}\n\n\t\tagent[kCacheableLookupCreateConnection] = agent.createConnection;\n\t\tagent[kCacheableLookupInstance] = this;\n\n\t\tagent.createConnection = (options, callback) => {\n\t\t\tif (!('lookup' in options)) {\n\t\t\t\toptions.lookup = this.lookup;\n\t\t\t}\n\n\t\t\treturn agent[kCacheableLookupCreateConnection](options, callback);\n\t\t};\n\t}\n\n\tuninstall(agent) {\n\t\tverifyAgent(agent);\n\n\t\tif (agent[kCacheableLookupCreateConnection]) {\n\t\t\tif (agent[kCacheableLookupInstance] !== this) {\n\t\t\t\tthrow new Error('The agent is not owned by this CacheableLookup instance');\n\t\t\t}\n\n\t\t\tagent.createConnection = agent[kCacheableLookupCreateConnection];\n\n\t\t\tdelete agent[kCacheableLookupCreateConnection];\n\t\t\tdelete agent[kCacheableLookupInstance];\n\t\t}\n\t}\n\n\tupdateInterfaceInfo() {\n\t\tconst {_iface} = this;\n\n\t\tthis._iface = getIfaceInfo();\n\n\t\tif ((_iface.has4 && !this._iface.has4) || (_iface.has6 && !this._iface.has6)) {\n\t\t\tthis._cache.clear();\n\t\t}\n\t}\n\n\tclear(hostname) {\n\t\tif (hostname) {\n\t\t\tthis._cache.delete(hostname);\n\t\t\treturn;\n\t\t}\n\n\t\tthis._cache.clear();\n\t}\n}\n\nmodule.exports = CacheableLookup;\nmodule.exports.default = CacheableLookup;\n", "'use strict';\n\n// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs\nconst DATA_URL_DEFAULT_MIME_TYPE = 'text/plain';\nconst DATA_URL_DEFAULT_CHARSET = 'us-ascii';\n\nconst testParameter = (name, filters) => {\n\treturn filters.some(filter => filter instanceof RegExp ? filter.test(name) : filter === name);\n};\n\nconst normalizeDataURL = (urlString, {stripHash}) => {\n\tconst match = /^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(urlString);\n\n\tif (!match) {\n\t\tthrow new Error(`Invalid URL: ${urlString}`);\n\t}\n\n\tlet {type, data, hash} = match.groups;\n\tconst mediaType = type.split(';');\n\thash = stripHash ? '' : hash;\n\n\tlet isBase64 = false;\n\tif (mediaType[mediaType.length - 1] === 'base64') {\n\t\tmediaType.pop();\n\t\tisBase64 = true;\n\t}\n\n\t// Lowercase MIME type\n\tconst mimeType = (mediaType.shift() || '').toLowerCase();\n\tconst attributes = mediaType\n\t\t.map(attribute => {\n\t\t\tlet [key, value = ''] = attribute.split('=').map(string => string.trim());\n\n\t\t\t// Lowercase `charset`\n\t\t\tif (key === 'charset') {\n\t\t\t\tvalue = value.toLowerCase();\n\n\t\t\t\tif (value === DATA_URL_DEFAULT_CHARSET) {\n\t\t\t\t\treturn '';\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn `${key}${value ? `=${value}` : ''}`;\n\t\t})\n\t\t.filter(Boolean);\n\n\tconst normalizedMediaType = [\n\t\t...attributes\n\t];\n\n\tif (isBase64) {\n\t\tnormalizedMediaType.push('base64');\n\t}\n\n\tif (normalizedMediaType.length !== 0 || (mimeType && mimeType !== DATA_URL_DEFAULT_MIME_TYPE)) {\n\t\tnormalizedMediaType.unshift(mimeType);\n\t}\n\n\treturn `data:${normalizedMediaType.join(';')},${isBase64 ? data.trim() : data}${hash ? `#${hash}` : ''}`;\n};\n\nconst normalizeUrl = (urlString, options) => {\n\toptions = {\n\t\tdefaultProtocol: 'http:',\n\t\tnormalizeProtocol: true,\n\t\tforceHttp: false,\n\t\tforceHttps: false,\n\t\tstripAuthentication: true,\n\t\tstripHash: false,\n\t\tstripTextFragment: true,\n\t\tstripWWW: true,\n\t\tremoveQueryParameters: [/^utm_\\w+/i],\n\t\tremoveTrailingSlash: true,\n\t\tremoveSingleSlash: true,\n\t\tremoveDirectoryIndex: false,\n\t\tsortQueryParameters: true,\n\t\t...options\n\t};\n\n\turlString = urlString.trim();\n\n\t// Data URL\n\tif (/^data:/i.test(urlString)) {\n\t\treturn normalizeDataURL(urlString, options);\n\t}\n\n\tif (/^view-source:/i.test(urlString)) {\n\t\tthrow new Error('`view-source:` is not supported as it is a non-standard protocol');\n\t}\n\n\tconst hasRelativeProtocol = urlString.startsWith('//');\n\tconst isRelativeUrl = !hasRelativeProtocol && /^\\.*\\//.test(urlString);\n\n\t// Prepend protocol\n\tif (!isRelativeUrl) {\n\t\turlString = urlString.replace(/^(?!(?:\\w+:)?\\/\\/)|^\\/\\//, options.defaultProtocol);\n\t}\n\n\tconst urlObj = new URL(urlString);\n\n\tif (options.forceHttp && options.forceHttps) {\n\t\tthrow new Error('The `forceHttp` and `forceHttps` options cannot be used together');\n\t}\n\n\tif (options.forceHttp && urlObj.protocol === 'https:') {\n\t\turlObj.protocol = 'http:';\n\t}\n\n\tif (options.forceHttps && urlObj.protocol === 'http:') {\n\t\turlObj.protocol = 'https:';\n\t}\n\n\t// Remove auth\n\tif (options.stripAuthentication) {\n\t\turlObj.username = '';\n\t\turlObj.password = '';\n\t}\n\n\t// Remove hash\n\tif (options.stripHash) {\n\t\turlObj.hash = '';\n\t} else if (options.stripTextFragment) {\n\t\turlObj.hash = urlObj.hash.replace(/#?:~:text.*?$/i, '');\n\t}\n\n\t// Remove duplicate slashes if not preceded by a protocol\n\tif (urlObj.pathname) {\n\t\turlObj.pathname = urlObj.pathname.replace(/(?<!\\b(?:[a-z][a-z\\d+\\-.]{1,50}:))\\/{2,}/g, '/');\n\t}\n\n\t// Decode URI octets\n\tif (urlObj.pathname) {\n\t\ttry {\n\t\t\turlObj.pathname = decodeURI(urlObj.pathname);\n\t\t} catch (_) {}\n\t}\n\n\t// Remove directory index\n\tif (options.removeDirectoryIndex === true) {\n\t\toptions.removeDirectoryIndex = [/^index\\.[a-z]+$/];\n\t}\n\n\tif (Array.isArray(options.removeDirectoryIndex) && options.removeDirectoryIndex.length > 0) {\n\t\tlet pathComponents = urlObj.pathname.split('/');\n\t\tconst lastComponent = pathComponents[pathComponents.length - 1];\n\n\t\tif (testParameter(lastComponent, options.removeDirectoryIndex)) {\n\t\t\tpathComponents = pathComponents.slice(0, pathComponents.length - 1);\n\t\t\turlObj.pathname = pathComponents.slice(1).join('/') + '/';\n\t\t}\n\t}\n\n\tif (urlObj.hostname) {\n\t\t// Remove trailing dot\n\t\turlObj.hostname = urlObj.hostname.replace(/\\.$/, '');\n\n\t\t// Remove `www.`\n\t\tif (options.stripWWW && /^www\\.(?!www\\.)(?:[a-z\\-\\d]{1,63})\\.(?:[a-z.\\-\\d]{2,63})$/.test(urlObj.hostname)) {\n\t\t\t// Each label should be max 63 at length (min: 1).\n\t\t\t// Source: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names\n\t\t\t// Each TLD should be up to 63 characters long (min: 2).\n\t\t\t// It is technically possible to have a single character TLD, but none currently exist.\n\t\t\turlObj.hostname = urlObj.hostname.replace(/^www\\./, '');\n\t\t}\n\t}\n\n\t// Remove query unwanted parameters\n\tif (Array.isArray(options.removeQueryParameters)) {\n\t\tfor (const key of [...urlObj.searchParams.keys()]) {\n\t\t\tif (testParameter(key, options.removeQueryParameters)) {\n\t\t\t\turlObj.searchParams.delete(key);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (options.removeQueryParameters === true) {\n\t\turlObj.search = '';\n\t}\n\n\t// Sort query parameters\n\tif (options.sortQueryParameters) {\n\t\turlObj.searchParams.sort();\n\t}\n\n\tif (options.removeTrailingSlash) {\n\t\turlObj.pathname = urlObj.pathname.replace(/\\/$/, '');\n\t}\n\n\tconst oldUrlString = urlString;\n\n\t// Take advantage of many of the Node `url` normalizations\n\turlString = urlObj.toString();\n\n\tif (!options.removeSingleSlash && urlObj.pathname === '/' && !oldUrlString.endsWith('/') && urlObj.hash === '') {\n\t\turlString = urlString.replace(/\\/$/, '');\n\t}\n\n\t// Remove ending `/` unless removeSingleSlash is false\n\tif ((options.removeTrailingSlash || urlObj.pathname === '/') && urlObj.hash === '' && options.removeSingleSlash) {\n\t\turlString = urlString.replace(/\\/$/, '');\n\t}\n\n\t// Restore relative protocol, if applicable\n\tif (hasRelativeProtocol && !options.normalizeProtocol) {\n\t\turlString = urlString.replace(/^http:\\/\\//, '//');\n\t}\n\n\t// Remove http/https\n\tif (options.stripProtocol) {\n\t\turlString = urlString.replace(/^(?:https?:)?\\/\\//, '');\n\t}\n\n\treturn urlString;\n};\n\nmodule.exports = normalizeUrl;\n", "// Returns a wrapper function that returns a wrapped callback\n// The wrapper function should do some stuff, and return a\n// presumably different callback function.\n// This makes sure that own properties are retained, so that\n// decorations and such are not lost along the way.\nmodule.exports = wrappy\nfunction wrappy (fn, cb) {\n if (fn && cb) return wrappy(fn)(cb)\n\n if (typeof fn !== 'function')\n throw new TypeError('need wrapper function')\n\n Object.keys(fn).forEach(function (k) {\n wrapper[k] = fn[k]\n })\n\n return wrapper\n\n function wrapper() {\n var args = new Array(arguments.length)\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i]\n }\n var ret = fn.apply(this, args)\n var cb = args[args.length-1]\n if (typeof ret === 'function' && ret !== cb) {\n Object.keys(cb).forEach(function (k) {\n ret[k] = cb[k]\n })\n }\n return ret\n }\n}\n", "var wrappy = require('wrappy')\nmodule.exports = wrappy(once)\nmodule.exports.strict = wrappy(onceStrict)\n\nonce.proto = once(function () {\n Object.defineProperty(Function.prototype, 'once', {\n value: function () {\n return once(this)\n },\n configurable: true\n })\n\n Object.defineProperty(Function.prototype, 'onceStrict', {\n value: function () {\n return onceStrict(this)\n },\n configurable: true\n })\n})\n\nfunction once (fn) {\n var f = function () {\n if (f.called) return f.value\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n f.called = false\n return f\n}\n\nfunction onceStrict (fn) {\n var f = function () {\n if (f.called)\n throw new Error(f.onceError)\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n var name = fn.name || 'Function wrapped with `once`'\n f.onceError = name + \" shouldn't be called more than once\"\n f.called = false\n return f\n}\n", "var once = require('once');\n\nvar noop = function() {};\n\nvar isRequest = function(stream) {\n\treturn stream.setHeader && typeof stream.abort === 'function';\n};\n\nvar isChildProcess = function(stream) {\n\treturn stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3\n};\n\nvar eos = function(stream, opts, callback) {\n\tif (typeof opts === 'function') return eos(stream, null, opts);\n\tif (!opts) opts = {};\n\n\tcallback = once(callback || noop);\n\n\tvar ws = stream._writableState;\n\tvar rs = stream._readableState;\n\tvar readable = opts.readable || (opts.readable !== false && stream.readable);\n\tvar writable = opts.writable || (opts.writable !== false && stream.writable);\n\tvar cancelled = false;\n\n\tvar onlegacyfinish = function() {\n\t\tif (!stream.writable) onfinish();\n\t};\n\n\tvar onfinish = function() {\n\t\twritable = false;\n\t\tif (!readable) callback.call(stream);\n\t};\n\n\tvar onend = function() {\n\t\treadable = false;\n\t\tif (!writable) callback.call(stream);\n\t};\n\n\tvar onexit = function(exitCode) {\n\t\tcallback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);\n\t};\n\n\tvar onerror = function(err) {\n\t\tcallback.call(stream, err);\n\t};\n\n\tvar onclose = function() {\n\t\tprocess.nextTick(onclosenexttick);\n\t};\n\n\tvar onclosenexttick = function() {\n\t\tif (cancelled) return;\n\t\tif (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close'));\n\t\tif (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close'));\n\t};\n\n\tvar onrequest = function() {\n\t\tstream.req.on('finish', onfinish);\n\t};\n\n\tif (isRequest(stream)) {\n\t\tstream.on('complete', onfinish);\n\t\tstream.on('abort', onclose);\n\t\tif (stream.req) onrequest();\n\t\telse stream.on('request', onrequest);\n\t} else if (writable && !ws) { // legacy streams\n\t\tstream.on('end', onlegacyfinish);\n\t\tstream.on('close', onlegacyfinish);\n\t}\n\n\tif (isChildProcess(stream)) stream.on('exit', onexit);\n\n\tstream.on('end', onend);\n\tstream.on('finish', onfinish);\n\tif (opts.error !== false) stream.on('error', onerror);\n\tstream.on('close', onclose);\n\n\treturn function() {\n\t\tcancelled = true;\n\t\tstream.removeListener('complete', onfinish);\n\t\tstream.removeListener('abort', onclose);\n\t\tstream.removeListener('request', onrequest);\n\t\tif (stream.req) stream.req.removeListener('finish', onfinish);\n\t\tstream.removeListener('end', onlegacyfinish);\n\t\tstream.removeListener('close', onlegacyfinish);\n\t\tstream.removeListener('finish', onfinish);\n\t\tstream.removeListener('exit', onexit);\n\t\tstream.removeListener('end', onend);\n\t\tstream.removeListener('error', onerror);\n\t\tstream.removeListener('close', onclose);\n\t};\n};\n\nmodule.exports = eos;\n", "var once = require('once')\nvar eos = require('end-of-stream')\nvar fs = require('fs') // we only need fs to get the ReadStream and WriteStream prototypes\n\nvar noop = function () {}\nvar ancient = /^v?\\.0/.test(process.version)\n\nvar isFn = function (fn) {\n return typeof fn === 'function'\n}\n\nvar isFS = function (stream) {\n if (!ancient) return false // newer node version do not need to care about fs is a special way\n if (!fs) return false // browser\n return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close)\n}\n\nvar isRequest = function (stream) {\n return stream.setHeader && isFn(stream.abort)\n}\n\nvar destroyer = function (stream, reading, writing, callback) {\n callback = once(callback)\n\n var closed = false\n stream.on('close', function () {\n closed = true\n })\n\n eos(stream, {readable: reading, writable: writing}, function (err) {\n if (err) return callback(err)\n closed = true\n callback()\n })\n\n var destroyed = false\n return function (err) {\n if (closed) return\n if (destroyed) return\n destroyed = true\n\n if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks\n if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want\n\n if (isFn(stream.destroy)) return stream.destroy()\n\n callback(err || new Error('stream was destroyed'))\n }\n}\n\nvar call = function (fn) {\n fn()\n}\n\nvar pipe = function (from, to) {\n return from.pipe(to)\n}\n\nvar pump = function () {\n var streams = Array.prototype.slice.call(arguments)\n var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop\n\n if (Array.isArray(streams[0])) streams = streams[0]\n if (streams.length < 2) throw new Error('pump requires two streams per minimum')\n\n var error\n var destroys = streams.map(function (stream, i) {\n var reading = i < streams.length - 1\n var writing = i > 0\n return destroyer(stream, reading, writing, function (err) {\n if (!error) error = err\n if (err) destroys.forEach(call)\n if (reading) return\n destroys.forEach(call)\n callback(error)\n })\n })\n\n return streams.reduce(pipe)\n}\n\nmodule.exports = pump\n", "'use strict';\nconst {PassThrough: PassThroughStream} = require('stream');\n\nmodule.exports = options => {\n\toptions = {...options};\n\n\tconst {array} = options;\n\tlet {encoding} = options;\n\tconst isBuffer = encoding === 'buffer';\n\tlet objectMode = false;\n\n\tif (array) {\n\t\tobjectMode = !(encoding || isBuffer);\n\t} else {\n\t\tencoding = encoding || 'utf8';\n\t}\n\n\tif (isBuffer) {\n\t\tencoding = null;\n\t}\n\n\tconst stream = new PassThroughStream({objectMode});\n\n\tif (encoding) {\n\t\tstream.setEncoding(encoding);\n\t}\n\n\tlet length = 0;\n\tconst chunks = [];\n\n\tstream.on('data', chunk => {\n\t\tchunks.push(chunk);\n\n\t\tif (objectMode) {\n\t\t\tlength = chunks.length;\n\t\t} else {\n\t\t\tlength += chunk.length;\n\t\t}\n\t});\n\n\tstream.getBufferedValue = () => {\n\t\tif (array) {\n\t\t\treturn chunks;\n\t\t}\n\n\t\treturn isBuffer ? Buffer.concat(chunks, length) : chunks.join('');\n\t};\n\n\tstream.getBufferedLength = () => length;\n\n\treturn stream;\n};\n", "'use strict';\nconst {constants: BufferConstants} = require('buffer');\nconst pump = require('pump');\nconst bufferStream = require('./buffer-stream');\n\nclass MaxBufferError extends Error {\n\tconstructor() {\n\t\tsuper('maxBuffer exceeded');\n\t\tthis.name = 'MaxBufferError';\n\t}\n}\n\nasync function getStream(inputStream, options) {\n\tif (!inputStream) {\n\t\treturn Promise.reject(new Error('Expected a stream'));\n\t}\n\n\toptions = {\n\t\tmaxBuffer: Infinity,\n\t\t...options\n\t};\n\n\tconst {maxBuffer} = options;\n\n\tlet stream;\n\tawait new Promise((resolve, reject) => {\n\t\tconst rejectPromise = error => {\n\t\t\t// Don't retrieve an oversized buffer.\n\t\t\tif (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) {\n\t\t\t\terror.bufferedData = stream.getBufferedValue();\n\t\t\t}\n\n\t\t\treject(error);\n\t\t};\n\n\t\tstream = pump(inputStream, bufferStream(options), error => {\n\t\t\tif (error) {\n\t\t\t\trejectPromise(error);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tresolve();\n\t\t});\n\n\t\tstream.on('data', () => {\n\t\t\tif (stream.getBufferedLength() > maxBuffer) {\n\t\t\t\trejectPromise(new MaxBufferError());\n\t\t\t}\n\t\t});\n\t});\n\n\treturn stream.getBufferedValue();\n}\n\nmodule.exports = getStream;\n// TODO: Remove this for the next major release\nmodule.exports.default = getStream;\nmodule.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'});\nmodule.exports.array = (stream, options) => getStream(stream, {...options, array: true});\nmodule.exports.MaxBufferError = MaxBufferError;\n", "'use strict';\n// rfc7231 6.1\nconst statusCodeCacheableByDefault = new Set([\n 200,\n 203,\n 204,\n 206,\n 300,\n 301,\n 404,\n 405,\n 410,\n 414,\n 501,\n]);\n\n// This implementation does not understand partial responses (206)\nconst understoodStatuses = new Set([\n 200,\n 203,\n 204,\n 300,\n 301,\n 302,\n 303,\n 307,\n 308,\n 404,\n 405,\n 410,\n 414,\n 501,\n]);\n\nconst errorStatusCodes = new Set([\n 500,\n 502,\n 503, \n 504,\n]);\n\nconst hopByHopHeaders = {\n date: true, // included, because we add Age update Date\n connection: true,\n 'keep-alive': true,\n 'proxy-authenticate': true,\n 'proxy-authorization': true,\n te: true,\n trailer: true,\n 'transfer-encoding': true,\n upgrade: true,\n};\n\nconst excludedFromRevalidationUpdate = {\n // Since the old body is reused, it doesn't make sense to change properties of the body\n 'content-length': true,\n 'content-encoding': true,\n 'transfer-encoding': true,\n 'content-range': true,\n};\n\nfunction toNumberOrZero(s) {\n const n = parseInt(s, 10);\n return isFinite(n) ? n : 0;\n}\n\n// RFC 5861\nfunction isErrorResponse(response) {\n // consider undefined response as faulty\n if(!response) {\n return true\n }\n return errorStatusCodes.has(response.status);\n}\n\nfunction parseCacheControl(header) {\n const cc = {};\n if (!header) return cc;\n\n // TODO: When there is more than one value present for a given directive (e.g., two Expires header fields, multiple Cache-Control: max-age directives),\n // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale\n const parts = header.trim().split(/\\s*,\\s*/); // TODO: lame parsing\n for (const part of parts) {\n const [k, v] = part.split(/\\s*=\\s*/, 2);\n cc[k] = v === undefined ? true : v.replace(/^\"|\"$/g, ''); // TODO: lame unquoting\n }\n\n return cc;\n}\n\nfunction formatCacheControl(cc) {\n let parts = [];\n for (const k in cc) {\n const v = cc[k];\n parts.push(v === true ? k : k + '=' + v);\n }\n if (!parts.length) {\n return undefined;\n }\n return parts.join(', ');\n}\n\nmodule.exports = class CachePolicy {\n constructor(\n req,\n res,\n {\n shared,\n cacheHeuristic,\n immutableMinTimeToLive,\n ignoreCargoCult,\n _fromObject,\n } = {}\n ) {\n if (_fromObject) {\n this._fromObject(_fromObject);\n return;\n }\n\n if (!res || !res.headers) {\n throw Error('Response headers missing');\n }\n this._assertRequestHasHeaders(req);\n\n this._responseTime = this.now();\n this._isShared = shared !== false;\n this._cacheHeuristic =\n undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE\n this._immutableMinTtl =\n undefined !== immutableMinTimeToLive\n ? immutableMinTimeToLive\n : 24 * 3600 * 1000;\n\n this._status = 'status' in res ? res.status : 200;\n this._resHeaders = res.headers;\n this._rescc = parseCacheControl(res.headers['cache-control']);\n this._method = 'method' in req ? req.method : 'GET';\n this._url = req.url;\n this._host = req.headers.host;\n this._noAuthorization = !req.headers.authorization;\n this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used\n this._reqcc = parseCacheControl(req.headers['cache-control']);\n\n // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching,\n // so there's no point stricly adhering to the blindly copy&pasted directives.\n if (\n ignoreCargoCult &&\n 'pre-check' in this._rescc &&\n 'post-check' in this._rescc\n ) {\n delete this._rescc['pre-check'];\n delete this._rescc['post-check'];\n delete this._rescc['no-cache'];\n delete this._rescc['no-store'];\n delete this._rescc['must-revalidate'];\n this._resHeaders = Object.assign({}, this._resHeaders, {\n 'cache-control': formatCacheControl(this._rescc),\n });\n delete this._resHeaders.expires;\n delete this._resHeaders.pragma;\n }\n\n // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive\n // as having the same effect as if \"Cache-Control: no-cache\" were present (see Section 5.2.1).\n if (\n res.headers['cache-control'] == null &&\n /no-cache/.test(res.headers.pragma)\n ) {\n this._rescc['no-cache'] = true;\n }\n }\n\n now() {\n return Date.now();\n }\n\n storable() {\n // The \"no-store\" request directive indicates that a cache MUST NOT store any part of either this request or any response to it.\n return !!(\n !this._reqcc['no-store'] &&\n // A cache MUST NOT store a response to any request, unless:\n // The request method is understood by the cache and defined as being cacheable, and\n ('GET' === this._method ||\n 'HEAD' === this._method ||\n ('POST' === this._method && this._hasExplicitExpiration())) &&\n // the response status code is understood by the cache, and\n understoodStatuses.has(this._status) &&\n // the \"no-store\" cache directive does not appear in request or response header fields, and\n !this._rescc['no-store'] &&\n // the \"private\" response directive does not appear in the response, if the cache is shared, and\n (!this._isShared || !this._rescc.private) &&\n // the Authorization header field does not appear in the request, if the cache is shared,\n (!this._isShared ||\n this._noAuthorization ||\n this._allowsStoringAuthenticated()) &&\n // the response either:\n // contains an Expires header field, or\n (this._resHeaders.expires ||\n // contains a max-age response directive, or\n // contains a s-maxage response directive and the cache is shared, or\n // contains a public response directive.\n this._rescc['max-age'] ||\n (this._isShared && this._rescc['s-maxage']) ||\n this._rescc.public ||\n // has a status code that is defined as cacheable by default\n statusCodeCacheableByDefault.has(this._status))\n );\n }\n\n _hasExplicitExpiration() {\n // 4.2.1 Calculating Freshness Lifetime\n return (\n (this._isShared && this._rescc['s-maxage']) ||\n this._rescc['max-age'] ||\n this._resHeaders.expires\n );\n }\n\n _assertRequestHasHeaders(req) {\n if (!req || !req.headers) {\n throw Error('Request headers missing');\n }\n }\n\n satisfiesWithoutRevalidation(req) {\n this._assertRequestHasHeaders(req);\n\n // When presented with a request, a cache MUST NOT reuse a stored response, unless:\n // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive,\n // unless the stored response is successfully validated (Section 4.3), and\n const requestCC = parseCacheControl(req.headers['cache-control']);\n if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) {\n return false;\n }\n\n if (requestCC['max-age'] && this.age() > requestCC['max-age']) {\n return false;\n }\n\n if (\n requestCC['min-fresh'] &&\n this.timeToLive() < 1000 * requestCC['min-fresh']\n ) {\n return false;\n }\n\n // the stored response is either:\n // fresh, or allowed to be served stale\n if (this.stale()) {\n const allowsStale =\n requestCC['max-stale'] &&\n !this._rescc['must-revalidate'] &&\n (true === requestCC['max-stale'] ||\n requestCC['max-stale'] > this.age() - this.maxAge());\n if (!allowsStale) {\n return false;\n }\n }\n\n return this._requestMatches(req, false);\n }\n\n _requestMatches(req, allowHeadMethod) {\n // The presented effective request URI and that of the stored response match, and\n return (\n (!this._url || this._url === req.url) &&\n this._host === req.headers.host &&\n // the request method associated with the stored response allows it to be used for the presented request, and\n (!req.method ||\n this._method === req.method ||\n (allowHeadMethod && 'HEAD' === req.method)) &&\n // selecting header fields nominated by the stored response (if any) match those presented, and\n this._varyMatches(req)\n );\n }\n\n _allowsStoringAuthenticated() {\n // following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage.\n return (\n this._rescc['must-revalidate'] ||\n this._rescc.public ||\n this._rescc['s-maxage']\n );\n }\n\n _varyMatches(req) {\n if (!this._resHeaders.vary) {\n return true;\n }\n\n // A Vary header field-value of \"*\" always fails to match\n if (this._resHeaders.vary === '*') {\n return false;\n }\n\n const fields = this._resHeaders.vary\n .trim()\n .toLowerCase()\n .split(/\\s*,\\s*/);\n for (const name of fields) {\n if (req.headers[name] !== this._reqHeaders[name]) return false;\n }\n return true;\n }\n\n _copyWithoutHopByHopHeaders(inHeaders) {\n const headers = {};\n for (const name in inHeaders) {\n if (hopByHopHeaders[name]) continue;\n headers[name] = inHeaders[name];\n }\n // 9.1. Connection\n if (inHeaders.connection) {\n const tokens = inHeaders.connection.trim().split(/\\s*,\\s*/);\n for (const name of tokens) {\n delete headers[name];\n }\n }\n if (headers.warning) {\n const warnings = headers.warning.split(/,/).filter(warning => {\n return !/^\\s*1[0-9][0-9]/.test(warning);\n });\n if (!warnings.length) {\n delete headers.warning;\n } else {\n headers.warning = warnings.join(',').trim();\n }\n }\n return headers;\n }\n\n responseHeaders() {\n const headers = this._copyWithoutHopByHopHeaders(this._resHeaders);\n const age = this.age();\n\n // A cache SHOULD generate 113 warning if it heuristically chose a freshness\n // lifetime greater than 24 hours and the response's age is greater than 24 hours.\n if (\n age > 3600 * 24 &&\n !this._hasExplicitExpiration() &&\n this.maxAge() > 3600 * 24\n ) {\n headers.warning =\n (headers.warning ? `${headers.warning}, ` : '') +\n '113 - \"rfc7234 5.5.4\"';\n }\n headers.age = `${Math.round(age)}`;\n headers.date = new Date(this.now()).toUTCString();\n return headers;\n }\n\n /**\n * Value of the Date response header or current time if Date was invalid\n * @return timestamp\n */\n date() {\n const serverDate = Date.parse(this._resHeaders.date);\n if (isFinite(serverDate)) {\n return serverDate;\n }\n return this._responseTime;\n }\n\n /**\n * Value of the Age header, in seconds, updated for the current time.\n * May be fractional.\n *\n * @return Number\n */\n age() {\n let age = this._ageValue();\n\n const residentTime = (this.now() - this._responseTime) / 1000;\n return age + residentTime;\n }\n\n _ageValue() {\n return toNumberOrZero(this._resHeaders.age);\n }\n\n /**\n * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`.\n *\n * For an up-to-date value, see `timeToLive()`.\n *\n * @return Number\n */\n maxAge() {\n if (!this.storable() || this._rescc['no-cache']) {\n return 0;\n }\n\n // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default\n // so this implementation requires explicit opt-in via public header\n if (\n this._isShared &&\n (this._resHeaders['set-cookie'] &&\n !this._rescc.public &&\n !this._rescc.immutable)\n ) {\n return 0;\n }\n\n if (this._resHeaders.vary === '*') {\n return 0;\n }\n\n if (this._isShared) {\n if (this._rescc['proxy-revalidate']) {\n return 0;\n }\n // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field.\n if (this._rescc['s-maxage']) {\n return toNumberOrZero(this._rescc['s-maxage']);\n }\n }\n\n // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field.\n if (this._rescc['max-age']) {\n return toNumberOrZero(this._rescc['max-age']);\n }\n\n const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0;\n\n const serverDate = this.date();\n if (this._resHeaders.expires) {\n const expires = Date.parse(this._resHeaders.expires);\n // A cache recipient MUST interpret invalid date formats, especially the value \"0\", as representing a time in the past (i.e., \"already expired\").\n if (Number.isNaN(expires) || expires < serverDate) {\n return 0;\n }\n return Math.max(defaultMinTtl, (expires - serverDate) / 1000);\n }\n\n if (this._resHeaders['last-modified']) {\n const lastModified = Date.parse(this._resHeaders['last-modified']);\n if (isFinite(lastModified) && serverDate > lastModified) {\n return Math.max(\n defaultMinTtl,\n ((serverDate - lastModified) / 1000) * this._cacheHeuristic\n );\n }\n }\n\n return defaultMinTtl;\n }\n\n timeToLive() {\n const age = this.maxAge() - this.age();\n const staleIfErrorAge = age + toNumberOrZero(this._rescc['stale-if-error']);\n const staleWhileRevalidateAge = age + toNumberOrZero(this._rescc['stale-while-revalidate']);\n return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1000;\n }\n\n stale() {\n return this.maxAge() <= this.age();\n }\n\n _useStaleIfError() {\n return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age();\n }\n\n useStaleWhileRevalidate() {\n return this.maxAge() + toNumberOrZero(this._rescc['stale-while-revalidate']) > this.age();\n }\n\n static fromObject(obj) {\n return new this(undefined, undefined, { _fromObject: obj });\n }\n\n _fromObject(obj) {\n if (this._responseTime) throw Error('Reinitialized');\n if (!obj || obj.v !== 1) throw Error('Invalid serialization');\n\n this._responseTime = obj.t;\n this._isShared = obj.sh;\n this._cacheHeuristic = obj.ch;\n this._immutableMinTtl =\n obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000;\n this._status = obj.st;\n this._resHeaders = obj.resh;\n this._rescc = obj.rescc;\n this._method = obj.m;\n this._url = obj.u;\n this._host = obj.h;\n this._noAuthorization = obj.a;\n this._reqHeaders = obj.reqh;\n this._reqcc = obj.reqcc;\n }\n\n toObject() {\n return {\n v: 1,\n t: this._responseTime,\n sh: this._isShared,\n ch: this._cacheHeuristic,\n imm: this._immutableMinTtl,\n st: this._status,\n resh: this._resHeaders,\n rescc: this._rescc,\n m: this._method,\n u: this._url,\n h: this._host,\n a: this._noAuthorization,\n reqh: this._reqHeaders,\n reqcc: this._reqcc,\n };\n }\n\n /**\n * Headers for sending to the origin server to revalidate stale response.\n * Allows server to return 304 to allow reuse of the previous response.\n *\n * Hop by hop headers are always stripped.\n * Revalidation headers may be added or removed, depending on request.\n */\n revalidationHeaders(incomingReq) {\n this._assertRequestHasHeaders(incomingReq);\n const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers);\n\n // This implementation does not understand range requests\n delete headers['if-range'];\n\n if (!this._requestMatches(incomingReq, true) || !this.storable()) {\n // revalidation allowed via HEAD\n // not for the same resource, or wasn't allowed to be cached anyway\n delete headers['if-none-match'];\n delete headers['if-modified-since'];\n return headers;\n }\n\n /* MUST send that entity-tag in any cache validation request (using If-Match or If-None-Match) if an entity-tag has been provided by the origin server. */\n if (this._resHeaders.etag) {\n headers['if-none-match'] = headers['if-none-match']\n ? `${headers['if-none-match']}, ${this._resHeaders.etag}`\n : this._resHeaders.etag;\n }\n\n // Clients MAY issue simple (non-subrange) GET requests with either weak validators or strong validators. Clients MUST NOT use weak validators in other forms of request.\n const forbidsWeakValidators =\n headers['accept-ranges'] ||\n headers['if-match'] ||\n headers['if-unmodified-since'] ||\n (this._method && this._method != 'GET');\n\n /* SHOULD send the Last-Modified value in non-subrange cache validation requests (using If-Modified-Since) if only a Last-Modified value has been provided by the origin server.\n Note: This implementation does not understand partial responses (206) */\n if (forbidsWeakValidators) {\n delete headers['if-modified-since'];\n\n if (headers['if-none-match']) {\n const etags = headers['if-none-match']\n .split(/,/)\n .filter(etag => {\n return !/^\\s*W\\//.test(etag);\n });\n if (!etags.length) {\n delete headers['if-none-match'];\n } else {\n headers['if-none-match'] = etags.join(',').trim();\n }\n }\n } else if (\n this._resHeaders['last-modified'] &&\n !headers['if-modified-since']\n ) {\n headers['if-modified-since'] = this._resHeaders['last-modified'];\n }\n\n return headers;\n }\n\n /**\n * Creates new CachePolicy with information combined from the previews response,\n * and the new revalidation response.\n *\n * Returns {policy, modified} where modified is a boolean indicating\n * whether the response body has been modified, and old cached body can't be used.\n *\n * @return {Object} {policy: CachePolicy, modified: Boolean}\n */\n revalidatedPolicy(request, response) {\n this._assertRequestHasHeaders(request);\n if(this._useStaleIfError() && isErrorResponse(response)) { // I consider the revalidation request unsuccessful\n return {\n modified: false,\n matches: false,\n policy: this,\n };\n }\n if (!response || !response.headers) {\n throw Error('Response headers missing');\n }\n\n // These aren't going to be supported exactly, since one CachePolicy object\n // doesn't know about all the other cached objects.\n let matches = false;\n if (response.status !== undefined && response.status != 304) {\n matches = false;\n } else if (\n response.headers.etag &&\n !/^\\s*W\\//.test(response.headers.etag)\n ) {\n // \"All of the stored responses with the same strong validator are selected.\n // If none of the stored responses contain the same strong validator,\n // then the cache MUST NOT use the new response to update any stored responses.\"\n matches =\n this._resHeaders.etag &&\n this._resHeaders.etag.replace(/^\\s*W\\//, '') ===\n response.headers.etag;\n } else if (this._resHeaders.etag && response.headers.etag) {\n // \"If the new response contains a weak validator and that validator corresponds\n // to one of the cache's stored responses,\n // then the most recent of those matching stored responses is selected for update.\"\n matches =\n this._resHeaders.etag.replace(/^\\s*W\\//, '') ===\n response.headers.etag.replace(/^\\s*W\\//, '');\n } else if (this._resHeaders['last-modified']) {\n matches =\n this._resHeaders['last-modified'] ===\n response.headers['last-modified'];\n } else {\n // If the new response does not include any form of validator (such as in the case where\n // a client generates an If-Modified-Since request from a source other than the Last-Modified\n // response header field), and there is only one stored response, and that stored response also\n // lacks a validator, then that stored response is selected for update.\n if (\n !this._resHeaders.etag &&\n !this._resHeaders['last-modified'] &&\n !response.headers.etag &&\n !response.headers['last-modified']\n ) {\n matches = true;\n }\n }\n\n if (!matches) {\n return {\n policy: new this.constructor(request, response),\n // Client receiving 304 without body, even if it's invalid/mismatched has no option\n // but to reuse a cached body. We don't have a good way to tell clients to do\n // error recovery in such case.\n modified: response.status != 304,\n matches: false,\n };\n }\n\n // use other header fields provided in the 304 (Not Modified) response to replace all instances\n // of the corresponding header fields in the stored response.\n const headers = {};\n for (const k in this._resHeaders) {\n headers[k] =\n k in response.headers && !excludedFromRevalidationUpdate[k]\n ? response.headers[k]\n : this._resHeaders[k];\n }\n\n const newResponse = Object.assign({}, response, {\n status: this._status,\n method: this._method,\n headers,\n });\n return {\n policy: new this.constructor(request, newResponse, {\n shared: this._isShared,\n cacheHeuristic: this._cacheHeuristic,\n immutableMinTimeToLive: this._immutableMinTtl,\n }),\n modified: false,\n matches: true,\n };\n }\n};\n", "'use strict';\nmodule.exports = object => {\n\tconst result = {};\n\n\tfor (const [key, value] of Object.entries(object)) {\n\t\tresult[key.toLowerCase()] = value;\n\t}\n\n\treturn result;\n};\n", "'use strict';\n\nconst Readable = require('stream').Readable;\nconst lowercaseKeys = require('lowercase-keys');\n\nclass Response extends Readable {\n\tconstructor(statusCode, headers, body, url) {\n\t\tif (typeof statusCode !== 'number') {\n\t\t\tthrow new TypeError('Argument `statusCode` should be a number');\n\t\t}\n\t\tif (typeof headers !== 'object') {\n\t\t\tthrow new TypeError('Argument `headers` should be an object');\n\t\t}\n\t\tif (!(body instanceof Buffer)) {\n\t\t\tthrow new TypeError('Argument `body` should be a buffer');\n\t\t}\n\t\tif (typeof url !== 'string') {\n\t\t\tthrow new TypeError('Argument `url` should be a string');\n\t\t}\n\n\t\tsuper();\n\t\tthis.statusCode = statusCode;\n\t\tthis.headers = lowercaseKeys(headers);\n\t\tthis.body = body;\n\t\tthis.url = url;\n\t}\n\n\t_read() {\n\t\tthis.push(this.body);\n\t\tthis.push(null);\n\t}\n}\n\nmodule.exports = Response;\n", "'use strict';\n\n// We define these manually to ensure they're always copied\n// even if they would move up the prototype chain\n// https://nodejs.org/api/http.html#http_class_http_incomingmessage\nconst knownProps = [\n\t'destroy',\n\t'setTimeout',\n\t'socket',\n\t'headers',\n\t'trailers',\n\t'rawHeaders',\n\t'statusCode',\n\t'httpVersion',\n\t'httpVersionMinor',\n\t'httpVersionMajor',\n\t'rawTrailers',\n\t'statusMessage'\n];\n\nmodule.exports = (fromStream, toStream) => {\n\tconst fromProps = new Set(Object.keys(fromStream).concat(knownProps));\n\n\tfor (const prop of fromProps) {\n\t\t// Don't overwrite existing properties\n\t\tif (prop in toStream) {\n\t\t\tcontinue;\n\t\t}\n\n\t\ttoStream[prop] = typeof fromStream[prop] === 'function' ? fromStream[prop].bind(fromStream) : fromStream[prop];\n\t}\n};\n", "'use strict';\n\nconst PassThrough = require('stream').PassThrough;\nconst mimicResponse = require('mimic-response');\n\nconst cloneResponse = response => {\n\tif (!(response && response.pipe)) {\n\t\tthrow new TypeError('Parameter `response` must be a response stream.');\n\t}\n\n\tconst clone = new PassThrough();\n\tmimicResponse(response, clone);\n\n\treturn response.pipe(clone);\n};\n\nmodule.exports = cloneResponse;\n", "//TODO: handle reviver/dehydrate function like normal\n//and handle indentation, like normal.\n//if anyone needs this... please send pull request.\n\nexports.stringify = function stringify (o) {\n if('undefined' == typeof o) return o\n\n if(o && Buffer.isBuffer(o))\n return JSON.stringify(':base64:' + o.toString('base64'))\n\n if(o && o.toJSON)\n o = o.toJSON()\n\n if(o && 'object' === typeof o) {\n var s = ''\n var array = Array.isArray(o)\n s = array ? '[' : '{'\n var first = true\n\n for(var k in o) {\n var ignore = 'function' == typeof o[k] || (!array && 'undefined' === typeof o[k])\n if(Object.hasOwnProperty.call(o, k) && !ignore) {\n if(!first)\n s += ','\n first = false\n if (array) {\n if(o[k] == undefined)\n s += 'null'\n else\n s += stringify(o[k])\n } else if (o[k] !== void(0)) {\n s += stringify(k) + ':' + stringify(o[k])\n }\n }\n }\n\n s += array ? ']' : '}'\n\n return s\n } else if ('string' === typeof o) {\n return JSON.stringify(/^:/.test(o) ? ':' + o : o)\n } else if ('undefined' === typeof o) {\n return 'null';\n } else\n return JSON.stringify(o)\n}\n\nexports.parse = function (s) {\n return JSON.parse(s, function (key, value) {\n if('string' === typeof value) {\n if(/^:base64:/.test(value))\n return Buffer.from(value.substring(8), 'base64')\n else\n return /^:/.test(value) ? value.substring(1) : value \n }\n return value\n })\n}\n", "'use strict';\n\nconst EventEmitter = require('events');\nconst JSONB = require('json-buffer');\n\nconst loadStore = opts => {\n\tconst adapters = {\n\t\tredis: '@keyv/redis',\n\t\tmongodb: '@keyv/mongo',\n\t\tmongo: '@keyv/mongo',\n\t\tsqlite: '@keyv/sqlite',\n\t\tpostgresql: '@keyv/postgres',\n\t\tpostgres: '@keyv/postgres',\n\t\tmysql: '@keyv/mysql'\n\t};\n\tif (opts.adapter || opts.uri) {\n\t\tconst adapter = opts.adapter || /^[^:]*/.exec(opts.uri)[0];\n\t\treturn new (require(adapters[adapter]))(opts);\n\t}\n\n\treturn new Map();\n};\n\nclass Keyv extends EventEmitter {\n\tconstructor(uri, opts) {\n\t\tsuper();\n\t\tthis.opts = Object.assign(\n\t\t\t{\n\t\t\t\tnamespace: 'keyv',\n\t\t\t\tserialize: JSONB.stringify,\n\t\t\t\tdeserialize: JSONB.parse\n\t\t\t},\n\t\t\t(typeof uri === 'string') ? { uri } : uri,\n\t\t\topts\n\t\t);\n\n\t\tif (!this.opts.store) {\n\t\t\tconst adapterOpts = Object.assign({}, this.opts);\n\t\t\tthis.opts.store = loadStore(adapterOpts);\n\t\t}\n\n\t\tif (typeof this.opts.store.on === 'function') {\n\t\t\tthis.opts.store.on('error', err => this.emit('error', err));\n\t\t}\n\n\t\tthis.opts.store.namespace = this.opts.namespace;\n\t}\n\n\t_getKeyPrefix(key) {\n\t\treturn `${this.opts.namespace}:${key}`;\n\t}\n\n\tget(key, opts) {\n\t\tconst keyPrefixed = this._getKeyPrefix(key);\n\t\tconst { store } = this.opts;\n\t\treturn Promise.resolve()\n\t\t\t.then(() => store.get(keyPrefixed))\n\t\t\t.then(data => {\n\t\t\t\treturn (typeof data === 'string') ? this.opts.deserialize(data) : data;\n\t\t\t})\n\t\t\t.then(data => {\n\t\t\t\tif (data === undefined) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\tif (typeof data.expires === 'number' && Date.now() > data.expires) {\n\t\t\t\t\tthis.delete(key);\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\treturn (opts && opts.raw) ? data : data.value;\n\t\t\t});\n\t}\n\n\tset(key, value, ttl) {\n\t\tconst keyPrefixed = this._getKeyPrefix(key);\n\t\tif (typeof ttl === 'undefined') {\n\t\t\tttl = this.opts.ttl;\n\t\t}\n\n\t\tif (ttl === 0) {\n\t\t\tttl = undefined;\n\t\t}\n\n\t\tconst { store } = this.opts;\n\n\t\treturn Promise.resolve()\n\t\t\t.then(() => {\n\t\t\t\tconst expires = (typeof ttl === 'number') ? (Date.now() + ttl) : null;\n\t\t\t\tvalue = { value, expires };\n\t\t\t\treturn this.opts.serialize(value);\n\t\t\t})\n\t\t\t.then(value => store.set(keyPrefixed, value, ttl))\n\t\t\t.then(() => true);\n\t}\n\n\tdelete(key) {\n\t\tconst keyPrefixed = this._getKeyPrefix(key);\n\t\tconst { store } = this.opts;\n\t\treturn Promise.resolve()\n\t\t\t.then(() => store.delete(keyPrefixed));\n\t}\n\n\tclear() {\n\t\tconst { store } = this.opts;\n\t\treturn Promise.resolve()\n\t\t\t.then(() => store.clear());\n\t}\n}\n\nmodule.exports = Keyv;\n", "'use strict';\n\nconst EventEmitter = require('events');\nconst urlLib = require('url');\nconst normalizeUrl = require('normalize-url');\nconst getStream = require('get-stream');\nconst CachePolicy = require('http-cache-semantics');\nconst Response = require('responselike');\nconst lowercaseKeys = require('lowercase-keys');\nconst cloneResponse = require('clone-response');\nconst Keyv = require('keyv');\n\nclass CacheableRequest {\n\tconstructor(request, cacheAdapter) {\n\t\tif (typeof request !== 'function') {\n\t\t\tthrow new TypeError('Parameter `request` must be a function');\n\t\t}\n\n\t\tthis.cache = new Keyv({\n\t\t\turi: typeof cacheAdapter === 'string' && cacheAdapter,\n\t\t\tstore: typeof cacheAdapter !== 'string' && cacheAdapter,\n\t\t\tnamespace: 'cacheable-request'\n\t\t});\n\n\t\treturn this.createCacheableRequest(request);\n\t}\n\n\tcreateCacheableRequest(request) {\n\t\treturn (opts, cb) => {\n\t\t\tlet url;\n\t\t\tif (typeof opts === 'string') {\n\t\t\t\turl = normalizeUrlObject(urlLib.parse(opts));\n\t\t\t\topts = {};\n\t\t\t} else if (opts instanceof urlLib.URL) {\n\t\t\t\turl = normalizeUrlObject(urlLib.parse(opts.toString()));\n\t\t\t\topts = {};\n\t\t\t} else {\n\t\t\t\tconst [pathname, ...searchParts] = (opts.path || '').split('?');\n\t\t\t\tconst search = searchParts.length > 0 ?\n\t\t\t\t\t`?${searchParts.join('?')}` :\n\t\t\t\t\t'';\n\t\t\t\turl = normalizeUrlObject({ ...opts, pathname, search });\n\t\t\t}\n\n\t\t\topts = {\n\t\t\t\theaders: {},\n\t\t\t\tmethod: 'GET',\n\t\t\t\tcache: true,\n\t\t\t\tstrictTtl: false,\n\t\t\t\tautomaticFailover: false,\n\t\t\t\t...opts,\n\t\t\t\t...urlObjectToRequestOptions(url)\n\t\t\t};\n\t\t\topts.headers = lowercaseKeys(opts.headers);\n\n\t\t\tconst ee = new EventEmitter();\n\t\t\tconst normalizedUrlString = normalizeUrl(\n\t\t\t\turlLib.format(url),\n\t\t\t\t{\n\t\t\t\t\tstripWWW: false,\n\t\t\t\t\tremoveTrailingSlash: false,\n\t\t\t\t\tstripAuthentication: false\n\t\t\t\t}\n\t\t\t);\n\t\t\tconst key = `${opts.method}:${normalizedUrlString}`;\n\t\t\tlet revalidate = false;\n\t\t\tlet madeRequest = false;\n\n\t\t\tconst makeRequest = opts => {\n\t\t\t\tmadeRequest = true;\n\t\t\t\tlet requestErrored = false;\n\t\t\t\tlet requestErrorCallback;\n\n\t\t\t\tconst requestErrorPromise = new Promise(resolve => {\n\t\t\t\t\trequestErrorCallback = () => {\n\t\t\t\t\t\tif (!requestErrored) {\n\t\t\t\t\t\t\trequestErrored = true;\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t});\n\n\t\t\t\tconst handler = response => {\n\t\t\t\t\tif (revalidate && !opts.forceRefresh) {\n\t\t\t\t\t\tresponse.status = response.statusCode;\n\t\t\t\t\t\tconst revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(opts, response);\n\t\t\t\t\t\tif (!revalidatedPolicy.modified) {\n\t\t\t\t\t\t\tconst headers = revalidatedPolicy.policy.responseHeaders();\n\t\t\t\t\t\t\tresponse = new Response(revalidate.statusCode, headers, revalidate.body, revalidate.url);\n\t\t\t\t\t\t\tresponse.cachePolicy = revalidatedPolicy.policy;\n\t\t\t\t\t\t\tresponse.fromCache = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!response.fromCache) {\n\t\t\t\t\t\tresponse.cachePolicy = new CachePolicy(opts, response, opts);\n\t\t\t\t\t\tresponse.fromCache = false;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet clonedResponse;\n\t\t\t\t\tif (opts.cache && response.cachePolicy.storable()) {\n\t\t\t\t\t\tclonedResponse = cloneResponse(response);\n\n\t\t\t\t\t\t(async () => {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst bodyPromise = getStream.buffer(response);\n\n\t\t\t\t\t\t\t\tawait Promise.race([\n\t\t\t\t\t\t\t\t\trequestErrorPromise,\n\t\t\t\t\t\t\t\t\tnew Promise(resolve => response.once('end', resolve))\n\t\t\t\t\t\t\t\t]);\n\n\t\t\t\t\t\t\t\tif (requestErrored) {\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tconst body = await bodyPromise;\n\n\t\t\t\t\t\t\t\tconst value = {\n\t\t\t\t\t\t\t\t\tcachePolicy: response.cachePolicy.toObject(),\n\t\t\t\t\t\t\t\t\turl: response.url,\n\t\t\t\t\t\t\t\t\tstatusCode: response.fromCache ? revalidate.statusCode : response.statusCode,\n\t\t\t\t\t\t\t\t\tbody\n\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\tlet ttl = opts.strictTtl ? response.cachePolicy.timeToLive() : undefined;\n\t\t\t\t\t\t\t\tif (opts.maxTtl) {\n\t\t\t\t\t\t\t\t\tttl = ttl ? Math.min(ttl, opts.maxTtl) : opts.maxTtl;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tawait this.cache.set(key, value, ttl);\n\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\tee.emit('error', new CacheableRequest.CacheError(error));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})();\n\t\t\t\t\t} else if (opts.cache && revalidate) {\n\t\t\t\t\t\t(async () => {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tawait this.cache.delete(key);\n\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\tee.emit('error', new CacheableRequest.CacheError(error));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})();\n\t\t\t\t\t}\n\n\t\t\t\t\tee.emit('response', clonedResponse || response);\n\t\t\t\t\tif (typeof cb === 'function') {\n\t\t\t\t\t\tcb(clonedResponse || response);\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\ttry {\n\t\t\t\t\tconst req = request(opts, handler);\n\t\t\t\t\treq.once('error', requestErrorCallback);\n\t\t\t\t\treq.once('abort', requestErrorCallback);\n\t\t\t\t\tee.emit('request', req);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tee.emit('error', new CacheableRequest.RequestError(error));\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t(async () => {\n\t\t\t\tconst get = async opts => {\n\t\t\t\t\tawait Promise.resolve();\n\n\t\t\t\t\tconst cacheEntry = opts.cache ? await this.cache.get(key) : undefined;\n\t\t\t\t\tif (typeof cacheEntry === 'undefined') {\n\t\t\t\t\t\treturn makeRequest(opts);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst policy = CachePolicy.fromObject(cacheEntry.cachePolicy);\n\t\t\t\t\tif (policy.satisfiesWithoutRevalidation(opts) && !opts.forceRefresh) {\n\t\t\t\t\t\tconst headers = policy.responseHeaders();\n\t\t\t\t\t\tconst response = new Response(cacheEntry.statusCode, headers, cacheEntry.body, cacheEntry.url);\n\t\t\t\t\t\tresponse.cachePolicy = policy;\n\t\t\t\t\t\tresponse.fromCache = true;\n\n\t\t\t\t\t\tee.emit('response', response);\n\t\t\t\t\t\tif (typeof cb === 'function') {\n\t\t\t\t\t\t\tcb(response);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\trevalidate = cacheEntry;\n\t\t\t\t\t\topts.headers = policy.revalidationHeaders(opts);\n\t\t\t\t\t\tmakeRequest(opts);\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tconst errorHandler = error => ee.emit('error', new CacheableRequest.CacheError(error));\n\t\t\t\tthis.cache.once('error', errorHandler);\n\t\t\t\tee.on('response', () => this.cache.removeListener('error', errorHandler));\n\n\t\t\t\ttry {\n\t\t\t\t\tawait get(opts);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (opts.automaticFailover && !madeRequest) {\n\t\t\t\t\t\tmakeRequest(opts);\n\t\t\t\t\t}\n\n\t\t\t\t\tee.emit('error', new CacheableRequest.CacheError(error));\n\t\t\t\t}\n\t\t\t})();\n\n\t\t\treturn ee;\n\t\t};\n\t}\n}\n\nfunction urlObjectToRequestOptions(url) {\n\tconst options = { ...url };\n\toptions.path = `${url.pathname || '/'}${url.search || ''}`;\n\tdelete options.pathname;\n\tdelete options.search;\n\treturn options;\n}\n\nfunction normalizeUrlObject(url) {\n\t// If url was parsed by url.parse or new URL:\n\t// - hostname will be set\n\t// - host will be hostname[:port]\n\t// - port will be set if it was explicit in the parsed string\n\t// Otherwise, url was from request options:\n\t// - hostname or host may be set\n\t// - host shall not have port encoded\n\treturn {\n\t\tprotocol: url.protocol,\n\t\tauth: url.auth,\n\t\thostname: url.hostname || url.host || 'localhost',\n\t\tport: url.port,\n\t\tpathname: url.pathname,\n\t\tsearch: url.search\n\t};\n}\n\nCacheableRequest.RequestError = class extends Error {\n\tconstructor(error) {\n\t\tsuper(error.message);\n\t\tthis.name = 'RequestError';\n\t\tObject.assign(this, error);\n\t}\n};\n\nCacheableRequest.CacheError = class extends Error {\n\tconstructor(error) {\n\t\tsuper(error.message);\n\t\tthis.name = 'CacheError';\n\t\tObject.assign(this, error);\n\t}\n};\n\nmodule.exports = CacheableRequest;\n", "'use strict';\n\n// We define these manually to ensure they're always copied\n// even if they would move up the prototype chain\n// https://nodejs.org/api/http.html#http_class_http_incomingmessage\nconst knownProperties = [\n\t'aborted',\n\t'complete',\n\t'headers',\n\t'httpVersion',\n\t'httpVersionMinor',\n\t'httpVersionMajor',\n\t'method',\n\t'rawHeaders',\n\t'rawTrailers',\n\t'setTimeout',\n\t'socket',\n\t'statusCode',\n\t'statusMessage',\n\t'trailers',\n\t'url'\n];\n\nmodule.exports = (fromStream, toStream) => {\n\tif (toStream._readableState.autoDestroy) {\n\t\tthrow new Error('The second stream must have the `autoDestroy` option set to `false`');\n\t}\n\n\tconst fromProperties = new Set(Object.keys(fromStream).concat(knownProperties));\n\n\tconst properties = {};\n\n\tfor (const property of fromProperties) {\n\t\t// Don't overwrite existing properties.\n\t\tif (property in toStream) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tproperties[property] = {\n\t\t\tget() {\n\t\t\t\tconst value = fromStream[property];\n\t\t\t\tconst isFunction = typeof value === 'function';\n\n\t\t\t\treturn isFunction ? value.bind(fromStream) : value;\n\t\t\t},\n\t\t\tset(value) {\n\t\t\t\tfromStream[property] = value;\n\t\t\t},\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false\n\t\t};\n\t}\n\n\tObject.defineProperties(toStream, properties);\n\n\tfromStream.once('aborted', () => {\n\t\ttoStream.destroy();\n\n\t\ttoStream.emit('aborted');\n\t});\n\n\tfromStream.once('close', () => {\n\t\tif (fromStream.complete) {\n\t\t\tif (toStream.readable) {\n\t\t\t\ttoStream.once('end', () => {\n\t\t\t\t\ttoStream.emit('close');\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ttoStream.emit('close');\n\t\t\t}\n\t\t} else {\n\t\t\ttoStream.emit('close');\n\t\t}\n\t});\n\n\treturn toStream;\n};\n", "'use strict';\nconst {Transform, PassThrough} = require('stream');\nconst zlib = require('zlib');\nconst mimicResponse = require('mimic-response');\n\nmodule.exports = response => {\n\tconst contentEncoding = (response.headers['content-encoding'] || '').toLowerCase();\n\n\tif (!['gzip', 'deflate', 'br'].includes(contentEncoding)) {\n\t\treturn response;\n\t}\n\n\t// TODO: Remove this when targeting Node.js 12.\n\tconst isBrotli = contentEncoding === 'br';\n\tif (isBrotli && typeof zlib.createBrotliDecompress !== 'function') {\n\t\tresponse.destroy(new Error('Brotli is not supported on Node.js < 12'));\n\t\treturn response;\n\t}\n\n\tlet isEmpty = true;\n\n\tconst checker = new Transform({\n\t\ttransform(data, _encoding, callback) {\n\t\t\tisEmpty = false;\n\n\t\t\tcallback(null, data);\n\t\t},\n\n\t\tflush(callback) {\n\t\t\tcallback();\n\t\t}\n\t});\n\n\tconst finalStream = new PassThrough({\n\t\tautoDestroy: false,\n\t\tdestroy(error, callback) {\n\t\t\tresponse.destroy();\n\n\t\t\tcallback(error);\n\t\t}\n\t});\n\n\tconst decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip();\n\n\tdecompressStream.once('error', error => {\n\t\tif (isEmpty && !response.readable) {\n\t\t\tfinalStream.end();\n\t\t\treturn;\n\t\t}\n\n\t\tfinalStream.destroy(error);\n\t});\n\n\tmimicResponse(response, finalStream);\n\tresponse.pipe(checker).pipe(decompressStream).pipe(finalStream);\n\n\treturn finalStream;\n};\n", "'use strict';\n\nclass QuickLRU {\n\tconstructor(options = {}) {\n\t\tif (!(options.maxSize && options.maxSize > 0)) {\n\t\t\tthrow new TypeError('`maxSize` must be a number greater than 0');\n\t\t}\n\n\t\tthis.maxSize = options.maxSize;\n\t\tthis.onEviction = options.onEviction;\n\t\tthis.cache = new Map();\n\t\tthis.oldCache = new Map();\n\t\tthis._size = 0;\n\t}\n\n\t_set(key, value) {\n\t\tthis.cache.set(key, value);\n\t\tthis._size++;\n\n\t\tif (this._size >= this.maxSize) {\n\t\t\tthis._size = 0;\n\n\t\t\tif (typeof this.onEviction === 'function') {\n\t\t\t\tfor (const [key, value] of this.oldCache.entries()) {\n\t\t\t\t\tthis.onEviction(key, value);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.oldCache = this.cache;\n\t\t\tthis.cache = new Map();\n\t\t}\n\t}\n\n\tget(key) {\n\t\tif (this.cache.has(key)) {\n\t\t\treturn this.cache.get(key);\n\t\t}\n\n\t\tif (this.oldCache.has(key)) {\n\t\t\tconst value = this.oldCache.get(key);\n\t\t\tthis.oldCache.delete(key);\n\t\t\tthis._set(key, value);\n\t\t\treturn value;\n\t\t}\n\t}\n\n\tset(key, value) {\n\t\tif (this.cache.has(key)) {\n\t\t\tthis.cache.set(key, value);\n\t\t} else {\n\t\t\tthis._set(key, value);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\thas(key) {\n\t\treturn this.cache.has(key) || this.oldCache.has(key);\n\t}\n\n\tpeek(key) {\n\t\tif (this.cache.has(key)) {\n\t\t\treturn this.cache.get(key);\n\t\t}\n\n\t\tif (this.oldCache.has(key)) {\n\t\t\treturn this.oldCache.get(key);\n\t\t}\n\t}\n\n\tdelete(key) {\n\t\tconst deleted = this.cache.delete(key);\n\t\tif (deleted) {\n\t\t\tthis._size--;\n\t\t}\n\n\t\treturn this.oldCache.delete(key) || deleted;\n\t}\n\n\tclear() {\n\t\tthis.cache.clear();\n\t\tthis.oldCache.clear();\n\t\tthis._size = 0;\n\t}\n\n\t* keys() {\n\t\tfor (const [key] of this) {\n\t\t\tyield key;\n\t\t}\n\t}\n\n\t* values() {\n\t\tfor (const [, value] of this) {\n\t\t\tyield value;\n\t\t}\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tfor (const item of this.cache) {\n\t\t\tyield item;\n\t\t}\n\n\t\tfor (const item of this.oldCache) {\n\t\t\tconst [key] = item;\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\tyield item;\n\t\t\t}\n\t\t}\n\t}\n\n\tget size() {\n\t\tlet oldCacheSize = 0;\n\t\tfor (const key of this.oldCache.keys()) {\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\toldCacheSize++;\n\t\t\t}\n\t\t}\n\n\t\treturn Math.min(this._size + oldCacheSize, this.maxSize);\n\t}\n}\n\nmodule.exports = QuickLRU;\n", "'use strict';\nconst EventEmitter = require('events');\nconst tls = require('tls');\nconst http2 = require('http2');\nconst QuickLRU = require('quick-lru');\n\nconst kCurrentStreamsCount = Symbol('currentStreamsCount');\nconst kRequest = Symbol('request');\nconst kOriginSet = Symbol('cachedOriginSet');\nconst kGracefullyClosing = Symbol('gracefullyClosing');\n\nconst nameKeys = [\n\t// `http2.connect()` options\n\t'maxDeflateDynamicTableSize',\n\t'maxSessionMemory',\n\t'maxHeaderListPairs',\n\t'maxOutstandingPings',\n\t'maxReservedRemoteStreams',\n\t'maxSendHeaderBlockLength',\n\t'paddingStrategy',\n\n\t// `tls.connect()` options\n\t'localAddress',\n\t'path',\n\t'rejectUnauthorized',\n\t'minDHSize',\n\n\t// `tls.createSecureContext()` options\n\t'ca',\n\t'cert',\n\t'clientCertEngine',\n\t'ciphers',\n\t'key',\n\t'pfx',\n\t'servername',\n\t'minVersion',\n\t'maxVersion',\n\t'secureProtocol',\n\t'crl',\n\t'honorCipherOrder',\n\t'ecdhCurve',\n\t'dhparam',\n\t'secureOptions',\n\t'sessionIdContext'\n];\n\nconst getSortedIndex = (array, value, compare) => {\n\tlet low = 0;\n\tlet high = array.length;\n\n\twhile (low < high) {\n\t\tconst mid = (low + high) >>> 1;\n\n\t\t/* istanbul ignore next */\n\t\tif (compare(array[mid], value)) {\n\t\t\t// This never gets called because we use descending sort. Better to have this anyway.\n\t\t\tlow = mid + 1;\n\t\t} else {\n\t\t\thigh = mid;\n\t\t}\n\t}\n\n\treturn low;\n};\n\nconst compareSessions = (a, b) => {\n\treturn a.remoteSettings.maxConcurrentStreams > b.remoteSettings.maxConcurrentStreams;\n};\n\n// See https://tools.ietf.org/html/rfc8336\nconst closeCoveredSessions = (where, session) => {\n\t// Clients SHOULD NOT emit new requests on any connection whose Origin\n\t// Set is a proper subset of another connection's Origin Set, and they\n\t// SHOULD close it once all outstanding requests are satisfied.\n\tfor (const coveredSession of where) {\n\t\tif (\n\t\t\t// The set is a proper subset when its length is less than the other set.\n\t\t\tcoveredSession[kOriginSet].length < session[kOriginSet].length &&\n\n\t\t\t// And the other set includes all elements of the subset.\n\t\t\tcoveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) &&\n\n\t\t\t// Makes sure that the session can handle all requests from the covered session.\n\t\t\tcoveredSession[kCurrentStreamsCount] + session[kCurrentStreamsCount] <= session.remoteSettings.maxConcurrentStreams\n\t\t) {\n\t\t\t// This allows pending requests to finish and prevents making new requests.\n\t\t\tgracefullyClose(coveredSession);\n\t\t}\n\t}\n};\n\n// This is basically inverted `closeCoveredSessions(...)`.\nconst closeSessionIfCovered = (where, coveredSession) => {\n\tfor (const session of where) {\n\t\tif (\n\t\t\tcoveredSession[kOriginSet].length < session[kOriginSet].length &&\n\t\t\tcoveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) &&\n\t\t\tcoveredSession[kCurrentStreamsCount] + session[kCurrentStreamsCount] <= session.remoteSettings.maxConcurrentStreams\n\t\t) {\n\t\t\tgracefullyClose(coveredSession);\n\t\t}\n\t}\n};\n\nconst getSessions = ({agent, isFree}) => {\n\tconst result = {};\n\n\t// eslint-disable-next-line guard-for-in\n\tfor (const normalizedOptions in agent.sessions) {\n\t\tconst sessions = agent.sessions[normalizedOptions];\n\n\t\tconst filtered = sessions.filter(session => {\n\t\t\tconst result = session[Agent.kCurrentStreamsCount] < session.remoteSettings.maxConcurrentStreams;\n\n\t\t\treturn isFree ? result : !result;\n\t\t});\n\n\t\tif (filtered.length !== 0) {\n\t\t\tresult[normalizedOptions] = filtered;\n\t\t}\n\t}\n\n\treturn result;\n};\n\nconst gracefullyClose = session => {\n\tsession[kGracefullyClosing] = true;\n\n\tif (session[kCurrentStreamsCount] === 0) {\n\t\tsession.close();\n\t}\n};\n\nclass Agent extends EventEmitter {\n\tconstructor({timeout = 60000, maxSessions = Infinity, maxFreeSessions = 10, maxCachedTlsSessions = 100} = {}) {\n\t\tsuper();\n\n\t\t// A session is considered busy when its current streams count\n\t\t// is equal to or greater than the `maxConcurrentStreams` value.\n\n\t\t// A session is considered free when its current streams count\n\t\t// is less than the `maxConcurrentStreams` value.\n\n\t\t// SESSIONS[NORMALIZED_OPTIONS] = [];\n\t\tthis.sessions = {};\n\n\t\t// The queue for creating new sessions. It looks like this:\n\t\t// QUEUE[NORMALIZED_OPTIONS][NORMALIZED_ORIGIN] = ENTRY_FUNCTION\n\t\t//\n\t\t// The entry function has `listeners`, `completed` and `destroyed` properties.\n\t\t// `listeners` is an array of objects containing `resolve` and `reject` functions.\n\t\t// `completed` is a boolean. It's set to true after ENTRY_FUNCTION is executed.\n\t\t// `destroyed` is a boolean. If it's set to true, the session will be destroyed if hasn't connected yet.\n\t\tthis.queue = {};\n\n\t\t// Each session will use this timeout value.\n\t\tthis.timeout = timeout;\n\n\t\t// Max sessions in total\n\t\tthis.maxSessions = maxSessions;\n\n\t\t// Max free sessions in total\n\t\t// TODO: decreasing `maxFreeSessions` should close some sessions\n\t\tthis.maxFreeSessions = maxFreeSessions;\n\n\t\tthis._freeSessionsCount = 0;\n\t\tthis._sessionsCount = 0;\n\n\t\t// We don't support push streams by default.\n\t\tthis.settings = {\n\t\t\tenablePush: false\n\t\t};\n\n\t\t// Reusing TLS sessions increases performance.\n\t\tthis.tlsSessionCache = new QuickLRU({maxSize: maxCachedTlsSessions});\n\t}\n\n\tstatic normalizeOrigin(url, servername) {\n\t\tif (typeof url === 'string') {\n\t\t\turl = new URL(url);\n\t\t}\n\n\t\tif (servername && url.hostname !== servername) {\n\t\t\turl.hostname = servername;\n\t\t}\n\n\t\treturn url.origin;\n\t}\n\n\tnormalizeOptions(options) {\n\t\tlet normalized = '';\n\n\t\tif (options) {\n\t\t\tfor (const key of nameKeys) {\n\t\t\t\tif (options[key]) {\n\t\t\t\t\tnormalized += `:${options[key]}`;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn normalized;\n\t}\n\n\t_tryToCreateNewSession(normalizedOptions, normalizedOrigin) {\n\t\tif (!(normalizedOptions in this.queue) || !(normalizedOrigin in this.queue[normalizedOptions])) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst item = this.queue[normalizedOptions][normalizedOrigin];\n\n\t\t// The entry function can be run only once.\n\t\t// BUG: The session may be never created when:\n\t\t// - the first condition is false AND\n\t\t// - this function is never called with the same arguments in the future.\n\t\tif (this._sessionsCount < this.maxSessions && !item.completed) {\n\t\t\titem.completed = true;\n\n\t\t\titem();\n\t\t}\n\t}\n\n\tgetSession(origin, options, listeners) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (Array.isArray(listeners)) {\n\t\t\t\tlisteners = [...listeners];\n\n\t\t\t\t// Resolve the current promise ASAP, we're just moving the listeners.\n\t\t\t\t// They will be executed at a different time.\n\t\t\t\tresolve();\n\t\t\t} else {\n\t\t\t\tlisteners = [{resolve, reject}];\n\t\t\t}\n\n\t\t\tconst normalizedOptions = this.normalizeOptions(options);\n\t\t\tconst normalizedOrigin = Agent.normalizeOrigin(origin, options && options.servername);\n\n\t\t\tif (normalizedOrigin === undefined) {\n\t\t\t\tfor (const {reject} of listeners) {\n\t\t\t\t\treject(new TypeError('The `origin` argument needs to be a string or an URL object'));\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (normalizedOptions in this.sessions) {\n\t\t\t\tconst sessions = this.sessions[normalizedOptions];\n\n\t\t\t\tlet maxConcurrentStreams = -1;\n\t\t\t\tlet currentStreamsCount = -1;\n\t\t\t\tlet optimalSession;\n\n\t\t\t\t// We could just do this.sessions[normalizedOptions].find(...) but that isn't optimal.\n\t\t\t\t// Additionally, we are looking for session which has biggest current pending streams count.\n\t\t\t\tfor (const session of sessions) {\n\t\t\t\t\tconst sessionMaxConcurrentStreams = session.remoteSettings.maxConcurrentStreams;\n\n\t\t\t\t\tif (sessionMaxConcurrentStreams < maxConcurrentStreams) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (session[kOriginSet].includes(normalizedOrigin)) {\n\t\t\t\t\t\tconst sessionCurrentStreamsCount = session[kCurrentStreamsCount];\n\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tsessionCurrentStreamsCount >= sessionMaxConcurrentStreams ||\n\t\t\t\t\t\t\tsession[kGracefullyClosing] ||\n\t\t\t\t\t\t\t// Unfortunately the `close` event isn't called immediately,\n\t\t\t\t\t\t\t// so `session.destroyed` is `true`, but `session.closed` is `false`.\n\t\t\t\t\t\t\tsession.destroyed\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// We only need set this once.\n\t\t\t\t\t\tif (!optimalSession) {\n\t\t\t\t\t\t\tmaxConcurrentStreams = sessionMaxConcurrentStreams;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// We're looking for the session which has biggest current pending stream count,\n\t\t\t\t\t\t// in order to minimalize the amount of active sessions.\n\t\t\t\t\t\tif (sessionCurrentStreamsCount > currentStreamsCount) {\n\t\t\t\t\t\t\toptimalSession = session;\n\t\t\t\t\t\t\tcurrentStreamsCount = sessionCurrentStreamsCount;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (optimalSession) {\n\t\t\t\t\t/* istanbul ignore next: safety check */\n\t\t\t\t\tif (listeners.length !== 1) {\n\t\t\t\t\t\tfor (const {reject} of listeners) {\n\t\t\t\t\t\t\tconst error = new Error(\n\t\t\t\t\t\t\t\t`Expected the length of listeners to be 1, got ${listeners.length}.\\n` +\n\t\t\t\t\t\t\t\t'Please report this to https://github.com/szmarczak/http2-wrapper/'\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tlisteners[0].resolve(optimalSession);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (normalizedOptions in this.queue) {\n\t\t\t\tif (normalizedOrigin in this.queue[normalizedOptions]) {\n\t\t\t\t\t// There's already an item in the queue, just attach ourselves to it.\n\t\t\t\t\tthis.queue[normalizedOptions][normalizedOrigin].listeners.push(...listeners);\n\n\t\t\t\t\t// This shouldn't be executed here.\n\t\t\t\t\t// See the comment inside _tryToCreateNewSession.\n\t\t\t\t\tthis._tryToCreateNewSession(normalizedOptions, normalizedOrigin);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis.queue[normalizedOptions] = {};\n\t\t\t}\n\n\t\t\t// The entry must be removed from the queue IMMEDIATELY when:\n\t\t\t// 1. the session connects successfully,\n\t\t\t// 2. an error occurs.\n\t\t\tconst removeFromQueue = () => {\n\t\t\t\t// Our entry can be replaced. We cannot remove the new one.\n\t\t\t\tif (normalizedOptions in this.queue && this.queue[normalizedOptions][normalizedOrigin] === entry) {\n\t\t\t\t\tdelete this.queue[normalizedOptions][normalizedOrigin];\n\n\t\t\t\t\tif (Object.keys(this.queue[normalizedOptions]).length === 0) {\n\t\t\t\t\t\tdelete this.queue[normalizedOptions];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t// The main logic is here\n\t\t\tconst entry = () => {\n\t\t\t\tconst name = `${normalizedOrigin}:${normalizedOptions}`;\n\t\t\t\tlet receivedSettings = false;\n\n\t\t\t\ttry {\n\t\t\t\t\tconst session = http2.connect(origin, {\n\t\t\t\t\t\tcreateConnection: this.createConnection,\n\t\t\t\t\t\tsettings: this.settings,\n\t\t\t\t\t\tsession: this.tlsSessionCache.get(name),\n\t\t\t\t\t\t...options\n\t\t\t\t\t});\n\t\t\t\t\tsession[kCurrentStreamsCount] = 0;\n\t\t\t\t\tsession[kGracefullyClosing] = false;\n\n\t\t\t\t\tconst isFree = () => session[kCurrentStreamsCount] < session.remoteSettings.maxConcurrentStreams;\n\t\t\t\t\tlet wasFree = true;\n\n\t\t\t\t\tsession.socket.once('session', tlsSession => {\n\t\t\t\t\t\tthis.tlsSessionCache.set(name, tlsSession);\n\t\t\t\t\t});\n\n\t\t\t\t\tsession.once('error', error => {\n\t\t\t\t\t\t// Listeners are empty when the session successfully connected.\n\t\t\t\t\t\tfor (const {reject} of listeners) {\n\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// The connection got broken, purge the cache.\n\t\t\t\t\t\tthis.tlsSessionCache.delete(name);\n\t\t\t\t\t});\n\n\t\t\t\t\tsession.setTimeout(this.timeout, () => {\n\t\t\t\t\t\t// Terminates all streams owned by this session.\n\t\t\t\t\t\t// TODO: Maybe the streams should have a \"Session timed out\" error?\n\t\t\t\t\t\tsession.destroy();\n\t\t\t\t\t});\n\n\t\t\t\t\tsession.once('close', () => {\n\t\t\t\t\t\tif (receivedSettings) {\n\t\t\t\t\t\t\t// 1. If it wasn't free then no need to decrease because\n\t\t\t\t\t\t\t// it has been decreased already in session.request().\n\t\t\t\t\t\t\t// 2. `stream.once('close')` won't increment the count\n\t\t\t\t\t\t\t// because the session is already closed.\n\t\t\t\t\t\t\tif (wasFree) {\n\t\t\t\t\t\t\t\tthis._freeSessionsCount--;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tthis._sessionsCount--;\n\n\t\t\t\t\t\t\t// This cannot be moved to the stream logic,\n\t\t\t\t\t\t\t// because there may be a session that hadn't made a single request.\n\t\t\t\t\t\t\tconst where = this.sessions[normalizedOptions];\n\t\t\t\t\t\t\twhere.splice(where.indexOf(session), 1);\n\n\t\t\t\t\t\t\tif (where.length === 0) {\n\t\t\t\t\t\t\t\tdelete this.sessions[normalizedOptions];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Broken connection\n\t\t\t\t\t\t\tconst error = new Error('Session closed without receiving a SETTINGS frame');\n\t\t\t\t\t\t\terror.code = 'HTTP2WRAPPER_NOSETTINGS';\n\n\t\t\t\t\t\t\tfor (const {reject} of listeners) {\n\t\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tremoveFromQueue();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// There may be another session awaiting.\n\t\t\t\t\t\tthis._tryToCreateNewSession(normalizedOptions, normalizedOrigin);\n\t\t\t\t\t});\n\n\t\t\t\t\t// Iterates over the queue and processes listeners.\n\t\t\t\t\tconst processListeners = () => {\n\t\t\t\t\t\tif (!(normalizedOptions in this.queue) || !isFree()) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (const origin of session[kOriginSet]) {\n\t\t\t\t\t\t\tif (origin in this.queue[normalizedOptions]) {\n\t\t\t\t\t\t\t\tconst {listeners} = this.queue[normalizedOptions][origin];\n\n\t\t\t\t\t\t\t\t// Prevents session overloading.\n\t\t\t\t\t\t\t\twhile (listeners.length !== 0 && isFree()) {\n\t\t\t\t\t\t\t\t\t// We assume `resolve(...)` calls `request(...)` *directly*,\n\t\t\t\t\t\t\t\t\t// otherwise the session will get overloaded.\n\t\t\t\t\t\t\t\t\tlisteners.shift().resolve(session);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tconst where = this.queue[normalizedOptions];\n\t\t\t\t\t\t\t\tif (where[origin].listeners.length === 0) {\n\t\t\t\t\t\t\t\t\tdelete where[origin];\n\n\t\t\t\t\t\t\t\t\tif (Object.keys(where).length === 0) {\n\t\t\t\t\t\t\t\t\t\tdelete this.queue[normalizedOptions];\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t// We're no longer free, no point in continuing.\n\t\t\t\t\t\t\t\tif (!isFree()) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\t// The Origin Set cannot shrink. No need to check if it suddenly became covered by another one.\n\t\t\t\t\tsession.on('origin', () => {\n\t\t\t\t\t\tsession[kOriginSet] = session.originSet;\n\n\t\t\t\t\t\tif (!isFree()) {\n\t\t\t\t\t\t\t// The session is full.\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tprocessListeners();\n\n\t\t\t\t\t\t// Close covered sessions (if possible).\n\t\t\t\t\t\tcloseCoveredSessions(this.sessions[normalizedOptions], session);\n\t\t\t\t\t});\n\n\t\t\t\t\tsession.once('remoteSettings', () => {\n\t\t\t\t\t\t// Fix Node.js bug preventing the process from exiting\n\t\t\t\t\t\tsession.ref();\n\t\t\t\t\t\tsession.unref();\n\n\t\t\t\t\t\tthis._sessionsCount++;\n\n\t\t\t\t\t\t// The Agent could have been destroyed already.\n\t\t\t\t\t\tif (entry.destroyed) {\n\t\t\t\t\t\t\tconst error = new Error('Agent has been destroyed');\n\n\t\t\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\t\t\tlistener.reject(error);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tsession.destroy();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tsession[kOriginSet] = session.originSet;\n\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst where = this.sessions;\n\n\t\t\t\t\t\t\tif (normalizedOptions in where) {\n\t\t\t\t\t\t\t\tconst sessions = where[normalizedOptions];\n\t\t\t\t\t\t\t\tsessions.splice(getSortedIndex(sessions, session, compareSessions), 0, session);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\twhere[normalizedOptions] = [session];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis._freeSessionsCount += 1;\n\t\t\t\t\t\treceivedSettings = true;\n\n\t\t\t\t\t\tthis.emit('session', session);\n\n\t\t\t\t\t\tprocessListeners();\n\t\t\t\t\t\tremoveFromQueue();\n\n\t\t\t\t\t\t// TODO: Close last recently used (or least used?) session\n\t\t\t\t\t\tif (session[kCurrentStreamsCount] === 0 && this._freeSessionsCount > this.maxFreeSessions) {\n\t\t\t\t\t\t\tsession.close();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Check if we haven't managed to execute all listeners.\n\t\t\t\t\t\tif (listeners.length !== 0) {\n\t\t\t\t\t\t\t// Request for a new session with predefined listeners.\n\t\t\t\t\t\t\tthis.getSession(normalizedOrigin, options, listeners);\n\t\t\t\t\t\t\tlisteners.length = 0;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// `session.remoteSettings.maxConcurrentStreams` might get increased\n\t\t\t\t\t\tsession.on('remoteSettings', () => {\n\t\t\t\t\t\t\tprocessListeners();\n\n\t\t\t\t\t\t\t// In case the Origin Set changes\n\t\t\t\t\t\t\tcloseCoveredSessions(this.sessions[normalizedOptions], session);\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\n\t\t\t\t\t// Shim `session.request()` in order to catch all streams\n\t\t\t\t\tsession[kRequest] = session.request;\n\t\t\t\t\tsession.request = (headers, streamOptions) => {\n\t\t\t\t\t\tif (session[kGracefullyClosing]) {\n\t\t\t\t\t\t\tthrow new Error('The session is gracefully closing. No new streams are allowed.');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst stream = session[kRequest](headers, streamOptions);\n\n\t\t\t\t\t\t// The process won't exit until the session is closed or all requests are gone.\n\t\t\t\t\t\tsession.ref();\n\n\t\t\t\t\t\t++session[kCurrentStreamsCount];\n\n\t\t\t\t\t\tif (session[kCurrentStreamsCount] === session.remoteSettings.maxConcurrentStreams) {\n\t\t\t\t\t\t\tthis._freeSessionsCount--;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tstream.once('close', () => {\n\t\t\t\t\t\t\twasFree = isFree();\n\n\t\t\t\t\t\t\t--session[kCurrentStreamsCount];\n\n\t\t\t\t\t\t\tif (!session.destroyed && !session.closed) {\n\t\t\t\t\t\t\t\tcloseSessionIfCovered(this.sessions[normalizedOptions], session);\n\n\t\t\t\t\t\t\t\tif (isFree() && !session.closed) {\n\t\t\t\t\t\t\t\t\tif (!wasFree) {\n\t\t\t\t\t\t\t\t\t\tthis._freeSessionsCount++;\n\n\t\t\t\t\t\t\t\t\t\twasFree = true;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tconst isEmpty = session[kCurrentStreamsCount] === 0;\n\n\t\t\t\t\t\t\t\t\tif (isEmpty) {\n\t\t\t\t\t\t\t\t\t\tsession.unref();\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\tisEmpty &&\n\t\t\t\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t\t\t\tthis._freeSessionsCount > this.maxFreeSessions ||\n\t\t\t\t\t\t\t\t\t\t\tsession[kGracefullyClosing]\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\tsession.close();\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tcloseCoveredSessions(this.sessions[normalizedOptions], session);\n\t\t\t\t\t\t\t\t\t\tprocessListeners();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\treturn stream;\n\t\t\t\t\t};\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\tlistener.reject(error);\n\t\t\t\t\t}\n\n\t\t\t\t\tremoveFromQueue();\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tentry.listeners = listeners;\n\t\t\tentry.completed = false;\n\t\t\tentry.destroyed = false;\n\n\t\t\tthis.queue[normalizedOptions][normalizedOrigin] = entry;\n\t\t\tthis._tryToCreateNewSession(normalizedOptions, normalizedOrigin);\n\t\t});\n\t}\n\n\trequest(origin, options, headers, streamOptions) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.getSession(origin, options, [{\n\t\t\t\treject,\n\t\t\t\tresolve: session => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresolve(session.request(headers, streamOptions));\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}]);\n\t\t});\n\t}\n\n\tcreateConnection(origin, options) {\n\t\treturn Agent.connect(origin, options);\n\t}\n\n\tstatic connect(origin, options) {\n\t\toptions.ALPNProtocols = ['h2'];\n\n\t\tconst port = origin.port || 443;\n\t\tconst host = origin.hostname || origin.host;\n\n\t\tif (typeof options.servername === 'undefined') {\n\t\t\toptions.servername = host;\n\t\t}\n\n\t\treturn tls.connect(port, host, options);\n\t}\n\n\tcloseFreeSessions() {\n\t\tfor (const sessions of Object.values(this.sessions)) {\n\t\t\tfor (const session of sessions) {\n\t\t\t\tif (session[kCurrentStreamsCount] === 0) {\n\t\t\t\t\tsession.close();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdestroy(reason) {\n\t\tfor (const sessions of Object.values(this.sessions)) {\n\t\t\tfor (const session of sessions) {\n\t\t\t\tsession.destroy(reason);\n\t\t\t}\n\t\t}\n\n\t\tfor (const entriesOfAuthority of Object.values(this.queue)) {\n\t\t\tfor (const entry of Object.values(entriesOfAuthority)) {\n\t\t\t\tentry.destroyed = true;\n\t\t\t}\n\t\t}\n\n\t\t// New requests should NOT attach to destroyed sessions\n\t\tthis.queue = {};\n\t}\n\n\tget freeSessions() {\n\t\treturn getSessions({agent: this, isFree: true});\n\t}\n\n\tget busySessions() {\n\t\treturn getSessions({agent: this, isFree: false});\n\t}\n}\n\nAgent.kCurrentStreamsCount = kCurrentStreamsCount;\nAgent.kGracefullyClosing = kGracefullyClosing;\n\nmodule.exports = {\n\tAgent,\n\tglobalAgent: new Agent()\n};\n", "'use strict';\nconst {Readable} = require('stream');\n\nclass IncomingMessage extends Readable {\n\tconstructor(socket, highWaterMark) {\n\t\tsuper({\n\t\t\thighWaterMark,\n\t\t\tautoDestroy: false\n\t\t});\n\n\t\tthis.statusCode = null;\n\t\tthis.statusMessage = '';\n\t\tthis.httpVersion = '2.0';\n\t\tthis.httpVersionMajor = 2;\n\t\tthis.httpVersionMinor = 0;\n\t\tthis.headers = {};\n\t\tthis.trailers = {};\n\t\tthis.req = null;\n\n\t\tthis.aborted = false;\n\t\tthis.complete = false;\n\t\tthis.upgrade = null;\n\n\t\tthis.rawHeaders = [];\n\t\tthis.rawTrailers = [];\n\n\t\tthis.socket = socket;\n\t\tthis.connection = socket;\n\n\t\tthis._dumped = false;\n\t}\n\n\t_destroy(error) {\n\t\tthis.req._request.destroy(error);\n\t}\n\n\tsetTimeout(ms, callback) {\n\t\tthis.req.setTimeout(ms, callback);\n\t\treturn this;\n\t}\n\n\t_dump() {\n\t\tif (!this._dumped) {\n\t\t\tthis._dumped = true;\n\n\t\t\tthis.removeAllListeners('data');\n\t\t\tthis.resume();\n\t\t}\n\t}\n\n\t_read() {\n\t\tif (this.req) {\n\t\t\tthis.req._request.resume();\n\t\t}\n\t}\n}\n\nmodule.exports = IncomingMessage;\n", "'use strict';\n/* istanbul ignore file: https://github.com/nodejs/node/blob/a91293d4d9ab403046ab5eb022332e4e3d249bd3/lib/internal/url.js#L1257 */\n\nmodule.exports = url => {\n\tconst options = {\n\t\tprotocol: url.protocol,\n\t\thostname: typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname,\n\t\thost: url.host,\n\t\thash: url.hash,\n\t\tsearch: url.search,\n\t\tpathname: url.pathname,\n\t\thref: url.href,\n\t\tpath: `${url.pathname || ''}${url.search || ''}`\n\t};\n\n\tif (typeof url.port === 'string' && url.port.length !== 0) {\n\t\toptions.port = Number(url.port);\n\t}\n\n\tif (url.username || url.password) {\n\t\toptions.auth = `${url.username || ''}:${url.password || ''}`;\n\t}\n\n\treturn options;\n};\n", "'use strict';\n\nmodule.exports = (from, to, events) => {\n\tfor (const event of events) {\n\t\tfrom.on(event, (...args) => to.emit(event, ...args));\n\t}\n};\n", "'use strict';\n\nmodule.exports = header => {\n\tswitch (header) {\n\t\tcase ':method':\n\t\tcase ':scheme':\n\t\tcase ':authority':\n\t\tcase ':path':\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n};\n", "'use strict';\n/* istanbul ignore file: https://github.com/nodejs/node/blob/master/lib/internal/errors.js */\n\nconst makeError = (Base, key, getMessage) => {\n\tmodule.exports[key] = class NodeError extends Base {\n\t\tconstructor(...args) {\n\t\t\tsuper(typeof getMessage === 'string' ? getMessage : getMessage(args));\n\t\t\tthis.name = `${super.name} [${key}]`;\n\t\t\tthis.code = key;\n\t\t}\n\t};\n};\n\nmakeError(TypeError, 'ERR_INVALID_ARG_TYPE', args => {\n\tconst type = args[0].includes('.') ? 'property' : 'argument';\n\n\tlet valid = args[1];\n\tconst isManyTypes = Array.isArray(valid);\n\n\tif (isManyTypes) {\n\t\tvalid = `${valid.slice(0, -1).join(', ')} or ${valid.slice(-1)}`;\n\t}\n\n\treturn `The \"${args[0]}\" ${type} must be ${isManyTypes ? 'one of' : 'of'} type ${valid}. Received ${typeof args[2]}`;\n});\n\nmakeError(TypeError, 'ERR_INVALID_PROTOCOL', args => {\n\treturn `Protocol \"${args[0]}\" not supported. Expected \"${args[1]}\"`;\n});\n\nmakeError(Error, 'ERR_HTTP_HEADERS_SENT', args => {\n\treturn `Cannot ${args[0]} headers after they are sent to the client`;\n});\n\nmakeError(TypeError, 'ERR_INVALID_HTTP_TOKEN', args => {\n\treturn `${args[0]} must be a valid HTTP token [${args[1]}]`;\n});\n\nmakeError(TypeError, 'ERR_HTTP_INVALID_HEADER_VALUE', args => {\n\treturn `Invalid value \"${args[0]} for header \"${args[1]}\"`;\n});\n\nmakeError(TypeError, 'ERR_INVALID_CHAR', args => {\n\treturn `Invalid character in ${args[0]} [${args[1]}]`;\n});\n", "'use strict';\nconst http2 = require('http2');\nconst {Writable} = require('stream');\nconst {Agent, globalAgent} = require('./agent');\nconst IncomingMessage = require('./incoming-message');\nconst urlToOptions = require('./utils/url-to-options');\nconst proxyEvents = require('./utils/proxy-events');\nconst isRequestPseudoHeader = require('./utils/is-request-pseudo-header');\nconst {\n\tERR_INVALID_ARG_TYPE,\n\tERR_INVALID_PROTOCOL,\n\tERR_HTTP_HEADERS_SENT,\n\tERR_INVALID_HTTP_TOKEN,\n\tERR_HTTP_INVALID_HEADER_VALUE,\n\tERR_INVALID_CHAR\n} = require('./utils/errors');\n\nconst {\n\tHTTP2_HEADER_STATUS,\n\tHTTP2_HEADER_METHOD,\n\tHTTP2_HEADER_PATH,\n\tHTTP2_METHOD_CONNECT\n} = http2.constants;\n\nconst kHeaders = Symbol('headers');\nconst kOrigin = Symbol('origin');\nconst kSession = Symbol('session');\nconst kOptions = Symbol('options');\nconst kFlushedHeaders = Symbol('flushedHeaders');\nconst kJobs = Symbol('jobs');\n\nconst isValidHttpToken = /^[\\^`\\-\\w!#$%&*+.|~]+$/;\nconst isInvalidHeaderValue = /[^\\t\\u0020-\\u007E\\u0080-\\u00FF]/;\n\nclass ClientRequest extends Writable {\n\tconstructor(input, options, callback) {\n\t\tsuper({\n\t\t\tautoDestroy: false\n\t\t});\n\n\t\tconst hasInput = typeof input === 'string' || input instanceof URL;\n\t\tif (hasInput) {\n\t\t\tinput = urlToOptions(input instanceof URL ? input : new URL(input));\n\t\t}\n\n\t\tif (typeof options === 'function' || options === undefined) {\n\t\t\t// (options, callback)\n\t\t\tcallback = options;\n\t\t\toptions = hasInput ? input : {...input};\n\t\t} else {\n\t\t\t// (input, options, callback)\n\t\t\toptions = {...input, ...options};\n\t\t}\n\n\t\tif (options.h2session) {\n\t\t\tthis[kSession] = options.h2session;\n\t\t} else if (options.agent === false) {\n\t\t\tthis.agent = new Agent({maxFreeSessions: 0});\n\t\t} else if (typeof options.agent === 'undefined' || options.agent === null) {\n\t\t\tif (typeof options.createConnection === 'function') {\n\t\t\t\t// This is a workaround - we don't have to create the session on our own.\n\t\t\t\tthis.agent = new Agent({maxFreeSessions: 0});\n\t\t\t\tthis.agent.createConnection = options.createConnection;\n\t\t\t} else {\n\t\t\t\tthis.agent = globalAgent;\n\t\t\t}\n\t\t} else if (typeof options.agent.request === 'function') {\n\t\t\tthis.agent = options.agent;\n\t\t} else {\n\t\t\tthrow new ERR_INVALID_ARG_TYPE('options.agent', ['Agent-like Object', 'undefined', 'false'], options.agent);\n\t\t}\n\n\t\tif (options.protocol && options.protocol !== 'https:') {\n\t\t\tthrow new ERR_INVALID_PROTOCOL(options.protocol, 'https:');\n\t\t}\n\n\t\tconst port = options.port || options.defaultPort || (this.agent && this.agent.defaultPort) || 443;\n\t\tconst host = options.hostname || options.host || 'localhost';\n\n\t\t// Don't enforce the origin via options. It may be changed in an Agent.\n\t\tdelete options.hostname;\n\t\tdelete options.host;\n\t\tdelete options.port;\n\n\t\tconst {timeout} = options;\n\t\toptions.timeout = undefined;\n\n\t\tthis[kHeaders] = Object.create(null);\n\t\tthis[kJobs] = [];\n\n\t\tthis.socket = null;\n\t\tthis.connection = null;\n\n\t\tthis.method = options.method || 'GET';\n\t\tthis.path = options.path;\n\n\t\tthis.res = null;\n\t\tthis.aborted = false;\n\t\tthis.reusedSocket = false;\n\n\t\tif (options.headers) {\n\t\t\tfor (const [header, value] of Object.entries(options.headers)) {\n\t\t\t\tthis.setHeader(header, value);\n\t\t\t}\n\t\t}\n\n\t\tif (options.auth && !('authorization' in this[kHeaders])) {\n\t\t\tthis[kHeaders].authorization = 'Basic ' + Buffer.from(options.auth).toString('base64');\n\t\t}\n\n\t\toptions.session = options.tlsSession;\n\t\toptions.path = options.socketPath;\n\n\t\tthis[kOptions] = options;\n\n\t\t// Clients that generate HTTP/2 requests directly SHOULD use the :authority pseudo-header field instead of the Host header field.\n\t\tif (port === 443) {\n\t\t\tthis[kOrigin] = `https://${host}`;\n\n\t\t\tif (!(':authority' in this[kHeaders])) {\n\t\t\t\tthis[kHeaders][':authority'] = host;\n\t\t\t}\n\t\t} else {\n\t\t\tthis[kOrigin] = `https://${host}:${port}`;\n\n\t\t\tif (!(':authority' in this[kHeaders])) {\n\t\t\t\tthis[kHeaders][':authority'] = `${host}:${port}`;\n\t\t\t}\n\t\t}\n\n\t\tif (timeout) {\n\t\t\tthis.setTimeout(timeout);\n\t\t}\n\n\t\tif (callback) {\n\t\t\tthis.once('response', callback);\n\t\t}\n\n\t\tthis[kFlushedHeaders] = false;\n\t}\n\n\tget method() {\n\t\treturn this[kHeaders][HTTP2_HEADER_METHOD];\n\t}\n\n\tset method(value) {\n\t\tif (value) {\n\t\t\tthis[kHeaders][HTTP2_HEADER_METHOD] = value.toUpperCase();\n\t\t}\n\t}\n\n\tget path() {\n\t\treturn this[kHeaders][HTTP2_HEADER_PATH];\n\t}\n\n\tset path(value) {\n\t\tif (value) {\n\t\t\tthis[kHeaders][HTTP2_HEADER_PATH] = value;\n\t\t}\n\t}\n\n\tget _mustNotHaveABody() {\n\t\treturn this.method === 'GET' || this.method === 'HEAD' || this.method === 'DELETE';\n\t}\n\n\t_write(chunk, encoding, callback) {\n\t\t// https://github.com/nodejs/node/blob/654df09ae0c5e17d1b52a900a545f0664d8c7627/lib/internal/http2/util.js#L148-L156\n\t\tif (this._mustNotHaveABody) {\n\t\t\tcallback(new Error('The GET, HEAD and DELETE methods must NOT have a body'));\n\t\t\t/* istanbul ignore next: Node.js 12 throws directly */\n\t\t\treturn;\n\t\t}\n\n\t\tthis.flushHeaders();\n\n\t\tconst callWrite = () => this._request.write(chunk, encoding, callback);\n\t\tif (this._request) {\n\t\t\tcallWrite();\n\t\t} else {\n\t\t\tthis[kJobs].push(callWrite);\n\t\t}\n\t}\n\n\t_final(callback) {\n\t\tif (this.destroyed) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.flushHeaders();\n\n\t\tconst callEnd = () => {\n\t\t\t// For GET, HEAD and DELETE\n\t\t\tif (this._mustNotHaveABody) {\n\t\t\t\tcallback();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis._request.end(callback);\n\t\t};\n\n\t\tif (this._request) {\n\t\t\tcallEnd();\n\t\t} else {\n\t\t\tthis[kJobs].push(callEnd);\n\t\t}\n\t}\n\n\tabort() {\n\t\tif (this.res && this.res.complete) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.aborted) {\n\t\t\tprocess.nextTick(() => this.emit('abort'));\n\t\t}\n\n\t\tthis.aborted = true;\n\n\t\tthis.destroy();\n\t}\n\n\t_destroy(error, callback) {\n\t\tif (this.res) {\n\t\t\tthis.res._dump();\n\t\t}\n\n\t\tif (this._request) {\n\t\t\tthis._request.destroy();\n\t\t}\n\n\t\tcallback(error);\n\t}\n\n\tasync flushHeaders() {\n\t\tif (this[kFlushedHeaders] || this.destroyed) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis[kFlushedHeaders] = true;\n\n\t\tconst isConnectMethod = this.method === HTTP2_METHOD_CONNECT;\n\n\t\t// The real magic is here\n\t\tconst onStream = stream => {\n\t\t\tthis._request = stream;\n\n\t\t\tif (this.destroyed) {\n\t\t\t\tstream.destroy();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Forwards `timeout`, `continue`, `close` and `error` events to this instance.\n\t\t\tif (!isConnectMethod) {\n\t\t\t\tproxyEvents(stream, this, ['timeout', 'continue', 'close', 'error']);\n\t\t\t}\n\n\t\t\t// Wait for the `finish` event. We don't want to emit the `response` event\n\t\t\t// before `request.end()` is called.\n\t\t\tconst waitForEnd = fn => {\n\t\t\t\treturn (...args) => {\n\t\t\t\t\tif (!this.writable && !this.destroyed) {\n\t\t\t\t\t\tfn(...args);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.once('finish', () => {\n\t\t\t\t\t\t\tfn(...args);\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t};\n\n\t\t\t// This event tells we are ready to listen for the data.\n\t\t\tstream.once('response', waitForEnd((headers, flags, rawHeaders) => {\n\t\t\t\t// If we were to emit raw request stream, it would be as fast as the native approach.\n\t\t\t\t// Note that wrapping the raw stream in a Proxy instance won't improve the performance (already tested it).\n\t\t\t\tconst response = new IncomingMessage(this.socket, stream.readableHighWaterMark);\n\t\t\t\tthis.res = response;\n\n\t\t\t\tresponse.req = this;\n\t\t\t\tresponse.statusCode = headers[HTTP2_HEADER_STATUS];\n\t\t\t\tresponse.headers = headers;\n\t\t\t\tresponse.rawHeaders = rawHeaders;\n\n\t\t\t\tresponse.once('end', () => {\n\t\t\t\t\tif (this.aborted) {\n\t\t\t\t\t\tresponse.aborted = true;\n\t\t\t\t\t\tresponse.emit('aborted');\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresponse.complete = true;\n\n\t\t\t\t\t\t// Has no effect, just be consistent with the Node.js behavior\n\t\t\t\t\t\tresponse.socket = null;\n\t\t\t\t\t\tresponse.connection = null;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tif (isConnectMethod) {\n\t\t\t\t\tresponse.upgrade = true;\n\n\t\t\t\t\t// The HTTP1 API says the socket is detached here,\n\t\t\t\t\t// but we can't do that so we pass the original HTTP2 request.\n\t\t\t\t\tif (this.emit('connect', response, stream, Buffer.alloc(0))) {\n\t\t\t\t\t\tthis.emit('close');\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// No listeners attached, destroy the original request.\n\t\t\t\t\t\tstream.destroy();\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Forwards data\n\t\t\t\t\tstream.on('data', chunk => {\n\t\t\t\t\t\tif (!response._dumped && !response.push(chunk)) {\n\t\t\t\t\t\t\tstream.pause();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\tstream.once('end', () => {\n\t\t\t\t\t\tresponse.push(null);\n\t\t\t\t\t});\n\n\t\t\t\t\tif (!this.emit('response', response)) {\n\t\t\t\t\t\t// No listeners attached, dump the response.\n\t\t\t\t\t\tresponse._dump();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}));\n\n\t\t\t// Emits `information` event\n\t\t\tstream.once('headers', waitForEnd(\n\t\t\t\theaders => this.emit('information', {statusCode: headers[HTTP2_HEADER_STATUS]})\n\t\t\t));\n\n\t\t\tstream.once('trailers', waitForEnd((trailers, flags, rawTrailers) => {\n\t\t\t\tconst {res} = this;\n\n\t\t\t\t// Assigns trailers to the response object.\n\t\t\t\tres.trailers = trailers;\n\t\t\t\tres.rawTrailers = rawTrailers;\n\t\t\t}));\n\n\t\t\tconst {socket} = stream.session;\n\t\t\tthis.socket = socket;\n\t\t\tthis.connection = socket;\n\n\t\t\tfor (const job of this[kJobs]) {\n\t\t\t\tjob();\n\t\t\t}\n\n\t\t\tthis.emit('socket', this.socket);\n\t\t};\n\n\t\t// Makes a HTTP2 request\n\t\tif (this[kSession]) {\n\t\t\ttry {\n\t\t\t\tonStream(this[kSession].request(this[kHeaders]));\n\t\t\t} catch (error) {\n\t\t\t\tthis.emit('error', error);\n\t\t\t}\n\t\t} else {\n\t\t\tthis.reusedSocket = true;\n\n\t\t\ttry {\n\t\t\t\tonStream(await this.agent.request(this[kOrigin], this[kOptions], this[kHeaders]));\n\t\t\t} catch (error) {\n\t\t\t\tthis.emit('error', error);\n\t\t\t}\n\t\t}\n\t}\n\n\tgetHeader(name) {\n\t\tif (typeof name !== 'string') {\n\t\t\tthrow new ERR_INVALID_ARG_TYPE('name', 'string', name);\n\t\t}\n\n\t\treturn this[kHeaders][name.toLowerCase()];\n\t}\n\n\tget headersSent() {\n\t\treturn this[kFlushedHeaders];\n\t}\n\n\tremoveHeader(name) {\n\t\tif (typeof name !== 'string') {\n\t\t\tthrow new ERR_INVALID_ARG_TYPE('name', 'string', name);\n\t\t}\n\n\t\tif (this.headersSent) {\n\t\t\tthrow new ERR_HTTP_HEADERS_SENT('remove');\n\t\t}\n\n\t\tdelete this[kHeaders][name.toLowerCase()];\n\t}\n\n\tsetHeader(name, value) {\n\t\tif (this.headersSent) {\n\t\t\tthrow new ERR_HTTP_HEADERS_SENT('set');\n\t\t}\n\n\t\tif (typeof name !== 'string' || (!isValidHttpToken.test(name) && !isRequestPseudoHeader(name))) {\n\t\t\tthrow new ERR_INVALID_HTTP_TOKEN('Header name', name);\n\t\t}\n\n\t\tif (typeof value === 'undefined') {\n\t\t\tthrow new ERR_HTTP_INVALID_HEADER_VALUE(value, name);\n\t\t}\n\n\t\tif (isInvalidHeaderValue.test(value)) {\n\t\t\tthrow new ERR_INVALID_CHAR('header content', name);\n\t\t}\n\n\t\tthis[kHeaders][name.toLowerCase()] = value;\n\t}\n\n\tsetNoDelay() {\n\t\t// HTTP2 sockets cannot be malformed, do nothing.\n\t}\n\n\tsetSocketKeepAlive() {\n\t\t// HTTP2 sockets cannot be malformed, do nothing.\n\t}\n\n\tsetTimeout(ms, callback) {\n\t\tconst applyTimeout = () => this._request.setTimeout(ms, callback);\n\n\t\tif (this._request) {\n\t\t\tapplyTimeout();\n\t\t} else {\n\t\t\tthis[kJobs].push(applyTimeout);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tget maxHeadersCount() {\n\t\tif (!this.destroyed && this._request) {\n\t\t\treturn this._request.session.localSettings.maxHeaderListSize;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tset maxHeadersCount(_value) {\n\t\t// Updating HTTP2 settings would affect all requests, do nothing.\n\t}\n}\n\nmodule.exports = ClientRequest;\n", "'use strict';\nconst tls = require('tls');\n\nmodule.exports = (options = {}, connect = tls.connect) => new Promise((resolve, reject) => {\n\tlet timeout = false;\n\n\tlet socket;\n\n\tconst callback = async () => {\n\t\tawait socketPromise;\n\n\t\tsocket.off('timeout', onTimeout);\n\t\tsocket.off('error', reject);\n\n\t\tif (options.resolveSocket) {\n\t\t\tresolve({alpnProtocol: socket.alpnProtocol, socket, timeout});\n\n\t\t\tif (timeout) {\n\t\t\t\tawait Promise.resolve();\n\t\t\t\tsocket.emit('timeout');\n\t\t\t}\n\t\t} else {\n\t\t\tsocket.destroy();\n\t\t\tresolve({alpnProtocol: socket.alpnProtocol, timeout});\n\t\t}\n\t};\n\n\tconst onTimeout = async () => {\n\t\ttimeout = true;\n\t\tcallback();\n\t};\n\n\tconst socketPromise = (async () => {\n\t\ttry {\n\t\t\tsocket = await connect(options, callback);\n\n\t\t\tsocket.on('error', reject);\n\t\t\tsocket.once('timeout', onTimeout);\n\t\t} catch (error) {\n\t\t\treject(error);\n\t\t}\n\t})();\n});\n", "'use strict';\nconst net = require('net');\n/* istanbul ignore file: https://github.com/nodejs/node/blob/v13.0.1/lib/_http_agent.js */\n\nmodule.exports = options => {\n\tlet servername = options.host;\n\tconst hostHeader = options.headers && options.headers.host;\n\n\tif (hostHeader) {\n\t\tif (hostHeader.startsWith('[')) {\n\t\t\tconst index = hostHeader.indexOf(']');\n\t\t\tif (index === -1) {\n\t\t\t\tservername = hostHeader;\n\t\t\t} else {\n\t\t\t\tservername = hostHeader.slice(1, -1);\n\t\t\t}\n\t\t} else {\n\t\t\tservername = hostHeader.split(':', 1)[0];\n\t\t}\n\t}\n\n\tif (net.isIP(servername)) {\n\t\treturn '';\n\t}\n\n\treturn servername;\n};\n", "'use strict';\nconst http = require('http');\nconst https = require('https');\nconst resolveALPN = require('resolve-alpn');\nconst QuickLRU = require('quick-lru');\nconst Http2ClientRequest = require('./client-request');\nconst calculateServerName = require('./utils/calculate-server-name');\nconst urlToOptions = require('./utils/url-to-options');\n\nconst cache = new QuickLRU({maxSize: 100});\nconst queue = new Map();\n\nconst installSocket = (agent, socket, options) => {\n\tsocket._httpMessage = {shouldKeepAlive: true};\n\n\tconst onFree = () => {\n\t\tagent.emit('free', socket, options);\n\t};\n\n\tsocket.on('free', onFree);\n\n\tconst onClose = () => {\n\t\tagent.removeSocket(socket, options);\n\t};\n\n\tsocket.on('close', onClose);\n\n\tconst onRemove = () => {\n\t\tagent.removeSocket(socket, options);\n\t\tsocket.off('close', onClose);\n\t\tsocket.off('free', onFree);\n\t\tsocket.off('agentRemove', onRemove);\n\t};\n\n\tsocket.on('agentRemove', onRemove);\n\n\tagent.emit('free', socket, options);\n};\n\nconst resolveProtocol = async options => {\n\tconst name = `${options.host}:${options.port}:${options.ALPNProtocols.sort()}`;\n\n\tif (!cache.has(name)) {\n\t\tif (queue.has(name)) {\n\t\t\tconst result = await queue.get(name);\n\t\t\treturn result.alpnProtocol;\n\t\t}\n\n\t\tconst {path, agent} = options;\n\t\toptions.path = options.socketPath;\n\n\t\tconst resultPromise = resolveALPN(options);\n\t\tqueue.set(name, resultPromise);\n\n\t\ttry {\n\t\t\tconst {socket, alpnProtocol} = await resultPromise;\n\t\t\tcache.set(name, alpnProtocol);\n\n\t\t\toptions.path = path;\n\n\t\t\tif (alpnProtocol === 'h2') {\n\t\t\t\t// https://github.com/nodejs/node/issues/33343\n\t\t\t\tsocket.destroy();\n\t\t\t} else {\n\t\t\t\tconst {globalAgent} = https;\n\t\t\t\tconst defaultCreateConnection = https.Agent.prototype.createConnection;\n\n\t\t\t\tif (agent) {\n\t\t\t\t\tif (agent.createConnection === defaultCreateConnection) {\n\t\t\t\t\t\tinstallSocket(agent, socket, options);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsocket.destroy();\n\t\t\t\t\t}\n\t\t\t\t} else if (globalAgent.createConnection === defaultCreateConnection) {\n\t\t\t\t\tinstallSocket(globalAgent, socket, options);\n\t\t\t\t} else {\n\t\t\t\t\tsocket.destroy();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tqueue.delete(name);\n\n\t\t\treturn alpnProtocol;\n\t\t} catch (error) {\n\t\t\tqueue.delete(name);\n\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\treturn cache.get(name);\n};\n\nmodule.exports = async (input, options, callback) => {\n\tif (typeof input === 'string' || input instanceof URL) {\n\t\tinput = urlToOptions(new URL(input));\n\t}\n\n\tif (typeof options === 'function') {\n\t\tcallback = options;\n\t\toptions = undefined;\n\t}\n\n\toptions = {\n\t\tALPNProtocols: ['h2', 'http/1.1'],\n\t\t...input,\n\t\t...options,\n\t\tresolveSocket: true\n\t};\n\n\tif (!Array.isArray(options.ALPNProtocols) || options.ALPNProtocols.length === 0) {\n\t\tthrow new Error('The `ALPNProtocols` option must be an Array with at least one entry');\n\t}\n\n\toptions.protocol = options.protocol || 'https:';\n\tconst isHttps = options.protocol === 'https:';\n\n\toptions.host = options.hostname || options.host || 'localhost';\n\toptions.session = options.tlsSession;\n\toptions.servername = options.servername || calculateServerName(options);\n\toptions.port = options.port || (isHttps ? 443 : 80);\n\toptions._defaultAgent = isHttps ? https.globalAgent : http.globalAgent;\n\n\tconst agents = options.agent;\n\n\tif (agents) {\n\t\tif (agents.addRequest) {\n\t\t\tthrow new Error('The `options.agent` object can contain only `http`, `https` or `http2` properties');\n\t\t}\n\n\t\toptions.agent = agents[isHttps ? 'https' : 'http'];\n\t}\n\n\tif (isHttps) {\n\t\tconst protocol = await resolveProtocol(options);\n\n\t\tif (protocol === 'h2') {\n\t\t\tif (agents) {\n\t\t\t\toptions.agent = agents.http2;\n\t\t\t}\n\n\t\t\treturn new Http2ClientRequest(options, callback);\n\t\t}\n\t}\n\n\treturn http.request(options, callback);\n};\n\nmodule.exports.protocolCache = cache;\n", "'use strict';\nconst http2 = require('http2');\nconst agent = require('./agent');\nconst ClientRequest = require('./client-request');\nconst IncomingMessage = require('./incoming-message');\nconst auto = require('./auto');\n\nconst request = (url, options, callback) => {\n\treturn new ClientRequest(url, options, callback);\n};\n\nconst get = (url, options, callback) => {\n\t// eslint-disable-next-line unicorn/prevent-abbreviations\n\tconst req = new ClientRequest(url, options, callback);\n\treq.end();\n\n\treturn req;\n};\n\nmodule.exports = {\n\t...http2,\n\tClientRequest,\n\tIncomingMessage,\n\t...agent,\n\trequest,\n\tget,\n\tauto\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst is_1 = require(\"@sindresorhus/is\");\nexports.default = (body) => is_1.default.nodeStream(body) && is_1.default.function_(body.getBoundary);\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst fs_1 = require(\"fs\");\nconst util_1 = require(\"util\");\nconst is_1 = require(\"@sindresorhus/is\");\nconst is_form_data_1 = require(\"./is-form-data\");\nconst statAsync = util_1.promisify(fs_1.stat);\nexports.default = async (body, headers) => {\n if (headers && 'content-length' in headers) {\n return Number(headers['content-length']);\n }\n if (!body) {\n return 0;\n }\n if (is_1.default.string(body)) {\n return Buffer.byteLength(body);\n }\n if (is_1.default.buffer(body)) {\n return body.length;\n }\n if (is_form_data_1.default(body)) {\n return util_1.promisify(body.getLength.bind(body))();\n }\n if (body instanceof fs_1.ReadStream) {\n const { size } = await statAsync(body.path);\n if (size === 0) {\n return undefined;\n }\n return size;\n }\n return undefined;\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction default_1(from, to, events) {\n const fns = {};\n for (const event of events) {\n fns[event] = (...args) => {\n to.emit(event, ...args);\n };\n from.on(event, fns[event]);\n }\n return () => {\n for (const event of events) {\n from.off(event, fns[event]);\n }\n };\n}\nexports.default = default_1;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// When attaching listeners, it's very easy to forget about them.\n// Especially if you do error handling and set timeouts.\n// So instead of checking if it's proper to throw an error on every timeout ever,\n// use this simple tool which will remove all listeners you have attached.\nexports.default = () => {\n const handlers = [];\n return {\n once(origin, event, fn) {\n origin.once(event, fn);\n handlers.push({ origin, event, fn });\n },\n unhandleAll() {\n for (const handler of handlers) {\n const { origin, event, fn } = handler;\n origin.removeListener(event, fn);\n }\n handlers.length = 0;\n }\n };\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TimeoutError = void 0;\nconst net = require(\"net\");\nconst unhandle_1 = require(\"./unhandle\");\nconst reentry = Symbol('reentry');\nconst noop = () => { };\nclass TimeoutError extends Error {\n constructor(threshold, event) {\n super(`Timeout awaiting '${event}' for ${threshold}ms`);\n this.event = event;\n this.name = 'TimeoutError';\n this.code = 'ETIMEDOUT';\n }\n}\nexports.TimeoutError = TimeoutError;\nexports.default = (request, delays, options) => {\n if (reentry in request) {\n return noop;\n }\n request[reentry] = true;\n const cancelers = [];\n const { once, unhandleAll } = unhandle_1.default();\n const addTimeout = (delay, callback, event) => {\n var _a;\n const timeout = setTimeout(callback, delay, delay, event);\n (_a = timeout.unref) === null || _a === void 0 ? void 0 : _a.call(timeout);\n const cancel = () => {\n clearTimeout(timeout);\n };\n cancelers.push(cancel);\n return cancel;\n };\n const { host, hostname } = options;\n const timeoutHandler = (delay, event) => {\n request.destroy(new TimeoutError(delay, event));\n };\n const cancelTimeouts = () => {\n for (const cancel of cancelers) {\n cancel();\n }\n unhandleAll();\n };\n request.once('error', error => {\n cancelTimeouts();\n // Save original behavior\n /* istanbul ignore next */\n if (request.listenerCount('error') === 0) {\n throw error;\n }\n });\n request.once('close', cancelTimeouts);\n once(request, 'response', (response) => {\n once(response, 'end', cancelTimeouts);\n });\n if (typeof delays.request !== 'undefined') {\n addTimeout(delays.request, timeoutHandler, 'request');\n }\n if (typeof delays.socket !== 'undefined') {\n const socketTimeoutHandler = () => {\n timeoutHandler(delays.socket, 'socket');\n };\n request.setTimeout(delays.socket, socketTimeoutHandler);\n // `request.setTimeout(0)` causes a memory leak.\n // We can just remove the listener and forget about the timer - it's unreffed.\n // See https://github.com/sindresorhus/got/issues/690\n cancelers.push(() => {\n request.removeListener('timeout', socketTimeoutHandler);\n });\n }\n once(request, 'socket', (socket) => {\n var _a;\n const { socketPath } = request;\n /* istanbul ignore next: hard to test */\n if (socket.connecting) {\n const hasPath = Boolean(socketPath !== null && socketPath !== void 0 ? socketPath : net.isIP((_a = hostname !== null && hostname !== void 0 ? hostname : host) !== null && _a !== void 0 ? _a : '') !== 0);\n if (typeof delays.lookup !== 'undefined' && !hasPath && typeof socket.address().address === 'undefined') {\n const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup');\n once(socket, 'lookup', cancelTimeout);\n }\n if (typeof delays.connect !== 'undefined') {\n const timeConnect = () => addTimeout(delays.connect, timeoutHandler, 'connect');\n if (hasPath) {\n once(socket, 'connect', timeConnect());\n }\n else {\n once(socket, 'lookup', (error) => {\n if (error === null) {\n once(socket, 'connect', timeConnect());\n }\n });\n }\n }\n if (typeof delays.secureConnect !== 'undefined' && options.protocol === 'https:') {\n once(socket, 'connect', () => {\n const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect');\n once(socket, 'secureConnect', cancelTimeout);\n });\n }\n }\n if (typeof delays.send !== 'undefined') {\n const timeRequest = () => addTimeout(delays.send, timeoutHandler, 'send');\n /* istanbul ignore next: hard to test */\n if (socket.connecting) {\n once(socket, 'connect', () => {\n once(request, 'upload-complete', timeRequest());\n });\n }\n else {\n once(request, 'upload-complete', timeRequest());\n }\n }\n });\n if (typeof delays.response !== 'undefined') {\n once(request, 'upload-complete', () => {\n const cancelTimeout = addTimeout(delays.response, timeoutHandler, 'response');\n once(request, 'response', cancelTimeout);\n });\n }\n return cancelTimeouts;\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst is_1 = require(\"@sindresorhus/is\");\nexports.default = (url) => {\n // Cast to URL\n url = url;\n const options = {\n protocol: url.protocol,\n hostname: is_1.default.string(url.hostname) && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname,\n host: url.host,\n hash: url.hash,\n search: url.search,\n pathname: url.pathname,\n href: url.href,\n path: `${url.pathname || ''}${url.search || ''}`\n };\n if (is_1.default.string(url.port) && url.port.length > 0) {\n options.port = Number(url.port);\n }\n if (url.username || url.password) {\n options.auth = `${url.username || ''}:${url.password || ''}`;\n }\n return options;\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/* istanbul ignore file: deprecated */\nconst url_1 = require(\"url\");\nconst keys = [\n 'protocol',\n 'host',\n 'hostname',\n 'port',\n 'pathname',\n 'search'\n];\nexports.default = (origin, options) => {\n var _a, _b;\n if (options.path) {\n if (options.pathname) {\n throw new TypeError('Parameters `path` and `pathname` are mutually exclusive.');\n }\n if (options.search) {\n throw new TypeError('Parameters `path` and `search` are mutually exclusive.');\n }\n if (options.searchParams) {\n throw new TypeError('Parameters `path` and `searchParams` are mutually exclusive.');\n }\n }\n if (options.search && options.searchParams) {\n throw new TypeError('Parameters `search` and `searchParams` are mutually exclusive.');\n }\n if (!origin) {\n if (!options.protocol) {\n throw new TypeError('No URL protocol specified');\n }\n origin = `${options.protocol}//${(_b = (_a = options.hostname) !== null && _a !== void 0 ? _a : options.host) !== null && _b !== void 0 ? _b : ''}`;\n }\n const url = new url_1.URL(origin);\n if (options.path) {\n const searchIndex = options.path.indexOf('?');\n if (searchIndex === -1) {\n options.pathname = options.path;\n }\n else {\n options.pathname = options.path.slice(0, searchIndex);\n options.search = options.path.slice(searchIndex + 1);\n }\n delete options.path;\n }\n for (const key of keys) {\n if (options[key]) {\n url[key] = options[key].toString();\n }\n }\n return url;\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass WeakableMap {\n constructor() {\n this.weakMap = new WeakMap();\n this.map = new Map();\n }\n set(key, value) {\n if (typeof key === 'object') {\n this.weakMap.set(key, value);\n }\n else {\n this.map.set(key, value);\n }\n }\n get(key) {\n if (typeof key === 'object') {\n return this.weakMap.get(key);\n }\n return this.map.get(key);\n }\n has(key) {\n if (typeof key === 'object') {\n return this.weakMap.has(key);\n }\n return this.map.has(key);\n }\n}\nexports.default = WeakableMap;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// TODO: Update https://github.com/sindresorhus/get-stream\nconst getBuffer = async (stream) => {\n const chunks = [];\n let length = 0;\n for await (const chunk of stream) {\n chunks.push(chunk);\n length += Buffer.byteLength(chunk);\n }\n if (Buffer.isBuffer(chunks[0])) {\n return Buffer.concat(chunks, length);\n }\n return Buffer.from(chunks.join(''));\n};\nexports.default = getBuffer;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.dnsLookupIpVersionToFamily = exports.isDnsLookupIpVersion = void 0;\nconst conversionTable = {\n auto: 0,\n ipv4: 4,\n ipv6: 6\n};\nexports.isDnsLookupIpVersion = (value) => {\n return value in conversionTable;\n};\nexports.dnsLookupIpVersionToFamily = (dnsLookupIpVersion) => {\n if (exports.isDnsLookupIpVersion(dnsLookupIpVersion)) {\n return conversionTable[dnsLookupIpVersion];\n }\n throw new Error('Invalid DNS lookup IP version');\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isResponseOk = void 0;\nexports.isResponseOk = (response) => {\n const { statusCode } = response;\n const limitStatusCode = response.request.options.followRedirect ? 299 : 399;\n return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304;\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst alreadyWarned = new Set();\nexports.default = (message) => {\n if (alreadyWarned.has(message)) {\n return;\n }\n alreadyWarned.add(message);\n // @ts-expect-error Missing types.\n process.emitWarning(`Got: ${message}`, {\n type: 'DeprecationWarning'\n });\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst is_1 = require(\"@sindresorhus/is\");\nconst normalizeArguments = (options, defaults) => {\n if (is_1.default.null_(options.encoding)) {\n throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead');\n }\n is_1.assert.any([is_1.default.string, is_1.default.undefined], options.encoding);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.resolveBodyOnly);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.methodRewriting);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.isStream);\n is_1.assert.any([is_1.default.string, is_1.default.undefined], options.responseType);\n // `options.responseType`\n if (options.responseType === undefined) {\n options.responseType = 'text';\n }\n // `options.retry`\n const { retry } = options;\n if (defaults) {\n options.retry = { ...defaults.retry };\n }\n else {\n options.retry = {\n calculateDelay: retryObject => retryObject.computedValue,\n limit: 0,\n methods: [],\n statusCodes: [],\n errorCodes: [],\n maxRetryAfter: undefined\n };\n }\n if (is_1.default.object(retry)) {\n options.retry = {\n ...options.retry,\n ...retry\n };\n options.retry.methods = [...new Set(options.retry.methods.map(method => method.toUpperCase()))];\n options.retry.statusCodes = [...new Set(options.retry.statusCodes)];\n options.retry.errorCodes = [...new Set(options.retry.errorCodes)];\n }\n else if (is_1.default.number(retry)) {\n options.retry.limit = retry;\n }\n if (is_1.default.undefined(options.retry.maxRetryAfter)) {\n options.retry.maxRetryAfter = Math.min(\n // TypeScript is not smart enough to handle `.filter(x => is.number(x))`.\n // eslint-disable-next-line unicorn/no-fn-reference-in-iterator\n ...[options.timeout.request, options.timeout.connect].filter(is_1.default.number));\n }\n // `options.pagination`\n if (is_1.default.object(options.pagination)) {\n if (defaults) {\n options.pagination = {\n ...defaults.pagination,\n ...options.pagination\n };\n }\n const { pagination } = options;\n if (!is_1.default.function_(pagination.transform)) {\n throw new Error('`options.pagination.transform` must be implemented');\n }\n if (!is_1.default.function_(pagination.shouldContinue)) {\n throw new Error('`options.pagination.shouldContinue` must be implemented');\n }\n if (!is_1.default.function_(pagination.filter)) {\n throw new TypeError('`options.pagination.filter` must be implemented');\n }\n if (!is_1.default.function_(pagination.paginate)) {\n throw new Error('`options.pagination.paginate` must be implemented');\n }\n }\n // JSON mode\n if (options.responseType === 'json' && options.headers.accept === undefined) {\n options.headers.accept = 'application/json';\n }\n return options;\n};\nexports.default = normalizeArguments;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.retryAfterStatusCodes = void 0;\nexports.retryAfterStatusCodes = new Set([413, 429, 503]);\nconst calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter }) => {\n if (attemptCount > retryOptions.limit) {\n return 0;\n }\n const hasMethod = retryOptions.methods.includes(error.options.method);\n const hasErrorCode = retryOptions.errorCodes.includes(error.code);\n const hasStatusCode = error.response && retryOptions.statusCodes.includes(error.response.statusCode);\n if (!hasMethod || (!hasErrorCode && !hasStatusCode)) {\n return 0;\n }\n if (error.response) {\n if (retryAfter) {\n if (retryOptions.maxRetryAfter === undefined || retryAfter > retryOptions.maxRetryAfter) {\n return 0;\n }\n return retryAfter;\n }\n if (error.response.statusCode === 413) {\n return 0;\n }\n }\n const noise = Math.random() * 100;\n return ((2 ** (attemptCount - 1)) * 1000) + noise;\n};\nexports.default = calculateRetryDelay;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.UnsupportedProtocolError = exports.ReadError = exports.TimeoutError = exports.UploadError = exports.CacheError = exports.HTTPError = exports.MaxRedirectsError = exports.RequestError = exports.setNonEnumerableProperties = exports.knownHookEvents = exports.withoutBody = exports.kIsNormalizedAlready = void 0;\nconst util_1 = require(\"util\");\nconst stream_1 = require(\"stream\");\nconst fs_1 = require(\"fs\");\nconst url_1 = require(\"url\");\nconst http = require(\"http\");\nconst http_1 = require(\"http\");\nconst https = require(\"https\");\nconst http_timer_1 = require(\"@szmarczak/http-timer\");\nconst cacheable_lookup_1 = require(\"cacheable-lookup\");\nconst CacheableRequest = require(\"cacheable-request\");\nconst decompressResponse = require(\"decompress-response\");\n// @ts-expect-error Missing types\nconst http2wrapper = require(\"http2-wrapper\");\nconst lowercaseKeys = require(\"lowercase-keys\");\nconst is_1 = require(\"@sindresorhus/is\");\nconst get_body_size_1 = require(\"./utils/get-body-size\");\nconst is_form_data_1 = require(\"./utils/is-form-data\");\nconst proxy_events_1 = require(\"./utils/proxy-events\");\nconst timed_out_1 = require(\"./utils/timed-out\");\nconst url_to_options_1 = require(\"./utils/url-to-options\");\nconst options_to_url_1 = require(\"./utils/options-to-url\");\nconst weakable_map_1 = require(\"./utils/weakable-map\");\nconst get_buffer_1 = require(\"./utils/get-buffer\");\nconst dns_ip_version_1 = require(\"./utils/dns-ip-version\");\nconst is_response_ok_1 = require(\"./utils/is-response-ok\");\nconst deprecation_warning_1 = require(\"../utils/deprecation-warning\");\nconst normalize_arguments_1 = require(\"../as-promise/normalize-arguments\");\nconst calculate_retry_delay_1 = require(\"./calculate-retry-delay\");\nlet globalDnsCache;\nconst kRequest = Symbol('request');\nconst kResponse = Symbol('response');\nconst kResponseSize = Symbol('responseSize');\nconst kDownloadedSize = Symbol('downloadedSize');\nconst kBodySize = Symbol('bodySize');\nconst kUploadedSize = Symbol('uploadedSize');\nconst kServerResponsesPiped = Symbol('serverResponsesPiped');\nconst kUnproxyEvents = Symbol('unproxyEvents');\nconst kIsFromCache = Symbol('isFromCache');\nconst kCancelTimeouts = Symbol('cancelTimeouts');\nconst kStartedReading = Symbol('startedReading');\nconst kStopReading = Symbol('stopReading');\nconst kTriggerRead = Symbol('triggerRead');\nconst kBody = Symbol('body');\nconst kJobs = Symbol('jobs');\nconst kOriginalResponse = Symbol('originalResponse');\nconst kRetryTimeout = Symbol('retryTimeout');\nexports.kIsNormalizedAlready = Symbol('isNormalizedAlready');\nconst supportsBrotli = is_1.default.string(process.versions.brotli);\nexports.withoutBody = new Set(['GET', 'HEAD']);\nexports.knownHookEvents = [\n 'init',\n 'beforeRequest',\n 'beforeRedirect',\n 'beforeError',\n 'beforeRetry',\n // Promise-Only\n 'afterResponse'\n];\nfunction validateSearchParameters(searchParameters) {\n // eslint-disable-next-line guard-for-in\n for (const key in searchParameters) {\n const value = searchParameters[key];\n if (!is_1.default.string(value) && !is_1.default.number(value) && !is_1.default.boolean(value) && !is_1.default.null_(value) && !is_1.default.undefined(value)) {\n throw new TypeError(`The \\`searchParams\\` value '${String(value)}' must be a string, number, boolean or null`);\n }\n }\n}\nfunction isClientRequest(clientRequest) {\n return is_1.default.object(clientRequest) && !('statusCode' in clientRequest);\n}\nconst cacheableStore = new weakable_map_1.default();\nconst waitForOpenFile = async (file) => new Promise((resolve, reject) => {\n const onError = (error) => {\n reject(error);\n };\n // Node.js 12 has incomplete types\n if (!file.pending) {\n resolve();\n }\n file.once('error', onError);\n file.once('ready', () => {\n file.off('error', onError);\n resolve();\n });\n});\nconst redirectCodes = new Set([300, 301, 302, 303, 304, 307, 308]);\nconst nonEnumerableProperties = [\n 'context',\n 'body',\n 'json',\n 'form'\n];\nexports.setNonEnumerableProperties = (sources, to) => {\n // Non enumerable properties shall not be merged\n const properties = {};\n for (const source of sources) {\n if (!source) {\n continue;\n }\n for (const name of nonEnumerableProperties) {\n if (!(name in source)) {\n continue;\n }\n properties[name] = {\n writable: true,\n configurable: true,\n enumerable: false,\n // @ts-expect-error TS doesn't see the check above\n value: source[name]\n };\n }\n }\n Object.defineProperties(to, properties);\n};\n/**\nAn error to be thrown when a request fails.\nContains a `code` property with error class code, like `ECONNREFUSED`.\n*/\nclass RequestError extends Error {\n constructor(message, error, self) {\n var _a;\n super(message);\n Error.captureStackTrace(this, this.constructor);\n this.name = 'RequestError';\n this.code = error.code;\n if (self instanceof Request) {\n Object.defineProperty(this, 'request', {\n enumerable: false,\n value: self\n });\n Object.defineProperty(this, 'response', {\n enumerable: false,\n value: self[kResponse]\n });\n Object.defineProperty(this, 'options', {\n // This fails because of TS 3.7.2 useDefineForClassFields\n // Ref: https://github.com/microsoft/TypeScript/issues/34972\n enumerable: false,\n value: self.options\n });\n }\n else {\n Object.defineProperty(this, 'options', {\n // This fails because of TS 3.7.2 useDefineForClassFields\n // Ref: https://github.com/microsoft/TypeScript/issues/34972\n enumerable: false,\n value: self\n });\n }\n this.timings = (_a = this.request) === null || _a === void 0 ? void 0 : _a.timings;\n // Recover the original stacktrace\n if (is_1.default.string(error.stack) && is_1.default.string(this.stack)) {\n const indexOfMessage = this.stack.indexOf(this.message) + this.message.length;\n const thisStackTrace = this.stack.slice(indexOfMessage).split('\\n').reverse();\n const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split('\\n').reverse();\n // Remove duplicated traces\n while (errorStackTrace.length !== 0 && errorStackTrace[0] === thisStackTrace[0]) {\n thisStackTrace.shift();\n }\n this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\\n')}${errorStackTrace.reverse().join('\\n')}`;\n }\n }\n}\nexports.RequestError = RequestError;\n/**\nAn error to be thrown when the server redirects you more than ten times.\nIncludes a `response` property.\n*/\nclass MaxRedirectsError extends RequestError {\n constructor(request) {\n super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request);\n this.name = 'MaxRedirectsError';\n }\n}\nexports.MaxRedirectsError = MaxRedirectsError;\n/**\nAn error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304.\nIncludes a `response` property.\n*/\nclass HTTPError extends RequestError {\n constructor(response) {\n super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, response.request);\n this.name = 'HTTPError';\n }\n}\nexports.HTTPError = HTTPError;\n/**\nAn error to be thrown when a cache method fails.\nFor example, if the database goes down or there's a filesystem error.\n*/\nclass CacheError extends RequestError {\n constructor(error, request) {\n super(error.message, error, request);\n this.name = 'CacheError';\n }\n}\nexports.CacheError = CacheError;\n/**\nAn error to be thrown when the request body is a stream and an error occurs while reading from that stream.\n*/\nclass UploadError extends RequestError {\n constructor(error, request) {\n super(error.message, error, request);\n this.name = 'UploadError';\n }\n}\nexports.UploadError = UploadError;\n/**\nAn error to be thrown when the request is aborted due to a timeout.\nIncludes an `event` and `timings` property.\n*/\nclass TimeoutError extends RequestError {\n constructor(error, timings, request) {\n super(error.message, error, request);\n this.name = 'TimeoutError';\n this.event = error.event;\n this.timings = timings;\n }\n}\nexports.TimeoutError = TimeoutError;\n/**\nAn error to be thrown when reading from response stream fails.\n*/\nclass ReadError extends RequestError {\n constructor(error, request) {\n super(error.message, error, request);\n this.name = 'ReadError';\n }\n}\nexports.ReadError = ReadError;\n/**\nAn error to be thrown when given an unsupported protocol.\n*/\nclass UnsupportedProtocolError extends RequestError {\n constructor(options) {\n super(`Unsupported protocol \"${options.url.protocol}\"`, {}, options);\n this.name = 'UnsupportedProtocolError';\n }\n}\nexports.UnsupportedProtocolError = UnsupportedProtocolError;\nconst proxiedRequestEvents = [\n 'socket',\n 'connect',\n 'continue',\n 'information',\n 'upgrade',\n 'timeout'\n];\nclass Request extends stream_1.Duplex {\n constructor(url, options = {}, defaults) {\n super({\n // This must be false, to enable throwing after destroy\n // It is used for retry logic in Promise API\n autoDestroy: false,\n // It needs to be zero because we're just proxying the data to another stream\n highWaterMark: 0\n });\n this[kDownloadedSize] = 0;\n this[kUploadedSize] = 0;\n this.requestInitialized = false;\n this[kServerResponsesPiped] = new Set();\n this.redirects = [];\n this[kStopReading] = false;\n this[kTriggerRead] = false;\n this[kJobs] = [];\n this.retryCount = 0;\n // TODO: Remove this when targeting Node.js >= 12\n this._progressCallbacks = [];\n const unlockWrite = () => this._unlockWrite();\n const lockWrite = () => this._lockWrite();\n this.on('pipe', (source) => {\n source.prependListener('data', unlockWrite);\n source.on('data', lockWrite);\n source.prependListener('end', unlockWrite);\n source.on('end', lockWrite);\n });\n this.on('unpipe', (source) => {\n source.off('data', unlockWrite);\n source.off('data', lockWrite);\n source.off('end', unlockWrite);\n source.off('end', lockWrite);\n });\n this.on('pipe', source => {\n if (source instanceof http_1.IncomingMessage) {\n this.options.headers = {\n ...source.headers,\n ...this.options.headers\n };\n }\n });\n const { json, body, form } = options;\n if (json || body || form) {\n this._lockWrite();\n }\n if (exports.kIsNormalizedAlready in options) {\n this.options = options;\n }\n else {\n try {\n // @ts-expect-error Common TypeScript bug saying that `this.constructor` is not accessible\n this.options = this.constructor.normalizeArguments(url, options, defaults);\n }\n catch (error) {\n // TODO: Move this to `_destroy()`\n if (is_1.default.nodeStream(options.body)) {\n options.body.destroy();\n }\n this.destroy(error);\n return;\n }\n }\n (async () => {\n var _a;\n try {\n if (this.options.body instanceof fs_1.ReadStream) {\n await waitForOpenFile(this.options.body);\n }\n const { url: normalizedURL } = this.options;\n if (!normalizedURL) {\n throw new TypeError('Missing `url` property');\n }\n this.requestUrl = normalizedURL.toString();\n decodeURI(this.requestUrl);\n await this._finalizeBody();\n await this._makeRequest();\n if (this.destroyed) {\n (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.destroy();\n return;\n }\n // Queued writes etc.\n for (const job of this[kJobs]) {\n job();\n }\n // Prevent memory leak\n this[kJobs].length = 0;\n this.requestInitialized = true;\n }\n catch (error) {\n if (error instanceof RequestError) {\n this._beforeError(error);\n return;\n }\n // This is a workaround for https://github.com/nodejs/node/issues/33335\n if (!this.destroyed) {\n this.destroy(error);\n }\n }\n })();\n }\n static normalizeArguments(url, options, defaults) {\n var _a, _b, _c, _d, _e;\n const rawOptions = options;\n if (is_1.default.object(url) && !is_1.default.urlInstance(url)) {\n options = { ...defaults, ...url, ...options };\n }\n else {\n if (url && options && options.url !== undefined) {\n throw new TypeError('The `url` option is mutually exclusive with the `input` argument');\n }\n options = { ...defaults, ...options };\n if (url !== undefined) {\n options.url = url;\n }\n if (is_1.default.urlInstance(options.url)) {\n options.url = new url_1.URL(options.url.toString());\n }\n }\n // TODO: Deprecate URL options in Got 12.\n // Support extend-specific options\n if (options.cache === false) {\n options.cache = undefined;\n }\n if (options.dnsCache === false) {\n options.dnsCache = undefined;\n }\n // Nice type assertions\n is_1.assert.any([is_1.default.string, is_1.default.undefined], options.method);\n is_1.assert.any([is_1.default.object, is_1.default.undefined], options.headers);\n is_1.assert.any([is_1.default.string, is_1.default.urlInstance, is_1.default.undefined], options.prefixUrl);\n is_1.assert.any([is_1.default.object, is_1.default.undefined], options.cookieJar);\n is_1.assert.any([is_1.default.object, is_1.default.string, is_1.default.undefined], options.searchParams);\n is_1.assert.any([is_1.default.object, is_1.default.string, is_1.default.undefined], options.cache);\n is_1.assert.any([is_1.default.object, is_1.default.number, is_1.default.undefined], options.timeout);\n is_1.assert.any([is_1.default.object, is_1.default.undefined], options.context);\n is_1.assert.any([is_1.default.object, is_1.default.undefined], options.hooks);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.decompress);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.ignoreInvalidCookies);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.followRedirect);\n is_1.assert.any([is_1.default.number, is_1.default.undefined], options.maxRedirects);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.throwHttpErrors);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.http2);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.allowGetBody);\n is_1.assert.any([is_1.default.string, is_1.default.undefined], options.localAddress);\n is_1.assert.any([dns_ip_version_1.isDnsLookupIpVersion, is_1.default.undefined], options.dnsLookupIpVersion);\n is_1.assert.any([is_1.default.object, is_1.default.undefined], options.https);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.rejectUnauthorized);\n if (options.https) {\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.https.rejectUnauthorized);\n is_1.assert.any([is_1.default.function_, is_1.default.undefined], options.https.checkServerIdentity);\n is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.certificateAuthority);\n is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.key);\n is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.certificate);\n is_1.assert.any([is_1.default.string, is_1.default.undefined], options.https.passphrase);\n is_1.assert.any([is_1.default.string, is_1.default.buffer, is_1.default.array, is_1.default.undefined], options.https.pfx);\n }\n is_1.assert.any([is_1.default.object, is_1.default.undefined], options.cacheOptions);\n // `options.method`\n if (is_1.default.string(options.method)) {\n options.method = options.method.toUpperCase();\n }\n else {\n options.method = 'GET';\n }\n // `options.headers`\n if (options.headers === (defaults === null || defaults === void 0 ? void 0 : defaults.headers)) {\n options.headers = { ...options.headers };\n }\n else {\n options.headers = lowercaseKeys({ ...(defaults === null || defaults === void 0 ? void 0 : defaults.headers), ...options.headers });\n }\n // Disallow legacy `url.Url`\n if ('slashes' in options) {\n throw new TypeError('The legacy `url.Url` has been deprecated. Use `URL` instead.');\n }\n // `options.auth`\n if ('auth' in options) {\n throw new TypeError('Parameter `auth` is deprecated. Use `username` / `password` instead.');\n }\n // `options.searchParams`\n if ('searchParams' in options) {\n if (options.searchParams && options.searchParams !== (defaults === null || defaults === void 0 ? void 0 : defaults.searchParams)) {\n let searchParameters;\n if (is_1.default.string(options.searchParams) || (options.searchParams instanceof url_1.URLSearchParams)) {\n searchParameters = new url_1.URLSearchParams(options.searchParams);\n }\n else {\n validateSearchParameters(options.searchParams);\n searchParameters = new url_1.URLSearchParams();\n // eslint-disable-next-line guard-for-in\n for (const key in options.searchParams) {\n const value = options.searchParams[key];\n if (value === null) {\n searchParameters.append(key, '');\n }\n else if (value !== undefined) {\n searchParameters.append(key, value);\n }\n }\n }\n // `normalizeArguments()` is also used to merge options\n (_a = defaults === null || defaults === void 0 ? void 0 : defaults.searchParams) === null || _a === void 0 ? void 0 : _a.forEach((value, key) => {\n // Only use default if one isn't already defined\n if (!searchParameters.has(key)) {\n searchParameters.append(key, value);\n }\n });\n options.searchParams = searchParameters;\n }\n }\n // `options.username` & `options.password`\n options.username = (_b = options.username) !== null && _b !== void 0 ? _b : '';\n options.password = (_c = options.password) !== null && _c !== void 0 ? _c : '';\n // `options.prefixUrl` & `options.url`\n if (is_1.default.undefined(options.prefixUrl)) {\n options.prefixUrl = (_d = defaults === null || defaults === void 0 ? void 0 : defaults.prefixUrl) !== null && _d !== void 0 ? _d : '';\n }\n else {\n options.prefixUrl = options.prefixUrl.toString();\n if (options.prefixUrl !== '' && !options.prefixUrl.endsWith('/')) {\n options.prefixUrl += '/';\n }\n }\n if (is_1.default.string(options.url)) {\n if (options.url.startsWith('/')) {\n throw new Error('`input` must not start with a slash when using `prefixUrl`');\n }\n options.url = options_to_url_1.default(options.prefixUrl + options.url, options);\n }\n else if ((is_1.default.undefined(options.url) && options.prefixUrl !== '') || options.protocol) {\n options.url = options_to_url_1.default(options.prefixUrl, options);\n }\n if (options.url) {\n if ('port' in options) {\n delete options.port;\n }\n // Make it possible to change `options.prefixUrl`\n let { prefixUrl } = options;\n Object.defineProperty(options, 'prefixUrl', {\n set: (value) => {\n const url = options.url;\n if (!url.href.startsWith(value)) {\n throw new Error(`Cannot change \\`prefixUrl\\` from ${prefixUrl} to ${value}: ${url.href}`);\n }\n options.url = new url_1.URL(value + url.href.slice(prefixUrl.length));\n prefixUrl = value;\n },\n get: () => prefixUrl\n });\n // Support UNIX sockets\n let { protocol } = options.url;\n if (protocol === 'unix:') {\n protocol = 'http:';\n options.url = new url_1.URL(`http://unix${options.url.pathname}${options.url.search}`);\n }\n // Set search params\n if (options.searchParams) {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n options.url.search = options.searchParams.toString();\n }\n // Protocol check\n if (protocol !== 'http:' && protocol !== 'https:') {\n throw new UnsupportedProtocolError(options);\n }\n // Update `username`\n if (options.username === '') {\n options.username = options.url.username;\n }\n else {\n options.url.username = options.username;\n }\n // Update `password`\n if (options.password === '') {\n options.password = options.url.password;\n }\n else {\n options.url.password = options.password;\n }\n }\n // `options.cookieJar`\n const { cookieJar } = options;\n if (cookieJar) {\n let { setCookie, getCookieString } = cookieJar;\n is_1.assert.function_(setCookie);\n is_1.assert.function_(getCookieString);\n /* istanbul ignore next: Horrible `tough-cookie` v3 check */\n if (setCookie.length === 4 && getCookieString.length === 0) {\n setCookie = util_1.promisify(setCookie.bind(options.cookieJar));\n getCookieString = util_1.promisify(getCookieString.bind(options.cookieJar));\n options.cookieJar = {\n setCookie,\n getCookieString: getCookieString\n };\n }\n }\n // `options.cache`\n const { cache } = options;\n if (cache) {\n if (!cacheableStore.has(cache)) {\n cacheableStore.set(cache, new CacheableRequest(((requestOptions, handler) => {\n const result = requestOptions[kRequest](requestOptions, handler);\n // TODO: remove this when `cacheable-request` supports async request functions.\n if (is_1.default.promise(result)) {\n // @ts-expect-error\n // We only need to implement the error handler in order to support HTTP2 caching.\n // The result will be a promise anyway.\n result.once = (event, handler) => {\n if (event === 'error') {\n result.catch(handler);\n }\n else if (event === 'abort') {\n // The empty catch is needed here in case when\n // it rejects before it's `await`ed in `_makeRequest`.\n (async () => {\n try {\n const request = (await result);\n request.once('abort', handler);\n }\n catch (_a) { }\n })();\n }\n else {\n /* istanbul ignore next: safety check */\n throw new Error(`Unknown HTTP2 promise event: ${event}`);\n }\n return result;\n };\n }\n return result;\n }), cache));\n }\n }\n // `options.cacheOptions`\n options.cacheOptions = { ...options.cacheOptions };\n // `options.dnsCache`\n if (options.dnsCache === true) {\n if (!globalDnsCache) {\n globalDnsCache = new cacheable_lookup_1.default();\n }\n options.dnsCache = globalDnsCache;\n }\n else if (!is_1.default.undefined(options.dnsCache) && !options.dnsCache.lookup) {\n throw new TypeError(`Parameter \\`dnsCache\\` must be a CacheableLookup instance or a boolean, got ${is_1.default(options.dnsCache)}`);\n }\n // `options.timeout`\n if (is_1.default.number(options.timeout)) {\n options.timeout = { request: options.timeout };\n }\n else if (defaults && options.timeout !== defaults.timeout) {\n options.timeout = {\n ...defaults.timeout,\n ...options.timeout\n };\n }\n else {\n options.timeout = { ...options.timeout };\n }\n // `options.context`\n if (!options.context) {\n options.context = {};\n }\n // `options.hooks`\n const areHooksDefault = options.hooks === (defaults === null || defaults === void 0 ? void 0 : defaults.hooks);\n options.hooks = { ...options.hooks };\n for (const event of exports.knownHookEvents) {\n if (event in options.hooks) {\n if (is_1.default.array(options.hooks[event])) {\n // See https://github.com/microsoft/TypeScript/issues/31445#issuecomment-576929044\n options.hooks[event] = [...options.hooks[event]];\n }\n else {\n throw new TypeError(`Parameter \\`${event}\\` must be an Array, got ${is_1.default(options.hooks[event])}`);\n }\n }\n else {\n options.hooks[event] = [];\n }\n }\n if (defaults && !areHooksDefault) {\n for (const event of exports.knownHookEvents) {\n const defaultHooks = defaults.hooks[event];\n if (defaultHooks.length > 0) {\n // See https://github.com/microsoft/TypeScript/issues/31445#issuecomment-576929044\n options.hooks[event] = [\n ...defaults.hooks[event],\n ...options.hooks[event]\n ];\n }\n }\n }\n // DNS options\n if ('family' in options) {\n deprecation_warning_1.default('\"options.family\" was never documented, please use \"options.dnsLookupIpVersion\"');\n }\n // HTTPS options\n if (defaults === null || defaults === void 0 ? void 0 : defaults.https) {\n options.https = { ...defaults.https, ...options.https };\n }\n if ('rejectUnauthorized' in options) {\n deprecation_warning_1.default('\"options.rejectUnauthorized\" is now deprecated, please use \"options.https.rejectUnauthorized\"');\n }\n if ('checkServerIdentity' in options) {\n deprecation_warning_1.default('\"options.checkServerIdentity\" was never documented, please use \"options.https.checkServerIdentity\"');\n }\n if ('ca' in options) {\n deprecation_warning_1.default('\"options.ca\" was never documented, please use \"options.https.certificateAuthority\"');\n }\n if ('key' in options) {\n deprecation_warning_1.default('\"options.key\" was never documented, please use \"options.https.key\"');\n }\n if ('cert' in options) {\n deprecation_warning_1.default('\"options.cert\" was never documented, please use \"options.https.certificate\"');\n }\n if ('passphrase' in options) {\n deprecation_warning_1.default('\"options.passphrase\" was never documented, please use \"options.https.passphrase\"');\n }\n if ('pfx' in options) {\n deprecation_warning_1.default('\"options.pfx\" was never documented, please use \"options.https.pfx\"');\n }\n // Other options\n if ('followRedirects' in options) {\n throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.');\n }\n if (options.agent) {\n for (const key in options.agent) {\n if (key !== 'http' && key !== 'https' && key !== 'http2') {\n throw new TypeError(`Expected the \\`options.agent\\` properties to be \\`http\\`, \\`https\\` or \\`http2\\`, got \\`${key}\\``);\n }\n }\n }\n options.maxRedirects = (_e = options.maxRedirects) !== null && _e !== void 0 ? _e : 0;\n // Set non-enumerable properties\n exports.setNonEnumerableProperties([defaults, rawOptions], options);\n return normalize_arguments_1.default(options, defaults);\n }\n _lockWrite() {\n const onLockedWrite = () => {\n throw new TypeError('The payload has been already provided');\n };\n this.write = onLockedWrite;\n this.end = onLockedWrite;\n }\n _unlockWrite() {\n this.write = super.write;\n this.end = super.end;\n }\n async _finalizeBody() {\n const { options } = this;\n const { headers } = options;\n const isForm = !is_1.default.undefined(options.form);\n const isJSON = !is_1.default.undefined(options.json);\n const isBody = !is_1.default.undefined(options.body);\n const hasPayload = isForm || isJSON || isBody;\n const cannotHaveBody = exports.withoutBody.has(options.method) && !(options.method === 'GET' && options.allowGetBody);\n this._cannotHaveBody = cannotHaveBody;\n if (hasPayload) {\n if (cannotHaveBody) {\n throw new TypeError(`The \\`${options.method}\\` method cannot be used with a body`);\n }\n if ([isBody, isForm, isJSON].filter(isTrue => isTrue).length > 1) {\n throw new TypeError('The `body`, `json` and `form` options are mutually exclusive');\n }\n if (isBody &&\n !(options.body instanceof stream_1.Readable) &&\n !is_1.default.string(options.body) &&\n !is_1.default.buffer(options.body) &&\n !is_form_data_1.default(options.body)) {\n throw new TypeError('The `body` option must be a stream.Readable, string or Buffer');\n }\n if (isForm && !is_1.default.object(options.form)) {\n throw new TypeError('The `form` option must be an Object');\n }\n {\n // Serialize body\n const noContentType = !is_1.default.string(headers['content-type']);\n if (isBody) {\n // Special case for https://github.com/form-data/form-data\n if (is_form_data_1.default(options.body) && noContentType) {\n headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`;\n }\n this[kBody] = options.body;\n }\n else if (isForm) {\n if (noContentType) {\n headers['content-type'] = 'application/x-www-form-urlencoded';\n }\n this[kBody] = (new url_1.URLSearchParams(options.form)).toString();\n }\n else {\n if (noContentType) {\n headers['content-type'] = 'application/json';\n }\n this[kBody] = options.stringifyJson(options.json);\n }\n const uploadBodySize = await get_body_size_1.default(this[kBody], options.headers);\n // See https://tools.ietf.org/html/rfc7230#section-3.3.2\n // A user agent SHOULD send a Content-Length in a request message when\n // no Transfer-Encoding is sent and the request method defines a meaning\n // for an enclosed payload body. For example, a Content-Length header\n // field is normally sent in a POST request even when the value is 0\n // (indicating an empty payload body). A user agent SHOULD NOT send a\n // Content-Length header field when the request message does not contain\n // a payload body and the method semantics do not anticipate such a\n // body.\n if (is_1.default.undefined(headers['content-length']) && is_1.default.undefined(headers['transfer-encoding'])) {\n if (!cannotHaveBody && !is_1.default.undefined(uploadBodySize)) {\n headers['content-length'] = String(uploadBodySize);\n }\n }\n }\n }\n else if (cannotHaveBody) {\n this._lockWrite();\n }\n else {\n this._unlockWrite();\n }\n this[kBodySize] = Number(headers['content-length']) || undefined;\n }\n async _onResponseBase(response) {\n const { options } = this;\n const { url } = options;\n this[kOriginalResponse] = response;\n if (options.decompress) {\n response = decompressResponse(response);\n }\n const statusCode = response.statusCode;\n const typedResponse = response;\n typedResponse.statusMessage = typedResponse.statusMessage ? typedResponse.statusMessage : http.STATUS_CODES[statusCode];\n typedResponse.url = options.url.toString();\n typedResponse.requestUrl = this.requestUrl;\n typedResponse.redirectUrls = this.redirects;\n typedResponse.request = this;\n typedResponse.isFromCache = response.fromCache || false;\n typedResponse.ip = this.ip;\n typedResponse.retryCount = this.retryCount;\n this[kIsFromCache] = typedResponse.isFromCache;\n this[kResponseSize] = Number(response.headers['content-length']) || undefined;\n this[kResponse] = response;\n response.once('end', () => {\n this[kResponseSize] = this[kDownloadedSize];\n this.emit('downloadProgress', this.downloadProgress);\n });\n response.once('error', (error) => {\n // Force clean-up, because some packages don't do this.\n // TODO: Fix decompress-response\n response.destroy();\n this._beforeError(new ReadError(error, this));\n });\n response.once('aborted', () => {\n this._beforeError(new ReadError({\n name: 'Error',\n message: 'The server aborted pending request',\n code: 'ECONNRESET'\n }, this));\n });\n this.emit('downloadProgress', this.downloadProgress);\n const rawCookies = response.headers['set-cookie'];\n if (is_1.default.object(options.cookieJar) && rawCookies) {\n let promises = rawCookies.map(async (rawCookie) => options.cookieJar.setCookie(rawCookie, url.toString()));\n if (options.ignoreInvalidCookies) {\n promises = promises.map(async (p) => p.catch(() => { }));\n }\n try {\n await Promise.all(promises);\n }\n catch (error) {\n this._beforeError(error);\n return;\n }\n }\n if (options.followRedirect && response.headers.location && redirectCodes.has(statusCode)) {\n // We're being redirected, we don't care about the response.\n // It'd be best to abort the request, but we can't because\n // we would have to sacrifice the TCP connection. We don't want that.\n response.resume();\n if (this[kRequest]) {\n this[kCancelTimeouts]();\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this[kRequest];\n this[kUnproxyEvents]();\n }\n const shouldBeGet = statusCode === 303 && options.method !== 'GET' && options.method !== 'HEAD';\n if (shouldBeGet || !options.methodRewriting) {\n // Server responded with \"see other\", indicating that the resource exists at another location,\n // and the client should request it from that location via GET or HEAD.\n options.method = 'GET';\n if ('body' in options) {\n delete options.body;\n }\n if ('json' in options) {\n delete options.json;\n }\n if ('form' in options) {\n delete options.form;\n }\n this[kBody] = undefined;\n delete options.headers['content-length'];\n }\n if (this.redirects.length >= options.maxRedirects) {\n this._beforeError(new MaxRedirectsError(this));\n return;\n }\n try {\n // Do not remove. See https://github.com/sindresorhus/got/pull/214\n const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString();\n // Handles invalid URLs. See https://github.com/sindresorhus/got/issues/604\n const redirectUrl = new url_1.URL(redirectBuffer, url);\n const redirectString = redirectUrl.toString();\n decodeURI(redirectString);\n // Redirecting to a different site, clear sensitive data.\n if (redirectUrl.hostname !== url.hostname || redirectUrl.port !== url.port) {\n if ('host' in options.headers) {\n delete options.headers.host;\n }\n if ('cookie' in options.headers) {\n delete options.headers.cookie;\n }\n if ('authorization' in options.headers) {\n delete options.headers.authorization;\n }\n if (options.username || options.password) {\n options.username = '';\n options.password = '';\n }\n }\n else {\n redirectUrl.username = options.username;\n redirectUrl.password = options.password;\n }\n this.redirects.push(redirectString);\n options.url = redirectUrl;\n for (const hook of options.hooks.beforeRedirect) {\n // eslint-disable-next-line no-await-in-loop\n await hook(options, typedResponse);\n }\n this.emit('redirect', typedResponse, options);\n await this._makeRequest();\n }\n catch (error) {\n this._beforeError(error);\n return;\n }\n return;\n }\n if (options.isStream && options.throwHttpErrors && !is_response_ok_1.isResponseOk(typedResponse)) {\n this._beforeError(new HTTPError(typedResponse));\n return;\n }\n response.on('readable', () => {\n if (this[kTriggerRead]) {\n this._read();\n }\n });\n this.on('resume', () => {\n response.resume();\n });\n this.on('pause', () => {\n response.pause();\n });\n response.once('end', () => {\n this.push(null);\n });\n this.emit('response', response);\n for (const destination of this[kServerResponsesPiped]) {\n if (destination.headersSent) {\n continue;\n }\n // eslint-disable-next-line guard-for-in\n for (const key in response.headers) {\n const isAllowed = options.decompress ? key !== 'content-encoding' : true;\n const value = response.headers[key];\n if (isAllowed) {\n destination.setHeader(key, value);\n }\n }\n destination.statusCode = statusCode;\n }\n }\n async _onResponse(response) {\n try {\n await this._onResponseBase(response);\n }\n catch (error) {\n /* istanbul ignore next: better safe than sorry */\n this._beforeError(error);\n }\n }\n _onRequest(request) {\n const { options } = this;\n const { timeout, url } = options;\n http_timer_1.default(request);\n this[kCancelTimeouts] = timed_out_1.default(request, timeout, url);\n const responseEventName = options.cache ? 'cacheableResponse' : 'response';\n request.once(responseEventName, (response) => {\n void this._onResponse(response);\n });\n request.once('error', (error) => {\n var _a;\n // Force clean-up, because some packages (e.g. nock) don't do this.\n request.destroy();\n // Node.js <= 12.18.2 mistakenly emits the response `end` first.\n (_a = request.res) === null || _a === void 0 ? void 0 : _a.removeAllListeners('end');\n error = error instanceof timed_out_1.TimeoutError ? new TimeoutError(error, this.timings, this) : new RequestError(error.message, error, this);\n this._beforeError(error);\n });\n this[kUnproxyEvents] = proxy_events_1.default(request, this, proxiedRequestEvents);\n this[kRequest] = request;\n this.emit('uploadProgress', this.uploadProgress);\n // Send body\n const body = this[kBody];\n const currentRequest = this.redirects.length === 0 ? this : request;\n if (is_1.default.nodeStream(body)) {\n body.pipe(currentRequest);\n body.once('error', (error) => {\n this._beforeError(new UploadError(error, this));\n });\n }\n else {\n this._unlockWrite();\n if (!is_1.default.undefined(body)) {\n this._writeRequest(body, undefined, () => { });\n currentRequest.end();\n this._lockWrite();\n }\n else if (this._cannotHaveBody || this._noPipe) {\n currentRequest.end();\n this._lockWrite();\n }\n }\n this.emit('request', request);\n }\n async _createCacheableRequest(url, options) {\n return new Promise((resolve, reject) => {\n // TODO: Remove `utils/url-to-options.ts` when `cacheable-request` is fixed\n Object.assign(options, url_to_options_1.default(url));\n // `http-cache-semantics` checks this\n // TODO: Fix this ignore.\n // @ts-expect-error\n delete options.url;\n let request;\n // This is ugly\n const cacheRequest = cacheableStore.get(options.cache)(options, async (response) => {\n // TODO: Fix `cacheable-response`\n response._readableState.autoDestroy = false;\n if (request) {\n (await request).emit('cacheableResponse', response);\n }\n resolve(response);\n });\n // Restore options\n options.url = url;\n cacheRequest.once('error', reject);\n cacheRequest.once('request', async (requestOrPromise) => {\n request = requestOrPromise;\n resolve(request);\n });\n });\n }\n async _makeRequest() {\n var _a, _b, _c, _d, _e;\n const { options } = this;\n const { headers } = options;\n for (const key in headers) {\n if (is_1.default.undefined(headers[key])) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete headers[key];\n }\n else if (is_1.default.null_(headers[key])) {\n throw new TypeError(`Use \\`undefined\\` instead of \\`null\\` to delete the \\`${key}\\` header`);\n }\n }\n if (options.decompress && is_1.default.undefined(headers['accept-encoding'])) {\n headers['accept-encoding'] = supportsBrotli ? 'gzip, deflate, br' : 'gzip, deflate';\n }\n // Set cookies\n if (options.cookieJar) {\n const cookieString = await options.cookieJar.getCookieString(options.url.toString());\n if (is_1.default.nonEmptyString(cookieString)) {\n options.headers.cookie = cookieString;\n }\n }\n for (const hook of options.hooks.beforeRequest) {\n // eslint-disable-next-line no-await-in-loop\n const result = await hook(options);\n if (!is_1.default.undefined(result)) {\n // @ts-expect-error Skip the type mismatch to support abstract responses\n options.request = () => result;\n break;\n }\n }\n if (options.body && this[kBody] !== options.body) {\n this[kBody] = options.body;\n }\n const { agent, request, timeout, url } = options;\n if (options.dnsCache && !('lookup' in options)) {\n options.lookup = options.dnsCache.lookup;\n }\n // UNIX sockets\n if (url.hostname === 'unix') {\n const matches = /(?<socketPath>.+?):(?<path>.+)/.exec(`${url.pathname}${url.search}`);\n if (matches === null || matches === void 0 ? void 0 : matches.groups) {\n const { socketPath, path } = matches.groups;\n Object.assign(options, {\n socketPath,\n path,\n host: ''\n });\n }\n }\n const isHttps = url.protocol === 'https:';\n // Fallback function\n let fallbackFn;\n if (options.http2) {\n fallbackFn = http2wrapper.auto;\n }\n else {\n fallbackFn = isHttps ? https.request : http.request;\n }\n const realFn = (_a = options.request) !== null && _a !== void 0 ? _a : fallbackFn;\n // Cache support\n const fn = options.cache ? this._createCacheableRequest : realFn;\n // Pass an agent directly when HTTP2 is disabled\n if (agent && !options.http2) {\n options.agent = agent[isHttps ? 'https' : 'http'];\n }\n // Prepare plain HTTP request options\n options[kRequest] = realFn;\n delete options.request;\n // TODO: Fix this ignore.\n // @ts-expect-error\n delete options.timeout;\n const requestOptions = options;\n requestOptions.shared = (_b = options.cacheOptions) === null || _b === void 0 ? void 0 : _b.shared;\n requestOptions.cacheHeuristic = (_c = options.cacheOptions) === null || _c === void 0 ? void 0 : _c.cacheHeuristic;\n requestOptions.immutableMinTimeToLive = (_d = options.cacheOptions) === null || _d === void 0 ? void 0 : _d.immutableMinTimeToLive;\n requestOptions.ignoreCargoCult = (_e = options.cacheOptions) === null || _e === void 0 ? void 0 : _e.ignoreCargoCult;\n // If `dnsLookupIpVersion` is not present do not override `family`\n if (options.dnsLookupIpVersion !== undefined) {\n try {\n requestOptions.family = dns_ip_version_1.dnsLookupIpVersionToFamily(options.dnsLookupIpVersion);\n }\n catch (_f) {\n throw new Error('Invalid `dnsLookupIpVersion` option value');\n }\n }\n // HTTPS options remapping\n if (options.https) {\n if ('rejectUnauthorized' in options.https) {\n requestOptions.rejectUnauthorized = options.https.rejectUnauthorized;\n }\n if (options.https.checkServerIdentity) {\n requestOptions.checkServerIdentity = options.https.checkServerIdentity;\n }\n if (options.https.certificateAuthority) {\n requestOptions.ca = options.https.certificateAuthority;\n }\n if (options.https.certificate) {\n requestOptions.cert = options.https.certificate;\n }\n if (options.https.key) {\n requestOptions.key = options.https.key;\n }\n if (options.https.passphrase) {\n requestOptions.passphrase = options.https.passphrase;\n }\n if (options.https.pfx) {\n requestOptions.pfx = options.https.pfx;\n }\n }\n try {\n let requestOrResponse = await fn(url, requestOptions);\n if (is_1.default.undefined(requestOrResponse)) {\n requestOrResponse = fallbackFn(url, requestOptions);\n }\n // Restore options\n options.request = request;\n options.timeout = timeout;\n options.agent = agent;\n // HTTPS options restore\n if (options.https) {\n if ('rejectUnauthorized' in options.https) {\n delete requestOptions.rejectUnauthorized;\n }\n if (options.https.checkServerIdentity) {\n // @ts-expect-error - This one will be removed when we remove the alias.\n delete requestOptions.checkServerIdentity;\n }\n if (options.https.certificateAuthority) {\n delete requestOptions.ca;\n }\n if (options.https.certificate) {\n delete requestOptions.cert;\n }\n if (options.https.key) {\n delete requestOptions.key;\n }\n if (options.https.passphrase) {\n delete requestOptions.passphrase;\n }\n if (options.https.pfx) {\n delete requestOptions.pfx;\n }\n }\n if (isClientRequest(requestOrResponse)) {\n this._onRequest(requestOrResponse);\n // Emit the response after the stream has been ended\n }\n else if (this.writable) {\n this.once('finish', () => {\n void this._onResponse(requestOrResponse);\n });\n this._unlockWrite();\n this.end();\n this._lockWrite();\n }\n else {\n void this._onResponse(requestOrResponse);\n }\n }\n catch (error) {\n if (error instanceof CacheableRequest.CacheError) {\n throw new CacheError(error, this);\n }\n throw new RequestError(error.message, error, this);\n }\n }\n async _error(error) {\n try {\n for (const hook of this.options.hooks.beforeError) {\n // eslint-disable-next-line no-await-in-loop\n error = await hook(error);\n }\n }\n catch (error_) {\n error = new RequestError(error_.message, error_, this);\n }\n this.destroy(error);\n }\n _beforeError(error) {\n if (this[kStopReading]) {\n return;\n }\n const { options } = this;\n const retryCount = this.retryCount + 1;\n this[kStopReading] = true;\n if (!(error instanceof RequestError)) {\n error = new RequestError(error.message, error, this);\n }\n const typedError = error;\n const { response } = typedError;\n void (async () => {\n if (response && !response.body) {\n response.setEncoding(this._readableState.encoding);\n try {\n response.rawBody = await get_buffer_1.default(response);\n response.body = response.rawBody.toString();\n }\n catch (_a) { }\n }\n if (this.listenerCount('retry') !== 0) {\n let backoff;\n try {\n let retryAfter;\n if (response && 'retry-after' in response.headers) {\n retryAfter = Number(response.headers['retry-after']);\n if (Number.isNaN(retryAfter)) {\n retryAfter = Date.parse(response.headers['retry-after']) - Date.now();\n if (retryAfter <= 0) {\n retryAfter = 1;\n }\n }\n else {\n retryAfter *= 1000;\n }\n }\n backoff = await options.retry.calculateDelay({\n attemptCount: retryCount,\n retryOptions: options.retry,\n error: typedError,\n retryAfter,\n computedValue: calculate_retry_delay_1.default({\n attemptCount: retryCount,\n retryOptions: options.retry,\n error: typedError,\n retryAfter,\n computedValue: 0\n })\n });\n }\n catch (error_) {\n void this._error(new RequestError(error_.message, error_, this));\n return;\n }\n if (backoff) {\n const retry = async () => {\n try {\n for (const hook of this.options.hooks.beforeRetry) {\n // eslint-disable-next-line no-await-in-loop\n await hook(this.options, typedError, retryCount);\n }\n }\n catch (error_) {\n void this._error(new RequestError(error_.message, error, this));\n return;\n }\n // Something forced us to abort the retry\n if (this.destroyed) {\n return;\n }\n this.destroy();\n this.emit('retry', retryCount, error);\n };\n this[kRetryTimeout] = setTimeout(retry, backoff);\n return;\n }\n }\n void this._error(typedError);\n })();\n }\n _read() {\n this[kTriggerRead] = true;\n const response = this[kResponse];\n if (response && !this[kStopReading]) {\n // We cannot put this in the `if` above\n // because `.read()` also triggers the `end` event\n if (response.readableLength) {\n this[kTriggerRead] = false;\n }\n let data;\n while ((data = response.read()) !== null) {\n this[kDownloadedSize] += data.length;\n this[kStartedReading] = true;\n const progress = this.downloadProgress;\n if (progress.percent < 1) {\n this.emit('downloadProgress', progress);\n }\n this.push(data);\n }\n }\n }\n // Node.js 12 has incorrect types, so the encoding must be a string\n _write(chunk, encoding, callback) {\n const write = () => {\n this._writeRequest(chunk, encoding, callback);\n };\n if (this.requestInitialized) {\n write();\n }\n else {\n this[kJobs].push(write);\n }\n }\n _writeRequest(chunk, encoding, callback) {\n if (this[kRequest].destroyed) {\n // Probably the `ClientRequest` instance will throw\n return;\n }\n this._progressCallbacks.push(() => {\n this[kUploadedSize] += Buffer.byteLength(chunk, encoding);\n const progress = this.uploadProgress;\n if (progress.percent < 1) {\n this.emit('uploadProgress', progress);\n }\n });\n // TODO: What happens if it's from cache? Then this[kRequest] won't be defined.\n this[kRequest].write(chunk, encoding, (error) => {\n if (!error && this._progressCallbacks.length > 0) {\n this._progressCallbacks.shift()();\n }\n callback(error);\n });\n }\n _final(callback) {\n const endRequest = () => {\n // FIX: Node.js 10 calls the write callback AFTER the end callback!\n while (this._progressCallbacks.length !== 0) {\n this._progressCallbacks.shift()();\n }\n // We need to check if `this[kRequest]` is present,\n // because it isn't when we use cache.\n if (!(kRequest in this)) {\n callback();\n return;\n }\n if (this[kRequest].destroyed) {\n callback();\n return;\n }\n this[kRequest].end((error) => {\n if (!error) {\n this[kBodySize] = this[kUploadedSize];\n this.emit('uploadProgress', this.uploadProgress);\n this[kRequest].emit('upload-complete');\n }\n callback(error);\n });\n };\n if (this.requestInitialized) {\n endRequest();\n }\n else {\n this[kJobs].push(endRequest);\n }\n }\n _destroy(error, callback) {\n var _a;\n this[kStopReading] = true;\n // Prevent further retries\n clearTimeout(this[kRetryTimeout]);\n if (kRequest in this) {\n this[kCancelTimeouts]();\n // TODO: Remove the next `if` when these get fixed:\n // - https://github.com/nodejs/node/issues/32851\n if (!((_a = this[kResponse]) === null || _a === void 0 ? void 0 : _a.complete)) {\n this[kRequest].destroy();\n }\n }\n if (error !== null && !is_1.default.undefined(error) && !(error instanceof RequestError)) {\n error = new RequestError(error.message, error, this);\n }\n callback(error);\n }\n get _isAboutToError() {\n return this[kStopReading];\n }\n /**\n The remote IP address.\n */\n get ip() {\n var _a;\n return (_a = this.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress;\n }\n /**\n Indicates whether the request has been aborted or not.\n */\n get aborted() {\n var _a, _b, _c;\n return ((_b = (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.destroyed) !== null && _b !== void 0 ? _b : this.destroyed) && !((_c = this[kOriginalResponse]) === null || _c === void 0 ? void 0 : _c.complete);\n }\n get socket() {\n var _a, _b;\n return (_b = (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.socket) !== null && _b !== void 0 ? _b : undefined;\n }\n /**\n Progress event for downloading (receiving a response).\n */\n get downloadProgress() {\n let percent;\n if (this[kResponseSize]) {\n percent = this[kDownloadedSize] / this[kResponseSize];\n }\n else if (this[kResponseSize] === this[kDownloadedSize]) {\n percent = 1;\n }\n else {\n percent = 0;\n }\n return {\n percent,\n transferred: this[kDownloadedSize],\n total: this[kResponseSize]\n };\n }\n /**\n Progress event for uploading (sending a request).\n */\n get uploadProgress() {\n let percent;\n if (this[kBodySize]) {\n percent = this[kUploadedSize] / this[kBodySize];\n }\n else if (this[kBodySize] === this[kUploadedSize]) {\n percent = 1;\n }\n else {\n percent = 0;\n }\n return {\n percent,\n transferred: this[kUploadedSize],\n total: this[kBodySize]\n };\n }\n /**\n The object contains the following properties:\n\n - `start` - Time when the request started.\n - `socket` - Time when a socket was assigned to the request.\n - `lookup` - Time when the DNS lookup finished.\n - `connect` - Time when the socket successfully connected.\n - `secureConnect` - Time when the socket securely connected.\n - `upload` - Time when the request finished uploading.\n - `response` - Time when the request fired `response` event.\n - `end` - Time when the response fired `end` event.\n - `error` - Time when the request fired `error` event.\n - `abort` - Time when the request fired `abort` event.\n - `phases`\n - `wait` - `timings.socket - timings.start`\n - `dns` - `timings.lookup - timings.socket`\n - `tcp` - `timings.connect - timings.lookup`\n - `tls` - `timings.secureConnect - timings.connect`\n - `request` - `timings.upload - (timings.secureConnect || timings.connect)`\n - `firstByte` - `timings.response - timings.upload`\n - `download` - `timings.end - timings.response`\n - `total` - `(timings.end || timings.error || timings.abort) - timings.start`\n\n If something has not been measured yet, it will be `undefined`.\n\n __Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch.\n */\n get timings() {\n var _a;\n return (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.timings;\n }\n /**\n Whether the response was retrieved from the cache.\n */\n get isFromCache() {\n return this[kIsFromCache];\n }\n pipe(destination, options) {\n if (this[kStartedReading]) {\n throw new Error('Failed to pipe. The response has been emitted already.');\n }\n if (destination instanceof http_1.ServerResponse) {\n this[kServerResponsesPiped].add(destination);\n }\n return super.pipe(destination, options);\n }\n unpipe(destination) {\n if (destination instanceof http_1.ServerResponse) {\n this[kServerResponsesPiped].delete(destination);\n }\n super.unpipe(destination);\n return this;\n }\n}\nexports.default = Request;\n", "\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CancelError = exports.ParseError = void 0;\nconst core_1 = require(\"../core\");\n/**\nAn error to be thrown when server response code is 2xx, and parsing body fails.\nIncludes a `response` property.\n*/\nclass ParseError extends core_1.RequestError {\n constructor(error, response) {\n const { options } = response.request;\n super(`${error.message} in \"${options.url.toString()}\"`, error, response.request);\n this.name = 'ParseError';\n }\n}\nexports.ParseError = ParseError;\n/**\nAn error to be thrown when the request is aborted with `.cancel()`.\n*/\nclass CancelError extends core_1.RequestError {\n constructor(request) {\n super('Promise was canceled', {}, request);\n this.name = 'CancelError';\n }\n get isCanceled() {\n return true;\n }\n}\nexports.CancelError = CancelError;\n__exportStar(require(\"../core\"), exports);\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst types_1 = require(\"./types\");\nconst parseBody = (response, responseType, parseJson, encoding) => {\n const { rawBody } = response;\n try {\n if (responseType === 'text') {\n return rawBody.toString(encoding);\n }\n if (responseType === 'json') {\n return rawBody.length === 0 ? '' : parseJson(rawBody.toString());\n }\n if (responseType === 'buffer') {\n return rawBody;\n }\n throw new types_1.ParseError({\n message: `Unknown body type '${responseType}'`,\n name: 'Error'\n }, response);\n }\n catch (error) {\n throw new types_1.ParseError(error, response);\n }\n};\nexports.default = parseBody;\n", "\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst events_1 = require(\"events\");\nconst is_1 = require(\"@sindresorhus/is\");\nconst PCancelable = require(\"p-cancelable\");\nconst types_1 = require(\"./types\");\nconst parse_body_1 = require(\"./parse-body\");\nconst core_1 = require(\"../core\");\nconst proxy_events_1 = require(\"../core/utils/proxy-events\");\nconst get_buffer_1 = require(\"../core/utils/get-buffer\");\nconst is_response_ok_1 = require(\"../core/utils/is-response-ok\");\nconst proxiedRequestEvents = [\n 'request',\n 'response',\n 'redirect',\n 'uploadProgress',\n 'downloadProgress'\n];\nfunction asPromise(normalizedOptions) {\n let globalRequest;\n let globalResponse;\n const emitter = new events_1.EventEmitter();\n const promise = new PCancelable((resolve, reject, onCancel) => {\n const makeRequest = (retryCount) => {\n const request = new core_1.default(undefined, normalizedOptions);\n request.retryCount = retryCount;\n request._noPipe = true;\n onCancel(() => request.destroy());\n onCancel.shouldReject = false;\n onCancel(() => reject(new types_1.CancelError(request)));\n globalRequest = request;\n request.once('response', async (response) => {\n var _a;\n response.retryCount = retryCount;\n if (response.request.aborted) {\n // Canceled while downloading - will throw a `CancelError` or `TimeoutError` error\n return;\n }\n // Download body\n let rawBody;\n try {\n rawBody = await get_buffer_1.default(request);\n response.rawBody = rawBody;\n }\n catch (_b) {\n // The same error is caught below.\n // See request.once('error')\n return;\n }\n if (request._isAboutToError) {\n return;\n }\n // Parse body\n const contentEncoding = ((_a = response.headers['content-encoding']) !== null && _a !== void 0 ? _a : '').toLowerCase();\n const isCompressed = ['gzip', 'deflate', 'br'].includes(contentEncoding);\n const { options } = request;\n if (isCompressed && !options.decompress) {\n response.body = rawBody;\n }\n else {\n try {\n response.body = parse_body_1.default(response, options.responseType, options.parseJson, options.encoding);\n }\n catch (error) {\n // Fallback to `utf8`\n response.body = rawBody.toString();\n if (is_response_ok_1.isResponseOk(response)) {\n request._beforeError(error);\n return;\n }\n }\n }\n try {\n for (const [index, hook] of options.hooks.afterResponse.entries()) {\n // @ts-expect-error TS doesn't notice that CancelableRequest is a Promise\n // eslint-disable-next-line no-await-in-loop\n response = await hook(response, async (updatedOptions) => {\n const typedOptions = core_1.default.normalizeArguments(undefined, {\n ...updatedOptions,\n retry: {\n calculateDelay: () => 0\n },\n throwHttpErrors: false,\n resolveBodyOnly: false\n }, options);\n // Remove any further hooks for that request, because we'll call them anyway.\n // The loop continues. We don't want duplicates (asPromise recursion).\n typedOptions.hooks.afterResponse = typedOptions.hooks.afterResponse.slice(0, index);\n for (const hook of typedOptions.hooks.beforeRetry) {\n // eslint-disable-next-line no-await-in-loop\n await hook(typedOptions);\n }\n const promise = asPromise(typedOptions);\n onCancel(() => {\n promise.catch(() => { });\n promise.cancel();\n });\n return promise;\n });\n }\n }\n catch (error) {\n request._beforeError(new types_1.RequestError(error.message, error, request));\n return;\n }\n if (!is_response_ok_1.isResponseOk(response)) {\n request._beforeError(new types_1.HTTPError(response));\n return;\n }\n globalResponse = response;\n resolve(request.options.resolveBodyOnly ? response.body : response);\n });\n const onError = (error) => {\n if (promise.isCanceled) {\n return;\n }\n const { options } = request;\n if (error instanceof types_1.HTTPError && !options.throwHttpErrors) {\n const { response } = error;\n resolve(request.options.resolveBodyOnly ? response.body : response);\n return;\n }\n reject(error);\n };\n request.once('error', onError);\n const previousBody = request.options.body;\n request.once('retry', (newRetryCount, error) => {\n var _a, _b;\n if (previousBody === ((_a = error.request) === null || _a === void 0 ? void 0 : _a.options.body) && is_1.default.nodeStream((_b = error.request) === null || _b === void 0 ? void 0 : _b.options.body)) {\n onError(error);\n return;\n }\n makeRequest(newRetryCount);\n });\n proxy_events_1.default(request, emitter, proxiedRequestEvents);\n };\n makeRequest(0);\n });\n promise.on = (event, fn) => {\n emitter.on(event, fn);\n return promise;\n };\n const shortcut = (responseType) => {\n const newPromise = (async () => {\n // Wait until downloading has ended\n await promise;\n const { options } = globalResponse.request;\n return parse_body_1.default(globalResponse, responseType, options.parseJson, options.encoding);\n })();\n Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise));\n return newPromise;\n };\n promise.json = () => {\n const { headers } = globalRequest.options;\n if (!globalRequest.writableFinished && headers.accept === undefined) {\n headers.accept = 'application/json';\n }\n return shortcut('json');\n };\n promise.buffer = () => shortcut('buffer');\n promise.text = () => shortcut('text');\n return promise;\n}\nexports.default = asPromise;\n__exportStar(require(\"./types\"), exports);\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst types_1 = require(\"./types\");\nfunction createRejection(error, ...beforeErrorGroups) {\n const promise = (async () => {\n if (error instanceof types_1.RequestError) {\n try {\n for (const hooks of beforeErrorGroups) {\n if (hooks) {\n for (const hook of hooks) {\n // eslint-disable-next-line no-await-in-loop\n error = await hook(error);\n }\n }\n }\n }\n catch (error_) {\n error = error_;\n }\n }\n throw error;\n })();\n const returnPromise = () => promise;\n promise.json = returnPromise;\n promise.text = returnPromise;\n promise.buffer = returnPromise;\n promise.on = returnPromise;\n return promise;\n}\nexports.default = createRejection;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst is_1 = require(\"@sindresorhus/is\");\nfunction deepFreeze(object) {\n for (const value of Object.values(object)) {\n if (is_1.default.plainObject(value) || is_1.default.array(value)) {\n deepFreeze(value);\n }\n }\n return Object.freeze(object);\n}\nexports.default = deepFreeze;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n", "\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.defaultHandler = void 0;\nconst is_1 = require(\"@sindresorhus/is\");\nconst as_promise_1 = require(\"./as-promise\");\nconst create_rejection_1 = require(\"./as-promise/create-rejection\");\nconst core_1 = require(\"./core\");\nconst deep_freeze_1 = require(\"./utils/deep-freeze\");\nconst errors = {\n RequestError: as_promise_1.RequestError,\n CacheError: as_promise_1.CacheError,\n ReadError: as_promise_1.ReadError,\n HTTPError: as_promise_1.HTTPError,\n MaxRedirectsError: as_promise_1.MaxRedirectsError,\n TimeoutError: as_promise_1.TimeoutError,\n ParseError: as_promise_1.ParseError,\n CancelError: as_promise_1.CancelError,\n UnsupportedProtocolError: as_promise_1.UnsupportedProtocolError,\n UploadError: as_promise_1.UploadError\n};\n// The `delay` package weighs 10KB (!)\nconst delay = async (ms) => new Promise(resolve => {\n setTimeout(resolve, ms);\n});\nconst { normalizeArguments } = core_1.default;\nconst mergeOptions = (...sources) => {\n let mergedOptions;\n for (const source of sources) {\n mergedOptions = normalizeArguments(undefined, source, mergedOptions);\n }\n return mergedOptions;\n};\nconst getPromiseOrStream = (options) => options.isStream ? new core_1.default(undefined, options) : as_promise_1.default(options);\nconst isGotInstance = (value) => ('defaults' in value && 'options' in value.defaults);\nconst aliases = [\n 'get',\n 'post',\n 'put',\n 'patch',\n 'head',\n 'delete'\n];\nexports.defaultHandler = (options, next) => next(options);\nconst callInitHooks = (hooks, options) => {\n if (hooks) {\n for (const hook of hooks) {\n hook(options);\n }\n }\n};\nconst create = (defaults) => {\n // Proxy properties from next handlers\n defaults._rawHandlers = defaults.handlers;\n defaults.handlers = defaults.handlers.map(fn => ((options, next) => {\n // This will be assigned by assigning result\n let root;\n const result = fn(options, newOptions => {\n root = next(newOptions);\n return root;\n });\n if (result !== root && !options.isStream && root) {\n const typedResult = result;\n const { then: promiseThen, catch: promiseCatch, finally: promiseFianlly } = typedResult;\n Object.setPrototypeOf(typedResult, Object.getPrototypeOf(root));\n Object.defineProperties(typedResult, Object.getOwnPropertyDescriptors(root));\n // These should point to the new promise\n // eslint-disable-next-line promise/prefer-await-to-then\n typedResult.then = promiseThen;\n typedResult.catch = promiseCatch;\n typedResult.finally = promiseFianlly;\n }\n return result;\n }));\n // Got interface\n const got = ((url, options = {}, _defaults) => {\n var _a, _b;\n let iteration = 0;\n const iterateHandlers = (newOptions) => {\n return defaults.handlers[iteration++](newOptions, iteration === defaults.handlers.length ? getPromiseOrStream : iterateHandlers);\n };\n // TODO: Remove this in Got 12.\n if (is_1.default.plainObject(url)) {\n const mergedOptions = {\n ...url,\n ...options\n };\n core_1.setNonEnumerableProperties([url, options], mergedOptions);\n options = mergedOptions;\n url = undefined;\n }\n try {\n // Call `init` hooks\n let initHookError;\n try {\n callInitHooks(defaults.options.hooks.init, options);\n callInitHooks((_a = options.hooks) === null || _a === void 0 ? void 0 : _a.init, options);\n }\n catch (error) {\n initHookError = error;\n }\n // Normalize options & call handlers\n const normalizedOptions = normalizeArguments(url, options, _defaults !== null && _defaults !== void 0 ? _defaults : defaults.options);\n normalizedOptions[core_1.kIsNormalizedAlready] = true;\n if (initHookError) {\n throw new as_promise_1.RequestError(initHookError.message, initHookError, normalizedOptions);\n }\n return iterateHandlers(normalizedOptions);\n }\n catch (error) {\n if (options.isStream) {\n throw error;\n }\n else {\n return create_rejection_1.default(error, defaults.options.hooks.beforeError, (_b = options.hooks) === null || _b === void 0 ? void 0 : _b.beforeError);\n }\n }\n });\n got.extend = (...instancesOrOptions) => {\n const optionsArray = [defaults.options];\n let handlers = [...defaults._rawHandlers];\n let isMutableDefaults;\n for (const value of instancesOrOptions) {\n if (isGotInstance(value)) {\n optionsArray.push(value.defaults.options);\n handlers.push(...value.defaults._rawHandlers);\n isMutableDefaults = value.defaults.mutableDefaults;\n }\n else {\n optionsArray.push(value);\n if ('handlers' in value) {\n handlers.push(...value.handlers);\n }\n isMutableDefaults = value.mutableDefaults;\n }\n }\n handlers = handlers.filter(handler => handler !== exports.defaultHandler);\n if (handlers.length === 0) {\n handlers.push(exports.defaultHandler);\n }\n return create({\n options: mergeOptions(...optionsArray),\n handlers,\n mutableDefaults: Boolean(isMutableDefaults)\n });\n };\n // Pagination\n const paginateEach = (async function* (url, options) {\n // TODO: Remove this `@ts-expect-error` when upgrading to TypeScript 4.\n // Error: Argument of type 'Merge<Options, PaginationOptions<T, R>> | undefined' is not assignable to parameter of type 'Options | undefined'.\n // @ts-expect-error\n let normalizedOptions = normalizeArguments(url, options, defaults.options);\n normalizedOptions.resolveBodyOnly = false;\n const pagination = normalizedOptions.pagination;\n if (!is_1.default.object(pagination)) {\n throw new TypeError('`options.pagination` must be implemented');\n }\n const all = [];\n let { countLimit } = pagination;\n let numberOfRequests = 0;\n while (numberOfRequests < pagination.requestLimit) {\n if (numberOfRequests !== 0) {\n // eslint-disable-next-line no-await-in-loop\n await delay(pagination.backoff);\n }\n // @ts-expect-error FIXME!\n // TODO: Throw when result is not an instance of Response\n // eslint-disable-next-line no-await-in-loop\n const result = (await got(undefined, undefined, normalizedOptions));\n // eslint-disable-next-line no-await-in-loop\n const parsed = await pagination.transform(result);\n const current = [];\n for (const item of parsed) {\n if (pagination.filter(item, all, current)) {\n if (!pagination.shouldContinue(item, all, current)) {\n return;\n }\n yield item;\n if (pagination.stackAllItems) {\n all.push(item);\n }\n current.push(item);\n if (--countLimit <= 0) {\n return;\n }\n }\n }\n const optionsToMerge = pagination.paginate(result, all, current);\n if (optionsToMerge === false) {\n return;\n }\n if (optionsToMerge === result.request.options) {\n normalizedOptions = result.request.options;\n }\n else if (optionsToMerge !== undefined) {\n normalizedOptions = normalizeArguments(undefined, optionsToMerge, normalizedOptions);\n }\n numberOfRequests++;\n }\n });\n got.paginate = paginateEach;\n got.paginate.all = (async (url, options) => {\n const results = [];\n for await (const item of paginateEach(url, options)) {\n results.push(item);\n }\n return results;\n });\n // For those who like very descriptive names\n got.paginate.each = paginateEach;\n // Stream API\n got.stream = ((url, options) => got(url, { ...options, isStream: true }));\n // Shortcuts\n for (const method of aliases) {\n got[method] = ((url, options) => got(url, { ...options, method }));\n got.stream[method] = ((url, options) => {\n return got(url, { ...options, method, isStream: true });\n });\n }\n Object.assign(got, errors);\n Object.defineProperty(got, 'defaults', {\n value: defaults.mutableDefaults ? defaults : deep_freeze_1.default(defaults),\n writable: defaults.mutableDefaults,\n configurable: defaults.mutableDefaults,\n enumerable: true\n });\n got.mergeOptions = mergeOptions;\n return got;\n};\nexports.default = create;\n__exportStar(require(\"./types\"), exports);\n", "\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst url_1 = require(\"url\");\nconst create_1 = require(\"./create\");\nconst defaults = {\n options: {\n method: 'GET',\n retry: {\n limit: 2,\n methods: [\n 'GET',\n 'PUT',\n 'HEAD',\n 'DELETE',\n 'OPTIONS',\n 'TRACE'\n ],\n statusCodes: [\n 408,\n 413,\n 429,\n 500,\n 502,\n 503,\n 504,\n 521,\n 522,\n 524\n ],\n errorCodes: [\n 'ETIMEDOUT',\n 'ECONNRESET',\n 'EADDRINUSE',\n 'ECONNREFUSED',\n 'EPIPE',\n 'ENOTFOUND',\n 'ENETUNREACH',\n 'EAI_AGAIN'\n ],\n maxRetryAfter: undefined,\n calculateDelay: ({ computedValue }) => computedValue\n },\n timeout: {},\n headers: {\n 'user-agent': 'got (https://github.com/sindresorhus/got)'\n },\n hooks: {\n init: [],\n beforeRequest: [],\n beforeRedirect: [],\n beforeRetry: [],\n beforeError: [],\n afterResponse: []\n },\n cache: undefined,\n dnsCache: undefined,\n decompress: true,\n throwHttpErrors: true,\n followRedirect: true,\n isStream: false,\n responseType: 'text',\n resolveBodyOnly: false,\n maxRedirects: 10,\n prefixUrl: '',\n methodRewriting: true,\n ignoreInvalidCookies: false,\n context: {},\n // TODO: Set this to `true` when Got 12 gets released\n http2: false,\n allowGetBody: false,\n https: undefined,\n pagination: {\n transform: (response) => {\n if (response.request.options.responseType === 'json') {\n return response.body;\n }\n return JSON.parse(response.body);\n },\n paginate: response => {\n if (!Reflect.has(response.headers, 'link')) {\n return false;\n }\n const items = response.headers.link.split(',');\n let next;\n for (const item of items) {\n const parsed = item.split(';');\n if (parsed[1].includes('next')) {\n next = parsed[0].trimStart().trim();\n next = next.slice(1, -1);\n break;\n }\n }\n if (next) {\n const options = {\n url: new url_1.URL(next)\n };\n return options;\n }\n return false;\n },\n filter: () => true,\n shouldContinue: () => true,\n countLimit: Infinity,\n backoff: 0,\n requestLimit: 10000,\n stackAllItems: true\n },\n parseJson: (text) => JSON.parse(text),\n stringifyJson: (object) => JSON.stringify(object),\n cacheOptions: {}\n },\n handlers: [create_1.defaultHandler],\n mutableDefaults: false\n};\nconst got = create_1.default(defaults);\nexports.default = got;\n// For CommonJS default export support\nmodule.exports = got;\nmodule.exports.default = got;\nmodule.exports.__esModule = true; // Workaround for TS issue: https://github.com/sindresorhus/got/pull/1267\n__exportStar(require(\"./create\"), exports);\n__exportStar(require(\"./as-promise\"), exports);\n", "'use strict'\n\nfunction isFunction (funktion) {\n return typeof funktion === 'function'\n}\n\n// Default to complaining loudly when things don't go according to plan.\nvar logger = console.error.bind(console)\n\n// Sets a property on an object, preserving its enumerability.\n// This function assumes that the property is already writable.\nfunction defineProperty (obj, name, value) {\n var enumerable = !!obj[name] && obj.propertyIsEnumerable(name)\n Object.defineProperty(obj, name, {\n configurable: true,\n enumerable: enumerable,\n writable: true,\n value: value\n })\n}\n\n// Keep initialization idempotent.\nfunction shimmer (options) {\n if (options && options.logger) {\n if (!isFunction(options.logger)) logger(\"new logger isn't a function, not replacing\")\n else logger = options.logger\n }\n}\n\nfunction wrap (nodule, name, wrapper) {\n if (!nodule || !nodule[name]) {\n logger('no original function ' + name + ' to wrap')\n return\n }\n\n if (!wrapper) {\n logger('no wrapper function')\n logger((new Error()).stack)\n return\n }\n\n if (!isFunction(nodule[name]) || !isFunction(wrapper)) {\n logger('original object and wrapper must be functions')\n return\n }\n\n var original = nodule[name]\n var wrapped = wrapper(original, name)\n\n defineProperty(wrapped, '__original', original)\n defineProperty(wrapped, '__unwrap', function () {\n if (nodule[name] === wrapped) defineProperty(nodule, name, original)\n })\n defineProperty(wrapped, '__wrapped', true)\n\n defineProperty(nodule, name, wrapped)\n return wrapped\n}\n\nfunction massWrap (nodules, names, wrapper) {\n if (!nodules) {\n logger('must provide one or more modules to patch')\n logger((new Error()).stack)\n return\n } else if (!Array.isArray(nodules)) {\n nodules = [nodules]\n }\n\n if (!(names && Array.isArray(names))) {\n logger('must provide one or more functions to wrap on modules')\n return\n }\n\n nodules.forEach(function (nodule) {\n names.forEach(function (name) {\n wrap(nodule, name, wrapper)\n })\n })\n}\n\nfunction unwrap (nodule, name) {\n if (!nodule || !nodule[name]) {\n logger('no function to unwrap.')\n logger((new Error()).stack)\n return\n }\n\n if (!nodule[name].__unwrap) {\n logger('no original to unwrap to -- has ' + name + ' already been unwrapped?')\n } else {\n return nodule[name].__unwrap()\n }\n}\n\nfunction massUnwrap (nodules, names) {\n if (!nodules) {\n logger('must provide one or more modules to patch')\n logger((new Error()).stack)\n return\n } else if (!Array.isArray(nodules)) {\n nodules = [nodules]\n }\n\n if (!(names && Array.isArray(names))) {\n logger('must provide one or more functions to unwrap on modules')\n return\n }\n\n nodules.forEach(function (nodule) {\n names.forEach(function (name) {\n unwrap(nodule, name)\n })\n })\n}\n\nshimmer.wrap = wrap\nshimmer.massWrap = massWrap\nshimmer.unwrap = unwrap\nshimmer.massUnwrap = massUnwrap\n\nmodule.exports = shimmer\n", "'use strict';\n\nvar shimmer = require('shimmer');\nvar wrap = shimmer.wrap;\nvar unwrap = shimmer.unwrap;\n\n// Default to complaining loudly when things don't go according to plan.\n// dunderscores are boring\nvar SYMBOL = 'wrap@before';\n\n// Sets a property on an object, preserving its enumerability.\n// This function assumes that the property is already writable.\nfunction defineProperty(obj, name, value) {\n var enumerable = !!obj[name] && obj.propertyIsEnumerable(name);\n Object.defineProperty(obj, name, {\n configurable: true,\n enumerable: enumerable,\n writable: true,\n value: value\n });\n}\n\nfunction _process(self, listeners) {\n var l = listeners.length;\n for (var p = 0; p < l; p++) {\n var listener = listeners[p];\n // set up the listener so that onEmit can do whatever it needs\n var before = self[SYMBOL];\n if (typeof before === 'function') {\n before(listener);\n }\n else if (Array.isArray(before)) {\n var length = before.length;\n for (var i = 0; i < length; i++) before[i](listener);\n }\n }\n}\n\nfunction _listeners(self, event) {\n var listeners;\n listeners = self._events && self._events[event];\n if (!Array.isArray(listeners)) {\n if (listeners) {\n listeners = [listeners];\n }\n else {\n listeners = [];\n }\n }\n\n return listeners;\n}\n\nfunction _findAndProcess(self, event, before) {\n var after = _listeners(self, event);\n var unprocessed = after.filter(function(fn) { return before.indexOf(fn) === -1; });\n if (unprocessed.length > 0) _process(self, unprocessed);\n}\n\nfunction _wrap(unwrapped, visit) {\n if (!unwrapped) return;\n\n var wrapped = unwrapped;\n if (typeof unwrapped === 'function') {\n wrapped = visit(unwrapped);\n }\n else if (Array.isArray(unwrapped)) {\n wrapped = [];\n for (var i = 0; i < unwrapped.length; i++) {\n wrapped[i] = visit(unwrapped[i]);\n }\n }\n return wrapped;\n}\n\nmodule.exports = function wrapEmitter(emitter, onAddListener, onEmit) {\n if (!emitter || !emitter.on || !emitter.addListener ||\n !emitter.removeListener || !emitter.emit) {\n throw new Error(\"can only wrap real EEs\");\n }\n\n if (!onAddListener) throw new Error(\"must have function to run on listener addition\");\n if (!onEmit) throw new Error(\"must have function to wrap listeners when emitting\");\n\n /* Attach a context to a listener, and make sure that this hook stays\n * attached to the emitter forevermore.\n */\n function adding(on) {\n return function added(event, listener) {\n var existing = _listeners(this, event).slice();\n\n try {\n var returned = on.call(this, event, listener);\n _findAndProcess(this, event, existing);\n return returned;\n }\n finally {\n // old-style streaming overwrites .on and .addListener, so rewrap\n if (!this.on.__wrapped) wrap(this, 'on', adding);\n if (!this.addListener.__wrapped) wrap(this, 'addListener', adding);\n }\n };\n }\n\n function emitting(emit) {\n return function emitted(event) {\n if (!this._events || !this._events[event]) return emit.apply(this, arguments);\n\n var unwrapped = this._events[event];\n\n /* Ensure that if removeListener gets called, it's working with the\n * unwrapped listeners.\n */\n function remover(removeListener) {\n return function removed() {\n this._events[event] = unwrapped;\n try {\n return removeListener.apply(this, arguments);\n }\n finally {\n unwrapped = this._events[event];\n this._events[event] = _wrap(unwrapped, onEmit);\n }\n };\n }\n wrap(this, 'removeListener', remover);\n\n try {\n /* At emit time, ensure that whatever else is going on, removeListener will\n * still work while at the same time running whatever hooks are necessary to\n * make sure the listener is run in the correct context.\n */\n this._events[event] = _wrap(unwrapped, onEmit);\n return emit.apply(this, arguments);\n }\n finally {\n /* Ensure that regardless of what happens when preparing and running the\n * listeners, the status quo ante is restored before continuing.\n */\n unwrap(this, 'removeListener');\n this._events[event] = unwrapped;\n }\n };\n }\n\n // support multiple onAddListeners\n if (!emitter[SYMBOL]) {\n defineProperty(emitter, SYMBOL, onAddListener);\n }\n else if (typeof emitter[SYMBOL] === 'function') {\n defineProperty(emitter, SYMBOL, [emitter[SYMBOL], onAddListener]);\n }\n else if (Array.isArray(emitter[SYMBOL])) {\n emitter[SYMBOL].push(onAddListener);\n }\n\n // only wrap the core functions once\n if (!emitter.__wrapped) {\n wrap(emitter, 'addListener', adding);\n wrap(emitter, 'on', adding);\n wrap(emitter, 'emit', emitting);\n\n defineProperty(emitter, '__unwrap', function () {\n unwrap(emitter, 'addListener');\n unwrap(emitter, 'on');\n unwrap(emitter, 'emit');\n delete emitter[SYMBOL];\n delete emitter.__wrapped;\n });\n defineProperty(emitter, '__wrapped', true);\n }\n};\n", "/* eslint-disable max-len */\n'use strict';\n\nconst util = require('util');\nconst assert = require('assert');\nconst wrapEmitter = require('emitter-listener');\nconst async_hooks = require('async_hooks');\n\nconst CONTEXTS_SYMBOL = 'cls@contexts';\nconst ERROR_SYMBOL = 'error@context';\n\nconst DEBUG_CLS_HOOKED = process.env.DEBUG_CLS_HOOKED;\n\nlet currentUid = -1;\n\nmodule.exports = {\n getNamespace: getNamespace,\n createNamespace: createNamespace,\n destroyNamespace: destroyNamespace,\n reset: reset,\n ERROR_SYMBOL: ERROR_SYMBOL\n};\n\nfunction Namespace(name) {\n this.name = name;\n // changed in 2.7: no default context\n this.active = null;\n this._set = [];\n this.id = null;\n this._contexts = new Map();\n this._indent = 0;\n}\n\nNamespace.prototype.set = function set(key, value) {\n if (!this.active) {\n throw new Error('No context available. ns.run() or ns.bind() must be called first.');\n }\n\n this.active[key] = value;\n\n if (DEBUG_CLS_HOOKED) {\n const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent);\n debug2(indentStr + 'CONTEXT-SET KEY:' + key + '=' + value + ' in ns:' + this.name + ' currentUid:' + currentUid + ' active:' + util.inspect(this.active, {showHidden:true, depth:2, colors:true}));\n }\n\n return value;\n};\n\nNamespace.prototype.get = function get(key) {\n if (!this.active) {\n if (DEBUG_CLS_HOOKED) {\n const asyncHooksCurrentId = async_hooks.currentId();\n const triggerId = async_hooks.triggerAsyncId();\n const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent);\n //debug2(indentStr + 'CONTEXT-GETTING KEY NO ACTIVE NS:' + key + '=undefined' + ' (' + this.name + ') currentUid:' + currentUid + ' active:' + util.inspect(this.active, {showHidden:true, depth:2, colors:true}));\n debug2(`${indentStr}CONTEXT-GETTING KEY NO ACTIVE NS: (${this.name}) ${key}=undefined currentUid:${currentUid} asyncHooksCurrentId:${asyncHooksCurrentId} triggerId:${triggerId} len:${this._set.length}`);\n }\n return undefined;\n }\n if (DEBUG_CLS_HOOKED) {\n const asyncHooksCurrentId = async_hooks.executionAsyncId();\n const triggerId = async_hooks.triggerAsyncId();\n const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent);\n debug2(indentStr + 'CONTEXT-GETTING KEY:' + key + '=' + this.active[key] + ' (' + this.name + ') currentUid:' + currentUid + ' active:' + util.inspect(this.active, {showHidden:true, depth:2, colors:true}));\n debug2(`${indentStr}CONTEXT-GETTING KEY: (${this.name}) ${key}=${this.active[key]} currentUid:${currentUid} asyncHooksCurrentId:${asyncHooksCurrentId} triggerId:${triggerId} len:${this._set.length} active:${util.inspect(this.active)}`);\n }\n return this.active[key];\n};\n\nNamespace.prototype.createContext = function createContext() {\n // Prototype inherit existing context if created a new child context within existing context.\n let context = Object.create(this.active ? this.active : Object.prototype);\n context._ns_name = this.name;\n context.id = currentUid;\n\n if (DEBUG_CLS_HOOKED) {\n const asyncHooksCurrentId = async_hooks.executionAsyncId();\n const triggerId = async_hooks.triggerAsyncId();\n const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent);\n debug2(`${indentStr}CONTEXT-CREATED Context: (${this.name}) currentUid:${currentUid} asyncHooksCurrentId:${asyncHooksCurrentId} triggerId:${triggerId} len:${this._set.length} context:${util.inspect(context, {showHidden:true, depth:2, colors:true})}`);\n }\n\n return context;\n};\n\nNamespace.prototype.run = function run(fn) {\n let context = this.createContext();\n this.enter(context);\n\n try {\n if (DEBUG_CLS_HOOKED) {\n const triggerId = async_hooks.triggerAsyncId();\n const asyncHooksCurrentId = async_hooks.executionAsyncId();\n const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent);\n debug2(`${indentStr}CONTEXT-RUN BEGIN: (${this.name}) currentUid:${currentUid} triggerId:${triggerId} asyncHooksCurrentId:${asyncHooksCurrentId} len:${this._set.length} context:${util.inspect(context)}`);\n }\n fn(context);\n return context;\n } catch (exception) {\n if (exception) {\n exception[ERROR_SYMBOL] = context;\n }\n throw exception;\n } finally {\n if (DEBUG_CLS_HOOKED) {\n const triggerId = async_hooks.triggerAsyncId();\n const asyncHooksCurrentId = async_hooks.executionAsyncId();\n const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent);\n debug2(`${indentStr}CONTEXT-RUN END: (${this.name}) currentUid:${currentUid} triggerId:${triggerId} asyncHooksCurrentId:${asyncHooksCurrentId} len:${this._set.length} ${util.inspect(context)}`);\n }\n this.exit(context);\n }\n};\n\nNamespace.prototype.runAndReturn = function runAndReturn(fn) {\n let value;\n this.run(function (context) {\n value = fn(context);\n });\n return value;\n};\n\n/**\n * Uses global Promise and assumes Promise is cls friendly or wrapped already.\n * @param {function} fn\n * @returns {*}\n */\nNamespace.prototype.runPromise = function runPromise(fn) {\n let context = this.createContext();\n this.enter(context);\n\n let promise = fn(context);\n if (!promise || !promise.then || !promise.catch) {\n throw new Error('fn must return a promise.');\n }\n\n if (DEBUG_CLS_HOOKED) {\n debug2('CONTEXT-runPromise BEFORE: (' + this.name + ') currentUid:' + currentUid + ' len:' + this._set.length + ' ' + util.inspect(context));\n }\n\n return promise\n .then(result => {\n if (DEBUG_CLS_HOOKED) {\n debug2('CONTEXT-runPromise AFTER then: (' + this.name + ') currentUid:' + currentUid + ' len:' + this._set.length + ' ' + util.inspect(context));\n }\n this.exit(context);\n return result;\n })\n .catch(err => {\n err[ERROR_SYMBOL] = context;\n if (DEBUG_CLS_HOOKED) {\n debug2('CONTEXT-runPromise AFTER catch: (' + this.name + ') currentUid:' + currentUid + ' len:' + this._set.length + ' ' + util.inspect(context));\n }\n this.exit(context);\n throw err;\n });\n};\n\nNamespace.prototype.bind = function bindFactory(fn, context) {\n if (!context) {\n if (!this.active) {\n context = this.createContext();\n } else {\n context = this.active;\n }\n }\n\n let self = this;\n return function clsBind() {\n self.enter(context);\n try {\n return fn.apply(this, arguments);\n } catch (exception) {\n if (exception) {\n exception[ERROR_SYMBOL] = context;\n }\n throw exception;\n } finally {\n self.exit(context);\n }\n };\n};\n\nNamespace.prototype.enter = function enter(context) {\n assert.ok(context, 'context must be provided for entering');\n if (DEBUG_CLS_HOOKED) {\n const asyncHooksCurrentId = async_hooks.executionAsyncId();\n const triggerId = async_hooks.triggerAsyncId();\n const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent);\n debug2(`${indentStr}CONTEXT-ENTER: (${this.name}) currentUid:${currentUid} triggerId:${triggerId} asyncHooksCurrentId:${asyncHooksCurrentId} len:${this._set.length} ${util.inspect(context)}`);\n }\n\n this._set.push(this.active);\n this.active = context;\n};\n\nNamespace.prototype.exit = function exit(context) {\n assert.ok(context, 'context must be provided for exiting');\n if (DEBUG_CLS_HOOKED) {\n const asyncHooksCurrentId = async_hooks.executionAsyncId();\n const triggerId = async_hooks.triggerAsyncId();\n const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent);\n debug2(`${indentStr}CONTEXT-EXIT: (${this.name}) currentUid:${currentUid} triggerId:${triggerId} asyncHooksCurrentId:${asyncHooksCurrentId} len:${this._set.length} ${util.inspect(context)}`);\n }\n\n // Fast path for most exits that are at the top of the stack\n if (this.active === context) {\n assert.ok(this._set.length, 'can\\'t remove top context');\n this.active = this._set.pop();\n return;\n }\n\n // Fast search in the stack using lastIndexOf\n let index = this._set.lastIndexOf(context);\n\n if (index < 0) {\n if (DEBUG_CLS_HOOKED) {\n debug2('??ERROR?? context exiting but not entered - ignoring: ' + util.inspect(context));\n }\n assert.ok(index >= 0, 'context not currently entered; can\\'t exit. \\n' + util.inspect(this) + '\\n' + util.inspect(context));\n } else {\n assert.ok(index, 'can\\'t remove top context');\n this._set.splice(index, 1);\n }\n};\n\nNamespace.prototype.bindEmitter = function bindEmitter(emitter) {\n assert.ok(emitter.on && emitter.addListener && emitter.emit, 'can only bind real EEs');\n\n let namespace = this;\n let thisSymbol = 'context@' + this.name;\n\n // Capture the context active at the time the emitter is bound.\n function attach(listener) {\n if (!listener) {\n return;\n }\n if (!listener[CONTEXTS_SYMBOL]) {\n listener[CONTEXTS_SYMBOL] = Object.create(null);\n }\n\n listener[CONTEXTS_SYMBOL][thisSymbol] = {\n namespace: namespace,\n context: namespace.active\n };\n }\n\n // At emit time, bind the listener within the correct context.\n function bind(unwrapped) {\n if (!(unwrapped && unwrapped[CONTEXTS_SYMBOL])) {\n return unwrapped;\n }\n\n let wrapped = unwrapped;\n let unwrappedContexts = unwrapped[CONTEXTS_SYMBOL];\n Object.keys(unwrappedContexts).forEach(function (name) {\n let thunk = unwrappedContexts[name];\n wrapped = thunk.namespace.bind(wrapped, thunk.context);\n });\n return wrapped;\n }\n\n wrapEmitter(emitter, attach, bind);\n};\n\n/**\n * If an error comes out of a namespace, it will have a context attached to it.\n * This function knows how to find it.\n *\n * @param {Error} exception Possibly annotated error.\n */\nNamespace.prototype.fromException = function fromException(exception) {\n return exception[ERROR_SYMBOL];\n};\n\nfunction getNamespace(name) {\n return process.namespaces[name];\n}\n\nfunction createNamespace(name) {\n assert.ok(name, 'namespace must be given a name.');\n\n if (DEBUG_CLS_HOOKED) {\n debug2(`NS-CREATING NAMESPACE (${name})`);\n }\n let namespace = new Namespace(name);\n namespace.id = currentUid;\n\n const hook = async_hooks.createHook({\n init(asyncId, type, triggerId, resource) {\n currentUid = async_hooks.executionAsyncId();\n\n //CHAIN Parent's Context onto child if none exists. This is needed to pass net-events.spec\n // let initContext = namespace.active;\n // if(!initContext && triggerId) {\n // let parentContext = namespace._contexts.get(triggerId);\n // if (parentContext) {\n // namespace.active = parentContext;\n // namespace._contexts.set(currentUid, parentContext);\n // if (DEBUG_CLS_HOOKED) {\n // const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n // debug2(`${indentStr}INIT [${type}] (${name}) WITH PARENT CONTEXT asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, true)} resource:${resource}`);\n // }\n // } else if (DEBUG_CLS_HOOKED) {\n // const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n // debug2(`${indentStr}INIT [${type}] (${name}) MISSING CONTEXT asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, true)} resource:${resource}`);\n // }\n // }else {\n // namespace._contexts.set(currentUid, namespace.active);\n // if (DEBUG_CLS_HOOKED) {\n // const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n // debug2(`${indentStr}INIT [${type}] (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, true)} resource:${resource}`);\n // }\n // }\n if(namespace.active) {\n namespace._contexts.set(asyncId, namespace.active);\n\n if (DEBUG_CLS_HOOKED) {\n const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n debug2(`${indentStr}INIT [${type}] (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} resource:${resource}`);\n }\n }else if(currentUid === 0){\n // CurrentId will be 0 when triggered from C++. Promise events\n // https://github.com/nodejs/node/blob/master/doc/api/async_hooks.md#triggerid\n const triggerId = async_hooks.triggerAsyncId();\n const triggerIdContext = namespace._contexts.get(triggerId);\n if (triggerIdContext) {\n namespace._contexts.set(asyncId, triggerIdContext);\n if (DEBUG_CLS_HOOKED) {\n const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n debug2(`${indentStr}INIT USING CONTEXT FROM TRIGGERID [${type}] (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, { showHidden: true, depth: 2, colors: true })} resource:${resource}`);\n }\n } else if (DEBUG_CLS_HOOKED) {\n const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n debug2(`${indentStr}INIT MISSING CONTEXT [${type}] (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, { showHidden: true, depth: 2, colors: true })} resource:${resource}`);\n }\n }\n\n\n if(DEBUG_CLS_HOOKED && type === 'PROMISE'){\n debug2(util.inspect(resource, {showHidden: true}));\n const parentId = resource.parentId;\n const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n debug2(`${indentStr}INIT RESOURCE-PROMISE [${type}] (${name}) parentId:${parentId} asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} resource:${resource}`);\n }\n\n },\n before(asyncId) {\n currentUid = async_hooks.executionAsyncId();\n let context;\n\n /*\n if(currentUid === 0){\n // CurrentId will be 0 when triggered from C++. Promise events\n // https://github.com/nodejs/node/blob/master/doc/api/async_hooks.md#triggerid\n //const triggerId = async_hooks.triggerAsyncId();\n context = namespace._contexts.get(asyncId); // || namespace._contexts.get(triggerId);\n }else{\n context = namespace._contexts.get(currentUid);\n }\n */\n\n //HACK to work with promises until they are fixed in node > 8.1.1\n context = namespace._contexts.get(asyncId) || namespace._contexts.get(currentUid);\n\n if (context) {\n if (DEBUG_CLS_HOOKED) {\n const triggerId = async_hooks.triggerAsyncId();\n const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n debug2(`${indentStr}BEFORE (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} context:${util.inspect(context)}`);\n namespace._indent += 2;\n }\n\n namespace.enter(context);\n\n } else if (DEBUG_CLS_HOOKED) {\n const triggerId = async_hooks.triggerAsyncId();\n const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n debug2(`${indentStr}BEFORE MISSING CONTEXT (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} namespace._contexts:${util.inspect(namespace._contexts, {showHidden:true, depth:2, colors:true})}`);\n namespace._indent += 2;\n }\n },\n after(asyncId) {\n currentUid = async_hooks.executionAsyncId();\n let context; // = namespace._contexts.get(currentUid);\n /*\n if(currentUid === 0){\n // CurrentId will be 0 when triggered from C++. Promise events\n // https://github.com/nodejs/node/blob/master/doc/api/async_hooks.md#triggerid\n //const triggerId = async_hooks.triggerAsyncId();\n context = namespace._contexts.get(asyncId); // || namespace._contexts.get(triggerId);\n }else{\n context = namespace._contexts.get(currentUid);\n }\n */\n //HACK to work with promises until they are fixed in node > 8.1.1\n context = namespace._contexts.get(asyncId) || namespace._contexts.get(currentUid);\n\n if (context) {\n if (DEBUG_CLS_HOOKED) {\n const triggerId = async_hooks.triggerAsyncId();\n namespace._indent -= 2;\n const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n debug2(`${indentStr}AFTER (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} context:${util.inspect(context)}`);\n }\n\n namespace.exit(context);\n\n } else if (DEBUG_CLS_HOOKED) {\n const triggerId = async_hooks.triggerAsyncId();\n namespace._indent -= 2;\n const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n debug2(`${indentStr}AFTER MISSING CONTEXT (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} context:${util.inspect(context)}`);\n }\n },\n destroy(asyncId) {\n currentUid = async_hooks.executionAsyncId();\n if (DEBUG_CLS_HOOKED) {\n const triggerId = async_hooks.triggerAsyncId();\n const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n debug2(`${indentStr}DESTROY (${name}) currentUid:${currentUid} asyncId:${asyncId} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} context:${util.inspect(namespace._contexts.get(currentUid))}`);\n }\n\n namespace._contexts.delete(asyncId);\n }\n });\n\n hook.enable();\n\n process.namespaces[name] = namespace;\n return namespace;\n}\n\nfunction destroyNamespace(name) {\n let namespace = getNamespace(name);\n\n assert.ok(namespace, 'can\\'t delete nonexistent namespace! \"' + name + '\"');\n assert.ok(namespace.id, 'don\\'t assign to process.namespaces directly! ' + util.inspect(namespace));\n\n process.namespaces[name] = null;\n}\n\nfunction reset() {\n // must unregister async listeners\n if (process.namespaces) {\n Object.keys(process.namespaces).forEach(function (name) {\n destroyNamespace(name);\n });\n }\n process.namespaces = Object.create(null);\n}\n\nprocess.namespaces = {};\n\n//const fs = require('fs');\nfunction debug2(...args) {\n if (DEBUG_CLS_HOOKED) {\n //fs.writeSync(1, `${util.format(...args)}\\n`);\n process._rawDebug(`${util.format(...args)}`);\n }\n}\n\n/*function getFunctionName(fn) {\n if (!fn) {\n return fn;\n }\n if (typeof fn === 'function') {\n if (fn.name) {\n return fn.name;\n }\n return (fn.toString().trim().match(/^function\\s*([^\\s(]+)/) || [])[1];\n } else if (fn.constructor && fn.constructor.name) {\n return fn.constructor.name;\n }\n}*/\n\n\n", "\"use strict\";\nvar validLogLevels = ['debug', 'info', 'warn', 'error', 'silent'];\nvar defaultLogLevel = validLogLevels.indexOf('error');\nvar logLevel = calculateLogLevel(process.env.AWS_XRAY_DEBUG_MODE ? 'debug' : process.env.AWS_XRAY_LOG_LEVEL);\nvar logger = {\n error: createLoggerForLevel('error'),\n info: createLoggerForLevel('info'),\n warn: createLoggerForLevel('warn'),\n debug: createLoggerForLevel('debug'),\n};\nfunction createLoggerForLevel(level) {\n var loggerLevel = validLogLevels.indexOf(level);\n var consoleMethod = console[level] || console.log || (() => { });\n if (loggerLevel >= logLevel) {\n return (message, meta) => {\n if (message || meta) {\n consoleMethod(formatLogMessage(level, message, meta));\n }\n };\n }\n else {\n return () => { };\n }\n}\nfunction calculateLogLevel(level) {\n if (level) {\n var normalisedLevel = level.toLowerCase();\n var index = validLogLevels.indexOf(normalisedLevel);\n return index >= 0 ? index : defaultLogLevel;\n }\n // Silently ignore invalid log levels, default to default level\n return defaultLogLevel;\n}\nfunction createTimestamp(date) {\n var tzo = -date.getTimezoneOffset(), // Negate to make this tzo = local - UTC\n dif = tzo >= 0 ? '+' : '-', pad = function (num) {\n var norm = Math.floor(Math.abs(num));\n return (norm < 10 ? '0' : '') + norm;\n };\n return new Date(date.getTime() + (tzo * 60 * 1000)).toISOString()\n .replace(/T/, ' ')\n .replace(/Z/, ' ') +\n dif + pad(tzo / 60) +\n ':' + pad(tzo % 60);\n}\nfunction isLambdaFunction() {\n return process.env.LAMBDA_TASK_ROOT !== undefined;\n}\nfunction formatLogMessage(level, message, meta) {\n var messageParts = [];\n if (!isLambdaFunction()) {\n messageParts.push(createTimestamp(new Date()));\n messageParts.push(`[${level.toUpperCase()}]`);\n }\n if (message) {\n messageParts.push(message);\n }\n var logString = messageParts.join(' ');\n var metaDataString = formatMetaData(meta);\n return [logString, metaDataString].filter(str => str.length > 0).join('\\n ');\n}\nfunction formatMetaData(meta) {\n if (!meta) {\n return '';\n }\n return ((typeof (meta) === 'string') ? meta : JSON.stringify(meta));\n}\nvar logging = {\n setLogger: function setLogger(logObj) {\n logger = logObj;\n },\n getLogger: function getLogger() {\n return logger;\n }\n};\nmodule.exports = logging;\n", "\"use strict\";\n/**\n * Represents a captured exception.\n * @constructor\n * @param {Exception} err - The exception to capture.\n * @param {boolean} [remote] - Flag for whether the error was remote.\n */\nfunction CapturedException(err, remote) {\n this.init(err, remote);\n}\nCapturedException.prototype.init = function init(err, remote) {\n var e = (typeof err === 'string' || err instanceof String) ? { message: err, name: '' } : err;\n this.message = e.message;\n this.type = e.name;\n this.stack = [];\n this.remote = !!remote;\n if (e.stack) {\n var stack = e.stack.split('\\n');\n stack.shift();\n var self = this;\n stack.forEach(function (stackline) {\n var line = stackline.trim().replace(/\\(|\\)/g, '');\n line = line.substring(line.indexOf(' ') + 1);\n var label = line.lastIndexOf(' ') >= 0 ? line.slice(0, line.lastIndexOf(' ')) : null;\n var path = Array.isArray(label) && !label.length ? line : line.slice(line.lastIndexOf(' ') + 1);\n path = path.split(':');\n var entry = {\n path: path[0],\n line: parseInt(path[1]),\n label: label || 'anonymous'\n };\n self.stack.push(entry);\n });\n }\n};\nmodule.exports = CapturedException;\n", "module.exports = batcher\n\nfunction batcher (run) {\n var running = false\n var pendingBatch = null\n var pendingCallbacks = null\n var callbacks = null\n\n return append\n\n function done (err) {\n if (callbacks) callAll(callbacks, err)\n\n running = false\n callbacks = pendingCallbacks\n var nextBatch = pendingBatch\n\n pendingBatch = null\n pendingCallbacks = null\n\n if (!nextBatch || !nextBatch.length) {\n if (!callbacks || !callbacks.length) {\n callbacks = null\n return\n }\n if (!nextBatch) nextBatch = []\n }\n\n running = true\n run(nextBatch, done)\n }\n\n function append (val, cb) {\n if (running) {\n if (!pendingBatch) {\n pendingBatch = []\n pendingCallbacks = []\n }\n pushAll(pendingBatch, val)\n if (cb) pendingCallbacks.push(cb)\n } else {\n if (cb) callbacks = [cb]\n running = true\n run(Array.isArray(val) ? val : [val], done)\n }\n }\n}\n\nfunction pushAll (list, val) {\n if (Array.isArray(val)) pushArray(list, val)\n else list.push(val)\n}\n\nfunction pushArray (list, val) {\n for (var i = 0; i < val.length; i++) list.push(val[i])\n}\n\nfunction callAll (list, err) {\n for (var i = 0; i < list.length; i++) list[i](err)\n}\n", "\"use strict\";\nvar logger = require('./logger');\n/**\n * A module representing the X-Ray daemon configuration including the udp and tcp addresses.\n * @module DaemonConfig\n */\nvar DaemonConfig = {\n udp_ip: '127.0.0.1',\n udp_port: 2000,\n tcp_ip: '127.0.0.1',\n tcp_port: 2000,\n setDaemonAddress: function setDaemonAddress(address) {\n if (!process.env.AWS_XRAY_DAEMON_ADDRESS) {\n processAddress(address);\n logger.getLogger().info('Configured daemon address to ' + address + '.');\n }\n else {\n logger.getLogger().warn('Ignoring call to setDaemonAddress as AWS_XRAY_DAEMON_ADDRESS is set. ' +\n 'The current daemon address will not be changed.');\n }\n }\n};\nvar processAddress = function processAddress(address) {\n if (address.indexOf(':') === -1) {\n throw new Error('Invalid Daemon Address. You must specify an ip and port.');\n }\n else {\n var splitAddress = address.split(' ');\n if (splitAddress.length === 1) {\n // in format of 127.0.0.1:2000\n if (address.indexOf('udp') > -1 || address.indexOf('tcp') > -1) {\n throw new Error('Invalid Daemon Address. You must specify both tcp and udp addresses.');\n }\n var addr = address.split(':');\n if (!addr[0])\n throw new Error('Invalid Daemon Address. You must specify an ip.');\n DaemonConfig.udp_ip = addr[0];\n DaemonConfig.tcp_ip = addr[0];\n DaemonConfig.udp_port = addr[1];\n DaemonConfig.tcp_port = addr[1];\n }\n else if (splitAddress.length === 2) {\n // in format of udp:127.0.0.1:2000 tcp:127.0.0.1:2001\n var part_1 = splitAddress[0].split(':');\n var part_2 = splitAddress[1].split(':');\n var addr_map = {};\n addr_map[part_1[0]] = part_1;\n addr_map[part_2[0]] = part_2;\n DaemonConfig.udp_ip = addr_map['udp'][1];\n DaemonConfig.udp_port = parseInt(addr_map['udp'][2]);\n DaemonConfig.tcp_ip = addr_map['tcp'][1];\n DaemonConfig.tcp_port = parseInt(addr_map['tcp'][2]);\n if (!DaemonConfig.udp_port || !DaemonConfig.tcp_port) {\n throw new Error('Invalid Daemon Address. You must specify port number.');\n }\n }\n }\n};\nif (process.env.AWS_XRAY_DAEMON_ADDRESS)\n processAddress(process.env.AWS_XRAY_DAEMON_ADDRESS);\nmodule.exports = DaemonConfig;\n", "\"use strict\";\nvar dgram = require('dgram');\nvar batcher = require('atomic-batcher');\nvar logger = require('./logger');\nvar PROTOCOL_HEADER = '{\"format\":\"json\",\"version\":1}';\nvar PROTOCOL_DELIMITER = '\\n';\n/**\n * Sends a collection of data over a UDP socket. This method\n * is designed to be used by `atomic-batcher` as a way to share\n * a single UDP socket for sending multiple data blocks.\n *\n * @param {object} ops - Details of the data to send\n * @param {Function} callback - The function to call when done\n */\nfunction batchSendData(ops, callback) {\n var client = dgram.createSocket('udp4');\n executeSendData(client, ops, 0, function () {\n try {\n client.close();\n }\n finally {\n callback();\n }\n });\n}\n/**\n * Execute sending data starting at the specified index and\n * using the provided client.\n *\n * @param {Socket} client - Socket to send data with\n * @param {object} ops - Details of data to send\n * @param {number} index - Starting index for sending\n * @param {Function} callback - Function to call when done\n */\nfunction executeSendData(client, ops, index, callback) {\n if (index >= ops.length) {\n callback();\n return;\n }\n sendMessage(client, ops[index], function () {\n executeSendData(client, ops, index + 1, callback);\n });\n}\n/**\n * Send a single message over a UDP socket.\n *\n * @param {Socket} client - Socket to send data with\n * @param {object} data - Details of the data to send\n * @param {Function} batchCallback - Function to call when done\n */\nfunction sendMessage(client, data, batchCallback) {\n var msg = data.msg;\n var offset = data.offset;\n var length = data.length;\n var port = data.port;\n var address = data.address;\n var callback = data.callback;\n client.send(msg, offset, length, port, address, function (err) {\n try {\n callback(err);\n }\n finally {\n batchCallback();\n }\n });\n}\n/**\n * Class to mimic the Socket interface for a UDP client, but to provided\n * batching of outgoing sends using temporary Sockets that are created and\n * destroyed as needed.\n */\nfunction BatchingTemporarySocket() {\n this.batchSend = batcher(batchSendData);\n}\n/**\n * Provide the same signature as the Socket.send method but the work will be\n * batched to share temporary UDP sockets whenever possible.\n */\nBatchingTemporarySocket.prototype.send = function (msg, offset, length, port, address, callback) {\n var work = {\n msg: msg,\n offset: offset,\n length: length,\n port: port,\n address: address,\n callback: callback\n };\n this.batchSend(work);\n};\n/**\n * Segment emitter module.\n * @module SegmentEmitter\n */\nvar SegmentEmitter = {\n daemonConfig: require('./daemon_config'),\n /**\n * Returns the formatted segment JSON string.\n */\n format: function format(segment) {\n return PROTOCOL_HEADER + PROTOCOL_DELIMITER + segment.toString();\n },\n /**\n * Creates a UDP socket connection and send the formatted segment.\n * @param {Segment} segment - The segment to send to the daemon.\n */\n send: function send(segment) {\n if (!this.socket) {\n if (this.useBatchingTemporarySocket) {\n this.socket = new BatchingTemporarySocket();\n }\n else {\n this.socket = dgram.createSocket('udp4').unref();\n }\n }\n var client = this.socket;\n var formatted = segment.format();\n var data = PROTOCOL_HEADER + PROTOCOL_DELIMITER + formatted;\n var message = Buffer.from(data);\n var short = '{\"trace_id:\"' + segment.trace_id + '\",\"id\":\"' + segment.id + '\"}';\n var type = segment.type === 'subsegment' ? 'Subsegment' : 'Segment';\n client.send(message, 0, message.length, this.daemonConfig.udp_port, this.daemonConfig.udp_ip, function (err) {\n if (err) {\n if (err.code === 'EMSGSIZE')\n logger.getLogger().error(type + ' too large to send: ' + short + ' (' + message.length + ' bytes).');\n else\n logger.getLogger().error('Error occured sending segment: ', err);\n }\n else {\n logger.getLogger().debug(type + ' sent: {\"trace_id:\"' + segment.trace_id + '\",\"id\":\"' + segment.id + '\"}');\n logger.getLogger().debug('UDP message sent: ' + segment);\n }\n });\n },\n /**\n * Configures the address and/or port the daemon is expected to be on.\n * @param {string} address - Address of the daemon the segments should be sent to. Should be formatted as an IPv4 address.\n * @module SegmentEmitter\n * @function setDaemonAddress\n */\n setDaemonAddress: function setDaemonAddress(address) {\n this.daemonConfig.setDaemonAddress(address);\n },\n /**\n * Get the UDP IP the emitter is configured to.\n * @module SegmentEmitter\n * @function getIp\n */\n getIp: function getIp() {\n return this.daemonConfig.udp_ip;\n },\n /**\n * Get the UDP port the emitter is configured to.\n * @module SegmentEmitter\n * @function getPort\n */\n getPort: function getPort() {\n return this.daemonConfig.udp_port;\n },\n /**\n * Forces the segment emitter to create a new socket on send, and close it on complete.\n * @module SegmentEmitter\n * @function disableReusableSocket\n */\n disableReusableSocket: function () {\n this.useBatchingTemporarySocket = true;\n }\n};\nmodule.exports = SegmentEmitter;\n", "\"use strict\";\nvar crypto = require('crypto');\nvar logger = require('../../logger');\n/**\n * Class describing an AWS X-Ray trace ID.\n * @see https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-traces\n */\nclass TraceID {\n /**\n * Constructs a new trace ID using the current time.\n * @param {string} [tsHex] - time stamp to use for trace ID in hexadecimal format\n * @param {string} [numberhex] - string of hexadecimal characters for random portion of Trace ID\n * @constructor\n */\n constructor(tsHex, numberhex) {\n this.version = 1;\n this.timestamp = tsHex || Math.round(new Date().getTime() / 1000).toString(16);\n this.id = numberhex || crypto.randomBytes(12).toString('hex');\n }\n /**\n * @returns {TraceID} - a hardcoded trace ID using zeroed timestamp and random ID\n */\n static Invalid() {\n return new TraceID('00000000', '000000000000000000000000');\n }\n /**\n * Constructs a new trace ID from provided string. If no string is provided or the provided string is invalid,\n * log an error but a new trace ID still returned. This can be used as a trace ID string validator.\n * @param {string} [rawID] - string to create a Trace ID object from.\n */\n static FromString(rawID) {\n const DELIMITER = '-';\n var traceID = new TraceID();\n var version, timestamp;\n if (!rawID || typeof rawID !== 'string') {\n logger.getLogger().error('Empty or non-string trace ID provided');\n return traceID;\n }\n const parts = rawID.trim().split(DELIMITER);\n if (parts.length !== 3) {\n logger.getLogger().error('Unrecognized trace ID format');\n return traceID;\n }\n version = parseInt(parts[0]);\n if (version === NaN || version < 1) {\n logger.getLogger().error('Trace ID version must be positive integer');\n return traceID;\n }\n timestamp = parseInt(parts[1], 16).toString(16);\n if (timestamp === 'NaN') {\n logger.getLogger().error('Trace ID timestamp must be a hex-encoded value');\n return traceID;\n }\n traceID.version = version;\n traceID.timestamp = timestamp;\n traceID.id = parts[2];\n return traceID;\n }\n /**\n * Returns a string representation of the trace ID.\n * @returns {string} - stringified trace ID, e.g. 1-57fbe041-2c7ad569f5d6ff149137be86\n */\n toString() {\n return `${this.version.toString()}-${this.timestamp}-${this.id}`;\n }\n}\nmodule.exports = TraceID;\n", "\"use strict\";\n/**\n * @module utils\n */\nvar crypto = require('crypto');\nvar logger = require('./logger');\nvar TraceID = require('./segments/attributes/trace_id');\nvar utils = {\n /**\n * Checks a HTTP response code, where 4xx are 'error' and 5xx are 'fault'.\n * @param {string} status - the HTTP response status code.\n * @returns [string] - 'error', 'fault' or nothing on no match\n * @alias module:utils.getCauseTypeFromHttpStatus\n */\n getCauseTypeFromHttpStatus: function getCauseTypeFromHttpStatus(status) {\n var stat = status.toString();\n if (stat.match(/^[4][0-9]{2}$/) !== null)\n return 'error';\n else if (stat.match(/^[5][0-9]{2}$/) !== null)\n return 'fault';\n },\n /**\n * Removes the query string parameters from a given http request path\n * as it may contain sensitive information\n *\n * Related issue: https://github.com/aws/aws-xray-sdk-node/issues/246\n *\n * Node documentation: https://nodejs.org/api/http.html#http_http_request_url_options_callback\n *\n * @param {string} path - options.path in a http.request callback\n * @returns [string] - removes query string element from path\n * @alias module:utils.stripQueryStringFromPath\n */\n stripQueryStringFromPath: function stripQueryStringFromPath(path) {\n return path ? path.split('?')[0] : '';\n },\n /**\n * Performs a case-insensitive wildcard match against two strings. This method works with pseduo-regex chars; specifically ? and * are supported.\n * An asterisk (*) represents any combination of characters\n * A question mark (?) represents any single character\n *\n * @param {string} pattern - the regex-like pattern to be compared against.\n * @param {string} text - the string to compare against the pattern.\n * @returns boolean\n * @alias module:utils.wildcardMatch\n */\n wildcardMatch: function wildcardMatch(pattern, text) {\n if (pattern === undefined || text === undefined)\n return false;\n if (pattern.length === 1 && pattern.charAt(0) === '*')\n return true;\n var patternLength = pattern.length;\n var textLength = text.length;\n var indexOfGlob = pattern.indexOf('*');\n pattern = pattern.toLowerCase();\n text = text.toLowerCase();\n // Infix globs are relatively rare, and the below search is expensive especially when\n // Balsa is used a lot. Check for infix globs and, in their absence, do the simple thing\n if (indexOfGlob === -1 || indexOfGlob === (patternLength - 1)) {\n var match = function simpleWildcardMatch() {\n var j = 0;\n for (var i = 0; i < patternLength; i++) {\n var patternChar = pattern.charAt(i);\n if (patternChar === '*') {\n // Presumption for this method is that globs only occur at end\n return true;\n }\n else if (patternChar === '?') {\n if (j === textLength)\n return false; // No character to match\n j++;\n }\n else {\n if (j >= textLength || patternChar != text.charAt(j))\n return false;\n j++;\n }\n }\n // Ate up all the pattern and didn't end at a glob, so a match will have consumed all\n // the text\n return j === textLength;\n };\n return match();\n }\n /*\n * The matchArray[i] is used to record if there is a match between the first i chars in =\n * text and the first j chars in pattern.\n * So will return matchArray[textLength+1] in the end\n * Loop from the beginning of the pattern\n * case not '*': if text[i]==pattern[j] or pattern[j] is '?', and matchArray[i] is true,\n * set matchArray[i+1] to true, otherwise false\n * case '*': since '*' can match any globing, as long as there is a true in matchArray before i\n * all the matchArray[i+1], matchArray[i+2],...,matchArray[textLength] could be true\n */\n var matchArray = [];\n matchArray[0] = true;\n for (var j = 0; j < patternLength; j++) {\n var i;\n var patternChar = pattern.charAt(j);\n if (patternChar != '*') {\n for (i = textLength - 1; i >= 0; i--)\n matchArray[i + 1] = !!matchArray[i] && (patternChar === '?' || (patternChar === text.charAt(i)));\n }\n else {\n i = 0;\n while (i <= textLength && !matchArray[i])\n i++;\n for (i; i <= textLength; i++)\n matchArray[i] = true;\n }\n matchArray[0] = (matchArray[0] && patternChar === '*');\n }\n return matchArray[textLength];\n },\n LambdaUtils: {\n validTraceData: function (xAmznTraceId) {\n var valid = false;\n if (xAmznTraceId) {\n var data = utils.processTraceData(xAmznTraceId);\n valid = !!(data && data.root && data.parent && data.sampled);\n }\n return valid;\n },\n /**\n * Populates trace ID, parent ID, and sampled decision of given segment. Will always populate valid values,\n * even if xAmznTraceId contains missing or invalid values. This ensures downstream services receive valid\n * headers.\n * @param {Segment} segment - Facade segment to be populated\n * @param {String} xAmznTraceId - Raw Trace Header to supply trace data\n * @returns {Boolean} - true if required fields are present and Trace ID is valid, false otherwise\n */\n populateTraceData: function (segment, xAmznTraceId) {\n logger.getLogger().debug('Lambda trace data found: ' + xAmznTraceId);\n var data = utils.processTraceData(xAmznTraceId);\n var valid = false;\n if (!data) {\n data = {};\n logger.getLogger().error('_X_AMZN_TRACE_ID is empty or has an invalid format');\n }\n else if (!data.root || !data.parent || !data.sampled) {\n logger.getLogger().error('_X_AMZN_TRACE_ID is missing required information');\n }\n else {\n valid = true;\n }\n segment.trace_id = TraceID.FromString(data.root).toString(); // Will always assign valid trace_id\n segment.id = data.parent || crypto.randomBytes(8).toString('hex');\n if (data.root && segment.trace_id !== data.root) {\n logger.getLogger().error('_X_AMZN_TRACE_ID contains invalid trace ID');\n valid = false;\n }\n if (!parseInt(data.sampled))\n segment.notTraced = true;\n else\n delete segment.notTraced;\n logger.getLogger().debug('Segment started: ' + JSON.stringify(data));\n return valid;\n }\n },\n /**\n * Splits out the data from the trace id format. Used by the middleware.\n * @param {String} traceData - The additional trace data (typically in req.headers.x-amzn-trace-id).\n * @returns {object}\n * @alias module:mw_utils.processTraceData\n */\n processTraceData: function processTraceData(traceData) {\n var amznTraceData = {};\n var reservedKeywords = ['root', 'parent', 'sampled', 'self'];\n var remainingBytes = 256;\n if (!(typeof traceData === 'string' && traceData))\n return amznTraceData;\n traceData.split(';').forEach(function (header) {\n if (!header)\n return;\n var pair = header.split('=');\n if (pair[0] && pair[1]) {\n var key = pair[0].trim().toLowerCase();\n var value = pair[1].trim().toLowerCase();\n var reserved = reservedKeywords.indexOf(key) !== -1;\n if (reserved) {\n amznTraceData[key] = value;\n }\n else if (!reserved && remainingBytes - (key.length + value.length) >= 0) {\n amznTraceData[key] = value;\n remainingBytes -= (key.length + value.length);\n }\n }\n });\n return amznTraceData;\n },\n /**\n * Makes a shallow copy of an object without given keys - keeps prototype\n * @param {Object} obj - The object to copy\n * @param {string[]} [keys=[]] - The keys that won't be copied\n * @param {boolean} [preservePrototype=false] - If true also copy prototype properties\n * @returns {}\n */\n objectWithoutProperties: function objectWithoutProperties(obj, keys, preservePrototype) {\n keys = Array.isArray(keys) ? keys : [];\n preservePrototype = typeof preservePrototype === 'boolean' ? preservePrototype : false;\n var target = preservePrototype ? Object.create(Object.getPrototypeOf(obj)) : {};\n for (var property in obj) {\n if (keys.indexOf(property) >= 0)\n continue;\n if (!Object.prototype.hasOwnProperty.call(obj, property))\n continue;\n target[property] = obj[property];\n }\n return target;\n },\n /**\n * Safely gets an integer from a string or number\n * @param {String | Number} - input to cast to integer\n * @returns {Number} - Integer representation of input, or 0 if input is not castable to int\n */\n safeParseInt: (val) => {\n if (!val || isNaN(val)) {\n return 0;\n }\n return parseInt(val);\n }\n};\nmodule.exports = utils;\n", "\"use strict\";\nconst { safeParseInt } = require('../utils');\nvar logger = require('../logger');\nvar DEFAULT_STREAMING_THRESHOLD = 100;\nvar utils = {\n streamingThreshold: DEFAULT_STREAMING_THRESHOLD,\n getCurrentTime: function getCurrentTime() {\n return Date.now() / 1000;\n },\n setOrigin: function setOrigin(origin) {\n this.origin = origin;\n },\n setPluginData: function setPluginData(pluginData) {\n this.pluginData = pluginData;\n },\n setSDKData: function setSDKData(sdkData) {\n this.sdkData = sdkData;\n },\n setServiceData: function setServiceData(serviceData) {\n this.serviceData = serviceData;\n },\n /**\n * Overrides the default streaming threshold (100).\n * The threshold represents the maximum number of subsegments on a single segment before\n * the SDK beings to send the completed subsegments out of band of the main segment.\n * Reduce this threshold if you see the 'Segment too large to send' error.\n * @param {number} threshold - The new threshold to use.\n * @memberof AWSXRay\n */\n setStreamingThreshold: function setStreamingThreshold(threshold) {\n if (isFinite(threshold) && threshold >= 0) {\n utils.streamingThreshold = threshold;\n logger.getLogger().debug('Subsegment streaming threshold set to: ' + threshold);\n }\n else {\n logger.getLogger().error('Invalid threshold: ' + threshold + '. Must be a whole number >= 0.');\n }\n },\n getStreamingThreshold: function getStreamingThreshold() {\n return utils.streamingThreshold;\n },\n /**\n * Parses an HTTP response object to return an X-Ray compliant HTTP response object.\n * @param {http.ServerResponse} res\n * @returns {Object} - X-Ray response object to be added to (sub)segment\n */\n getHttpResponseData: (res) => {\n const ret = {};\n if (!res) {\n return ret;\n }\n const status = safeParseInt(res.statusCode);\n if (status !== 0) {\n ret.status = status;\n }\n if (res.headers && res.headers['content-length']) {\n ret.content_length = safeParseInt(res.headers['content-length']);\n }\n return ret;\n }\n};\nmodule.exports = utils;\n", "\"use strict\";\nconst { getHttpResponseData } = require('../segment_utils');\nvar { stripQueryStringFromPath } = require('../../utils');\n/**\n * Represents an outgoing HTTP/HTTPS call.\n * @constructor\n * @param {http.ClientRequest|https.ClientRequest} req - The request object from the HTTP/HTTPS call.\n * @param {http.IncomingMessage|https.IncomingMessage} res - The response object from the HTTP/HTTPS call.\n * @param {boolean} downstreamXRayEnabled - when true, adds a \"traced\": true hint to generated subsegments such that the AWS X-Ray service expects a corresponding segment from the downstream service.\n */\nfunction RemoteRequestData(req, res, downstreamXRayEnabled) {\n this.init(req, res, downstreamXRayEnabled);\n}\nRemoteRequestData.prototype.init = function init(req, res, downstreamXRayEnabled) {\n this.request = {\n url: (req.agent && req.agent.protocol) ? (req.agent.protocol + '//' + req.getHeader('host') + stripQueryStringFromPath(req.path)) : '',\n method: req.method || '',\n };\n if (downstreamXRayEnabled) {\n this.request.traced = true;\n }\n if (res) {\n this.response = getHttpResponseData(res);\n }\n};\nmodule.exports = RemoteRequestData;\n", "\"use strict\";\nvar crypto = require('crypto');\nvar CapturedException = require('./captured_exception');\nvar RemoteRequestData = require('./remote_request_data');\nvar SegmentEmitter = require('../../segment_emitter');\nvar SegmentUtils = require('../segment_utils');\nvar Utils = require('../../utils');\nvar logger = require('../../logger');\n/**\n * Represents a subsegment.\n * @constructor\n * @param {string} name - The name of the subsegment.\n */\nfunction Subsegment(name) {\n this.init(name);\n}\nSubsegment.prototype.init = function init(name) {\n if (typeof name != 'string')\n throw new Error('Subsegment name must be of type string.');\n this.id = crypto.randomBytes(8).toString('hex');\n this.name = name;\n this.start_time = SegmentUtils.getCurrentTime();\n this.in_progress = true;\n this.counter = 0;\n};\n/**\n * Nests a new subsegment to the array of subsegments.\n * @param {string} name - The name of the new subsegment to append.\n * @returns {Subsegment} - The newly created subsegment.\n */\nSubsegment.prototype.addNewSubsegment = function addNewSubsegment(name) {\n var subsegment = new Subsegment(name);\n this.addSubsegment(subsegment);\n return subsegment;\n};\n/**\n * Adds a subsegment to the array of subsegments.\n * @param {Subsegment} subsegment - The subsegment to append.\n */\nSubsegment.prototype.addSubsegment = function (subsegment) {\n if (!(subsegment instanceof Subsegment)) {\n throw new Error('Failed to add subsegment:' + subsegment + ' to subsegment \"' + this.name +\n '\". Not a subsegment.');\n }\n if (this.subsegments === undefined)\n this.subsegments = [];\n subsegment.segment = this.segment;\n subsegment.parent = this;\n if (subsegment.end_time === undefined) {\n this.incrementCounter(subsegment.counter);\n }\n this.subsegments.push(subsegment);\n};\n/**\n * Removes the subsegment from the subsegments array, used in subsegment streaming.\n */\nSubsegment.prototype.removeSubsegment = function removeSubsegment(subsegment) {\n if (!(subsegment instanceof Subsegment)) {\n throw new Error('Failed to remove subsegment:' + subsegment + ' from subsegment \"' + this.name +\n '\". Not a subsegment.');\n }\n if (this.subsegments !== undefined) {\n var index = this.subsegments.indexOf(subsegment);\n if (index >= 0)\n this.subsegments.splice(index, 1);\n }\n};\n/**\n * Adds a property with associated data into the subsegment.\n * @param {string} name - The name of the property to add.\n * @param {Object} data - The data of the property to add.\n */\nSubsegment.prototype.addAttribute = function addAttribute(name, data) {\n this[name] = data;\n};\n/**\n * Adds a subsegement id to record ordering.\n * @param {string} id - A subsegment id.\n */\nSubsegment.prototype.addPrecursorId = function (id) {\n if (typeof id !== 'string')\n logger.getLogger().error('Failed to add id:' + id + ' to subsegment ' + this.name +\n '. Precursor Ids must be of type string.');\n if (this.precursor_ids === undefined)\n this.precursor_ids = [];\n this.precursor_ids.push(id);\n};\n/**\n * Adds a key-value pair that can be queryable through GetTraceSummaries.\n * Only acceptable types are string, float/int and boolean.\n * @param {string} key - The name of key to add.\n * @param {boolean|string|number} value - The value to add for the given key.\n */\nSubsegment.prototype.addAnnotation = function (key, value) {\n if (!(typeof value === 'boolean' || typeof value === 'string' || (typeof value === 'number' && isFinite(value)))) {\n throw new Error('Failed to add annotation key: ' + key + ' value: ' + value + ' to subsegment ' +\n this.name + '. Value must be of type string, number or boolean.');\n }\n else if (typeof key !== 'string') {\n throw new Error('Failed to add annotation key: ' + key + ' value: ' + value + ' to subsegment ' +\n this.name + '. Key must be of type string.');\n }\n if (this.annotations === undefined)\n this.annotations = {};\n this.annotations[key] = value;\n};\n/**\n * Adds a key-value pair to the metadata.default attribute when no namespace is given.\n * Metadata is not queryable, but is recorded.\n * @param {string} key - The name of the key to add.\n * @param {object|null} value - The value of the associated key.\n * @param {string} [namespace] - The property name to put the key/value pair under.\n */\nSubsegment.prototype.addMetadata = function (key, value, namespace) {\n if (typeof key !== 'string') {\n throw new Error('Failed to add annotation key: ' + key + ' value: ' + value + ' to subsegment ' +\n this.name + '. Key must be of type string.');\n }\n else if (namespace && typeof namespace !== 'string') {\n throw new Error('Failed to add annotation key: ' + key + ' value: ' + value + 'namespace: ' + namespace + ' to subsegment ' +\n this.name + '. Namespace must be of type string.');\n }\n var ns = namespace || 'default';\n if (!this.metadata) {\n this.metadata = {};\n }\n if (!this.metadata[ns]) {\n this.metadata[ns] = {};\n }\n this.metadata[ns][key] = value;\n};\nSubsegment.prototype.addSqlData = function addSqlData(sqlData) {\n this.sql = sqlData;\n};\n/**\n * Adds an error with associated data into the subsegment.\n * To handle propagating errors, the subsegment also sets a copy of the error on the\n * root segment. As the error passes up the execution stack, a reference is created\n * on each subsegment to the originating subsegment.\n * @param {Error|string} err - The error to capture.\n * @param {boolean} [remote] - Flag for whether the exception caught was remote or not.\n */\nSubsegment.prototype.addError = function addError(err, remote) {\n if (err == null || typeof err !== 'object' && typeof (err) !== 'string') {\n throw new Error('Failed to add error:' + err + ' to subsegment \"' + this.name +\n '\". Not an object or string literal.');\n }\n this.addFaultFlag();\n if (this.segment && this.segment.exception) {\n if (err === this.segment.exception.ex) {\n this.fault = true;\n this.cause = { id: this.segment.exception.cause };\n return;\n }\n delete this.segment.exception;\n }\n if (this.segment) {\n this.segment.exception = {\n ex: err,\n cause: this.id\n };\n }\n else {\n //error, cannot propagate exception if not added to segment\n }\n if (this.cause === undefined) {\n this.cause = {\n working_directory: process.cwd(),\n exceptions: []\n };\n }\n this.cause.exceptions.unshift(new CapturedException(err, remote));\n};\n/**\n * Adds data for an outgoing HTTP/HTTPS call.\n * @param {http.ClientRequest/https.ClientRequest} req - The request object from the HTTP/HTTPS call.\n * @param {http.IncomingMessage/https.IncomingMessage} res - The response object from the HTTP/HTTPS call.\n * @param {boolean} downstreamXRayEnabled - when true, adds a \"traced\": true hint to generated subsegments such that the AWS X-Ray service expects a corresponding segment from the downstream service.\n */\nSubsegment.prototype.addRemoteRequestData = function addRemoteRequestData(req, res, downstreamXRayEnabled) {\n this.http = new RemoteRequestData(req, res, downstreamXRayEnabled);\n if ('traced' in this.http.request) {\n this.traced = this.http.request.traced;\n delete this.http.request.traced;\n }\n};\n/**\n * Adds fault flag to the subsegment.\n */\nSubsegment.prototype.addFaultFlag = function addFaultFlag() {\n this.fault = true;\n};\n/**\n * Adds error flag to the subsegment.\n */\nSubsegment.prototype.addErrorFlag = function addErrorFlag() {\n this.error = true;\n};\n/**\n * Adds throttle flag to the subsegment.\n */\nSubsegment.prototype.addThrottleFlag = function addThrottleFlag() {\n this.throttle = true;\n};\n/**\n * Closes the current subsegment. This automatically captures any exceptions and sets the end time.\n * @param {Error|string} [err] - The error to capture.\n * @param {boolean} [remote] - Flag for whether the exception caught was remote or not.\n */\nSubsegment.prototype.close = function close(err, remote) {\n var root = this.segment;\n this.end_time = SegmentUtils.getCurrentTime();\n delete this.in_progress;\n if (err)\n this.addError(err, remote);\n if (this.parent)\n this.parent.decrementCounter();\n if (root && root.counter > SegmentUtils.getStreamingThreshold()) {\n if (this.streamSubsegments() && this.parent)\n this.parent.removeSubsegment(this);\n }\n};\n/**\n * Each subsegment holds a counter of open subsegments. This increments\n * the counter such that it can be called from a child and propagate up.\n * @param {Number} [additional] - An additional amount to increment. Used when adding subsegment trees.\n */\nSubsegment.prototype.incrementCounter = function incrementCounter(additional) {\n this.counter = additional ? this.counter + additional + 1 : this.counter + 1;\n if (this.parent)\n this.parent.incrementCounter(additional);\n};\n/**\n * Each subsegment holds a counter of its open subsegments. This decrements\n * the counter such that it can be called from a child and propagate up.\n */\nSubsegment.prototype.decrementCounter = function decrementCounter() {\n this.counter--;\n if (this.parent)\n this.parent.decrementCounter();\n};\n/**\n * Returns a boolean indicating whether or not the subsegment has been closed.\n * @returns {boolean} - Returns true if the subsegment is closed.\n */\nSubsegment.prototype.isClosed = function isClosed() {\n return !this.in_progress;\n};\n/**\n * Sends the subsegment to the daemon.\n */\nSubsegment.prototype.flush = function flush() {\n if (!this.parent || !this.segment) {\n throw new Error('Failed to flush subsegment: ' + this.name + '. Subsegment must be added ' +\n 'to a segment chain to flush.');\n }\n if (this.segment.trace_id) {\n if (this.segment.notTraced !== true) {\n SegmentEmitter.send(this);\n }\n else {\n logger.getLogger().debug('Ignoring flush on subsegment ' + this.id + '. Associated segment is marked as not sampled.');\n }\n }\n else {\n logger.getLogger().debug('Ignoring flush on subsegment ' + this.id + '. Associated segment is missing a trace ID.');\n }\n};\n/**\n * Returns true if the subsegment was streamed in its entirety\n */\nSubsegment.prototype.streamSubsegments = function streamSubsegments() {\n if (this.isClosed() && this.counter <= 0) {\n this.flush();\n return true;\n }\n else if (this.subsegments && this.subsegments.length > 0) {\n var open = [];\n this.subsegments.forEach(function (child) {\n if (!child.streamSubsegments())\n open.push(child);\n });\n this.subsegments = open;\n }\n};\n/**\n * Returns the formatted, trimmed subsegment JSON string to send to the daemon.\n */\nSubsegment.prototype.format = function format() {\n this.type = 'subsegment';\n if (this.parent)\n this.parent_id = this.parent.id;\n if (this.segment)\n this.trace_id = this.segment.trace_id;\n return JSON.stringify(this);\n};\n/**\n * Returns the formatted subsegment JSON string.\n */\nSubsegment.prototype.toString = function toString() {\n return JSON.stringify(this);\n};\nSubsegment.prototype.toJSON = function toJSON() {\n var ignore = ['segment', 'parent', 'counter'];\n if (this.subsegments == null || this.subsegments.length === 0)\n ignore.push('subsegments');\n var thisCopy = Utils.objectWithoutProperties(this, ignore, false);\n return thisCopy;\n};\nmodule.exports = Subsegment;\n", "\"use strict\";\nvar crypto = require('crypto');\nvar CapturedException = require('./attributes/captured_exception');\nvar SegmentEmitter = require('../segment_emitter');\nvar SegmentUtils = require('./segment_utils');\nvar Subsegment = require('./attributes/subsegment');\nvar TraceID = require('./attributes/trace_id');\nvar Utils = require('../utils');\nvar logger = require('../logger');\n/**\n * Represents a segment.\n * @constructor\n * @param {string} name - The name of the subsegment.\n * @param {string} [rootId] - The trace ID of the spawning parent, included in the 'X-Amzn-Trace-Id' header of the incoming request. If one is not supplied, it will be generated.\n * @param {string} [parentId] - The sub/segment ID of the spawning parent, included in the 'X-Amzn-Trace-Id' header of the incoming request.\n */\nfunction Segment(name, rootId, parentId) {\n this.init(name, rootId, parentId);\n}\nSegment.prototype.init = function init(name, rootId, parentId) {\n if (typeof name != 'string')\n throw new Error('Segment name must be of type string.');\n // Validate the Trace ID\n var traceId;\n if (rootId && typeof rootId == 'string') {\n traceId = TraceID.FromString(rootId);\n }\n else {\n traceId = new TraceID();\n }\n var id = crypto.randomBytes(8).toString('hex');\n var startTime = SegmentUtils.getCurrentTime();\n this.trace_id = traceId.toString();\n this.id = id;\n this.start_time = startTime;\n this.name = name || '';\n this.in_progress = true;\n this.counter = 0;\n if (parentId)\n this.parent_id = parentId;\n if (SegmentUtils.serviceData)\n this.setServiceData(SegmentUtils.serviceData);\n if (SegmentUtils.pluginData)\n this.addPluginData(SegmentUtils.pluginData);\n if (SegmentUtils.origin)\n this.origin = SegmentUtils.origin;\n if (SegmentUtils.sdkData)\n this.setSDKData(SegmentUtils.sdkData);\n};\n/**\n * Adds incoming request data to the http block of the segment.\n * @param {IncomingRequestData} data - The data of the property to add.\n */\nSegment.prototype.addIncomingRequestData = function addIncomingRequestData(data) {\n this.http = data;\n};\n/**\n * Adds a key-value pair that can be queryable through GetTraceSummaries.\n * Only acceptable types are string, float/int and boolean.\n * @param {string} key - The name of key to add.\n * @param {boolean|string|number} value - The value to add for the given key.\n */\nSegment.prototype.addAnnotation = function addAnnotation(key, value) {\n if (typeof value !== 'boolean' && typeof value !== 'string' && !isFinite(value)) {\n logger.getLogger().error('Add annotation key: ' + key + ' value: ' + value + ' failed.' +\n ' Annotations must be of type string, number or boolean.');\n return;\n }\n if (this.annotations === undefined)\n this.annotations = {};\n this.annotations[key] = value;\n};\n/**\n * Adds a User ID that can be queried from the X-Ray console. User ID\n * must be a string.\n * @param {string} user - The ID of the user corresponding to this segment\n */\nSegment.prototype.setUser = function (user) {\n if (typeof user !== 'string') {\n logger.getLogger().error('Set user: ' + user + ' failed. User IDs must be of type string.');\n }\n this.user = user;\n};\n/**\n * Adds a key-value pair to the metadata.default attribute when no namespace is given.\n * Metadata is not queryable, but is recorded.\n * @param {string} key - The name of the key to add.\n * @param {object|null} value - The value of the associated key.\n * @param {string} [namespace] - The property name to put the key/value pair under.\n */\nSegment.prototype.addMetadata = function (key, value, namespace) {\n if (typeof key !== 'string') {\n throw new Error('Failed to add annotation key: ' + key + ' value: ' + value + ' to subsegment ' +\n this.name + '. Key must be of type string.');\n }\n else if (namespace && typeof namespace !== 'string') {\n throw new Error('Failed to add annotation key: ' + key + ' value: ' + value + 'namespace: ' + namespace + ' to subsegment ' +\n this.name + '. Namespace must be of type string.');\n }\n var ns = namespace || 'default';\n if (!this.metadata) {\n this.metadata = {};\n }\n if (!this.metadata[ns]) {\n this.metadata[ns] = {};\n }\n this.metadata[ns][key] = value;\n};\n/**\n * Adds data about the AWS X-Ray SDK onto the segment.\n * @param {Object} data - Object that contains the version of the SDK, and other information.\n */\nSegment.prototype.setSDKData = function setSDKData(data) {\n if (!data) {\n logger.getLogger().error('Add SDK data: ' + data + ' failed.' +\n 'Must not be empty.');\n return;\n }\n if (!this.aws)\n this.aws = {};\n this.aws.xray = data;\n};\nSegment.prototype.setMatchedSamplingRule = function setMatchedSamplingRule(ruleName) {\n if (this.aws)\n this.aws = JSON.parse(JSON.stringify(this.aws));\n if (this.aws && this.aws['xray'])\n this.aws.xray['rule_name'] = ruleName;\n else\n this.aws = { xray: { 'rule_name': ruleName } };\n};\n/**\n * Adds data about the service into the segment.\n * @param {Object} data - Object that contains the version of the application, and other information.\n */\nSegment.prototype.setServiceData = function setServiceData(data) {\n if (!data) {\n logger.getLogger().error('Add service data: ' + data + ' failed.' +\n 'Must not be empty.');\n return;\n }\n this.service = data;\n};\n/**\n * Adds a service with associated version data into the segment.\n * @param {Object} data - The associated AWS data.\n */\nSegment.prototype.addPluginData = function addPluginData(data) {\n if (this.aws === undefined)\n this.aws = {};\n Object.assign(this.aws, data);\n};\n/**\n * Adds a new subsegment to the array of subsegments.\n * @param {string} name - The name of the new subsegment to append.\n */\nSegment.prototype.addNewSubsegment = function addNewSubsegment(name) {\n var subsegment = new Subsegment(name);\n this.addSubsegment(subsegment);\n return subsegment;\n};\n/**\n * Adds a subsegment to the array of subsegments.\n * @param {Subsegment} subsegment - The subsegment to append.\n */\nSegment.prototype.addSubsegment = function addSubsegment(subsegment) {\n if (!(subsegment instanceof Subsegment))\n throw new Error('Cannot add subsegment: ' + subsegment + '. Not a subsegment.');\n if (this.subsegments === undefined)\n this.subsegments = [];\n subsegment.segment = this;\n subsegment.parent = this;\n this.subsegments.push(subsegment);\n if (!subsegment.end_time)\n this.incrementCounter(subsegment.counter);\n};\n/**\n * Removes the subsegment from the subsegments array, used in subsegment streaming.\n */\nSegment.prototype.removeSubsegment = function removeSubsegment(subsegment) {\n if (!(subsegment instanceof Subsegment)) {\n throw new Error('Failed to remove subsegment:' + subsegment + ' from subsegment \"' + this.name +\n '\". Not a subsegment.');\n }\n if (this.subsegments !== undefined) {\n var index = this.subsegments.indexOf(subsegment);\n if (index >= 0)\n this.subsegments.splice(index, 1);\n }\n};\n/**\n * Adds error data into the segment.\n * @param {Error|string} err - The error to capture.\n * @param {boolean} [remote] - Flag for whether the exception caught was remote or not.\n */\nSegment.prototype.addError = function addError(err, remote) {\n if (err == null || typeof err !== 'object' && typeof (err) !== 'string') {\n throw new Error('Failed to add error:' + err + ' to subsegment \"' + this.name +\n '\". Not an object or string literal.');\n }\n this.addFaultFlag();\n if (this.exception) {\n if (err === this.exception.ex) {\n this.cause = { id: this.exception.cause };\n delete this.exception;\n return;\n }\n delete this.exception;\n }\n if (this.cause === undefined) {\n this.cause = {\n working_directory: process.cwd(),\n exceptions: []\n };\n }\n this.cause.exceptions.push(new CapturedException(err, remote));\n};\n/**\n * Adds fault flag to the subsegment.\n */\nSegment.prototype.addFaultFlag = function addFaultFlag() {\n this.fault = true;\n};\n/**\n * Adds error flag to the subsegment.\n */\nSegment.prototype.addErrorFlag = function addErrorFlag() {\n this.error = true;\n};\n/**\n * Adds throttle flag to the subsegment.\n */\nSegment.prototype.addThrottleFlag = function addThrottleFlag() {\n this.throttle = true;\n};\n/**\n * Returns a boolean indicating whether or not the segment has been closed.\n * @returns {boolean} - Returns true if the subsegment is closed.\n */\nSegment.prototype.isClosed = function isClosed() {\n return !this.in_progress;\n};\n/**\n * Each segment holds a counter of open subsegments. This increments the counter.\n * @param {Number} [additional] - An additional amount to increment. Used when adding subsegment trees.\n */\nSegment.prototype.incrementCounter = function incrementCounter(additional) {\n this.counter = additional ? this.counter + additional + 1 : this.counter + 1;\n if (this.counter > SegmentUtils.streamingThreshold && this.subsegments && this.subsegments.length > 0) {\n var open = [];\n this.subsegments.forEach(function (child) {\n if (!child.streamSubsegments())\n open.push(child);\n });\n this.subsegments = open;\n }\n};\n/**\n * Each segment holds a counter of open subsegments. This decrements\n * the counter such that it can be called from a child and propagate up.\n */\nSegment.prototype.decrementCounter = function decrementCounter() {\n this.counter--;\n if (this.counter <= 0 && this.isClosed()) {\n this.flush();\n }\n};\n/**\n * Closes the current segment. This automatically sets the end time.\n * @param {Error|string} [err] - The error to capture.\n * @param {boolean} [remote] - Flag for whether the exception caught was remote or not.\n */\nSegment.prototype.close = function (err, remote) {\n if (!this.end_time)\n this.end_time = SegmentUtils.getCurrentTime();\n if (err !== undefined)\n this.addError(err, remote);\n delete this.in_progress;\n delete this.exception;\n if (this.counter <= 0) {\n this.flush();\n }\n};\n/**\n * Sends the segment to the daemon.\n */\nSegment.prototype.flush = function flush() {\n if (this.notTraced !== true) {\n delete this.exception;\n var thisCopy = Utils.objectWithoutProperties(this, ['counter', 'notTraced'], true);\n SegmentEmitter.send(thisCopy);\n }\n};\nSegment.prototype.format = function format() {\n var ignore = ['segment', 'parent', 'counter'];\n if (this.subsegments == null || this.subsegments.length === 0)\n ignore.push('subsegments');\n var thisCopy = Utils.objectWithoutProperties(this, ignore, false);\n return JSON.stringify(thisCopy);\n};\nSegment.prototype.toString = function toString() {\n return JSON.stringify(this);\n};\nmodule.exports = Segment;\n", "\"use strict\";\n/**\n * @module context_utils\n */\nvar cls = require('cls-hooked/context');\nvar logger = require('./logger');\nvar Segment = require('./segments/segment');\nvar Subsegment = require('./segments/attributes/subsegment');\nvar cls_mode = true;\nvar NAMESPACE = 'AWSXRay';\nvar SEGMENT = 'segment';\nvar contextOverride = false;\nvar contextUtils = {\n CONTEXT_MISSING_STRATEGY: {\n RUNTIME_ERROR: {\n contextMissing: function contextMissingRuntimeError(message) {\n throw new Error(message);\n }\n },\n LOG_ERROR: {\n contextMissing: function contextMissingLogError(message) {\n var err = new Error(message);\n logger.getLogger().error(err.stack);\n }\n },\n IGNORE_ERROR: {\n contextMissing: function contextMissingIgnoreError(message) {\n }\n }\n },\n contextMissingStrategy: {},\n /**\n * Resolves the segment or subsegment given manual mode and params on the call required.\n * @param [Segment|Subsegment] segment - The segment manually provided via params.XraySegment, if provided.\n * @returns {Segment|Subsegment}\n * @alias module:context_utils.resolveManualSegmentParams\n */\n resolveManualSegmentParams: function resolveManualSegmentParams(params) {\n if (params && !contextUtils.isAutomaticMode()) {\n var xraySegment = params.XRaySegment || params.XraySegment;\n var segment = params.Segment;\n var found = null;\n if (xraySegment && (xraySegment instanceof Segment || xraySegment instanceof Subsegment)) {\n found = xraySegment;\n delete params.XRaySegment;\n delete params.XraySegment;\n }\n else if (segment && (segment instanceof Segment || segment instanceof Subsegment)) {\n found = segment;\n delete params.Segment;\n }\n return found;\n }\n },\n /**\n * Gets current CLS namespace for X-Ray SDK or creates one if absent.\n * @returns {Namespace}\n * @alias module:context_utils.getNamespace\n */\n getNamespace: function getNamespace() {\n return cls.getNamespace(NAMESPACE) || cls.createNamespace(NAMESPACE);\n },\n /**\n * Resolves the segment or subsegment given manual or automatic mode.\n * @param [Segment|Subsegment] segment - The segment manually provided, if provided.\n * @returns {Segment|Subsegment}\n * @alias module:context_utils.resolveSegment\n */\n resolveSegment: function resolveSegment(segment) {\n if (cls_mode) {\n return this.getSegment();\n }\n else if (segment && !cls_mode) {\n return segment;\n }\n else if (!segment && !cls_mode) {\n contextUtils.contextMissingStrategy.contextMissing('No sub/segment specified. A sub/segment must be provided for manual mode.');\n }\n },\n /**\n * Returns the current segment or subsegment. For use with in automatic mode only.\n * @returns {Segment|Subsegment}\n * @alias module:context_utils.getSegment\n */\n getSegment: function getSegment() {\n if (cls_mode) {\n var segment = contextUtils.getNamespace(NAMESPACE).get(SEGMENT);\n if (!segment) {\n contextUtils.contextMissingStrategy.contextMissing('Failed to get the current sub/segment from the context.');\n }\n else if (segment instanceof Segment && process.env.LAMBDA_TASK_ROOT && segment.facade == true) {\n segment.resolveLambdaTraceData();\n }\n return segment;\n }\n else {\n contextUtils.contextMissingStrategy.contextMissing('Cannot get sub/segment from context. Not supported in manual mode.');\n }\n },\n /**\n * Sets the current segment or subsegment. For use with in automatic mode only.\n * @param [Segment|Subsegment] segment - The sub/segment to set.\n * @returns {Segment|Subsegment}\n * @alias module:context_utils.setSegment\n */\n setSegment: function setSegment(segment) {\n if (cls_mode) {\n if (!contextUtils.getNamespace(NAMESPACE).set(SEGMENT, segment))\n logger.getLogger().warn('Failed to set the current sub/segment on the context.');\n }\n else {\n contextUtils.contextMissingStrategy.contextMissing('Cannot set sub/segment on context. Not supported in manual mode.');\n }\n },\n /**\n * Returns true if in automatic mode, otherwise false.\n * @returns {Segment|Subsegment}\n * @alias module:context_utils.isAutomaticMode\n */\n isAutomaticMode: function isAutomaticMode() {\n return cls_mode;\n },\n /**\n * Enables automatic mode. Automatic mode uses 'cls-hooked'.\n * @see https://github.com/jeff-lewis/cls-hooked\n * @alias module:context_utils.enableAutomaticMode\n */\n enableAutomaticMode: function enableAutomaticMode() {\n cls_mode = true;\n contextUtils.getNamespace(NAMESPACE);\n logger.getLogger().debug('Overriding AWS X-Ray SDK mode. Set to automatic mode.');\n },\n /**\n * Disables automatic mode. Current segment or subsegment then must be passed manually\n * via the parent optional on captureFunc, captureAsyncFunc etc.\n * @alias module:context_utils.enableManualMode\n */\n enableManualMode: function enableManualMode() {\n cls_mode = false;\n if (cls.getNamespace(NAMESPACE))\n cls.destroyNamespace(NAMESPACE);\n logger.getLogger().debug('Overriding AWS X-Ray SDK mode. Set to manual mode.');\n },\n /**\n * Sets the context missing strategy if no context missing strategy is set using the environment variable with\n * key AWS_XRAY_CONTEXT_MISSING. The context missing strategy's contextMissing function will be called whenever\n * trace context is not found.\n * @param {string|function} strategy - The strategy to set. Valid string values are 'LOG_ERROR' and 'RUNTIME_ERROR'.\n * Alternatively, a custom function can be supplied, which takes a error message string.\n */\n setContextMissingStrategy: function setContextMissingStrategy(strategy) {\n if (!contextOverride) {\n if (typeof strategy === 'string') {\n var lookupStrategy = contextUtils.CONTEXT_MISSING_STRATEGY[strategy.toUpperCase()];\n if (lookupStrategy) {\n contextUtils.contextMissingStrategy.contextMissing = lookupStrategy.contextMissing;\n if (process.env.AWS_XRAY_CONTEXT_MISSING)\n logger.getLogger().debug('AWS_XRAY_CONTEXT_MISSING is set. Configured context missing strategy to ' +\n process.env.AWS_XRAY_CONTEXT_MISSING + '.');\n else\n logger.getLogger().debug('Configured context missing strategy to: ' + strategy);\n }\n else {\n throw new Error('Invalid context missing strategy: ' + strategy + '. Valid values are ' +\n Object.keys(contextUtils.CONTEXT_MISSING_STRATEGY) + '.');\n }\n }\n else if (typeof strategy === 'function') {\n contextUtils.contextMissingStrategy.contextMissing = strategy;\n logger.getLogger().info('Configured custom context missing strategy to function: ' + strategy.name);\n }\n else {\n throw new Error('Context missing strategy must be either a string or a custom function.');\n }\n }\n else {\n logger.getLogger().warn('Ignoring call to setContextMissingStrategy as AWS_XRAY_CONTEXT_MISSING is set. ' +\n 'The current context missing strategy will not be changed.');\n }\n }\n};\ncls.createNamespace(NAMESPACE);\nlogger.getLogger().debug('Starting the AWS X-Ray SDK in automatic mode (default).');\nif (process.env.AWS_XRAY_CONTEXT_MISSING) {\n contextUtils.setContextMissingStrategy(process.env.AWS_XRAY_CONTEXT_MISSING);\n contextOverride = true;\n}\nelse {\n contextUtils.contextMissingStrategy.contextMissing = contextUtils.CONTEXT_MISSING_STRATEGY.RUNTIME_ERROR.contextMissing;\n logger.getLogger().debug('Using default context missing strategy: RUNTIME_ERROR');\n}\nmodule.exports = contextUtils;\n", "\"use strict\";\nvar { getHttpResponseData } = require('../segments/segment_utils');\n/**\n * Represents an incoming HTTP/HTTPS call.\n * @constructor\n * @param {http.IncomingMessage|https.IncomingMessage} req - The request object from the HTTP/HTTPS call.\n */\nfunction IncomingRequestData(req) {\n this.init(req);\n}\nIncomingRequestData.prototype.init = function init(req) {\n var forwarded = !!req.headers['x-forwarded-for'];\n var url;\n if (req.connection)\n url = ((req.connection.secure || req.connection.encrypted) ? 'https://' : 'http://') +\n ((req.headers['host'] || '') + (req.url || ''));\n this.request = {\n method: req.method || '',\n user_agent: req.headers['user-agent'] || '',\n client_ip: getClientIp(req) || '',\n url: url || '',\n };\n if (forwarded)\n this.request.x_forwarded_for = forwarded;\n};\nvar getClientIp = function getClientIp(req) {\n var clientIp;\n if (req.headers['x-forwarded-for'])\n clientIp = (req.headers['x-forwarded-for'] || '').split(',')[0];\n else if (req.connection && req.connection.remoteAddress)\n clientIp = req.connection.remoteAddress;\n else if (req.socket && req.socket.remoteAddress)\n clientIp = req.socket.remoteAddress;\n else if (req.connection && req.connection.socket && req.connection.socket.remoteAddress)\n clientIp = req.connection.socket.remoteAddress;\n return clientIp;\n};\n/**\n * Closes the local and automatically captures the response data.\n * @param {http.ServerResponse|https.ServerResponse} res - The response object from the HTTP/HTTPS call.\n */\nIncomingRequestData.prototype.close = function close(res) {\n this.response = getHttpResponseData(res);\n};\nmodule.exports = IncomingRequestData;\n", "\"use strict\";\n/**\n * Represents a LocalReservoir object that keeps track of the number of traces per second sampled and\n * the fixed rate for a given sampling rule defined locally.\n * It also decides if a given trace should be sampled or not based on the state of current second.\n * @constructor\n * @param {number} fixedTarget - An integer value to specify the maximum number of traces per second to sample.\n * @param {number} fallbackRate - A value between 0 and 1 indicating the sampling rate after the maximum traces per second has been hit.\n */\nfunction LocalReservoir(fixedTarget, fallbackRate) {\n this.init(fixedTarget, fallbackRate);\n}\nLocalReservoir.prototype.init = function init(fixedTarget, fallbackRate) {\n this.usedThisSecond = 0;\n if (typeof fixedTarget === 'number' && fixedTarget % 1 === 0 && fixedTarget >= 0)\n this.fixedTarget = fixedTarget;\n else\n throw new Error('Error in sampling file. Rule attribute \"fixed_target\" must be a non-negative integer.');\n if (typeof fallbackRate === 'number' && fallbackRate >= 0 && fallbackRate <= 1)\n this.fallbackRate = fallbackRate;\n else\n throw new Error('Error in sampling file. Rule attribute \"rate\" must be a number between 0 and 1 inclusive.');\n};\nLocalReservoir.prototype.isSampled = function isSampled() {\n var now = Math.round(new Date().getTime() / 1000);\n if (now !== this.thisSecond) {\n this.usedThisSecond = 0;\n this.thisSecond = now;\n }\n if (this.usedThisSecond >= this.fixedTarget)\n return Math.random() < this.fallbackRate;\n this.usedThisSecond++;\n return true;\n};\nmodule.exports = LocalReservoir;\n", "\"use strict\";\nvar fs = require('fs');\nvar LocalReservoir = require('./local_reservoir');\nvar Utils = require('../../utils');\nvar defaultRules = require('../../resources/default_sampling_rules.json');\nvar logger = require('../../logger');\n/**\n * The local sampler used to make sampling decisions when the decisions are absent in the incoming requests\n * and the default sampler needs to fall back on local rules. It will also be the primary sampler\n * if the default sampler is disabled.\n * @module LocalSampler\n */\nvar LocalSampler = {\n /**\n * Makes a sample decision based on the sample request.\n * @param {object} sampleRequest - Contains information for rules matching.\n * @module LocalSampler\n * @function shouldSample\n */\n shouldSample: function shouldSample(sampleRequest) {\n var host = sampleRequest.host;\n var httpMethod = sampleRequest.httpMethod;\n var urlPath = sampleRequest.urlPath;\n var formatted = '{ http_method: ' + httpMethod + ', host: ' + host + ', url_path: ' + urlPath + ' }';\n var matched;\n this.rules.some(function (rule) {\n // Any null parameters provided will be considered an implicit match.\n if (rule.default || (host == null || (Utils.wildcardMatch(rule.host, host))\n && (httpMethod == null || Utils.wildcardMatch(rule.http_method, httpMethod))\n && (urlPath == null || Utils.wildcardMatch(rule.url_path, urlPath)))) {\n matched = rule.reservoir;\n logger.getLogger().debug('Local sampling rule match found for ' + formatted + '. Matched ' + (rule.default ?\n 'default' : '{ http_method: ' + rule.http_method + ', host: ' + rule.host + ', url_path: ' +\n rule.url_path + ' }') + '. Using fixed_target: ' + matched.fixedTarget + ' and rate: ' + matched.fallbackRate + '.');\n return true;\n }\n });\n if (matched) {\n return matched.isSampled();\n }\n else {\n logger.getLogger().debug('No sampling rule matched for ' + formatted);\n return false;\n }\n },\n /**\n * Set local rules for making sampling decisions.\n * @module LocalSampler\n * @function setLocalRules\n */\n setLocalRules: function setLocalRules(source) {\n if (source) {\n if (typeof source === 'string') {\n logger.getLogger().info('Using custom sampling rules file: ' + source);\n this.rules = loadRulesConfig(JSON.parse(fs.readFileSync(source, 'utf8')));\n }\n else {\n logger.getLogger().info('Using custom sampling rules source.');\n this.rules = loadRulesConfig(source);\n }\n }\n else\n this.rules = parseRulesConfig(defaultRules);\n }\n};\nvar loadRulesConfig = function loadRulesConfig(config) {\n if (!config.version)\n throw new Error('Error in sampling file. Missing \"version\" attribute.');\n if (config.version === 1 || config.version === 2)\n return parseRulesConfig(config);\n else\n throw new Error('Error in sampling file. Unknown version \"' + config.version + '\".');\n};\nvar parseRulesConfig = function parseRulesConfig(config) {\n var defaultRule;\n var rules = [];\n if (config.default) {\n var missing = [];\n for (var key in config.default) {\n if (key !== 'fixed_target' && key !== 'rate') {\n throw new Error('Error in sampling file. Invalid attribute for default: ' + key +\n '. Valid attributes for default are \"fixed_target\" and \"rate\".');\n }\n else if (typeof config.default[key] !== 'number') {\n throw new Error('Error in sampling file. Default ' + key + ' must be a number.');\n }\n }\n if (typeof config.default.fixed_target === 'undefined')\n missing.push('fixed_target');\n if (typeof config.default.rate === 'undefined')\n missing.push('rate');\n if (missing.length !== 0)\n throw new Error('Error in sampling file. Missing required attributes for default: ' + missing + '.');\n defaultRule = { default: true, reservoir: new LocalReservoir(config.default.fixed_target, config.default.rate) };\n }\n else {\n throw new Error('Error in sampling file. Expecting \"default\" object to be defined with attributes \"fixed_target\" and \"rate\".');\n }\n if (Array.isArray(config.rules)) {\n config.rules.forEach(function (rawRule) {\n var params = {};\n var required;\n if (config.version === 2)\n required = { host: 1, http_method: 1, url_path: 1, fixed_target: 1, rate: 1 };\n if (config.version === 1)\n required = { service_name: 1, http_method: 1, url_path: 1, fixed_target: 1, rate: 1 };\n for (var key in rawRule) {\n var value = rawRule[key];\n if (!required[key] && key != 'description')\n throw new Error('Error in sampling file. Rule ' + JSON.stringify(rawRule) + ' has invalid attribute: ' + key + '.');\n else if (key != 'description' && !value && value !== 0)\n throw new Error('Error in sampling file. Rule ' + JSON.stringify(rawRule) + ' attribute \"' + key + '\" has invalid value: ' + value + '.');\n else {\n if (config.version === 2)\n params[key] = value;\n if (config.version === 1 && key === 'service_name')\n params['host'] = value;\n else\n params[key] = value;\n delete required[key];\n }\n }\n if (Object.keys(required).length !== 0 && required.constructor === Object)\n throw new Error('Error in sampling file. Rule ' + JSON.stringify(rawRule) + ' is missing required attributes: ' + Object.keys(required) + '.');\n var rule = params;\n rule.reservoir = new LocalReservoir(rawRule.fixed_target, rawRule.rate);\n rules.push(rule);\n });\n }\n rules.push(defaultRule);\n return rules;\n};\nLocalSampler.setLocalRules();\nmodule.exports = LocalSampler;\n", "\"use strict\";\n/**\n * Represents a Reservoir object that keeps track of the number of traces per second sampled and\n * the fixed rate for a given sampling rule. This information is fetched from X-Ray serivce.\n * It decides if a given trace should be borrowed or sampled or not sampled based on the state of current second.\n * @constructor\n */\nfunction Reservoir() {\n this.init();\n}\nReservoir.prototype.init = function init() {\n this.quota = null;\n this.TTL = null;\n this.takenThisSec = 0;\n this.borrowedThisSec = 0;\n this.reportInterval = 1;\n this.reportElapsed = 0;\n};\nReservoir.prototype.borrowOrTake = function borrowOrTake(now, canBorrow) {\n this.adjustThisSec(now);\n // Don't borrow if the quota is available and fresh.\n if (this.quota >= 0 && this.TTL >= now) {\n if (this.takenThisSec >= this.quota)\n return false;\n this.takenThisSec++;\n return 'take';\n }\n // Otherwise try to borrow if the quota is not present or expired.\n if (canBorrow) {\n if (this.borrowedThisSec >= 1)\n return false;\n this.borrowedThisSec++;\n return 'borrow';\n }\n};\nReservoir.prototype.adjustThisSec = function adjustThisSec(now) {\n if (now !== this.thisSec) {\n this.takenThisSec = 0;\n this.borrowedThisSec = 0;\n this.thisSec = now;\n }\n};\nReservoir.prototype.loadNewQuota = function loadNewQuota(quota, TTL, interval) {\n if (quota)\n this.quota = quota;\n if (TTL)\n this.TTL = TTL;\n if (interval)\n this.reportInterval = interval / 10; // Report interval is always time of 10.\n};\nReservoir.prototype.timeToReport = function timeToReport() {\n if (this.reportElapsed + 1 >= this.reportInterval) {\n this.reportElapsed = 0;\n return true;\n }\n else {\n this.reportElapsed += 1;\n return false;\n }\n};\nmodule.exports = Reservoir;\n", "\"use strict\";\nvar Utils = require('../../utils');\nvar Reservoir = require('./reservoir');\n/**\n * The data model for a sampling rule defined using X-Ray API CreateSamplingRules.\n * It should be only instantiated directly from the X-Ray API response.\n * @constructor\n */\nfunction SamplingRule(name, priority, rate, reservoirSize, host, httpMethod, urlPath, serviceName, serviceType) {\n this.init(name, priority, rate, reservoirSize, host, httpMethod, urlPath, serviceName, serviceType);\n}\nSamplingRule.prototype.init = function init(name, priority, rate, reservoirSize, host, httpMethod, urlPath, serviceName, serviceType) {\n this.name = name;\n this.priority = priority;\n this.rate = rate;\n this.host = host;\n this.httpMethod = httpMethod;\n this.urlPath = urlPath;\n this.serviceName = serviceName;\n this.serviceType = serviceType;\n this.reservoir = new Reservoir();\n this.borrow = !!reservoirSize;\n this.resetStatistics();\n};\nSamplingRule.prototype.match = function match(sampleRequest) {\n var host = sampleRequest.host;\n var httpMethod = sampleRequest.httpMethod;\n var serviceName = sampleRequest.serviceName;\n var urlPath = sampleRequest.urlPath;\n var serviceType = sampleRequest.serviceType;\n return this.isDefault() || (!host || Utils.wildcardMatch(this.host, host))\n && (!httpMethod || Utils.wildcardMatch(this.httpMethod, httpMethod))\n && (!serviceName || Utils.wildcardMatch(this.serviceName, serviceName))\n && (!urlPath || Utils.wildcardMatch(this.urlPath, urlPath))\n && (!serviceType || Utils.wildcardMatch(this.serviceType, serviceType));\n};\nSamplingRule.prototype.snapshotStatistics = function snapshotStatistics() {\n var statistics = {\n requestCount: this.requestCount,\n borrowCount: this.borrowCount,\n sampledCount: this.sampledCount\n };\n this.resetStatistics();\n return statistics;\n};\nSamplingRule.prototype.merge = function merge(rule) {\n this.reservoir = rule.reservoir;\n this.requestCount = rule.requestCount;\n this.borrowCount = rule.borrowCount;\n this.sampledCount = rule.sampledCount;\n rule = null; // unref the old rule so it can be garbage collected.\n};\nSamplingRule.prototype.isDefault = function isDefault() {\n return this.name === 'Default'; // \"Default\" is a reserved keyword from X-Ray back-end.\n};\nSamplingRule.prototype.incrementRequestCount = function incrementRequestCount() {\n this.requestCount++;\n};\nSamplingRule.prototype.incrementBorrowCount = function incrementBorrowCount() {\n this.borrowCount++;\n};\nSamplingRule.prototype.incrementSampledCount = function incrementSampledCount() {\n this.sampledCount++;\n};\nSamplingRule.prototype.setRate = function setRate(rate) {\n this.rate = rate;\n};\nSamplingRule.prototype.getRate = function getRate() {\n return this.rate;\n};\nSamplingRule.prototype.getName = function getName() {\n return this.name;\n};\nSamplingRule.prototype.getPriority = function getPriority() {\n return this.priority;\n};\nSamplingRule.prototype.getReservoir = function getReservoir() {\n return this.reservoir;\n};\nSamplingRule.prototype.resetStatistics = function resetStatistics() {\n this.requestCount = 0;\n this.borrowCount = 0;\n this.sampledCount = 0;\n};\nSamplingRule.prototype.canBorrow = function canBorrow() {\n return this.borrow;\n};\nSamplingRule.prototype.everMatched = function everMatched() {\n return this.requestCount > 0;\n};\nSamplingRule.prototype.timeToReport = function timeToReport() {\n return this.reservoir.timeToReport();\n};\nmodule.exports = SamplingRule;\n", "\"use strict\";\nvar crypto = require('crypto');\nvar logger = require('../../logger');\nvar SamplingRule = require('./sampling_rule');\nvar DaemonConfig = require('../../daemon_config');\nconst util = require('util');\nconst http = require('http');\n/**\n * The ServiceConnector that calls X-Ray service and convert the API response bodies to data models\n * defined in the X-Ray SDK and return them to the pollers.\n * @module ServiceConnector\n */\nvar ServiceConnector = {\n // client_id is a 12 byte cryptographically secure random hex\n // identifying the SDK instance and is generated during SDK initialization/\n // This is required when reporting sampling to X-Ray back-end.\n clientId: crypto.randomBytes(12).toString('hex'),\n samplingRulesPath: '/GetSamplingRules',\n samplingTargetsPath: '/SamplingTargets',\n logger: logger,\n httpClient: http,\n fetchSamplingRules: function fetchSamplingRules(callback) {\n const body = '{}'; // Payload needed for GetSamplingRules POST request\n const options = getOptions(this.samplingRulesPath, body.length);\n const httpReq = this.httpClient.__request ? this.httpClient.__request : this.httpClient.request;\n const req = httpReq(options, res => {\n var data = '';\n res.on('data', d => {\n data += d;\n });\n res.on('error', error => {\n callback(error);\n });\n res.on('end', () => {\n var dataObj;\n try {\n dataObj = JSON.parse(data);\n }\n catch (err) {\n callback(err);\n return;\n }\n if (!dataObj) {\n callback(new Error('AWS X-Ray GetSamplingRules API returned empty response'));\n return;\n }\n var newRules = assembleRules(dataObj);\n callback(null, newRules);\n });\n });\n req.on('error', (err) => {\n callback(new Error(`Failed to connect to X-Ray daemon at ${options.hostname}:${options.port} to get sampling rules.`));\n });\n req.write(body);\n req.end();\n },\n fetchTargets: function fetchTargets(rules, callback) {\n const body = JSON.stringify(constructStatisticsDocs(rules));\n const options = getOptions(this.samplingTargetsPath, body.length);\n const httpReq = this.httpClient.__request ? this.httpClient.__request : this.httpClient.request;\n const req = httpReq(options, res => {\n var data = '';\n res.on('data', d => {\n data += d;\n });\n res.on('error', error => {\n callback(error);\n });\n res.on('end', () => {\n var dataObj;\n try {\n dataObj = JSON.parse(data);\n }\n catch (err) {\n callback(err);\n return;\n }\n if (!dataObj || typeof dataObj['LastRuleModification'] != 'number') {\n callback(new Error('AWS X-Ray SamplingTargets API returned invalid response'));\n return;\n }\n var targetsMapping = assembleTargets(dataObj);\n var ruleFreshness = dateToEpoch(dataObj['LastRuleModification']);\n callback(null, targetsMapping, ruleFreshness);\n });\n });\n req.on('error', (err) => {\n callback(new Error(`Failed to connect to X-Ray daemon at ${options.hostname}:${options.port} to get sampling targets.`));\n });\n req.write(body);\n req.end();\n }\n};\nvar constructStatisticsDocs = function constructStatisticsDocs(rules) {\n var documents = [];\n var now = Math.floor(new Date().getTime() / 1000);\n rules.forEach(function (rule) {\n var statistics = rule.snapshotStatistics();\n var doc = {\n 'RuleName': rule.getName(),\n 'ClientID': ServiceConnector.clientId,\n 'RequestCount': statistics.requestCount,\n 'BorrowCount': statistics.borrowCount,\n 'SampledCount': statistics.sampledCount,\n 'Timestamp': now\n };\n documents.push(doc);\n });\n return { SamplingStatisticsDocuments: documents };\n};\nvar assembleRules = function assembleRules(data) {\n var newRules = [];\n var ruleList = data['SamplingRuleRecords'] || [];\n ruleList.forEach(function (ruleRecord) {\n ruleRecord = ruleRecord['SamplingRule'];\n // For forward compatibility reason right now it only\n // deals with version 1 sampling rules.\n if (isRuleValid(ruleRecord)) {\n var newRule = new SamplingRule(ruleRecord['RuleName'], ruleRecord['Priority'], ruleRecord['FixedRate'], ruleRecord['ReservoirSize'], ruleRecord['Host'], ruleRecord['HTTPMethod'], ruleRecord['URLPath'], ruleRecord['ServiceName'], ruleRecord['ServiceType']);\n newRules.push(newRule);\n }\n });\n return newRules;\n};\nvar assembleTargets = function assembleTargets(data) {\n var docs = data['SamplingTargetDocuments'] || [];\n var targetsMapping = {};\n docs.forEach(function (doc) {\n var newTarget = {\n rate: doc['FixedRate'],\n quota: doc['ReservoirQuota'],\n TTL: dateToEpoch(doc['ReservoirQuotaTTL']),\n interval: doc['Interval']\n };\n targetsMapping[doc['RuleName']] = newTarget;\n });\n return targetsMapping;\n};\nvar isRuleValid = function isRuleValid(record) {\n return record['Version'] === 1\n && record['ResourceARN'] === '*'\n && record['Attributes'] && Object.keys(record['Attributes']).length === 0\n && record['ServiceType']\n && record['RuleName']\n && record['Priority']\n && typeof record['FixedRate'] == 'number';\n};\nvar dateToEpoch = function dateToEpoch(date) {\n return new Date(date).getTime() / 1000;\n};\nvar getOptions = function getOptions(path, contentLength) {\n const options = {\n hostname: DaemonConfig.tcp_ip,\n port: DaemonConfig.tcp_port,\n method: 'POST',\n path: path,\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': contentLength,\n 'Host': util.format('%s:%d', DaemonConfig.tcp_ip, DaemonConfig.tcp_port)\n }\n };\n return options;\n};\nmodule.exports = ServiceConnector;\n", "\"use strict\";\nvar TTL = 60 * 60; // The cache expires 1 hour after the last refresh time.\n/**\n * The rule cache that stores sampling rules fetched from X-Ray service.\n * @module RuleCache\n */\nvar RuleCache = {\n rules: [],\n lastUpdated: null,\n /**\n * Tries to find a valid rule that matches the sample request.\n * @param {object} sampleRequest - Contains information for rules matching.\n * @param {number} now - Current epoch in seconds.\n * @module RuleCache\n * @function getMatchedRule\n */\n getMatchedRule: function getMatchedRule(sampleRequest, now) {\n if (isExpired(now))\n return null;\n var matchedRule;\n this.rules.forEach(function (rule) {\n if (!matchedRule && rule.match(sampleRequest))\n matchedRule = rule;\n if (rule.isDefault() && !matchedRule)\n matchedRule = rule;\n });\n return matchedRule;\n },\n /**\n * Load rules fetched from X-Ray service in order sorted by priorities.\n * @param {object} rules - Newly fetched rules to load.\n * @module RuleCache\n * @function loadRules\n */\n loadRules: function loadRules(rules) {\n // Record the old rules for later merging.\n var oldRules = {};\n this.rules.forEach(function (rule) {\n oldRules[rule.getName()] = rule;\n });\n // Update the rules in the cache.\n this.rules = rules;\n // Transfer state information to refreshed rules.\n this.rules.forEach(function (rule) {\n var oldRule = oldRules[rule.getName()];\n if (oldRule)\n rule.merge(oldRule);\n });\n // The cache should maintain the order of the rules based on\n // priority. If priority is the same we sort name by alphabet\n // as rule name is unique.\n this.rules.sort(function (a, b) {\n var v = a.getPriority() - b.getPriority();\n if (v !== 0)\n return v;\n if (a.getName() > b.getName())\n return 1;\n else\n return -1;\n });\n },\n /**\n * Load targets fetched from X-Ray service.\n * @param {object} targetsMapping - Newly fetched targets map with rule name as key.\n * @module RuleCache\n * @function loadTargets\n */\n loadTargets: function loadTargets(targetsMapping) {\n this.rules.forEach(function (rule) {\n var target = targetsMapping[rule.getName()];\n if (target) {\n rule.getReservoir().loadNewQuota(target.quota, target.TTL, target.interval);\n rule.setRate(target.rate);\n }\n });\n },\n getRules: function getRules() {\n return this.rules;\n },\n timestamp: function timestamp(now) {\n this.lastUpdated = now;\n },\n getLastUpdated: function getLastUpdated() {\n return this.lastUpdated;\n }\n};\nvar isExpired = function isExpired(now) {\n // The cache is considered expired if it is never loaded.\n if (!RuleCache.getLastUpdated())\n return true;\n return now > RuleCache.getLastUpdated() + TTL;\n};\nmodule.exports = RuleCache;\n", "\"use strict\";\nvar logger = require('../../logger');\nvar ServiceConnector = require('./service_connector');\nvar ruleCache = require('./rule_cache');\nvar DEFAULT_INTERVAL = 5 * 60 * 1000; // 5 minutes on sampling rules fetch\n/**\n * The RulePoller that periodically fetch sampling rules from X-Ray service\n * and load them into RuleCache.\n * @module RulePoller\n */\nvar RulePoller = {\n start: function start() {\n if (this.poller)\n clearInterval(this.poller);\n // Refresh sampling rules cache with no jitter upon start.\n refresh(false);\n this.poller = setInterval(refresh, DEFAULT_INTERVAL);\n this.poller.unref();\n },\n};\nvar refresh = function refresh(jitter) {\n // Add jitter by default unless explicitly told not to.\n jitter = typeof jitter === 'undefined' ? true : jitter;\n if (jitter) {\n var delay = getJitter();\n setTimeout(refreshWithFirewall, delay);\n }\n else\n refreshWithFirewall();\n};\nvar refreshWithFirewall = function refreshWithFirewall() {\n try {\n refreshCache();\n }\n catch (e) {\n logger.getLogger().warn('Encountered unexpected exception when fetching sampling rules: ' + e);\n }\n};\nvar refreshCache = function refreshCache() {\n // Timestamp should be generated *before* the actual outbound call to ensure\n // we don't mark the cache as being fresher than it actually is.\n var now = Math.floor(new Date().getTime() / 1000);\n // Pass a callback that only runs when the new rules are\n // successfully fetched. \n ServiceConnector.fetchSamplingRules(function (err, newRules) {\n if (err) {\n logger.getLogger().warn('Failed to retrieve sampling rules from X-Ray service:', err);\n }\n else if (newRules.length !== 0) {\n ruleCache.loadRules(newRules);\n ruleCache.timestamp(now);\n logger.getLogger().info('Successfully refreshed centralized sampling rule cache.');\n }\n });\n};\n// A random jitter of up to 5 seconds is injected after every run to ensure\n// the calls eventually get evenly distributed over the 5 minute window.\nvar getJitter = function getJitter() {\n return Math.random() * 5;\n};\nmodule.exports = RulePoller;\n", "\"use strict\";\nvar rulePoller = require('./rule_poller');\nvar serviceConnector = require('./service_connector');\nvar ruleCache = require('./rule_cache');\nvar logger = require('../../logger');\nvar DEFAULT_INTERVAL = 10 * 1000; // 10 seconds on sampling targets fetch\n/**\n * The TargetPoller that periodically fetch sampling targets from X-Ray service\n * and load them into RuleCache.\n * @module TargetPoller\n */\nvar TargetPoller = {\n interval: DEFAULT_INTERVAL,\n start: function start() {\n this.poller = setInterval(refreshWithFirewall, DEFAULT_INTERVAL + getJitter());\n this.poller.unref();\n },\n};\nvar refreshWithFirewall = function refreshWithFirewall() {\n try {\n refresh();\n }\n catch (e) {\n logger.getLogger().warn('Encountered unexpected exception when fetching sampling targets: ' + e);\n }\n};\nvar refresh = function refresh() {\n var candidates = getCandidates();\n if (candidates && candidates.length > 0) {\n serviceConnector.fetchTargets(candidates, function (err, targetsMapping, ruleFreshness) {\n if (err) {\n logger.getLogger().warn('Failed to retrieve sampling targets from X-Ray service:', err);\n return;\n }\n ruleCache.loadTargets(targetsMapping);\n if (ruleFreshness > ruleCache.getLastUpdated()) {\n logger.getLogger().info('Performing out-of-band sampling rule polling to fetch updated rules.');\n rulePoller.start();\n }\n logger.getLogger().info('Successfully reported rule statistics to get new sampling quota.');\n });\n }\n};\n// Don't report a rule statistics if any of the conditions is met:\n// 1. The report time hasn't come (some rules might have larger report intervals).\n// 2. The rule is never matched.\nvar getCandidates = function getCandidates() {\n var rules = ruleCache.getRules();\n var candidates = [];\n rules.forEach(function (rule) {\n if (rule.everMatched() && rule.timeToReport())\n candidates.push(rule);\n });\n return candidates;\n};\n// A random jitter of up to 0.1 seconds is injected after every run to ensure\n// the calls eventually get evenly distributed over the 10 second window.\nvar getJitter = function getJitter() {\n return Math.random() / TargetPoller.interval;\n};\nmodule.exports = TargetPoller;\n", "\"use strict\";\nvar logger = require('../../logger');\nconst util = require('util');\nvar SegmentUtils = require('../../segments/segment_utils');\n/**\n * The default sampler used to make sampling decisions when the decisions are absent in the incoming requests.\n * The sampler use pollers to poll sampling rules from X-Ray service.\n * @module DefaultSampler\n */\nvar DefaultSampler = {\n localSampler: require('./local_sampler'),\n rulePoller: require('./rule_poller'),\n targetPoller: require('./target_poller'),\n ruleCache: require('./rule_cache'),\n started: false,\n /**\n * Makes a sample decision based on the sample request.\n * @param {object} sampleRequest - Contains information for rules matching.\n * @module DefaultSampler\n * @function shouldSample\n */\n shouldSample: function shouldSample(sampleRequest) {\n try {\n if (!this.started)\n this.start();\n if (!sampleRequest.serviceType)\n sampleRequest.serviceType = SegmentUtils.origin;\n var now = Math.floor(new Date().getTime() / 1000);\n var matchedRule = this.ruleCache.getMatchedRule(sampleRequest, now);\n if (matchedRule) {\n logger.getLogger().debug(util.format('Rule %s is matched.', matchedRule.getName()));\n return processMatchedRule(matchedRule, now);\n }\n else {\n logger.getLogger().info('No effective centralized sampling rule match. Fallback to local rules.');\n return this.localSampler.shouldSample(sampleRequest);\n }\n }\n catch (err) {\n logger.getLogger().error('Unhandled exception by the SDK during making sampling decisions: ' + err);\n }\n },\n /**\n * Set local rules in case there is a need to fallback.\n * @module DefaultSampler\n * @function setLocalRules\n */\n setLocalRules: function setLocalRules(source) {\n this.localSampler.setLocalRules(source);\n },\n /**\n * Start the pollers to poll sampling rules and targets from X-Ray service.\n * @module DefaultSampler\n * @function start\n */\n start: function start() {\n if (!this.started) {\n this.rulePoller.start();\n this.targetPoller.start();\n this.started = true;\n }\n }\n};\nvar processMatchedRule = function processMatchedRule(rule, now) {\n // As long as a rule is matched we increment request counter.\n rule.incrementRequestCount();\n var reservoir = rule.getReservoir();\n var sample = true;\n // We check if we can borrow or take from reservoir first.\n var decision = reservoir.borrowOrTake(now, rule.canBorrow());\n if (decision === 'borrow')\n rule.incrementBorrowCount();\n else if (decision === 'take')\n rule.incrementSampledCount();\n // Otherwise we compute based on FixedRate of this sampling rule.\n else if (Math.random() <= rule.getRate())\n rule.incrementSampledCount();\n else\n sample = false;\n if (sample)\n return rule.getName();\n else\n return false;\n};\nmodule.exports = DefaultSampler;\n", "\"use strict\";\n/**\n * Middleware Utils module.\n *\n * Exposes various configuration and helper methods to be used by the middleware.\n * @module mw_utils\n */\nvar Segment = require('../segments/segment');\nvar IncomingRequestData = require('./incoming_request_data');\nvar logger = require('../logger');\nvar coreUtils = require('../utils');\nvar wildcardMatch = require('../utils').wildcardMatch;\nvar processTraceData = require('../utils').processTraceData;\n//headers are case-insensitive\nvar XRAY_HEADER = 'x-amzn-trace-id';\nvar overrideFlag = !!process.env.AWS_XRAY_TRACING_NAME;\nvar utils = {\n defaultName: process.env.AWS_XRAY_TRACING_NAME,\n dynamicNaming: false,\n hostPattern: null,\n sampler: require('./sampling/default_sampler'),\n /**\n * Enables dynamic naming for segments via the middleware. Use 'AWSXRay.middleware.enableDynamicNaming()'.\n * @param {string} [hostPattern] - The pattern to match the host header. See the README on dynamic and fixed naming modes.\n * @alias module:mw_utils.enableDynamicNaming\n */\n enableDynamicNaming: function (hostPattern) {\n this.dynamicNaming = true;\n if (hostPattern && typeof hostPattern !== 'string')\n throw new Error('Host pattern must be a string.');\n this.hostPattern = hostPattern || null;\n },\n /**\n * Splits out the 'x-amzn-trace-id' header params from the incoming request. Used by the middleware.\n * @param {http.IncomingMessage|https.IncomingMessage} req - The request object from the incoming call.\n * @returns {object}\n * @alias module:mw_utils.processHeaders\n */\n processHeaders: function processHeaders(req) {\n var amznTraceHeader = {};\n if (req && req.headers && req.headers[XRAY_HEADER]) {\n amznTraceHeader = processTraceData(req.headers[XRAY_HEADER]);\n }\n return amznTraceHeader;\n },\n /**\n * Resolves the name of the segment as determined by fixed or dynamic mode options. Used by the middleware.\n * @param {string} hostHeader - The string from the request.headers.host property.\n * @returns {string}\n * @alias module:mw_utils.resolveName\n */\n resolveName: function resolveName(hostHeader) {\n var name;\n if (this.dynamicNaming && hostHeader)\n name = this.hostPattern ? (wildcardMatch(this.hostPattern, hostHeader) ? hostHeader : this.defaultName) : hostHeader;\n else\n name = this.defaultName;\n return name;\n },\n /**\n * Resolves the sampling decision as determined by the values given and options set. Used by the middleware.\n * @param {object} amznTraceHeader - The object as returned by the processHeaders function.\n * @param {Segment} segment - The string from the request.headers.host property.\n * @param {http.ServerResponse|https.ServerResponse} res - The response object from the incoming call.\n * @returns {boolean}\n * @alias module:mw_utils.resolveSampling\n */\n resolveSampling: function resolveSampling(amznTraceHeader, segment, res) {\n var isSampled;\n if (amznTraceHeader.sampled === '1')\n isSampled = true;\n else if (amznTraceHeader.sampled === '0')\n isSampled = false;\n else {\n var sampleRequest = {\n host: res.req.headers.host,\n httpMethod: res.req.method,\n urlPath: res.req.url,\n serviceName: segment.name\n };\n isSampled = this.sampler.shouldSample(sampleRequest);\n if (isSampled instanceof String || typeof isSampled === 'string') {\n segment.setMatchedSamplingRule(isSampled);\n isSampled = true;\n }\n }\n if (amznTraceHeader.sampled === '?')\n res.header[XRAY_HEADER] = 'Root=' + amznTraceHeader.root + ';Sampled=' + (isSampled ? '1' : '0');\n if (!isSampled)\n segment.notTraced = true;\n },\n /**\n * Sets the default name of created segments. Used with the middleware.\n * Can be overridden by the AWS_XRAY_TRACING_NAME environment variable.\n * @param {string} name - The default name for segments created in the middleware.\n * @alias module:mw_utils.setDefaultName\n */\n setDefaultName: function setDefaultName(name) {\n if (!overrideFlag)\n this.defaultName = name;\n },\n disableCentralizedSampling: function disableCentralizedSampling() {\n this.sampler = require('./sampling/local_sampler');\n },\n /**\n * Overrides the default sampling rules file to specify at what rate to sample at for specific routes.\n * The base sampling rules file can be found at /lib/resources/default_sampling_rules.json\n * @param {string|Object} source - The path to the custom sampling rules file, or the source JSON object.\n * @memberof AWSXRay\n */\n setSamplingRules: function setSamplingRules(source) {\n if (!source || source instanceof String || !(typeof source === 'string' || (source instanceof Object)))\n throw new Error('Please specify a path to the local sampling rules file, or supply an object containing the rules.');\n this.sampler.setLocalRules(source);\n },\n /**\n * Logs a debug message including core request and segment information\n * @param {string} message - The message to be logged\n * @param {string} url - The request url being traced\n * @param {Segment} - The current segment\n */\n middlewareLog: function middlewareLog(message, url, segment) {\n logger.getLogger().debug(message + ': { url: ' + url + ', name: ' + segment.name + ', trace_id: ' +\n segment.trace_id + ', id: ' + segment.id + ', sampled: ' + !segment.notTraced + ' }');\n },\n /**\n * Traces the request/response cycle of an http.IncomingMessage / http.ServerResponse pair.\n * Resolves sampling rules, creates a segment, adds the core request / response data adding\n * throttling / error / fault flags based on the response status code.\n * @param {http.IncomingMessage} req - The incoming request.\n * @param {http.ServerResponse} res - The server response.\n * @returns {Segment}\n * @memberof AWSXRay\n */\n traceRequestResponseCycle: function traceRequestResponseCycle(req, res) {\n var amznTraceHeader = this.processHeaders(req);\n var name = this.resolveName(req.headers.host);\n var segment = new Segment(name, amznTraceHeader.root, amznTraceHeader.parent);\n var responseWithEmbeddedRequest = Object.assign({}, res, { req: req });\n this.resolveSampling(amznTraceHeader, segment, responseWithEmbeddedRequest);\n segment.addIncomingRequestData(new IncomingRequestData(req));\n this.middlewareLog('Starting middleware segment', req.url, segment);\n var middlewareLog = this.middlewareLog;\n var didEnd = false;\n var endSegment = function () {\n // ensure `endSegment` is only called once\n // in some versions of node.js 10.x and in all versions of node.js 11.x and higher,\n // the 'finish' and 'close' event are BOTH triggered.\n // Previously, only one or the other was triggered:\n // https://github.com/nodejs/node/pull/20611\n if (didEnd)\n return;\n didEnd = true;\n if (res.statusCode === 429) {\n segment.addThrottleFlag();\n }\n const cause = coreUtils.getCauseTypeFromHttpStatus(res.statusCode);\n if (cause) {\n segment[cause] = true;\n }\n segment.http.close(res);\n segment.close();\n middlewareLog('Closed middleware segment successfully', req.url, segment);\n };\n res.on('finish', endSegment);\n res.on('close', endSegment);\n return segment;\n }\n};\nmodule.exports = utils;\n", "\"use strict\";\nvar contextUtils = require('../context_utils');\nvar mwUtils = require('../middleware/mw_utils');\nvar LambdaUtils = require('../utils').LambdaUtils;\nvar Segment = require('../segments/segment');\nvar SegmentEmitter = require('../segment_emitter');\nvar SegmentUtils = require('../segments/segment_utils');\nvar logger = require('../logger');\nconst TraceID = require('../segments/attributes/trace_id');\n/**\n * @namespace\n * @ignore\n */\nvar xAmznTraceIdPrev = null;\n/**\n* Used to initialize segments on AWS Lambda with extra data from the context.\n*/\nmodule.exports.init = function init() {\n contextUtils.enableManualMode = function () {\n logger.getLogger().warn('AWS Lambda does not support AWS X-Ray manual mode.');\n };\n SegmentEmitter.disableReusableSocket();\n SegmentUtils.setStreamingThreshold(0);\n /**\n * Disabling all centralized sampling in Lambda environments. The sampling decisions would be\n * uselessly applied to the facade segment, and the sampling pollers were causing errors.\n *\n * See: https://github.com/aws/aws-xray-sdk-node/issues/217\n */\n logger.getLogger().info('Disabling centralized sampling in Lambda environment.');\n mwUtils.disableCentralizedSampling();\n var namespace = contextUtils.getNamespace();\n namespace.enter(namespace.createContext());\n contextUtils.setSegment(facadeSegment());\n};\nvar facadeSegment = function facadeSegment() {\n var segment = new Segment('facade');\n var whitelistFcn = ['addNewSubsegment', 'addSubsegment', 'removeSubsegment', 'toString'];\n var silentFcn = ['incrementCounter', 'decrementCounter', 'isClosed', 'close', 'format', 'flush'];\n var xAmznTraceId = process.env._X_AMZN_TRACE_ID;\n for (var key in segment) {\n if (typeof segment[key] === 'function' && whitelistFcn.indexOf(key) === -1) {\n if (silentFcn.indexOf(key) === -1) {\n segment[key] = (function () {\n var func = key;\n return function facade() {\n logger.getLogger().warn('Function \"' + func + '\" cannot be called on an AWS Lambda segment. Please use a subsegment to record data.');\n return;\n };\n })();\n }\n else {\n segment[key] = function facade() { return; };\n }\n }\n }\n segment.trace_id = TraceID.Invalid().toString();\n segment.isClosed = function () { return true; };\n segment.in_progress = false;\n segment.counter = 1;\n segment.notTraced = true;\n segment.facade = true;\n segment.reset = function reset() {\n this.trace_id = TraceID.Invalid().toString();\n this.id = '00000000';\n delete this.subsegments;\n this.notTraced = true;\n };\n segment.resolveLambdaTraceData = function resolveLambdaTraceData() {\n var xAmznLambda = process.env._X_AMZN_TRACE_ID;\n if (xAmznLambda) {\n // This check resets the trace data whenever a new trace header is read to not leak data between invocations\n if (xAmznLambda != xAmznTraceIdPrev) {\n this.reset();\n if (LambdaUtils.populateTraceData(segment, xAmznLambda))\n xAmznTraceIdPrev = xAmznLambda;\n }\n }\n else {\n this.reset();\n contextUtils.contextMissingStrategy.contextMissing('Missing AWS Lambda trace data for X-Ray. ' +\n 'Ensure Active Tracing is enabled and no subsegments are created outside the function handler.');\n }\n };\n // Test for valid trace data during SDK startup. It's likely we're still in the cold-start portion of the\n // code at this point and a valid trace header has not been set\n if (LambdaUtils.validTraceData(xAmznTraceId)) {\n if (LambdaUtils.populateTraceData(segment, xAmznTraceId))\n xAmznTraceIdPrev = xAmznTraceId;\n }\n return segment;\n};\n", "\"use strict\";\nvar http = require('http');\nvar Plugin = {\n METADATA_TIMEOUT: 1000,\n /**\n * Asynchronously retrieves metadata from on-instance endpoint with an HTTP request using retries for\n * requests that time out.\n * @param {object} options - The HTTP options to make the request with\n * @param {function} callback - callback to plugin\n */\n getPluginMetadata: function (options, callback) {\n const METADATA_RETRY_TIMEOUT = 250; // Millis\n const METADATA_RETRIES = 5;\n var retries = METADATA_RETRIES;\n var getMetadata = function () {\n var httpReq = http.__request ? http.__request : http.request;\n var req = httpReq(options, function (res) {\n var body = '';\n res.on('data', function (chunk) {\n body += chunk;\n });\n res.on('end', function () {\n if (this.statusCode === 200 || this.statusCode === 300) {\n try {\n body = JSON.parse(body);\n }\n catch (e) {\n callback(e);\n return;\n }\n callback(null, body);\n }\n else if (retries > 0 && Math.floor(this.statusCode / 100) === 5) {\n retries--;\n setTimeout(getMetadata, METADATA_RETRY_TIMEOUT);\n }\n else {\n callback(new Error(`Failed to retrieve metadata with options: ${options}`));\n }\n });\n });\n req.on('error', function (err) {\n callback(err);\n });\n req.on('timeout', function () {\n req.abort();\n });\n req.setTimeout(Plugin.METADATA_TIMEOUT);\n req.end();\n };\n getMetadata();\n }\n};\nmodule.exports = Plugin;\n", "\"use strict\";\nvar Plugin = require('./plugin');\nvar logger = require('../../logger');\nvar http = require('http');\nvar EC2Plugin = {\n /**\n * A function to get the instance data from the EC2 metadata service.\n * @param {function} callback - The callback for the plugin loader.\n */\n getData: function (callback) {\n const METADATA_PATH = '/latest/dynamic/instance-identity/document';\n function populateMetadata(token) {\n const options = getOptions(METADATA_PATH, 'GET', token ? { 'X-aws-ec2-metadata-token': token } : {});\n Plugin.getPluginMetadata(options, function (err, data) {\n if (err || !data) {\n logger.getLogger().error('Error loading EC2 plugin metadata: ', err ? err.toString() : 'Could not retrieve data from IMDS.');\n callback();\n return;\n }\n const metadata = {\n ec2: {\n instance_id: data.instanceId,\n availability_zone: data.availabilityZone,\n instance_size: data.instanceType,\n ami_id: data.imageId\n }\n };\n callback(metadata);\n });\n }\n /**\n * This kicks off a requet to get a token used for requests to IMDSv2. If the request for the token\n * fails, we fall back to IMDSv1. Otherwise, the token will be used for an IMDSv2 request.\n */\n getToken(function (token) {\n if (token === null) {\n logger.getLogger().debug('EC2Plugin failed to get token from IMDSv2. Falling back to IMDSv1.');\n }\n populateMetadata(token);\n });\n },\n originName: 'AWS::EC2::Instance'\n};\n/**\n * Asynchronously retrieves a token used in requests to EC2 instance metadata service.\n * @param {function} callback - callback to plugin\n */\nfunction getToken(callback) {\n const httpReq = http.__request ? http.__request : http.request;\n const TTL = 60; //seconds\n const TOKEN_PATH = '/latest/api/token';\n const options = getOptions(TOKEN_PATH, 'PUT', {\n 'X-aws-ec2-metadata-token-ttl-seconds': TTL\n });\n let req = httpReq(options, function (res) {\n let body = '';\n res.on('data', function (chunk) {\n body += chunk;\n });\n res.on('end', function () {\n if (this.statusCode === 200 || this.statusCode === 300) {\n callback(body);\n }\n else {\n callback(null);\n }\n });\n });\n req.on('error', function () {\n callback(null);\n });\n req.on('timeout', function () {\n req.abort();\n callback(null);\n });\n req.setTimeout(Plugin.METADATA_TIMEOUT);\n req.end();\n}\nfunction getOptions(path, method, headers) {\n if (!method) {\n method = 'GET';\n }\n if (!headers) {\n headers = {};\n }\n return {\n host: '169.254.169.254',\n path: path,\n method: method,\n headers: headers\n };\n}\nmodule.exports = EC2Plugin;\n", "\"use strict\";\nvar os = require('os');\nvar ECSPlugin = {\n /**\n * A function to get the instance data from the ECS instance.\n * @param {function} callback - The callback for the plugin loader.\n */\n getData: function (callback) {\n callback({ ecs: { container: os.hostname() } });\n },\n originName: 'AWS::ECS::Container'\n};\nmodule.exports = ECSPlugin;\n", "\"use strict\";\nvar fs = require('fs');\nvar logger = require('../../logger');\nvar ENV_CONFIG_LOCATION = '/var/elasticbeanstalk/xray/environment.conf';\nvar ElasticBeanstalkPlugin = {\n /**\n * A function to get data from the Elastic Beanstalk environment configuration file.\n * @param {function} callback - The callback for the plugin loader.\n */\n getData: function (callback) {\n fs.readFile(ENV_CONFIG_LOCATION, 'utf8', function (err, rawData) {\n if (err) {\n logger.getLogger().error('Error loading Elastic Beanstalk plugin:', err.stack);\n callback();\n }\n else {\n var data = JSON.parse(rawData);\n var metadata = {\n elastic_beanstalk: {\n environment: data.environment_name,\n version_label: data.version_label,\n deployment_id: data.deployment_id\n }\n };\n callback(metadata);\n }\n });\n },\n originName: 'AWS::ElasticBeanstalk::Environment'\n};\nmodule.exports = ElasticBeanstalkPlugin;\n", "\"use strict\";\nvar fs = require('fs');\nvar logger = require('../logger');\nvar whitelist = require('../resources/aws_whitelist.json');\nvar paramTypes = {\n REQ_DESC: 'request_descriptors',\n REQ_PARAMS: 'request_parameters',\n RES_DESC: 'response_descriptors',\n RES_PARAMS: 'response_parameters'\n};\n/**\n * Represents a set of AWS services, operations and keys or params to capture.\n * @constructor\n * @param {string|Object} [source] - The location or source JSON object of the custom AWS whitelist file. If none is provided, the default file will be used.\n */\nfunction CallCapturer(source) {\n this.init(source);\n}\nCallCapturer.prototype.init = function init(source) {\n if (source) {\n if (typeof source === 'string') {\n logger.getLogger().info('Using custom AWS whitelist file: ' + source);\n this.services = loadWhitelist(JSON.parse(fs.readFileSync(source, 'utf8')));\n }\n else {\n logger.getLogger().info('Using custom AWS whitelist source.');\n this.services = loadWhitelist(source);\n }\n }\n else\n this.services = whitelist.services;\n};\nCallCapturer.prototype.append = function append(source) {\n var newServices = {};\n if (typeof source === 'string') {\n logger.getLogger().info('Appending AWS whitelist with custom file: ' + source);\n newServices = loadWhitelist(JSON.parse(fs.readFileSync(source, 'utf8')));\n }\n else {\n logger.getLogger().info('Appending AWS whitelist with a custom source.');\n newServices = loadWhitelist(source);\n }\n for (var attribute in newServices) {\n this.services[attribute] = newServices[attribute];\n }\n};\nCallCapturer.prototype.capture = function capture(serviceName, response) {\n var operation = response.request.operation;\n var call = this.services[serviceName] !== undefined ? this.services[serviceName].operations[operation] : null;\n if (call === null) {\n logger.getLogger().debug('Call \"' + serviceName + '.' + operation + '\" is not whitelisted for additional data capturing. Ignoring.');\n return;\n }\n var dataCaptured = {};\n for (var paramType in call) {\n var params = call[paramType];\n if (paramType === paramTypes.REQ_PARAMS) {\n captureCallParams(params, response.request.params, dataCaptured);\n }\n else if (paramType === paramTypes.REQ_DESC) {\n captureDescriptors(params, response.request.params, dataCaptured);\n }\n else if (paramType === paramTypes.RES_PARAMS) {\n if (response.data) {\n captureCallParams(params, response.data, dataCaptured);\n }\n }\n else if (paramType === paramTypes.RES_DESC) {\n if (response.data) {\n captureDescriptors(params, response.data, dataCaptured);\n }\n }\n else {\n logger.getLogger().error('Unknown parameter type \"' + paramType + '\". Must be \"request_descriptors\", \"response_descriptors\", ' +\n '\"request_parameters\" or \"response_parameters\".');\n }\n }\n return dataCaptured;\n};\nfunction captureCallParams(params, call, data) {\n params.forEach(function (param) {\n if (typeof call[param] !== 'undefined') {\n var formatted = toSnakeCase(param);\n this[formatted] = call[param];\n }\n }, data);\n}\nfunction captureDescriptors(descriptors, params, data) {\n for (var paramName in descriptors) {\n var attributes = descriptors[paramName];\n if (typeof params[paramName] !== 'undefined') {\n var paramData;\n if (attributes.list && attributes.get_count)\n paramData = params[paramName] ? params[paramName].length : 0;\n else\n paramData = attributes.get_keys === true ? Object.keys(params[paramName]) : params[paramName];\n if (typeof attributes.rename_to === 'string') {\n data[attributes.rename_to] = paramData;\n }\n else {\n var formatted = toSnakeCase(paramName);\n data[formatted] = paramData;\n }\n }\n }\n}\nfunction toSnakeCase(param) {\n if (param === 'IPAddress')\n return 'ip_address';\n else\n return param.split(/(?=[A-Z])/).join('_').toLowerCase();\n}\nfunction loadWhitelist(source) {\n var doc = source;\n if (doc.services === undefined)\n throw new Error('Document formatting is incorrect. Expecting \"services\" param.');\n return doc.services;\n}\nmodule.exports = CallCapturer;\n", "\"use strict\";\nvar CallCapturer = require('../../patchers/call_capturer.js');\nvar capturer = new CallCapturer();\n/**\n * Represents a AWS client call. Automatically captures data from the supplied response object,\n * Data captured depends on the whitelisting file supplied.\n * The base whitelisting file can be found at /lib/resources/aws_whitelist.json.\n * @constructor\n * @param {any} res - The response object from the AWS call. Typed as any to avoid AWS SDK dependency. Otherwise would be AWS.Response.\n * @param {string} serviceName - The service name of the AWS client.\n * @see https://github.com/aws/aws-sdk-js/blob/master/lib/response.js\n */\nfunction Aws(res, serviceName) {\n this.init(res, serviceName);\n}\nAws.prototype.init = function init(res, serviceName) {\n //TODO: account ID\n this.operation = formatOperation(res.request.operation) || '';\n if (res && res.request && res.request.httpRequest && res.request.httpRequest.region) {\n this.region = res.request.httpRequest.region;\n }\n if (res && res.requestId) {\n this.request_id = res.requestId;\n }\n this.retries = res.retryCount || 0;\n if (res.extendedRequestId && serviceName && serviceName.toLowerCase() === 's3')\n this.id_2 = res.extendedRequestId;\n this.addData(capturer.capture(serviceName, res));\n};\nAws.prototype.addData = function addData(data) {\n for (var attribute in data) {\n this[attribute] = data[attribute];\n }\n};\n/**\n * Overrides the default whitelisting file to specify what params to capture on each AWS Service call.\n * @param {string|Object} source - The path to the custom whitelist file, or a whitelist source JSON object.\n * @exports setAWSWhitelist\n */\nvar setAWSWhitelist = function setAWSWhitelist(source) {\n if (!source || source instanceof String || !(typeof source === 'string' || (source instanceof Object)))\n throw new Error('Please specify a path to the local whitelist file, or supply a whitelist source object.');\n capturer = new CallCapturer(source);\n};\n/**\n * Appends to the default whitelisting file to specify what params to capture on each AWS Service call.\n * @param {string|Object} source - The path to the custom whitelist file, or a whitelist source JSON object.\n * @exports appendAWSWhitelist\n */\nvar appendAWSWhitelist = function appendAWSWhitelist(source) {\n if (!source || source instanceof String || !(typeof source === 'string' || (source instanceof Object)))\n throw new Error('Please specify a path to the local whitelist file, or supply a whitelist source object.');\n capturer.append(source);\n};\nfunction formatOperation(operation) {\n if (!operation)\n return;\n return operation.charAt(0).toUpperCase() + operation.slice(1);\n}\nmodule.exports = Aws;\nmodule.exports.appendAWSWhitelist = appendAWSWhitelist;\nmodule.exports.setAWSWhitelist = setAWSWhitelist;\n", "\"use strict\";\n/**\n * Capture module.\n * @module capture\n */\nvar contextUtils = require('./context_utils');\nvar logger = require('./logger');\n/**\n * Wrap to automatically capture information for the segment.\n * @param {string} name - The name of the new subsegment.\n * @param {function} fcn - The function context to wrap. Can take a single 'subsegment' argument.\n * @param {Segment|Subsegment} [parent] - The parent for the new subsegment, for manual mode.\n * @alias module:capture.captureFunc\n * @return {*} - Returns the result if any by executing the provided function.\n */\nvar captureFunc = function captureFunc(name, fcn, parent) {\n validate(name, fcn);\n var current, executeFcn;\n var parentSeg = contextUtils.resolveSegment(parent);\n if (!parentSeg) {\n logger.getLogger().warn('Failed to capture function.');\n return fcn();\n }\n current = parentSeg.addNewSubsegment(name);\n executeFcn = captureFcn(fcn, current);\n try {\n const response = executeFcn(current);\n current.close();\n return response;\n }\n catch (e) {\n current.close(e);\n throw (e);\n }\n};\n/**\n * Wrap to automatically capture information for the sub/segment. You must close the segment\n * manually from within the function.\n * @param {string} name - The name of the new subsegment.\n * @param {function} fcn - The function context to wrap. Must take a single 'subsegment' argument and call 'subsegment.close([optional error])' when the async function completes.\n * @param {Segment|Subsegment} [parent] - The parent for the new subsegment, for manual mode.\n * @alias module:capture.captureAsyncFunc\n * @return {*} - Returns a promise by executing the provided async function.\n */\nvar captureAsyncFunc = function captureAsyncFunc(name, fcn, parent) {\n validate(name, fcn);\n var current, executeFcn;\n var parentSeg = contextUtils.resolveSegment(parent);\n if (!parentSeg) {\n logger.getLogger().warn('Failed to capture async function.');\n return fcn();\n }\n current = parentSeg.addNewSubsegment(name);\n executeFcn = captureFcn(fcn, current);\n try {\n return executeFcn(current);\n }\n catch (e) {\n current.close(e);\n throw (e);\n }\n};\n/**\n * Wrap to automatically capture information for the sub/segment. This wraps the callback and returns a function.\n * when executed, all arguments are passed through accordingly. An additional argument is appended to gain access to the newly created subsegment.\n * For this reason, always call the captured callback with the full list of arguments.\n * @param {string} name - The name of the new subsegment.\n * @param {function} fcn - The function context to wrap. Can take a single 'subsegment' argument.\n * @param {Segment|Subsegment} [parent] - The parent for the new subsegment, for manual mode.\n * @alias module:capture.captureCallbackFunc\n */\nvar captureCallbackFunc = function captureCallbackFunc(name, fcn, parent) {\n validate(name, fcn);\n var base = contextUtils.resolveSegment(parent);\n if (!base) {\n logger.getLogger().warn('Failed to capture callback function.');\n return fcn;\n }\n base.incrementCounter();\n return function () {\n var parentSeg = contextUtils.resolveSegment(parent);\n var args = Array.prototype.slice.call(arguments);\n captureFunc(name, fcn.bind.apply(fcn, [null].concat(args)), parentSeg);\n base.decrementCounter();\n }.bind(this);\n};\nfunction captureFcn(fcn, current) {\n var executeFcn;\n if (contextUtils.isAutomaticMode()) {\n var session = contextUtils.getNamespace();\n var contextFcn = function () {\n var value;\n session.run(function () {\n contextUtils.setSegment(current);\n value = fcn(current);\n });\n return value;\n };\n executeFcn = contextFcn;\n }\n else {\n executeFcn = fcn;\n }\n return executeFcn;\n}\nfunction validate(name, fcn) {\n var error;\n if (!name || typeof name !== 'string') {\n error = 'Param \"name\" must be a non-empty string.';\n logger.getLogger().error(error);\n throw new Error(error);\n }\n else if (typeof fcn !== 'function') {\n error = 'Param \"fcn\" must be a function.';\n logger.getLogger().error(error);\n throw new Error(error);\n }\n}\nmodule.exports.captureFunc = captureFunc;\nmodule.exports.captureAsyncFunc = captureAsyncFunc;\nmodule.exports.captureCallbackFunc = captureCallbackFunc;\n", "exports = module.exports = SemVer\n\nvar debug\n/* istanbul ignore next */\nif (typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)) {\n debug = function () {\n var args = Array.prototype.slice.call(arguments, 0)\n args.unshift('SEMVER')\n console.log.apply(console, args)\n }\n} else {\n debug = function () {}\n}\n\n// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nexports.SEMVER_SPEC_VERSION = '2.0.0'\n\nvar MAX_LENGTH = 256\nvar MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n /* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nvar MAX_SAFE_COMPONENT_LENGTH = 16\n\n// The actual regexps go on exports.re\nvar re = exports.re = []\nvar src = exports.src = []\nvar R = 0\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\nvar NUMERICIDENTIFIER = R++\nsrc[NUMERICIDENTIFIER] = '0|[1-9]\\\\d*'\nvar NUMERICIDENTIFIERLOOSE = R++\nsrc[NUMERICIDENTIFIERLOOSE] = '[0-9]+'\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\nvar NONNUMERICIDENTIFIER = R++\nsrc[NONNUMERICIDENTIFIER] = '\\\\d*[a-zA-Z-][a-zA-Z0-9-]*'\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\nvar MAINVERSION = R++\nsrc[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\\\.' +\n '(' + src[NUMERICIDENTIFIER] + ')\\\\.' +\n '(' + src[NUMERICIDENTIFIER] + ')'\n\nvar MAINVERSIONLOOSE = R++\nsrc[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\\\.' +\n '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\\\.' +\n '(' + src[NUMERICIDENTIFIERLOOSE] + ')'\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n\nvar PRERELEASEIDENTIFIER = R++\nsrc[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] +\n '|' + src[NONNUMERICIDENTIFIER] + ')'\n\nvar PRERELEASEIDENTIFIERLOOSE = R++\nsrc[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] +\n '|' + src[NONNUMERICIDENTIFIER] + ')'\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\nvar PRERELEASE = R++\nsrc[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] +\n '(?:\\\\.' + src[PRERELEASEIDENTIFIER] + ')*))'\n\nvar PRERELEASELOOSE = R++\nsrc[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] +\n '(?:\\\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\nvar BUILDIDENTIFIER = R++\nsrc[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\nvar BUILD = R++\nsrc[BUILD] = '(?:\\\\+(' + src[BUILDIDENTIFIER] +\n '(?:\\\\.' + src[BUILDIDENTIFIER] + ')*))'\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\nvar FULL = R++\nvar FULLPLAIN = 'v?' + src[MAINVERSION] +\n src[PRERELEASE] + '?' +\n src[BUILD] + '?'\n\nsrc[FULL] = '^' + FULLPLAIN + '$'\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\nvar LOOSEPLAIN = '[v=\\\\s]*' + src[MAINVERSIONLOOSE] +\n src[PRERELEASELOOSE] + '?' +\n src[BUILD] + '?'\n\nvar LOOSE = R++\nsrc[LOOSE] = '^' + LOOSEPLAIN + '$'\n\nvar GTLT = R++\nsrc[GTLT] = '((?:<|>)?=?)'\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifer, meaning \"any version\"\n// Only the first item is strictly required.\nvar XRANGEIDENTIFIERLOOSE = R++\nsrc[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\\\*'\nvar XRANGEIDENTIFIER = R++\nsrc[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\\\*'\n\nvar XRANGEPLAIN = R++\nsrc[XRANGEPLAIN] = '[v=\\\\s]*(' + src[XRANGEIDENTIFIER] + ')' +\n '(?:\\\\.(' + src[XRANGEIDENTIFIER] + ')' +\n '(?:\\\\.(' + src[XRANGEIDENTIFIER] + ')' +\n '(?:' + src[PRERELEASE] + ')?' +\n src[BUILD] + '?' +\n ')?)?'\n\nvar XRANGEPLAINLOOSE = R++\nsrc[XRANGEPLAINLOOSE] = '[v=\\\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' +\n '(?:\\\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +\n '(?:\\\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +\n '(?:' + src[PRERELEASELOOSE] + ')?' +\n src[BUILD] + '?' +\n ')?)?'\n\nvar XRANGE = R++\nsrc[XRANGE] = '^' + src[GTLT] + '\\\\s*' + src[XRANGEPLAIN] + '$'\nvar XRANGELOOSE = R++\nsrc[XRANGELOOSE] = '^' + src[GTLT] + '\\\\s*' + src[XRANGEPLAINLOOSE] + '$'\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\nvar COERCE = R++\nsrc[COERCE] = '(?:^|[^\\\\d])' +\n '(\\\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' +\n '(?:\\\\.(\\\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +\n '(?:\\\\.(\\\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +\n '(?:$|[^\\\\d])'\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\nvar LONETILDE = R++\nsrc[LONETILDE] = '(?:~>?)'\n\nvar TILDETRIM = R++\nsrc[TILDETRIM] = '(\\\\s*)' + src[LONETILDE] + '\\\\s+'\nre[TILDETRIM] = new RegExp(src[TILDETRIM], 'g')\nvar tildeTrimReplace = '$1~'\n\nvar TILDE = R++\nsrc[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'\nvar TILDELOOSE = R++\nsrc[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\nvar LONECARET = R++\nsrc[LONECARET] = '(?:\\\\^)'\n\nvar CARETTRIM = R++\nsrc[CARETTRIM] = '(\\\\s*)' + src[LONECARET] + '\\\\s+'\nre[CARETTRIM] = new RegExp(src[CARETTRIM], 'g')\nvar caretTrimReplace = '$1^'\n\nvar CARET = R++\nsrc[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'\nvar CARETLOOSE = R++\nsrc[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\nvar COMPARATORLOOSE = R++\nsrc[COMPARATORLOOSE] = '^' + src[GTLT] + '\\\\s*(' + LOOSEPLAIN + ')$|^$'\nvar COMPARATOR = R++\nsrc[COMPARATOR] = '^' + src[GTLT] + '\\\\s*(' + FULLPLAIN + ')$|^$'\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\nvar COMPARATORTRIM = R++\nsrc[COMPARATORTRIM] = '(\\\\s*)' + src[GTLT] +\n '\\\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'\n\n// this one has to use the /g flag\nre[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g')\nvar comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\nvar HYPHENRANGE = R++\nsrc[HYPHENRANGE] = '^\\\\s*(' + src[XRANGEPLAIN] + ')' +\n '\\\\s+-\\\\s+' +\n '(' + src[XRANGEPLAIN] + ')' +\n '\\\\s*$'\n\nvar HYPHENRANGELOOSE = R++\nsrc[HYPHENRANGELOOSE] = '^\\\\s*(' + src[XRANGEPLAINLOOSE] + ')' +\n '\\\\s+-\\\\s+' +\n '(' + src[XRANGEPLAINLOOSE] + ')' +\n '\\\\s*$'\n\n// Star ranges basically just allow anything at all.\nvar STAR = R++\nsrc[STAR] = '(<|>)?=?\\\\s*\\\\*'\n\n// Compile to actual regexp objects.\n// All are flag-free, unless they were created above with a flag.\nfor (var i = 0; i < R; i++) {\n debug(i, src[i])\n if (!re[i]) {\n re[i] = new RegExp(src[i])\n }\n}\n\nexports.parse = parse\nfunction parse (version, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n if (version.length > MAX_LENGTH) {\n return null\n }\n\n var r = options.loose ? re[LOOSE] : re[FULL]\n if (!r.test(version)) {\n return null\n }\n\n try {\n return new SemVer(version, options)\n } catch (er) {\n return null\n }\n}\n\nexports.valid = valid\nfunction valid (version, options) {\n var v = parse(version, options)\n return v ? v.version : null\n}\n\nexports.clean = clean\nfunction clean (version, options) {\n var s = parse(version.trim().replace(/^[=v]+/, ''), options)\n return s ? s.version : null\n}\n\nexports.SemVer = SemVer\n\nfunction SemVer (version, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n if (version instanceof SemVer) {\n if (version.loose === options.loose) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError('Invalid Version: ' + version)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters')\n }\n\n if (!(this instanceof SemVer)) {\n return new SemVer(version, options)\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n\n var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL])\n\n if (!m) {\n throw new TypeError('Invalid Version: ' + version)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map(function (id) {\n if (/^[0-9]+$/.test(id)) {\n var num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n}\n\nSemVer.prototype.format = function () {\n this.version = this.major + '.' + this.minor + '.' + this.patch\n if (this.prerelease.length) {\n this.version += '-' + this.prerelease.join('.')\n }\n return this.version\n}\n\nSemVer.prototype.toString = function () {\n return this.version\n}\n\nSemVer.prototype.compare = function (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n return this.compareMain(other) || this.comparePre(other)\n}\n\nSemVer.prototype.compareMain = function (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n return compareIdentifiers(this.major, other.major) ||\n compareIdentifiers(this.minor, other.minor) ||\n compareIdentifiers(this.patch, other.patch)\n}\n\nSemVer.prototype.comparePre = function (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n var i = 0\n do {\n var a = this.prerelease[i]\n var b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n}\n\n// preminor will bump the version up to the next minor release, and immediately\n// down to pre-release. premajor and prepatch work the same way.\nSemVer.prototype.inc = function (release, identifier) {\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier)\n this.inc('pre', identifier)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier)\n }\n this.inc('pre', identifier)\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 \"pre\" would become 1.0.0-0 which is the wrong direction.\n case 'pre':\n if (this.prerelease.length === 0) {\n this.prerelease = [0]\n } else {\n var i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n this.prerelease.push(0)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n if (this.prerelease[0] === identifier) {\n if (isNaN(this.prerelease[1])) {\n this.prerelease = [identifier, 0]\n }\n } else {\n this.prerelease = [identifier, 0]\n }\n }\n break\n\n default:\n throw new Error('invalid increment argument: ' + release)\n }\n this.format()\n this.raw = this.version\n return this\n}\n\nexports.inc = inc\nfunction inc (version, release, loose, identifier) {\n if (typeof (loose) === 'string') {\n identifier = loose\n loose = undefined\n }\n\n try {\n return new SemVer(version, loose).inc(release, identifier).version\n } catch (er) {\n return null\n }\n}\n\nexports.diff = diff\nfunction diff (version1, version2) {\n if (eq(version1, version2)) {\n return null\n } else {\n var v1 = parse(version1)\n var v2 = parse(version2)\n var prefix = ''\n if (v1.prerelease.length || v2.prerelease.length) {\n prefix = 'pre'\n var defaultResult = 'prerelease'\n }\n for (var key in v1) {\n if (key === 'major' || key === 'minor' || key === 'patch') {\n if (v1[key] !== v2[key]) {\n return prefix + key\n }\n }\n }\n return defaultResult // may be undefined\n }\n}\n\nexports.compareIdentifiers = compareIdentifiers\n\nvar numeric = /^[0-9]+$/\nfunction compareIdentifiers (a, b) {\n var anum = numeric.test(a)\n var bnum = numeric.test(b)\n\n if (anum && bnum) {\n a = +a\n b = +b\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n}\n\nexports.rcompareIdentifiers = rcompareIdentifiers\nfunction rcompareIdentifiers (a, b) {\n return compareIdentifiers(b, a)\n}\n\nexports.major = major\nfunction major (a, loose) {\n return new SemVer(a, loose).major\n}\n\nexports.minor = minor\nfunction minor (a, loose) {\n return new SemVer(a, loose).minor\n}\n\nexports.patch = patch\nfunction patch (a, loose) {\n return new SemVer(a, loose).patch\n}\n\nexports.compare = compare\nfunction compare (a, b, loose) {\n return new SemVer(a, loose).compare(new SemVer(b, loose))\n}\n\nexports.compareLoose = compareLoose\nfunction compareLoose (a, b) {\n return compare(a, b, true)\n}\n\nexports.rcompare = rcompare\nfunction rcompare (a, b, loose) {\n return compare(b, a, loose)\n}\n\nexports.sort = sort\nfunction sort (list, loose) {\n return list.sort(function (a, b) {\n return exports.compare(a, b, loose)\n })\n}\n\nexports.rsort = rsort\nfunction rsort (list, loose) {\n return list.sort(function (a, b) {\n return exports.rcompare(a, b, loose)\n })\n}\n\nexports.gt = gt\nfunction gt (a, b, loose) {\n return compare(a, b, loose) > 0\n}\n\nexports.lt = lt\nfunction lt (a, b, loose) {\n return compare(a, b, loose) < 0\n}\n\nexports.eq = eq\nfunction eq (a, b, loose) {\n return compare(a, b, loose) === 0\n}\n\nexports.neq = neq\nfunction neq (a, b, loose) {\n return compare(a, b, loose) !== 0\n}\n\nexports.gte = gte\nfunction gte (a, b, loose) {\n return compare(a, b, loose) >= 0\n}\n\nexports.lte = lte\nfunction lte (a, b, loose) {\n return compare(a, b, loose) <= 0\n}\n\nexports.cmp = cmp\nfunction cmp (a, op, b, loose) {\n switch (op) {\n case '===':\n if (typeof a === 'object')\n a = a.version\n if (typeof b === 'object')\n b = b.version\n return a === b\n\n case '!==':\n if (typeof a === 'object')\n a = a.version\n if (typeof b === 'object')\n b = b.version\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt(a, b, loose)\n\n case '>=':\n return gte(a, b, loose)\n\n case '<':\n return lt(a, b, loose)\n\n case '<=':\n return lte(a, b, loose)\n\n default:\n throw new TypeError('Invalid operator: ' + op)\n }\n}\n\nexports.Comparator = Comparator\nfunction Comparator (comp, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n if (!(this instanceof Comparator)) {\n return new Comparator(comp, options)\n }\n\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n}\n\nvar ANY = {}\nComparator.prototype.parse = function (comp) {\n var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]\n var m = comp.match(r)\n\n if (!m) {\n throw new TypeError('Invalid comparator: ' + comp)\n }\n\n this.operator = m[1]\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n}\n\nComparator.prototype.toString = function () {\n return this.value\n}\n\nComparator.prototype.test = function (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n version = new SemVer(version, this.options)\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n}\n\nComparator.prototype.intersects = function (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n var rangeTmp\n\n if (this.operator === '') {\n rangeTmp = new Range(comp.value, options)\n return satisfies(this.value, rangeTmp, options)\n } else if (comp.operator === '') {\n rangeTmp = new Range(this.value, options)\n return satisfies(comp.semver, rangeTmp, options)\n }\n\n var sameDirectionIncreasing =\n (this.operator === '>=' || this.operator === '>') &&\n (comp.operator === '>=' || comp.operator === '>')\n var sameDirectionDecreasing =\n (this.operator === '<=' || this.operator === '<') &&\n (comp.operator === '<=' || comp.operator === '<')\n var sameSemVer = this.semver.version === comp.semver.version\n var differentDirectionsInclusive =\n (this.operator === '>=' || this.operator === '<=') &&\n (comp.operator === '>=' || comp.operator === '<=')\n var oppositeDirectionsLessThan =\n cmp(this.semver, '<', comp.semver, options) &&\n ((this.operator === '>=' || this.operator === '>') &&\n (comp.operator === '<=' || comp.operator === '<'))\n var oppositeDirectionsGreaterThan =\n cmp(this.semver, '>', comp.semver, options) &&\n ((this.operator === '<=' || this.operator === '<') &&\n (comp.operator === '>=' || comp.operator === '>'))\n\n return sameDirectionIncreasing || sameDirectionDecreasing ||\n (sameSemVer && differentDirectionsInclusive) ||\n oppositeDirectionsLessThan || oppositeDirectionsGreaterThan\n}\n\nexports.Range = Range\nfunction Range (range, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n if (range instanceof Range) {\n if (range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n return new Range(range.value, options)\n }\n\n if (!(this instanceof Range)) {\n return new Range(range, options)\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First, split based on boolean or ||\n this.raw = range\n this.set = range.split(/\\s*\\|\\|\\s*/).map(function (range) {\n return this.parseRange(range.trim())\n }, this).filter(function (c) {\n // throw out any that are not relevant for whatever reason\n return c.length\n })\n\n if (!this.set.length) {\n throw new TypeError('Invalid SemVer Range: ' + range)\n }\n\n this.format()\n}\n\nRange.prototype.format = function () {\n this.range = this.set.map(function (comps) {\n return comps.join(' ').trim()\n }).join('||').trim()\n return this.range\n}\n\nRange.prototype.toString = function () {\n return this.range\n}\n\nRange.prototype.parseRange = function (range) {\n var loose = this.options.loose\n range = range.trim()\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]\n range = range.replace(hr, hyphenReplace)\n debug('hyphen replace', range)\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range, re[COMPARATORTRIM])\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[TILDETRIM], tildeTrimReplace)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[CARETTRIM], caretTrimReplace)\n\n // normalize spaces\n range = range.split(/\\s+/).join(' ')\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]\n var set = range.split(' ').map(function (comp) {\n return parseComparator(comp, this.options)\n }, this).join(' ').split(/\\s+/)\n if (this.options.loose) {\n // in loose mode, throw out any that are not valid comparators\n set = set.filter(function (comp) {\n return !!comp.match(compRe)\n })\n }\n set = set.map(function (comp) {\n return new Comparator(comp, this.options)\n }, this)\n\n return set\n}\n\nRange.prototype.intersects = function (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some(function (thisComparators) {\n return thisComparators.every(function (thisComparator) {\n return range.set.some(function (rangeComparators) {\n return rangeComparators.every(function (rangeComparator) {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n })\n })\n}\n\n// Mostly just for testing and legacy API reasons\nexports.toComparators = toComparators\nfunction toComparators (range, options) {\n return new Range(range, options).set.map(function (comp) {\n return comp.map(function (c) {\n return c.value\n }).join(' ').trim().split(' ')\n })\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nfunction parseComparator (comp, options) {\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nfunction isX (id) {\n return !id || id.toLowerCase() === 'x' || id === '*'\n}\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0\nfunction replaceTildes (comp, options) {\n return comp.trim().split(/\\s+/).map(function (comp) {\n return replaceTilde(comp, options)\n }).join(' ')\n}\n\nfunction replaceTilde (comp, options) {\n var r = options.loose ? re[TILDELOOSE] : re[TILDE]\n return comp.replace(r, function (_, M, m, p, pr) {\n debug('tilde', comp, _, M, m, p, pr)\n var ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0\n ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + M + '.' + (+m + 1) + '.0'\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + M + '.' + (+m + 1) + '.0'\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0\n// ^1.2.3 --> >=1.2.3 <2.0.0\n// ^1.2.0 --> >=1.2.0 <2.0.0\nfunction replaceCarets (comp, options) {\n return comp.trim().split(/\\s+/).map(function (comp) {\n return replaceCaret(comp, options)\n }).join(' ')\n}\n\nfunction replaceCaret (comp, options) {\n debug('caret', comp, options)\n var r = options.loose ? re[CARETLOOSE] : re[CARET]\n return comp.replace(r, function (_, M, m, p, pr) {\n debug('caret', comp, _, M, m, p, pr)\n var ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'\n } else if (isX(p)) {\n if (M === '0') {\n ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'\n } else {\n ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + M + '.' + m + '.' + (+p + 1)\n } else {\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + M + '.' + (+m + 1) + '.0'\n }\n } else {\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + (+M + 1) + '.0.0'\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + M + '.' + m + '.' + (+p + 1)\n } else {\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + M + '.' + (+m + 1) + '.0'\n }\n } else {\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + (+M + 1) + '.0.0'\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nfunction replaceXRanges (comp, options) {\n debug('replaceXRanges', comp, options)\n return comp.split(/\\s+/).map(function (comp) {\n return replaceXRange(comp, options)\n }).join(' ')\n}\n\nfunction replaceXRange (comp, options) {\n comp = comp.trim()\n var r = options.loose ? re[XRANGELOOSE] : re[XRANGE]\n return comp.replace(r, function (ret, gtlt, M, m, p, pr) {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n var xM = isX(M)\n var xm = xM || isX(m)\n var xp = xm || isX(p)\n var anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n // >1.2.3 => >= 1.2.4\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n ret = gtlt + M + '.' + m + '.' + p\n } else if (xm) {\n ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'\n } else if (xp) {\n ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nfunction replaceStars (comp, options) {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp.trim().replace(re[STAR], '')\n}\n\n// This function is passed to string.replace(re[HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0\nfunction hyphenReplace ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr, tb) {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = '>=' + fM + '.0.0'\n } else if (isX(fp)) {\n from = '>=' + fM + '.' + fm + '.0'\n } else {\n from = '>=' + from\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = '<' + (+tM + 1) + '.0.0'\n } else if (isX(tp)) {\n to = '<' + tM + '.' + (+tm + 1) + '.0'\n } else if (tpr) {\n to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr\n } else {\n to = '<=' + to\n }\n\n return (from + ' ' + to).trim()\n}\n\n// if ANY of the sets match ALL of its comparators, then pass\nRange.prototype.test = function (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n version = new SemVer(version, this.options)\n }\n\n for (var i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n}\n\nfunction testSet (set, version, options) {\n for (var i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n var allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n\nexports.satisfies = satisfies\nfunction satisfies (version, range, options) {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\n\nexports.maxSatisfying = maxSatisfying\nfunction maxSatisfying (versions, range, options) {\n var max = null\n var maxSV = null\n try {\n var rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach(function (v) {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!max || maxSV.compare(v) === -1) {\n // compare(max, v, true)\n max = v\n maxSV = new SemVer(max, options)\n }\n }\n })\n return max\n}\n\nexports.minSatisfying = minSatisfying\nfunction minSatisfying (versions, range, options) {\n var min = null\n var minSV = null\n try {\n var rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach(function (v) {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!min || minSV.compare(v) === 1) {\n // compare(min, v, true)\n min = v\n minSV = new SemVer(min, options)\n }\n }\n })\n return min\n}\n\nexports.minVersion = minVersion\nfunction minVersion (range, loose) {\n range = new Range(range, loose)\n\n var minver = new SemVer('0.0.0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = new SemVer('0.0.0-0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = null\n for (var i = 0; i < range.set.length; ++i) {\n var comparators = range.set[i]\n\n comparators.forEach(function (comparator) {\n // Clone to avoid manipulating the comparator's semver object.\n var compver = new SemVer(comparator.semver.version)\n switch (comparator.operator) {\n case '>':\n if (compver.prerelease.length === 0) {\n compver.patch++\n } else {\n compver.prerelease.push(0)\n }\n compver.raw = compver.format()\n /* fallthrough */\n case '':\n case '>=':\n if (!minver || gt(minver, compver)) {\n minver = compver\n }\n break\n case '<':\n case '<=':\n /* Ignore maximum versions */\n break\n /* istanbul ignore next */\n default:\n throw new Error('Unexpected operation: ' + comparator.operator)\n }\n })\n }\n\n if (minver && range.test(minver)) {\n return minver\n }\n\n return null\n}\n\nexports.validRange = validRange\nfunction validRange (range, options) {\n try {\n // Return '*' instead of '' so that truthiness works.\n // This will throw if it's invalid anyway\n return new Range(range, options).range || '*'\n } catch (er) {\n return null\n }\n}\n\n// Determine if version is less than all the versions possible in the range\nexports.ltr = ltr\nfunction ltr (version, range, options) {\n return outside(version, range, '<', options)\n}\n\n// Determine if version is greater than all the versions possible in the range.\nexports.gtr = gtr\nfunction gtr (version, range, options) {\n return outside(version, range, '>', options)\n}\n\nexports.outside = outside\nfunction outside (version, range, hilo, options) {\n version = new SemVer(version, options)\n range = new Range(range, options)\n\n var gtfn, ltefn, ltfn, comp, ecomp\n switch (hilo) {\n case '>':\n gtfn = gt\n ltefn = lte\n ltfn = lt\n comp = '>'\n ecomp = '>='\n break\n case '<':\n gtfn = lt\n ltefn = gte\n ltfn = gt\n comp = '<'\n ecomp = '<='\n break\n default:\n throw new TypeError('Must provide a hilo val of \"<\" or \">\"')\n }\n\n // If it satisifes the range it is not outside\n if (satisfies(version, range, options)) {\n return false\n }\n\n // From now on, variable terms are as if we're in \"gtr\" mode.\n // but note that everything is flipped for the \"ltr\" function.\n\n for (var i = 0; i < range.set.length; ++i) {\n var comparators = range.set[i]\n\n var high = null\n var low = null\n\n comparators.forEach(function (comparator) {\n if (comparator.semver === ANY) {\n comparator = new Comparator('>=0.0.0')\n }\n high = high || comparator\n low = low || comparator\n if (gtfn(comparator.semver, high.semver, options)) {\n high = comparator\n } else if (ltfn(comparator.semver, low.semver, options)) {\n low = comparator\n }\n })\n\n // If the edge version comparator has a operator then our version\n // isn't outside it\n if (high.operator === comp || high.operator === ecomp) {\n return false\n }\n\n // If the lowest version comparator has an operator and our version\n // is less than it then it isn't higher than the range\n if ((!low.operator || low.operator === comp) &&\n ltefn(version, low.semver)) {\n return false\n } else if (low.operator === ecomp && ltfn(version, low.semver)) {\n return false\n }\n }\n return true\n}\n\nexports.prerelease = prerelease\nfunction prerelease (version, options) {\n var parsed = parse(version, options)\n return (parsed && parsed.prerelease.length) ? parsed.prerelease : null\n}\n\nexports.intersects = intersects\nfunction intersects (r1, r2, options) {\n r1 = new Range(r1, options)\n r2 = new Range(r2, options)\n return r1.intersects(r2)\n}\n\nexports.coerce = coerce\nfunction coerce (version) {\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n var match = version.match(re[COERCE])\n\n if (match == null) {\n return null\n }\n\n return parse(match[1] +\n '.' + (match[2] || '0') +\n '.' + (match[3] || '0'))\n}\n", "\"use strict\";\n/**\n * Capture module.\n * @module aws_p\n */\nvar semver = require('semver');\nvar Aws = require('../segments/attributes/aws');\nvar contextUtils = require('../context_utils');\nvar Utils = require('../utils');\nvar logger = require('../logger');\nvar minVersion = '2.7.15';\nvar throttledErrorDefault = function throttledErrorDefault() {\n return false; // If the customer doesn't provide an aws-sdk with a throttled error function, we can't make assumptions.\n};\n/**\n * Configures the AWS SDK to automatically capture information for the segment.\n * All created clients will automatically be captured. See 'captureAWSClient'\n * for additional details.\n * @param {AWS} awssdk - The Javascript AWS SDK.\n * @alias module:aws_p.captureAWS\n * @returns {AWS}\n * @see https://github.com/aws/aws-sdk-js\n */\nvar captureAWS = function captureAWS(awssdk) {\n if (!semver.gte(awssdk.VERSION, minVersion))\n throw new Error('AWS SDK version ' + minVersion + ' or greater required.');\n for (var prop in awssdk) {\n if (awssdk[prop].serviceIdentifier) {\n var Service = awssdk[prop];\n Service.prototype.customizeRequests(captureAWSRequest);\n }\n }\n return awssdk;\n};\n/**\n * Configures any AWS Client instance to automatically capture information for the segment.\n * For manual mode, a param with key called 'Segment' is required as a part of the AWS\n * call paramaters, and must reference a Segment or Subsegment object.\n * @param {AWS.Service} service - An instance of a AWS service to wrap.\n * @alias module:aws_p.captureAWSClient\n * @returns {AWS.Service}\n * @see https://github.com/aws/aws-sdk-js\n */\nvar captureAWSClient = function captureAWSClient(service) {\n service.customizeRequests(captureAWSRequest);\n return service;\n};\nfunction captureAWSRequest(req) {\n var parent = contextUtils.resolveSegment(contextUtils.resolveManualSegmentParams(req.params));\n if (!parent) {\n var output = this.serviceIdentifier + '.' + req.operation;\n if (!contextUtils.isAutomaticMode()) {\n logger.getLogger().info('Call ' + output + ' requires a segment object' +\n ' on the request params as \"XRaySegment\" for tracing in manual mode. Ignoring.');\n }\n else {\n logger.getLogger().info('Call ' + output +\n ' is missing the sub/segment context for automatic mode. Ignoring.');\n }\n return req;\n }\n var throttledError = this.throttledError || throttledErrorDefault;\n var stack = (new Error()).stack;\n var subsegment = parent.addNewSubsegment(this.serviceIdentifier);\n var traceId = parent.segment ? parent.segment.trace_id : parent.trace_id;\n var buildListener = function (req) {\n req.httpRequest.headers['X-Amzn-Trace-Id'] = 'Root=' + traceId + ';Parent=' + subsegment.id +\n ';Sampled=' + (subsegment.segment.notTraced ? '0' : '1');\n };\n var completeListener = function (res) {\n subsegment.addAttribute('namespace', 'aws');\n subsegment.addAttribute('aws', new Aws(res, subsegment.name));\n var httpRes = res.httpResponse;\n if (httpRes) {\n subsegment.addAttribute('http', new HttpResponse(httpRes));\n if (httpRes.statusCode === 429 || (res.error && throttledError(res.error)))\n subsegment.addThrottleFlag();\n }\n if (res.error) {\n var err = { message: res.error.message, name: res.error.code, stack: stack };\n if (httpRes && httpRes.statusCode) {\n if (Utils.getCauseTypeFromHttpStatus(httpRes.statusCode) == 'error') {\n subsegment.addErrorFlag();\n }\n subsegment.close(err, true);\n }\n else\n subsegment.close(err);\n }\n else {\n if (httpRes && httpRes.statusCode) {\n var cause = Utils.getCauseTypeFromHttpStatus(httpRes.statusCode);\n if (cause)\n subsegment[cause] = true;\n }\n subsegment.close();\n }\n };\n req.on('beforePresign', function (req) {\n // Only the AWS Presigner triggers this event,\n // so we can rely on this event to notify us when\n // a request is for a presigned url\n parent.removeSubsegment(subsegment);\n parent.decrementCounter();\n req.removeListener('build', buildListener);\n req.removeListener('complete', completeListener);\n });\n req.on('build', buildListener).on('complete', completeListener);\n if (!req.__send) {\n req.__send = req.send;\n req.send = function (callback) {\n if (contextUtils.isAutomaticMode()) {\n var session = contextUtils.getNamespace();\n session.run(function () {\n contextUtils.setSegment(subsegment);\n req.__send(callback);\n });\n }\n else {\n req.__send(callback);\n }\n };\n }\n}\nfunction HttpResponse(res) {\n this.init(res);\n}\nHttpResponse.prototype.init = function init(res) {\n this.response = {\n status: res.statusCode || '',\n };\n if (res.headers && res.headers['content-length'])\n this.response.content_length = res.headers['content-length'];\n};\nmodule.exports.captureAWSClient = captureAWSClient;\nmodule.exports.captureAWS = captureAWS;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TRANSIENT_ERROR_STATUS_CODES = exports.TRANSIENT_ERROR_CODES = exports.THROTTLING_ERROR_CODES = exports.CLOCK_SKEW_ERROR_CODES = void 0;\nexports.CLOCK_SKEW_ERROR_CODES = [\n \"AuthFailure\",\n \"InvalidSignatureException\",\n \"RequestExpired\",\n \"RequestInTheFuture\",\n \"RequestTimeTooSkewed\",\n \"SignatureDoesNotMatch\",\n];\nexports.THROTTLING_ERROR_CODES = [\n \"BandwidthLimitExceeded\",\n \"EC2ThrottledException\",\n \"LimitExceededException\",\n \"PriorRequestNotComplete\",\n \"ProvisionedThroughputExceededException\",\n \"RequestLimitExceeded\",\n \"RequestThrottled\",\n \"RequestThrottledException\",\n \"SlowDown\",\n \"ThrottledException\",\n \"Throttling\",\n \"ThrottlingException\",\n \"TooManyRequestsException\",\n \"TransactionInProgressException\",\n];\nexports.TRANSIENT_ERROR_CODES = [\"AbortError\", \"TimeoutError\", \"RequestTimeout\", \"RequestTimeoutException\"];\nexports.TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504];\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isTransientError = exports.isThrottlingError = exports.isClockSkewError = exports.isRetryableByTrait = void 0;\nconst constants_1 = require(\"./constants\");\nconst isRetryableByTrait = (error) => error.$retryable !== undefined;\nexports.isRetryableByTrait = isRetryableByTrait;\nconst isClockSkewError = (error) => constants_1.CLOCK_SKEW_ERROR_CODES.includes(error.name);\nexports.isClockSkewError = isClockSkewError;\nconst isThrottlingError = (error) => {\n var _a, _b;\n return ((_a = error.$metadata) === null || _a === void 0 ? void 0 : _a.httpStatusCode) === 429 ||\n constants_1.THROTTLING_ERROR_CODES.includes(error.name) ||\n ((_b = error.$retryable) === null || _b === void 0 ? void 0 : _b.throttling) == true;\n};\nexports.isThrottlingError = isThrottlingError;\nconst isTransientError = (error) => {\n var _a;\n return constants_1.TRANSIENT_ERROR_CODES.includes(error.name) ||\n constants_1.TRANSIENT_ERROR_STATUS_CODES.includes(((_a = error.$metadata) === null || _a === void 0 ? void 0 : _a.httpStatusCode) || 0);\n};\nexports.isTransientError = isTransientError;\n", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.captureAWSClient = void 0;\nconst service_error_classification_1 = require(\"@aws-sdk/service-error-classification\");\nconst aws_1 = __importDefault(require(\"../segments/attributes/aws\"));\nconst querystring_1 = require(\"querystring\");\nconst subsegment_1 = __importDefault(require(\"../segments/attributes/subsegment\"));\nconst contextUtils = require('../context_utils');\nconst logger = require('../logger');\nconst { safeParseInt } = require('../utils');\nconst utils_1 = require(\"../utils\");\nconst XRAY_PLUGIN_NAME = 'XRaySDKInstrumentation';\n;\nconst buildAttributesFromMetadata = async (service, operation, region, res, error) => {\n var _a, _b, _c;\n const { extendedRequestId, requestId, httpStatusCode: statusCode, attempts } = ((_a = res === null || res === void 0 ? void 0 : res.output) === null || _a === void 0 ? void 0 : _a.$metadata) || (error === null || error === void 0 ? void 0 : error.$metadata);\n const aws = new aws_1.default({\n extendedRequestId,\n requestId,\n retryCount: attempts,\n request: {\n operation,\n httpRequest: {\n region,\n statusCode,\n },\n },\n }, service);\n const http = {};\n if (statusCode) {\n http.response = {};\n http.response.status = statusCode;\n }\n if (((_b = res === null || res === void 0 ? void 0 : res.response) === null || _b === void 0 ? void 0 : _b.headers) && ((_c = res === null || res === void 0 ? void 0 : res.response) === null || _c === void 0 ? void 0 : _c.headers['content-length']) !== undefined) {\n if (!http.response) {\n http.response = {};\n }\n http.response.content_length = safeParseInt(res.response.headers['content-length']);\n }\n return [aws, http];\n};\nfunction addFlags(http, subsegment, err) {\n var _a, _b, _c;\n if (err && service_error_classification_1.isThrottlingError(err)) {\n subsegment.addThrottleFlag();\n }\n else if (safeParseInt((_a = http.response) === null || _a === void 0 ? void 0 : _a.status) === 429 || safeParseInt((_b = err === null || err === void 0 ? void 0 : err.$metadata) === null || _b === void 0 ? void 0 : _b.httpStatusCode) === 429) {\n subsegment.addThrottleFlag();\n }\n const cause = utils_1.getCauseTypeFromHttpStatus(safeParseInt((_c = http.response) === null || _c === void 0 ? void 0 : _c.status));\n if (cause === 'fault') {\n subsegment.addFaultFlag();\n }\n else if (cause === 'error') {\n subsegment.addErrorFlag();\n }\n}\n;\nconst getXRayMiddleware = (config, manualSegment) => (next, context) => async (args) => {\n const segment = contextUtils.isAutomaticMode() ? contextUtils.resolveSegment() : manualSegment;\n const { clientName, commandName } = context;\n const operation = commandName.slice(0, -7); // Strip trailing \"Command\" string\n const service = clientName.slice(0, -6); // Strip trailing \"Client\" string\n if (!segment) {\n const output = service + '.' + operation.charAt(0).toLowerCase() + operation.slice(1);\n if (!contextUtils.isAutomaticMode()) {\n logger.getLogger().info('Call ' + output + ' requires a segment object' +\n ' passed to captureAWSv3Client for tracing in manual mode. Ignoring.');\n }\n else {\n logger.getLogger().info('Call ' + output +\n ' is missing the sub/segment context for automatic mode. Ignoring.');\n }\n return next(args);\n }\n const subsegment = segment.addNewSubsegment(service);\n subsegment.addAttribute('namespace', 'aws');\n const parent = (segment instanceof subsegment_1.default ? segment.segment : segment);\n args.request.headers['X-Amzn-Trace-Id'] = querystring_1.stringify({\n Root: parent.trace_id,\n Parent: subsegment.id,\n Sampled: parent.notTraced ? '0' : '1',\n }, ';');\n let res;\n try {\n res = await next(args);\n if (!res)\n throw new Error('Failed to get response from instrumented AWS Client.');\n const [aws, http] = await buildAttributesFromMetadata(service, operation, await config.region(), res, null);\n subsegment.addAttribute('aws', aws);\n subsegment.addAttribute('http', http);\n addFlags(http, subsegment);\n subsegment.close();\n return res;\n }\n catch (err) {\n if (err.$metadata) {\n const [aws, http] = await buildAttributesFromMetadata(service, operation, await config.region(), null, err);\n subsegment.addAttribute('aws', aws);\n subsegment.addAttribute('http', http);\n addFlags(http, subsegment, err);\n }\n const errObj = { message: err.message, name: err.name, stack: err.stack || new Error().stack };\n subsegment.close(errObj, true);\n throw err;\n }\n};\nconst xRayMiddlewareOptions = {\n name: XRAY_PLUGIN_NAME,\n step: 'build',\n};\nconst getXRayPlugin = (config, manualSegment) => ({\n applyToStack: (stack) => {\n stack.add(getXRayMiddleware(config, manualSegment), xRayMiddlewareOptions);\n },\n});\n/**\n * Instruments AWS SDK V3 clients with X-Ray via middleware.\n *\n * @param client - AWS SDK V3 client to instrument\n * @param manualSegment - Parent segment or subsegment that is passed in for manual mode users\n * @returns - the client with the X-Ray instrumentation middleware added to its middleware stack\n */\nfunction captureAWSClient(client, manualSegment) {\n // Remove existing middleware to ensure operation is idempotent\n client.middlewareStack.remove(XRAY_PLUGIN_NAME);\n client.middlewareStack.use(getXRayPlugin(client.config, manualSegment));\n return client;\n}\nexports.captureAWSClient = captureAWSClient;\n", "\"use strict\";\n/**\n * @module http_p\n */\n/**\n * This module patches the HTTP and HTTPS node built-in libraries and returns a copy of the module with tracing enabled.\n */\nvar url = require('url');\nvar contextUtils = require('../context_utils');\nvar Utils = require('../utils');\nvar logger = require('../logger');\nvar events = require('events');\n/**\n * Wraps the http/https.request() and .get() calls to automatically capture information for the segment.\n * This patches the built-in HTTP and HTTPS modules globally. If using a 3rd party HTTP library,\n * it should still use HTTP under the hood. Be sure to patch globally before requiring the 3rd party library.\n * 3rd party library compatibility is best effort. Some incompatibility issues may arise.\n * @param {http|https} module - The built in Node.js HTTP or HTTPS module.\n * @param {boolean} downstreamXRayEnabled - when true, adds a \"traced:true\" property to the subsegment\n * so the AWS X-Ray service expects a corresponding segment from the downstream service.\n * @param {function} subsegmentCallback - a callback that is called with the subsegment, the Node.js\n * http.ClientRequest, the Node.js http.IncomingMessage (if a response was received) and any error issued,\n * allowing custom annotations and metadata to be added.\n * to be added to the subsegment.\n * @alias module:http_p.captureHTTPsGlobal\n */\nvar captureHTTPsGlobal = function captureHTTPsGlobal(module, downstreamXRayEnabled, subsegmentCallback) {\n if (!module.__request)\n enableCapture(module, downstreamXRayEnabled, subsegmentCallback);\n};\n/**\n * Wraps the http/https.request() and .get() calls to automatically capture information for the segment.\n * Returns an instance of the HTTP or HTTPS module that is patched.\n * @param {http|https} module - The built in Node.js HTTP or HTTPS module.\n * @param {boolean} downstreamXRayEnabled - when true, adds a \"traced:true\" property to the subsegment\n * so the AWS X-Ray service expects a corresponding segment from the downstream service.\n * @param {function} subsegmentCallback - a callback that is called with the subsegment, the Node.js\n * http.ClientRequest, and the Node.js http.IncomingMessage to allow custom annotations and metadata\n * to be added to the subsegment.\n * @alias module:http_p.captureHTTPs\n * @returns {http|https}\n */\nvar captureHTTPs = function captureHTTPs(module, downstreamXRayEnabled, subsegmentCallback) {\n if (module.__request)\n return module;\n var tracedModule = {};\n Object.keys(module).forEach(function (val) {\n tracedModule[val] = module[val];\n });\n enableCapture(tracedModule, downstreamXRayEnabled, subsegmentCallback);\n return tracedModule;\n};\nfunction enableCapture(module, downstreamXRayEnabled, subsegmentCallback) {\n function captureOutgoingHTTPs(baseFunc, ...args) {\n let options;\n let callback;\n let hasUrl;\n let urlObj;\n let arg0 = args[0];\n if (typeof args[1] === 'object') {\n hasUrl = true;\n urlObj = typeof arg0 === 'string' ? new url.URL(arg0) : arg0;\n options = args[1],\n callback = args[2];\n }\n else {\n hasUrl = false;\n options = arg0;\n callback = args[1];\n }\n // Short circuit if the HTTP request has no options or is already being captured\n if (!options || (options.headers && (options.headers['X-Amzn-Trace-Id']))) {\n return baseFunc(...args);\n }\n // Case of calling a string URL without options, e.g.: http.request('http://amazon.com', callback)\n if (typeof options === 'string') {\n options = new url.URL(options);\n }\n if (!hasUrl) {\n urlObj = options;\n }\n const parent = contextUtils.resolveSegment(contextUtils.resolveManualSegmentParams(options));\n const hostname = options.hostname || options.host || urlObj.hostname || urlObj.host || 'Unknown host';\n if (!parent) {\n let output = '[ host: ' + hostname;\n output = options.method ? (output + ', method: ' + options.method) : output;\n output += ', path: ' + (urlObj.pathname || Utils.stripQueryStringFromPath(options.path)) + ' ]';\n if (!contextUtils.isAutomaticMode()) {\n logger.getLogger().info('Options for request ' + output +\n ' requires a segment object on the options params as \"XRaySegment\" for tracing in manual mode. Ignoring.');\n }\n else {\n logger.getLogger().info('Options for request ' + output +\n ' is missing the sub/segment context for automatic mode. Ignoring.');\n }\n // Options are not modified, only parsed for logging. We can pass in the original arguments.\n return baseFunc(...args);\n }\n const subsegment = parent.addNewSubsegment(hostname);\n const root = parent.segment ? parent.segment : parent;\n subsegment.namespace = 'remote';\n if (!options.headers)\n options.headers = {};\n options.headers['X-Amzn-Trace-Id'] = 'Root=' + root.trace_id + ';Parent=' + subsegment.id +\n ';Sampled=' + (!root.notTraced ? '1' : '0');\n const errorCapturer = function errorCapturer(e) {\n if (subsegmentCallback)\n subsegmentCallback(subsegment, this, null, e);\n if (subsegment.http && subsegment.http.response) {\n if (Utils.getCauseTypeFromHttpStatus(subsegment.http.response.status) === 'error') {\n subsegment.addErrorFlag();\n }\n subsegment.close(e, true);\n }\n else {\n const madeItToDownstream = (e.code !== 'ECONNREFUSED');\n subsegment.addRemoteRequestData(this, null, madeItToDownstream && downstreamXRayEnabled);\n subsegment.close(e);\n }\n // Only need to remove our listener & re-emit if we're not listening using the errorMonitor,\n // e.g. the app is running on Node 10. Otherwise the errorMonitor will re-emit automatically.\n // See: https://github.com/aws/aws-xray-sdk-node/issues/318\n // TODO: Remove this logic once node 12 support is deprecated\n if (!events.errorMonitor && this.listenerCount('error') <= 1) {\n this.removeListener('error', errorCapturer);\n this.emit('error', e);\n }\n };\n const optionsCopy = Utils.objectWithoutProperties(options, ['Segment'], true);\n let req = baseFunc(...(hasUrl ? [arg0, optionsCopy] : [options]), function (res) {\n res.on('end', function () {\n if (subsegmentCallback)\n subsegmentCallback(subsegment, this.req, res);\n if (res.statusCode === 429)\n subsegment.addThrottleFlag();\n const cause = Utils.getCauseTypeFromHttpStatus(res.statusCode);\n if (cause)\n subsegment[cause] = true;\n subsegment.addRemoteRequestData(res.req, res, !!downstreamXRayEnabled);\n subsegment.close();\n });\n if (typeof callback === 'function') {\n if (contextUtils.isAutomaticMode()) {\n const session = contextUtils.getNamespace();\n session.run(function () {\n contextUtils.setSegment(subsegment);\n callback(res);\n });\n }\n else {\n callback(res);\n }\n // if no callback provided by user application, AND no explicit response listener\n // added by user application, then we consume the response so the 'end' event fires\n // See: https://nodejs.org/api/http.html#http_class_http_clientrequest\n }\n else if (res.req && res.req.listenerCount('response') === 0) {\n res.resume();\n }\n });\n // Use errorMonitor if available (in Node 12.17+), otherwise fall back to standard error listener\n // See: https://nodejs.org/dist/latest-v12.x/docs/api/events.html#events_eventemitter_errormonitor\n req.on(events.errorMonitor || 'error', errorCapturer);\n return req;\n }\n module.__request = module.request;\n module.request = function captureHTTPsRequest(...args) {\n return captureOutgoingHTTPs(module.__request, ...args);\n };\n module.__get = module.get;\n module.get = function captureHTTPsGet(...args) {\n return captureOutgoingHTTPs(module.__get, ...args);\n };\n}\nmodule.exports.captureHTTPsGlobal = captureHTTPsGlobal;\nmodule.exports.captureHTTPs = captureHTTPs;\n", "\"use strict\";\n/**\n * @module promise_p\n */\n/**\n * This module patches native Promise libraries provided by V8 engine\n * so all subsegments generated within Promise are attached to the correct parent.\n */\nconst contextUtils = require('../context_utils');\nconst originalThen = Symbol('original then');\nconst originalCatch = Symbol('original catch');\nfunction patchPromise(Promise) {\n const then = Promise.prototype.then;\n if (!then[originalThen]) {\n Promise.prototype.then = function (onFulfilled, onRejected) {\n if (contextUtils.isAutomaticMode()\n && tryGetCurrentSegment()) {\n const ns = contextUtils.getNamespace();\n onFulfilled = onFulfilled && ns.bind(onFulfilled);\n onRejected = onRejected && ns.bind(onRejected);\n }\n return then.call(this, onFulfilled, onRejected);\n };\n Promise.prototype.then[originalThen] = then;\n }\n const origCatch = Promise.prototype.catch;\n if (origCatch && !origCatch[originalCatch]) {\n Promise.prototype.catch = function (onRejected) {\n if (contextUtils.isAutomaticMode()\n && tryGetCurrentSegment()) {\n const ns = contextUtils.getNamespace();\n onRejected = onRejected && ns.bind(onRejected);\n }\n return origCatch.call(this, onRejected);\n };\n Promise.prototype.catch[originalCatch] = origCatch;\n }\n}\nfunction unpatchPromise(Promise) {\n const then = Promise.prototype.then;\n if (then[originalThen]) {\n Promise.prototype.then = then[originalThen];\n }\n const origCatch = Promise.prototype.catch;\n if (origCatch && origCatch[originalCatch]) {\n Promise.prototype.catch = origCatch[originalCatch];\n }\n}\nfunction tryGetCurrentSegment() {\n try {\n return contextUtils.getSegment();\n }\n catch (e) {\n return undefined;\n }\n}\nfunction capturePromise() {\n patchPromise(Promise);\n}\nfunction uncapturePromise() {\n unpatchPromise(Promise);\n}\ncapturePromise.patchThirdPartyPromise = patchPromise;\nmodule.exports.capturePromise = capturePromise;\nmodule.exports.uncapturePromise = uncapturePromise;\n", "\"use strict\";\n/**\n * Represents a SQL database call.\n * @constructor\n * @param {string} databaseVer - The version on the database (user supplied).\n * @param {string} driverVer - The version on the database driver (user supplied).\n * @param {string} user - The user associated to the database call.\n * @param {string} queryType - The SQL query type.\n */\nfunction SqlData(databaseVer, driverVer, user, url, queryType) {\n this.init(databaseVer, driverVer, user, url, queryType);\n}\nSqlData.prototype.init = function init(databaseVer, driverVer, user, url, queryType) {\n if (databaseVer)\n this.database_version = databaseVer;\n if (driverVer)\n this.driver_version = driverVer;\n if (queryType)\n this.preparation = queryType;\n this.url = url;\n this.user = user;\n};\nmodule.exports = SqlData;\n", "\"use strict\";\nvar contextUtils = require('./context_utils');\nvar logging = require('./logger');\nvar segmentUtils = require('./segments/segment_utils');\nvar utils = require('./utils');\nvar LambdaEnv = require('./env/aws_lambda');\n// Import Data from package.json,\n// If the importing of package.json fails leave\n// pkginfo as an empty object\nvar pkginfo = {};\ntry {\n pkginfo = require('../../package.json');\n}\ncatch (err) {\n logging.getLogger().debug('Failed to load SDK data:', err);\n}\nvar UNKNOWN = 'unknown';\n/**\n * A module representing the AWSXRay SDK.\n * @namespace AWSXRay\n */\nvar AWSXRay = {\n /**\n * @memberof AWSXRay\n * @type {object}\n * @namespace AWSXRay.plugins\n */\n plugins: {\n /**\n * Exposes the AWS EC2 plugin.\n * @memberof AWSXRay.plugins\n */\n EC2Plugin: require('./segments/plugins/ec2_plugin'),\n /**\n * Exposes the AWS ECS plugin.\n * @memberof AWSXRay.plugins\n */\n ECSPlugin: require('./segments/plugins/ecs_plugin'),\n /**\n * Exposes the AWS Elastic Beanstalk plugin.\n * @memberof AWSXRay.plugins\n */\n ElasticBeanstalkPlugin: require('./segments/plugins/elastic_beanstalk_plugin'),\n },\n /**\n * Enables use of plugins to capture additional data for segments.\n * @param {Array} plugins - A configurable subset of AWSXRay.plugins.\n * @memberof AWSXRay\n * @see AWSXRay.plugins\n */\n config: function (plugins) {\n var pluginData = {};\n plugins.forEach(function (plugin) {\n plugin.getData(function (data) {\n if (data) {\n for (var attribute in data) {\n pluginData[attribute] = data[attribute];\n }\n }\n });\n segmentUtils.setOrigin(plugin.originName);\n segmentUtils.setPluginData(pluginData);\n });\n },\n /**\n * Overrides the default whitelisting file to specify what params to capture on each AWS Service call.\n * If a service or API is not listed, no additional data is captured.\n * The base whitelisting file can be found at /lib/resources/aws_whitelist.json\n * @param {string|Object} source - The path to the custom whitelist file, or a whitelist source JSON object.\n * @memberof AWSXRay\n */\n setAWSWhitelist: require('./segments/attributes/aws').setAWSWhitelist,\n /**\n * Appends to the current whitelisting file.\n * In the case of a duplicate service API listed, the new source will override the previous values.\n * @param {string|Object} source - The path to the custom whitelist file, or a whitelist source JSON object.\n * @memberof AWSXRay\n */\n appendAWSWhitelist: require('./segments/attributes/aws').appendAWSWhitelist,\n /**\n * Overrides the default streaming threshold (100).\n * The threshold represents the maximum number of subsegments on a single segment before\n * the SDK begins to send the completed subsegments out of band of the main segment.\n * Reduce this threshold if you see the 'Segment too large to send' error.\n * @param {number} threshold - The new threshold to use.\n * @memberof AWSXRay\n */\n setStreamingThreshold: segmentUtils.setStreamingThreshold,\n /**\n * Set your own logger for the SDK.\n * @param {Object} logger - A logger which responds to debug/info/warn/error calls.\n * @memberof AWSXRay\n */\n setLogger: logging.setLogger,\n /**\n * Gets the set logger for the SDK.\n * @memberof AWSXRay\n */\n getLogger: logging.getLogger,\n /**\n * Configures the address and port the daemon is expected to be on.\n * @param {string} address - Address of the daemon the segments should be sent to. Expects 'x.x.x.x', ':yyyy' or 'x.x.x.x:yyyy' IPv4 formats.\n * @module DaemonConfig\n * @memberof AWSXRay\n * @function\n * @see module:DaemonConfig.setDaemonAddress\n */\n setDaemonAddress: require('./daemon_config').setDaemonAddress,\n /**\n * @param {string} name - The name of the new subsegment.\n * @param {function} fcn - The function conext to wrap.\n * @param {Segment|Subsegment} [parent] - The parent for the new subsegment, for manual mode.\n * @memberof AWSXRay\n * @function\n * @see module:capture.captureFunc\n */\n captureFunc: require('./capture').captureFunc,\n /**\n * @param {string} name - The name of the new subsegment.\n * @param {function} fcn - The function conext to wrap.\n * @param {Segment|Subsegment} [parent] - The parent for the new subsegment, for manual mode.\n * @memberof AWSXRay\n * @function\n * @see module:capture.captureAsyncFunc\n */\n captureAsyncFunc: require('./capture').captureAsyncFunc,\n /**\n * @param {string} name - The name of the new subsegment.\n * @param {function} fcn - The function conext to wrap.\n * @param {Segment|Subsegment} [parent] - The parent for the new subsegment, for manual mode.\n * @memberof AWSXRay\n * @function\n * @see module:capture.captureCallbackFunc\n */\n captureCallbackFunc: require('./capture').captureCallbackFunc,\n /**\n * @param {AWS} awssdk - The Javascript AWS SDK.\n * @memberof AWSXRay\n * @function\n * @see module:aws_p.captureAWS\n */\n captureAWS: require('./patchers/aws_p').captureAWS,\n /**\n * @param {AWS.Service} service - An instance of a AWS service to wrap.\n * @memberof AWSXRay\n * @function\n * @see module:aws_p.captureAWSClient\n */\n captureAWSClient: require('./patchers/aws_p').captureAWSClient,\n /**\n * @param {AWSv3.Service} service - An instance of a AWS SDK v3 service to wrap.\n * @param {Segment|Subsegment} segment - Optional segment for manual mode.\n * @memberof AWSXRay\n * @function\n * @see module:aws3_p.captureAWSClient\n */\n captureAWSv3Client: require('./patchers/aws3_p').captureAWSClient,\n /**\n * @param {http|https} module - The built in Node.js HTTP or HTTPS module.\n * @memberof AWSXRay\n * @function\n * @returns {http|https}\n * @see module:http_p.captureHTTPs\n */\n captureHTTPs: require('./patchers/http_p').captureHTTPs,\n /**\n * @param {http|https} module - The built in Node.js HTTP or HTTPS module.\n * @memberof AWSXRay\n * @function\n * @see module:http_p.captureHTTPsGlobal\n */\n captureHTTPsGlobal: require('./patchers/http_p').captureHTTPsGlobal,\n /**\n * @memberof AWSXRay\n * @function\n * @see module:promise_p.capturePromise\n */\n capturePromise: require('./patchers/promise_p').capturePromise,\n /**\n * Exposes various helper methods.\n * @memberof AWSXRay\n * @function\n * @see module:utils\n */\n utils: utils,\n /**\n * @memberof AWSXRay\n * @type {object}\n * @namespace AWSXRay.database\n */\n database: {\n /**\n * Exposes the SqlData class.\n * @memberof AWSXRay.database\n * @see SqlData\n */\n SqlData: require('./database/sql_data'),\n },\n /**\n * Exposes the Middleware Utils class.\n * @memberof AWSXRay\n * @function\n * @see module:mw_utils\n */\n middleware: require('./middleware/mw_utils'),\n /**\n * Gets the current namespace of the context.\n * Used for supporting functions that can be used in automatic mode.\n * @memberof AWSXRay\n * @function\n * @returns {Segment|Subsegment}\n * @see module:context_utils.getNamespace\n */\n getNamespace: contextUtils.getNamespace,\n /**\n * Resolves the current segment or subsegment, checks manual and automatic modes.\n * Used for supporting functions that can be used in both manual and automatic modes.\n * @memberof AWSXRay\n * @function\n * @returns {Segment|Subsegment}\n * @see module:context_utils.resolveSegment\n */\n resolveSegment: contextUtils.resolveSegment,\n /**\n * Returns the current segment or subsegment. For use with automatic mode only.\n * @memberof AWSXRay\n * @function\n * @returns {Segment|Subsegment}\n * @see module:context_utils.getSegment\n */\n getSegment: contextUtils.getSegment,\n /**\n * Sets the current segment or subsegment. For use with automatic mode only.\n * @memberof AWSXRay\n * @function\n * @see module:context_utils.setSegment\n */\n setSegment: contextUtils.setSegment,\n /**\n * Returns true if automatic mode is enabled, otherwise false.\n * @memberof AWSXRay\n * @function\n * @see module:context_utils.isAutomaticMode\n */\n isAutomaticMode: contextUtils.isAutomaticMode,\n /**\n * Enables automatic mode. Automatic mode uses 'cls-hooked'.\n * @see https://github.com/jeff-lewis/cls-hooked\n * @memberof AWSXRay\n * @function\n * @see module:context_utils.enableAutomaticMode\n */\n enableAutomaticMode: contextUtils.enableAutomaticMode,\n /**\n * Disables automatic mode. Current segment or subsegment must be passed manually\n * via the parent optional on captureFunc, captureAsyncFunc etc.\n * @memberof AWSXRay\n * @function\n * @see module:context_utils.enableManualMode\n */\n enableManualMode: contextUtils.enableManualMode,\n /**\n * Sets the context missing strategy.\n * @param {Object} strategy - The strategy to set. This object's contextMissing function will be called whenever trace context is not found.\n */\n setContextMissingStrategy: contextUtils.setContextMissingStrategy,\n /**\n * Exposes the segment class.\n * @memberof AWSXRay\n * @function\n */\n Segment: require('./segments/segment'),\n /**\n * Exposes the subsegment class.\n * @memberof AWSXRay\n * @see Subsegment\n */\n Subsegment: require('./segments/attributes/subsegment'),\n SegmentUtils: segmentUtils\n};\n/**\n * Exposes the IncomingRequestData, to capture incoming request data.\n * For use with middleware.\n * @memberof AWSXRay.middleware\n * @see IncomingRequestData\n */\nAWSXRay.middleware.IncomingRequestData = require('./middleware/incoming_request_data'),\n (function () {\n var data = {\n runtime: (process.release && process.release.name) ? process.release.name : UNKNOWN,\n runtime_version: process.version,\n version: process.env.npm_package_version || UNKNOWN,\n name: process.env.npm_package_name || UNKNOWN\n };\n var sdkData = {\n sdk: 'X-Ray for Node.js',\n sdk_version: pkginfo.version ? pkginfo.version : UNKNOWN,\n package: pkginfo.name ? pkginfo.name : UNKNOWN,\n };\n segmentUtils.setSDKData(sdkData);\n segmentUtils.setServiceData(data);\n if (process.env.LAMBDA_TASK_ROOT)\n LambdaEnv.init();\n })();\nmodule.exports = AWSXRay;\n", "\"use strict\";\n// Convenience file to require the SDK from the root of the repository\nmodule.exports = require('./aws-xray');\n", "import { metricScope, Unit } from 'aws-embedded-metrics';\nimport type { Context } from 'aws-lambda';\nimport got from 'got';\nimport { CatalogClient } from '../catalog-builder/client.lambda-shared';\nimport * as aws from '../shared/aws.lambda-shared';\nimport { requireEnv } from '../shared/env.lambda-shared';\nimport { MetricName, METRICS_NAMESPACE } from './constants';\nimport { NpmDownloadsClient, NpmDownloadsEntry, NpmDownloadsPeriod } from './npm-downloads.lambda-shared';\n\n/**\n * Rebuilds the `stats.json` object in the configured S3 bucket.\n * Validates that the number of packages on a full rebuild should not decrease\n * significantly (due to network errors from e.g. NPM) - can be ignored\n * by passing { ignoreValidation: true }.\n *\n * @param event configuration for the rebuild job.\n * @param context the lambda context in which this execution runs.\n *\n * @returns the information about the updated S3 object.\n */\nexport async function handler(event: any, context: Context) {\n console.log(JSON.stringify(event, null, 2));\n\n const STATS_BUCKET_NAME = requireEnv('STATS_BUCKET_NAME');\n const STATS_OBJECT_KEY = requireEnv('STATS_OBJECT_KEY');\n\n const catalogClient = await CatalogClient.newClient();\n const catalog = catalogClient.packages;\n if (catalog.length === 0) {\n throw new Error('No packages found.');\n }\n\n const currentDate = new Date().toISOString();\n const stats: PackageStatsOutput = { packages: {}, updated: currentDate };\n const npmClient = new NpmDownloadsClient(got);\n\n // remove duplicates from different major versions\n const packageNames = [...new Set(catalog.map(pkg => pkg.name)).values()];\n\n console.log(`Retrieving download stats for all ${packageNames.length} registered packages: [${packageNames.join(',')}].`);\n const npmDownloads = await npmClient.getDownloads(packageNames, {\n period: NpmDownloadsPeriod.LAST_WEEK,\n throwErrors: false,\n });\n\n for (const [pkgName, entry] of npmDownloads.entries()) {\n updateStats(stats, pkgName, entry);\n }\n\n // Update metrics\n const statsCount = Object.keys(stats.packages).length;\n console.log(`There are now ${statsCount} packages with NPM stats stored.`);\n await metricScope((metrics) => async () => {\n // Clear out default dimensions as we don't need those. See https://github.com/awslabs/aws-embedded-metrics-node/issues/73\n metrics.setDimensions();\n\n metrics.setNamespace(METRICS_NAMESPACE);\n metrics.putMetric(MetricName.REGISTERED_PACKAGES_WITH_STATS, statsCount, Unit.Count);\n })();\n\n // Upload the result to S3 and exit.\n return aws.s3().putObject({\n Bucket: STATS_BUCKET_NAME,\n Key: STATS_OBJECT_KEY,\n Body: JSON.stringify(stats, null, 2),\n ContentType: 'application/json',\n CacheControl: 'public, max-age=300', // Expire from cache after 5 minutes\n Metadata: {\n 'Lambda-Log-Group': context.logGroupName,\n 'Lambda-Log-Stream': context.logStreamName,\n 'Lambda-Run-Id': context.awsRequestId,\n 'Package-Stats-Count': `${statsCount}`,\n },\n }).promise();\n}\n\nfunction updateStats(stats: PackageStatsOutput, pkgName: string, entry: NpmDownloadsEntry) {\n stats.packages[pkgName] = {\n ...(stats.packages[pkgName] ?? {}),\n downloads: {\n ...(stats.packages[pkgName]?.downloads ?? {}),\n npm: entry.downloads,\n },\n };\n}\n\nexport interface PackageStatsOutput {\n readonly packages: { [key: string]: PackageStatsEntry };\n readonly updated: string;\n}\n\nexport interface PackageStatsEntry {\n readonly downloads: PackageStatsDownloads;\n}\n\nexport interface PackageStatsDownloads {\n readonly npm: number;\n}\n", "import * as _AWS from 'aws-sdk';\nimport * as AWSXRay from 'aws-xray-sdk-core';\n\n// Do nothing if there is no XRay trace context\nAWSXRay.setContextMissingStrategy(() => {});\n\nconst AWS = AWSXRay.captureAWS(_AWS);\n\nlet _s3: AWS.S3 | undefined;\nlet _sqs: AWS.SQS | undefined;\nlet _sfn: AWS.StepFunctions | undefined;\nlet _lambda: AWS.Lambda | undefined;\nlet _codeArtifact: AWS.CodeArtifact | undefined;\n\nexport function s3(): AWS.S3 {\n if (_s3 == null) {\n _s3 = new AWS.S3();\n }\n return _s3;\n}\n\n/**\n * Checks whether an object exists in S3 at the provided bucket and key.\n */\nexport function s3ObjectExists(bucket: string, key: string): Promise<boolean> {\n return s3().headObject({\n Bucket: bucket,\n Key: key,\n }).promise()\n .then(\n () => true,\n (cause) => {\n if (cause.code === 'NotFound') {\n return false;\n }\n return Promise.reject(cause);\n },\n );\n}\n\nexport function sqs(): AWS.SQS {\n if (_sqs == null) {\n _sqs = new AWS.SQS();\n }\n return _sqs;\n}\n\nexport function stepFunctions(): AWS.StepFunctions {\n if (_sfn == null) {\n _sfn = new AWS.StepFunctions();\n }\n return _sfn;\n}\n\nexport function lambda(): AWS.Lambda {\n if (_lambda == null) {\n _lambda = new AWS.Lambda();\n }\n return _lambda;\n}\n\nexport function codeArtifact(): AWS.CodeArtifact {\n if (_codeArtifact == null) {\n _codeArtifact = new AWS.CodeArtifact();\n }\n return _codeArtifact;\n}\n\n/**\n * Resets all clients vended by this module. This is useful in unit tests when\n * `aws-sdk-mocks` is used, so that new mocks are injected as intended.\n */\nexport function reset(): void {\n _s3 = _sqs = _sfn = _lambda = _codeArtifact = undefined;\n}\n", "import { env } from 'process';\n\nexport function requireEnv(name: string): string {\n const result = env[name];\n if (!result) {\n throw new Error(`No value specified for required environment variable: ${name}`);\n }\n return result;\n}\n", "import * as AWS from 'aws-sdk';\nimport { CatalogModel, PackageInfo } from '.';\nimport { s3 } from '../shared/aws.lambda-shared';\nimport { requireEnv } from '../shared/env.lambda-shared';\n\n/**\n * A client for working with the catalog.\n */\nexport class CatalogClient {\n /**\n * Creates a new client for accessing the catalog.\n */\n public static async newClient() {\n const client = new CatalogClient();\n await client.init();\n return client;\n }\n\n private readonly s3: AWS.S3;\n private readonly bucketName: string;\n private readonly objectKey: string;\n\n private _packages: PackageInfo[] | undefined;\n\n private constructor() {\n this.bucketName = requireEnv('CATALOG_BUCKET_NAME');\n this.objectKey = requireEnv('CATALOG_OBJECT_KEY');\n this.s3 = s3();\n }\n\n /**\n * Downloads the catalog object and stores it in memory.\n */\n private async init() {\n if (this._packages) {\n throw new Error('init() cannot be called twice');\n }\n\n this._packages = [];\n\n const params = {\n Bucket: this.bucketName,\n Key: this.objectKey,\n };\n\n let body: AWS.S3.Body | undefined;\n try {\n const data = await this.s3.getObject(params).promise();\n body = data.Body;\n } catch (e) {\n throw new Error(`No catalog was found at ${this.bucketName}/${this.objectKey}`);\n }\n\n if (!body) {\n throw new Error(`Catalog body is empty at ${this.bucketName}/${this.objectKey}`);\n }\n\n const contents = body.toString('utf-8');\n\n try {\n const data = JSON.parse(contents) as CatalogModel;\n if (typeof(data) != 'object') {\n throw new Error('Invalid format in catalog file. Expecting a map');\n }\n this._packages = data.packages;\n } catch (e) {\n throw new Error(`Unable to parse catalog file ${this.bucketName}/${this.objectKey}: ${e}`);\n }\n }\n\n /**\n * Returns a copy of the catalog list.\n */\n public get packages() {\n if (!this._packages) {\n throw new Error('CatalogClient must be initialized');\n }\n\n return [...this._packages];\n }\n}\n", "export const METRICS_NAMESPACE = 'ConstructHub/PackageStats';\n\nexport const enum MetricName {\n REGISTERED_PACKAGES_WITH_STATS = 'RegisteredPackagesWithStats',\n}\n", "import type { Got } from 'got/dist/source/types';\n\nexport enum NpmDownloadsPeriod {\n /**\n * Gets downloads for the last available day. In practice, this will usually\n * be \"yesterday\" (in GMT) but if stats for that day have not yet landed, it\n * will be the day before.\n */\n LAST_DAY = 'last-day',\n\n /**\n * Gets downloads for the last 7 available days.\n */\n LAST_WEEK = 'last-week',\n\n /**\n * Gets downloads for the last 30 available days.\n */\n LAST_MONTH = 'last-month'\n}\n\nexport interface NpmDownloadsEntry {\n readonly downloads: number;\n readonly start: string;\n readonly end: string;\n readonly package: string;\n}\n\nexport type NpmDownloadsOutput = Map<string, NpmDownloadsEntry>;\n\nexport interface NpmDownloadsOptions {\n /**\n * The period to query for package download counts.\n * @default NpmDownloadsPeriod.LAST_WEEK\n */\n readonly period?: NpmDownloadsPeriod;\n\n /**\n * Throw an error when any package's download metrics are not available.\n * @default true\n */\n readonly throwErrors?: boolean;\n}\n\nexport class NpmDownloadsClient {\n public static readonly NPM_DOWNLOADS_API_URL = 'https://api.npmjs.org/downloads/point';\n public static readonly MAX_PACKAGES_PER_QUERY = 128; // this is a limitation from npm's API! do not change\n\n private readonly got: Got;\n\n constructor(gotService: Got) {\n this.got = gotService;\n }\n\n private async getDownloadsRaw(\n packages: readonly string[],\n period: NpmDownloadsPeriod,\n throwErrors: boolean,\n ): Promise<NpmDownloadsOutput> {\n if (packages.length > NpmDownloadsClient.MAX_PACKAGES_PER_QUERY) {\n throw new Error(`Too many packages were provided (max: ${NpmDownloadsClient.MAX_PACKAGES_PER_QUERY})`);\n }\n if (packages.some((pkg) => this.isScopedPackage(pkg)) && packages.length > 1) {\n throw new Error('Scoped packages aren\\'t supported by the bulk query API.');\n }\n if (packages.length === 0) return new Map();\n\n console.log(`Querying NPM for ${packages.length} package(s): [${packages.join(', ')}]`);\n const result = await this.got(`${NpmDownloadsClient.NPM_DOWNLOADS_API_URL}/${period}/${packages.join(',')}`, {\n timeout: 5 * 1000, // 5 seconds\n }).catch((err) => {\n if (throwErrors) {\n throw err;\n } else {\n return { body: JSON.stringify({ error: JSON.stringify(err) }) };\n }\n });\n\n const data: NpmApiResult = JSON.parse(result.body);\n\n // single package query error\n // ex. { \"error\": \"package foo not found\" }\n if ('error' in data) {\n if (throwErrors) {\n throw new Error(`Could not retrieve download metrics: ${data.error}`);\n } else {\n console.error(`Could not retrieve download metrics: ${data.error}`);\n return new Map();\n }\n }\n\n // only a single package was returned\n if (isSingleDownloadsEntry(data)) {\n return new Map([[packages[0], data]]);\n }\n\n // bulk query result\n for (const key of Object.keys(data)) {\n if (data[key] === null) {\n if (throwErrors) {\n throw new Error(`Could not retrieve download metrics for package ${key}`);\n } else {\n console.error(`Could not retrieve download metrics for package ${key}`);\n delete data[key];\n }\n }\n }\n\n // typescript can't figure out that we removed all null values\n // @ts-ignore\n return new Map(Object.entries(data));\n }\n\n /**\n * Retrieves the number of downloads each package has on npm in the latest period.\n * Output is not guaranteed to be returned in a specific order.\n * If throwErrors option is specified, an error is thrown when a package's\n * download count is unavailable - otherwise, it's just omitted from\n * the output.\n */\n public async getDownloads(\n packages: string[],\n options: NpmDownloadsOptions = {},\n ): Promise<NpmDownloadsOutput> {\n const period = options.period ?? NpmDownloadsPeriod.LAST_WEEK;\n const throwErrors = options.throwErrors ?? true;\n\n // separate scoped and unscoped packages since scoped packages are not\n // supported by the bulk query API\n const scopedPackages = [];\n const unscopedPackages = [];\n for (const pkg of packages) {\n if (this.isScopedPackage(pkg)) {\n scopedPackages.push(pkg);\n } else {\n unscopedPackages.push(pkg);\n }\n }\n\n // we could parallelize this, but then it's more likely we get throttled\n const output: NpmDownloadsOutput = new Map();\n for (const pkg of scopedPackages) {\n const partialResults = await this.getDownloadsRaw([pkg], period, throwErrors);\n for (const [key, value] of partialResults) {\n output.set(key, value);\n }\n }\n for (let i = 0; i < unscopedPackages.length; i += NpmDownloadsClient.MAX_PACKAGES_PER_QUERY) {\n const batch = unscopedPackages.slice(i, i + NpmDownloadsClient.MAX_PACKAGES_PER_QUERY);\n const partialResults = await this.getDownloadsRaw(batch, period, throwErrors);\n for (const [key, value] of partialResults) {\n output.set(key, value);\n }\n }\n\n return output;\n }\n\n private isScopedPackage(packageName: string) {\n return packageName.startsWith('@');\n }\n}\n\n// Types for the output of NPM's API.\ntype NpmApiResult = NpmApiError | NpmApiSingleResult | NpmApiMultipleResult;\ntype NpmApiError = { error: string };\ntype NpmApiSingleResult = NpmDownloadsEntry;\ntype NpmApiMultipleResult = { [key: string]: NpmApiSingleResult | null };\n\nfunction isSingleDownloadsEntry(data: any): data is NpmDownloadsEntry {\n return 'downloads' in data && typeof data.downloads === 'number';\n}\n"],
|
4
|
+
"sourcesContent": ["\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Constants;\n(function (Constants) {\n Constants[Constants[\"MAX_DIMENSIONS\"] = 9] = \"MAX_DIMENSIONS\";\n Constants[\"DEFAULT_NAMESPACE\"] = \"aws-embedded-metrics\";\n Constants[Constants[\"MAX_METRICS_PER_EVENT\"] = 100] = \"MAX_METRICS_PER_EVENT\";\n Constants[\"DEFAULT_AGENT_HOST\"] = \"0.0.0.0\";\n Constants[Constants[\"DEFAULT_AGENT_PORT\"] = 25888] = \"DEFAULT_AGENT_PORT\";\n})(Constants = exports.Constants || (exports.Constants = {}));\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Environments;\n(function (Environments) {\n Environments[\"Local\"] = \"Local\";\n Environments[\"Lambda\"] = \"Lambda\";\n Environments[\"Agent\"] = \"Agent\";\n Environments[\"EC2\"] = \"EC2\";\n Environments[\"ECS\"] = \"ECS\";\n Environments[\"Unknown\"] = \"\";\n})(Environments || (Environments = {}));\nexports.default = Environments;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Constants_1 = require(\"../Constants\");\nconst Environments_1 = require(\"../environment/Environments\");\nconst ENV_VAR_PREFIX = 'AWS_EMF';\nvar ConfigKeys;\n(function (ConfigKeys) {\n ConfigKeys[\"LOG_GROUP_NAME\"] = \"LOG_GROUP_NAME\";\n ConfigKeys[\"LOG_STREAM_NAME\"] = \"LOG_STREAM_NAME\";\n ConfigKeys[\"ENABLE_DEBUG_LOGGING\"] = \"ENABLE_DEBUG_LOGGING\";\n ConfigKeys[\"SERVICE_NAME\"] = \"SERVICE_NAME\";\n ConfigKeys[\"SERVICE_TYPE\"] = \"SERVICE_TYPE\";\n ConfigKeys[\"AGENT_ENDPOINT\"] = \"AGENT_ENDPOINT\";\n ConfigKeys[\"ENVIRONMENT_OVERRIDE\"] = \"ENVIRONMENT\";\n ConfigKeys[\"NAMESPACE\"] = \"NAMESPACE\";\n})(ConfigKeys || (ConfigKeys = {}));\nclass EnvironmentConfigurationProvider {\n getConfiguration() {\n return {\n agentEndpoint: this.getEnvVariable(ConfigKeys.AGENT_ENDPOINT),\n debuggingLoggingEnabled: this.tryGetEnvVariableAsBoolean(ConfigKeys.ENABLE_DEBUG_LOGGING, false),\n logGroupName: this.getEnvVariable(ConfigKeys.LOG_GROUP_NAME),\n logStreamName: this.getEnvVariable(ConfigKeys.LOG_STREAM_NAME),\n serviceName: this.getEnvVariable(ConfigKeys.SERVICE_NAME) || this.getEnvVariableWithoutPrefix(ConfigKeys.SERVICE_NAME),\n serviceType: this.getEnvVariable(ConfigKeys.SERVICE_TYPE) || this.getEnvVariableWithoutPrefix(ConfigKeys.SERVICE_TYPE),\n environmentOverride: this.getEnvironmentOverride(),\n namespace: this.getEnvVariable(ConfigKeys.NAMESPACE) || Constants_1.Constants.DEFAULT_NAMESPACE,\n };\n }\n getEnvVariableWithoutPrefix(configKey) {\n return process.env[configKey];\n }\n getEnvVariable(configKey) {\n return process.env[`${ENV_VAR_PREFIX}_${configKey}`];\n }\n tryGetEnvVariableAsBoolean(configKey, fallback) {\n const configValue = this.getEnvVariable(configKey);\n return !configValue ? fallback : configValue.toLowerCase() === 'true';\n }\n getEnvironmentOverride() {\n const overrideValue = this.getEnvVariable(ConfigKeys.ENVIRONMENT_OVERRIDE);\n const environment = Environments_1.default[overrideValue];\n if (environment === undefined) {\n return Environments_1.default.Unknown;\n }\n return environment;\n }\n}\nexports.EnvironmentConfigurationProvider = EnvironmentConfigurationProvider;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst EnvironmentConfigurationProvider_1 = require(\"./EnvironmentConfigurationProvider\");\nconst Configuration = new EnvironmentConfigurationProvider_1.EnvironmentConfigurationProvider().getConfiguration();\nexports.default = Configuration;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Configuration_1 = require(\"../config/Configuration\");\nconst LOG = (...args) => {\n if (Configuration_1.default.debuggingLoggingEnabled) {\n console.log(...args);\n }\n};\nexports.LOG = LOG;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass MetricValues {\n constructor(value, unit) {\n this.values = [value];\n this.unit = unit || 'None';\n }\n /**\n * Appends the provided value to the current metric\n * @param value\n */\n addValue(value) {\n this.values.push(value);\n }\n}\nexports.MetricValues = MetricValues;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Configuration_1 = require(\"../config/Configuration\");\nconst Logger_1 = require(\"../utils/Logger\");\nconst MetricValues_1 = require(\"./MetricValues\");\nclass MetricsContext {\n /**\n * Constructor used to create child instances.\n * You should not use this constructor directly.\n * Instead, use createCopyWithContext() or empty().\n *\n * The reason for this is to avoid unexpected behavior when creating\n * MetricsContexts with defaultDimensions and existing dimensions.\n *\n * @param properties\n * @param dimensions\n */\n constructor(namespace, properties, dimensions, defaultDimensions, shouldUseDefaultDimensions, timestamp) {\n this.metrics = new Map();\n this.meta = {};\n this.shouldUseDefaultDimensions = true;\n this.namespace = namespace || Configuration_1.default.namespace;\n this.properties = properties || {};\n this.dimensions = dimensions || [];\n this.timestamp = timestamp;\n this.meta.Timestamp = MetricsContext.resolveMetaTimestamp(timestamp);\n this.defaultDimensions = defaultDimensions || {};\n if (shouldUseDefaultDimensions != undefined) {\n this.shouldUseDefaultDimensions = shouldUseDefaultDimensions;\n }\n }\n /**\n * Use this to create a new, empty context.\n */\n static empty() {\n return new MetricsContext();\n }\n static resolveMetaTimestamp(timestamp) {\n if (timestamp instanceof Date) {\n return timestamp.getTime();\n }\n else if (timestamp) {\n return timestamp;\n }\n else {\n return Date.now();\n }\n }\n setNamespace(value) {\n this.namespace = value;\n }\n setProperty(key, value) {\n this.properties[key] = value;\n }\n setTimestamp(timestamp) {\n this.timestamp = timestamp;\n this.meta.Timestamp = MetricsContext.resolveMetaTimestamp(timestamp);\n }\n /**\n * Sets default dimensions for the Context.\n * A dimension set will be created with just the default dimensions\n * and all calls to putDimensions will be prepended with the defaults.\n */\n setDefaultDimensions(dimensions) {\n Logger_1.LOG(`Received default dimensions`, dimensions);\n this.defaultDimensions = dimensions;\n }\n /**\n * Adds a new set of dimensions. Any time a new dimensions set\n * is added, the set is first prepended by the default dimensions.\n *\n * @param dimensions\n */\n putDimensions(incomingDimensionSet) {\n if (this.dimensions.length === 0) {\n this.dimensions.push(incomingDimensionSet);\n return;\n }\n for (let i = 0; i < this.dimensions.length; i++) {\n const existingDimensionSet = this.dimensions[i];\n // check for duplicate dimensions when putting\n // this is an O(n^2) operation, but since we never expect to have more than\n // 10 dimensions, this is acceptable for almost all cases.\n // This makes re-using loggers much easier.\n const existingDimensionSetKeys = Object.keys(existingDimensionSet);\n const incomingDimensionSetKeys = Object.keys(incomingDimensionSet);\n if (existingDimensionSetKeys.length !== incomingDimensionSetKeys.length) {\n this.dimensions.push(incomingDimensionSet);\n return;\n }\n for (let j = 0; j < existingDimensionSetKeys.length; j++) {\n if (!incomingDimensionSetKeys.includes(existingDimensionSetKeys[j])) {\n // we're done now because we know that the dimensions keys are not identical\n this.dimensions.push(incomingDimensionSet);\n return;\n }\n }\n }\n }\n /**\n * Overwrite all dimensions.\n *\n * @param dimensionSets\n */\n setDimensions(dimensionSets) {\n this.shouldUseDefaultDimensions = false;\n this.dimensions = dimensionSets;\n }\n /**\n * Get the current dimensions.\n */\n getDimensions() {\n // caller has explicitly called setDimensions\n if (this.shouldUseDefaultDimensions === false) {\n return this.dimensions;\n }\n // if there are no default dimensions, return the custom dimensions\n if (Object.keys(this.defaultDimensions).length === 0) {\n return this.dimensions;\n }\n // if default dimensions have been provided, but no custom dimensions, use the defaults\n if (this.dimensions.length === 0) {\n return [this.defaultDimensions];\n }\n // otherwise, merge the dimensions\n // we do this on the read path because default dimensions\n // may get updated asynchronously by environment detection\n return this.dimensions.map(custom => {\n return Object.assign(Object.assign({}, this.defaultDimensions), custom);\n });\n }\n putMetric(key, value, unit) {\n const currentMetric = this.metrics.get(key);\n if (currentMetric) {\n currentMetric.addValue(value);\n }\n else {\n this.metrics.set(key, new MetricValues_1.MetricValues(value, unit));\n }\n }\n /**\n * Creates an independently flushable context.\n */\n createCopyWithContext() {\n return new MetricsContext(this.namespace, Object.assign({}, this.properties), Object.assign([], this.dimensions), this.defaultDimensions, this.shouldUseDefaultDimensions, this.timestamp);\n }\n}\nexports.MetricsContext = MetricsContext;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Configuration_1 = require(\"../config/Configuration\");\nconst MetricsContext_1 = require(\"./MetricsContext\");\n/**\n * An async metrics logger.\n * Use this interface to publish logs to CloudWatch Logs\n * and extract metrics to CloudWatch Metrics asynchronously.\n */\nclass MetricsLogger {\n constructor(resolveEnvironment, context) {\n this.configureContextForEnvironment = (context, environment) => {\n const defaultDimensions = {\n // LogGroup name will entirely depend on the environment since there\n // are some cases where the LogGroup cannot be configured (e.g. Lambda)\n LogGroup: environment.getLogGroupName(),\n ServiceName: Configuration_1.default.serviceName || environment.getName(),\n ServiceType: Configuration_1.default.serviceType || environment.getType(),\n };\n context.setDefaultDimensions(defaultDimensions);\n environment.configureContext(context);\n };\n this.resolveEnvironment = resolveEnvironment;\n this.context = context || MetricsContext_1.MetricsContext.empty();\n }\n /**\n * Flushes the current context state to the configured sink.\n */\n flush() {\n return __awaiter(this, void 0, void 0, function* () {\n // resolve the environment and get the sink\n // MOST of the time this will run synchonrously\n // This only runs asynchronously if executing for the\n // first time in a non-lambda environment\n const environment = yield this.resolveEnvironment();\n this.configureContextForEnvironment(this.context, environment);\n const sink = environment.getSink();\n // accept and reset the context\n yield sink.accept(this.context);\n this.context = this.context.createCopyWithContext();\n });\n }\n /**\n * Set a property on the published metrics.\n * This is stored in the emitted log data and you are not\n * charged for this data by CloudWatch Metrics.\n * These values can be values that are useful for searching on,\n * but have too high cardinality to emit as dimensions to\n * CloudWatch Metrics.\n *\n * @param key Property name\n * @param value Property value\n */\n setProperty(key, value) {\n this.context.setProperty(key, value);\n return this;\n }\n /**\n * Adds a dimension.\n * This is generally a low cardinality key-value pair that is part of the metric identity.\n * CloudWatch treats each unique combination of dimensions as a separate metric, even if the metrics have the same metric name.\n *\n * @param dimension\n * @param value\n * @see [CloudWatch Dimensions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension)\n */\n putDimensions(dimensions) {\n this.context.putDimensions(dimensions);\n return this;\n }\n /**\n * Overwrite all dimensions on this MetricsLogger instance.\n *\n * @param dimensionSets\n * @see [CloudWatch Dimensions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension)\n */\n setDimensions(...dimensionSets) {\n this.context.setDimensions(dimensionSets);\n return this;\n }\n /**\n * Put a metric value.\n * This value will be emitted to CloudWatch Metrics asyncronously and does not contribute to your\n * account TPS limits. The value will also be available in your CloudWatch Logs\n * @param key\n * @param value\n * @param unit\n */\n putMetric(key, value, unit) {\n this.context.putMetric(key, value, unit);\n return this;\n }\n /**\n * Set the CloudWatch namespace that metrics should be published to.\n * @param value\n */\n setNamespace(value) {\n this.context.setNamespace(value);\n return this;\n }\n /**\n * Set the timestamp of metrics emitted in this context.\n *\n * If not set, the timestamp will default to new Date() at the point\n * the context is constructed.\n *\n * If set, timestamp will preserved across calls to flush().\n *\n * @param timestamp\n */\n setTimestamp(timestamp) {\n this.context.setTimestamp(timestamp);\n return this;\n }\n /**\n * Creates a new logger using the same contextual data as\n * the previous logger. This allows you to flush the instances\n * independently.\n */\n new() {\n return new MetricsLogger(this.resolveEnvironment, this.context.createCopyWithContext());\n }\n}\nexports.MetricsLogger = MetricsLogger;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Constants_1 = require(\"../Constants\");\n/**\n * Serializes the provided context to the CWL Structured\n * Logs format with Embedded Metric Filters.\n */\nclass LogSerializer {\n /**\n * Retrieve the current context as a JSON string\n */\n serialize(context) {\n const dimensionKeys = [];\n let dimensionProperties = {};\n context.getDimensions().forEach(d => {\n // we can only take the first 9 defined dimensions\n // the reason we do this in the serializer is because\n // it is possible that other sinks or formats can\n // support more dimensions\n // in the future it may make sense to introduce a higher-order\n // representation for sink-specific validations\n const keys = Object.keys(d).slice(0, Constants_1.Constants.MAX_DIMENSIONS);\n dimensionKeys.push(keys);\n dimensionProperties = Object.assign(Object.assign({}, dimensionProperties), d);\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const createBody = () => {\n return Object.assign(Object.assign(Object.assign({}, dimensionProperties), context.properties), { _aws: Object.assign(Object.assign({}, context.meta), { CloudWatchMetrics: [\n {\n Dimensions: dimensionKeys,\n Metrics: [],\n Namespace: context.namespace,\n },\n ] }) });\n };\n const eventBatches = [];\n let currentBody = createBody();\n const currentMetricsInBody = () => currentBody._aws.CloudWatchMetrics[0].Metrics.length;\n const shouldSerialize = () => currentMetricsInBody() === Constants_1.Constants.MAX_METRICS_PER_EVENT;\n // converts the body to JSON and pushes it into the batches\n const serializeCurrentBody = () => {\n eventBatches.push(JSON.stringify(currentBody));\n currentBody = createBody();\n };\n for (const [key, metric] of context.metrics) {\n // if there is only one metric value, unwrap it to make querying easier\n const metricValue = metric.values.length === 1 ? metric.values[0] : metric.values;\n currentBody[key] = metricValue;\n currentBody._aws.CloudWatchMetrics[0].Metrics.push({ Name: key, Unit: metric.unit });\n if (shouldSerialize()) {\n serializeCurrentBody();\n }\n }\n if (eventBatches.length === 0 || currentMetricsInBody() > 0) {\n serializeCurrentBody();\n }\n return eventBatches;\n }\n}\nexports.LogSerializer = LogSerializer;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst LogSerializer_1 = require(\"../serializers/LogSerializer\");\n/**\n * A sink that flushes log data to stdout.\n * This is the preferred sink for Lambda functions.\n */\nclass ConsoleSink {\n constructor(serializer) {\n this.name = 'ConsoleSink';\n this.serializer = serializer || new LogSerializer_1.LogSerializer();\n }\n accept(context) {\n // tslint:disable-next-line\n const events = this.serializer.serialize(context);\n events.forEach(event => console.log(event));\n return Promise.resolve();\n }\n}\nexports.ConsoleSink = ConsoleSink;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst net = require(\"net\");\nconst Logger_1 = require(\"../../utils/Logger\");\nclass TcpClient {\n constructor(endpoint) {\n this.endpoint = endpoint;\n this.socket = new net.Socket({ allowHalfOpen: true, writable: false })\n .setEncoding('utf8')\n .setKeepAlive(true)\n .setTimeout(5000) // idle timeout\n .on('timeout', () => this.disconnect('idle timeout'))\n .on('end', () => this.disconnect('end'))\n .on('data', data => Logger_1.LOG('TcpClient received data.', data));\n }\n warmup() {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n yield this.establishConnection();\n }\n catch (err) {\n Logger_1.LOG('Failed to connect', err);\n }\n });\n }\n sendMessage(message) {\n return __awaiter(this, void 0, void 0, function* () {\n // ensure the socket is open and writable\n yield this.waitForOpenConnection();\n yield new Promise((resolve, reject) => {\n const onSendError = (err) => {\n Logger_1.LOG('Failed to write', err);\n reject(err);\n };\n const wasFlushedToKernel = this.socket.write(message, (err) => {\n if (!err) {\n Logger_1.LOG('Write succeeded');\n resolve();\n }\n else {\n onSendError(err);\n }\n });\n if (!wasFlushedToKernel) {\n Logger_1.LOG('TcpClient data was not flushed to kernel buffer and was queued in memory.');\n }\n });\n });\n }\n disconnect(eventName) {\n Logger_1.LOG('TcpClient disconnected due to:', eventName);\n this.socket.removeAllListeners();\n this.socket.destroy();\n this.socket.unref();\n }\n waitForOpenConnection() {\n return __awaiter(this, void 0, void 0, function* () {\n if (!this.socket.writeable || this.socket.readyState !== 'open') {\n yield this.establishConnection();\n }\n });\n }\n establishConnection() {\n return __awaiter(this, void 0, void 0, function* () {\n yield new Promise((resolve, reject) => {\n const onError = (e) => {\n // socket is already open, no need to connect\n if (e.message.includes('EISCONN')) {\n resolve();\n return;\n }\n Logger_1.LOG('TCP Client received error', e);\n this.disconnect(e.message);\n reject(e);\n };\n const onConnect = () => {\n this.socket.removeListener('error', onError);\n Logger_1.LOG('TcpClient connected.', this.endpoint);\n resolve();\n };\n // TODO: convert this to a proper state machine\n switch (this.socket.readyState) {\n case 'open':\n resolve();\n break;\n case 'opening':\n // the socket is currently opening, we will resolve\n // or fail the current promise on the connect or\n // error events\n this.socket.once('connect', onConnect);\n this.socket.once('error', onError);\n break;\n default:\n Logger_1.LOG('opening connection with socket in state: ', this.socket.readyState);\n this.socket.connect(this.endpoint.port, this.endpoint.host, onConnect).once('error', onError);\n break;\n }\n });\n });\n }\n}\nexports.TcpClient = TcpClient;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst dgram = require(\"dgram\");\nconst Logger_1 = require(\"../../utils/Logger\");\nclass UdpClient {\n constructor(endpoint) {\n this.endpoint = endpoint;\n }\n // No warm up for UDP\n warmup() {\n return Promise.resolve();\n }\n sendMessage(message) {\n return __awaiter(this, void 0, void 0, function* () {\n const client = dgram.createSocket('udp4');\n client.send(message, this.endpoint.port, this.endpoint.host, (error) => {\n if (error) {\n Logger_1.LOG(error);\n }\n client.close();\n });\n return Promise.resolve();\n });\n }\n}\nexports.UdpClient = UdpClient;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst url = require(\"url\");\nconst Configuration_1 = require(\"../config/Configuration\");\nconst LogSerializer_1 = require(\"../serializers/LogSerializer\");\nconst Logger_1 = require(\"../utils/Logger\");\nconst TcpClient_1 = require(\"./connections/TcpClient\");\nconst UdpClient_1 = require(\"./connections/UdpClient\");\nconst TCP = 'tcp:';\nconst UDP = 'udp:';\nconst defaultTcpEndpoint = {\n host: '0.0.0.0',\n port: 25888,\n protocol: TCP,\n};\nconst parseEndpoint = (endpoint) => {\n try {\n if (!endpoint) {\n return defaultTcpEndpoint;\n }\n const parsedUrl = url.parse(endpoint);\n if (!parsedUrl.hostname || !parsedUrl.port || !parsedUrl.protocol) {\n Logger_1.LOG(`Failed to parse the provided agent endpoint. Falling back to the default TCP endpoint.`, parsedUrl);\n return defaultTcpEndpoint;\n }\n if (parsedUrl.protocol !== TCP && parsedUrl.protocol !== UDP) {\n Logger_1.LOG(`The provided agent endpoint protocol '${parsedUrl.protocol}' is not supported. Please use TCP or UDP. Falling back to the default TCP endpoint.`, parsedUrl);\n return defaultTcpEndpoint;\n }\n return {\n host: parsedUrl.hostname,\n port: Number(parsedUrl.port),\n protocol: parsedUrl.protocol,\n };\n }\n catch (e) {\n Logger_1.LOG('Failed to parse the provided agent endpoint', e);\n return defaultTcpEndpoint;\n }\n};\n/**\n * A sink that flushes to the CW Agent.\n * This sink instance should be re-used to avoid\n * leaking connections.\n */\nclass AgentSink {\n constructor(logGroupName, logStreamName, serializer) {\n this.name = 'AgentSink';\n this.logGroupName = logGroupName;\n this.logStreamName = logStreamName;\n this.serializer = serializer || new LogSerializer_1.LogSerializer();\n this.endpoint = parseEndpoint(Configuration_1.default.agentEndpoint);\n this.socketClient = this.getSocketClient(this.endpoint);\n Logger_1.LOG('Using socket client', this.socketClient.constructor.name);\n }\n accept(context) {\n return __awaiter(this, void 0, void 0, function* () {\n if (this.logGroupName) {\n context.meta.LogGroupName = this.logGroupName;\n }\n if (this.logStreamName) {\n context.meta.LogStreamName = this.logStreamName;\n }\n const events = this.serializer.serialize(context);\n Logger_1.LOG(`Sending {} events to socket.`, events.length);\n for (let index = 0; index < events.length; index++) {\n const event = events[index];\n const message = event + '\\n';\n const bytes = Buffer.from(message);\n yield this.socketClient.sendMessage(bytes);\n }\n });\n }\n getSocketClient(endpoint) {\n Logger_1.LOG('Getting socket client for connection.', endpoint);\n const client = endpoint.protocol === TCP ? new TcpClient_1.TcpClient(endpoint) : new UdpClient_1.UdpClient(endpoint);\n client.warmup();\n return client;\n }\n}\nexports.AgentSink = AgentSink;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Configuration_1 = require(\"../config/Configuration\");\nconst AgentSink_1 = require(\"../sinks/AgentSink\");\nconst Logger_1 = require(\"../utils/Logger\");\nclass DefaultEnvironment {\n probe() {\n return Promise.resolve(true);\n }\n getName() {\n if (!Configuration_1.default.serviceName) {\n Logger_1.LOG('Unknown ServiceName.');\n return 'Unknown';\n }\n return Configuration_1.default.serviceName;\n }\n getType() {\n if (!Configuration_1.default.serviceType) {\n Logger_1.LOG('Unknown ServiceType.');\n return 'Unknown';\n }\n return Configuration_1.default.serviceType;\n }\n getLogGroupName() {\n // if the caller explicitly overrides logGroupName to\n // be empty, we should honor that rather than providing\n // the default behavior.\n if (Configuration_1.default.logGroupName === '') {\n return '';\n }\n return Configuration_1.default.logGroupName ? Configuration_1.default.logGroupName : `${this.getName()}-metrics`;\n }\n configureContext() {\n // no-op\n }\n getSink() {\n if (!this.sink) {\n this.sink = new AgentSink_1.AgentSink(this.getLogGroupName(), Configuration_1.default.logStreamName);\n }\n return this.sink;\n }\n}\nexports.DefaultEnvironment = DefaultEnvironment;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst http = require(\"http\");\nconst SOCKET_TIMEOUT = 1000;\n/**\n * Fetch JSON data from an remote HTTP endpoint and de-serialize to the provided type.\n * There are no guarantees the response will conform to the contract defined by T.\n * It is up to the consumer to ensure the provided T captures all possible response types\n * from the provided endpoint.\n *\n * @param url - currently only supports HTTP\n */\nconst fetch = (url) => {\n return new Promise((resolve, reject) => {\n const request = http\n .get(url, { timeout: 2000 }, (response) => {\n if (!response.statusCode) {\n reject(`Received undefined response status code from '${url}'`);\n return;\n }\n if (response.statusCode < 200 || response.statusCode > 299) {\n reject(new Error('Failed to load page, status code: ' + response.statusCode));\n return;\n }\n // using similar approach to node-fetch\n // https://github.com/bitinn/node-fetch/blob/6a5d192034a0f438551dffb6d2d8df2c00921d16/src/body.js#L217\n const body = [];\n let bodyBytes = 0;\n response.on('data', (chunk) => {\n bodyBytes += chunk.length;\n body.push(chunk);\n });\n response.on('end', () => {\n let responseString;\n try {\n const buffer = Buffer.concat(body, bodyBytes);\n responseString = buffer.toString();\n const parsedJson = JSON.parse(responseString);\n resolve(parsedJson);\n }\n catch (e) {\n reject(`Failed to parse response from '${url}' as JSON. Received: ${responseString}`);\n }\n });\n })\n .on('error', (err) => {\n reject(err);\n });\n request.on('socket', socket => {\n socket.on('timeout', () => {\n request.abort();\n reject(`Socket timeout while connecting to '${url}'`);\n });\n socket.setTimeout(SOCKET_TIMEOUT);\n });\n });\n};\nexports.fetch = fetch;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Configuration_1 = require(\"../config/Configuration\");\nconst AgentSink_1 = require(\"../sinks/AgentSink\");\nconst Fetch_1 = require(\"../utils/Fetch\");\nconst Logger_1 = require(\"../utils/Logger\");\nconst os = require(\"os\");\nconst Constants_1 = require(\"../Constants\");\n// formats image names into something more readable for a metric name\n// e.g. <account-id>.dkr.ecr.<region>.amazonaws.com/<image-name>:latest -> <image-name>:latest\nconst formatImageName = (imageName) => {\n if (imageName) {\n const splitImageName = imageName.split('/');\n return splitImageName[splitImageName.length - 1];\n }\n return imageName;\n};\nclass ECSEnvironment {\n probe() {\n return __awaiter(this, void 0, void 0, function* () {\n if (!process.env.ECS_CONTAINER_METADATA_URI) {\n return Promise.resolve(false);\n }\n if (process.env.FLUENT_HOST && !Configuration_1.default.agentEndpoint) {\n this.fluentBitEndpoint = `tcp://${process.env.FLUENT_HOST}:${Constants_1.Constants.DEFAULT_AGENT_PORT}`;\n Configuration_1.default.agentEndpoint = this.fluentBitEndpoint;\n Logger_1.LOG(`Using FluentBit configuration. Endpoint: ${this.fluentBitEndpoint}`);\n }\n try {\n this.metadata = yield Fetch_1.fetch(process.env.ECS_CONTAINER_METADATA_URI);\n if (this.metadata) {\n this.metadata.FormattedImageName = formatImageName(this.metadata.Image);\n Logger_1.LOG(`Successfully collected ECS Container metadata.`);\n }\n }\n catch (e) {\n Logger_1.LOG('Failed to collect ECS Container Metadata.');\n Logger_1.LOG(e);\n }\n // return true regardless of whether or not metadata collection\n // succeeded. we know that this is supposed to be an ECS environment\n // just from the environment variable\n return true;\n });\n }\n getName() {\n var _a;\n if (Configuration_1.default.serviceName) {\n return Configuration_1.default.serviceName;\n }\n return ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.FormattedImageName) ? this.metadata.FormattedImageName : 'Unknown';\n }\n getType() {\n return 'AWS::ECS::Container';\n }\n getLogGroupName() {\n // FireLens / fluent-bit does not need the log group to be included\n // since configuration of the LogGroup is handled by the\n // fluent bit config file\n if (this.fluentBitEndpoint) {\n return '';\n }\n return Configuration_1.default.logGroupName || this.getName();\n }\n configureContext(context) {\n var _a, _b, _c, _d, _e;\n this.addProperty(context, 'containerId', os.hostname());\n this.addProperty(context, 'createdAt', (_a = this.metadata) === null || _a === void 0 ? void 0 : _a.CreatedAt);\n this.addProperty(context, 'startedAt', (_b = this.metadata) === null || _b === void 0 ? void 0 : _b.StartedAt);\n this.addProperty(context, 'image', (_c = this.metadata) === null || _c === void 0 ? void 0 : _c.Image);\n this.addProperty(context, 'cluster', (_d = this.metadata) === null || _d === void 0 ? void 0 : _d.Labels['com.amazonaws.ecs.cluster']);\n this.addProperty(context, 'taskArn', (_e = this.metadata) === null || _e === void 0 ? void 0 : _e.Labels['com.amazonaws.ecs.task-arn']);\n // we override the standard default dimensions here because in the\n // FireLens / fluent-bit case, we don't need the LogGroup\n if (this.fluentBitEndpoint) {\n context.setDefaultDimensions({\n ServiceName: Configuration_1.default.serviceName || this.getName(),\n ServiceType: Configuration_1.default.serviceType || this.getType(),\n });\n }\n }\n getSink() {\n if (!this.sink) {\n const logGroupName = this.fluentBitEndpoint ? '' : this.getLogGroupName();\n this.sink = new AgentSink_1.AgentSink(logGroupName);\n }\n return this.sink;\n }\n addProperty(context, key, value) {\n if (value) {\n context.setProperty(key, value);\n }\n }\n}\nexports.ECSEnvironment = ECSEnvironment;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Configuration_1 = require(\"../config/Configuration\");\nconst AgentSink_1 = require(\"../sinks/AgentSink\");\nconst Fetch_1 = require(\"../utils/Fetch\");\nconst Logger_1 = require(\"../utils/Logger\");\nconst endpoint = 'http://169.254.169.254/latest/dynamic/instance-identity/document';\nclass EC2Environment {\n probe() {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n this.metadata = yield Fetch_1.fetch(endpoint);\n if (this.metadata) {\n return true;\n }\n return false;\n }\n catch (e) {\n Logger_1.LOG(e);\n return false;\n }\n });\n }\n getName() {\n if (!Configuration_1.default.serviceName) {\n Logger_1.LOG('Unknown ServiceName.');\n return 'Unknown';\n }\n return Configuration_1.default.serviceName;\n }\n getType() {\n if (this.metadata) {\n return 'AWS::EC2::Instance';\n }\n // this will only happen if probe() is not called first\n return 'Unknown';\n }\n getLogGroupName() {\n return Configuration_1.default.logGroupName ? Configuration_1.default.logGroupName : `${this.getName()}-metrics`;\n }\n configureContext(context) {\n if (this.metadata) {\n context.setProperty('imageId', this.metadata.imageId);\n context.setProperty('instanceId', this.metadata.instanceId);\n context.setProperty('instanceType', this.metadata.instanceType);\n context.setProperty('privateIP', this.metadata.privateIp);\n context.setProperty('availabilityZone', this.metadata.availabilityZone);\n }\n }\n getSink() {\n if (!this.sink) {\n this.sink = new AgentSink_1.AgentSink(this.getLogGroupName(), Configuration_1.default.logStreamName);\n }\n return this.sink;\n }\n}\nexports.EC2Environment = EC2Environment;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst ConsoleSink_1 = require(\"../sinks/ConsoleSink\");\nclass LambdaEnvironment {\n probe() {\n return Promise.resolve(process.env.AWS_LAMBDA_FUNCTION_NAME ? true : false);\n }\n getName() {\n return process.env.AWS_LAMBDA_FUNCTION_NAME || 'Unknown';\n }\n getType() {\n return 'AWS::Lambda::Function';\n }\n getLogGroupName() {\n return this.getName();\n }\n configureContext(context) {\n this.addProperty(context, 'executionEnvironment', process.env.AWS_EXECUTION_ENV);\n this.addProperty(context, 'memorySize', process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE);\n this.addProperty(context, 'functionVersion', process.env.AWS_LAMBDA_FUNCTION_VERSION);\n this.addProperty(context, 'logStreamId', process.env.AWS_LAMBDA_LOG_STREAM_NAME);\n const trace = this.getSampledTrace();\n if (trace) {\n this.addProperty(context, 'traceId', trace);\n }\n }\n getSink() {\n if (!this.sink) {\n this.sink = new ConsoleSink_1.ConsoleSink();\n }\n return this.sink;\n }\n addProperty(context, key, value) {\n if (value) {\n context.setProperty(key, value);\n }\n }\n getSampledTrace() {\n // only collect traces which have been sampled\n if (process.env._X_AMZN_TRACE_ID && process.env._X_AMZN_TRACE_ID.includes('Sampled=1')) {\n return process.env._X_AMZN_TRACE_ID;\n }\n }\n}\nexports.LambdaEnvironment = LambdaEnvironment;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Configuration_1 = require(\"../config/Configuration\");\nconst Logger_1 = require(\"../utils/Logger\");\nconst ConsoleSink_1 = require(\"../sinks/ConsoleSink\");\nclass LocalEnvironment {\n probe() {\n // probe is not intended to be used in the LocalEnvironment\n // To use the local environment you should set the environment\n // override\n return Promise.resolve(false);\n }\n getName() {\n if (!Configuration_1.default.serviceName) {\n Logger_1.LOG('Unknown ServiceName.');\n return 'Unknown';\n }\n return Configuration_1.default.serviceName;\n }\n getType() {\n if (!Configuration_1.default.serviceType) {\n Logger_1.LOG('Unknown ServiceType.');\n return 'Unknown';\n }\n return Configuration_1.default.serviceType;\n }\n getLogGroupName() {\n return Configuration_1.default.logGroupName ? Configuration_1.default.logGroupName : `${this.getName()}-metrics`;\n }\n configureContext() {\n // no-op\n }\n getSink() {\n if (!this.sink) {\n this.sink = new ConsoleSink_1.ConsoleSink();\n }\n return this.sink;\n }\n}\nexports.LocalEnvironment = LocalEnvironment;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Logger_1 = require(\"../utils/Logger\");\nconst DefaultEnvironment_1 = require(\"./DefaultEnvironment\");\nconst ECSEnvironment_1 = require(\"./ECSEnvironment\");\nconst EC2Environment_1 = require(\"./EC2Environment\");\nconst LambdaEnvironment_1 = require(\"./LambdaEnvironment\");\nconst Configuration_1 = require(\"../config/Configuration\");\nconst Environments_1 = require(\"./Environments\");\nconst LocalEnvironment_1 = require(\"./LocalEnvironment\");\nconst lambdaEnvironment = new LambdaEnvironment_1.LambdaEnvironment();\nconst ecsEnvironment = new ECSEnvironment_1.ECSEnvironment();\nconst ec2Environment = new EC2Environment_1.EC2Environment();\nconst defaultEnvironment = new DefaultEnvironment_1.DefaultEnvironment();\n// ordering of this array matters\n// both Lambda and ECS can be determined from environment variables\n// making the entire detection process fast an cheap\n// EC2 can only be determined by making a remote HTTP request\nconst environments = [lambdaEnvironment, ecsEnvironment, ec2Environment];\nlet environment = undefined;\nconst getEnvironmentFromOverride = () => {\n // short-circuit environment detection and use override\n switch (Configuration_1.default.environmentOverride) {\n case Environments_1.default.Agent:\n return defaultEnvironment;\n case Environments_1.default.EC2:\n return ec2Environment;\n case Environments_1.default.Lambda:\n return lambdaEnvironment;\n case Environments_1.default.ECS:\n return ecsEnvironment;\n case Environments_1.default.Local:\n return new LocalEnvironment_1.LocalEnvironment();\n case Environments_1.default.Unknown:\n default:\n return undefined;\n }\n};\nconst discoverEnvironment = () => __awaiter(void 0, void 0, void 0, function* () {\n Logger_1.LOG(`Discovering environment`);\n for (const envUnderTest of environments) {\n Logger_1.LOG(`Testing: ${envUnderTest.constructor.name}`);\n try {\n if (yield envUnderTest.probe()) {\n return envUnderTest;\n }\n }\n catch (e) {\n Logger_1.LOG(`Failed probe: ${envUnderTest.constructor.name}`);\n }\n }\n return defaultEnvironment;\n});\nconst _resolveEnvironment = () => __awaiter(void 0, void 0, void 0, function* () {\n Logger_1.LOG('Resolving environment');\n if (environment) {\n return environment;\n }\n if (Configuration_1.default.environmentOverride) {\n Logger_1.LOG('Environment override supplied', Configuration_1.default.environmentOverride);\n // this will be falsy if an invalid configuration value is provided\n environment = getEnvironmentFromOverride();\n if (environment) {\n return environment;\n }\n else {\n Logger_1.LOG('Invalid environment provided. Falling back to auto-discovery.', Configuration_1.default.environmentOverride);\n }\n }\n environment = yield discoverEnvironment(); // eslint-disable-line require-atomic-updates\n return environment;\n});\n// pro-actively begin resolving the environment\n// this will allow us to kick off any async tasks\n// at module load time to reduce any blocking that\n// may occur on the initial flush()\nconst environmentPromise = _resolveEnvironment();\nconst resolveEnvironment = () => __awaiter(void 0, void 0, void 0, function* () {\n return environmentPromise;\n});\nexports.resolveEnvironment = resolveEnvironment;\n// this method is used for testing to bypass the cached environmentPromise result\nconst cleanResolveEnvironment = () => __awaiter(void 0, void 0, void 0, function* () {\n yield environmentPromise;\n environment = undefined;\n return yield _resolveEnvironment();\n});\nexports.cleanResolveEnvironment = cleanResolveEnvironment;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst __1 = require(\"..\");\nconst EnvironmentDetector_1 = require(\"../environment/EnvironmentDetector\");\nconst MetricsContext_1 = require(\"./MetricsContext\");\nconst createMetricsLogger = () => {\n const context = MetricsContext_1.MetricsContext.empty();\n const logger = new __1.MetricsLogger(EnvironmentDetector_1.resolveEnvironment, context);\n return logger;\n};\nexports.createMetricsLogger = createMetricsLogger;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Logger_1 = require(\"../utils/Logger\");\nconst MetricsLoggerFactory_1 = require(\"./MetricsLoggerFactory\");\n/**\n * An asynchronous wrapper that provides a metrics instance.\n */\nconst metricScope = (handler) => {\n const wrappedHandler = (...args) => __awaiter(void 0, void 0, void 0, function* () {\n const metrics = MetricsLoggerFactory_1.createMetricsLogger();\n try {\n return yield handler(metrics)(...args);\n }\n finally {\n try {\n yield metrics.flush();\n }\n catch (e) {\n Logger_1.LOG('Failed to flush metrics', e);\n }\n }\n });\n return wrappedHandler;\n};\nexports.metricScope = metricScope;\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Unit;\n(function (Unit) {\n Unit[\"Seconds\"] = \"Seconds\";\n Unit[\"Microseconds\"] = \"Microseconds\";\n Unit[\"Milliseconds\"] = \"Milliseconds\";\n Unit[\"Bytes\"] = \"Bytes\";\n Unit[\"Kilobytes\"] = \"Kilobytes\";\n Unit[\"Megabytes\"] = \"Megabytes\";\n Unit[\"Gigabytes\"] = \"Gigabytes\";\n Unit[\"Terabytes\"] = \"Terabytes\";\n Unit[\"Bits\"] = \"Bits\";\n Unit[\"Kilobits\"] = \"Kilobits\";\n Unit[\"Megabits\"] = \"Megabits\";\n Unit[\"Gigabits\"] = \"Gigabits\";\n Unit[\"Terabits\"] = \"Terabits\";\n Unit[\"Percent\"] = \"Percent\";\n Unit[\"Count\"] = \"Count\";\n Unit[\"BytesPerSecond\"] = \"Bytes/Second\";\n Unit[\"KilobytesPerSecond\"] = \"Kilobytes/Second\";\n Unit[\"MegabytesPerSecond\"] = \"Megabytes/Second\";\n Unit[\"GigabytesPerSecond\"] = \"Gigabytes/Second\";\n Unit[\"TerabytesPerSecond\"] = \"Terabytes/Second\";\n Unit[\"BitsPerSecond\"] = \"Bits/Second\";\n Unit[\"KilobitsPerSecond\"] = \"Kilobits/Second\";\n Unit[\"MegabitsPerSecond\"] = \"Megabits/Second\";\n Unit[\"GigabitsPerSecond\"] = \"Gigabits/Second\";\n Unit[\"TerabitsPerSecond\"] = \"Terabits/Second\";\n Unit[\"CountPerSecond\"] = \"Count/Second\";\n Unit[\"None\"] = \"None\";\n})(Unit = exports.Unit || (exports.Unit = {}));\n", "\"use strict\";\n/*\n * Copyright 2019 Amazon.com, Inc. or its affiliates.\n * Licensed under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar MetricsLogger_1 = require(\"./logger/MetricsLogger\");\nexports.MetricsLogger = MetricsLogger_1.MetricsLogger;\nvar ConsoleSink_1 = require(\"./sinks/ConsoleSink\");\nexports.LocalSink = ConsoleSink_1.ConsoleSink;\nvar AgentSink_1 = require(\"./sinks/AgentSink\");\nexports.AgentSink = AgentSink_1.AgentSink;\nvar MetricScope_1 = require(\"./logger/MetricScope\");\nexports.metricScope = MetricScope_1.metricScope;\nvar MetricsLoggerFactory_1 = require(\"./logger/MetricsLoggerFactory\");\nexports.createMetricsLogger = MetricsLoggerFactory_1.createMetricsLogger;\nvar Unit_1 = require(\"./logger/Unit\");\nexports.Unit = Unit_1.Unit;\nconst Configuration_1 = require(\"./config/Configuration\");\nexports.Configuration = Configuration_1.default;\n", "\"use strict\";\n/// <reference lib=\"es2018\"/>\n/// <reference lib=\"dom\"/>\n/// <reference types=\"node\"/>\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst typedArrayTypeNames = [\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array',\n 'BigInt64Array',\n 'BigUint64Array'\n];\nfunction isTypedArrayName(name) {\n return typedArrayTypeNames.includes(name);\n}\nconst objectTypeNames = [\n 'Function',\n 'Generator',\n 'AsyncGenerator',\n 'GeneratorFunction',\n 'AsyncGeneratorFunction',\n 'AsyncFunction',\n 'Observable',\n 'Array',\n 'Buffer',\n 'Object',\n 'RegExp',\n 'Date',\n 'Error',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'ArrayBuffer',\n 'SharedArrayBuffer',\n 'DataView',\n 'Promise',\n 'URL',\n 'FormData',\n 'URLSearchParams',\n 'HTMLElement',\n ...typedArrayTypeNames\n];\nfunction isObjectTypeName(name) {\n return objectTypeNames.includes(name);\n}\nconst primitiveTypeNames = [\n 'null',\n 'undefined',\n 'string',\n 'number',\n 'bigint',\n 'boolean',\n 'symbol'\n];\nfunction isPrimitiveTypeName(name) {\n return primitiveTypeNames.includes(name);\n}\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction isOfType(type) {\n return (value) => typeof value === type;\n}\nconst { toString } = Object.prototype;\nconst getObjectType = (value) => {\n const objectTypeName = toString.call(value).slice(8, -1);\n if (/HTML\\w+Element/.test(objectTypeName) && is.domElement(value)) {\n return 'HTMLElement';\n }\n if (isObjectTypeName(objectTypeName)) {\n return objectTypeName;\n }\n return undefined;\n};\nconst isObjectOfType = (type) => (value) => getObjectType(value) === type;\nfunction is(value) {\n if (value === null) {\n return 'null';\n }\n switch (typeof value) {\n case 'undefined':\n return 'undefined';\n case 'string':\n return 'string';\n case 'number':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'function':\n return 'Function';\n case 'bigint':\n return 'bigint';\n case 'symbol':\n return 'symbol';\n default:\n }\n if (is.observable(value)) {\n return 'Observable';\n }\n if (is.array(value)) {\n return 'Array';\n }\n if (is.buffer(value)) {\n return 'Buffer';\n }\n const tagType = getObjectType(value);\n if (tagType) {\n return tagType;\n }\n if (value instanceof String || value instanceof Boolean || value instanceof Number) {\n throw new TypeError('Please don\\'t use object wrappers for primitive types');\n }\n return 'Object';\n}\nis.undefined = isOfType('undefined');\nis.string = isOfType('string');\nconst isNumberType = isOfType('number');\nis.number = (value) => isNumberType(value) && !is.nan(value);\nis.bigint = isOfType('bigint');\n// eslint-disable-next-line @typescript-eslint/ban-types\nis.function_ = isOfType('function');\nis.null_ = (value) => value === null;\nis.class_ = (value) => is.function_(value) && value.toString().startsWith('class ');\nis.boolean = (value) => value === true || value === false;\nis.symbol = isOfType('symbol');\nis.numericString = (value) => is.string(value) && !is.emptyStringOrWhitespace(value) && !Number.isNaN(Number(value));\nis.array = (value, assertion) => {\n if (!Array.isArray(value)) {\n return false;\n }\n if (!is.function_(assertion)) {\n return true;\n }\n return value.every(assertion);\n};\nis.buffer = (value) => { var _a, _b, _c, _d; return (_d = (_c = (_b = (_a = value) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.isBuffer) === null || _c === void 0 ? void 0 : _c.call(_b, value)) !== null && _d !== void 0 ? _d : false; };\nis.nullOrUndefined = (value) => is.null_(value) || is.undefined(value);\nis.object = (value) => !is.null_(value) && (typeof value === 'object' || is.function_(value));\nis.iterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.iterator]); };\nis.asyncIterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.asyncIterator]); };\nis.generator = (value) => is.iterable(value) && is.function_(value.next) && is.function_(value.throw);\nis.asyncGenerator = (value) => is.asyncIterable(value) && is.function_(value.next) && is.function_(value.throw);\nis.nativePromise = (value) => isObjectOfType('Promise')(value);\nconst hasPromiseAPI = (value) => {\n var _a, _b;\n return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a.then) &&\n is.function_((_b = value) === null || _b === void 0 ? void 0 : _b.catch);\n};\nis.promise = (value) => is.nativePromise(value) || hasPromiseAPI(value);\nis.generatorFunction = isObjectOfType('GeneratorFunction');\nis.asyncGeneratorFunction = (value) => getObjectType(value) === 'AsyncGeneratorFunction';\nis.asyncFunction = (value) => getObjectType(value) === 'AsyncFunction';\n// eslint-disable-next-line no-prototype-builtins, @typescript-eslint/ban-types\nis.boundFunction = (value) => is.function_(value) && !value.hasOwnProperty('prototype');\nis.regExp = isObjectOfType('RegExp');\nis.date = isObjectOfType('Date');\nis.error = isObjectOfType('Error');\nis.map = (value) => isObjectOfType('Map')(value);\nis.set = (value) => isObjectOfType('Set')(value);\nis.weakMap = (value) => isObjectOfType('WeakMap')(value);\nis.weakSet = (value) => isObjectOfType('WeakSet')(value);\nis.int8Array = isObjectOfType('Int8Array');\nis.uint8Array = isObjectOfType('Uint8Array');\nis.uint8ClampedArray = isObjectOfType('Uint8ClampedArray');\nis.int16Array = isObjectOfType('Int16Array');\nis.uint16Array = isObjectOfType('Uint16Array');\nis.int32Array = isObjectOfType('Int32Array');\nis.uint32Array = isObjectOfType('Uint32Array');\nis.float32Array = isObjectOfType('Float32Array');\nis.float64Array = isObjectOfType('Float64Array');\nis.bigInt64Array = isObjectOfType('BigInt64Array');\nis.bigUint64Array = isObjectOfType('BigUint64Array');\nis.arrayBuffer = isObjectOfType('ArrayBuffer');\nis.sharedArrayBuffer = isObjectOfType('SharedArrayBuffer');\nis.dataView = isObjectOfType('DataView');\nis.directInstanceOf = (instance, class_) => Object.getPrototypeOf(instance) === class_.prototype;\nis.urlInstance = (value) => isObjectOfType('URL')(value);\nis.urlString = (value) => {\n if (!is.string(value)) {\n return false;\n }\n try {\n new URL(value); // eslint-disable-line no-new\n return true;\n }\n catch (_a) {\n return false;\n }\n};\n// TODO: Use the `not` operator with a type guard here when it's available.\n// Example: `is.truthy = (value: unknown): value is (not false | not 0 | not '' | not undefined | not null) => Boolean(value);`\nis.truthy = (value) => Boolean(value);\n// Example: `is.falsy = (value: unknown): value is (not true | 0 | '' | undefined | null) => Boolean(value);`\nis.falsy = (value) => !value;\nis.nan = (value) => Number.isNaN(value);\nis.primitive = (value) => is.null_(value) || isPrimitiveTypeName(typeof value);\nis.integer = (value) => Number.isInteger(value);\nis.safeInteger = (value) => Number.isSafeInteger(value);\nis.plainObject = (value) => {\n // From: https://github.com/sindresorhus/is-plain-obj/blob/main/index.js\n if (toString.call(value) !== '[object Object]') {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === null || prototype === Object.getPrototypeOf({});\n};\nis.typedArray = (value) => isTypedArrayName(getObjectType(value));\nconst isValidLength = (value) => is.safeInteger(value) && value >= 0;\nis.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length);\nis.inRange = (value, range) => {\n if (is.number(range)) {\n return value >= Math.min(0, range) && value <= Math.max(range, 0);\n }\n if (is.array(range) && range.length === 2) {\n return value >= Math.min(...range) && value <= Math.max(...range);\n }\n throw new TypeError(`Invalid range: ${JSON.stringify(range)}`);\n};\nconst NODE_TYPE_ELEMENT = 1;\nconst DOM_PROPERTIES_TO_CHECK = [\n 'innerHTML',\n 'ownerDocument',\n 'style',\n 'attributes',\n 'nodeValue'\n];\nis.domElement = (value) => {\n return is.object(value) &&\n value.nodeType === NODE_TYPE_ELEMENT &&\n is.string(value.nodeName) &&\n !is.plainObject(value) &&\n DOM_PROPERTIES_TO_CHECK.every(property => property in value);\n};\nis.observable = (value) => {\n var _a, _b, _c, _d;\n if (!value) {\n return false;\n }\n // eslint-disable-next-line no-use-extend-native/no-use-extend-native\n if (value === ((_b = (_a = value)[Symbol.observable]) === null || _b === void 0 ? void 0 : _b.call(_a))) {\n return true;\n }\n if (value === ((_d = (_c = value)['@@observable']) === null || _d === void 0 ? void 0 : _d.call(_c))) {\n return true;\n }\n return false;\n};\nis.nodeStream = (value) => is.object(value) && is.function_(value.pipe) && !is.observable(value);\nis.infinite = (value) => value === Infinity || value === -Infinity;\nconst isAbsoluteMod2 = (remainder) => (value) => is.integer(value) && Math.abs(value % 2) === remainder;\nis.evenInteger = isAbsoluteMod2(0);\nis.oddInteger = isAbsoluteMod2(1);\nis.emptyArray = (value) => is.array(value) && value.length === 0;\nis.nonEmptyArray = (value) => is.array(value) && value.length > 0;\nis.emptyString = (value) => is.string(value) && value.length === 0;\n// TODO: Use `not ''` when the `not` operator is available.\nis.nonEmptyString = (value) => is.string(value) && value.length > 0;\nconst isWhiteSpaceString = (value) => is.string(value) && !/\\S/.test(value);\nis.emptyStringOrWhitespace = (value) => is.emptyString(value) || isWhiteSpaceString(value);\nis.emptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length === 0;\n// TODO: Use `not` operator here to remove `Map` and `Set` from type guard:\n// - https://github.com/Microsoft/TypeScript/pull/29317\nis.nonEmptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length > 0;\nis.emptySet = (value) => is.set(value) && value.size === 0;\nis.nonEmptySet = (value) => is.set(value) && value.size > 0;\nis.emptyMap = (value) => is.map(value) && value.size === 0;\nis.nonEmptyMap = (value) => is.map(value) && value.size > 0;\n// `PropertyKey` is any value that can be used as an object key (string, number, or symbol)\nis.propertyKey = (value) => is.any([is.string, is.number, is.symbol], value);\nis.formData = (value) => isObjectOfType('FormData')(value);\nis.urlSearchParams = (value) => isObjectOfType('URLSearchParams')(value);\nconst predicateOnArray = (method, predicate, values) => {\n if (!is.function_(predicate)) {\n throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`);\n }\n if (values.length === 0) {\n throw new TypeError('Invalid number of values');\n }\n return method.call(values, predicate);\n};\nis.any = (predicate, ...values) => {\n const predicates = is.array(predicate) ? predicate : [predicate];\n return predicates.some(singlePredicate => predicateOnArray(Array.prototype.some, singlePredicate, values));\n};\nis.all = (predicate, ...values) => predicateOnArray(Array.prototype.every, predicate, values);\nconst assertType = (condition, description, value, options = {}) => {\n if (!condition) {\n const { multipleValues } = options;\n const valuesMessage = multipleValues ?\n `received values of types ${[\n ...new Set(value.map(singleValue => `\\`${is(singleValue)}\\``))\n ].join(', ')}` :\n `received value of type \\`${is(value)}\\``;\n throw new TypeError(`Expected value which is \\`${description}\\`, ${valuesMessage}.`);\n }\n};\nexports.assert = {\n // Unknowns.\n undefined: (value) => assertType(is.undefined(value), 'undefined', value),\n string: (value) => assertType(is.string(value), 'string', value),\n number: (value) => assertType(is.number(value), 'number', value),\n bigint: (value) => assertType(is.bigint(value), 'bigint', value),\n // eslint-disable-next-line @typescript-eslint/ban-types\n function_: (value) => assertType(is.function_(value), 'Function', value),\n null_: (value) => assertType(is.null_(value), 'null', value),\n class_: (value) => assertType(is.class_(value), \"Class\" /* class_ */, value),\n boolean: (value) => assertType(is.boolean(value), 'boolean', value),\n symbol: (value) => assertType(is.symbol(value), 'symbol', value),\n numericString: (value) => assertType(is.numericString(value), \"string with a number\" /* numericString */, value),\n array: (value, assertion) => {\n const assert = assertType;\n assert(is.array(value), 'Array', value);\n if (assertion) {\n value.forEach(assertion);\n }\n },\n buffer: (value) => assertType(is.buffer(value), 'Buffer', value),\n nullOrUndefined: (value) => assertType(is.nullOrUndefined(value), \"null or undefined\" /* nullOrUndefined */, value),\n object: (value) => assertType(is.object(value), 'Object', value),\n iterable: (value) => assertType(is.iterable(value), \"Iterable\" /* iterable */, value),\n asyncIterable: (value) => assertType(is.asyncIterable(value), \"AsyncIterable\" /* asyncIterable */, value),\n generator: (value) => assertType(is.generator(value), 'Generator', value),\n asyncGenerator: (value) => assertType(is.asyncGenerator(value), 'AsyncGenerator', value),\n nativePromise: (value) => assertType(is.nativePromise(value), \"native Promise\" /* nativePromise */, value),\n promise: (value) => assertType(is.promise(value), 'Promise', value),\n generatorFunction: (value) => assertType(is.generatorFunction(value), 'GeneratorFunction', value),\n asyncGeneratorFunction: (value) => assertType(is.asyncGeneratorFunction(value), 'AsyncGeneratorFunction', value),\n // eslint-disable-next-line @typescript-eslint/ban-types\n asyncFunction: (value) => assertType(is.asyncFunction(value), 'AsyncFunction', value),\n // eslint-disable-next-line @typescript-eslint/ban-types\n boundFunction: (value) => assertType(is.boundFunction(value), 'Function', value),\n regExp: (value) => assertType(is.regExp(value), 'RegExp', value),\n date: (value) => assertType(is.date(value), 'Date', value),\n error: (value) => assertType(is.error(value), 'Error', value),\n map: (value) => assertType(is.map(value), 'Map', value),\n set: (value) => assertType(is.set(value), 'Set', value),\n weakMap: (value) => assertType(is.weakMap(value), 'WeakMap', value),\n weakSet: (value) => assertType(is.weakSet(value), 'WeakSet', value),\n int8Array: (value) => assertType(is.int8Array(value), 'Int8Array', value),\n uint8Array: (value) => assertType(is.uint8Array(value), 'Uint8Array', value),\n uint8ClampedArray: (value) => assertType(is.uint8ClampedArray(value), 'Uint8ClampedArray', value),\n int16Array: (value) => assertType(is.int16Array(value), 'Int16Array', value),\n uint16Array: (value) => assertType(is.uint16Array(value), 'Uint16Array', value),\n int32Array: (value) => assertType(is.int32Array(value), 'Int32Array', value),\n uint32Array: (value) => assertType(is.uint32Array(value), 'Uint32Array', value),\n float32Array: (value) => assertType(is.float32Array(value), 'Float32Array', value),\n float64Array: (value) => assertType(is.float64Array(value), 'Float64Array', value),\n bigInt64Array: (value) => assertType(is.bigInt64Array(value), 'BigInt64Array', value),\n bigUint64Array: (value) => assertType(is.bigUint64Array(value), 'BigUint64Array', value),\n arrayBuffer: (value) => assertType(is.arrayBuffer(value), 'ArrayBuffer', value),\n sharedArrayBuffer: (value) => assertType(is.sharedArrayBuffer(value), 'SharedArrayBuffer', value),\n dataView: (value) => assertType(is.dataView(value), 'DataView', value),\n urlInstance: (value) => assertType(is.urlInstance(value), 'URL', value),\n urlString: (value) => assertType(is.urlString(value), \"string with a URL\" /* urlString */, value),\n truthy: (value) => assertType(is.truthy(value), \"truthy\" /* truthy */, value),\n falsy: (value) => assertType(is.falsy(value), \"falsy\" /* falsy */, value),\n nan: (value) => assertType(is.nan(value), \"NaN\" /* nan */, value),\n primitive: (value) => assertType(is.primitive(value), \"primitive\" /* primitive */, value),\n integer: (value) => assertType(is.integer(value), \"integer\" /* integer */, value),\n safeInteger: (value) => assertType(is.safeInteger(value), \"integer\" /* safeInteger */, value),\n plainObject: (value) => assertType(is.plainObject(value), \"plain object\" /* plainObject */, value),\n typedArray: (value) => assertType(is.typedArray(value), \"TypedArray\" /* typedArray */, value),\n arrayLike: (value) => assertType(is.arrayLike(value), \"array-like\" /* arrayLike */, value),\n domElement: (value) => assertType(is.domElement(value), \"HTMLElement\" /* domElement */, value),\n observable: (value) => assertType(is.observable(value), 'Observable', value),\n nodeStream: (value) => assertType(is.nodeStream(value), \"Node.js Stream\" /* nodeStream */, value),\n infinite: (value) => assertType(is.infinite(value), \"infinite number\" /* infinite */, value),\n emptyArray: (value) => assertType(is.emptyArray(value), \"empty array\" /* emptyArray */, value),\n nonEmptyArray: (value) => assertType(is.nonEmptyArray(value), \"non-empty array\" /* nonEmptyArray */, value),\n emptyString: (value) => assertType(is.emptyString(value), \"empty string\" /* emptyString */, value),\n nonEmptyString: (value) => assertType(is.nonEmptyString(value), \"non-empty string\" /* nonEmptyString */, value),\n emptyStringOrWhitespace: (value) => assertType(is.emptyStringOrWhitespace(value), \"empty string or whitespace\" /* emptyStringOrWhitespace */, value),\n emptyObject: (value) => assertType(is.emptyObject(value), \"empty object\" /* emptyObject */, value),\n nonEmptyObject: (value) => assertType(is.nonEmptyObject(value), \"non-empty object\" /* nonEmptyObject */, value),\n emptySet: (value) => assertType(is.emptySet(value), \"empty set\" /* emptySet */, value),\n nonEmptySet: (value) => assertType(is.nonEmptySet(value), \"non-empty set\" /* nonEmptySet */, value),\n emptyMap: (value) => assertType(is.emptyMap(value), \"empty map\" /* emptyMap */, value),\n nonEmptyMap: (value) => assertType(is.nonEmptyMap(value), \"non-empty map\" /* nonEmptyMap */, value),\n propertyKey: (value) => assertType(is.propertyKey(value), 'PropertyKey', value),\n formData: (value) => assertType(is.formData(value), 'FormData', value),\n urlSearchParams: (value) => assertType(is.urlSearchParams(value), 'URLSearchParams', value),\n // Numbers.\n evenInteger: (value) => assertType(is.evenInteger(value), \"even integer\" /* evenInteger */, value),\n oddInteger: (value) => assertType(is.oddInteger(value), \"odd integer\" /* oddInteger */, value),\n // Two arguments.\n directInstanceOf: (instance, class_) => assertType(is.directInstanceOf(instance, class_), \"T\" /* directInstanceOf */, instance),\n inRange: (value, range) => assertType(is.inRange(value, range), \"in range\" /* inRange */, value),\n // Variadic functions.\n any: (predicate, ...values) => {\n return assertType(is.any(predicate, ...values), \"predicate returns truthy for any value\" /* any */, values, { multipleValues: true });\n },\n all: (predicate, ...values) => assertType(is.all(predicate, ...values), \"predicate returns truthy for all values\" /* all */, values, { multipleValues: true })\n};\n// Some few keywords are reserved, but we'll populate them for Node.js users\n// See https://github.com/Microsoft/TypeScript/issues/2536\nObject.defineProperties(is, {\n class: {\n value: is.class_\n },\n function: {\n value: is.function_\n },\n null: {\n value: is.null_\n }\n});\nObject.defineProperties(exports.assert, {\n class: {\n value: exports.assert.class_\n },\n function: {\n value: exports.assert.function_\n },\n null: {\n value: exports.assert.null_\n }\n});\nexports.default = is;\n// For CommonJS default export support\nmodule.exports = is;\nmodule.exports.default = is;\nmodule.exports.assert = exports.assert;\n", "'use strict';\n\nclass CancelError extends Error {\n\tconstructor(reason) {\n\t\tsuper(reason || 'Promise was canceled');\n\t\tthis.name = 'CancelError';\n\t}\n\n\tget isCanceled() {\n\t\treturn true;\n\t}\n}\n\nclass PCancelable {\n\tstatic fn(userFn) {\n\t\treturn (...arguments_) => {\n\t\t\treturn new PCancelable((resolve, reject, onCancel) => {\n\t\t\t\targuments_.push(onCancel);\n\t\t\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\t\t\tuserFn(...arguments_).then(resolve, reject);\n\t\t\t});\n\t\t};\n\t}\n\n\tconstructor(executor) {\n\t\tthis._cancelHandlers = [];\n\t\tthis._isPending = true;\n\t\tthis._isCanceled = false;\n\t\tthis._rejectOnCancel = true;\n\n\t\tthis._promise = new Promise((resolve, reject) => {\n\t\t\tthis._reject = reject;\n\n\t\t\tconst onResolve = value => {\n\t\t\t\tif (!this._isCanceled || !onCancel.shouldReject) {\n\t\t\t\t\tthis._isPending = false;\n\t\t\t\t\tresolve(value);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst onReject = error => {\n\t\t\t\tthis._isPending = false;\n\t\t\t\treject(error);\n\t\t\t};\n\n\t\t\tconst onCancel = handler => {\n\t\t\t\tif (!this._isPending) {\n\t\t\t\t\tthrow new Error('The `onCancel` handler was attached after the promise settled.');\n\t\t\t\t}\n\n\t\t\t\tthis._cancelHandlers.push(handler);\n\t\t\t};\n\n\t\t\tObject.defineProperties(onCancel, {\n\t\t\t\tshouldReject: {\n\t\t\t\t\tget: () => this._rejectOnCancel,\n\t\t\t\t\tset: boolean => {\n\t\t\t\t\t\tthis._rejectOnCancel = boolean;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn executor(onResolve, onReject, onCancel);\n\t\t});\n\t}\n\n\tthen(onFulfilled, onRejected) {\n\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\treturn this._promise.then(onFulfilled, onRejected);\n\t}\n\n\tcatch(onRejected) {\n\t\treturn this._promise.catch(onRejected);\n\t}\n\n\tfinally(onFinally) {\n\t\treturn this._promise.finally(onFinally);\n\t}\n\n\tcancel(reason) {\n\t\tif (!this._isPending || this._isCanceled) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._isCanceled = true;\n\n\t\tif (this._cancelHandlers.length > 0) {\n\t\t\ttry {\n\t\t\t\tfor (const handler of this._cancelHandlers) {\n\t\t\t\t\thandler();\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthis._reject(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (this._rejectOnCancel) {\n\t\t\tthis._reject(new CancelError(reason));\n\t\t}\n\t}\n\n\tget isCanceled() {\n\t\treturn this._isCanceled;\n\t}\n}\n\nObject.setPrototypeOf(PCancelable.prototype, Promise.prototype);\n\nmodule.exports = PCancelable;\nmodule.exports.CancelError = CancelError;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction isTLSSocket(socket) {\n return socket.encrypted;\n}\nconst deferToConnect = (socket, fn) => {\n let listeners;\n if (typeof fn === 'function') {\n const connect = fn;\n listeners = { connect };\n }\n else {\n listeners = fn;\n }\n const hasConnectListener = typeof listeners.connect === 'function';\n const hasSecureConnectListener = typeof listeners.secureConnect === 'function';\n const hasCloseListener = typeof listeners.close === 'function';\n const onConnect = () => {\n if (hasConnectListener) {\n listeners.connect();\n }\n if (isTLSSocket(socket) && hasSecureConnectListener) {\n if (socket.authorized) {\n listeners.secureConnect();\n }\n else if (!socket.authorizationError) {\n socket.once('secureConnect', listeners.secureConnect);\n }\n }\n if (hasCloseListener) {\n socket.once('close', listeners.close);\n }\n };\n if (socket.writable && !socket.connecting) {\n onConnect();\n }\n else if (socket.connecting) {\n socket.once('connect', onConnect);\n }\n else if (socket.destroyed && hasCloseListener) {\n listeners.close(socket._hadError);\n }\n};\nexports.default = deferToConnect;\n// For CommonJS default export support\nmodule.exports = deferToConnect;\nmodule.exports.default = deferToConnect;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst defer_to_connect_1 = require(\"defer-to-connect\");\nconst util_1 = require(\"util\");\nconst nodejsMajorVersion = Number(process.versions.node.split('.')[0]);\nconst timer = (request) => {\n if (request.timings) {\n return request.timings;\n }\n const timings = {\n start: Date.now(),\n socket: undefined,\n lookup: undefined,\n connect: undefined,\n secureConnect: undefined,\n upload: undefined,\n response: undefined,\n end: undefined,\n error: undefined,\n abort: undefined,\n phases: {\n wait: undefined,\n dns: undefined,\n tcp: undefined,\n tls: undefined,\n request: undefined,\n firstByte: undefined,\n download: undefined,\n total: undefined\n }\n };\n request.timings = timings;\n const handleError = (origin) => {\n const emit = origin.emit.bind(origin);\n origin.emit = (event, ...args) => {\n // Catches the `error` event\n if (event === 'error') {\n timings.error = Date.now();\n timings.phases.total = timings.error - timings.start;\n origin.emit = emit;\n }\n // Saves the original behavior\n return emit(event, ...args);\n };\n };\n handleError(request);\n const onAbort = () => {\n timings.abort = Date.now();\n // Let the `end` response event be responsible for setting the total phase,\n // unless the Node.js major version is >= 13.\n if (!timings.response || nodejsMajorVersion >= 13) {\n timings.phases.total = Date.now() - timings.start;\n }\n };\n request.prependOnceListener('abort', onAbort);\n const onSocket = (socket) => {\n timings.socket = Date.now();\n timings.phases.wait = timings.socket - timings.start;\n if (util_1.types.isProxy(socket)) {\n return;\n }\n const lookupListener = () => {\n timings.lookup = Date.now();\n timings.phases.dns = timings.lookup - timings.socket;\n };\n socket.prependOnceListener('lookup', lookupListener);\n defer_to_connect_1.default(socket, {\n connect: () => {\n timings.connect = Date.now();\n if (timings.lookup === undefined) {\n socket.removeListener('lookup', lookupListener);\n timings.lookup = timings.connect;\n timings.phases.dns = timings.lookup - timings.socket;\n }\n timings.phases.tcp = timings.connect - timings.lookup;\n // This callback is called before flushing any data,\n // so we don't need to set `timings.phases.request` here.\n },\n secureConnect: () => {\n timings.secureConnect = Date.now();\n timings.phases.tls = timings.secureConnect - timings.connect;\n }\n });\n };\n if (request.socket) {\n onSocket(request.socket);\n }\n else {\n request.prependOnceListener('socket', onSocket);\n }\n const onUpload = () => {\n var _a;\n timings.upload = Date.now();\n timings.phases.request = timings.upload - ((_a = timings.secureConnect) !== null && _a !== void 0 ? _a : timings.connect);\n };\n const writableFinished = () => {\n if (typeof request.writableFinished === 'boolean') {\n return request.writableFinished;\n }\n // Node.js doesn't have `request.writableFinished` property\n return request.finished && request.outputSize === 0 && (!request.socket || request.socket.writableLength === 0);\n };\n if (writableFinished()) {\n onUpload();\n }\n else {\n request.prependOnceListener('finish', onUpload);\n }\n request.prependOnceListener('response', (response) => {\n timings.response = Date.now();\n timings.phases.firstByte = timings.response - timings.upload;\n response.timings = timings;\n handleError(response);\n response.prependOnceListener('end', () => {\n timings.end = Date.now();\n timings.phases.download = timings.end - timings.response;\n timings.phases.total = timings.end - timings.start;\n });\n response.prependOnceListener('aborted', onAbort);\n });\n return timings;\n};\nexports.default = timer;\n// For CommonJS default export support\nmodule.exports = timer;\nmodule.exports.default = timer;\n", "'use strict';\nconst {\n\tV4MAPPED,\n\tADDRCONFIG,\n\tALL,\n\tpromises: {\n\t\tResolver: AsyncResolver\n\t},\n\tlookup: dnsLookup\n} = require('dns');\nconst {promisify} = require('util');\nconst os = require('os');\n\nconst kCacheableLookupCreateConnection = Symbol('cacheableLookupCreateConnection');\nconst kCacheableLookupInstance = Symbol('cacheableLookupInstance');\nconst kExpires = Symbol('expires');\n\nconst supportsALL = typeof ALL === 'number';\n\nconst verifyAgent = agent => {\n\tif (!(agent && typeof agent.createConnection === 'function')) {\n\t\tthrow new Error('Expected an Agent instance as the first argument');\n\t}\n};\n\nconst map4to6 = entries => {\n\tfor (const entry of entries) {\n\t\tif (entry.family === 6) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tentry.address = `::ffff:${entry.address}`;\n\t\tentry.family = 6;\n\t}\n};\n\nconst getIfaceInfo = () => {\n\tlet has4 = false;\n\tlet has6 = false;\n\n\tfor (const device of Object.values(os.networkInterfaces())) {\n\t\tfor (const iface of device) {\n\t\t\tif (iface.internal) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (iface.family === 'IPv6') {\n\t\t\t\thas6 = true;\n\t\t\t} else {\n\t\t\t\thas4 = true;\n\t\t\t}\n\n\t\t\tif (has4 && has6) {\n\t\t\t\treturn {has4, has6};\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {has4, has6};\n};\n\nconst isIterable = map => {\n\treturn Symbol.iterator in map;\n};\n\nconst ttl = {ttl: true};\nconst all = {all: true};\n\nclass CacheableLookup {\n\tconstructor({\n\t\tcache = new Map(),\n\t\tmaxTtl = Infinity,\n\t\tfallbackDuration = 3600,\n\t\terrorTtl = 0.15,\n\t\tresolver = new AsyncResolver(),\n\t\tlookup = dnsLookup\n\t} = {}) {\n\t\tthis.maxTtl = maxTtl;\n\t\tthis.errorTtl = errorTtl;\n\n\t\tthis._cache = cache;\n\t\tthis._resolver = resolver;\n\t\tthis._dnsLookup = promisify(lookup);\n\n\t\tif (this._resolver instanceof AsyncResolver) {\n\t\t\tthis._resolve4 = this._resolver.resolve4.bind(this._resolver);\n\t\t\tthis._resolve6 = this._resolver.resolve6.bind(this._resolver);\n\t\t} else {\n\t\t\tthis._resolve4 = promisify(this._resolver.resolve4.bind(this._resolver));\n\t\t\tthis._resolve6 = promisify(this._resolver.resolve6.bind(this._resolver));\n\t\t}\n\n\t\tthis._iface = getIfaceInfo();\n\n\t\tthis._pending = {};\n\t\tthis._nextRemovalTime = false;\n\t\tthis._hostnamesToFallback = new Set();\n\n\t\tif (fallbackDuration < 1) {\n\t\t\tthis._fallback = false;\n\t\t} else {\n\t\t\tthis._fallback = true;\n\n\t\t\tconst interval = setInterval(() => {\n\t\t\t\tthis._hostnamesToFallback.clear();\n\t\t\t}, fallbackDuration * 1000);\n\n\t\t\t/* istanbul ignore next: There is no `interval.unref()` when running inside an Electron renderer */\n\t\t\tif (interval.unref) {\n\t\t\t\tinterval.unref();\n\t\t\t}\n\t\t}\n\n\t\tthis.lookup = this.lookup.bind(this);\n\t\tthis.lookupAsync = this.lookupAsync.bind(this);\n\t}\n\n\tset servers(servers) {\n\t\tthis.clear();\n\n\t\tthis._resolver.setServers(servers);\n\t}\n\n\tget servers() {\n\t\treturn this._resolver.getServers();\n\t}\n\n\tlookup(hostname, options, callback) {\n\t\tif (typeof options === 'function') {\n\t\t\tcallback = options;\n\t\t\toptions = {};\n\t\t} else if (typeof options === 'number') {\n\t\t\toptions = {\n\t\t\t\tfamily: options\n\t\t\t};\n\t\t}\n\n\t\tif (!callback) {\n\t\t\tthrow new Error('Callback must be a function.');\n\t\t}\n\n\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\tthis.lookupAsync(hostname, options).then(result => {\n\t\t\tif (options.all) {\n\t\t\t\tcallback(null, result);\n\t\t\t} else {\n\t\t\t\tcallback(null, result.address, result.family, result.expires, result.ttl);\n\t\t\t}\n\t\t}, callback);\n\t}\n\n\tasync lookupAsync(hostname, options = {}) {\n\t\tif (typeof options === 'number') {\n\t\t\toptions = {\n\t\t\t\tfamily: options\n\t\t\t};\n\t\t}\n\n\t\tlet cached = await this.query(hostname);\n\n\t\tif (options.family === 6) {\n\t\t\tconst filtered = cached.filter(entry => entry.family === 6);\n\n\t\t\tif (options.hints & V4MAPPED) {\n\t\t\t\tif ((supportsALL && options.hints & ALL) || filtered.length === 0) {\n\t\t\t\t\tmap4to6(cached);\n\t\t\t\t} else {\n\t\t\t\t\tcached = filtered;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcached = filtered;\n\t\t\t}\n\t\t} else if (options.family === 4) {\n\t\t\tcached = cached.filter(entry => entry.family === 4);\n\t\t}\n\n\t\tif (options.hints & ADDRCONFIG) {\n\t\t\tconst {_iface} = this;\n\t\t\tcached = cached.filter(entry => entry.family === 6 ? _iface.has6 : _iface.has4);\n\t\t}\n\n\t\tif (cached.length === 0) {\n\t\t\tconst error = new Error(`cacheableLookup ENOTFOUND ${hostname}`);\n\t\t\terror.code = 'ENOTFOUND';\n\t\t\terror.hostname = hostname;\n\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (options.all) {\n\t\t\treturn cached;\n\t\t}\n\n\t\treturn cached[0];\n\t}\n\n\tasync query(hostname) {\n\t\tlet cached = await this._cache.get(hostname);\n\n\t\tif (!cached) {\n\t\t\tconst pending = this._pending[hostname];\n\n\t\t\tif (pending) {\n\t\t\t\tcached = await pending;\n\t\t\t} else {\n\t\t\t\tconst newPromise = this.queryAndCache(hostname);\n\t\t\t\tthis._pending[hostname] = newPromise;\n\n\t\t\t\ttry {\n\t\t\t\t\tcached = await newPromise;\n\t\t\t\t} finally {\n\t\t\t\t\tdelete this._pending[hostname];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tcached = cached.map(entry => {\n\t\t\treturn {...entry};\n\t\t});\n\n\t\treturn cached;\n\t}\n\n\tasync _resolve(hostname) {\n\t\tconst wrap = async promise => {\n\t\t\ttry {\n\t\t\t\treturn await promise;\n\t\t\t} catch (error) {\n\t\t\t\tif (error.code === 'ENODATA' || error.code === 'ENOTFOUND') {\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t};\n\n\t\t// ANY is unsafe as it doesn't trigger new queries in the underlying server.\n\t\tconst [A, AAAA] = await Promise.all([\n\t\t\tthis._resolve4(hostname, ttl),\n\t\t\tthis._resolve6(hostname, ttl)\n\t\t].map(promise => wrap(promise)));\n\n\t\tlet aTtl = 0;\n\t\tlet aaaaTtl = 0;\n\t\tlet cacheTtl = 0;\n\n\t\tconst now = Date.now();\n\n\t\tfor (const entry of A) {\n\t\t\tentry.family = 4;\n\t\t\tentry.expires = now + (entry.ttl * 1000);\n\n\t\t\taTtl = Math.max(aTtl, entry.ttl);\n\t\t}\n\n\t\tfor (const entry of AAAA) {\n\t\t\tentry.family = 6;\n\t\t\tentry.expires = now + (entry.ttl * 1000);\n\n\t\t\taaaaTtl = Math.max(aaaaTtl, entry.ttl);\n\t\t}\n\n\t\tif (A.length > 0) {\n\t\t\tif (AAAA.length > 0) {\n\t\t\t\tcacheTtl = Math.min(aTtl, aaaaTtl);\n\t\t\t} else {\n\t\t\t\tcacheTtl = aTtl;\n\t\t\t}\n\t\t} else {\n\t\t\tcacheTtl = aaaaTtl;\n\t\t}\n\n\t\treturn {\n\t\t\tentries: [\n\t\t\t\t...A,\n\t\t\t\t...AAAA\n\t\t\t],\n\t\t\tcacheTtl\n\t\t};\n\t}\n\n\tasync _lookup(hostname) {\n\t\ttry {\n\t\t\tconst entries = await this._dnsLookup(hostname, {\n\t\t\t\tall: true\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\tentries,\n\t\t\t\tcacheTtl: 0\n\t\t\t};\n\t\t} catch (_) {\n\t\t\treturn {\n\t\t\t\tentries: [],\n\t\t\t\tcacheTtl: 0\n\t\t\t};\n\t\t}\n\t}\n\n\tasync _set(hostname, data, cacheTtl) {\n\t\tif (this.maxTtl > 0 && cacheTtl > 0) {\n\t\t\tcacheTtl = Math.min(cacheTtl, this.maxTtl) * 1000;\n\t\t\tdata[kExpires] = Date.now() + cacheTtl;\n\n\t\t\ttry {\n\t\t\t\tawait this._cache.set(hostname, data, cacheTtl);\n\t\t\t} catch (error) {\n\t\t\t\tthis.lookupAsync = async () => {\n\t\t\t\t\tconst cacheError = new Error('Cache Error. Please recreate the CacheableLookup instance.');\n\t\t\t\t\tcacheError.cause = error;\n\n\t\t\t\t\tthrow cacheError;\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (isIterable(this._cache)) {\n\t\t\t\tthis._tick(cacheTtl);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync queryAndCache(hostname) {\n\t\tif (this._hostnamesToFallback.has(hostname)) {\n\t\t\treturn this._dnsLookup(hostname, all);\n\t\t}\n\n\t\tlet query = await this._resolve(hostname);\n\n\t\tif (query.entries.length === 0 && this._fallback) {\n\t\t\tquery = await this._lookup(hostname);\n\n\t\t\tif (query.entries.length !== 0) {\n\t\t\t\t// Use `dns.lookup(...)` for that particular hostname\n\t\t\t\tthis._hostnamesToFallback.add(hostname);\n\t\t\t}\n\t\t}\n\n\t\tconst cacheTtl = query.entries.length === 0 ? this.errorTtl : query.cacheTtl;\n\t\tawait this._set(hostname, query.entries, cacheTtl);\n\n\t\treturn query.entries;\n\t}\n\n\t_tick(ms) {\n\t\tconst nextRemovalTime = this._nextRemovalTime;\n\n\t\tif (!nextRemovalTime || ms < nextRemovalTime) {\n\t\t\tclearTimeout(this._removalTimeout);\n\n\t\t\tthis._nextRemovalTime = ms;\n\n\t\t\tthis._removalTimeout = setTimeout(() => {\n\t\t\t\tthis._nextRemovalTime = false;\n\n\t\t\t\tlet nextExpiry = Infinity;\n\n\t\t\t\tconst now = Date.now();\n\n\t\t\t\tfor (const [hostname, entries] of this._cache) {\n\t\t\t\t\tconst expires = entries[kExpires];\n\n\t\t\t\t\tif (now >= expires) {\n\t\t\t\t\t\tthis._cache.delete(hostname);\n\t\t\t\t\t} else if (expires < nextExpiry) {\n\t\t\t\t\t\tnextExpiry = expires;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (nextExpiry !== Infinity) {\n\t\t\t\t\tthis._tick(nextExpiry - now);\n\t\t\t\t}\n\t\t\t}, ms);\n\n\t\t\t/* istanbul ignore next: There is no `timeout.unref()` when running inside an Electron renderer */\n\t\t\tif (this._removalTimeout.unref) {\n\t\t\t\tthis._removalTimeout.unref();\n\t\t\t}\n\t\t}\n\t}\n\n\tinstall(agent) {\n\t\tverifyAgent(agent);\n\n\t\tif (kCacheableLookupCreateConnection in agent) {\n\t\t\tthrow new Error('CacheableLookup has been already installed');\n\t\t}\n\n\t\tagent[kCacheableLookupCreateConnection] = agent.createConnection;\n\t\tagent[kCacheableLookupInstance] = this;\n\n\t\tagent.createConnection = (options, callback) => {\n\t\t\tif (!('lookup' in options)) {\n\t\t\t\toptions.lookup = this.lookup;\n\t\t\t}\n\n\t\t\treturn agent[kCacheableLookupCreateConnection](options, callback);\n\t\t};\n\t}\n\n\tuninstall(agent) {\n\t\tverifyAgent(agent);\n\n\t\tif (agent[kCacheableLookupCreateConnection]) {\n\t\t\tif (agent[kCacheableLookupInstance] !== this) {\n\t\t\t\tthrow new Error('The agent is not owned by this CacheableLookup instance');\n\t\t\t}\n\n\t\t\tagent.createConnection = agent[kCacheableLookupCreateConnection];\n\n\t\t\tdelete agent[kCacheableLookupCreateConnection];\n\t\t\tdelete agent[kCacheableLookupInstance];\n\t\t}\n\t}\n\n\tupdateInterfaceInfo() {\n\t\tconst {_iface} = this;\n\n\t\tthis._iface = getIfaceInfo();\n\n\t\tif ((_iface.has4 && !this._iface.has4) || (_iface.has6 && !this._iface.has6)) {\n\t\t\tthis._cache.clear();\n\t\t}\n\t}\n\n\tclear(hostname) {\n\t\tif (hostname) {\n\t\t\tthis._cache.delete(hostname);\n\t\t\treturn;\n\t\t}\n\n\t\tthis._cache.clear();\n\t}\n}\n\nmodule.exports = CacheableLookup;\nmodule.exports.default = CacheableLookup;\n", "'use strict';\n\n// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs\nconst DATA_URL_DEFAULT_MIME_TYPE = 'text/plain';\nconst DATA_URL_DEFAULT_CHARSET = 'us-ascii';\n\nconst testParameter = (name, filters) => {\n\treturn filters.some(filter => filter instanceof RegExp ? filter.test(name) : filter === name);\n};\n\nconst normalizeDataURL = (urlString, {stripHash}) => {\n\tconst match = /^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(urlString);\n\n\tif (!match) {\n\t\tthrow new Error(`Invalid URL: ${urlString}`);\n\t}\n\n\tlet {type, data, hash} = match.groups;\n\tconst mediaType = type.split(';');\n\thash = stripHash ? '' : hash;\n\n\tlet isBase64 = false;\n\tif (mediaType[mediaType.length - 1] === 'base64') {\n\t\tmediaType.pop();\n\t\tisBase64 = true;\n\t}\n\n\t// Lowercase MIME type\n\tconst mimeType = (mediaType.shift() || '').toLowerCase();\n\tconst attributes = mediaType\n\t\t.map(attribute => {\n\t\t\tlet [key, value = ''] = attribute.split('=').map(string => string.trim());\n\n\t\t\t// Lowercase `charset`\n\t\t\tif (key === 'charset') {\n\t\t\t\tvalue = value.toLowerCase();\n\n\t\t\t\tif (value === DATA_URL_DEFAULT_CHARSET) {\n\t\t\t\t\treturn '';\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn `${key}${value ? `=${value}` : ''}`;\n\t\t})\n\t\t.filter(Boolean);\n\n\tconst normalizedMediaType = [\n\t\t...attributes\n\t];\n\n\tif (isBase64) {\n\t\tnormalizedMediaType.push('base64');\n\t}\n\n\tif (normalizedMediaType.length !== 0 || (mimeType && mimeType !== DATA_URL_DEFAULT_MIME_TYPE)) {\n\t\tnormalizedMediaType.unshift(mimeType);\n\t}\n\n\treturn `data:${normalizedMediaType.join(';')},${isBase64 ? data.trim() : data}${hash ? `#${hash}` : ''}`;\n};\n\nconst normalizeUrl = (urlString, options) => {\n\toptions = {\n\t\tdefaultProtocol: 'http:',\n\t\tnormalizeProtocol: true,\n\t\tforceHttp: false,\n\t\tforceHttps: false,\n\t\tstripAuthentication: true,\n\t\tstripHash: false,\n\t\tstripTextFragment: true,\n\t\tstripWWW: true,\n\t\tremoveQueryParameters: [/^utm_\\w+/i],\n\t\tremoveTrailingSlash: true,\n\t\tremoveSingleSlash: true,\n\t\tremoveDirectoryIndex: false,\n\t\tsortQueryParameters: true,\n\t\t...options\n\t};\n\n\turlString = urlString.trim();\n\n\t// Data URL\n\tif (/^data:/i.test(urlString)) {\n\t\treturn normalizeDataURL(urlString, options);\n\t}\n\n\tif (/^view-source:/i.test(urlString)) {\n\t\tthrow new Error('`view-source:` is not supported as it is a non-standard protocol');\n\t}\n\n\tconst hasRelativeProtocol = urlString.startsWith('//');\n\tconst isRelativeUrl = !hasRelativeProtocol && /^\\.*\\//.test(urlString);\n\n\t// Prepend protocol\n\tif (!isRelativeUrl) {\n\t\turlString = urlString.replace(/^(?!(?:\\w+:)?\\/\\/)|^\\/\\//, options.defaultProtocol);\n\t}\n\n\tconst urlObj = new URL(urlString);\n\n\tif (options.forceHttp && options.forceHttps) {\n\t\tthrow new Error('The `forceHttp` and `forceHttps` options cannot be used together');\n\t}\n\n\tif (options.forceHttp && urlObj.protocol === 'https:') {\n\t\turlObj.protocol = 'http:';\n\t}\n\n\tif (options.forceHttps && urlObj.protocol === 'http:') {\n\t\turlObj.protocol = 'https:';\n\t}\n\n\t// Remove auth\n\tif (options.stripAuthentication) {\n\t\turlObj.username = '';\n\t\turlObj.password = '';\n\t}\n\n\t// Remove hash\n\tif (options.stripHash) {\n\t\turlObj.hash = '';\n\t} else if (options.stripTextFragment) {\n\t\turlObj.hash = urlObj.hash.replace(/#?:~:text.*?$/i, '');\n\t}\n\n\t// Remove duplicate slashes if not preceded by a protocol\n\tif (urlObj.pathname) {\n\t\turlObj.pathname = urlObj.pathname.replace(/(?<!\\b(?:[a-z][a-z\\d+\\-.]{1,50}:))\\/{2,}/g, '/');\n\t}\n\n\t// Decode URI octets\n\tif (urlObj.pathname) {\n\t\ttry {\n\t\t\turlObj.pathname = decodeURI(urlObj.pathname);\n\t\t} catch (_) {}\n\t}\n\n\t// Remove directory index\n\tif (options.removeDirectoryIndex === true) {\n\t\toptions.removeDirectoryIndex = [/^index\\.[a-z]+$/];\n\t}\n\n\tif (Array.isArray(options.removeDirectoryIndex) && options.removeDirectoryIndex.length > 0) {\n\t\tlet pathComponents = urlObj.pathname.split('/');\n\t\tconst lastComponent = pathComponents[pathComponents.length - 1];\n\n\t\tif (testParameter(lastComponent, options.removeDirectoryIndex)) {\n\t\t\tpathComponents = pathComponents.slice(0, pathComponents.length - 1);\n\t\t\turlObj.pathname = pathComponents.slice(1).join('/') + '/';\n\t\t}\n\t}\n\n\tif (urlObj.hostname) {\n\t\t// Remove trailing dot\n\t\turlObj.hostname = urlObj.hostname.replace(/\\.$/, '');\n\n\t\t// Remove `www.`\n\t\tif (options.stripWWW && /^www\\.(?!www\\.)(?:[a-z\\-\\d]{1,63})\\.(?:[a-z.\\-\\d]{2,63})$/.test(urlObj.hostname)) {\n\t\t\t// Each label should be max 63 at length (min: 1).\n\t\t\t// Source: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names\n\t\t\t// Each TLD should be up to 63 characters long (min: 2).\n\t\t\t// It is technically possible to have a single character TLD, but none currently exist.\n\t\t\turlObj.hostname = urlObj.hostname.replace(/^www\\./, '');\n\t\t}\n\t}\n\n\t// Remove query unwanted parameters\n\tif (Array.isArray(options.removeQueryParameters)) {\n\t\tfor (const key of [...urlObj.searchParams.keys()]) {\n\t\t\tif (testParameter(key, options.removeQueryParameters)) {\n\t\t\t\turlObj.searchParams.delete(key);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (options.removeQueryParameters === true) {\n\t\turlObj.search = '';\n\t}\n\n\t// Sort query parameters\n\tif (options.sortQueryParameters) {\n\t\turlObj.searchParams.sort();\n\t}\n\n\tif (options.removeTrailingSlash) {\n\t\turlObj.pathname = urlObj.pathname.replace(/\\/$/, '');\n\t}\n\n\tconst oldUrlString = urlString;\n\n\t// Take advantage of many of the Node `url` normalizations\n\turlString = urlObj.toString();\n\n\tif (!options.removeSingleSlash && urlObj.pathname === '/' && !oldUrlString.endsWith('/') && urlObj.hash === '') {\n\t\turlString = urlString.replace(/\\/$/, '');\n\t}\n\n\t// Remove ending `/` unless removeSingleSlash is false\n\tif ((options.removeTrailingSlash || urlObj.pathname === '/') && urlObj.hash === '' && options.removeSingleSlash) {\n\t\turlString = urlString.replace(/\\/$/, '');\n\t}\n\n\t// Restore relative protocol, if applicable\n\tif (hasRelativeProtocol && !options.normalizeProtocol) {\n\t\turlString = urlString.replace(/^http:\\/\\//, '//');\n\t}\n\n\t// Remove http/https\n\tif (options.stripProtocol) {\n\t\turlString = urlString.replace(/^(?:https?:)?\\/\\//, '');\n\t}\n\n\treturn urlString;\n};\n\nmodule.exports = normalizeUrl;\n", "// Returns a wrapper function that returns a wrapped callback\n// The wrapper function should do some stuff, and return a\n// presumably different callback function.\n// This makes sure that own properties are retained, so that\n// decorations and such are not lost along the way.\nmodule.exports = wrappy\nfunction wrappy (fn, cb) {\n if (fn && cb) return wrappy(fn)(cb)\n\n if (typeof fn !== 'function')\n throw new TypeError('need wrapper function')\n\n Object.keys(fn).forEach(function (k) {\n wrapper[k] = fn[k]\n })\n\n return wrapper\n\n function wrapper() {\n var args = new Array(arguments.length)\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i]\n }\n var ret = fn.apply(this, args)\n var cb = args[args.length-1]\n if (typeof ret === 'function' && ret !== cb) {\n Object.keys(cb).forEach(function (k) {\n ret[k] = cb[k]\n })\n }\n return ret\n }\n}\n", "var wrappy = require('wrappy')\nmodule.exports = wrappy(once)\nmodule.exports.strict = wrappy(onceStrict)\n\nonce.proto = once(function () {\n Object.defineProperty(Function.prototype, 'once', {\n value: function () {\n return once(this)\n },\n configurable: true\n })\n\n Object.defineProperty(Function.prototype, 'onceStrict', {\n value: function () {\n return onceStrict(this)\n },\n configurable: true\n })\n})\n\nfunction once (fn) {\n var f = function () {\n if (f.called) return f.value\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n f.called = false\n return f\n}\n\nfunction onceStrict (fn) {\n var f = function () {\n if (f.called)\n throw new Error(f.onceError)\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n var name = fn.name || 'Function wrapped with `once`'\n f.onceError = name + \" shouldn't be called more than once\"\n f.called = false\n return f\n}\n", "var once = require('once');\n\nvar noop = function() {};\n\nvar isRequest = function(stream) {\n\treturn stream.setHeader && typeof stream.abort === 'function';\n};\n\nvar isChildProcess = function(stream) {\n\treturn stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3\n};\n\nvar eos = function(stream, opts, callback) {\n\tif (typeof opts === 'function') return eos(stream, null, opts);\n\tif (!opts) opts = {};\n\n\tcallback = once(callback || noop);\n\n\tvar ws = stream._writableState;\n\tvar rs = stream._readableState;\n\tvar readable = opts.readable || (opts.readable !== false && stream.readable);\n\tvar writable = opts.writable || (opts.writable !== false && stream.writable);\n\tvar cancelled = false;\n\n\tvar onlegacyfinish = function() {\n\t\tif (!stream.writable) onfinish();\n\t};\n\n\tvar onfinish = function() {\n\t\twritable = false;\n\t\tif (!readable) callback.call(stream);\n\t};\n\n\tvar onend = function() {\n\t\treadable = false;\n\t\tif (!writable) callback.call(stream);\n\t};\n\n\tvar onexit = function(exitCode) {\n\t\tcallback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);\n\t};\n\n\tvar onerror = function(err) {\n\t\tcallback.call(stream, err);\n\t};\n\n\tvar onclose = function() {\n\t\tprocess.nextTick(onclosenexttick);\n\t};\n\n\tvar onclosenexttick = function() {\n\t\tif (cancelled) return;\n\t\tif (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close'));\n\t\tif (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close'));\n\t};\n\n\tvar onrequest = function() {\n\t\tstream.req.on('finish', onfinish);\n\t};\n\n\tif (isRequest(stream)) {\n\t\tstream.on('complete', onfinish);\n\t\tstream.on('abort', onclose);\n\t\tif (stream.req) onrequest();\n\t\telse stream.on('request', onrequest);\n\t} else if (writable && !ws) { // legacy streams\n\t\tstream.on('end', onlegacyfinish);\n\t\tstream.on('close', onlegacyfinish);\n\t}\n\n\tif (isChildProcess(stream)) stream.on('exit', onexit);\n\n\tstream.on('end', onend);\n\tstream.on('finish', onfinish);\n\tif (opts.error !== false) stream.on('error', onerror);\n\tstream.on('close', onclose);\n\n\treturn function() {\n\t\tcancelled = true;\n\t\tstream.removeListener('complete', onfinish);\n\t\tstream.removeListener('abort', onclose);\n\t\tstream.removeListener('request', onrequest);\n\t\tif (stream.req) stream.req.removeListener('finish', onfinish);\n\t\tstream.removeListener('end', onlegacyfinish);\n\t\tstream.removeListener('close', onlegacyfinish);\n\t\tstream.removeListener('finish', onfinish);\n\t\tstream.removeListener('exit', onexit);\n\t\tstream.removeListener('end', onend);\n\t\tstream.removeListener('error', onerror);\n\t\tstream.removeListener('close', onclose);\n\t};\n};\n\nmodule.exports = eos;\n", "var once = require('once')\nvar eos = require('end-of-stream')\nvar fs = require('fs') // we only need fs to get the ReadStream and WriteStream prototypes\n\nvar noop = function () {}\nvar ancient = /^v?\\.0/.test(process.version)\n\nvar isFn = function (fn) {\n return typeof fn === 'function'\n}\n\nvar isFS = function (stream) {\n if (!ancient) return false // newer node version do not need to care about fs is a special way\n if (!fs) return false // browser\n return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close)\n}\n\nvar isRequest = function (stream) {\n return stream.setHeader && isFn(stream.abort)\n}\n\nvar destroyer = function (stream, reading, writing, callback) {\n callback = once(callback)\n\n var closed = false\n stream.on('close', function () {\n closed = true\n })\n\n eos(stream, {readable: reading, writable: writing}, function (err) {\n if (err) return callback(err)\n closed = true\n callback()\n })\n\n var destroyed = false\n return function (err) {\n if (closed) return\n if (destroyed) return\n destroyed = true\n\n if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks\n if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want\n\n if (isFn(stream.destroy)) return stream.destroy()\n\n callback(err || new Error('stream was destroyed'))\n }\n}\n\nvar call = function (fn) {\n fn()\n}\n\nvar pipe = function (from, to) {\n return from.pipe(to)\n}\n\nvar pump = function () {\n var streams = Array.prototype.slice.call(arguments)\n var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop\n\n if (Array.isArray(streams[0])) streams = streams[0]\n if (streams.length < 2) throw new Error('pump requires two streams per minimum')\n\n var error\n var destroys = streams.map(function (stream, i) {\n var reading = i < streams.length - 1\n var writing = i > 0\n return destroyer(stream, reading, writing, function (err) {\n if (!error) error = err\n if (err) destroys.forEach(call)\n if (reading) return\n destroys.forEach(call)\n callback(error)\n })\n })\n\n return streams.reduce(pipe)\n}\n\nmodule.exports = pump\n", "'use strict';\nconst {PassThrough: PassThroughStream} = require('stream');\n\nmodule.exports = options => {\n\toptions = {...options};\n\n\tconst {array} = options;\n\tlet {encoding} = options;\n\tconst isBuffer = encoding === 'buffer';\n\tlet objectMode = false;\n\n\tif (array) {\n\t\tobjectMode = !(encoding || isBuffer);\n\t} else {\n\t\tencoding = encoding || 'utf8';\n\t}\n\n\tif (isBuffer) {\n\t\tencoding = null;\n\t}\n\n\tconst stream = new PassThroughStream({objectMode});\n\n\tif (encoding) {\n\t\tstream.setEncoding(encoding);\n\t}\n\n\tlet length = 0;\n\tconst chunks = [];\n\n\tstream.on('data', chunk => {\n\t\tchunks.push(chunk);\n\n\t\tif (objectMode) {\n\t\t\tlength = chunks.length;\n\t\t} else {\n\t\t\tlength += chunk.length;\n\t\t}\n\t});\n\n\tstream.getBufferedValue = () => {\n\t\tif (array) {\n\t\t\treturn chunks;\n\t\t}\n\n\t\treturn isBuffer ? Buffer.concat(chunks, length) : chunks.join('');\n\t};\n\n\tstream.getBufferedLength = () => length;\n\n\treturn stream;\n};\n", "'use strict';\nconst {constants: BufferConstants} = require('buffer');\nconst pump = require('pump');\nconst bufferStream = require('./buffer-stream');\n\nclass MaxBufferError extends Error {\n\tconstructor() {\n\t\tsuper('maxBuffer exceeded');\n\t\tthis.name = 'MaxBufferError';\n\t}\n}\n\nasync function getStream(inputStream, options) {\n\tif (!inputStream) {\n\t\treturn Promise.reject(new Error('Expected a stream'));\n\t}\n\n\toptions = {\n\t\tmaxBuffer: Infinity,\n\t\t...options\n\t};\n\n\tconst {maxBuffer} = options;\n\n\tlet stream;\n\tawait new Promise((resolve, reject) => {\n\t\tconst rejectPromise = error => {\n\t\t\t// Don't retrieve an oversized buffer.\n\t\t\tif (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) {\n\t\t\t\terror.bufferedData = stream.getBufferedValue();\n\t\t\t}\n\n\t\t\treject(error);\n\t\t};\n\n\t\tstream = pump(inputStream, bufferStream(options), error => {\n\t\t\tif (error) {\n\t\t\t\trejectPromise(error);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tresolve();\n\t\t});\n\n\t\tstream.on('data', () => {\n\t\t\tif (stream.getBufferedLength() > maxBuffer) {\n\t\t\t\trejectPromise(new MaxBufferError());\n\t\t\t}\n\t\t});\n\t});\n\n\treturn stream.getBufferedValue();\n}\n\nmodule.exports = getStream;\n// TODO: Remove this for the next major release\nmodule.exports.default = getStream;\nmodule.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'});\nmodule.exports.array = (stream, options) => getStream(stream, {...options, array: true});\nmodule.exports.MaxBufferError = MaxBufferError;\n", "'use strict';\n// rfc7231 6.1\nconst statusCodeCacheableByDefault = new Set([\n 200,\n 203,\n 204,\n 206,\n 300,\n 301,\n 404,\n 405,\n 410,\n 414,\n 501,\n]);\n\n// This implementation does not understand partial responses (206)\nconst understoodStatuses = new Set([\n 200,\n 203,\n 204,\n 300,\n 301,\n 302,\n 303,\n 307,\n 308,\n 404,\n 405,\n 410,\n 414,\n 501,\n]);\n\nconst errorStatusCodes = new Set([\n 500,\n 502,\n 503, \n 504,\n]);\n\nconst hopByHopHeaders = {\n date: true, // included, because we add Age update Date\n connection: true,\n 'keep-alive': true,\n 'proxy-authenticate': true,\n 'proxy-authorization': true,\n te: true,\n trailer: true,\n 'transfer-encoding': true,\n upgrade: true,\n};\n\nconst excludedFromRevalidationUpdate = {\n // Since the old body is reused, it doesn't make sense to change properties of the body\n 'content-length': true,\n 'content-encoding': true,\n 'transfer-encoding': true,\n 'content-range': true,\n};\n\nfunction toNumberOrZero(s) {\n const n = parseInt(s, 10);\n return isFinite(n) ? n : 0;\n}\n\n// RFC 5861\nfunction isErrorResponse(response) {\n // consider undefined response as faulty\n if(!response) {\n return true\n }\n return errorStatusCodes.has(response.status);\n}\n\nfunction parseCacheControl(header) {\n const cc = {};\n if (!header) return cc;\n\n // TODO: When there is more than one value present for a given directive (e.g., two Expires header fields, multiple Cache-Control: max-age directives),\n // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale\n const parts = header.trim().split(/\\s*,\\s*/); // TODO: lame parsing\n for (const part of parts) {\n const [k, v] = part.split(/\\s*=\\s*/, 2);\n cc[k] = v === undefined ? true : v.replace(/^\"|\"$/g, ''); // TODO: lame unquoting\n }\n\n return cc;\n}\n\nfunction formatCacheControl(cc) {\n let parts = [];\n for (const k in cc) {\n const v = cc[k];\n parts.push(v === true ? k : k + '=' + v);\n }\n if (!parts.length) {\n return undefined;\n }\n return parts.join(', ');\n}\n\nmodule.exports = class CachePolicy {\n constructor(\n req,\n res,\n {\n shared,\n cacheHeuristic,\n immutableMinTimeToLive,\n ignoreCargoCult,\n _fromObject,\n } = {}\n ) {\n if (_fromObject) {\n this._fromObject(_fromObject);\n return;\n }\n\n if (!res || !res.headers) {\n throw Error('Response headers missing');\n }\n this._assertRequestHasHeaders(req);\n\n this._responseTime = this.now();\n this._isShared = shared !== false;\n this._cacheHeuristic =\n undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE\n this._immutableMinTtl =\n undefined !== immutableMinTimeToLive\n ? immutableMinTimeToLive\n : 24 * 3600 * 1000;\n\n this._status = 'status' in res ? res.status : 200;\n this._resHeaders = res.headers;\n this._rescc = parseCacheControl(res.headers['cache-control']);\n this._method = 'method' in req ? req.method : 'GET';\n this._url = req.url;\n this._host = req.headers.host;\n this._noAuthorization = !req.headers.authorization;\n this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used\n this._reqcc = parseCacheControl(req.headers['cache-control']);\n\n // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching,\n // so there's no point stricly adhering to the blindly copy&pasted directives.\n if (\n ignoreCargoCult &&\n 'pre-check' in this._rescc &&\n 'post-check' in this._rescc\n ) {\n delete this._rescc['pre-check'];\n delete this._rescc['post-check'];\n delete this._rescc['no-cache'];\n delete this._rescc['no-store'];\n delete this._rescc['must-revalidate'];\n this._resHeaders = Object.assign({}, this._resHeaders, {\n 'cache-control': formatCacheControl(this._rescc),\n });\n delete this._resHeaders.expires;\n delete this._resHeaders.pragma;\n }\n\n // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive\n // as having the same effect as if \"Cache-Control: no-cache\" were present (see Section 5.2.1).\n if (\n res.headers['cache-control'] == null &&\n /no-cache/.test(res.headers.pragma)\n ) {\n this._rescc['no-cache'] = true;\n }\n }\n\n now() {\n return Date.now();\n }\n\n storable() {\n // The \"no-store\" request directive indicates that a cache MUST NOT store any part of either this request or any response to it.\n return !!(\n !this._reqcc['no-store'] &&\n // A cache MUST NOT store a response to any request, unless:\n // The request method is understood by the cache and defined as being cacheable, and\n ('GET' === this._method ||\n 'HEAD' === this._method ||\n ('POST' === this._method && this._hasExplicitExpiration())) &&\n // the response status code is understood by the cache, and\n understoodStatuses.has(this._status) &&\n // the \"no-store\" cache directive does not appear in request or response header fields, and\n !this._rescc['no-store'] &&\n // the \"private\" response directive does not appear in the response, if the cache is shared, and\n (!this._isShared || !this._rescc.private) &&\n // the Authorization header field does not appear in the request, if the cache is shared,\n (!this._isShared ||\n this._noAuthorization ||\n this._allowsStoringAuthenticated()) &&\n // the response either:\n // contains an Expires header field, or\n (this._resHeaders.expires ||\n // contains a max-age response directive, or\n // contains a s-maxage response directive and the cache is shared, or\n // contains a public response directive.\n this._rescc['max-age'] ||\n (this._isShared && this._rescc['s-maxage']) ||\n this._rescc.public ||\n // has a status code that is defined as cacheable by default\n statusCodeCacheableByDefault.has(this._status))\n );\n }\n\n _hasExplicitExpiration() {\n // 4.2.1 Calculating Freshness Lifetime\n return (\n (this._isShared && this._rescc['s-maxage']) ||\n this._rescc['max-age'] ||\n this._resHeaders.expires\n );\n }\n\n _assertRequestHasHeaders(req) {\n if (!req || !req.headers) {\n throw Error('Request headers missing');\n }\n }\n\n satisfiesWithoutRevalidation(req) {\n this._assertRequestHasHeaders(req);\n\n // When presented with a request, a cache MUST NOT reuse a stored response, unless:\n // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive,\n // unless the stored response is successfully validated (Section 4.3), and\n const requestCC = parseCacheControl(req.headers['cache-control']);\n if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) {\n return false;\n }\n\n if (requestCC['max-age'] && this.age() > requestCC['max-age']) {\n return false;\n }\n\n if (\n requestCC['min-fresh'] &&\n this.timeToLive() < 1000 * requestCC['min-fresh']\n ) {\n return false;\n }\n\n // the stored response is either:\n // fresh, or allowed to be served stale\n if (this.stale()) {\n const allowsStale =\n requestCC['max-stale'] &&\n !this._rescc['must-revalidate'] &&\n (true === requestCC['max-stale'] ||\n requestCC['max-stale'] > this.age() - this.maxAge());\n if (!allowsStale) {\n return false;\n }\n }\n\n return this._requestMatches(req, false);\n }\n\n _requestMatches(req, allowHeadMethod) {\n // The presented effective request URI and that of the stored response match, and\n return (\n (!this._url || this._url === req.url) &&\n this._host === req.headers.host &&\n // the request method associated with the stored response allows it to be used for the presented request, and\n (!req.method ||\n this._method === req.method ||\n (allowHeadMethod && 'HEAD' === req.method)) &&\n // selecting header fields nominated by the stored response (if any) match those presented, and\n this._varyMatches(req)\n );\n }\n\n _allowsStoringAuthenticated() {\n // following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage.\n return (\n this._rescc['must-revalidate'] ||\n this._rescc.public ||\n this._rescc['s-maxage']\n );\n }\n\n _varyMatches(req) {\n if (!this._resHeaders.vary) {\n return true;\n }\n\n // A Vary header field-value of \"*\" always fails to match\n if (this._resHeaders.vary === '*') {\n return false;\n }\n\n const fields = this._resHeaders.vary\n .trim()\n .toLowerCase()\n .split(/\\s*,\\s*/);\n for (const name of fields) {\n if (req.headers[name] !== this._reqHeaders[name]) return false;\n }\n return true;\n }\n\n _copyWithoutHopByHopHeaders(inHeaders) {\n const headers = {};\n for (const name in inHeaders) {\n if (hopByHopHeaders[name]) continue;\n headers[name] = inHeaders[name];\n }\n // 9.1. Connection\n if (inHeaders.connection) {\n const tokens = inHeaders.connection.trim().split(/\\s*,\\s*/);\n for (const name of tokens) {\n delete headers[name];\n }\n }\n if (headers.warning) {\n const warnings = headers.warning.split(/,/).filter(warning => {\n return !/^\\s*1[0-9][0-9]/.test(warning);\n });\n if (!warnings.length) {\n delete headers.warning;\n } else {\n headers.warning = warnings.join(',').trim();\n }\n }\n return headers;\n }\n\n responseHeaders() {\n const headers = this._copyWithoutHopByHopHeaders(this._resHeaders);\n const age = this.age();\n\n // A cache SHOULD generate 113 warning if it heuristically chose a freshness\n // lifetime greater than 24 hours and the response's age is greater than 24 hours.\n if (\n age > 3600 * 24 &&\n !this._hasExplicitExpiration() &&\n this.maxAge() > 3600 * 24\n ) {\n headers.warning =\n (headers.warning ? `${headers.warning}, ` : '') +\n '113 - \"rfc7234 5.5.4\"';\n }\n headers.age = `${Math.round(age)}`;\n headers.date = new Date(this.now()).toUTCString();\n return headers;\n }\n\n /**\n * Value of the Date response header or current time if Date was invalid\n * @return timestamp\n */\n date() {\n const serverDate = Date.parse(this._resHeaders.date);\n if (isFinite(serverDate)) {\n return serverDate;\n }\n return this._responseTime;\n }\n\n /**\n * Value of the Age header, in seconds, updated for the current time.\n * May be fractional.\n *\n * @return Number\n */\n age() {\n let age = this._ageValue();\n\n const residentTime = (this.now() - this._responseTime) / 1000;\n return age + residentTime;\n }\n\n _ageValue() {\n return toNumberOrZero(this._resHeaders.age);\n }\n\n /**\n * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`.\n *\n * For an up-to-date value, see `timeToLive()`.\n *\n * @return Number\n */\n maxAge() {\n if (!this.storable() || this._rescc['no-cache']) {\n return 0;\n }\n\n // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default\n // so this implementation requires explicit opt-in via public header\n if (\n this._isShared &&\n (this._resHeaders['set-cookie'] &&\n !this._rescc.public &&\n !this._rescc.immutable)\n ) {\n return 0;\n }\n\n if (this._resHeaders.vary === '*') {\n return 0;\n }\n\n if (this._isShared) {\n if (this._rescc['proxy-revalidate']) {\n return 0;\n }\n // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field.\n if (this._rescc['s-maxage']) {\n return toNumberOrZero(this._rescc['s-maxage']);\n }\n }\n\n // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field.\n if (this._rescc['max-age']) {\n return toNumberOrZero(this._rescc['max-age']);\n }\n\n const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0;\n\n const serverDate = this.date();\n if (this._resHeaders.expires) {\n const expires = Date.parse(this._resHeaders.expires);\n // A cache recipient MUST interpret invalid date formats, especially the value \"0\", as representing a time in the past (i.e., \"already expired\").\n if (Number.isNaN(expires) || expires < serverDate) {\n return 0;\n }\n return Math.max(defaultMinTtl, (expires - serverDate) / 1000);\n }\n\n if (this._resHeaders['last-modified']) {\n const lastModified = Date.parse(this._resHeaders['last-modified']);\n if (isFinite(lastModified) && serverDate > lastModified) {\n return Math.max(\n defaultMinTtl,\n ((serverDate - lastModified) / 1000) * this._cacheHeuristic\n );\n }\n }\n\n return defaultMinTtl;\n }\n\n timeToLive() {\n const age = this.maxAge() - this.age();\n const staleIfErrorAge = age + toNumberOrZero(this._rescc['stale-if-error']);\n const staleWhileRevalidateAge = age + toNumberOrZero(this._rescc['stale-while-revalidate']);\n return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1000;\n }\n\n stale() {\n return this.maxAge() <= this.age();\n }\n\n _useStaleIfError() {\n return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age();\n }\n\n useStaleWhileRevalidate() {\n return this.maxAge() + toNumberOrZero(this._rescc['stale-while-revalidate']) > this.age();\n }\n\n static fromObject(obj) {\n return new this(undefined, undefined, { _fromObject: obj });\n }\n\n _fromObject(obj) {\n if (this._responseTime) throw Error('Reinitialized');\n if (!obj || obj.v !== 1) throw Error('Invalid serialization');\n\n this._responseTime = obj.t;\n this._isShared = obj.sh;\n this._cacheHeuristic = obj.ch;\n this._immutableMinTtl =\n obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000;\n this._status = obj.st;\n this._resHeaders = obj.resh;\n this._rescc = obj.rescc;\n this._method = obj.m;\n this._url = obj.u;\n this._host = obj.h;\n this._noAuthorization = obj.a;\n this._reqHeaders = obj.reqh;\n this._reqcc = obj.reqcc;\n }\n\n toObject() {\n return {\n v: 1,\n t: this._responseTime,\n sh: this._isShared,\n ch: this._cacheHeuristic,\n imm: this._immutableMinTtl,\n st: this._status,\n resh: this._resHeaders,\n rescc: this._rescc,\n m: this._method,\n u: this._url,\n h: this._host,\n a: this._noAuthorization,\n reqh: this._reqHeaders,\n reqcc: this._reqcc,\n };\n }\n\n /**\n * Headers for sending to the origin server to revalidate stale response.\n * Allows server to return 304 to allow reuse of the previous response.\n *\n * Hop by hop headers are always stripped.\n * Revalidation headers may be added or removed, depending on request.\n */\n revalidationHeaders(incomingReq) {\n this._assertRequestHasHeaders(incomingReq);\n const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers);\n\n // This implementation does not understand range requests\n delete headers['if-range'];\n\n if (!this._requestMatches(incomingReq, true) || !this.storable()) {\n // revalidation allowed via HEAD\n // not for the same resource, or wasn't allowed to be cached anyway\n delete headers['if-none-match'];\n delete headers['if-modified-since'];\n return headers;\n }\n\n /* MUST send that entity-tag in any cache validation request (using If-Match or If-None-Match) if an entity-tag has been provided by the origin server. */\n if (this._resHeaders.etag) {\n headers['if-none-match'] = headers['if-none-match']\n ? `${headers['if-none-match']}, ${this._resHeaders.etag}`\n : this._resHeaders.etag;\n }\n\n // Clients MAY issue simple (non-subrange) GET requests with either weak validators or strong validators. Clients MUST NOT use weak validators in other forms of request.\n const forbidsWeakValidators =\n headers['accept-ranges'] ||\n headers['if-match'] ||\n headers['if-unmodified-since'] ||\n (this._method && this._method != 'GET');\n\n /* SHOULD send the Last-Modified value in non-subrange cache validation requests (using If-Modified-Since) if only a Last-Modified value has been provided by the origin server.\n Note: This implementation does not understand partial responses (206) */\n if (forbidsWeakValidators) {\n delete headers['if-modified-since'];\n\n if (headers['if-none-match']) {\n const etags = headers['if-none-match']\n .split(/,/)\n .filter(etag => {\n return !/^\\s*W\\//.test(etag);\n });\n if (!etags.length) {\n delete headers['if-none-match'];\n } else {\n headers['if-none-match'] = etags.join(',').trim();\n }\n }\n } else if (\n this._resHeaders['last-modified'] &&\n !headers['if-modified-since']\n ) {\n headers['if-modified-since'] = this._resHeaders['last-modified'];\n }\n\n return headers;\n }\n\n /**\n * Creates new CachePolicy with information combined from the previews response,\n * and the new revalidation response.\n *\n * Returns {policy, modified} where modified is a boolean indicating\n * whether the response body has been modified, and old cached body can't be used.\n *\n * @return {Object} {policy: CachePolicy, modified: Boolean}\n */\n revalidatedPolicy(request, response) {\n this._assertRequestHasHeaders(request);\n if(this._useStaleIfError() && isErrorResponse(response)) { // I consider the revalidation request unsuccessful\n return {\n modified: false,\n matches: false,\n policy: this,\n };\n }\n if (!response || !response.headers) {\n throw Error('Response headers missing');\n }\n\n // These aren't going to be supported exactly, since one CachePolicy object\n // doesn't know about all the other cached objects.\n let matches = false;\n if (response.status !== undefined && response.status != 304) {\n matches = false;\n } else if (\n response.headers.etag &&\n !/^\\s*W\\//.test(response.headers.etag)\n ) {\n // \"All of the stored responses with the same strong validator are selected.\n // If none of the stored responses contain the same strong validator,\n // then the cache MUST NOT use the new response to update any stored responses.\"\n matches =\n this._resHeaders.etag &&\n this._resHeaders.etag.replace(/^\\s*W\\//, '') ===\n response.headers.etag;\n } else if (this._resHeaders.etag && response.headers.etag) {\n // \"If the new response contains a weak validator and that validator corresponds\n // to one of the cache's stored responses,\n // then the most recent of those matching stored responses is selected for update.\"\n matches =\n this._resHeaders.etag.replace(/^\\s*W\\//, '') ===\n response.headers.etag.replace(/^\\s*W\\//, '');\n } else if (this._resHeaders['last-modified']) {\n matches =\n this._resHeaders['last-modified'] ===\n response.headers['last-modified'];\n } else {\n // If the new response does not include any form of validator (such as in the case where\n // a client generates an If-Modified-Since request from a source other than the Last-Modified\n // response header field), and there is only one stored response, and that stored response also\n // lacks a validator, then that stored response is selected for update.\n if (\n !this._resHeaders.etag &&\n !this._resHeaders['last-modified'] &&\n !response.headers.etag &&\n !response.headers['last-modified']\n ) {\n matches = true;\n }\n }\n\n if (!matches) {\n return {\n policy: new this.constructor(request, response),\n // Client receiving 304 without body, even if it's invalid/mismatched has no option\n // but to reuse a cached body. We don't have a good way to tell clients to do\n // error recovery in such case.\n modified: response.status != 304,\n matches: false,\n };\n }\n\n // use other header fields provided in the 304 (Not Modified) response to replace all instances\n // of the corresponding header fields in the stored response.\n const headers = {};\n for (const k in this._resHeaders) {\n headers[k] =\n k in response.headers && !excludedFromRevalidationUpdate[k]\n ? response.headers[k]\n : this._resHeaders[k];\n }\n\n const newResponse = Object.assign({}, response, {\n status: this._status,\n method: this._method,\n headers,\n });\n return {\n policy: new this.constructor(request, newResponse, {\n shared: this._isShared,\n cacheHeuristic: this._cacheHeuristic,\n immutableMinTimeToLive: this._immutableMinTtl,\n }),\n modified: false,\n matches: true,\n };\n }\n};\n", "'use strict';\nmodule.exports = object => {\n\tconst result = {};\n\n\tfor (const [key, value] of Object.entries(object)) {\n\t\tresult[key.toLowerCase()] = value;\n\t}\n\n\treturn result;\n};\n", "'use strict';\n\nconst Readable = require('stream').Readable;\nconst lowercaseKeys = require('lowercase-keys');\n\nclass Response extends Readable {\n\tconstructor(statusCode, headers, body, url) {\n\t\tif (typeof statusCode !== 'number') {\n\t\t\tthrow new TypeError('Argument `statusCode` should be a number');\n\t\t}\n\t\tif (typeof headers !== 'object') {\n\t\t\tthrow new TypeError('Argument `headers` should be an object');\n\t\t}\n\t\tif (!(body instanceof Buffer)) {\n\t\t\tthrow new TypeError('Argument `body` should be a buffer');\n\t\t}\n\t\tif (typeof url !== 'string') {\n\t\t\tthrow new TypeError('Argument `url` should be a string');\n\t\t}\n\n\t\tsuper();\n\t\tthis.statusCode = statusCode;\n\t\tthis.headers = lowercaseKeys(headers);\n\t\tthis.body = body;\n\t\tthis.url = url;\n\t}\n\n\t_read() {\n\t\tthis.push(this.body);\n\t\tthis.push(null);\n\t}\n}\n\nmodule.exports = Response;\n", "'use strict';\n\n// We define these manually to ensure they're always copied\n// even if they would move up the prototype chain\n// https://nodejs.org/api/http.html#http_class_http_incomingmessage\nconst knownProps = [\n\t'destroy',\n\t'setTimeout',\n\t'socket',\n\t'headers',\n\t'trailers',\n\t'rawHeaders',\n\t'statusCode',\n\t'httpVersion',\n\t'httpVersionMinor',\n\t'httpVersionMajor',\n\t'rawTrailers',\n\t'statusMessage'\n];\n\nmodule.exports = (fromStream, toStream) => {\n\tconst fromProps = new Set(Object.keys(fromStream).concat(knownProps));\n\n\tfor (const prop of fromProps) {\n\t\t// Don't overwrite existing properties\n\t\tif (prop in toStream) {\n\t\t\tcontinue;\n\t\t}\n\n\t\ttoStream[prop] = typeof fromStream[prop] === 'function' ? fromStream[prop].bind(fromStream) : fromStream[prop];\n\t}\n};\n", "'use strict';\n\nconst PassThrough = require('stream').PassThrough;\nconst mimicResponse = require('mimic-response');\n\nconst cloneResponse = response => {\n\tif (!(response && response.pipe)) {\n\t\tthrow new TypeError('Parameter `response` must be a response stream.');\n\t}\n\n\tconst clone = new PassThrough();\n\tmimicResponse(response, clone);\n\n\treturn response.pipe(clone);\n};\n\nmodule.exports = cloneResponse;\n", "//TODO: handle reviver/dehydrate function like normal\n//and handle indentation, like normal.\n//if anyone needs this... please send pull request.\n\nexports.stringify = function stringify (o) {\n if('undefined' == typeof o) return o\n\n if(o && Buffer.isBuffer(o))\n return JSON.stringify(':base64:' + o.toString('base64'))\n\n if(o && o.toJSON)\n o = o.toJSON()\n\n if(o && 'object' === typeof o) {\n var s = ''\n var array = Array.isArray(o)\n s = array ? '[' : '{'\n var first = true\n\n for(var k in o) {\n var ignore = 'function' == typeof o[k] || (!array && 'undefined' === typeof o[k])\n if(Object.hasOwnProperty.call(o, k) && !ignore) {\n if(!first)\n s += ','\n first = false\n if (array) {\n if(o[k] == undefined)\n s += 'null'\n else\n s += stringify(o[k])\n } else if (o[k] !== void(0)) {\n s += stringify(k) + ':' + stringify(o[k])\n }\n }\n }\n\n s += array ? ']' : '}'\n\n return s\n } else if ('string' === typeof o) {\n return JSON.stringify(/^:/.test(o) ? ':' + o : o)\n } else if ('undefined' === typeof o) {\n return 'null';\n } else\n return JSON.stringify(o)\n}\n\nexports.parse = function (s) {\n return JSON.parse(s, function (key, value) {\n if('string' === typeof value) {\n if(/^:base64:/.test(value))\n return Buffer.from(value.substring(8), 'base64')\n else\n return /^:/.test(value) ? value.substring(1) : value \n }\n return value\n })\n}\n", "'use strict';\n\nconst EventEmitter = require('events');\nconst JSONB = require('json-buffer');\n\nconst loadStore = opts => {\n\tconst adapters = {\n\t\tredis: '@keyv/redis',\n\t\tmongodb: '@keyv/mongo',\n\t\tmongo: '@keyv/mongo',\n\t\tsqlite: '@keyv/sqlite',\n\t\tpostgresql: '@keyv/postgres',\n\t\tpostgres: '@keyv/postgres',\n\t\tmysql: '@keyv/mysql'\n\t};\n\tif (opts.adapter || opts.uri) {\n\t\tconst adapter = opts.adapter || /^[^:]*/.exec(opts.uri)[0];\n\t\treturn new (require(adapters[adapter]))(opts);\n\t}\n\n\treturn new Map();\n};\n\nclass Keyv extends EventEmitter {\n\tconstructor(uri, opts) {\n\t\tsuper();\n\t\tthis.opts = Object.assign(\n\t\t\t{\n\t\t\t\tnamespace: 'keyv',\n\t\t\t\tserialize: JSONB.stringify,\n\t\t\t\tdeserialize: JSONB.parse\n\t\t\t},\n\t\t\t(typeof uri === 'string') ? { uri } : uri,\n\t\t\topts\n\t\t);\n\n\t\tif (!this.opts.store) {\n\t\t\tconst adapterOpts = Object.assign({}, this.opts);\n\t\t\tthis.opts.store = loadStore(adapterOpts);\n\t\t}\n\n\t\tif (typeof this.opts.store.on === 'function') {\n\t\t\tthis.opts.store.on('error', err => this.emit('error', err));\n\t\t}\n\n\t\tthis.opts.store.namespace = this.opts.namespace;\n\t}\n\n\t_getKeyPrefix(key) {\n\t\treturn `${this.opts.namespace}:${key}`;\n\t}\n\n\tget(key, opts) {\n\t\tconst keyPrefixed = this._getKeyPrefix(key);\n\t\tconst { store } = this.opts;\n\t\treturn Promise.resolve()\n\t\t\t.then(() => store.get(keyPrefixed))\n\t\t\t.then(data => {\n\t\t\t\treturn (typeof data === 'string') ? this.opts.deserialize(data) : data;\n\t\t\t})\n\t\t\t.then(data => {\n\t\t\t\tif (data === undefined) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\tif (typeof data.expires === 'number' && Date.now() > data.expires) {\n\t\t\t\t\tthis.delete(key);\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\treturn (opts && opts.raw) ? data : data.value;\n\t\t\t});\n\t}\n\n\tset(key, value, ttl) {\n\t\tconst keyPrefixed = this._getKeyPrefix(key);\n\t\tif (typeof ttl === 'undefined') {\n\t\t\tttl = this.opts.ttl;\n\t\t}\n\n\t\tif (ttl === 0) {\n\t\t\tttl = undefined;\n\t\t}\n\n\t\tconst { store } = this.opts;\n\n\t\treturn Promise.resolve()\n\t\t\t.then(() => {\n\t\t\t\tconst expires = (typeof ttl === 'number') ? (Date.now() + ttl) : null;\n\t\t\t\tvalue = { value, expires };\n\t\t\t\treturn this.opts.serialize(value);\n\t\t\t})\n\t\t\t.then(value => store.set(keyPrefixed, value, ttl))\n\t\t\t.then(() => true);\n\t}\n\n\tdelete(key) {\n\t\tconst keyPrefixed = this._getKeyPrefix(key);\n\t\tconst { store } = this.opts;\n\t\treturn Promise.resolve()\n\t\t\t.then(() => store.delete(keyPrefixed));\n\t}\n\n\tclear() {\n\t\tconst { store } = this.opts;\n\t\treturn Promise.resolve()\n\t\t\t.then(() => store.clear());\n\t}\n}\n\nmodule.exports = Keyv;\n", "'use strict';\n\nconst EventEmitter = require('events');\nconst urlLib = require('url');\nconst normalizeUrl = require('normalize-url');\nconst getStream = require('get-stream');\nconst CachePolicy = require('http-cache-semantics');\nconst Response = require('responselike');\nconst lowercaseKeys = require('lowercase-keys');\nconst cloneResponse = require('clone-response');\nconst Keyv = require('keyv');\n\nclass CacheableRequest {\n\tconstructor(request, cacheAdapter) {\n\t\tif (typeof request !== 'function') {\n\t\t\tthrow new TypeError('Parameter `request` must be a function');\n\t\t}\n\n\t\tthis.cache = new Keyv({\n\t\t\turi: typeof cacheAdapter === 'string' && cacheAdapter,\n\t\t\tstore: typeof cacheAdapter !== 'string' && cacheAdapter,\n\t\t\tnamespace: 'cacheable-request'\n\t\t});\n\n\t\treturn this.createCacheableRequest(request);\n\t}\n\n\tcreateCacheableRequest(request) {\n\t\treturn (opts, cb) => {\n\t\t\tlet url;\n\t\t\tif (typeof opts === 'string') {\n\t\t\t\turl = normalizeUrlObject(urlLib.parse(opts));\n\t\t\t\topts = {};\n\t\t\t} else if (opts instanceof urlLib.URL) {\n\t\t\t\turl = normalizeUrlObject(urlLib.parse(opts.toString()));\n\t\t\t\topts = {};\n\t\t\t} else {\n\t\t\t\tconst [pathname, ...searchParts] = (opts.path || '').split('?');\n\t\t\t\tconst search = searchParts.length > 0 ?\n\t\t\t\t\t`?${searchParts.join('?')}` :\n\t\t\t\t\t'';\n\t\t\t\turl = normalizeUrlObject({ ...opts, pathname, search });\n\t\t\t}\n\n\t\t\topts = {\n\t\t\t\theaders: {},\n\t\t\t\tmethod: 'GET',\n\t\t\t\tcache: true,\n\t\t\t\tstrictTtl: false,\n\t\t\t\tautomaticFailover: false,\n\t\t\t\t...opts,\n\t\t\t\t...urlObjectToRequestOptions(url)\n\t\t\t};\n\t\t\topts.headers = lowercaseKeys(opts.headers);\n\n\t\t\tconst ee = new EventEmitter();\n\t\t\tconst normalizedUrlString = normalizeUrl(\n\t\t\t\turlLib.format(url),\n\t\t\t\t{\n\t\t\t\t\tstripWWW: false,\n\t\t\t\t\tremoveTrailingSlash: false,\n\t\t\t\t\tstripAuthentication: false\n\t\t\t\t}\n\t\t\t);\n\t\t\tconst key = `${opts.method}:${normalizedUrlString}`;\n\t\t\tlet revalidate = false;\n\t\t\tlet madeRequest = false;\n\n\t\t\tconst makeRequest = opts => {\n\t\t\t\tmadeRequest = true;\n\t\t\t\tlet requestErrored = false;\n\t\t\t\tlet requestErrorCallback;\n\n\t\t\t\tconst requestErrorPromise = new Promise(resolve => {\n\t\t\t\t\trequestErrorCallback = () => {\n\t\t\t\t\t\tif (!requestErrored) {\n\t\t\t\t\t\t\trequestErrored = true;\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t});\n\n\t\t\t\tconst handler = response => {\n\t\t\t\t\tif (revalidate && !opts.forceRefresh) {\n\t\t\t\t\t\tresponse.status = response.statusCode;\n\t\t\t\t\t\tconst revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(opts, response);\n\t\t\t\t\t\tif (!revalidatedPolicy.modified) {\n\t\t\t\t\t\t\tconst headers = revalidatedPolicy.policy.responseHeaders();\n\t\t\t\t\t\t\tresponse = new Response(revalidate.statusCode, headers, revalidate.body, revalidate.url);\n\t\t\t\t\t\t\tresponse.cachePolicy = revalidatedPolicy.policy;\n\t\t\t\t\t\t\tresponse.fromCache = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!response.fromCache) {\n\t\t\t\t\t\tresponse.cachePolicy = new CachePolicy(opts, response, opts);\n\t\t\t\t\t\tresponse.fromCache = false;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet clonedResponse;\n\t\t\t\t\tif (opts.cache && response.cachePolicy.storable()) {\n\t\t\t\t\t\tclonedResponse = cloneResponse(response);\n\n\t\t\t\t\t\t(async () => {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst bodyPromise = getStream.buffer(response);\n\n\t\t\t\t\t\t\t\tawait Promise.race([\n\t\t\t\t\t\t\t\t\trequestErrorPromise,\n\t\t\t\t\t\t\t\t\tnew Promise(resolve => response.once('end', resolve))\n\t\t\t\t\t\t\t\t]);\n\n\t\t\t\t\t\t\t\tif (requestErrored) {\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tconst body = await bodyPromise;\n\n\t\t\t\t\t\t\t\tconst value = {\n\t\t\t\t\t\t\t\t\tcachePolicy: response.cachePolicy.toObject(),\n\t\t\t\t\t\t\t\t\turl: response.url,\n\t\t\t\t\t\t\t\t\tstatusCode: response.fromCache ? revalidate.statusCode : response.statusCode,\n\t\t\t\t\t\t\t\t\tbody\n\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\tlet ttl = opts.strictTtl ? response.cachePolicy.timeToLive() : undefined;\n\t\t\t\t\t\t\t\tif (opts.maxTtl) {\n\t\t\t\t\t\t\t\t\tttl = ttl ? Math.min(ttl, opts.maxTtl) : opts.maxTtl;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tawait this.cache.set(key, value, ttl);\n\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\tee.emit('error', new CacheableRequest.CacheError(error));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})();\n\t\t\t\t\t} else if (opts.cache && revalidate) {\n\t\t\t\t\t\t(async () => {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tawait this.cache.delete(key);\n\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\tee.emit('error', new CacheableRequest.CacheError(error));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})();\n\t\t\t\t\t}\n\n\t\t\t\t\tee.emit('response', clonedResponse || response);\n\t\t\t\t\tif (typeof cb === 'function') {\n\t\t\t\t\t\tcb(clonedResponse || response);\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\ttry {\n\t\t\t\t\tconst req = request(opts, handler);\n\t\t\t\t\treq.once('error', requestErrorCallback);\n\t\t\t\t\treq.once('abort', requestErrorCallback);\n\t\t\t\t\tee.emit('request', req);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tee.emit('error', new CacheableRequest.RequestError(error));\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t(async () => {\n\t\t\t\tconst get = async opts => {\n\t\t\t\t\tawait Promise.resolve();\n\n\t\t\t\t\tconst cacheEntry = opts.cache ? await this.cache.get(key) : undefined;\n\t\t\t\t\tif (typeof cacheEntry === 'undefined') {\n\t\t\t\t\t\treturn makeRequest(opts);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst policy = CachePolicy.fromObject(cacheEntry.cachePolicy);\n\t\t\t\t\tif (policy.satisfiesWithoutRevalidation(opts) && !opts.forceRefresh) {\n\t\t\t\t\t\tconst headers = policy.responseHeaders();\n\t\t\t\t\t\tconst response = new Response(cacheEntry.statusCode, headers, cacheEntry.body, cacheEntry.url);\n\t\t\t\t\t\tresponse.cachePolicy = policy;\n\t\t\t\t\t\tresponse.fromCache = true;\n\n\t\t\t\t\t\tee.emit('response', response);\n\t\t\t\t\t\tif (typeof cb === 'function') {\n\t\t\t\t\t\t\tcb(response);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\trevalidate = cacheEntry;\n\t\t\t\t\t\topts.headers = policy.revalidationHeaders(opts);\n\t\t\t\t\t\tmakeRequest(opts);\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tconst errorHandler = error => ee.emit('error', new CacheableRequest.CacheError(error));\n\t\t\t\tthis.cache.once('error', errorHandler);\n\t\t\t\tee.on('response', () => this.cache.removeListener('error', errorHandler));\n\n\t\t\t\ttry {\n\t\t\t\t\tawait get(opts);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (opts.automaticFailover && !madeRequest) {\n\t\t\t\t\t\tmakeRequest(opts);\n\t\t\t\t\t}\n\n\t\t\t\t\tee.emit('error', new CacheableRequest.CacheError(error));\n\t\t\t\t}\n\t\t\t})();\n\n\t\t\treturn ee;\n\t\t};\n\t}\n}\n\nfunction urlObjectToRequestOptions(url) {\n\tconst options = { ...url };\n\toptions.path = `${url.pathname || '/'}${url.search || ''}`;\n\tdelete options.pathname;\n\tdelete options.search;\n\treturn options;\n}\n\nfunction normalizeUrlObject(url) {\n\t// If url was parsed by url.parse or new URL:\n\t// - hostname will be set\n\t// - host will be hostname[:port]\n\t// - port will be set if it was explicit in the parsed string\n\t// Otherwise, url was from request options:\n\t// - hostname or host may be set\n\t// - host shall not have port encoded\n\treturn {\n\t\tprotocol: url.protocol,\n\t\tauth: url.auth,\n\t\thostname: url.hostname || url.host || 'localhost',\n\t\tport: url.port,\n\t\tpathname: url.pathname,\n\t\tsearch: url.search\n\t};\n}\n\nCacheableRequest.RequestError = class extends Error {\n\tconstructor(error) {\n\t\tsuper(error.message);\n\t\tthis.name = 'RequestError';\n\t\tObject.assign(this, error);\n\t}\n};\n\nCacheableRequest.CacheError = class extends Error {\n\tconstructor(error) {\n\t\tsuper(error.message);\n\t\tthis.name = 'CacheError';\n\t\tObject.assign(this, error);\n\t}\n};\n\nmodule.exports = CacheableRequest;\n", "'use strict';\n\n// We define these manually to ensure they're always copied\n// even if they would move up the prototype chain\n// https://nodejs.org/api/http.html#http_class_http_incomingmessage\nconst knownProperties = [\n\t'aborted',\n\t'complete',\n\t'headers',\n\t'httpVersion',\n\t'httpVersionMinor',\n\t'httpVersionMajor',\n\t'method',\n\t'rawHeaders',\n\t'rawTrailers',\n\t'setTimeout',\n\t'socket',\n\t'statusCode',\n\t'statusMessage',\n\t'trailers',\n\t'url'\n];\n\nmodule.exports = (fromStream, toStream) => {\n\tif (toStream._readableState.autoDestroy) {\n\t\tthrow new Error('The second stream must have the `autoDestroy` option set to `false`');\n\t}\n\n\tconst fromProperties = new Set(Object.keys(fromStream).concat(knownProperties));\n\n\tconst properties = {};\n\n\tfor (const property of fromProperties) {\n\t\t// Don't overwrite existing properties.\n\t\tif (property in toStream) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tproperties[property] = {\n\t\t\tget() {\n\t\t\t\tconst value = fromStream[property];\n\t\t\t\tconst isFunction = typeof value === 'function';\n\n\t\t\t\treturn isFunction ? value.bind(fromStream) : value;\n\t\t\t},\n\t\t\tset(value) {\n\t\t\t\tfromStream[property] = value;\n\t\t\t},\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false\n\t\t};\n\t}\n\n\tObject.defineProperties(toStream, properties);\n\n\tfromStream.once('aborted', () => {\n\t\ttoStream.destroy();\n\n\t\ttoStream.emit('aborted');\n\t});\n\n\tfromStream.once('close', () => {\n\t\tif (fromStream.complete) {\n\t\t\tif (toStream.readable) {\n\t\t\t\ttoStream.once('end', () => {\n\t\t\t\t\ttoStream.emit('close');\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ttoStream.emit('close');\n\t\t\t}\n\t\t} else {\n\t\t\ttoStream.emit('close');\n\t\t}\n\t});\n\n\treturn toStream;\n};\n", "'use strict';\nconst {Transform, PassThrough} = require('stream');\nconst zlib = require('zlib');\nconst mimicResponse = require('mimic-response');\n\nmodule.exports = response => {\n\tconst contentEncoding = (response.headers['content-encoding'] || '').toLowerCase();\n\n\tif (!['gzip', 'deflate', 'br'].includes(contentEncoding)) {\n\t\treturn response;\n\t}\n\n\t// TODO: Remove this when targeting Node.js 12.\n\tconst isBrotli = contentEncoding === 'br';\n\tif (isBrotli && typeof zlib.createBrotliDecompress !== 'function') {\n\t\tresponse.destroy(new Error('Brotli is not supported on Node.js < 12'));\n\t\treturn response;\n\t}\n\n\tlet isEmpty = true;\n\n\tconst checker = new Transform({\n\t\ttransform(data, _encoding, callback) {\n\t\t\tisEmpty = false;\n\n\t\t\tcallback(null, data);\n\t\t},\n\n\t\tflush(callback) {\n\t\t\tcallback();\n\t\t}\n\t});\n\n\tconst finalStream = new PassThrough({\n\t\tautoDestroy: false,\n\t\tdestroy(error, callback) {\n\t\t\tresponse.destroy();\n\n\t\t\tcallback(error);\n\t\t}\n\t});\n\n\tconst decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip();\n\n\tdecompressStream.once('error', error => {\n\t\tif (isEmpty && !response.readable) {\n\t\t\tfinalStream.end();\n\t\t\treturn;\n\t\t}\n\n\t\tfinalStream.destroy(error);\n\t});\n\n\tmimicResponse(response, finalStream);\n\tresponse.pipe(checker).pipe(decompressStream).pipe(finalStream);\n\n\treturn finalStream;\n};\n", "'use strict';\n\nclass QuickLRU {\n\tconstructor(options = {}) {\n\t\tif (!(options.maxSize && options.maxSize > 0)) {\n\t\t\tthrow new TypeError('`maxSize` must be a number greater than 0');\n\t\t}\n\n\t\tthis.maxSize = options.maxSize;\n\t\tthis.onEviction = options.onEviction;\n\t\tthis.cache = new Map();\n\t\tthis.oldCache = new Map();\n\t\tthis._size = 0;\n\t}\n\n\t_set(key, value) {\n\t\tthis.cache.set(key, value);\n\t\tthis._size++;\n\n\t\tif (this._size >= this.maxSize) {\n\t\t\tthis._size = 0;\n\n\t\t\tif (typeof this.onEviction === 'function') {\n\t\t\t\tfor (const [key, value] of this.oldCache.entries()) {\n\t\t\t\t\tthis.onEviction(key, value);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.oldCache = this.cache;\n\t\t\tthis.cache = new Map();\n\t\t}\n\t}\n\n\tget(key) {\n\t\tif (this.cache.has(key)) {\n\t\t\treturn this.cache.get(key);\n\t\t}\n\n\t\tif (this.oldCache.has(key)) {\n\t\t\tconst value = this.oldCache.get(key);\n\t\t\tthis.oldCache.delete(key);\n\t\t\tthis._set(key, value);\n\t\t\treturn value;\n\t\t}\n\t}\n\n\tset(key, value) {\n\t\tif (this.cache.has(key)) {\n\t\t\tthis.cache.set(key, value);\n\t\t} else {\n\t\t\tthis._set(key, value);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\thas(key) {\n\t\treturn this.cache.has(key) || this.oldCache.has(key);\n\t}\n\n\tpeek(key) {\n\t\tif (this.cache.has(key)) {\n\t\t\treturn this.cache.get(key);\n\t\t}\n\n\t\tif (this.oldCache.has(key)) {\n\t\t\treturn this.oldCache.get(key);\n\t\t}\n\t}\n\n\tdelete(key) {\n\t\tconst deleted = this.cache.delete(key);\n\t\tif (deleted) {\n\t\t\tthis._size--;\n\t\t}\n\n\t\treturn this.oldCache.delete(key) || deleted;\n\t}\n\n\tclear() {\n\t\tthis.cache.clear();\n\t\tthis.oldCache.clear();\n\t\tthis._size = 0;\n\t}\n\n\t* keys() {\n\t\tfor (const [key] of this) {\n\t\t\tyield key;\n\t\t}\n\t}\n\n\t* values() {\n\t\tfor (const [, value] of this) {\n\t\t\tyield value;\n\t\t}\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tfor (const item of this.cache) {\n\t\t\tyield item;\n\t\t}\n\n\t\tfor (const item of this.oldCache) {\n\t\t\tconst [key] = item;\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\tyield item;\n\t\t\t}\n\t\t}\n\t}\n\n\tget size() {\n\t\tlet oldCacheSize = 0;\n\t\tfor (const key of this.oldCache.keys()) {\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\toldCacheSize++;\n\t\t\t}\n\t\t}\n\n\t\treturn Math.min(this._size + oldCacheSize, this.maxSize);\n\t}\n}\n\nmodule.exports = QuickLRU;\n", "'use strict';\nconst EventEmitter = require('events');\nconst tls = require('tls');\nconst http2 = require('http2');\nconst QuickLRU = require('quick-lru');\n\nconst kCurrentStreamsCount = Symbol('currentStreamsCount');\nconst kRequest = Symbol('request');\nconst kOriginSet = Symbol('cachedOriginSet');\nconst kGracefullyClosing = Symbol('gracefullyClosing');\n\nconst nameKeys = [\n\t// `http2.connect()` options\n\t'maxDeflateDynamicTableSize',\n\t'maxSessionMemory',\n\t'maxHeaderListPairs',\n\t'maxOutstandingPings',\n\t'maxReservedRemoteStreams',\n\t'maxSendHeaderBlockLength',\n\t'paddingStrategy',\n\n\t// `tls.connect()` options\n\t'localAddress',\n\t'path',\n\t'rejectUnauthorized',\n\t'minDHSize',\n\n\t// `tls.createSecureContext()` options\n\t'ca',\n\t'cert',\n\t'clientCertEngine',\n\t'ciphers',\n\t'key',\n\t'pfx',\n\t'servername',\n\t'minVersion',\n\t'maxVersion',\n\t'secureProtocol',\n\t'crl',\n\t'honorCipherOrder',\n\t'ecdhCurve',\n\t'dhparam',\n\t'secureOptions',\n\t'sessionIdContext'\n];\n\nconst getSortedIndex = (array, value, compare) => {\n\tlet low = 0;\n\tlet high = array.length;\n\n\twhile (low < high) {\n\t\tconst mid = (low + high) >>> 1;\n\n\t\t/* istanbul ignore next */\n\t\tif (compare(array[mid], value)) {\n\t\t\t// This never gets called because we use descending sort. Better to have this anyway.\n\t\t\tlow = mid + 1;\n\t\t} else {\n\t\t\thigh = mid;\n\t\t}\n\t}\n\n\treturn low;\n};\n\nconst compareSessions = (a, b) => {\n\treturn a.remoteSettings.maxConcurrentStreams > b.remoteSettings.maxConcurrentStreams;\n};\n\n// See https://tools.ietf.org/html/rfc8336\nconst closeCoveredSessions = (where, session) => {\n\t// Clients SHOULD NOT emit new requests on any connection whose Origin\n\t// Set is a proper subset of another connection's Origin Set, and they\n\t// SHOULD close it once all outstanding requests are satisfied.\n\tfor (const coveredSession of where) {\n\t\tif (\n\t\t\t// The set is a proper subset when its length is less than the other set.\n\t\t\tcoveredSession[kOriginSet].length < session[kOriginSet].length &&\n\n\t\t\t// And the other set includes all elements of the subset.\n\t\t\tcoveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) &&\n\n\t\t\t// Makes sure that the session can handle all requests from the covered session.\n\t\t\tcoveredSession[kCurrentStreamsCount] + session[kCurrentStreamsCount] <= session.remoteSettings.maxConcurrentStreams\n\t\t) {\n\t\t\t// This allows pending requests to finish and prevents making new requests.\n\t\t\tgracefullyClose(coveredSession);\n\t\t}\n\t}\n};\n\n// This is basically inverted `closeCoveredSessions(...)`.\nconst closeSessionIfCovered = (where, coveredSession) => {\n\tfor (const session of where) {\n\t\tif (\n\t\t\tcoveredSession[kOriginSet].length < session[kOriginSet].length &&\n\t\t\tcoveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) &&\n\t\t\tcoveredSession[kCurrentStreamsCount] + session[kCurrentStreamsCount] <= session.remoteSettings.maxConcurrentStreams\n\t\t) {\n\t\t\tgracefullyClose(coveredSession);\n\t\t}\n\t}\n};\n\nconst getSessions = ({agent, isFree}) => {\n\tconst result = {};\n\n\t// eslint-disable-next-line guard-for-in\n\tfor (const normalizedOptions in agent.sessions) {\n\t\tconst sessions = agent.sessions[normalizedOptions];\n\n\t\tconst filtered = sessions.filter(session => {\n\t\t\tconst result = session[Agent.kCurrentStreamsCount] < session.remoteSettings.maxConcurrentStreams;\n\n\t\t\treturn isFree ? result : !result;\n\t\t});\n\n\t\tif (filtered.length !== 0) {\n\t\t\tresult[normalizedOptions] = filtered;\n\t\t}\n\t}\n\n\treturn result;\n};\n\nconst gracefullyClose = session => {\n\tsession[kGracefullyClosing] = true;\n\n\tif (session[kCurrentStreamsCount] === 0) {\n\t\tsession.close();\n\t}\n};\n\nclass Agent extends EventEmitter {\n\tconstructor({timeout = 60000, maxSessions = Infinity, maxFreeSessions = 10, maxCachedTlsSessions = 100} = {}) {\n\t\tsuper();\n\n\t\t// A session is considered busy when its current streams count\n\t\t// is equal to or greater than the `maxConcurrentStreams` value.\n\n\t\t// A session is considered free when its current streams count\n\t\t// is less than the `maxConcurrentStreams` value.\n\n\t\t// SESSIONS[NORMALIZED_OPTIONS] = [];\n\t\tthis.sessions = {};\n\n\t\t// The queue for creating new sessions. It looks like this:\n\t\t// QUEUE[NORMALIZED_OPTIONS][NORMALIZED_ORIGIN] = ENTRY_FUNCTION\n\t\t//\n\t\t// The entry function has `listeners`, `completed` and `destroyed` properties.\n\t\t// `listeners` is an array of objects containing `resolve` and `reject` functions.\n\t\t// `completed` is a boolean. It's set to true after ENTRY_FUNCTION is executed.\n\t\t// `destroyed` is a boolean. If it's set to true, the session will be destroyed if hasn't connected yet.\n\t\tthis.queue = {};\n\n\t\t// Each session will use this timeout value.\n\t\tthis.timeout = timeout;\n\n\t\t// Max sessions in total\n\t\tthis.maxSessions = maxSessions;\n\n\t\t// Max free sessions in total\n\t\t// TODO: decreasing `maxFreeSessions` should close some sessions\n\t\tthis.maxFreeSessions = maxFreeSessions;\n\n\t\tthis._freeSessionsCount = 0;\n\t\tthis._sessionsCount = 0;\n\n\t\t// We don't support push streams by default.\n\t\tthis.settings = {\n\t\t\tenablePush: false\n\t\t};\n\n\t\t// Reusing TLS sessions increases performance.\n\t\tthis.tlsSessionCache = new QuickLRU({maxSize: maxCachedTlsSessions});\n\t}\n\n\tstatic normalizeOrigin(url, servername) {\n\t\tif (typeof url === 'string') {\n\t\t\turl = new URL(url);\n\t\t}\n\n\t\tif (servername && url.hostname !== servername) {\n\t\t\turl.hostname = servername;\n\t\t}\n\n\t\treturn url.origin;\n\t}\n\n\tnormalizeOptions(options) {\n\t\tlet normalized = '';\n\n\t\tif (options) {\n\t\t\tfor (const key of nameKeys) {\n\t\t\t\tif (options[key]) {\n\t\t\t\t\tnormalized += `:${options[key]}`;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn normalized;\n\t}\n\n\t_tryToCreateNewSession(normalizedOptions, normalizedOrigin) {\n\t\tif (!(normalizedOptions in this.queue) || !(normalizedOrigin in this.queue[normalizedOptions])) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst item = this.queue[normalizedOptions][normalizedOrigin];\n\n\t\t// The entry function can be run only once.\n\t\t// BUG: The session may be never created when:\n\t\t// - the first condition is false AND\n\t\t// - this function is never called with the same arguments in the future.\n\t\tif (this._sessionsCount < this.maxSessions && !item.completed) {\n\t\t\titem.completed = true;\n\n\t\t\titem();\n\t\t}\n\t}\n\n\tgetSession(origin, options, listeners) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (Array.isArray(listeners)) {\n\t\t\t\tlisteners = [...listeners];\n\n\t\t\t\t// Resolve the current promise ASAP, we're just moving the listeners.\n\t\t\t\t// They will be executed at a different time.\n\t\t\t\tresolve();\n\t\t\t} else {\n\t\t\t\tlisteners = [{resolve, reject}];\n\t\t\t}\n\n\t\t\tconst normalizedOptions = this.normalizeOptions(options);\n\t\t\tconst normalizedOrigin = Agent.normalizeOrigin(origin, options && options.servername);\n\n\t\t\tif (normalizedOrigin === undefined) {\n\t\t\t\tfor (const {reject} of listeners) {\n\t\t\t\t\treject(new TypeError('The `origin` argument needs to be a string or an URL object'));\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (normalizedOptions in this.sessions) {\n\t\t\t\tconst sessions = this.sessions[normalizedOptions];\n\n\t\t\t\tlet maxConcurrentStreams = -1;\n\t\t\t\tlet currentStreamsCount = -1;\n\t\t\t\tlet optimalSession;\n\n\t\t\t\t// We could just do this.sessions[normalizedOptions].find(...) but that isn't optimal.\n\t\t\t\t// Additionally, we are looking for session which has biggest current pending streams count.\n\t\t\t\tfor (const session of sessions) {\n\t\t\t\t\tconst sessionMaxConcurrentStreams = session.remoteSettings.maxConcurrentStreams;\n\n\t\t\t\t\tif (sessionMaxConcurrentStreams < maxConcurrentStreams) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (session[kOriginSet].includes(normalizedOrigin)) {\n\t\t\t\t\t\tconst sessionCurrentStreamsCount = session[kCurrentStreamsCount];\n\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tsessionCurrentStreamsCount >= sessionMaxConcurrentStreams ||\n\t\t\t\t\t\t\tsession[kGracefullyClosing] ||\n\t\t\t\t\t\t\t// Unfortunately the `close` event isn't called immediately,\n\t\t\t\t\t\t\t// so `session.destroyed` is `true`, but `session.closed` is `false`.\n\t\t\t\t\t\t\tsession.destroyed\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// We only need set this once.\n\t\t\t\t\t\tif (!optimalSession) {\n\t\t\t\t\t\t\tmaxConcurrentStreams = sessionMaxConcurrentStreams;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// We're looking for the session which has biggest current pending stream count,\n\t\t\t\t\t\t// in order to minimalize the amount of active sessions.\n\t\t\t\t\t\tif (sessionCurrentStreamsCount > currentStreamsCount) {\n\t\t\t\t\t\t\toptimalSession = session;\n\t\t\t\t\t\t\tcurrentStreamsCount = sessionCurrentStreamsCount;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (optimalSession) {\n\t\t\t\t\t/* istanbul ignore next: safety check */\n\t\t\t\t\tif (listeners.length !== 1) {\n\t\t\t\t\t\tfor (const {reject} of listeners) {\n\t\t\t\t\t\t\tconst error = new Error(\n\t\t\t\t\t\t\t\t`Expected the length of listeners to be 1, got ${listeners.length}.\\n` +\n\t\t\t\t\t\t\t\t'Please report this to https://github.com/szmarczak/http2-wrapper/'\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tlisteners[0].resolve(optimalSession);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (normalizedOptions in this.queue) {\n\t\t\t\tif (normalizedOrigin in this.queue[normalizedOptions]) {\n\t\t\t\t\t// There's already an item in the queue, just attach ourselves to it.\n\t\t\t\t\tthis.queue[normalizedOptions][normalizedOrigin].listeners.push(...listeners);\n\n\t\t\t\t\t// This shouldn't be executed here.\n\t\t\t\t\t// See the comment inside _tryToCreateNewSession.\n\t\t\t\t\tthis._tryToCreateNewSession(normalizedOptions, normalizedOrigin);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis.queue[normalizedOptions] = {};\n\t\t\t}\n\n\t\t\t// The entry must be removed from the queue IMMEDIATELY when:\n\t\t\t// 1. the session connects successfully,\n\t\t\t// 2. an error occurs.\n\t\t\tconst removeFromQueue = () => {\n\t\t\t\t// Our entry can be replaced. We cannot remove the new one.\n\t\t\t\tif (normalizedOptions in this.queue && this.queue[normalizedOptions][normalizedOrigin] === entry) {\n\t\t\t\t\tdelete this.queue[normalizedOptions][normalizedOrigin];\n\n\t\t\t\t\tif (Object.keys(this.queue[normalizedOptions]).length === 0) {\n\t\t\t\t\t\tdelete this.queue[normalizedOptions];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t// The main logic is here\n\t\t\tconst entry = () => {\n\t\t\t\tconst name = `${normalizedOrigin}:${normalizedOptions}`;\n\t\t\t\tlet receivedSettings = false;\n\n\t\t\t\ttry {\n\t\t\t\t\tconst session = http2.connect(origin, {\n\t\t\t\t\t\tcreateConnection: this.createConnection,\n\t\t\t\t\t\tsettings: this.settings,\n\t\t\t\t\t\tsession: this.tlsSessionCache.get(name),\n\t\t\t\t\t\t...options\n\t\t\t\t\t});\n\t\t\t\t\tsession[kCurrentStreamsCount] = 0;\n\t\t\t\t\tsession[kGracefullyClosing] = false;\n\n\t\t\t\t\tconst isFree = () => session[kCurrentStreamsCount] < session.remoteSettings.maxConcurrentStreams;\n\t\t\t\t\tlet wasFree = true;\n\n\t\t\t\t\tsession.socket.once('session', tlsSession => {\n\t\t\t\t\t\tthis.tlsSessionCache.set(name, tlsSession);\n\t\t\t\t\t});\n\n\t\t\t\t\tsession.once('error', error => {\n\t\t\t\t\t\t// Listeners are empty when the session successfully connected.\n\t\t\t\t\t\tfor (const {reject} of listeners) {\n\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// The connection got broken, purge the cache.\n\t\t\t\t\t\tthis.tlsSessionCache.delete(name);\n\t\t\t\t\t});\n\n\t\t\t\t\tsession.setTimeout(this.timeout, () => {\n\t\t\t\t\t\t// Terminates all streams owned by this session.\n\t\t\t\t\t\t// TODO: Maybe the streams should have a \"Session timed out\" error?\n\t\t\t\t\t\tsession.destroy();\n\t\t\t\t\t});\n\n\t\t\t\t\tsession.once('close', () => {\n\t\t\t\t\t\tif (receivedSettings) {\n\t\t\t\t\t\t\t// 1. If it wasn't free then no need to decrease because\n\t\t\t\t\t\t\t// it has been decreased already in session.request().\n\t\t\t\t\t\t\t// 2. `stream.once('close')` won't increment the count\n\t\t\t\t\t\t\t// because the session is already closed.\n\t\t\t\t\t\t\tif (wasFree) {\n\t\t\t\t\t\t\t\tthis._freeSessionsCount--;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tthis._sessionsCount--;\n\n\t\t\t\t\t\t\t// This cannot be moved to the stream logic,\n\t\t\t\t\t\t\t// because there may be a session that hadn't made a single request.\n\t\t\t\t\t\t\tconst where = this.sessions[normalizedOptions];\n\t\t\t\t\t\t\twhere.splice(where.indexOf(session), 1);\n\n\t\t\t\t\t\t\tif (where.length === 0) {\n\t\t\t\t\t\t\t\tdelete this.sessions[normalizedOptions];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Broken connection\n\t\t\t\t\t\t\tconst error = new Error('Session closed without receiving a SETTINGS frame');\n\t\t\t\t\t\t\terror.code = 'HTTP2WRAPPER_NOSETTINGS';\n\n\t\t\t\t\t\t\tfor (const {reject} of listeners) {\n\t\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tremoveFromQueue();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// There may be another session awaiting.\n\t\t\t\t\t\tthis._tryToCreateNewSession(normalizedOptions, normalizedOrigin);\n\t\t\t\t\t});\n\n\t\t\t\t\t// Iterates over the queue and processes listeners.\n\t\t\t\t\tconst processListeners = () => {\n\t\t\t\t\t\tif (!(normalizedOptions in this.queue) || !isFree()) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (const origin of session[kOriginSet]) {\n\t\t\t\t\t\t\tif (origin in this.queue[normalizedOptions]) {\n\t\t\t\t\t\t\t\tconst {listeners} = this.queue[normalizedOptions][origin];\n\n\t\t\t\t\t\t\t\t// Prevents session overloading.\n\t\t\t\t\t\t\t\twhile (listeners.length !== 0 && isFree()) {\n\t\t\t\t\t\t\t\t\t// We assume `resolve(...)` calls `request(...)` *directly*,\n\t\t\t\t\t\t\t\t\t// otherwise the session will get overloaded.\n\t\t\t\t\t\t\t\t\tlisteners.shift().resolve(session);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tconst where = this.queue[normalizedOptions];\n\t\t\t\t\t\t\t\tif (where[origin].listeners.length === 0) {\n\t\t\t\t\t\t\t\t\tdelete where[origin];\n\n\t\t\t\t\t\t\t\t\tif (Object.keys(where).length === 0) {\n\t\t\t\t\t\t\t\t\t\tdelete this.queue[normalizedOptions];\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t// We're no longer free, no point in continuing.\n\t\t\t\t\t\t\t\tif (!isFree()) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\t// The Origin Set cannot shrink. No need to check if it suddenly became covered by another one.\n\t\t\t\t\tsession.on('origin', () => {\n\t\t\t\t\t\tsession[kOriginSet] = session.originSet;\n\n\t\t\t\t\t\tif (!isFree()) {\n\t\t\t\t\t\t\t// The session is full.\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tprocessListeners();\n\n\t\t\t\t\t\t// Close covered sessions (if possible).\n\t\t\t\t\t\tcloseCoveredSessions(this.sessions[normalizedOptions], session);\n\t\t\t\t\t});\n\n\t\t\t\t\tsession.once('remoteSettings', () => {\n\t\t\t\t\t\t// Fix Node.js bug preventing the process from exiting\n\t\t\t\t\t\tsession.ref();\n\t\t\t\t\t\tsession.unref();\n\n\t\t\t\t\t\tthis._sessionsCount++;\n\n\t\t\t\t\t\t// The Agent could have been destroyed already.\n\t\t\t\t\t\tif (entry.destroyed) {\n\t\t\t\t\t\t\tconst error = new Error('Agent has been destroyed');\n\n\t\t\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\t\t\tlistener.reject(error);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tsession.destroy();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tsession[kOriginSet] = session.originSet;\n\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst where = this.sessions;\n\n\t\t\t\t\t\t\tif (normalizedOptions in where) {\n\t\t\t\t\t\t\t\tconst sessions = where[normalizedOptions];\n\t\t\t\t\t\t\t\tsessions.splice(getSortedIndex(sessions, session, compareSessions), 0, session);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\twhere[normalizedOptions] = [session];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis._freeSessionsCount += 1;\n\t\t\t\t\t\treceivedSettings = true;\n\n\t\t\t\t\t\tthis.emit('session', session);\n\n\t\t\t\t\t\tprocessListeners();\n\t\t\t\t\t\tremoveFromQueue();\n\n\t\t\t\t\t\t// TODO: Close last recently used (or least used?) session\n\t\t\t\t\t\tif (session[kCurrentStreamsCount] === 0 && this._freeSessionsCount > this.maxFreeSessions) {\n\t\t\t\t\t\t\tsession.close();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Check if we haven't managed to execute all listeners.\n\t\t\t\t\t\tif (listeners.length !== 0) {\n\t\t\t\t\t\t\t// Request for a new session with predefined listeners.\n\t\t\t\t\t\t\tthis.getSession(normalizedOrigin, options, listeners);\n\t\t\t\t\t\t\tlisteners.length = 0;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// `session.remoteSettings.maxConcurrentStreams` might get increased\n\t\t\t\t\t\tsession.on('remoteSettings', () => {\n\t\t\t\t\t\t\tprocessListeners();\n\n\t\t\t\t\t\t\t// In case the Origin Set changes\n\t\t\t\t\t\t\tcloseCoveredSessions(this.sessions[normalizedOptions], session);\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\n\t\t\t\t\t// Shim `session.request()` in order to catch all streams\n\t\t\t\t\tsession[kRequest] = session.request;\n\t\t\t\t\tsession.request = (headers, streamOptions) => {\n\t\t\t\t\t\tif (session[kGracefullyClosing]) {\n\t\t\t\t\t\t\tthrow new Error('The session is gracefully closing. No new streams are allowed.');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst stream = session[kRequest](headers, streamOptions);\n\n\t\t\t\t\t\t// The process won't exit until the session is closed or all requests are gone.\n\t\t\t\t\t\tsession.ref();\n\n\t\t\t\t\t\t++session[kCurrentStreamsCount];\n\n\t\t\t\t\t\tif (session[kCurrentStreamsCount] === session.remoteSettings.maxConcurrentStreams) {\n\t\t\t\t\t\t\tthis._freeSessionsCount--;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tstream.once('close', () => {\n\t\t\t\t\t\t\twasFree = isFree();\n\n\t\t\t\t\t\t\t--session[kCurrentStreamsCount];\n\n\t\t\t\t\t\t\tif (!session.destroyed && !session.closed) {\n\t\t\t\t\t\t\t\tcloseSessionIfCovered(this.sessions[normalizedOptions], session);\n\n\t\t\t\t\t\t\t\tif (isFree() && !session.closed) {\n\t\t\t\t\t\t\t\t\tif (!wasFree) {\n\t\t\t\t\t\t\t\t\t\tthis._freeSessionsCount++;\n\n\t\t\t\t\t\t\t\t\t\twasFree = true;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tconst isEmpty = session[kCurrentStreamsCount] === 0;\n\n\t\t\t\t\t\t\t\t\tif (isEmpty) {\n\t\t\t\t\t\t\t\t\t\tsession.unref();\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\tisEmpty &&\n\t\t\t\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t\t\t\tthis._freeSessionsCount > this.maxFreeSessions ||\n\t\t\t\t\t\t\t\t\t\t\tsession[kGracefullyClosing]\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\tsession.close();\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tcloseCoveredSessions(this.sessions[normalizedOptions], session);\n\t\t\t\t\t\t\t\t\t\tprocessListeners();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\treturn stream;\n\t\t\t\t\t};\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\tlistener.reject(error);\n\t\t\t\t\t}\n\n\t\t\t\t\tremoveFromQueue();\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tentry.listeners = listeners;\n\t\t\tentry.completed = false;\n\t\t\tentry.destroyed = false;\n\n\t\t\tthis.queue[normalizedOptions][normalizedOrigin] = entry;\n\t\t\tthis._tryToCreateNewSession(normalizedOptions, normalizedOrigin);\n\t\t});\n\t}\n\n\trequest(origin, options, headers, streamOptions) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.getSession(origin, options, [{\n\t\t\t\treject,\n\t\t\t\tresolve: session => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresolve(session.request(headers, streamOptions));\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}]);\n\t\t});\n\t}\n\n\tcreateConnection(origin, options) {\n\t\treturn Agent.connect(origin, options);\n\t}\n\n\tstatic connect(origin, options) {\n\t\toptions.ALPNProtocols = ['h2'];\n\n\t\tconst port = origin.port || 443;\n\t\tconst host = origin.hostname || origin.host;\n\n\t\tif (typeof options.servername === 'undefined') {\n\t\t\toptions.servername = host;\n\t\t}\n\n\t\treturn tls.connect(port, host, options);\n\t}\n\n\tcloseFreeSessions() {\n\t\tfor (const sessions of Object.values(this.sessions)) {\n\t\t\tfor (const session of sessions) {\n\t\t\t\tif (session[kCurrentStreamsCount] === 0) {\n\t\t\t\t\tsession.close();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdestroy(reason) {\n\t\tfor (const sessions of Object.values(this.sessions)) {\n\t\t\tfor (const session of sessions) {\n\t\t\t\tsession.destroy(reason);\n\t\t\t}\n\t\t}\n\n\t\tfor (const entriesOfAuthority of Object.values(this.queue)) {\n\t\t\tfor (const entry of Object.values(entriesOfAuthority)) {\n\t\t\t\tentry.destroyed = true;\n\t\t\t}\n\t\t}\n\n\t\t// New requests should NOT attach to destroyed sessions\n\t\tthis.queue = {};\n\t}\n\n\tget freeSessions() {\n\t\treturn getSessions({agent: this, isFree: true});\n\t}\n\n\tget busySessions() {\n\t\treturn getSessions({agent: this, isFree: false});\n\t}\n}\n\nAgent.kCurrentStreamsCount = kCurrentStreamsCount;\nAgent.kGracefullyClosing = kGracefullyClosing;\n\nmodule.exports = {\n\tAgent,\n\tglobalAgent: new Agent()\n};\n", "'use strict';\nconst {Readable} = require('stream');\n\nclass IncomingMessage extends Readable {\n\tconstructor(socket, highWaterMark) {\n\t\tsuper({\n\t\t\thighWaterMark,\n\t\t\tautoDestroy: false\n\t\t});\n\n\t\tthis.statusCode = null;\n\t\tthis.statusMessage = '';\n\t\tthis.httpVersion = '2.0';\n\t\tthis.httpVersionMajor = 2;\n\t\tthis.httpVersionMinor = 0;\n\t\tthis.headers = {};\n\t\tthis.trailers = {};\n\t\tthis.req = null;\n\n\t\tthis.aborted = false;\n\t\tthis.complete = false;\n\t\tthis.upgrade = null;\n\n\t\tthis.rawHeaders = [];\n\t\tthis.rawTrailers = [];\n\n\t\tthis.socket = socket;\n\t\tthis.connection = socket;\n\n\t\tthis._dumped = false;\n\t}\n\n\t_destroy(error) {\n\t\tthis.req._request.destroy(error);\n\t}\n\n\tsetTimeout(ms, callback) {\n\t\tthis.req.setTimeout(ms, callback);\n\t\treturn this;\n\t}\n\n\t_dump() {\n\t\tif (!this._dumped) {\n\t\t\tthis._dumped = true;\n\n\t\t\tthis.removeAllListeners('data');\n\t\t\tthis.resume();\n\t\t}\n\t}\n\n\t_read() {\n\t\tif (this.req) {\n\t\t\tthis.req._request.resume();\n\t\t}\n\t}\n}\n\nmodule.exports = IncomingMessage;\n", "'use strict';\n/* istanbul ignore file: https://github.com/nodejs/node/blob/a91293d4d9ab403046ab5eb022332e4e3d249bd3/lib/internal/url.js#L1257 */\n\nmodule.exports = url => {\n\tconst options = {\n\t\tprotocol: url.protocol,\n\t\thostname: typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname,\n\t\thost: url.host,\n\t\thash: url.hash,\n\t\tsearch: url.search,\n\t\tpathname: url.pathname,\n\t\thref: url.href,\n\t\tpath: `${url.pathname || ''}${url.search || ''}`\n\t};\n\n\tif (typeof url.port === 'string' && url.port.length !== 0) {\n\t\toptions.port = Number(url.port);\n\t}\n\n\tif (url.username || url.password) {\n\t\toptions.auth = `${url.username || ''}:${url.password || ''}`;\n\t}\n\n\treturn options;\n};\n", "'use strict';\n\nmodule.exports = (from, to, events) => {\n\tfor (const event of events) {\n\t\tfrom.on(event, (...args) => to.emit(event, ...args));\n\t}\n};\n", "'use strict';\n\nmodule.exports = header => {\n\tswitch (header) {\n\t\tcase ':method':\n\t\tcase ':scheme':\n\t\tcase ':authority':\n\t\tcase ':path':\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n};\n", "'use strict';\n/* istanbul ignore file: https://github.com/nodejs/node/blob/master/lib/internal/errors.js */\n\nconst makeError = (Base, key, getMessage) => {\n\tmodule.exports[key] = class NodeError extends Base {\n\t\tconstructor(...args) {\n\t\t\tsuper(typeof getMessage === 'string' ? getMessage : getMessage(args));\n\t\t\tthis.name = `${super.name} [${key}]`;\n\t\t\tthis.code = key;\n\t\t}\n\t};\n};\n\nmakeError(TypeError, 'ERR_INVALID_ARG_TYPE', args => {\n\tconst type = args[0].includes('.') ? 'property' : 'argument';\n\n\tlet valid = args[1];\n\tconst isManyTypes = Array.isArray(valid);\n\n\tif (isManyTypes) {\n\t\tvalid = `${valid.slice(0, -1).join(', ')} or ${valid.slice(-1)}`;\n\t}\n\n\treturn `The \"${args[0]}\" ${type} must be ${isManyTypes ? 'one of' : 'of'} type ${valid}. Received ${typeof args[2]}`;\n});\n\nmakeError(TypeError, 'ERR_INVALID_PROTOCOL', args => {\n\treturn `Protocol \"${args[0]}\" not supported. Expected \"${args[1]}\"`;\n});\n\nmakeError(Error, 'ERR_HTTP_HEADERS_SENT', args => {\n\treturn `Cannot ${args[0]} headers after they are sent to the client`;\n});\n\nmakeError(TypeError, 'ERR_INVALID_HTTP_TOKEN', args => {\n\treturn `${args[0]} must be a valid HTTP token [${args[1]}]`;\n});\n\nmakeError(TypeError, 'ERR_HTTP_INVALID_HEADER_VALUE', args => {\n\treturn `Invalid value \"${args[0]} for header \"${args[1]}\"`;\n});\n\nmakeError(TypeError, 'ERR_INVALID_CHAR', args => {\n\treturn `Invalid character in ${args[0]} [${args[1]}]`;\n});\n", "'use strict';\nconst http2 = require('http2');\nconst {Writable} = require('stream');\nconst {Agent, globalAgent} = require('./agent');\nconst IncomingMessage = require('./incoming-message');\nconst urlToOptions = require('./utils/url-to-options');\nconst proxyEvents = require('./utils/proxy-events');\nconst isRequestPseudoHeader = require('./utils/is-request-pseudo-header');\nconst {\n\tERR_INVALID_ARG_TYPE,\n\tERR_INVALID_PROTOCOL,\n\tERR_HTTP_HEADERS_SENT,\n\tERR_INVALID_HTTP_TOKEN,\n\tERR_HTTP_INVALID_HEADER_VALUE,\n\tERR_INVALID_CHAR\n} = require('./utils/errors');\n\nconst {\n\tHTTP2_HEADER_STATUS,\n\tHTTP2_HEADER_METHOD,\n\tHTTP2_HEADER_PATH,\n\tHTTP2_METHOD_CONNECT\n} = http2.constants;\n\nconst kHeaders = Symbol('headers');\nconst kOrigin = Symbol('origin');\nconst kSession = Symbol('session');\nconst kOptions = Symbol('options');\nconst kFlushedHeaders = Symbol('flushedHeaders');\nconst kJobs = Symbol('jobs');\n\nconst isValidHttpToken = /^[\\^`\\-\\w!#$%&*+.|~]+$/;\nconst isInvalidHeaderValue = /[^\\t\\u0020-\\u007E\\u0080-\\u00FF]/;\n\nclass ClientRequest extends Writable {\n\tconstructor(input, options, callback) {\n\t\tsuper({\n\t\t\tautoDestroy: false\n\t\t});\n\n\t\tconst hasInput = typeof input === 'string' || input instanceof URL;\n\t\tif (hasInput) {\n\t\t\tinput = urlToOptions(input instanceof URL ? input : new URL(input));\n\t\t}\n\n\t\tif (typeof options === 'function' || options === undefined) {\n\t\t\t// (options, callback)\n\t\t\tcallback = options;\n\t\t\toptions = hasInput ? input : {...input};\n\t\t} else {\n\t\t\t// (input, options, callback)\n\t\t\toptions = {...input, ...options};\n\t\t}\n\n\t\tif (options.h2session) {\n\t\t\tthis[kSession] = options.h2session;\n\t\t} else if (options.agent === false) {\n\t\t\tthis.agent = new Agent({maxFreeSessions: 0});\n\t\t} else if (typeof options.agent === 'undefined' || options.agent === null) {\n\t\t\tif (typeof options.createConnection === 'function') {\n\t\t\t\t// This is a workaround - we don't have to create the session on our own.\n\t\t\t\tthis.agent = new Agent({maxFreeSessions: 0});\n\t\t\t\tthis.agent.createConnection = options.createConnection;\n\t\t\t} else {\n\t\t\t\tthis.agent = globalAgent;\n\t\t\t}\n\t\t} else if (typeof options.agent.request === 'function') {\n\t\t\tthis.agent = options.agent;\n\t\t} else {\n\t\t\tthrow new ERR_INVALID_ARG_TYPE('options.agent', ['Agent-like Object', 'undefined', 'false'], options.agent);\n\t\t}\n\n\t\tif (options.protocol && options.protocol !== 'https:') {\n\t\t\tthrow new ERR_INVALID_PROTOCOL(options.protocol, 'https:');\n\t\t}\n\n\t\tconst port = options.port || options.defaultPort || (this.agent && this.agent.defaultPort) || 443;\n\t\tconst host = options.hostname || options.host || 'localhost';\n\n\t\t// Don't enforce the origin via options. It may be changed in an Agent.\n\t\tdelete options.hostname;\n\t\tdelete options.host;\n\t\tdelete options.port;\n\n\t\tconst {timeout} = options;\n\t\toptions.timeout = undefined;\n\n\t\tthis[kHeaders] = Object.create(null);\n\t\tthis[kJobs] = [];\n\n\t\tthis.socket = null;\n\t\tthis.connection = null;\n\n\t\tthis.method = options.method || 'GET';\n\t\tthis.path = options.path;\n\n\t\tthis.res = null;\n\t\tthis.aborted = false;\n\t\tthis.reusedSocket = false;\n\n\t\tif (options.headers) {\n\t\t\tfor (const [header, value] of Object.entries(options.headers)) {\n\t\t\t\tthis.setHeader(header, value);\n\t\t\t}\n\t\t}\n\n\t\tif (options.auth && !('authorization' in this[kHeaders])) {\n\t\t\tthis[kHeaders].authorization = 'Basic ' + Buffer.from(options.auth).toString('base64');\n\t\t}\n\n\t\toptions.session = options.tlsSession;\n\t\toptions.path = options.socketPath;\n\n\t\tthis[kOptions] = options;\n\n\t\t// Clients that generate HTTP/2 requests directly SHOULD use the :authority pseudo-header field instead of the Host header field.\n\t\tif (port === 443) {\n\t\t\tthis[kOrigin] = `https://${host}`;\n\n\t\t\tif (!(':authority' in this[kHeaders])) {\n\t\t\t\tthis[kHeaders][':authority'] = host;\n\t\t\t}\n\t\t} else {\n\t\t\tthis[kOrigin] = `https://${host}:${port}`;\n\n\t\t\tif (!(':authority' in this[kHeaders])) {\n\t\t\t\tthis[kHeaders][':authority'] = `${host}:${port}`;\n\t\t\t}\n\t\t}\n\n\t\tif (timeout) {\n\t\t\tthis.setTimeout(timeout);\n\t\t}\n\n\t\tif (callback) {\n\t\t\tthis.once('response', callback);\n\t\t}\n\n\t\tthis[kFlushedHeaders] = false;\n\t}\n\n\tget method() {\n\t\treturn this[kHeaders][HTTP2_HEADER_METHOD];\n\t}\n\n\tset method(value) {\n\t\tif (value) {\n\t\t\tthis[kHeaders][HTTP2_HEADER_METHOD] = value.toUpperCase();\n\t\t}\n\t}\n\n\tget path() {\n\t\treturn this[kHeaders][HTTP2_HEADER_PATH];\n\t}\n\n\tset path(value) {\n\t\tif (value) {\n\t\t\tthis[kHeaders][HTTP2_HEADER_PATH] = value;\n\t\t}\n\t}\n\n\tget _mustNotHaveABody() {\n\t\treturn this.method === 'GET' || this.method === 'HEAD' || this.method === 'DELETE';\n\t}\n\n\t_write(chunk, encoding, callback) {\n\t\t// https://github.com/nodejs/node/blob/654df09ae0c5e17d1b52a900a545f0664d8c7627/lib/internal/http2/util.js#L148-L156\n\t\tif (this._mustNotHaveABody) {\n\t\t\tcallback(new Error('The GET, HEAD and DELETE methods must NOT have a body'));\n\t\t\t/* istanbul ignore next: Node.js 12 throws directly */\n\t\t\treturn;\n\t\t}\n\n\t\tthis.flushHeaders();\n\n\t\tconst callWrite = () => this._request.write(chunk, encoding, callback);\n\t\tif (this._request) {\n\t\t\tcallWrite();\n\t\t} else {\n\t\t\tthis[kJobs].push(callWrite);\n\t\t}\n\t}\n\n\t_final(callback) {\n\t\tif (this.destroyed) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.flushHeaders();\n\n\t\tconst callEnd = () => {\n\t\t\t// For GET, HEAD and DELETE\n\t\t\tif (this._mustNotHaveABody) {\n\t\t\t\tcallback();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis._request.end(callback);\n\t\t};\n\n\t\tif (this._request) {\n\t\t\tcallEnd();\n\t\t} else {\n\t\t\tthis[kJobs].push(callEnd);\n\t\t}\n\t}\n\n\tabort() {\n\t\tif (this.res && this.res.complete) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.aborted) {\n\t\t\tprocess.nextTick(() => this.emit('abort'));\n\t\t}\n\n\t\tthis.aborted = true;\n\n\t\tthis.destroy();\n\t}\n\n\t_destroy(error, callback) {\n\t\tif (this.res) {\n\t\t\tthis.res._dump();\n\t\t}\n\n\t\tif (this._request) {\n\t\t\tthis._request.destroy();\n\t\t}\n\n\t\tcallback(error);\n\t}\n\n\tasync flushHeaders() {\n\t\tif (this[kFlushedHeaders] || this.destroyed) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis[kFlushedHeaders] = true;\n\n\t\tconst isConnectMethod = this.method === HTTP2_METHOD_CONNECT;\n\n\t\t// The real magic is here\n\t\tconst onStream = stream => {\n\t\t\tthis._request = stream;\n\n\t\t\tif (this.destroyed) {\n\t\t\t\tstream.destroy();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Forwards `timeout`, `continue`, `close` and `error` events to this instance.\n\t\t\tif (!isConnectMethod) {\n\t\t\t\tproxyEvents(stream, this, ['timeout', 'continue', 'close', 'error']);\n\t\t\t}\n\n\t\t\t// Wait for the `finish` event. We don't want to emit the `response` event\n\t\t\t// before `request.end()` is called.\n\t\t\tconst waitForEnd = fn => {\n\t\t\t\treturn (...args) => {\n\t\t\t\t\tif (!this.writable && !this.destroyed) {\n\t\t\t\t\t\tfn(...args);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.once('finish', () => {\n\t\t\t\t\t\t\tfn(...args);\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t};\n\n\t\t\t// This event tells we are ready to listen for the data.\n\t\t\tstream.once('response', waitForEnd((headers, flags, rawHeaders) => {\n\t\t\t\t// If we were to emit raw request stream, it would be as fast as the native approach.\n\t\t\t\t// Note that wrapping the raw stream in a Proxy instance won't improve the performance (already tested it).\n\t\t\t\tconst response = new IncomingMessage(this.socket, stream.readableHighWaterMark);\n\t\t\t\tthis.res = response;\n\n\t\t\t\tresponse.req = this;\n\t\t\t\tresponse.statusCode = headers[HTTP2_HEADER_STATUS];\n\t\t\t\tresponse.headers = headers;\n\t\t\t\tresponse.rawHeaders = rawHeaders;\n\n\t\t\t\tresponse.once('end', () => {\n\t\t\t\t\tif (this.aborted) {\n\t\t\t\t\t\tresponse.aborted = true;\n\t\t\t\t\t\tresponse.emit('aborted');\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresponse.complete = true;\n\n\t\t\t\t\t\t// Has no effect, just be consistent with the Node.js behavior\n\t\t\t\t\t\tresponse.socket = null;\n\t\t\t\t\t\tresponse.connection = null;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tif (isConnectMethod) {\n\t\t\t\t\tresponse.upgrade = true;\n\n\t\t\t\t\t// The HTTP1 API says the socket is detached here,\n\t\t\t\t\t// but we can't do that so we pass the original HTTP2 request.\n\t\t\t\t\tif (this.emit('connect', response, stream, Buffer.alloc(0))) {\n\t\t\t\t\t\tthis.emit('close');\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// No listeners attached, destroy the original request.\n\t\t\t\t\t\tstream.destroy();\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Forwards data\n\t\t\t\t\tstream.on('data', chunk => {\n\t\t\t\t\t\tif (!response._dumped && !response.push(chunk)) {\n\t\t\t\t\t\t\tstream.pause();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\tstream.once('end', () => {\n\t\t\t\t\t\tresponse.push(null);\n\t\t\t\t\t});\n\n\t\t\t\t\tif (!this.emit('response', response)) {\n\t\t\t\t\t\t// No listeners attached, dump the response.\n\t\t\t\t\t\tresponse._dump();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}));\n\n\t\t\t// Emits `information` event\n\t\t\tstream.once('headers', waitForEnd(\n\t\t\t\theaders => this.emit('information', {statusCode: headers[HTTP2_HEADER_STATUS]})\n\t\t\t));\n\n\t\t\tstream.once('trailers', waitForEnd((trailers, flags, rawTrailers) => {\n\t\t\t\tconst {res} = this;\n\n\t\t\t\t// Assigns trailers to the response object.\n\t\t\t\tres.trailers = trailers;\n\t\t\t\tres.rawTrailers = rawTrailers;\n\t\t\t}));\n\n\t\t\tconst {socket} = stream.session;\n\t\t\tthis.socket = socket;\n\t\t\tthis.connection = socket;\n\n\t\t\tfor (const job of this[kJobs]) {\n\t\t\t\tjob();\n\t\t\t}\n\n\t\t\tthis.emit('socket', this.socket);\n\t\t};\n\n\t\t// Makes a HTTP2 request\n\t\tif (this[kSession]) {\n\t\t\ttry {\n\t\t\t\tonStream(this[kSession].request(this[kHeaders]));\n\t\t\t} catch (error) {\n\t\t\t\tthis.emit('error', error);\n\t\t\t}\n\t\t} else {\n\t\t\tthis.reusedSocket = true;\n\n\t\t\ttry {\n\t\t\t\tonStream(await this.agent.request(this[kOrigin], this[kOptions], this[kHeaders]));\n\t\t\t} catch (error) {\n\t\t\t\tthis.emit('error', error);\n\t\t\t}\n\t\t}\n\t}\n\n\tgetHeader(name) {\n\t\tif (typeof name !== 'string') {\n\t\t\tthrow new ERR_INVALID_ARG_TYPE('name', 'string', name);\n\t\t}\n\n\t\treturn this[kHeaders][name.toLowerCase()];\n\t}\n\n\tget headersSent() {\n\t\treturn this[kFlushedHeaders];\n\t}\n\n\tremoveHeader(name) {\n\t\tif (typeof name !== 'string') {\n\t\t\tthrow new ERR_INVALID_ARG_TYPE('name', 'string', name);\n\t\t}\n\n\t\tif (this.headersSent) {\n\t\t\tthrow new ERR_HTTP_HEADERS_SENT('remove');\n\t\t}\n\n\t\tdelete this[kHeaders][name.toLowerCase()];\n\t}\n\n\tsetHeader(name, value) {\n\t\tif (this.headersSent) {\n\t\t\tthrow new ERR_HTTP_HEADERS_SENT('set');\n\t\t}\n\n\t\tif (typeof name !== 'string' || (!isValidHttpToken.test(name) && !isRequestPseudoHeader(name))) {\n\t\t\tthrow new ERR_INVALID_HTTP_TOKEN('Header name', name);\n\t\t}\n\n\t\tif (typeof value === 'undefined') {\n\t\t\tthrow new ERR_HTTP_INVALID_HEADER_VALUE(value, name);\n\t\t}\n\n\t\tif (isInvalidHeaderValue.test(value)) {\n\t\t\tthrow new ERR_INVALID_CHAR('header content', name);\n\t\t}\n\n\t\tthis[kHeaders][name.toLowerCase()] = value;\n\t}\n\n\tsetNoDelay() {\n\t\t// HTTP2 sockets cannot be malformed, do nothing.\n\t}\n\n\tsetSocketKeepAlive() {\n\t\t// HTTP2 sockets cannot be malformed, do nothing.\n\t}\n\n\tsetTimeout(ms, callback) {\n\t\tconst applyTimeout = () => this._request.setTimeout(ms, callback);\n\n\t\tif (this._request) {\n\t\t\tapplyTimeout();\n\t\t} else {\n\t\t\tthis[kJobs].push(applyTimeout);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tget maxHeadersCount() {\n\t\tif (!this.destroyed && this._request) {\n\t\t\treturn this._request.session.localSettings.maxHeaderListSize;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tset maxHeadersCount(_value) {\n\t\t// Updating HTTP2 settings would affect all requests, do nothing.\n\t}\n}\n\nmodule.exports = ClientRequest;\n", "'use strict';\nconst tls = require('tls');\n\nmodule.exports = (options = {}, connect = tls.connect) => new Promise((resolve, reject) => {\n\tlet timeout = false;\n\n\tlet socket;\n\n\tconst callback = async () => {\n\t\tawait socketPromise;\n\n\t\tsocket.off('timeout', onTimeout);\n\t\tsocket.off('error', reject);\n\n\t\tif (options.resolveSocket) {\n\t\t\tresolve({alpnProtocol: socket.alpnProtocol, socket, timeout});\n\n\t\t\tif (timeout) {\n\t\t\t\tawait Promise.resolve();\n\t\t\t\tsocket.emit('timeout');\n\t\t\t}\n\t\t} else {\n\t\t\tsocket.destroy();\n\t\t\tresolve({alpnProtocol: socket.alpnProtocol, timeout});\n\t\t}\n\t};\n\n\tconst onTimeout = async () => {\n\t\ttimeout = true;\n\t\tcallback();\n\t};\n\n\tconst socketPromise = (async () => {\n\t\ttry {\n\t\t\tsocket = await connect(options, callback);\n\n\t\t\tsocket.on('error', reject);\n\t\t\tsocket.once('timeout', onTimeout);\n\t\t} catch (error) {\n\t\t\treject(error);\n\t\t}\n\t})();\n});\n", "'use strict';\nconst net = require('net');\n/* istanbul ignore file: https://github.com/nodejs/node/blob/v13.0.1/lib/_http_agent.js */\n\nmodule.exports = options => {\n\tlet servername = options.host;\n\tconst hostHeader = options.headers && options.headers.host;\n\n\tif (hostHeader) {\n\t\tif (hostHeader.startsWith('[')) {\n\t\t\tconst index = hostHeader.indexOf(']');\n\t\t\tif (index === -1) {\n\t\t\t\tservername = hostHeader;\n\t\t\t} else {\n\t\t\t\tservername = hostHeader.slice(1, -1);\n\t\t\t}\n\t\t} else {\n\t\t\tservername = hostHeader.split(':', 1)[0];\n\t\t}\n\t}\n\n\tif (net.isIP(servername)) {\n\t\treturn '';\n\t}\n\n\treturn servername;\n};\n", "'use strict';\nconst http = require('http');\nconst https = require('https');\nconst resolveALPN = require('resolve-alpn');\nconst QuickLRU = require('quick-lru');\nconst Http2ClientRequest = require('./client-request');\nconst calculateServerName = require('./utils/calculate-server-name');\nconst urlToOptions = require('./utils/url-to-options');\n\nconst cache = new QuickLRU({maxSize: 100});\nconst queue = new Map();\n\nconst installSocket = (agent, socket, options) => {\n\tsocket._httpMessage = {shouldKeepAlive: true};\n\n\tconst onFree = () => {\n\t\tagent.emit('free', socket, options);\n\t};\n\n\tsocket.on('free', onFree);\n\n\tconst onClose = () => {\n\t\tagent.removeSocket(socket, options);\n\t};\n\n\tsocket.on('close', onClose);\n\n\tconst onRemove = () => {\n\t\tagent.removeSocket(socket, options);\n\t\tsocket.off('close', onClose);\n\t\tsocket.off('free', onFree);\n\t\tsocket.off('agentRemove', onRemove);\n\t};\n\n\tsocket.on('agentRemove', onRemove);\n\n\tagent.emit('free', socket, options);\n};\n\nconst resolveProtocol = async options => {\n\tconst name = `${options.host}:${options.port}:${options.ALPNProtocols.sort()}`;\n\n\tif (!cache.has(name)) {\n\t\tif (queue.has(name)) {\n\t\t\tconst result = await queue.get(name);\n\t\t\treturn result.alpnProtocol;\n\t\t}\n\n\t\tconst {path, agent} = options;\n\t\toptions.path = options.socketPath;\n\n\t\tconst resultPromise = resolveALPN(options);\n\t\tqueue.set(name, resultPromise);\n\n\t\ttry {\n\t\t\tconst {socket, alpnProtocol} = await resultPromise;\n\t\t\tcache.set(name, alpnProtocol);\n\n\t\t\toptions.path = path;\n\n\t\t\tif (alpnProtocol === 'h2') {\n\t\t\t\t// https://github.com/nodejs/node/issues/33343\n\t\t\t\tsocket.destroy();\n\t\t\t} else {\n\t\t\t\tconst {globalAgent} = https;\n\t\t\t\tconst defaultCreateConnection = https.Agent.prototype.createConnection;\n\n\t\t\t\tif (agent) {\n\t\t\t\t\tif (agent.createConnection === defaultCreateConnection) {\n\t\t\t\t\t\tinstallSocket(agent, socket, options);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsocket.destroy();\n\t\t\t\t\t}\n\t\t\t\t} else if (globalAgent.createConnection === defaultCreateConnection) {\n\t\t\t\t\tinstallSocket(globalAgent, socket, options);\n\t\t\t\t} else {\n\t\t\t\t\tsocket.destroy();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tqueue.delete(name);\n\n\t\t\treturn alpnProtocol;\n\t\t} catch (error) {\n\t\t\tqueue.delete(name);\n\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\treturn cache.get(name);\n};\n\nmodule.exports = async (input, options, callback) => {\n\tif (typeof input === 'string' || input instanceof URL) {\n\t\tinput = urlToOptions(new URL(input));\n\t}\n\n\tif (typeof options === 'function') {\n\t\tcallback = options;\n\t\toptions = undefined;\n\t}\n\n\toptions = {\n\t\tALPNProtocols: ['h2', 'http/1.1'],\n\t\t...input,\n\t\t...options,\n\t\tresolveSocket: true\n\t};\n\n\tif (!Array.isArray(options.ALPNProtocols) || options.ALPNProtocols.length === 0) {\n\t\tthrow new Error('The `ALPNProtocols` option must be an Array with at least one entry');\n\t}\n\n\toptions.protocol = options.protocol || 'https:';\n\tconst isHttps = options.protocol === 'https:';\n\n\toptions.host = options.hostname || options.host || 'localhost';\n\toptions.session = options.tlsSession;\n\toptions.servername = options.servername || calculateServerName(options);\n\toptions.port = options.port || (isHttps ? 443 : 80);\n\toptions._defaultAgent = isHttps ? https.globalAgent : http.globalAgent;\n\n\tconst agents = options.agent;\n\n\tif (agents) {\n\t\tif (agents.addRequest) {\n\t\t\tthrow new Error('The `options.agent` object can contain only `http`, `https` or `http2` properties');\n\t\t}\n\n\t\toptions.agent = agents[isHttps ? 'https' : 'http'];\n\t}\n\n\tif (isHttps) {\n\t\tconst protocol = await resolveProtocol(options);\n\n\t\tif (protocol === 'h2') {\n\t\t\tif (agents) {\n\t\t\t\toptions.agent = agents.http2;\n\t\t\t}\n\n\t\t\treturn new Http2ClientRequest(options, callback);\n\t\t}\n\t}\n\n\treturn http.request(options, callback);\n};\n\nmodule.exports.protocolCache = cache;\n", "'use strict';\nconst http2 = require('http2');\nconst agent = require('./agent');\nconst ClientRequest = require('./client-request');\nconst IncomingMessage = require('./incoming-message');\nconst auto = require('./auto');\n\nconst request = (url, options, callback) => {\n\treturn new ClientRequest(url, options, callback);\n};\n\nconst get = (url, options, callback) => {\n\t// eslint-disable-next-line unicorn/prevent-abbreviations\n\tconst req = new ClientRequest(url, options, callback);\n\treq.end();\n\n\treturn req;\n};\n\nmodule.exports = {\n\t...http2,\n\tClientRequest,\n\tIncomingMessage,\n\t...agent,\n\trequest,\n\tget,\n\tauto\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst is_1 = require(\"@sindresorhus/is\");\nexports.default = (body) => is_1.default.nodeStream(body) && is_1.default.function_(body.getBoundary);\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst fs_1 = require(\"fs\");\nconst util_1 = require(\"util\");\nconst is_1 = require(\"@sindresorhus/is\");\nconst is_form_data_1 = require(\"./is-form-data\");\nconst statAsync = util_1.promisify(fs_1.stat);\nexports.default = async (body, headers) => {\n if (headers && 'content-length' in headers) {\n return Number(headers['content-length']);\n }\n if (!body) {\n return 0;\n }\n if (is_1.default.string(body)) {\n return Buffer.byteLength(body);\n }\n if (is_1.default.buffer(body)) {\n return body.length;\n }\n if (is_form_data_1.default(body)) {\n return util_1.promisify(body.getLength.bind(body))();\n }\n if (body instanceof fs_1.ReadStream) {\n const { size } = await statAsync(body.path);\n if (size === 0) {\n return undefined;\n }\n return size;\n }\n return undefined;\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction default_1(from, to, events) {\n const fns = {};\n for (const event of events) {\n fns[event] = (...args) => {\n to.emit(event, ...args);\n };\n from.on(event, fns[event]);\n }\n return () => {\n for (const event of events) {\n from.off(event, fns[event]);\n }\n };\n}\nexports.default = default_1;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// When attaching listeners, it's very easy to forget about them.\n// Especially if you do error handling and set timeouts.\n// So instead of checking if it's proper to throw an error on every timeout ever,\n// use this simple tool which will remove all listeners you have attached.\nexports.default = () => {\n const handlers = [];\n return {\n once(origin, event, fn) {\n origin.once(event, fn);\n handlers.push({ origin, event, fn });\n },\n unhandleAll() {\n for (const handler of handlers) {\n const { origin, event, fn } = handler;\n origin.removeListener(event, fn);\n }\n handlers.length = 0;\n }\n };\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TimeoutError = void 0;\nconst net = require(\"net\");\nconst unhandle_1 = require(\"./unhandle\");\nconst reentry = Symbol('reentry');\nconst noop = () => { };\nclass TimeoutError extends Error {\n constructor(threshold, event) {\n super(`Timeout awaiting '${event}' for ${threshold}ms`);\n this.event = event;\n this.name = 'TimeoutError';\n this.code = 'ETIMEDOUT';\n }\n}\nexports.TimeoutError = TimeoutError;\nexports.default = (request, delays, options) => {\n if (reentry in request) {\n return noop;\n }\n request[reentry] = true;\n const cancelers = [];\n const { once, unhandleAll } = unhandle_1.default();\n const addTimeout = (delay, callback, event) => {\n var _a;\n const timeout = setTimeout(callback, delay, delay, event);\n (_a = timeout.unref) === null || _a === void 0 ? void 0 : _a.call(timeout);\n const cancel = () => {\n clearTimeout(timeout);\n };\n cancelers.push(cancel);\n return cancel;\n };\n const { host, hostname } = options;\n const timeoutHandler = (delay, event) => {\n request.destroy(new TimeoutError(delay, event));\n };\n const cancelTimeouts = () => {\n for (const cancel of cancelers) {\n cancel();\n }\n unhandleAll();\n };\n request.once('error', error => {\n cancelTimeouts();\n // Save original behavior\n /* istanbul ignore next */\n if (request.listenerCount('error') === 0) {\n throw error;\n }\n });\n request.once('close', cancelTimeouts);\n once(request, 'response', (response) => {\n once(response, 'end', cancelTimeouts);\n });\n if (typeof delays.request !== 'undefined') {\n addTimeout(delays.request, timeoutHandler, 'request');\n }\n if (typeof delays.socket !== 'undefined') {\n const socketTimeoutHandler = () => {\n timeoutHandler(delays.socket, 'socket');\n };\n request.setTimeout(delays.socket, socketTimeoutHandler);\n // `request.setTimeout(0)` causes a memory leak.\n // We can just remove the listener and forget about the timer - it's unreffed.\n // See https://github.com/sindresorhus/got/issues/690\n cancelers.push(() => {\n request.removeListener('timeout', socketTimeoutHandler);\n });\n }\n once(request, 'socket', (socket) => {\n var _a;\n const { socketPath } = request;\n /* istanbul ignore next: hard to test */\n if (socket.connecting) {\n const hasPath = Boolean(socketPath !== null && socketPath !== void 0 ? socketPath : net.isIP((_a = hostname !== null && hostname !== void 0 ? hostname : host) !== null && _a !== void 0 ? _a : '') !== 0);\n if (typeof delays.lookup !== 'undefined' && !hasPath && typeof socket.address().address === 'undefined') {\n const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup');\n once(socket, 'lookup', cancelTimeout);\n }\n if (typeof delays.connect !== 'undefined') {\n const timeConnect = () => addTimeout(delays.connect, timeoutHandler, 'connect');\n if (hasPath) {\n once(socket, 'connect', timeConnect());\n }\n else {\n once(socket, 'lookup', (error) => {\n if (error === null) {\n once(socket, 'connect', timeConnect());\n }\n });\n }\n }\n if (typeof delays.secureConnect !== 'undefined' && options.protocol === 'https:') {\n once(socket, 'connect', () => {\n const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect');\n once(socket, 'secureConnect', cancelTimeout);\n });\n }\n }\n if (typeof delays.send !== 'undefined') {\n const timeRequest = () => addTimeout(delays.send, timeoutHandler, 'send');\n /* istanbul ignore next: hard to test */\n if (socket.connecting) {\n once(socket, 'connect', () => {\n once(request, 'upload-complete', timeRequest());\n });\n }\n else {\n once(request, 'upload-complete', timeRequest());\n }\n }\n });\n if (typeof delays.response !== 'undefined') {\n once(request, 'upload-complete', () => {\n const cancelTimeout = addTimeout(delays.response, timeoutHandler, 'response');\n once(request, 'response', cancelTimeout);\n });\n }\n return cancelTimeouts;\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst is_1 = require(\"@sindresorhus/is\");\nexports.default = (url) => {\n // Cast to URL\n url = url;\n const options = {\n protocol: url.protocol,\n hostname: is_1.default.string(url.hostname) && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname,\n host: url.host,\n hash: url.hash,\n search: url.search,\n pathname: url.pathname,\n href: url.href,\n path: `${url.pathname || ''}${url.search || ''}`\n };\n if (is_1.default.string(url.port) && url.port.length > 0) {\n options.port = Number(url.port);\n }\n if (url.username || url.password) {\n options.auth = `${url.username || ''}:${url.password || ''}`;\n }\n return options;\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/* istanbul ignore file: deprecated */\nconst url_1 = require(\"url\");\nconst keys = [\n 'protocol',\n 'host',\n 'hostname',\n 'port',\n 'pathname',\n 'search'\n];\nexports.default = (origin, options) => {\n var _a, _b;\n if (options.path) {\n if (options.pathname) {\n throw new TypeError('Parameters `path` and `pathname` are mutually exclusive.');\n }\n if (options.search) {\n throw new TypeError('Parameters `path` and `search` are mutually exclusive.');\n }\n if (options.searchParams) {\n throw new TypeError('Parameters `path` and `searchParams` are mutually exclusive.');\n }\n }\n if (options.search && options.searchParams) {\n throw new TypeError('Parameters `search` and `searchParams` are mutually exclusive.');\n }\n if (!origin) {\n if (!options.protocol) {\n throw new TypeError('No URL protocol specified');\n }\n origin = `${options.protocol}//${(_b = (_a = options.hostname) !== null && _a !== void 0 ? _a : options.host) !== null && _b !== void 0 ? _b : ''}`;\n }\n const url = new url_1.URL(origin);\n if (options.path) {\n const searchIndex = options.path.indexOf('?');\n if (searchIndex === -1) {\n options.pathname = options.path;\n }\n else {\n options.pathname = options.path.slice(0, searchIndex);\n options.search = options.path.slice(searchIndex + 1);\n }\n delete options.path;\n }\n for (const key of keys) {\n if (options[key]) {\n url[key] = options[key].toString();\n }\n }\n return url;\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass WeakableMap {\n constructor() {\n this.weakMap = new WeakMap();\n this.map = new Map();\n }\n set(key, value) {\n if (typeof key === 'object') {\n this.weakMap.set(key, value);\n }\n else {\n this.map.set(key, value);\n }\n }\n get(key) {\n if (typeof key === 'object') {\n return this.weakMap.get(key);\n }\n return this.map.get(key);\n }\n has(key) {\n if (typeof key === 'object') {\n return this.weakMap.has(key);\n }\n return this.map.has(key);\n }\n}\nexports.default = WeakableMap;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// TODO: Update https://github.com/sindresorhus/get-stream\nconst getBuffer = async (stream) => {\n const chunks = [];\n let length = 0;\n for await (const chunk of stream) {\n chunks.push(chunk);\n length += Buffer.byteLength(chunk);\n }\n if (Buffer.isBuffer(chunks[0])) {\n return Buffer.concat(chunks, length);\n }\n return Buffer.from(chunks.join(''));\n};\nexports.default = getBuffer;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.dnsLookupIpVersionToFamily = exports.isDnsLookupIpVersion = void 0;\nconst conversionTable = {\n auto: 0,\n ipv4: 4,\n ipv6: 6\n};\nexports.isDnsLookupIpVersion = (value) => {\n return value in conversionTable;\n};\nexports.dnsLookupIpVersionToFamily = (dnsLookupIpVersion) => {\n if (exports.isDnsLookupIpVersion(dnsLookupIpVersion)) {\n return conversionTable[dnsLookupIpVersion];\n }\n throw new Error('Invalid DNS lookup IP version');\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isResponseOk = void 0;\nexports.isResponseOk = (response) => {\n const { statusCode } = response;\n const limitStatusCode = response.request.options.followRedirect ? 299 : 399;\n return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304;\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst alreadyWarned = new Set();\nexports.default = (message) => {\n if (alreadyWarned.has(message)) {\n return;\n }\n alreadyWarned.add(message);\n // @ts-expect-error Missing types.\n process.emitWarning(`Got: ${message}`, {\n type: 'DeprecationWarning'\n });\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst is_1 = require(\"@sindresorhus/is\");\nconst normalizeArguments = (options, defaults) => {\n if (is_1.default.null_(options.encoding)) {\n throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead');\n }\n is_1.assert.any([is_1.default.string, is_1.default.undefined], options.encoding);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.resolveBodyOnly);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.methodRewriting);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.isStream);\n is_1.assert.any([is_1.default.string, is_1.default.undefined], options.responseType);\n // `options.responseType`\n if (options.responseType === undefined) {\n options.responseType = 'text';\n }\n // `options.retry`\n const { retry } = options;\n if (defaults) {\n options.retry = { ...defaults.retry };\n }\n else {\n options.retry = {\n calculateDelay: retryObject => retryObject.computedValue,\n limit: 0,\n methods: [],\n statusCodes: [],\n errorCodes: [],\n maxRetryAfter: undefined\n };\n }\n if (is_1.default.object(retry)) {\n options.retry = {\n ...options.retry,\n ...retry\n };\n options.retry.methods = [...new Set(options.retry.methods.map(method => method.toUpperCase()))];\n options.retry.statusCodes = [...new Set(options.retry.statusCodes)];\n options.retry.errorCodes = [...new Set(options.retry.errorCodes)];\n }\n else if (is_1.default.number(retry)) {\n options.retry.limit = retry;\n }\n if (is_1.default.undefined(options.retry.maxRetryAfter)) {\n options.retry.maxRetryAfter = Math.min(\n // TypeScript is not smart enough to handle `.filter(x => is.number(x))`.\n // eslint-disable-next-line unicorn/no-fn-reference-in-iterator\n ...[options.timeout.request, options.timeout.connect].filter(is_1.default.number));\n }\n // `options.pagination`\n if (is_1.default.object(options.pagination)) {\n if (defaults) {\n options.pagination = {\n ...defaults.pagination,\n ...options.pagination\n };\n }\n const { pagination } = options;\n if (!is_1.default.function_(pagination.transform)) {\n throw new Error('`options.pagination.transform` must be implemented');\n }\n if (!is_1.default.function_(pagination.shouldContinue)) {\n throw new Error('`options.pagination.shouldContinue` must be implemented');\n }\n if (!is_1.default.function_(pagination.filter)) {\n throw new TypeError('`options.pagination.filter` must be implemented');\n }\n if (!is_1.default.function_(pagination.paginate)) {\n throw new Error('`options.pagination.paginate` must be implemented');\n }\n }\n // JSON mode\n if (options.responseType === 'json' && options.headers.accept === undefined) {\n options.headers.accept = 'application/json';\n }\n return options;\n};\nexports.default = normalizeArguments;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.retryAfterStatusCodes = void 0;\nexports.retryAfterStatusCodes = new Set([413, 429, 503]);\nconst calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter }) => {\n if (attemptCount > retryOptions.limit) {\n return 0;\n }\n const hasMethod = retryOptions.methods.includes(error.options.method);\n const hasErrorCode = retryOptions.errorCodes.includes(error.code);\n const hasStatusCode = error.response && retryOptions.statusCodes.includes(error.response.statusCode);\n if (!hasMethod || (!hasErrorCode && !hasStatusCode)) {\n return 0;\n }\n if (error.response) {\n if (retryAfter) {\n if (retryOptions.maxRetryAfter === undefined || retryAfter > retryOptions.maxRetryAfter) {\n return 0;\n }\n return retryAfter;\n }\n if (error.response.statusCode === 413) {\n return 0;\n }\n }\n const noise = Math.random() * 100;\n return ((2 ** (attemptCount - 1)) * 1000) + noise;\n};\nexports.default = calculateRetryDelay;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.UnsupportedProtocolError = exports.ReadError = exports.TimeoutError = exports.UploadError = exports.CacheError = exports.HTTPError = exports.MaxRedirectsError = exports.RequestError = exports.setNonEnumerableProperties = exports.knownHookEvents = exports.withoutBody = exports.kIsNormalizedAlready = void 0;\nconst util_1 = require(\"util\");\nconst stream_1 = require(\"stream\");\nconst fs_1 = require(\"fs\");\nconst url_1 = require(\"url\");\nconst http = require(\"http\");\nconst http_1 = require(\"http\");\nconst https = require(\"https\");\nconst http_timer_1 = require(\"@szmarczak/http-timer\");\nconst cacheable_lookup_1 = require(\"cacheable-lookup\");\nconst CacheableRequest = require(\"cacheable-request\");\nconst decompressResponse = require(\"decompress-response\");\n// @ts-expect-error Missing types\nconst http2wrapper = require(\"http2-wrapper\");\nconst lowercaseKeys = require(\"lowercase-keys\");\nconst is_1 = require(\"@sindresorhus/is\");\nconst get_body_size_1 = require(\"./utils/get-body-size\");\nconst is_form_data_1 = require(\"./utils/is-form-data\");\nconst proxy_events_1 = require(\"./utils/proxy-events\");\nconst timed_out_1 = require(\"./utils/timed-out\");\nconst url_to_options_1 = require(\"./utils/url-to-options\");\nconst options_to_url_1 = require(\"./utils/options-to-url\");\nconst weakable_map_1 = require(\"./utils/weakable-map\");\nconst get_buffer_1 = require(\"./utils/get-buffer\");\nconst dns_ip_version_1 = require(\"./utils/dns-ip-version\");\nconst is_response_ok_1 = require(\"./utils/is-response-ok\");\nconst deprecation_warning_1 = require(\"../utils/deprecation-warning\");\nconst normalize_arguments_1 = require(\"../as-promise/normalize-arguments\");\nconst calculate_retry_delay_1 = require(\"./calculate-retry-delay\");\nlet globalDnsCache;\nconst kRequest = Symbol('request');\nconst kResponse = Symbol('response');\nconst kResponseSize = Symbol('responseSize');\nconst kDownloadedSize = Symbol('downloadedSize');\nconst kBodySize = Symbol('bodySize');\nconst kUploadedSize = Symbol('uploadedSize');\nconst kServerResponsesPiped = Symbol('serverResponsesPiped');\nconst kUnproxyEvents = Symbol('unproxyEvents');\nconst kIsFromCache = Symbol('isFromCache');\nconst kCancelTimeouts = Symbol('cancelTimeouts');\nconst kStartedReading = Symbol('startedReading');\nconst kStopReading = Symbol('stopReading');\nconst kTriggerRead = Symbol('triggerRead');\nconst kBody = Symbol('body');\nconst kJobs = Symbol('jobs');\nconst kOriginalResponse = Symbol('originalResponse');\nconst kRetryTimeout = Symbol('retryTimeout');\nexports.kIsNormalizedAlready = Symbol('isNormalizedAlready');\nconst supportsBrotli = is_1.default.string(process.versions.brotli);\nexports.withoutBody = new Set(['GET', 'HEAD']);\nexports.knownHookEvents = [\n 'init',\n 'beforeRequest',\n 'beforeRedirect',\n 'beforeError',\n 'beforeRetry',\n // Promise-Only\n 'afterResponse'\n];\nfunction validateSearchParameters(searchParameters) {\n // eslint-disable-next-line guard-for-in\n for (const key in searchParameters) {\n const value = searchParameters[key];\n if (!is_1.default.string(value) && !is_1.default.number(value) && !is_1.default.boolean(value) && !is_1.default.null_(value) && !is_1.default.undefined(value)) {\n throw new TypeError(`The \\`searchParams\\` value '${String(value)}' must be a string, number, boolean or null`);\n }\n }\n}\nfunction isClientRequest(clientRequest) {\n return is_1.default.object(clientRequest) && !('statusCode' in clientRequest);\n}\nconst cacheableStore = new weakable_map_1.default();\nconst waitForOpenFile = async (file) => new Promise((resolve, reject) => {\n const onError = (error) => {\n reject(error);\n };\n // Node.js 12 has incomplete types\n if (!file.pending) {\n resolve();\n }\n file.once('error', onError);\n file.once('ready', () => {\n file.off('error', onError);\n resolve();\n });\n});\nconst redirectCodes = new Set([300, 301, 302, 303, 304, 307, 308]);\nconst nonEnumerableProperties = [\n 'context',\n 'body',\n 'json',\n 'form'\n];\nexports.setNonEnumerableProperties = (sources, to) => {\n // Non enumerable properties shall not be merged\n const properties = {};\n for (const source of sources) {\n if (!source) {\n continue;\n }\n for (const name of nonEnumerableProperties) {\n if (!(name in source)) {\n continue;\n }\n properties[name] = {\n writable: true,\n configurable: true,\n enumerable: false,\n // @ts-expect-error TS doesn't see the check above\n value: source[name]\n };\n }\n }\n Object.defineProperties(to, properties);\n};\n/**\nAn error to be thrown when a request fails.\nContains a `code` property with error class code, like `ECONNREFUSED`.\n*/\nclass RequestError extends Error {\n constructor(message, error, self) {\n var _a;\n super(message);\n Error.captureStackTrace(this, this.constructor);\n this.name = 'RequestError';\n this.code = error.code;\n if (self instanceof Request) {\n Object.defineProperty(this, 'request', {\n enumerable: false,\n value: self\n });\n Object.defineProperty(this, 'response', {\n enumerable: false,\n value: self[kResponse]\n });\n Object.defineProperty(this, 'options', {\n // This fails because of TS 3.7.2 useDefineForClassFields\n // Ref: https://github.com/microsoft/TypeScript/issues/34972\n enumerable: false,\n value: self.options\n });\n }\n else {\n Object.defineProperty(this, 'options', {\n // This fails because of TS 3.7.2 useDefineForClassFields\n // Ref: https://github.com/microsoft/TypeScript/issues/34972\n enumerable: false,\n value: self\n });\n }\n this.timings = (_a = this.request) === null || _a === void 0 ? void 0 : _a.timings;\n // Recover the original stacktrace\n if (is_1.default.string(error.stack) && is_1.default.string(this.stack)) {\n const indexOfMessage = this.stack.indexOf(this.message) + this.message.length;\n const thisStackTrace = this.stack.slice(indexOfMessage).split('\\n').reverse();\n const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split('\\n').reverse();\n // Remove duplicated traces\n while (errorStackTrace.length !== 0 && errorStackTrace[0] === thisStackTrace[0]) {\n thisStackTrace.shift();\n }\n this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\\n')}${errorStackTrace.reverse().join('\\n')}`;\n }\n }\n}\nexports.RequestError = RequestError;\n/**\nAn error to be thrown when the server redirects you more than ten times.\nIncludes a `response` property.\n*/\nclass MaxRedirectsError extends RequestError {\n constructor(request) {\n super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request);\n this.name = 'MaxRedirectsError';\n }\n}\nexports.MaxRedirectsError = MaxRedirectsError;\n/**\nAn error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304.\nIncludes a `response` property.\n*/\nclass HTTPError extends RequestError {\n constructor(response) {\n super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, response.request);\n this.name = 'HTTPError';\n }\n}\nexports.HTTPError = HTTPError;\n/**\nAn error to be thrown when a cache method fails.\nFor example, if the database goes down or there's a filesystem error.\n*/\nclass CacheError extends RequestError {\n constructor(error, request) {\n super(error.message, error, request);\n this.name = 'CacheError';\n }\n}\nexports.CacheError = CacheError;\n/**\nAn error to be thrown when the request body is a stream and an error occurs while reading from that stream.\n*/\nclass UploadError extends RequestError {\n constructor(error, request) {\n super(error.message, error, request);\n this.name = 'UploadError';\n }\n}\nexports.UploadError = UploadError;\n/**\nAn error to be thrown when the request is aborted due to a timeout.\nIncludes an `event` and `timings` property.\n*/\nclass TimeoutError extends RequestError {\n constructor(error, timings, request) {\n super(error.message, error, request);\n this.name = 'TimeoutError';\n this.event = error.event;\n this.timings = timings;\n }\n}\nexports.TimeoutError = TimeoutError;\n/**\nAn error to be thrown when reading from response stream fails.\n*/\nclass ReadError extends RequestError {\n constructor(error, request) {\n super(error.message, error, request);\n this.name = 'ReadError';\n }\n}\nexports.ReadError = ReadError;\n/**\nAn error to be thrown when given an unsupported protocol.\n*/\nclass UnsupportedProtocolError extends RequestError {\n constructor(options) {\n super(`Unsupported protocol \"${options.url.protocol}\"`, {}, options);\n this.name = 'UnsupportedProtocolError';\n }\n}\nexports.UnsupportedProtocolError = UnsupportedProtocolError;\nconst proxiedRequestEvents = [\n 'socket',\n 'connect',\n 'continue',\n 'information',\n 'upgrade',\n 'timeout'\n];\nclass Request extends stream_1.Duplex {\n constructor(url, options = {}, defaults) {\n super({\n // This must be false, to enable throwing after destroy\n // It is used for retry logic in Promise API\n autoDestroy: false,\n // It needs to be zero because we're just proxying the data to another stream\n highWaterMark: 0\n });\n this[kDownloadedSize] = 0;\n this[kUploadedSize] = 0;\n this.requestInitialized = false;\n this[kServerResponsesPiped] = new Set();\n this.redirects = [];\n this[kStopReading] = false;\n this[kTriggerRead] = false;\n this[kJobs] = [];\n this.retryCount = 0;\n // TODO: Remove this when targeting Node.js >= 12\n this._progressCallbacks = [];\n const unlockWrite = () => this._unlockWrite();\n const lockWrite = () => this._lockWrite();\n this.on('pipe', (source) => {\n source.prependListener('data', unlockWrite);\n source.on('data', lockWrite);\n source.prependListener('end', unlockWrite);\n source.on('end', lockWrite);\n });\n this.on('unpipe', (source) => {\n source.off('data', unlockWrite);\n source.off('data', lockWrite);\n source.off('end', unlockWrite);\n source.off('end', lockWrite);\n });\n this.on('pipe', source => {\n if (source instanceof http_1.IncomingMessage) {\n this.options.headers = {\n ...source.headers,\n ...this.options.headers\n };\n }\n });\n const { json, body, form } = options;\n if (json || body || form) {\n this._lockWrite();\n }\n if (exports.kIsNormalizedAlready in options) {\n this.options = options;\n }\n else {\n try {\n // @ts-expect-error Common TypeScript bug saying that `this.constructor` is not accessible\n this.options = this.constructor.normalizeArguments(url, options, defaults);\n }\n catch (error) {\n // TODO: Move this to `_destroy()`\n if (is_1.default.nodeStream(options.body)) {\n options.body.destroy();\n }\n this.destroy(error);\n return;\n }\n }\n (async () => {\n var _a;\n try {\n if (this.options.body instanceof fs_1.ReadStream) {\n await waitForOpenFile(this.options.body);\n }\n const { url: normalizedURL } = this.options;\n if (!normalizedURL) {\n throw new TypeError('Missing `url` property');\n }\n this.requestUrl = normalizedURL.toString();\n decodeURI(this.requestUrl);\n await this._finalizeBody();\n await this._makeRequest();\n if (this.destroyed) {\n (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.destroy();\n return;\n }\n // Queued writes etc.\n for (const job of this[kJobs]) {\n job();\n }\n // Prevent memory leak\n this[kJobs].length = 0;\n this.requestInitialized = true;\n }\n catch (error) {\n if (error instanceof RequestError) {\n this._beforeError(error);\n return;\n }\n // This is a workaround for https://github.com/nodejs/node/issues/33335\n if (!this.destroyed) {\n this.destroy(error);\n }\n }\n })();\n }\n static normalizeArguments(url, options, defaults) {\n var _a, _b, _c, _d, _e;\n const rawOptions = options;\n if (is_1.default.object(url) && !is_1.default.urlInstance(url)) {\n options = { ...defaults, ...url, ...options };\n }\n else {\n if (url && options && options.url !== undefined) {\n throw new TypeError('The `url` option is mutually exclusive with the `input` argument');\n }\n options = { ...defaults, ...options };\n if (url !== undefined) {\n options.url = url;\n }\n if (is_1.default.urlInstance(options.url)) {\n options.url = new url_1.URL(options.url.toString());\n }\n }\n // TODO: Deprecate URL options in Got 12.\n // Support extend-specific options\n if (options.cache === false) {\n options.cache = undefined;\n }\n if (options.dnsCache === false) {\n options.dnsCache = undefined;\n }\n // Nice type assertions\n is_1.assert.any([is_1.default.string, is_1.default.undefined], options.method);\n is_1.assert.any([is_1.default.object, is_1.default.undefined], options.headers);\n is_1.assert.any([is_1.default.string, is_1.default.urlInstance, is_1.default.undefined], options.prefixUrl);\n is_1.assert.any([is_1.default.object, is_1.default.undefined], options.cookieJar);\n is_1.assert.any([is_1.default.object, is_1.default.string, is_1.default.undefined], options.searchParams);\n is_1.assert.any([is_1.default.object, is_1.default.string, is_1.default.undefined], options.cache);\n is_1.assert.any([is_1.default.object, is_1.default.number, is_1.default.undefined], options.timeout);\n is_1.assert.any([is_1.default.object, is_1.default.undefined], options.context);\n is_1.assert.any([is_1.default.object, is_1.default.undefined], options.hooks);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.decompress);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.ignoreInvalidCookies);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.followRedirect);\n is_1.assert.any([is_1.default.number, is_1.default.undefined], options.maxRedirects);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.throwHttpErrors);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.http2);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.allowGetBody);\n is_1.assert.any([is_1.default.string, is_1.default.undefined], options.localAddress);\n is_1.assert.any([dns_ip_version_1.isDnsLookupIpVersion, is_1.default.undefined], options.dnsLookupIpVersion);\n is_1.assert.any([is_1.default.object, is_1.default.undefined], options.https);\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.rejectUnauthorized);\n if (options.https) {\n is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.https.rejectUnauthorized);\n is_1.assert.any([is_1.default.function_, is_1.default.undefined], options.https.checkServerIdentity);\n is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.certificateAuthority);\n is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.key);\n is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.certificate);\n is_1.assert.any([is_1.default.string, is_1.default.undefined], options.https.passphrase);\n is_1.assert.any([is_1.default.string, is_1.default.buffer, is_1.default.array, is_1.default.undefined], options.https.pfx);\n }\n is_1.assert.any([is_1.default.object, is_1.default.undefined], options.cacheOptions);\n // `options.method`\n if (is_1.default.string(options.method)) {\n options.method = options.method.toUpperCase();\n }\n else {\n options.method = 'GET';\n }\n // `options.headers`\n if (options.headers === (defaults === null || defaults === void 0 ? void 0 : defaults.headers)) {\n options.headers = { ...options.headers };\n }\n else {\n options.headers = lowercaseKeys({ ...(defaults === null || defaults === void 0 ? void 0 : defaults.headers), ...options.headers });\n }\n // Disallow legacy `url.Url`\n if ('slashes' in options) {\n throw new TypeError('The legacy `url.Url` has been deprecated. Use `URL` instead.');\n }\n // `options.auth`\n if ('auth' in options) {\n throw new TypeError('Parameter `auth` is deprecated. Use `username` / `password` instead.');\n }\n // `options.searchParams`\n if ('searchParams' in options) {\n if (options.searchParams && options.searchParams !== (defaults === null || defaults === void 0 ? void 0 : defaults.searchParams)) {\n let searchParameters;\n if (is_1.default.string(options.searchParams) || (options.searchParams instanceof url_1.URLSearchParams)) {\n searchParameters = new url_1.URLSearchParams(options.searchParams);\n }\n else {\n validateSearchParameters(options.searchParams);\n searchParameters = new url_1.URLSearchParams();\n // eslint-disable-next-line guard-for-in\n for (const key in options.searchParams) {\n const value = options.searchParams[key];\n if (value === null) {\n searchParameters.append(key, '');\n }\n else if (value !== undefined) {\n searchParameters.append(key, value);\n }\n }\n }\n // `normalizeArguments()` is also used to merge options\n (_a = defaults === null || defaults === void 0 ? void 0 : defaults.searchParams) === null || _a === void 0 ? void 0 : _a.forEach((value, key) => {\n // Only use default if one isn't already defined\n if (!searchParameters.has(key)) {\n searchParameters.append(key, value);\n }\n });\n options.searchParams = searchParameters;\n }\n }\n // `options.username` & `options.password`\n options.username = (_b = options.username) !== null && _b !== void 0 ? _b : '';\n options.password = (_c = options.password) !== null && _c !== void 0 ? _c : '';\n // `options.prefixUrl` & `options.url`\n if (is_1.default.undefined(options.prefixUrl)) {\n options.prefixUrl = (_d = defaults === null || defaults === void 0 ? void 0 : defaults.prefixUrl) !== null && _d !== void 0 ? _d : '';\n }\n else {\n options.prefixUrl = options.prefixUrl.toString();\n if (options.prefixUrl !== '' && !options.prefixUrl.endsWith('/')) {\n options.prefixUrl += '/';\n }\n }\n if (is_1.default.string(options.url)) {\n if (options.url.startsWith('/')) {\n throw new Error('`input` must not start with a slash when using `prefixUrl`');\n }\n options.url = options_to_url_1.default(options.prefixUrl + options.url, options);\n }\n else if ((is_1.default.undefined(options.url) && options.prefixUrl !== '') || options.protocol) {\n options.url = options_to_url_1.default(options.prefixUrl, options);\n }\n if (options.url) {\n if ('port' in options) {\n delete options.port;\n }\n // Make it possible to change `options.prefixUrl`\n let { prefixUrl } = options;\n Object.defineProperty(options, 'prefixUrl', {\n set: (value) => {\n const url = options.url;\n if (!url.href.startsWith(value)) {\n throw new Error(`Cannot change \\`prefixUrl\\` from ${prefixUrl} to ${value}: ${url.href}`);\n }\n options.url = new url_1.URL(value + url.href.slice(prefixUrl.length));\n prefixUrl = value;\n },\n get: () => prefixUrl\n });\n // Support UNIX sockets\n let { protocol } = options.url;\n if (protocol === 'unix:') {\n protocol = 'http:';\n options.url = new url_1.URL(`http://unix${options.url.pathname}${options.url.search}`);\n }\n // Set search params\n if (options.searchParams) {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n options.url.search = options.searchParams.toString();\n }\n // Protocol check\n if (protocol !== 'http:' && protocol !== 'https:') {\n throw new UnsupportedProtocolError(options);\n }\n // Update `username`\n if (options.username === '') {\n options.username = options.url.username;\n }\n else {\n options.url.username = options.username;\n }\n // Update `password`\n if (options.password === '') {\n options.password = options.url.password;\n }\n else {\n options.url.password = options.password;\n }\n }\n // `options.cookieJar`\n const { cookieJar } = options;\n if (cookieJar) {\n let { setCookie, getCookieString } = cookieJar;\n is_1.assert.function_(setCookie);\n is_1.assert.function_(getCookieString);\n /* istanbul ignore next: Horrible `tough-cookie` v3 check */\n if (setCookie.length === 4 && getCookieString.length === 0) {\n setCookie = util_1.promisify(setCookie.bind(options.cookieJar));\n getCookieString = util_1.promisify(getCookieString.bind(options.cookieJar));\n options.cookieJar = {\n setCookie,\n getCookieString: getCookieString\n };\n }\n }\n // `options.cache`\n const { cache } = options;\n if (cache) {\n if (!cacheableStore.has(cache)) {\n cacheableStore.set(cache, new CacheableRequest(((requestOptions, handler) => {\n const result = requestOptions[kRequest](requestOptions, handler);\n // TODO: remove this when `cacheable-request` supports async request functions.\n if (is_1.default.promise(result)) {\n // @ts-expect-error\n // We only need to implement the error handler in order to support HTTP2 caching.\n // The result will be a promise anyway.\n result.once = (event, handler) => {\n if (event === 'error') {\n result.catch(handler);\n }\n else if (event === 'abort') {\n // The empty catch is needed here in case when\n // it rejects before it's `await`ed in `_makeRequest`.\n (async () => {\n try {\n const request = (await result);\n request.once('abort', handler);\n }\n catch (_a) { }\n })();\n }\n else {\n /* istanbul ignore next: safety check */\n throw new Error(`Unknown HTTP2 promise event: ${event}`);\n }\n return result;\n };\n }\n return result;\n }), cache));\n }\n }\n // `options.cacheOptions`\n options.cacheOptions = { ...options.cacheOptions };\n // `options.dnsCache`\n if (options.dnsCache === true) {\n if (!globalDnsCache) {\n globalDnsCache = new cacheable_lookup_1.default();\n }\n options.dnsCache = globalDnsCache;\n }\n else if (!is_1.default.undefined(options.dnsCache) && !options.dnsCache.lookup) {\n throw new TypeError(`Parameter \\`dnsCache\\` must be a CacheableLookup instance or a boolean, got ${is_1.default(options.dnsCache)}`);\n }\n // `options.timeout`\n if (is_1.default.number(options.timeout)) {\n options.timeout = { request: options.timeout };\n }\n else if (defaults && options.timeout !== defaults.timeout) {\n options.timeout = {\n ...defaults.timeout,\n ...options.timeout\n };\n }\n else {\n options.timeout = { ...options.timeout };\n }\n // `options.context`\n if (!options.context) {\n options.context = {};\n }\n // `options.hooks`\n const areHooksDefault = options.hooks === (defaults === null || defaults === void 0 ? void 0 : defaults.hooks);\n options.hooks = { ...options.hooks };\n for (const event of exports.knownHookEvents) {\n if (event in options.hooks) {\n if (is_1.default.array(options.hooks[event])) {\n // See https://github.com/microsoft/TypeScript/issues/31445#issuecomment-576929044\n options.hooks[event] = [...options.hooks[event]];\n }\n else {\n throw new TypeError(`Parameter \\`${event}\\` must be an Array, got ${is_1.default(options.hooks[event])}`);\n }\n }\n else {\n options.hooks[event] = [];\n }\n }\n if (defaults && !areHooksDefault) {\n for (const event of exports.knownHookEvents) {\n const defaultHooks = defaults.hooks[event];\n if (defaultHooks.length > 0) {\n // See https://github.com/microsoft/TypeScript/issues/31445#issuecomment-576929044\n options.hooks[event] = [\n ...defaults.hooks[event],\n ...options.hooks[event]\n ];\n }\n }\n }\n // DNS options\n if ('family' in options) {\n deprecation_warning_1.default('\"options.family\" was never documented, please use \"options.dnsLookupIpVersion\"');\n }\n // HTTPS options\n if (defaults === null || defaults === void 0 ? void 0 : defaults.https) {\n options.https = { ...defaults.https, ...options.https };\n }\n if ('rejectUnauthorized' in options) {\n deprecation_warning_1.default('\"options.rejectUnauthorized\" is now deprecated, please use \"options.https.rejectUnauthorized\"');\n }\n if ('checkServerIdentity' in options) {\n deprecation_warning_1.default('\"options.checkServerIdentity\" was never documented, please use \"options.https.checkServerIdentity\"');\n }\n if ('ca' in options) {\n deprecation_warning_1.default('\"options.ca\" was never documented, please use \"options.https.certificateAuthority\"');\n }\n if ('key' in options) {\n deprecation_warning_1.default('\"options.key\" was never documented, please use \"options.https.key\"');\n }\n if ('cert' in options) {\n deprecation_warning_1.default('\"options.cert\" was never documented, please use \"options.https.certificate\"');\n }\n if ('passphrase' in options) {\n deprecation_warning_1.default('\"options.passphrase\" was never documented, please use \"options.https.passphrase\"');\n }\n if ('pfx' in options) {\n deprecation_warning_1.default('\"options.pfx\" was never documented, please use \"options.https.pfx\"');\n }\n // Other options\n if ('followRedirects' in options) {\n throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.');\n }\n if (options.agent) {\n for (const key in options.agent) {\n if (key !== 'http' && key !== 'https' && key !== 'http2') {\n throw new TypeError(`Expected the \\`options.agent\\` properties to be \\`http\\`, \\`https\\` or \\`http2\\`, got \\`${key}\\``);\n }\n }\n }\n options.maxRedirects = (_e = options.maxRedirects) !== null && _e !== void 0 ? _e : 0;\n // Set non-enumerable properties\n exports.setNonEnumerableProperties([defaults, rawOptions], options);\n return normalize_arguments_1.default(options, defaults);\n }\n _lockWrite() {\n const onLockedWrite = () => {\n throw new TypeError('The payload has been already provided');\n };\n this.write = onLockedWrite;\n this.end = onLockedWrite;\n }\n _unlockWrite() {\n this.write = super.write;\n this.end = super.end;\n }\n async _finalizeBody() {\n const { options } = this;\n const { headers } = options;\n const isForm = !is_1.default.undefined(options.form);\n const isJSON = !is_1.default.undefined(options.json);\n const isBody = !is_1.default.undefined(options.body);\n const hasPayload = isForm || isJSON || isBody;\n const cannotHaveBody = exports.withoutBody.has(options.method) && !(options.method === 'GET' && options.allowGetBody);\n this._cannotHaveBody = cannotHaveBody;\n if (hasPayload) {\n if (cannotHaveBody) {\n throw new TypeError(`The \\`${options.method}\\` method cannot be used with a body`);\n }\n if ([isBody, isForm, isJSON].filter(isTrue => isTrue).length > 1) {\n throw new TypeError('The `body`, `json` and `form` options are mutually exclusive');\n }\n if (isBody &&\n !(options.body instanceof stream_1.Readable) &&\n !is_1.default.string(options.body) &&\n !is_1.default.buffer(options.body) &&\n !is_form_data_1.default(options.body)) {\n throw new TypeError('The `body` option must be a stream.Readable, string or Buffer');\n }\n if (isForm && !is_1.default.object(options.form)) {\n throw new TypeError('The `form` option must be an Object');\n }\n {\n // Serialize body\n const noContentType = !is_1.default.string(headers['content-type']);\n if (isBody) {\n // Special case for https://github.com/form-data/form-data\n if (is_form_data_1.default(options.body) && noContentType) {\n headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`;\n }\n this[kBody] = options.body;\n }\n else if (isForm) {\n if (noContentType) {\n headers['content-type'] = 'application/x-www-form-urlencoded';\n }\n this[kBody] = (new url_1.URLSearchParams(options.form)).toString();\n }\n else {\n if (noContentType) {\n headers['content-type'] = 'application/json';\n }\n this[kBody] = options.stringifyJson(options.json);\n }\n const uploadBodySize = await get_body_size_1.default(this[kBody], options.headers);\n // See https://tools.ietf.org/html/rfc7230#section-3.3.2\n // A user agent SHOULD send a Content-Length in a request message when\n // no Transfer-Encoding is sent and the request method defines a meaning\n // for an enclosed payload body. For example, a Content-Length header\n // field is normally sent in a POST request even when the value is 0\n // (indicating an empty payload body). A user agent SHOULD NOT send a\n // Content-Length header field when the request message does not contain\n // a payload body and the method semantics do not anticipate such a\n // body.\n if (is_1.default.undefined(headers['content-length']) && is_1.default.undefined(headers['transfer-encoding'])) {\n if (!cannotHaveBody && !is_1.default.undefined(uploadBodySize)) {\n headers['content-length'] = String(uploadBodySize);\n }\n }\n }\n }\n else if (cannotHaveBody) {\n this._lockWrite();\n }\n else {\n this._unlockWrite();\n }\n this[kBodySize] = Number(headers['content-length']) || undefined;\n }\n async _onResponseBase(response) {\n const { options } = this;\n const { url } = options;\n this[kOriginalResponse] = response;\n if (options.decompress) {\n response = decompressResponse(response);\n }\n const statusCode = response.statusCode;\n const typedResponse = response;\n typedResponse.statusMessage = typedResponse.statusMessage ? typedResponse.statusMessage : http.STATUS_CODES[statusCode];\n typedResponse.url = options.url.toString();\n typedResponse.requestUrl = this.requestUrl;\n typedResponse.redirectUrls = this.redirects;\n typedResponse.request = this;\n typedResponse.isFromCache = response.fromCache || false;\n typedResponse.ip = this.ip;\n typedResponse.retryCount = this.retryCount;\n this[kIsFromCache] = typedResponse.isFromCache;\n this[kResponseSize] = Number(response.headers['content-length']) || undefined;\n this[kResponse] = response;\n response.once('end', () => {\n this[kResponseSize] = this[kDownloadedSize];\n this.emit('downloadProgress', this.downloadProgress);\n });\n response.once('error', (error) => {\n // Force clean-up, because some packages don't do this.\n // TODO: Fix decompress-response\n response.destroy();\n this._beforeError(new ReadError(error, this));\n });\n response.once('aborted', () => {\n this._beforeError(new ReadError({\n name: 'Error',\n message: 'The server aborted pending request',\n code: 'ECONNRESET'\n }, this));\n });\n this.emit('downloadProgress', this.downloadProgress);\n const rawCookies = response.headers['set-cookie'];\n if (is_1.default.object(options.cookieJar) && rawCookies) {\n let promises = rawCookies.map(async (rawCookie) => options.cookieJar.setCookie(rawCookie, url.toString()));\n if (options.ignoreInvalidCookies) {\n promises = promises.map(async (p) => p.catch(() => { }));\n }\n try {\n await Promise.all(promises);\n }\n catch (error) {\n this._beforeError(error);\n return;\n }\n }\n if (options.followRedirect && response.headers.location && redirectCodes.has(statusCode)) {\n // We're being redirected, we don't care about the response.\n // It'd be best to abort the request, but we can't because\n // we would have to sacrifice the TCP connection. We don't want that.\n response.resume();\n if (this[kRequest]) {\n this[kCancelTimeouts]();\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this[kRequest];\n this[kUnproxyEvents]();\n }\n const shouldBeGet = statusCode === 303 && options.method !== 'GET' && options.method !== 'HEAD';\n if (shouldBeGet || !options.methodRewriting) {\n // Server responded with \"see other\", indicating that the resource exists at another location,\n // and the client should request it from that location via GET or HEAD.\n options.method = 'GET';\n if ('body' in options) {\n delete options.body;\n }\n if ('json' in options) {\n delete options.json;\n }\n if ('form' in options) {\n delete options.form;\n }\n this[kBody] = undefined;\n delete options.headers['content-length'];\n }\n if (this.redirects.length >= options.maxRedirects) {\n this._beforeError(new MaxRedirectsError(this));\n return;\n }\n try {\n // Do not remove. See https://github.com/sindresorhus/got/pull/214\n const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString();\n // Handles invalid URLs. See https://github.com/sindresorhus/got/issues/604\n const redirectUrl = new url_1.URL(redirectBuffer, url);\n const redirectString = redirectUrl.toString();\n decodeURI(redirectString);\n // Redirecting to a different site, clear sensitive data.\n if (redirectUrl.hostname !== url.hostname || redirectUrl.port !== url.port) {\n if ('host' in options.headers) {\n delete options.headers.host;\n }\n if ('cookie' in options.headers) {\n delete options.headers.cookie;\n }\n if ('authorization' in options.headers) {\n delete options.headers.authorization;\n }\n if (options.username || options.password) {\n options.username = '';\n options.password = '';\n }\n }\n else {\n redirectUrl.username = options.username;\n redirectUrl.password = options.password;\n }\n this.redirects.push(redirectString);\n options.url = redirectUrl;\n for (const hook of options.hooks.beforeRedirect) {\n // eslint-disable-next-line no-await-in-loop\n await hook(options, typedResponse);\n }\n this.emit('redirect', typedResponse, options);\n await this._makeRequest();\n }\n catch (error) {\n this._beforeError(error);\n return;\n }\n return;\n }\n if (options.isStream && options.throwHttpErrors && !is_response_ok_1.isResponseOk(typedResponse)) {\n this._beforeError(new HTTPError(typedResponse));\n return;\n }\n response.on('readable', () => {\n if (this[kTriggerRead]) {\n this._read();\n }\n });\n this.on('resume', () => {\n response.resume();\n });\n this.on('pause', () => {\n response.pause();\n });\n response.once('end', () => {\n this.push(null);\n });\n this.emit('response', response);\n for (const destination of this[kServerResponsesPiped]) {\n if (destination.headersSent) {\n continue;\n }\n // eslint-disable-next-line guard-for-in\n for (const key in response.headers) {\n const isAllowed = options.decompress ? key !== 'content-encoding' : true;\n const value = response.headers[key];\n if (isAllowed) {\n destination.setHeader(key, value);\n }\n }\n destination.statusCode = statusCode;\n }\n }\n async _onResponse(response) {\n try {\n await this._onResponseBase(response);\n }\n catch (error) {\n /* istanbul ignore next: better safe than sorry */\n this._beforeError(error);\n }\n }\n _onRequest(request) {\n const { options } = this;\n const { timeout, url } = options;\n http_timer_1.default(request);\n this[kCancelTimeouts] = timed_out_1.default(request, timeout, url);\n const responseEventName = options.cache ? 'cacheableResponse' : 'response';\n request.once(responseEventName, (response) => {\n void this._onResponse(response);\n });\n request.once('error', (error) => {\n var _a;\n // Force clean-up, because some packages (e.g. nock) don't do this.\n request.destroy();\n // Node.js <= 12.18.2 mistakenly emits the response `end` first.\n (_a = request.res) === null || _a === void 0 ? void 0 : _a.removeAllListeners('end');\n error = error instanceof timed_out_1.TimeoutError ? new TimeoutError(error, this.timings, this) : new RequestError(error.message, error, this);\n this._beforeError(error);\n });\n this[kUnproxyEvents] = proxy_events_1.default(request, this, proxiedRequestEvents);\n this[kRequest] = request;\n this.emit('uploadProgress', this.uploadProgress);\n // Send body\n const body = this[kBody];\n const currentRequest = this.redirects.length === 0 ? this : request;\n if (is_1.default.nodeStream(body)) {\n body.pipe(currentRequest);\n body.once('error', (error) => {\n this._beforeError(new UploadError(error, this));\n });\n }\n else {\n this._unlockWrite();\n if (!is_1.default.undefined(body)) {\n this._writeRequest(body, undefined, () => { });\n currentRequest.end();\n this._lockWrite();\n }\n else if (this._cannotHaveBody || this._noPipe) {\n currentRequest.end();\n this._lockWrite();\n }\n }\n this.emit('request', request);\n }\n async _createCacheableRequest(url, options) {\n return new Promise((resolve, reject) => {\n // TODO: Remove `utils/url-to-options.ts` when `cacheable-request` is fixed\n Object.assign(options, url_to_options_1.default(url));\n // `http-cache-semantics` checks this\n // TODO: Fix this ignore.\n // @ts-expect-error\n delete options.url;\n let request;\n // This is ugly\n const cacheRequest = cacheableStore.get(options.cache)(options, async (response) => {\n // TODO: Fix `cacheable-response`\n response._readableState.autoDestroy = false;\n if (request) {\n (await request).emit('cacheableResponse', response);\n }\n resolve(response);\n });\n // Restore options\n options.url = url;\n cacheRequest.once('error', reject);\n cacheRequest.once('request', async (requestOrPromise) => {\n request = requestOrPromise;\n resolve(request);\n });\n });\n }\n async _makeRequest() {\n var _a, _b, _c, _d, _e;\n const { options } = this;\n const { headers } = options;\n for (const key in headers) {\n if (is_1.default.undefined(headers[key])) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete headers[key];\n }\n else if (is_1.default.null_(headers[key])) {\n throw new TypeError(`Use \\`undefined\\` instead of \\`null\\` to delete the \\`${key}\\` header`);\n }\n }\n if (options.decompress && is_1.default.undefined(headers['accept-encoding'])) {\n headers['accept-encoding'] = supportsBrotli ? 'gzip, deflate, br' : 'gzip, deflate';\n }\n // Set cookies\n if (options.cookieJar) {\n const cookieString = await options.cookieJar.getCookieString(options.url.toString());\n if (is_1.default.nonEmptyString(cookieString)) {\n options.headers.cookie = cookieString;\n }\n }\n for (const hook of options.hooks.beforeRequest) {\n // eslint-disable-next-line no-await-in-loop\n const result = await hook(options);\n if (!is_1.default.undefined(result)) {\n // @ts-expect-error Skip the type mismatch to support abstract responses\n options.request = () => result;\n break;\n }\n }\n if (options.body && this[kBody] !== options.body) {\n this[kBody] = options.body;\n }\n const { agent, request, timeout, url } = options;\n if (options.dnsCache && !('lookup' in options)) {\n options.lookup = options.dnsCache.lookup;\n }\n // UNIX sockets\n if (url.hostname === 'unix') {\n const matches = /(?<socketPath>.+?):(?<path>.+)/.exec(`${url.pathname}${url.search}`);\n if (matches === null || matches === void 0 ? void 0 : matches.groups) {\n const { socketPath, path } = matches.groups;\n Object.assign(options, {\n socketPath,\n path,\n host: ''\n });\n }\n }\n const isHttps = url.protocol === 'https:';\n // Fallback function\n let fallbackFn;\n if (options.http2) {\n fallbackFn = http2wrapper.auto;\n }\n else {\n fallbackFn = isHttps ? https.request : http.request;\n }\n const realFn = (_a = options.request) !== null && _a !== void 0 ? _a : fallbackFn;\n // Cache support\n const fn = options.cache ? this._createCacheableRequest : realFn;\n // Pass an agent directly when HTTP2 is disabled\n if (agent && !options.http2) {\n options.agent = agent[isHttps ? 'https' : 'http'];\n }\n // Prepare plain HTTP request options\n options[kRequest] = realFn;\n delete options.request;\n // TODO: Fix this ignore.\n // @ts-expect-error\n delete options.timeout;\n const requestOptions = options;\n requestOptions.shared = (_b = options.cacheOptions) === null || _b === void 0 ? void 0 : _b.shared;\n requestOptions.cacheHeuristic = (_c = options.cacheOptions) === null || _c === void 0 ? void 0 : _c.cacheHeuristic;\n requestOptions.immutableMinTimeToLive = (_d = options.cacheOptions) === null || _d === void 0 ? void 0 : _d.immutableMinTimeToLive;\n requestOptions.ignoreCargoCult = (_e = options.cacheOptions) === null || _e === void 0 ? void 0 : _e.ignoreCargoCult;\n // If `dnsLookupIpVersion` is not present do not override `family`\n if (options.dnsLookupIpVersion !== undefined) {\n try {\n requestOptions.family = dns_ip_version_1.dnsLookupIpVersionToFamily(options.dnsLookupIpVersion);\n }\n catch (_f) {\n throw new Error('Invalid `dnsLookupIpVersion` option value');\n }\n }\n // HTTPS options remapping\n if (options.https) {\n if ('rejectUnauthorized' in options.https) {\n requestOptions.rejectUnauthorized = options.https.rejectUnauthorized;\n }\n if (options.https.checkServerIdentity) {\n requestOptions.checkServerIdentity = options.https.checkServerIdentity;\n }\n if (options.https.certificateAuthority) {\n requestOptions.ca = options.https.certificateAuthority;\n }\n if (options.https.certificate) {\n requestOptions.cert = options.https.certificate;\n }\n if (options.https.key) {\n requestOptions.key = options.https.key;\n }\n if (options.https.passphrase) {\n requestOptions.passphrase = options.https.passphrase;\n }\n if (options.https.pfx) {\n requestOptions.pfx = options.https.pfx;\n }\n }\n try {\n let requestOrResponse = await fn(url, requestOptions);\n if (is_1.default.undefined(requestOrResponse)) {\n requestOrResponse = fallbackFn(url, requestOptions);\n }\n // Restore options\n options.request = request;\n options.timeout = timeout;\n options.agent = agent;\n // HTTPS options restore\n if (options.https) {\n if ('rejectUnauthorized' in options.https) {\n delete requestOptions.rejectUnauthorized;\n }\n if (options.https.checkServerIdentity) {\n // @ts-expect-error - This one will be removed when we remove the alias.\n delete requestOptions.checkServerIdentity;\n }\n if (options.https.certificateAuthority) {\n delete requestOptions.ca;\n }\n if (options.https.certificate) {\n delete requestOptions.cert;\n }\n if (options.https.key) {\n delete requestOptions.key;\n }\n if (options.https.passphrase) {\n delete requestOptions.passphrase;\n }\n if (options.https.pfx) {\n delete requestOptions.pfx;\n }\n }\n if (isClientRequest(requestOrResponse)) {\n this._onRequest(requestOrResponse);\n // Emit the response after the stream has been ended\n }\n else if (this.writable) {\n this.once('finish', () => {\n void this._onResponse(requestOrResponse);\n });\n this._unlockWrite();\n this.end();\n this._lockWrite();\n }\n else {\n void this._onResponse(requestOrResponse);\n }\n }\n catch (error) {\n if (error instanceof CacheableRequest.CacheError) {\n throw new CacheError(error, this);\n }\n throw new RequestError(error.message, error, this);\n }\n }\n async _error(error) {\n try {\n for (const hook of this.options.hooks.beforeError) {\n // eslint-disable-next-line no-await-in-loop\n error = await hook(error);\n }\n }\n catch (error_) {\n error = new RequestError(error_.message, error_, this);\n }\n this.destroy(error);\n }\n _beforeError(error) {\n if (this[kStopReading]) {\n return;\n }\n const { options } = this;\n const retryCount = this.retryCount + 1;\n this[kStopReading] = true;\n if (!(error instanceof RequestError)) {\n error = new RequestError(error.message, error, this);\n }\n const typedError = error;\n const { response } = typedError;\n void (async () => {\n if (response && !response.body) {\n response.setEncoding(this._readableState.encoding);\n try {\n response.rawBody = await get_buffer_1.default(response);\n response.body = response.rawBody.toString();\n }\n catch (_a) { }\n }\n if (this.listenerCount('retry') !== 0) {\n let backoff;\n try {\n let retryAfter;\n if (response && 'retry-after' in response.headers) {\n retryAfter = Number(response.headers['retry-after']);\n if (Number.isNaN(retryAfter)) {\n retryAfter = Date.parse(response.headers['retry-after']) - Date.now();\n if (retryAfter <= 0) {\n retryAfter = 1;\n }\n }\n else {\n retryAfter *= 1000;\n }\n }\n backoff = await options.retry.calculateDelay({\n attemptCount: retryCount,\n retryOptions: options.retry,\n error: typedError,\n retryAfter,\n computedValue: calculate_retry_delay_1.default({\n attemptCount: retryCount,\n retryOptions: options.retry,\n error: typedError,\n retryAfter,\n computedValue: 0\n })\n });\n }\n catch (error_) {\n void this._error(new RequestError(error_.message, error_, this));\n return;\n }\n if (backoff) {\n const retry = async () => {\n try {\n for (const hook of this.options.hooks.beforeRetry) {\n // eslint-disable-next-line no-await-in-loop\n await hook(this.options, typedError, retryCount);\n }\n }\n catch (error_) {\n void this._error(new RequestError(error_.message, error, this));\n return;\n }\n // Something forced us to abort the retry\n if (this.destroyed) {\n return;\n }\n this.destroy();\n this.emit('retry', retryCount, error);\n };\n this[kRetryTimeout] = setTimeout(retry, backoff);\n return;\n }\n }\n void this._error(typedError);\n })();\n }\n _read() {\n this[kTriggerRead] = true;\n const response = this[kResponse];\n if (response && !this[kStopReading]) {\n // We cannot put this in the `if` above\n // because `.read()` also triggers the `end` event\n if (response.readableLength) {\n this[kTriggerRead] = false;\n }\n let data;\n while ((data = response.read()) !== null) {\n this[kDownloadedSize] += data.length;\n this[kStartedReading] = true;\n const progress = this.downloadProgress;\n if (progress.percent < 1) {\n this.emit('downloadProgress', progress);\n }\n this.push(data);\n }\n }\n }\n // Node.js 12 has incorrect types, so the encoding must be a string\n _write(chunk, encoding, callback) {\n const write = () => {\n this._writeRequest(chunk, encoding, callback);\n };\n if (this.requestInitialized) {\n write();\n }\n else {\n this[kJobs].push(write);\n }\n }\n _writeRequest(chunk, encoding, callback) {\n if (this[kRequest].destroyed) {\n // Probably the `ClientRequest` instance will throw\n return;\n }\n this._progressCallbacks.push(() => {\n this[kUploadedSize] += Buffer.byteLength(chunk, encoding);\n const progress = this.uploadProgress;\n if (progress.percent < 1) {\n this.emit('uploadProgress', progress);\n }\n });\n // TODO: What happens if it's from cache? Then this[kRequest] won't be defined.\n this[kRequest].write(chunk, encoding, (error) => {\n if (!error && this._progressCallbacks.length > 0) {\n this._progressCallbacks.shift()();\n }\n callback(error);\n });\n }\n _final(callback) {\n const endRequest = () => {\n // FIX: Node.js 10 calls the write callback AFTER the end callback!\n while (this._progressCallbacks.length !== 0) {\n this._progressCallbacks.shift()();\n }\n // We need to check if `this[kRequest]` is present,\n // because it isn't when we use cache.\n if (!(kRequest in this)) {\n callback();\n return;\n }\n if (this[kRequest].destroyed) {\n callback();\n return;\n }\n this[kRequest].end((error) => {\n if (!error) {\n this[kBodySize] = this[kUploadedSize];\n this.emit('uploadProgress', this.uploadProgress);\n this[kRequest].emit('upload-complete');\n }\n callback(error);\n });\n };\n if (this.requestInitialized) {\n endRequest();\n }\n else {\n this[kJobs].push(endRequest);\n }\n }\n _destroy(error, callback) {\n var _a;\n this[kStopReading] = true;\n // Prevent further retries\n clearTimeout(this[kRetryTimeout]);\n if (kRequest in this) {\n this[kCancelTimeouts]();\n // TODO: Remove the next `if` when these get fixed:\n // - https://github.com/nodejs/node/issues/32851\n if (!((_a = this[kResponse]) === null || _a === void 0 ? void 0 : _a.complete)) {\n this[kRequest].destroy();\n }\n }\n if (error !== null && !is_1.default.undefined(error) && !(error instanceof RequestError)) {\n error = new RequestError(error.message, error, this);\n }\n callback(error);\n }\n get _isAboutToError() {\n return this[kStopReading];\n }\n /**\n The remote IP address.\n */\n get ip() {\n var _a;\n return (_a = this.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress;\n }\n /**\n Indicates whether the request has been aborted or not.\n */\n get aborted() {\n var _a, _b, _c;\n return ((_b = (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.destroyed) !== null && _b !== void 0 ? _b : this.destroyed) && !((_c = this[kOriginalResponse]) === null || _c === void 0 ? void 0 : _c.complete);\n }\n get socket() {\n var _a, _b;\n return (_b = (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.socket) !== null && _b !== void 0 ? _b : undefined;\n }\n /**\n Progress event for downloading (receiving a response).\n */\n get downloadProgress() {\n let percent;\n if (this[kResponseSize]) {\n percent = this[kDownloadedSize] / this[kResponseSize];\n }\n else if (this[kResponseSize] === this[kDownloadedSize]) {\n percent = 1;\n }\n else {\n percent = 0;\n }\n return {\n percent,\n transferred: this[kDownloadedSize],\n total: this[kResponseSize]\n };\n }\n /**\n Progress event for uploading (sending a request).\n */\n get uploadProgress() {\n let percent;\n if (this[kBodySize]) {\n percent = this[kUploadedSize] / this[kBodySize];\n }\n else if (this[kBodySize] === this[kUploadedSize]) {\n percent = 1;\n }\n else {\n percent = 0;\n }\n return {\n percent,\n transferred: this[kUploadedSize],\n total: this[kBodySize]\n };\n }\n /**\n The object contains the following properties:\n\n - `start` - Time when the request started.\n - `socket` - Time when a socket was assigned to the request.\n - `lookup` - Time when the DNS lookup finished.\n - `connect` - Time when the socket successfully connected.\n - `secureConnect` - Time when the socket securely connected.\n - `upload` - Time when the request finished uploading.\n - `response` - Time when the request fired `response` event.\n - `end` - Time when the response fired `end` event.\n - `error` - Time when the request fired `error` event.\n - `abort` - Time when the request fired `abort` event.\n - `phases`\n - `wait` - `timings.socket - timings.start`\n - `dns` - `timings.lookup - timings.socket`\n - `tcp` - `timings.connect - timings.lookup`\n - `tls` - `timings.secureConnect - timings.connect`\n - `request` - `timings.upload - (timings.secureConnect || timings.connect)`\n - `firstByte` - `timings.response - timings.upload`\n - `download` - `timings.end - timings.response`\n - `total` - `(timings.end || timings.error || timings.abort) - timings.start`\n\n If something has not been measured yet, it will be `undefined`.\n\n __Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch.\n */\n get timings() {\n var _a;\n return (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.timings;\n }\n /**\n Whether the response was retrieved from the cache.\n */\n get isFromCache() {\n return this[kIsFromCache];\n }\n pipe(destination, options) {\n if (this[kStartedReading]) {\n throw new Error('Failed to pipe. The response has been emitted already.');\n }\n if (destination instanceof http_1.ServerResponse) {\n this[kServerResponsesPiped].add(destination);\n }\n return super.pipe(destination, options);\n }\n unpipe(destination) {\n if (destination instanceof http_1.ServerResponse) {\n this[kServerResponsesPiped].delete(destination);\n }\n super.unpipe(destination);\n return this;\n }\n}\nexports.default = Request;\n", "\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CancelError = exports.ParseError = void 0;\nconst core_1 = require(\"../core\");\n/**\nAn error to be thrown when server response code is 2xx, and parsing body fails.\nIncludes a `response` property.\n*/\nclass ParseError extends core_1.RequestError {\n constructor(error, response) {\n const { options } = response.request;\n super(`${error.message} in \"${options.url.toString()}\"`, error, response.request);\n this.name = 'ParseError';\n }\n}\nexports.ParseError = ParseError;\n/**\nAn error to be thrown when the request is aborted with `.cancel()`.\n*/\nclass CancelError extends core_1.RequestError {\n constructor(request) {\n super('Promise was canceled', {}, request);\n this.name = 'CancelError';\n }\n get isCanceled() {\n return true;\n }\n}\nexports.CancelError = CancelError;\n__exportStar(require(\"../core\"), exports);\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst types_1 = require(\"./types\");\nconst parseBody = (response, responseType, parseJson, encoding) => {\n const { rawBody } = response;\n try {\n if (responseType === 'text') {\n return rawBody.toString(encoding);\n }\n if (responseType === 'json') {\n return rawBody.length === 0 ? '' : parseJson(rawBody.toString());\n }\n if (responseType === 'buffer') {\n return rawBody;\n }\n throw new types_1.ParseError({\n message: `Unknown body type '${responseType}'`,\n name: 'Error'\n }, response);\n }\n catch (error) {\n throw new types_1.ParseError(error, response);\n }\n};\nexports.default = parseBody;\n", "\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst events_1 = require(\"events\");\nconst is_1 = require(\"@sindresorhus/is\");\nconst PCancelable = require(\"p-cancelable\");\nconst types_1 = require(\"./types\");\nconst parse_body_1 = require(\"./parse-body\");\nconst core_1 = require(\"../core\");\nconst proxy_events_1 = require(\"../core/utils/proxy-events\");\nconst get_buffer_1 = require(\"../core/utils/get-buffer\");\nconst is_response_ok_1 = require(\"../core/utils/is-response-ok\");\nconst proxiedRequestEvents = [\n 'request',\n 'response',\n 'redirect',\n 'uploadProgress',\n 'downloadProgress'\n];\nfunction asPromise(normalizedOptions) {\n let globalRequest;\n let globalResponse;\n const emitter = new events_1.EventEmitter();\n const promise = new PCancelable((resolve, reject, onCancel) => {\n const makeRequest = (retryCount) => {\n const request = new core_1.default(undefined, normalizedOptions);\n request.retryCount = retryCount;\n request._noPipe = true;\n onCancel(() => request.destroy());\n onCancel.shouldReject = false;\n onCancel(() => reject(new types_1.CancelError(request)));\n globalRequest = request;\n request.once('response', async (response) => {\n var _a;\n response.retryCount = retryCount;\n if (response.request.aborted) {\n // Canceled while downloading - will throw a `CancelError` or `TimeoutError` error\n return;\n }\n // Download body\n let rawBody;\n try {\n rawBody = await get_buffer_1.default(request);\n response.rawBody = rawBody;\n }\n catch (_b) {\n // The same error is caught below.\n // See request.once('error')\n return;\n }\n if (request._isAboutToError) {\n return;\n }\n // Parse body\n const contentEncoding = ((_a = response.headers['content-encoding']) !== null && _a !== void 0 ? _a : '').toLowerCase();\n const isCompressed = ['gzip', 'deflate', 'br'].includes(contentEncoding);\n const { options } = request;\n if (isCompressed && !options.decompress) {\n response.body = rawBody;\n }\n else {\n try {\n response.body = parse_body_1.default(response, options.responseType, options.parseJson, options.encoding);\n }\n catch (error) {\n // Fallback to `utf8`\n response.body = rawBody.toString();\n if (is_response_ok_1.isResponseOk(response)) {\n request._beforeError(error);\n return;\n }\n }\n }\n try {\n for (const [index, hook] of options.hooks.afterResponse.entries()) {\n // @ts-expect-error TS doesn't notice that CancelableRequest is a Promise\n // eslint-disable-next-line no-await-in-loop\n response = await hook(response, async (updatedOptions) => {\n const typedOptions = core_1.default.normalizeArguments(undefined, {\n ...updatedOptions,\n retry: {\n calculateDelay: () => 0\n },\n throwHttpErrors: false,\n resolveBodyOnly: false\n }, options);\n // Remove any further hooks for that request, because we'll call them anyway.\n // The loop continues. We don't want duplicates (asPromise recursion).\n typedOptions.hooks.afterResponse = typedOptions.hooks.afterResponse.slice(0, index);\n for (const hook of typedOptions.hooks.beforeRetry) {\n // eslint-disable-next-line no-await-in-loop\n await hook(typedOptions);\n }\n const promise = asPromise(typedOptions);\n onCancel(() => {\n promise.catch(() => { });\n promise.cancel();\n });\n return promise;\n });\n }\n }\n catch (error) {\n request._beforeError(new types_1.RequestError(error.message, error, request));\n return;\n }\n if (!is_response_ok_1.isResponseOk(response)) {\n request._beforeError(new types_1.HTTPError(response));\n return;\n }\n globalResponse = response;\n resolve(request.options.resolveBodyOnly ? response.body : response);\n });\n const onError = (error) => {\n if (promise.isCanceled) {\n return;\n }\n const { options } = request;\n if (error instanceof types_1.HTTPError && !options.throwHttpErrors) {\n const { response } = error;\n resolve(request.options.resolveBodyOnly ? response.body : response);\n return;\n }\n reject(error);\n };\n request.once('error', onError);\n const previousBody = request.options.body;\n request.once('retry', (newRetryCount, error) => {\n var _a, _b;\n if (previousBody === ((_a = error.request) === null || _a === void 0 ? void 0 : _a.options.body) && is_1.default.nodeStream((_b = error.request) === null || _b === void 0 ? void 0 : _b.options.body)) {\n onError(error);\n return;\n }\n makeRequest(newRetryCount);\n });\n proxy_events_1.default(request, emitter, proxiedRequestEvents);\n };\n makeRequest(0);\n });\n promise.on = (event, fn) => {\n emitter.on(event, fn);\n return promise;\n };\n const shortcut = (responseType) => {\n const newPromise = (async () => {\n // Wait until downloading has ended\n await promise;\n const { options } = globalResponse.request;\n return parse_body_1.default(globalResponse, responseType, options.parseJson, options.encoding);\n })();\n Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise));\n return newPromise;\n };\n promise.json = () => {\n const { headers } = globalRequest.options;\n if (!globalRequest.writableFinished && headers.accept === undefined) {\n headers.accept = 'application/json';\n }\n return shortcut('json');\n };\n promise.buffer = () => shortcut('buffer');\n promise.text = () => shortcut('text');\n return promise;\n}\nexports.default = asPromise;\n__exportStar(require(\"./types\"), exports);\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst types_1 = require(\"./types\");\nfunction createRejection(error, ...beforeErrorGroups) {\n const promise = (async () => {\n if (error instanceof types_1.RequestError) {\n try {\n for (const hooks of beforeErrorGroups) {\n if (hooks) {\n for (const hook of hooks) {\n // eslint-disable-next-line no-await-in-loop\n error = await hook(error);\n }\n }\n }\n }\n catch (error_) {\n error = error_;\n }\n }\n throw error;\n })();\n const returnPromise = () => promise;\n promise.json = returnPromise;\n promise.text = returnPromise;\n promise.buffer = returnPromise;\n promise.on = returnPromise;\n return promise;\n}\nexports.default = createRejection;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst is_1 = require(\"@sindresorhus/is\");\nfunction deepFreeze(object) {\n for (const value of Object.values(object)) {\n if (is_1.default.plainObject(value) || is_1.default.array(value)) {\n deepFreeze(value);\n }\n }\n return Object.freeze(object);\n}\nexports.default = deepFreeze;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n", "\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.defaultHandler = void 0;\nconst is_1 = require(\"@sindresorhus/is\");\nconst as_promise_1 = require(\"./as-promise\");\nconst create_rejection_1 = require(\"./as-promise/create-rejection\");\nconst core_1 = require(\"./core\");\nconst deep_freeze_1 = require(\"./utils/deep-freeze\");\nconst errors = {\n RequestError: as_promise_1.RequestError,\n CacheError: as_promise_1.CacheError,\n ReadError: as_promise_1.ReadError,\n HTTPError: as_promise_1.HTTPError,\n MaxRedirectsError: as_promise_1.MaxRedirectsError,\n TimeoutError: as_promise_1.TimeoutError,\n ParseError: as_promise_1.ParseError,\n CancelError: as_promise_1.CancelError,\n UnsupportedProtocolError: as_promise_1.UnsupportedProtocolError,\n UploadError: as_promise_1.UploadError\n};\n// The `delay` package weighs 10KB (!)\nconst delay = async (ms) => new Promise(resolve => {\n setTimeout(resolve, ms);\n});\nconst { normalizeArguments } = core_1.default;\nconst mergeOptions = (...sources) => {\n let mergedOptions;\n for (const source of sources) {\n mergedOptions = normalizeArguments(undefined, source, mergedOptions);\n }\n return mergedOptions;\n};\nconst getPromiseOrStream = (options) => options.isStream ? new core_1.default(undefined, options) : as_promise_1.default(options);\nconst isGotInstance = (value) => ('defaults' in value && 'options' in value.defaults);\nconst aliases = [\n 'get',\n 'post',\n 'put',\n 'patch',\n 'head',\n 'delete'\n];\nexports.defaultHandler = (options, next) => next(options);\nconst callInitHooks = (hooks, options) => {\n if (hooks) {\n for (const hook of hooks) {\n hook(options);\n }\n }\n};\nconst create = (defaults) => {\n // Proxy properties from next handlers\n defaults._rawHandlers = defaults.handlers;\n defaults.handlers = defaults.handlers.map(fn => ((options, next) => {\n // This will be assigned by assigning result\n let root;\n const result = fn(options, newOptions => {\n root = next(newOptions);\n return root;\n });\n if (result !== root && !options.isStream && root) {\n const typedResult = result;\n const { then: promiseThen, catch: promiseCatch, finally: promiseFianlly } = typedResult;\n Object.setPrototypeOf(typedResult, Object.getPrototypeOf(root));\n Object.defineProperties(typedResult, Object.getOwnPropertyDescriptors(root));\n // These should point to the new promise\n // eslint-disable-next-line promise/prefer-await-to-then\n typedResult.then = promiseThen;\n typedResult.catch = promiseCatch;\n typedResult.finally = promiseFianlly;\n }\n return result;\n }));\n // Got interface\n const got = ((url, options = {}, _defaults) => {\n var _a, _b;\n let iteration = 0;\n const iterateHandlers = (newOptions) => {\n return defaults.handlers[iteration++](newOptions, iteration === defaults.handlers.length ? getPromiseOrStream : iterateHandlers);\n };\n // TODO: Remove this in Got 12.\n if (is_1.default.plainObject(url)) {\n const mergedOptions = {\n ...url,\n ...options\n };\n core_1.setNonEnumerableProperties([url, options], mergedOptions);\n options = mergedOptions;\n url = undefined;\n }\n try {\n // Call `init` hooks\n let initHookError;\n try {\n callInitHooks(defaults.options.hooks.init, options);\n callInitHooks((_a = options.hooks) === null || _a === void 0 ? void 0 : _a.init, options);\n }\n catch (error) {\n initHookError = error;\n }\n // Normalize options & call handlers\n const normalizedOptions = normalizeArguments(url, options, _defaults !== null && _defaults !== void 0 ? _defaults : defaults.options);\n normalizedOptions[core_1.kIsNormalizedAlready] = true;\n if (initHookError) {\n throw new as_promise_1.RequestError(initHookError.message, initHookError, normalizedOptions);\n }\n return iterateHandlers(normalizedOptions);\n }\n catch (error) {\n if (options.isStream) {\n throw error;\n }\n else {\n return create_rejection_1.default(error, defaults.options.hooks.beforeError, (_b = options.hooks) === null || _b === void 0 ? void 0 : _b.beforeError);\n }\n }\n });\n got.extend = (...instancesOrOptions) => {\n const optionsArray = [defaults.options];\n let handlers = [...defaults._rawHandlers];\n let isMutableDefaults;\n for (const value of instancesOrOptions) {\n if (isGotInstance(value)) {\n optionsArray.push(value.defaults.options);\n handlers.push(...value.defaults._rawHandlers);\n isMutableDefaults = value.defaults.mutableDefaults;\n }\n else {\n optionsArray.push(value);\n if ('handlers' in value) {\n handlers.push(...value.handlers);\n }\n isMutableDefaults = value.mutableDefaults;\n }\n }\n handlers = handlers.filter(handler => handler !== exports.defaultHandler);\n if (handlers.length === 0) {\n handlers.push(exports.defaultHandler);\n }\n return create({\n options: mergeOptions(...optionsArray),\n handlers,\n mutableDefaults: Boolean(isMutableDefaults)\n });\n };\n // Pagination\n const paginateEach = (async function* (url, options) {\n // TODO: Remove this `@ts-expect-error` when upgrading to TypeScript 4.\n // Error: Argument of type 'Merge<Options, PaginationOptions<T, R>> | undefined' is not assignable to parameter of type 'Options | undefined'.\n // @ts-expect-error\n let normalizedOptions = normalizeArguments(url, options, defaults.options);\n normalizedOptions.resolveBodyOnly = false;\n const pagination = normalizedOptions.pagination;\n if (!is_1.default.object(pagination)) {\n throw new TypeError('`options.pagination` must be implemented');\n }\n const all = [];\n let { countLimit } = pagination;\n let numberOfRequests = 0;\n while (numberOfRequests < pagination.requestLimit) {\n if (numberOfRequests !== 0) {\n // eslint-disable-next-line no-await-in-loop\n await delay(pagination.backoff);\n }\n // @ts-expect-error FIXME!\n // TODO: Throw when result is not an instance of Response\n // eslint-disable-next-line no-await-in-loop\n const result = (await got(undefined, undefined, normalizedOptions));\n // eslint-disable-next-line no-await-in-loop\n const parsed = await pagination.transform(result);\n const current = [];\n for (const item of parsed) {\n if (pagination.filter(item, all, current)) {\n if (!pagination.shouldContinue(item, all, current)) {\n return;\n }\n yield item;\n if (pagination.stackAllItems) {\n all.push(item);\n }\n current.push(item);\n if (--countLimit <= 0) {\n return;\n }\n }\n }\n const optionsToMerge = pagination.paginate(result, all, current);\n if (optionsToMerge === false) {\n return;\n }\n if (optionsToMerge === result.request.options) {\n normalizedOptions = result.request.options;\n }\n else if (optionsToMerge !== undefined) {\n normalizedOptions = normalizeArguments(undefined, optionsToMerge, normalizedOptions);\n }\n numberOfRequests++;\n }\n });\n got.paginate = paginateEach;\n got.paginate.all = (async (url, options) => {\n const results = [];\n for await (const item of paginateEach(url, options)) {\n results.push(item);\n }\n return results;\n });\n // For those who like very descriptive names\n got.paginate.each = paginateEach;\n // Stream API\n got.stream = ((url, options) => got(url, { ...options, isStream: true }));\n // Shortcuts\n for (const method of aliases) {\n got[method] = ((url, options) => got(url, { ...options, method }));\n got.stream[method] = ((url, options) => {\n return got(url, { ...options, method, isStream: true });\n });\n }\n Object.assign(got, errors);\n Object.defineProperty(got, 'defaults', {\n value: defaults.mutableDefaults ? defaults : deep_freeze_1.default(defaults),\n writable: defaults.mutableDefaults,\n configurable: defaults.mutableDefaults,\n enumerable: true\n });\n got.mergeOptions = mergeOptions;\n return got;\n};\nexports.default = create;\n__exportStar(require(\"./types\"), exports);\n", "\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst url_1 = require(\"url\");\nconst create_1 = require(\"./create\");\nconst defaults = {\n options: {\n method: 'GET',\n retry: {\n limit: 2,\n methods: [\n 'GET',\n 'PUT',\n 'HEAD',\n 'DELETE',\n 'OPTIONS',\n 'TRACE'\n ],\n statusCodes: [\n 408,\n 413,\n 429,\n 500,\n 502,\n 503,\n 504,\n 521,\n 522,\n 524\n ],\n errorCodes: [\n 'ETIMEDOUT',\n 'ECONNRESET',\n 'EADDRINUSE',\n 'ECONNREFUSED',\n 'EPIPE',\n 'ENOTFOUND',\n 'ENETUNREACH',\n 'EAI_AGAIN'\n ],\n maxRetryAfter: undefined,\n calculateDelay: ({ computedValue }) => computedValue\n },\n timeout: {},\n headers: {\n 'user-agent': 'got (https://github.com/sindresorhus/got)'\n },\n hooks: {\n init: [],\n beforeRequest: [],\n beforeRedirect: [],\n beforeRetry: [],\n beforeError: [],\n afterResponse: []\n },\n cache: undefined,\n dnsCache: undefined,\n decompress: true,\n throwHttpErrors: true,\n followRedirect: true,\n isStream: false,\n responseType: 'text',\n resolveBodyOnly: false,\n maxRedirects: 10,\n prefixUrl: '',\n methodRewriting: true,\n ignoreInvalidCookies: false,\n context: {},\n // TODO: Set this to `true` when Got 12 gets released\n http2: false,\n allowGetBody: false,\n https: undefined,\n pagination: {\n transform: (response) => {\n if (response.request.options.responseType === 'json') {\n return response.body;\n }\n return JSON.parse(response.body);\n },\n paginate: response => {\n if (!Reflect.has(response.headers, 'link')) {\n return false;\n }\n const items = response.headers.link.split(',');\n let next;\n for (const item of items) {\n const parsed = item.split(';');\n if (parsed[1].includes('next')) {\n next = parsed[0].trimStart().trim();\n next = next.slice(1, -1);\n break;\n }\n }\n if (next) {\n const options = {\n url: new url_1.URL(next)\n };\n return options;\n }\n return false;\n },\n filter: () => true,\n shouldContinue: () => true,\n countLimit: Infinity,\n backoff: 0,\n requestLimit: 10000,\n stackAllItems: true\n },\n parseJson: (text) => JSON.parse(text),\n stringifyJson: (object) => JSON.stringify(object),\n cacheOptions: {}\n },\n handlers: [create_1.defaultHandler],\n mutableDefaults: false\n};\nconst got = create_1.default(defaults);\nexports.default = got;\n// For CommonJS default export support\nmodule.exports = got;\nmodule.exports.default = got;\nmodule.exports.__esModule = true; // Workaround for TS issue: https://github.com/sindresorhus/got/pull/1267\n__exportStar(require(\"./create\"), exports);\n__exportStar(require(\"./as-promise\"), exports);\n", "'use strict'\n\nfunction isFunction (funktion) {\n return typeof funktion === 'function'\n}\n\n// Default to complaining loudly when things don't go according to plan.\nvar logger = console.error.bind(console)\n\n// Sets a property on an object, preserving its enumerability.\n// This function assumes that the property is already writable.\nfunction defineProperty (obj, name, value) {\n var enumerable = !!obj[name] && obj.propertyIsEnumerable(name)\n Object.defineProperty(obj, name, {\n configurable: true,\n enumerable: enumerable,\n writable: true,\n value: value\n })\n}\n\n// Keep initialization idempotent.\nfunction shimmer (options) {\n if (options && options.logger) {\n if (!isFunction(options.logger)) logger(\"new logger isn't a function, not replacing\")\n else logger = options.logger\n }\n}\n\nfunction wrap (nodule, name, wrapper) {\n if (!nodule || !nodule[name]) {\n logger('no original function ' + name + ' to wrap')\n return\n }\n\n if (!wrapper) {\n logger('no wrapper function')\n logger((new Error()).stack)\n return\n }\n\n if (!isFunction(nodule[name]) || !isFunction(wrapper)) {\n logger('original object and wrapper must be functions')\n return\n }\n\n var original = nodule[name]\n var wrapped = wrapper(original, name)\n\n defineProperty(wrapped, '__original', original)\n defineProperty(wrapped, '__unwrap', function () {\n if (nodule[name] === wrapped) defineProperty(nodule, name, original)\n })\n defineProperty(wrapped, '__wrapped', true)\n\n defineProperty(nodule, name, wrapped)\n return wrapped\n}\n\nfunction massWrap (nodules, names, wrapper) {\n if (!nodules) {\n logger('must provide one or more modules to patch')\n logger((new Error()).stack)\n return\n } else if (!Array.isArray(nodules)) {\n nodules = [nodules]\n }\n\n if (!(names && Array.isArray(names))) {\n logger('must provide one or more functions to wrap on modules')\n return\n }\n\n nodules.forEach(function (nodule) {\n names.forEach(function (name) {\n wrap(nodule, name, wrapper)\n })\n })\n}\n\nfunction unwrap (nodule, name) {\n if (!nodule || !nodule[name]) {\n logger('no function to unwrap.')\n logger((new Error()).stack)\n return\n }\n\n if (!nodule[name].__unwrap) {\n logger('no original to unwrap to -- has ' + name + ' already been unwrapped?')\n } else {\n return nodule[name].__unwrap()\n }\n}\n\nfunction massUnwrap (nodules, names) {\n if (!nodules) {\n logger('must provide one or more modules to patch')\n logger((new Error()).stack)\n return\n } else if (!Array.isArray(nodules)) {\n nodules = [nodules]\n }\n\n if (!(names && Array.isArray(names))) {\n logger('must provide one or more functions to unwrap on modules')\n return\n }\n\n nodules.forEach(function (nodule) {\n names.forEach(function (name) {\n unwrap(nodule, name)\n })\n })\n}\n\nshimmer.wrap = wrap\nshimmer.massWrap = massWrap\nshimmer.unwrap = unwrap\nshimmer.massUnwrap = massUnwrap\n\nmodule.exports = shimmer\n", "'use strict';\n\nvar shimmer = require('shimmer');\nvar wrap = shimmer.wrap;\nvar unwrap = shimmer.unwrap;\n\n// Default to complaining loudly when things don't go according to plan.\n// dunderscores are boring\nvar SYMBOL = 'wrap@before';\n\n// Sets a property on an object, preserving its enumerability.\n// This function assumes that the property is already writable.\nfunction defineProperty(obj, name, value) {\n var enumerable = !!obj[name] && obj.propertyIsEnumerable(name);\n Object.defineProperty(obj, name, {\n configurable: true,\n enumerable: enumerable,\n writable: true,\n value: value\n });\n}\n\nfunction _process(self, listeners) {\n var l = listeners.length;\n for (var p = 0; p < l; p++) {\n var listener = listeners[p];\n // set up the listener so that onEmit can do whatever it needs\n var before = self[SYMBOL];\n if (typeof before === 'function') {\n before(listener);\n }\n else if (Array.isArray(before)) {\n var length = before.length;\n for (var i = 0; i < length; i++) before[i](listener);\n }\n }\n}\n\nfunction _listeners(self, event) {\n var listeners;\n listeners = self._events && self._events[event];\n if (!Array.isArray(listeners)) {\n if (listeners) {\n listeners = [listeners];\n }\n else {\n listeners = [];\n }\n }\n\n return listeners;\n}\n\nfunction _findAndProcess(self, event, before) {\n var after = _listeners(self, event);\n var unprocessed = after.filter(function(fn) { return before.indexOf(fn) === -1; });\n if (unprocessed.length > 0) _process(self, unprocessed);\n}\n\nfunction _wrap(unwrapped, visit) {\n if (!unwrapped) return;\n\n var wrapped = unwrapped;\n if (typeof unwrapped === 'function') {\n wrapped = visit(unwrapped);\n }\n else if (Array.isArray(unwrapped)) {\n wrapped = [];\n for (var i = 0; i < unwrapped.length; i++) {\n wrapped[i] = visit(unwrapped[i]);\n }\n }\n return wrapped;\n}\n\nmodule.exports = function wrapEmitter(emitter, onAddListener, onEmit) {\n if (!emitter || !emitter.on || !emitter.addListener ||\n !emitter.removeListener || !emitter.emit) {\n throw new Error(\"can only wrap real EEs\");\n }\n\n if (!onAddListener) throw new Error(\"must have function to run on listener addition\");\n if (!onEmit) throw new Error(\"must have function to wrap listeners when emitting\");\n\n /* Attach a context to a listener, and make sure that this hook stays\n * attached to the emitter forevermore.\n */\n function adding(on) {\n return function added(event, listener) {\n var existing = _listeners(this, event).slice();\n\n try {\n var returned = on.call(this, event, listener);\n _findAndProcess(this, event, existing);\n return returned;\n }\n finally {\n // old-style streaming overwrites .on and .addListener, so rewrap\n if (!this.on.__wrapped) wrap(this, 'on', adding);\n if (!this.addListener.__wrapped) wrap(this, 'addListener', adding);\n }\n };\n }\n\n function emitting(emit) {\n return function emitted(event) {\n if (!this._events || !this._events[event]) return emit.apply(this, arguments);\n\n var unwrapped = this._events[event];\n\n /* Ensure that if removeListener gets called, it's working with the\n * unwrapped listeners.\n */\n function remover(removeListener) {\n return function removed() {\n this._events[event] = unwrapped;\n try {\n return removeListener.apply(this, arguments);\n }\n finally {\n unwrapped = this._events[event];\n this._events[event] = _wrap(unwrapped, onEmit);\n }\n };\n }\n wrap(this, 'removeListener', remover);\n\n try {\n /* At emit time, ensure that whatever else is going on, removeListener will\n * still work while at the same time running whatever hooks are necessary to\n * make sure the listener is run in the correct context.\n */\n this._events[event] = _wrap(unwrapped, onEmit);\n return emit.apply(this, arguments);\n }\n finally {\n /* Ensure that regardless of what happens when preparing and running the\n * listeners, the status quo ante is restored before continuing.\n */\n unwrap(this, 'removeListener');\n this._events[event] = unwrapped;\n }\n };\n }\n\n // support multiple onAddListeners\n if (!emitter[SYMBOL]) {\n defineProperty(emitter, SYMBOL, onAddListener);\n }\n else if (typeof emitter[SYMBOL] === 'function') {\n defineProperty(emitter, SYMBOL, [emitter[SYMBOL], onAddListener]);\n }\n else if (Array.isArray(emitter[SYMBOL])) {\n emitter[SYMBOL].push(onAddListener);\n }\n\n // only wrap the core functions once\n if (!emitter.__wrapped) {\n wrap(emitter, 'addListener', adding);\n wrap(emitter, 'on', adding);\n wrap(emitter, 'emit', emitting);\n\n defineProperty(emitter, '__unwrap', function () {\n unwrap(emitter, 'addListener');\n unwrap(emitter, 'on');\n unwrap(emitter, 'emit');\n delete emitter[SYMBOL];\n delete emitter.__wrapped;\n });\n defineProperty(emitter, '__wrapped', true);\n }\n};\n", "/* eslint-disable max-len */\n'use strict';\n\nconst util = require('util');\nconst assert = require('assert');\nconst wrapEmitter = require('emitter-listener');\nconst async_hooks = require('async_hooks');\n\nconst CONTEXTS_SYMBOL = 'cls@contexts';\nconst ERROR_SYMBOL = 'error@context';\n\nconst DEBUG_CLS_HOOKED = process.env.DEBUG_CLS_HOOKED;\n\nlet currentUid = -1;\n\nmodule.exports = {\n getNamespace: getNamespace,\n createNamespace: createNamespace,\n destroyNamespace: destroyNamespace,\n reset: reset,\n ERROR_SYMBOL: ERROR_SYMBOL\n};\n\nfunction Namespace(name) {\n this.name = name;\n // changed in 2.7: no default context\n this.active = null;\n this._set = [];\n this.id = null;\n this._contexts = new Map();\n this._indent = 0;\n}\n\nNamespace.prototype.set = function set(key, value) {\n if (!this.active) {\n throw new Error('No context available. ns.run() or ns.bind() must be called first.');\n }\n\n this.active[key] = value;\n\n if (DEBUG_CLS_HOOKED) {\n const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent);\n debug2(indentStr + 'CONTEXT-SET KEY:' + key + '=' + value + ' in ns:' + this.name + ' currentUid:' + currentUid + ' active:' + util.inspect(this.active, {showHidden:true, depth:2, colors:true}));\n }\n\n return value;\n};\n\nNamespace.prototype.get = function get(key) {\n if (!this.active) {\n if (DEBUG_CLS_HOOKED) {\n const asyncHooksCurrentId = async_hooks.currentId();\n const triggerId = async_hooks.triggerAsyncId();\n const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent);\n //debug2(indentStr + 'CONTEXT-GETTING KEY NO ACTIVE NS:' + key + '=undefined' + ' (' + this.name + ') currentUid:' + currentUid + ' active:' + util.inspect(this.active, {showHidden:true, depth:2, colors:true}));\n debug2(`${indentStr}CONTEXT-GETTING KEY NO ACTIVE NS: (${this.name}) ${key}=undefined currentUid:${currentUid} asyncHooksCurrentId:${asyncHooksCurrentId} triggerId:${triggerId} len:${this._set.length}`);\n }\n return undefined;\n }\n if (DEBUG_CLS_HOOKED) {\n const asyncHooksCurrentId = async_hooks.executionAsyncId();\n const triggerId = async_hooks.triggerAsyncId();\n const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent);\n debug2(indentStr + 'CONTEXT-GETTING KEY:' + key + '=' + this.active[key] + ' (' + this.name + ') currentUid:' + currentUid + ' active:' + util.inspect(this.active, {showHidden:true, depth:2, colors:true}));\n debug2(`${indentStr}CONTEXT-GETTING KEY: (${this.name}) ${key}=${this.active[key]} currentUid:${currentUid} asyncHooksCurrentId:${asyncHooksCurrentId} triggerId:${triggerId} len:${this._set.length} active:${util.inspect(this.active)}`);\n }\n return this.active[key];\n};\n\nNamespace.prototype.createContext = function createContext() {\n // Prototype inherit existing context if created a new child context within existing context.\n let context = Object.create(this.active ? this.active : Object.prototype);\n context._ns_name = this.name;\n context.id = currentUid;\n\n if (DEBUG_CLS_HOOKED) {\n const asyncHooksCurrentId = async_hooks.executionAsyncId();\n const triggerId = async_hooks.triggerAsyncId();\n const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent);\n debug2(`${indentStr}CONTEXT-CREATED Context: (${this.name}) currentUid:${currentUid} asyncHooksCurrentId:${asyncHooksCurrentId} triggerId:${triggerId} len:${this._set.length} context:${util.inspect(context, {showHidden:true, depth:2, colors:true})}`);\n }\n\n return context;\n};\n\nNamespace.prototype.run = function run(fn) {\n let context = this.createContext();\n this.enter(context);\n\n try {\n if (DEBUG_CLS_HOOKED) {\n const triggerId = async_hooks.triggerAsyncId();\n const asyncHooksCurrentId = async_hooks.executionAsyncId();\n const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent);\n debug2(`${indentStr}CONTEXT-RUN BEGIN: (${this.name}) currentUid:${currentUid} triggerId:${triggerId} asyncHooksCurrentId:${asyncHooksCurrentId} len:${this._set.length} context:${util.inspect(context)}`);\n }\n fn(context);\n return context;\n } catch (exception) {\n if (exception) {\n exception[ERROR_SYMBOL] = context;\n }\n throw exception;\n } finally {\n if (DEBUG_CLS_HOOKED) {\n const triggerId = async_hooks.triggerAsyncId();\n const asyncHooksCurrentId = async_hooks.executionAsyncId();\n const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent);\n debug2(`${indentStr}CONTEXT-RUN END: (${this.name}) currentUid:${currentUid} triggerId:${triggerId} asyncHooksCurrentId:${asyncHooksCurrentId} len:${this._set.length} ${util.inspect(context)}`);\n }\n this.exit(context);\n }\n};\n\nNamespace.prototype.runAndReturn = function runAndReturn(fn) {\n let value;\n this.run(function (context) {\n value = fn(context);\n });\n return value;\n};\n\n/**\n * Uses global Promise and assumes Promise is cls friendly or wrapped already.\n * @param {function} fn\n * @returns {*}\n */\nNamespace.prototype.runPromise = function runPromise(fn) {\n let context = this.createContext();\n this.enter(context);\n\n let promise = fn(context);\n if (!promise || !promise.then || !promise.catch) {\n throw new Error('fn must return a promise.');\n }\n\n if (DEBUG_CLS_HOOKED) {\n debug2('CONTEXT-runPromise BEFORE: (' + this.name + ') currentUid:' + currentUid + ' len:' + this._set.length + ' ' + util.inspect(context));\n }\n\n return promise\n .then(result => {\n if (DEBUG_CLS_HOOKED) {\n debug2('CONTEXT-runPromise AFTER then: (' + this.name + ') currentUid:' + currentUid + ' len:' + this._set.length + ' ' + util.inspect(context));\n }\n this.exit(context);\n return result;\n })\n .catch(err => {\n err[ERROR_SYMBOL] = context;\n if (DEBUG_CLS_HOOKED) {\n debug2('CONTEXT-runPromise AFTER catch: (' + this.name + ') currentUid:' + currentUid + ' len:' + this._set.length + ' ' + util.inspect(context));\n }\n this.exit(context);\n throw err;\n });\n};\n\nNamespace.prototype.bind = function bindFactory(fn, context) {\n if (!context) {\n if (!this.active) {\n context = this.createContext();\n } else {\n context = this.active;\n }\n }\n\n let self = this;\n return function clsBind() {\n self.enter(context);\n try {\n return fn.apply(this, arguments);\n } catch (exception) {\n if (exception) {\n exception[ERROR_SYMBOL] = context;\n }\n throw exception;\n } finally {\n self.exit(context);\n }\n };\n};\n\nNamespace.prototype.enter = function enter(context) {\n assert.ok(context, 'context must be provided for entering');\n if (DEBUG_CLS_HOOKED) {\n const asyncHooksCurrentId = async_hooks.executionAsyncId();\n const triggerId = async_hooks.triggerAsyncId();\n const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent);\n debug2(`${indentStr}CONTEXT-ENTER: (${this.name}) currentUid:${currentUid} triggerId:${triggerId} asyncHooksCurrentId:${asyncHooksCurrentId} len:${this._set.length} ${util.inspect(context)}`);\n }\n\n this._set.push(this.active);\n this.active = context;\n};\n\nNamespace.prototype.exit = function exit(context) {\n assert.ok(context, 'context must be provided for exiting');\n if (DEBUG_CLS_HOOKED) {\n const asyncHooksCurrentId = async_hooks.executionAsyncId();\n const triggerId = async_hooks.triggerAsyncId();\n const indentStr = ' '.repeat(this._indent < 0 ? 0 : this._indent);\n debug2(`${indentStr}CONTEXT-EXIT: (${this.name}) currentUid:${currentUid} triggerId:${triggerId} asyncHooksCurrentId:${asyncHooksCurrentId} len:${this._set.length} ${util.inspect(context)}`);\n }\n\n // Fast path for most exits that are at the top of the stack\n if (this.active === context) {\n assert.ok(this._set.length, 'can\\'t remove top context');\n this.active = this._set.pop();\n return;\n }\n\n // Fast search in the stack using lastIndexOf\n let index = this._set.lastIndexOf(context);\n\n if (index < 0) {\n if (DEBUG_CLS_HOOKED) {\n debug2('??ERROR?? context exiting but not entered - ignoring: ' + util.inspect(context));\n }\n assert.ok(index >= 0, 'context not currently entered; can\\'t exit. \\n' + util.inspect(this) + '\\n' + util.inspect(context));\n } else {\n assert.ok(index, 'can\\'t remove top context');\n this._set.splice(index, 1);\n }\n};\n\nNamespace.prototype.bindEmitter = function bindEmitter(emitter) {\n assert.ok(emitter.on && emitter.addListener && emitter.emit, 'can only bind real EEs');\n\n let namespace = this;\n let thisSymbol = 'context@' + this.name;\n\n // Capture the context active at the time the emitter is bound.\n function attach(listener) {\n if (!listener) {\n return;\n }\n if (!listener[CONTEXTS_SYMBOL]) {\n listener[CONTEXTS_SYMBOL] = Object.create(null);\n }\n\n listener[CONTEXTS_SYMBOL][thisSymbol] = {\n namespace: namespace,\n context: namespace.active\n };\n }\n\n // At emit time, bind the listener within the correct context.\n function bind(unwrapped) {\n if (!(unwrapped && unwrapped[CONTEXTS_SYMBOL])) {\n return unwrapped;\n }\n\n let wrapped = unwrapped;\n let unwrappedContexts = unwrapped[CONTEXTS_SYMBOL];\n Object.keys(unwrappedContexts).forEach(function (name) {\n let thunk = unwrappedContexts[name];\n wrapped = thunk.namespace.bind(wrapped, thunk.context);\n });\n return wrapped;\n }\n\n wrapEmitter(emitter, attach, bind);\n};\n\n/**\n * If an error comes out of a namespace, it will have a context attached to it.\n * This function knows how to find it.\n *\n * @param {Error} exception Possibly annotated error.\n */\nNamespace.prototype.fromException = function fromException(exception) {\n return exception[ERROR_SYMBOL];\n};\n\nfunction getNamespace(name) {\n return process.namespaces[name];\n}\n\nfunction createNamespace(name) {\n assert.ok(name, 'namespace must be given a name.');\n\n if (DEBUG_CLS_HOOKED) {\n debug2(`NS-CREATING NAMESPACE (${name})`);\n }\n let namespace = new Namespace(name);\n namespace.id = currentUid;\n\n const hook = async_hooks.createHook({\n init(asyncId, type, triggerId, resource) {\n currentUid = async_hooks.executionAsyncId();\n\n //CHAIN Parent's Context onto child if none exists. This is needed to pass net-events.spec\n // let initContext = namespace.active;\n // if(!initContext && triggerId) {\n // let parentContext = namespace._contexts.get(triggerId);\n // if (parentContext) {\n // namespace.active = parentContext;\n // namespace._contexts.set(currentUid, parentContext);\n // if (DEBUG_CLS_HOOKED) {\n // const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n // debug2(`${indentStr}INIT [${type}] (${name}) WITH PARENT CONTEXT asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, true)} resource:${resource}`);\n // }\n // } else if (DEBUG_CLS_HOOKED) {\n // const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n // debug2(`${indentStr}INIT [${type}] (${name}) MISSING CONTEXT asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, true)} resource:${resource}`);\n // }\n // }else {\n // namespace._contexts.set(currentUid, namespace.active);\n // if (DEBUG_CLS_HOOKED) {\n // const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n // debug2(`${indentStr}INIT [${type}] (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, true)} resource:${resource}`);\n // }\n // }\n if(namespace.active) {\n namespace._contexts.set(asyncId, namespace.active);\n\n if (DEBUG_CLS_HOOKED) {\n const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n debug2(`${indentStr}INIT [${type}] (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} resource:${resource}`);\n }\n }else if(currentUid === 0){\n // CurrentId will be 0 when triggered from C++. Promise events\n // https://github.com/nodejs/node/blob/master/doc/api/async_hooks.md#triggerid\n const triggerId = async_hooks.triggerAsyncId();\n const triggerIdContext = namespace._contexts.get(triggerId);\n if (triggerIdContext) {\n namespace._contexts.set(asyncId, triggerIdContext);\n if (DEBUG_CLS_HOOKED) {\n const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n debug2(`${indentStr}INIT USING CONTEXT FROM TRIGGERID [${type}] (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, { showHidden: true, depth: 2, colors: true })} resource:${resource}`);\n }\n } else if (DEBUG_CLS_HOOKED) {\n const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n debug2(`${indentStr}INIT MISSING CONTEXT [${type}] (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, { showHidden: true, depth: 2, colors: true })} resource:${resource}`);\n }\n }\n\n\n if(DEBUG_CLS_HOOKED && type === 'PROMISE'){\n debug2(util.inspect(resource, {showHidden: true}));\n const parentId = resource.parentId;\n const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n debug2(`${indentStr}INIT RESOURCE-PROMISE [${type}] (${name}) parentId:${parentId} asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} resource:${resource}`);\n }\n\n },\n before(asyncId) {\n currentUid = async_hooks.executionAsyncId();\n let context;\n\n /*\n if(currentUid === 0){\n // CurrentId will be 0 when triggered from C++. Promise events\n // https://github.com/nodejs/node/blob/master/doc/api/async_hooks.md#triggerid\n //const triggerId = async_hooks.triggerAsyncId();\n context = namespace._contexts.get(asyncId); // || namespace._contexts.get(triggerId);\n }else{\n context = namespace._contexts.get(currentUid);\n }\n */\n\n //HACK to work with promises until they are fixed in node > 8.1.1\n context = namespace._contexts.get(asyncId) || namespace._contexts.get(currentUid);\n\n if (context) {\n if (DEBUG_CLS_HOOKED) {\n const triggerId = async_hooks.triggerAsyncId();\n const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n debug2(`${indentStr}BEFORE (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} context:${util.inspect(context)}`);\n namespace._indent += 2;\n }\n\n namespace.enter(context);\n\n } else if (DEBUG_CLS_HOOKED) {\n const triggerId = async_hooks.triggerAsyncId();\n const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n debug2(`${indentStr}BEFORE MISSING CONTEXT (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} namespace._contexts:${util.inspect(namespace._contexts, {showHidden:true, depth:2, colors:true})}`);\n namespace._indent += 2;\n }\n },\n after(asyncId) {\n currentUid = async_hooks.executionAsyncId();\n let context; // = namespace._contexts.get(currentUid);\n /*\n if(currentUid === 0){\n // CurrentId will be 0 when triggered from C++. Promise events\n // https://github.com/nodejs/node/blob/master/doc/api/async_hooks.md#triggerid\n //const triggerId = async_hooks.triggerAsyncId();\n context = namespace._contexts.get(asyncId); // || namespace._contexts.get(triggerId);\n }else{\n context = namespace._contexts.get(currentUid);\n }\n */\n //HACK to work with promises until they are fixed in node > 8.1.1\n context = namespace._contexts.get(asyncId) || namespace._contexts.get(currentUid);\n\n if (context) {\n if (DEBUG_CLS_HOOKED) {\n const triggerId = async_hooks.triggerAsyncId();\n namespace._indent -= 2;\n const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n debug2(`${indentStr}AFTER (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} context:${util.inspect(context)}`);\n }\n\n namespace.exit(context);\n\n } else if (DEBUG_CLS_HOOKED) {\n const triggerId = async_hooks.triggerAsyncId();\n namespace._indent -= 2;\n const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n debug2(`${indentStr}AFTER MISSING CONTEXT (${name}) asyncId:${asyncId} currentUid:${currentUid} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} context:${util.inspect(context)}`);\n }\n },\n destroy(asyncId) {\n currentUid = async_hooks.executionAsyncId();\n if (DEBUG_CLS_HOOKED) {\n const triggerId = async_hooks.triggerAsyncId();\n const indentStr = ' '.repeat(namespace._indent < 0 ? 0 : namespace._indent);\n debug2(`${indentStr}DESTROY (${name}) currentUid:${currentUid} asyncId:${asyncId} triggerId:${triggerId} active:${util.inspect(namespace.active, {showHidden:true, depth:2, colors:true})} context:${util.inspect(namespace._contexts.get(currentUid))}`);\n }\n\n namespace._contexts.delete(asyncId);\n }\n });\n\n hook.enable();\n\n process.namespaces[name] = namespace;\n return namespace;\n}\n\nfunction destroyNamespace(name) {\n let namespace = getNamespace(name);\n\n assert.ok(namespace, 'can\\'t delete nonexistent namespace! \"' + name + '\"');\n assert.ok(namespace.id, 'don\\'t assign to process.namespaces directly! ' + util.inspect(namespace));\n\n process.namespaces[name] = null;\n}\n\nfunction reset() {\n // must unregister async listeners\n if (process.namespaces) {\n Object.keys(process.namespaces).forEach(function (name) {\n destroyNamespace(name);\n });\n }\n process.namespaces = Object.create(null);\n}\n\nprocess.namespaces = {};\n\n//const fs = require('fs');\nfunction debug2(...args) {\n if (DEBUG_CLS_HOOKED) {\n //fs.writeSync(1, `${util.format(...args)}\\n`);\n process._rawDebug(`${util.format(...args)}`);\n }\n}\n\n/*function getFunctionName(fn) {\n if (!fn) {\n return fn;\n }\n if (typeof fn === 'function') {\n if (fn.name) {\n return fn.name;\n }\n return (fn.toString().trim().match(/^function\\s*([^\\s(]+)/) || [])[1];\n } else if (fn.constructor && fn.constructor.name) {\n return fn.constructor.name;\n }\n}*/\n\n\n", "\"use strict\";\nvar validLogLevels = ['debug', 'info', 'warn', 'error', 'silent'];\nvar defaultLogLevel = validLogLevels.indexOf('error');\nvar logLevel = calculateLogLevel(process.env.AWS_XRAY_DEBUG_MODE ? 'debug' : process.env.AWS_XRAY_LOG_LEVEL);\nvar logger = {\n error: createLoggerForLevel('error'),\n info: createLoggerForLevel('info'),\n warn: createLoggerForLevel('warn'),\n debug: createLoggerForLevel('debug'),\n};\nfunction createLoggerForLevel(level) {\n var loggerLevel = validLogLevels.indexOf(level);\n var consoleMethod = console[level] || console.log || (() => { });\n if (loggerLevel >= logLevel) {\n return (message, meta) => {\n if (message || meta) {\n consoleMethod(formatLogMessage(level, message, meta));\n }\n };\n }\n else {\n return () => { };\n }\n}\nfunction calculateLogLevel(level) {\n if (level) {\n var normalisedLevel = level.toLowerCase();\n var index = validLogLevels.indexOf(normalisedLevel);\n return index >= 0 ? index : defaultLogLevel;\n }\n // Silently ignore invalid log levels, default to default level\n return defaultLogLevel;\n}\nfunction createTimestamp(date) {\n var tzo = -date.getTimezoneOffset(), // Negate to make this tzo = local - UTC\n dif = tzo >= 0 ? '+' : '-', pad = function (num) {\n var norm = Math.floor(Math.abs(num));\n return (norm < 10 ? '0' : '') + norm;\n };\n return new Date(date.getTime() + (tzo * 60 * 1000)).toISOString()\n .replace(/T/, ' ')\n .replace(/Z/, ' ') +\n dif + pad(tzo / 60) +\n ':' + pad(tzo % 60);\n}\nfunction isLambdaFunction() {\n return process.env.LAMBDA_TASK_ROOT !== undefined;\n}\nfunction formatLogMessage(level, message, meta) {\n var messageParts = [];\n if (!isLambdaFunction()) {\n messageParts.push(createTimestamp(new Date()));\n messageParts.push(`[${level.toUpperCase()}]`);\n }\n if (message) {\n messageParts.push(message);\n }\n var logString = messageParts.join(' ');\n var metaDataString = formatMetaData(meta);\n return [logString, metaDataString].filter(str => str.length > 0).join('\\n ');\n}\nfunction formatMetaData(meta) {\n if (!meta) {\n return '';\n }\n return ((typeof (meta) === 'string') ? meta : JSON.stringify(meta));\n}\nvar logging = {\n setLogger: function setLogger(logObj) {\n logger = logObj;\n },\n getLogger: function getLogger() {\n return logger;\n }\n};\nmodule.exports = logging;\n", "\"use strict\";\n/**\n * Represents a captured exception.\n * @constructor\n * @param {Exception} err - The exception to capture.\n * @param {boolean} [remote] - Flag for whether the error was remote.\n */\nfunction CapturedException(err, remote) {\n this.init(err, remote);\n}\nCapturedException.prototype.init = function init(err, remote) {\n var e = (typeof err === 'string' || err instanceof String) ? { message: err, name: '' } : err;\n this.message = e.message;\n this.type = e.name;\n this.stack = [];\n this.remote = !!remote;\n if (e.stack) {\n var stack = e.stack.split('\\n');\n stack.shift();\n var self = this;\n stack.forEach(function (stackline) {\n var line = stackline.trim().replace(/\\(|\\)/g, '');\n line = line.substring(line.indexOf(' ') + 1);\n var label = line.lastIndexOf(' ') >= 0 ? line.slice(0, line.lastIndexOf(' ')) : null;\n var path = Array.isArray(label) && !label.length ? line : line.slice(line.lastIndexOf(' ') + 1);\n path = path.split(':');\n var entry = {\n path: path[0],\n line: parseInt(path[1]),\n label: label || 'anonymous'\n };\n self.stack.push(entry);\n });\n }\n};\nmodule.exports = CapturedException;\n", "module.exports = batcher\n\nfunction batcher (run) {\n var running = false\n var pendingBatch = null\n var pendingCallbacks = null\n var callbacks = null\n\n return append\n\n function done (err) {\n if (callbacks) callAll(callbacks, err)\n\n running = false\n callbacks = pendingCallbacks\n var nextBatch = pendingBatch\n\n pendingBatch = null\n pendingCallbacks = null\n\n if (!nextBatch || !nextBatch.length) {\n if (!callbacks || !callbacks.length) {\n callbacks = null\n return\n }\n if (!nextBatch) nextBatch = []\n }\n\n running = true\n run(nextBatch, done)\n }\n\n function append (val, cb) {\n if (running) {\n if (!pendingBatch) {\n pendingBatch = []\n pendingCallbacks = []\n }\n pushAll(pendingBatch, val)\n if (cb) pendingCallbacks.push(cb)\n } else {\n if (cb) callbacks = [cb]\n running = true\n run(Array.isArray(val) ? val : [val], done)\n }\n }\n}\n\nfunction pushAll (list, val) {\n if (Array.isArray(val)) pushArray(list, val)\n else list.push(val)\n}\n\nfunction pushArray (list, val) {\n for (var i = 0; i < val.length; i++) list.push(val[i])\n}\n\nfunction callAll (list, err) {\n for (var i = 0; i < list.length; i++) list[i](err)\n}\n", "\"use strict\";\nvar logger = require('./logger');\n/**\n * A module representing the X-Ray daemon configuration including the udp and tcp addresses.\n * @module DaemonConfig\n */\nvar DaemonConfig = {\n udp_ip: '127.0.0.1',\n udp_port: 2000,\n tcp_ip: '127.0.0.1',\n tcp_port: 2000,\n setDaemonAddress: function setDaemonAddress(address) {\n if (!process.env.AWS_XRAY_DAEMON_ADDRESS) {\n processAddress(address);\n logger.getLogger().info('Configured daemon address to ' + address + '.');\n }\n else {\n logger.getLogger().warn('Ignoring call to setDaemonAddress as AWS_XRAY_DAEMON_ADDRESS is set. ' +\n 'The current daemon address will not be changed.');\n }\n }\n};\nvar processAddress = function processAddress(address) {\n if (address.indexOf(':') === -1) {\n throw new Error('Invalid Daemon Address. You must specify an ip and port.');\n }\n else {\n var splitAddress = address.split(' ');\n if (splitAddress.length === 1) {\n // in format of 127.0.0.1:2000\n if (address.indexOf('udp') > -1 || address.indexOf('tcp') > -1) {\n throw new Error('Invalid Daemon Address. You must specify both tcp and udp addresses.');\n }\n var addr = address.split(':');\n if (!addr[0])\n throw new Error('Invalid Daemon Address. You must specify an ip.');\n DaemonConfig.udp_ip = addr[0];\n DaemonConfig.tcp_ip = addr[0];\n DaemonConfig.udp_port = addr[1];\n DaemonConfig.tcp_port = addr[1];\n }\n else if (splitAddress.length === 2) {\n // in format of udp:127.0.0.1:2000 tcp:127.0.0.1:2001\n var part_1 = splitAddress[0].split(':');\n var part_2 = splitAddress[1].split(':');\n var addr_map = {};\n addr_map[part_1[0]] = part_1;\n addr_map[part_2[0]] = part_2;\n DaemonConfig.udp_ip = addr_map['udp'][1];\n DaemonConfig.udp_port = parseInt(addr_map['udp'][2]);\n DaemonConfig.tcp_ip = addr_map['tcp'][1];\n DaemonConfig.tcp_port = parseInt(addr_map['tcp'][2]);\n if (!DaemonConfig.udp_port || !DaemonConfig.tcp_port) {\n throw new Error('Invalid Daemon Address. You must specify port number.');\n }\n }\n }\n};\nif (process.env.AWS_XRAY_DAEMON_ADDRESS)\n processAddress(process.env.AWS_XRAY_DAEMON_ADDRESS);\nmodule.exports = DaemonConfig;\n", "\"use strict\";\nvar dgram = require('dgram');\nvar batcher = require('atomic-batcher');\nvar logger = require('./logger');\nvar PROTOCOL_HEADER = '{\"format\":\"json\",\"version\":1}';\nvar PROTOCOL_DELIMITER = '\\n';\n/**\n * Sends a collection of data over a UDP socket. This method\n * is designed to be used by `atomic-batcher` as a way to share\n * a single UDP socket for sending multiple data blocks.\n *\n * @param {object} ops - Details of the data to send\n * @param {Function} callback - The function to call when done\n */\nfunction batchSendData(ops, callback) {\n var client = dgram.createSocket('udp4');\n executeSendData(client, ops, 0, function () {\n try {\n client.close();\n }\n finally {\n callback();\n }\n });\n}\n/**\n * Execute sending data starting at the specified index and\n * using the provided client.\n *\n * @param {Socket} client - Socket to send data with\n * @param {object} ops - Details of data to send\n * @param {number} index - Starting index for sending\n * @param {Function} callback - Function to call when done\n */\nfunction executeSendData(client, ops, index, callback) {\n if (index >= ops.length) {\n callback();\n return;\n }\n sendMessage(client, ops[index], function () {\n executeSendData(client, ops, index + 1, callback);\n });\n}\n/**\n * Send a single message over a UDP socket.\n *\n * @param {Socket} client - Socket to send data with\n * @param {object} data - Details of the data to send\n * @param {Function} batchCallback - Function to call when done\n */\nfunction sendMessage(client, data, batchCallback) {\n var msg = data.msg;\n var offset = data.offset;\n var length = data.length;\n var port = data.port;\n var address = data.address;\n var callback = data.callback;\n client.send(msg, offset, length, port, address, function (err) {\n try {\n callback(err);\n }\n finally {\n batchCallback();\n }\n });\n}\n/**\n * Class to mimic the Socket interface for a UDP client, but to provided\n * batching of outgoing sends using temporary Sockets that are created and\n * destroyed as needed.\n */\nfunction BatchingTemporarySocket() {\n this.batchSend = batcher(batchSendData);\n}\n/**\n * Provide the same signature as the Socket.send method but the work will be\n * batched to share temporary UDP sockets whenever possible.\n */\nBatchingTemporarySocket.prototype.send = function (msg, offset, length, port, address, callback) {\n var work = {\n msg: msg,\n offset: offset,\n length: length,\n port: port,\n address: address,\n callback: callback\n };\n this.batchSend(work);\n};\n/**\n * Segment emitter module.\n * @module SegmentEmitter\n */\nvar SegmentEmitter = {\n daemonConfig: require('./daemon_config'),\n /**\n * Returns the formatted segment JSON string.\n */\n format: function format(segment) {\n return PROTOCOL_HEADER + PROTOCOL_DELIMITER + segment.toString();\n },\n /**\n * Creates a UDP socket connection and send the formatted segment.\n * @param {Segment} segment - The segment to send to the daemon.\n */\n send: function send(segment) {\n if (!this.socket) {\n if (this.useBatchingTemporarySocket) {\n this.socket = new BatchingTemporarySocket();\n }\n else {\n this.socket = dgram.createSocket('udp4').unref();\n }\n }\n var client = this.socket;\n var formatted = segment.format();\n var data = PROTOCOL_HEADER + PROTOCOL_DELIMITER + formatted;\n var message = Buffer.from(data);\n var short = '{\"trace_id:\"' + segment.trace_id + '\",\"id\":\"' + segment.id + '\"}';\n var type = segment.type === 'subsegment' ? 'Subsegment' : 'Segment';\n client.send(message, 0, message.length, this.daemonConfig.udp_port, this.daemonConfig.udp_ip, function (err) {\n if (err) {\n if (err.code === 'EMSGSIZE')\n logger.getLogger().error(type + ' too large to send: ' + short + ' (' + message.length + ' bytes).');\n else\n logger.getLogger().error('Error occured sending segment: ', err);\n }\n else {\n logger.getLogger().debug(type + ' sent: {\"trace_id:\"' + segment.trace_id + '\",\"id\":\"' + segment.id + '\"}');\n logger.getLogger().debug('UDP message sent: ' + segment);\n }\n });\n },\n /**\n * Configures the address and/or port the daemon is expected to be on.\n * @param {string} address - Address of the daemon the segments should be sent to. Should be formatted as an IPv4 address.\n * @module SegmentEmitter\n * @function setDaemonAddress\n */\n setDaemonAddress: function setDaemonAddress(address) {\n this.daemonConfig.setDaemonAddress(address);\n },\n /**\n * Get the UDP IP the emitter is configured to.\n * @module SegmentEmitter\n * @function getIp\n */\n getIp: function getIp() {\n return this.daemonConfig.udp_ip;\n },\n /**\n * Get the UDP port the emitter is configured to.\n * @module SegmentEmitter\n * @function getPort\n */\n getPort: function getPort() {\n return this.daemonConfig.udp_port;\n },\n /**\n * Forces the segment emitter to create a new socket on send, and close it on complete.\n * @module SegmentEmitter\n * @function disableReusableSocket\n */\n disableReusableSocket: function () {\n this.useBatchingTemporarySocket = true;\n }\n};\nmodule.exports = SegmentEmitter;\n", "\"use strict\";\nvar crypto = require('crypto');\nvar logger = require('../../logger');\n/**\n * Class describing an AWS X-Ray trace ID.\n * @see https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-traces\n */\nclass TraceID {\n /**\n * Constructs a new trace ID using the current time.\n * @param {string} [tsHex] - time stamp to use for trace ID in hexadecimal format\n * @param {string} [numberhex] - string of hexadecimal characters for random portion of Trace ID\n * @constructor\n */\n constructor(tsHex, numberhex) {\n this.version = 1;\n this.timestamp = tsHex || Math.round(new Date().getTime() / 1000).toString(16);\n this.id = numberhex || crypto.randomBytes(12).toString('hex');\n }\n /**\n * @returns {TraceID} - a hardcoded trace ID using zeroed timestamp and random ID\n */\n static Invalid() {\n return new TraceID('00000000', '000000000000000000000000');\n }\n /**\n * Constructs a new trace ID from provided string. If no string is provided or the provided string is invalid,\n * log an error but a new trace ID still returned. This can be used as a trace ID string validator.\n * @param {string} [rawID] - string to create a Trace ID object from.\n */\n static FromString(rawID) {\n const DELIMITER = '-';\n var traceID = new TraceID();\n var version, timestamp;\n if (!rawID || typeof rawID !== 'string') {\n logger.getLogger().error('Empty or non-string trace ID provided');\n return traceID;\n }\n const parts = rawID.trim().split(DELIMITER);\n if (parts.length !== 3) {\n logger.getLogger().error('Unrecognized trace ID format');\n return traceID;\n }\n version = parseInt(parts[0]);\n if (version === NaN || version < 1) {\n logger.getLogger().error('Trace ID version must be positive integer');\n return traceID;\n }\n timestamp = parseInt(parts[1], 16).toString(16);\n if (timestamp === 'NaN') {\n logger.getLogger().error('Trace ID timestamp must be a hex-encoded value');\n return traceID;\n }\n traceID.version = version;\n traceID.timestamp = timestamp;\n traceID.id = parts[2];\n return traceID;\n }\n /**\n * Returns a string representation of the trace ID.\n * @returns {string} - stringified trace ID, e.g. 1-57fbe041-2c7ad569f5d6ff149137be86\n */\n toString() {\n return `${this.version.toString()}-${this.timestamp}-${this.id}`;\n }\n}\nmodule.exports = TraceID;\n", "\"use strict\";\n/**\n * @module utils\n */\nvar crypto = require('crypto');\nvar logger = require('./logger');\nvar TraceID = require('./segments/attributes/trace_id');\nvar utils = {\n /**\n * Checks a HTTP response code, where 4xx are 'error' and 5xx are 'fault'.\n * @param {string} status - the HTTP response status code.\n * @returns [string] - 'error', 'fault' or nothing on no match\n * @alias module:utils.getCauseTypeFromHttpStatus\n */\n getCauseTypeFromHttpStatus: function getCauseTypeFromHttpStatus(status) {\n var stat = status.toString();\n if (stat.match(/^[4][0-9]{2}$/) !== null)\n return 'error';\n else if (stat.match(/^[5][0-9]{2}$/) !== null)\n return 'fault';\n },\n /**\n * Removes the query string parameters from a given http request path\n * as it may contain sensitive information\n *\n * Related issue: https://github.com/aws/aws-xray-sdk-node/issues/246\n *\n * Node documentation: https://nodejs.org/api/http.html#http_http_request_url_options_callback\n *\n * @param {string} path - options.path in a http.request callback\n * @returns [string] - removes query string element from path\n * @alias module:utils.stripQueryStringFromPath\n */\n stripQueryStringFromPath: function stripQueryStringFromPath(path) {\n return path ? path.split('?')[0] : '';\n },\n /**\n * Performs a case-insensitive wildcard match against two strings. This method works with pseduo-regex chars; specifically ? and * are supported.\n * An asterisk (*) represents any combination of characters\n * A question mark (?) represents any single character\n *\n * @param {string} pattern - the regex-like pattern to be compared against.\n * @param {string} text - the string to compare against the pattern.\n * @returns boolean\n * @alias module:utils.wildcardMatch\n */\n wildcardMatch: function wildcardMatch(pattern, text) {\n if (pattern === undefined || text === undefined)\n return false;\n if (pattern.length === 1 && pattern.charAt(0) === '*')\n return true;\n var patternLength = pattern.length;\n var textLength = text.length;\n var indexOfGlob = pattern.indexOf('*');\n pattern = pattern.toLowerCase();\n text = text.toLowerCase();\n // Infix globs are relatively rare, and the below search is expensive especially when\n // Balsa is used a lot. Check for infix globs and, in their absence, do the simple thing\n if (indexOfGlob === -1 || indexOfGlob === (patternLength - 1)) {\n var match = function simpleWildcardMatch() {\n var j = 0;\n for (var i = 0; i < patternLength; i++) {\n var patternChar = pattern.charAt(i);\n if (patternChar === '*') {\n // Presumption for this method is that globs only occur at end\n return true;\n }\n else if (patternChar === '?') {\n if (j === textLength)\n return false; // No character to match\n j++;\n }\n else {\n if (j >= textLength || patternChar != text.charAt(j))\n return false;\n j++;\n }\n }\n // Ate up all the pattern and didn't end at a glob, so a match will have consumed all\n // the text\n return j === textLength;\n };\n return match();\n }\n /*\n * The matchArray[i] is used to record if there is a match between the first i chars in =\n * text and the first j chars in pattern.\n * So will return matchArray[textLength+1] in the end\n * Loop from the beginning of the pattern\n * case not '*': if text[i]==pattern[j] or pattern[j] is '?', and matchArray[i] is true,\n * set matchArray[i+1] to true, otherwise false\n * case '*': since '*' can match any globing, as long as there is a true in matchArray before i\n * all the matchArray[i+1], matchArray[i+2],...,matchArray[textLength] could be true\n */\n var matchArray = [];\n matchArray[0] = true;\n for (var j = 0; j < patternLength; j++) {\n var i;\n var patternChar = pattern.charAt(j);\n if (patternChar != '*') {\n for (i = textLength - 1; i >= 0; i--)\n matchArray[i + 1] = !!matchArray[i] && (patternChar === '?' || (patternChar === text.charAt(i)));\n }\n else {\n i = 0;\n while (i <= textLength && !matchArray[i])\n i++;\n for (i; i <= textLength; i++)\n matchArray[i] = true;\n }\n matchArray[0] = (matchArray[0] && patternChar === '*');\n }\n return matchArray[textLength];\n },\n LambdaUtils: {\n validTraceData: function (xAmznTraceId) {\n var valid = false;\n if (xAmznTraceId) {\n var data = utils.processTraceData(xAmznTraceId);\n valid = !!(data && data.root && data.parent && data.sampled);\n }\n return valid;\n },\n /**\n * Populates trace ID, parent ID, and sampled decision of given segment. Will always populate valid values,\n * even if xAmznTraceId contains missing or invalid values. This ensures downstream services receive valid\n * headers.\n * @param {Segment} segment - Facade segment to be populated\n * @param {String} xAmznTraceId - Raw Trace Header to supply trace data\n * @returns {Boolean} - true if required fields are present and Trace ID is valid, false otherwise\n */\n populateTraceData: function (segment, xAmznTraceId) {\n logger.getLogger().debug('Lambda trace data found: ' + xAmznTraceId);\n var data = utils.processTraceData(xAmznTraceId);\n var valid = false;\n if (!data) {\n data = {};\n logger.getLogger().error('_X_AMZN_TRACE_ID is empty or has an invalid format');\n }\n else if (!data.root || !data.parent || !data.sampled) {\n logger.getLogger().error('_X_AMZN_TRACE_ID is missing required information');\n }\n else {\n valid = true;\n }\n segment.trace_id = TraceID.FromString(data.root).toString(); // Will always assign valid trace_id\n segment.id = data.parent || crypto.randomBytes(8).toString('hex');\n if (data.root && segment.trace_id !== data.root) {\n logger.getLogger().error('_X_AMZN_TRACE_ID contains invalid trace ID');\n valid = false;\n }\n if (!parseInt(data.sampled))\n segment.notTraced = true;\n else\n delete segment.notTraced;\n logger.getLogger().debug('Segment started: ' + JSON.stringify(data));\n return valid;\n }\n },\n /**\n * Splits out the data from the trace id format. Used by the middleware.\n * @param {String} traceData - The additional trace data (typically in req.headers.x-amzn-trace-id).\n * @returns {object}\n * @alias module:mw_utils.processTraceData\n */\n processTraceData: function processTraceData(traceData) {\n var amznTraceData = {};\n var reservedKeywords = ['root', 'parent', 'sampled', 'self'];\n var remainingBytes = 256;\n if (!(typeof traceData === 'string' && traceData))\n return amznTraceData;\n traceData.split(';').forEach(function (header) {\n if (!header)\n return;\n var pair = header.split('=');\n if (pair[0] && pair[1]) {\n var key = pair[0].trim().toLowerCase();\n var value = pair[1].trim().toLowerCase();\n var reserved = reservedKeywords.indexOf(key) !== -1;\n if (reserved) {\n amznTraceData[key] = value;\n }\n else if (!reserved && remainingBytes - (key.length + value.length) >= 0) {\n amznTraceData[key] = value;\n remainingBytes -= (key.length + value.length);\n }\n }\n });\n return amznTraceData;\n },\n /**\n * Makes a shallow copy of an object without given keys - keeps prototype\n * @param {Object} obj - The object to copy\n * @param {string[]} [keys=[]] - The keys that won't be copied\n * @param {boolean} [preservePrototype=false] - If true also copy prototype properties\n * @returns {}\n */\n objectWithoutProperties: function objectWithoutProperties(obj, keys, preservePrototype) {\n keys = Array.isArray(keys) ? keys : [];\n preservePrototype = typeof preservePrototype === 'boolean' ? preservePrototype : false;\n var target = preservePrototype ? Object.create(Object.getPrototypeOf(obj)) : {};\n for (var property in obj) {\n if (keys.indexOf(property) >= 0)\n continue;\n if (!Object.prototype.hasOwnProperty.call(obj, property))\n continue;\n target[property] = obj[property];\n }\n return target;\n },\n /**\n * Safely gets an integer from a string or number\n * @param {String | Number} - input to cast to integer\n * @returns {Number} - Integer representation of input, or 0 if input is not castable to int\n */\n safeParseInt: (val) => {\n if (!val || isNaN(val)) {\n return 0;\n }\n return parseInt(val);\n }\n};\nmodule.exports = utils;\n", "\"use strict\";\nconst { safeParseInt } = require('../utils');\nvar logger = require('../logger');\nvar DEFAULT_STREAMING_THRESHOLD = 100;\nvar utils = {\n streamingThreshold: DEFAULT_STREAMING_THRESHOLD,\n getCurrentTime: function getCurrentTime() {\n return Date.now() / 1000;\n },\n setOrigin: function setOrigin(origin) {\n this.origin = origin;\n },\n setPluginData: function setPluginData(pluginData) {\n this.pluginData = pluginData;\n },\n setSDKData: function setSDKData(sdkData) {\n this.sdkData = sdkData;\n },\n setServiceData: function setServiceData(serviceData) {\n this.serviceData = serviceData;\n },\n /**\n * Overrides the default streaming threshold (100).\n * The threshold represents the maximum number of subsegments on a single segment before\n * the SDK beings to send the completed subsegments out of band of the main segment.\n * Reduce this threshold if you see the 'Segment too large to send' error.\n * @param {number} threshold - The new threshold to use.\n * @memberof AWSXRay\n */\n setStreamingThreshold: function setStreamingThreshold(threshold) {\n if (isFinite(threshold) && threshold >= 0) {\n utils.streamingThreshold = threshold;\n logger.getLogger().debug('Subsegment streaming threshold set to: ' + threshold);\n }\n else {\n logger.getLogger().error('Invalid threshold: ' + threshold + '. Must be a whole number >= 0.');\n }\n },\n getStreamingThreshold: function getStreamingThreshold() {\n return utils.streamingThreshold;\n },\n /**\n * Parses an HTTP response object to return an X-Ray compliant HTTP response object.\n * @param {http.ServerResponse} res\n * @returns {Object} - X-Ray response object to be added to (sub)segment\n */\n getHttpResponseData: (res) => {\n const ret = {};\n if (!res) {\n return ret;\n }\n const status = safeParseInt(res.statusCode);\n if (status !== 0) {\n ret.status = status;\n }\n if (res.headers && res.headers['content-length']) {\n ret.content_length = safeParseInt(res.headers['content-length']);\n }\n return ret;\n }\n};\nmodule.exports = utils;\n", "\"use strict\";\nconst { getHttpResponseData } = require('../segment_utils');\nvar { stripQueryStringFromPath } = require('../../utils');\n/**\n * Represents an outgoing HTTP/HTTPS call.\n * @constructor\n * @param {http.ClientRequest|https.ClientRequest} req - The request object from the HTTP/HTTPS call.\n * @param {http.IncomingMessage|https.IncomingMessage} res - The response object from the HTTP/HTTPS call.\n * @param {boolean} downstreamXRayEnabled - when true, adds a \"traced\": true hint to generated subsegments such that the AWS X-Ray service expects a corresponding segment from the downstream service.\n */\nfunction RemoteRequestData(req, res, downstreamXRayEnabled) {\n this.init(req, res, downstreamXRayEnabled);\n}\nRemoteRequestData.prototype.init = function init(req, res, downstreamXRayEnabled) {\n this.request = {\n url: (req.agent && req.agent.protocol) ? (req.agent.protocol + '//' + req.getHeader('host') + stripQueryStringFromPath(req.path)) : '',\n method: req.method || '',\n };\n if (downstreamXRayEnabled) {\n this.request.traced = true;\n }\n if (res) {\n this.response = getHttpResponseData(res);\n }\n};\nmodule.exports = RemoteRequestData;\n", "\"use strict\";\nvar crypto = require('crypto');\nvar CapturedException = require('./captured_exception');\nvar RemoteRequestData = require('./remote_request_data');\nvar SegmentEmitter = require('../../segment_emitter');\nvar SegmentUtils = require('../segment_utils');\nvar Utils = require('../../utils');\nvar logger = require('../../logger');\n/**\n * Represents a subsegment.\n * @constructor\n * @param {string} name - The name of the subsegment.\n */\nfunction Subsegment(name) {\n this.init(name);\n}\nSubsegment.prototype.init = function init(name) {\n if (typeof name != 'string')\n throw new Error('Subsegment name must be of type string.');\n this.id = crypto.randomBytes(8).toString('hex');\n this.name = name;\n this.start_time = SegmentUtils.getCurrentTime();\n this.in_progress = true;\n this.counter = 0;\n};\n/**\n * Nests a new subsegment to the array of subsegments.\n * @param {string} name - The name of the new subsegment to append.\n * @returns {Subsegment} - The newly created subsegment.\n */\nSubsegment.prototype.addNewSubsegment = function addNewSubsegment(name) {\n var subsegment = new Subsegment(name);\n this.addSubsegment(subsegment);\n return subsegment;\n};\n/**\n * Adds a subsegment to the array of subsegments.\n * @param {Subsegment} subsegment - The subsegment to append.\n */\nSubsegment.prototype.addSubsegment = function (subsegment) {\n if (!(subsegment instanceof Subsegment)) {\n throw new Error('Failed to add subsegment:' + subsegment + ' to subsegment \"' + this.name +\n '\". Not a subsegment.');\n }\n if (this.subsegments === undefined)\n this.subsegments = [];\n subsegment.segment = this.segment;\n subsegment.parent = this;\n if (subsegment.end_time === undefined) {\n this.incrementCounter(subsegment.counter);\n }\n this.subsegments.push(subsegment);\n};\n/**\n * Removes the subsegment from the subsegments array, used in subsegment streaming.\n */\nSubsegment.prototype.removeSubsegment = function removeSubsegment(subsegment) {\n if (!(subsegment instanceof Subsegment)) {\n throw new Error('Failed to remove subsegment:' + subsegment + ' from subsegment \"' + this.name +\n '\". Not a subsegment.');\n }\n if (this.subsegments !== undefined) {\n var index = this.subsegments.indexOf(subsegment);\n if (index >= 0)\n this.subsegments.splice(index, 1);\n }\n};\n/**\n * Adds a property with associated data into the subsegment.\n * @param {string} name - The name of the property to add.\n * @param {Object} data - The data of the property to add.\n */\nSubsegment.prototype.addAttribute = function addAttribute(name, data) {\n this[name] = data;\n};\n/**\n * Adds a subsegement id to record ordering.\n * @param {string} id - A subsegment id.\n */\nSubsegment.prototype.addPrecursorId = function (id) {\n if (typeof id !== 'string')\n logger.getLogger().error('Failed to add id:' + id + ' to subsegment ' + this.name +\n '. Precursor Ids must be of type string.');\n if (this.precursor_ids === undefined)\n this.precursor_ids = [];\n this.precursor_ids.push(id);\n};\n/**\n * Adds a key-value pair that can be queryable through GetTraceSummaries.\n * Only acceptable types are string, float/int and boolean.\n * @param {string} key - The name of key to add.\n * @param {boolean|string|number} value - The value to add for the given key.\n */\nSubsegment.prototype.addAnnotation = function (key, value) {\n if (!(typeof value === 'boolean' || typeof value === 'string' || (typeof value === 'number' && isFinite(value)))) {\n throw new Error('Failed to add annotation key: ' + key + ' value: ' + value + ' to subsegment ' +\n this.name + '. Value must be of type string, number or boolean.');\n }\n else if (typeof key !== 'string') {\n throw new Error('Failed to add annotation key: ' + key + ' value: ' + value + ' to subsegment ' +\n this.name + '. Key must be of type string.');\n }\n if (this.annotations === undefined)\n this.annotations = {};\n this.annotations[key] = value;\n};\n/**\n * Adds a key-value pair to the metadata.default attribute when no namespace is given.\n * Metadata is not queryable, but is recorded.\n * @param {string} key - The name of the key to add.\n * @param {object|null} value - The value of the associated key.\n * @param {string} [namespace] - The property name to put the key/value pair under.\n */\nSubsegment.prototype.addMetadata = function (key, value, namespace) {\n if (typeof key !== 'string') {\n throw new Error('Failed to add annotation key: ' + key + ' value: ' + value + ' to subsegment ' +\n this.name + '. Key must be of type string.');\n }\n else if (namespace && typeof namespace !== 'string') {\n throw new Error('Failed to add annotation key: ' + key + ' value: ' + value + 'namespace: ' + namespace + ' to subsegment ' +\n this.name + '. Namespace must be of type string.');\n }\n var ns = namespace || 'default';\n if (!this.metadata) {\n this.metadata = {};\n }\n if (!this.metadata[ns]) {\n this.metadata[ns] = {};\n }\n this.metadata[ns][key] = value;\n};\nSubsegment.prototype.addSqlData = function addSqlData(sqlData) {\n this.sql = sqlData;\n};\n/**\n * Adds an error with associated data into the subsegment.\n * To handle propagating errors, the subsegment also sets a copy of the error on the\n * root segment. As the error passes up the execution stack, a reference is created\n * on each subsegment to the originating subsegment.\n * @param {Error|string} err - The error to capture.\n * @param {boolean} [remote] - Flag for whether the exception caught was remote or not.\n */\nSubsegment.prototype.addError = function addError(err, remote) {\n if (err == null || typeof err !== 'object' && typeof (err) !== 'string') {\n throw new Error('Failed to add error:' + err + ' to subsegment \"' + this.name +\n '\". Not an object or string literal.');\n }\n this.addFaultFlag();\n if (this.segment && this.segment.exception) {\n if (err === this.segment.exception.ex) {\n this.fault = true;\n this.cause = { id: this.segment.exception.cause };\n return;\n }\n delete this.segment.exception;\n }\n if (this.segment) {\n this.segment.exception = {\n ex: err,\n cause: this.id\n };\n }\n else {\n //error, cannot propagate exception if not added to segment\n }\n if (this.cause === undefined) {\n this.cause = {\n working_directory: process.cwd(),\n exceptions: []\n };\n }\n this.cause.exceptions.unshift(new CapturedException(err, remote));\n};\n/**\n * Adds data for an outgoing HTTP/HTTPS call.\n * @param {http.ClientRequest/https.ClientRequest} req - The request object from the HTTP/HTTPS call.\n * @param {http.IncomingMessage/https.IncomingMessage} res - The response object from the HTTP/HTTPS call.\n * @param {boolean} downstreamXRayEnabled - when true, adds a \"traced\": true hint to generated subsegments such that the AWS X-Ray service expects a corresponding segment from the downstream service.\n */\nSubsegment.prototype.addRemoteRequestData = function addRemoteRequestData(req, res, downstreamXRayEnabled) {\n this.http = new RemoteRequestData(req, res, downstreamXRayEnabled);\n if ('traced' in this.http.request) {\n this.traced = this.http.request.traced;\n delete this.http.request.traced;\n }\n};\n/**\n * Adds fault flag to the subsegment.\n */\nSubsegment.prototype.addFaultFlag = function addFaultFlag() {\n this.fault = true;\n};\n/**\n * Adds error flag to the subsegment.\n */\nSubsegment.prototype.addErrorFlag = function addErrorFlag() {\n this.error = true;\n};\n/**\n * Adds throttle flag to the subsegment.\n */\nSubsegment.prototype.addThrottleFlag = function addThrottleFlag() {\n this.throttle = true;\n};\n/**\n * Closes the current subsegment. This automatically captures any exceptions and sets the end time.\n * @param {Error|string} [err] - The error to capture.\n * @param {boolean} [remote] - Flag for whether the exception caught was remote or not.\n */\nSubsegment.prototype.close = function close(err, remote) {\n var root = this.segment;\n this.end_time = SegmentUtils.getCurrentTime();\n delete this.in_progress;\n if (err)\n this.addError(err, remote);\n if (this.parent)\n this.parent.decrementCounter();\n if (root && root.counter > SegmentUtils.getStreamingThreshold()) {\n if (this.streamSubsegments() && this.parent)\n this.parent.removeSubsegment(this);\n }\n};\n/**\n * Each subsegment holds a counter of open subsegments. This increments\n * the counter such that it can be called from a child and propagate up.\n * @param {Number} [additional] - An additional amount to increment. Used when adding subsegment trees.\n */\nSubsegment.prototype.incrementCounter = function incrementCounter(additional) {\n this.counter = additional ? this.counter + additional + 1 : this.counter + 1;\n if (this.parent)\n this.parent.incrementCounter(additional);\n};\n/**\n * Each subsegment holds a counter of its open subsegments. This decrements\n * the counter such that it can be called from a child and propagate up.\n */\nSubsegment.prototype.decrementCounter = function decrementCounter() {\n this.counter--;\n if (this.parent)\n this.parent.decrementCounter();\n};\n/**\n * Returns a boolean indicating whether or not the subsegment has been closed.\n * @returns {boolean} - Returns true if the subsegment is closed.\n */\nSubsegment.prototype.isClosed = function isClosed() {\n return !this.in_progress;\n};\n/**\n * Sends the subsegment to the daemon.\n */\nSubsegment.prototype.flush = function flush() {\n if (!this.parent || !this.segment) {\n throw new Error('Failed to flush subsegment: ' + this.name + '. Subsegment must be added ' +\n 'to a segment chain to flush.');\n }\n if (this.segment.trace_id) {\n if (this.segment.notTraced !== true) {\n SegmentEmitter.send(this);\n }\n else {\n logger.getLogger().debug('Ignoring flush on subsegment ' + this.id + '. Associated segment is marked as not sampled.');\n }\n }\n else {\n logger.getLogger().debug('Ignoring flush on subsegment ' + this.id + '. Associated segment is missing a trace ID.');\n }\n};\n/**\n * Returns true if the subsegment was streamed in its entirety\n */\nSubsegment.prototype.streamSubsegments = function streamSubsegments() {\n if (this.isClosed() && this.counter <= 0) {\n this.flush();\n return true;\n }\n else if (this.subsegments && this.subsegments.length > 0) {\n var open = [];\n this.subsegments.forEach(function (child) {\n if (!child.streamSubsegments())\n open.push(child);\n });\n this.subsegments = open;\n }\n};\n/**\n * Returns the formatted, trimmed subsegment JSON string to send to the daemon.\n */\nSubsegment.prototype.format = function format() {\n this.type = 'subsegment';\n if (this.parent)\n this.parent_id = this.parent.id;\n if (this.segment)\n this.trace_id = this.segment.trace_id;\n return JSON.stringify(this);\n};\n/**\n * Returns the formatted subsegment JSON string.\n */\nSubsegment.prototype.toString = function toString() {\n return JSON.stringify(this);\n};\nSubsegment.prototype.toJSON = function toJSON() {\n var ignore = ['segment', 'parent', 'counter'];\n if (this.subsegments == null || this.subsegments.length === 0)\n ignore.push('subsegments');\n var thisCopy = Utils.objectWithoutProperties(this, ignore, false);\n return thisCopy;\n};\nmodule.exports = Subsegment;\n", "\"use strict\";\nvar crypto = require('crypto');\nvar CapturedException = require('./attributes/captured_exception');\nvar SegmentEmitter = require('../segment_emitter');\nvar SegmentUtils = require('./segment_utils');\nvar Subsegment = require('./attributes/subsegment');\nvar TraceID = require('./attributes/trace_id');\nvar Utils = require('../utils');\nvar logger = require('../logger');\n/**\n * Represents a segment.\n * @constructor\n * @param {string} name - The name of the subsegment.\n * @param {string} [rootId] - The trace ID of the spawning parent, included in the 'X-Amzn-Trace-Id' header of the incoming request. If one is not supplied, it will be generated.\n * @param {string} [parentId] - The sub/segment ID of the spawning parent, included in the 'X-Amzn-Trace-Id' header of the incoming request.\n */\nfunction Segment(name, rootId, parentId) {\n this.init(name, rootId, parentId);\n}\nSegment.prototype.init = function init(name, rootId, parentId) {\n if (typeof name != 'string')\n throw new Error('Segment name must be of type string.');\n // Validate the Trace ID\n var traceId;\n if (rootId && typeof rootId == 'string') {\n traceId = TraceID.FromString(rootId);\n }\n else {\n traceId = new TraceID();\n }\n var id = crypto.randomBytes(8).toString('hex');\n var startTime = SegmentUtils.getCurrentTime();\n this.trace_id = traceId.toString();\n this.id = id;\n this.start_time = startTime;\n this.name = name || '';\n this.in_progress = true;\n this.counter = 0;\n if (parentId)\n this.parent_id = parentId;\n if (SegmentUtils.serviceData)\n this.setServiceData(SegmentUtils.serviceData);\n if (SegmentUtils.pluginData)\n this.addPluginData(SegmentUtils.pluginData);\n if (SegmentUtils.origin)\n this.origin = SegmentUtils.origin;\n if (SegmentUtils.sdkData)\n this.setSDKData(SegmentUtils.sdkData);\n};\n/**\n * Adds incoming request data to the http block of the segment.\n * @param {IncomingRequestData} data - The data of the property to add.\n */\nSegment.prototype.addIncomingRequestData = function addIncomingRequestData(data) {\n this.http = data;\n};\n/**\n * Adds a key-value pair that can be queryable through GetTraceSummaries.\n * Only acceptable types are string, float/int and boolean.\n * @param {string} key - The name of key to add.\n * @param {boolean|string|number} value - The value to add for the given key.\n */\nSegment.prototype.addAnnotation = function addAnnotation(key, value) {\n if (typeof value !== 'boolean' && typeof value !== 'string' && !isFinite(value)) {\n logger.getLogger().error('Add annotation key: ' + key + ' value: ' + value + ' failed.' +\n ' Annotations must be of type string, number or boolean.');\n return;\n }\n if (this.annotations === undefined)\n this.annotations = {};\n this.annotations[key] = value;\n};\n/**\n * Adds a User ID that can be queried from the X-Ray console. User ID\n * must be a string.\n * @param {string} user - The ID of the user corresponding to this segment\n */\nSegment.prototype.setUser = function (user) {\n if (typeof user !== 'string') {\n logger.getLogger().error('Set user: ' + user + ' failed. User IDs must be of type string.');\n }\n this.user = user;\n};\n/**\n * Adds a key-value pair to the metadata.default attribute when no namespace is given.\n * Metadata is not queryable, but is recorded.\n * @param {string} key - The name of the key to add.\n * @param {object|null} value - The value of the associated key.\n * @param {string} [namespace] - The property name to put the key/value pair under.\n */\nSegment.prototype.addMetadata = function (key, value, namespace) {\n if (typeof key !== 'string') {\n throw new Error('Failed to add annotation key: ' + key + ' value: ' + value + ' to subsegment ' +\n this.name + '. Key must be of type string.');\n }\n else if (namespace && typeof namespace !== 'string') {\n throw new Error('Failed to add annotation key: ' + key + ' value: ' + value + 'namespace: ' + namespace + ' to subsegment ' +\n this.name + '. Namespace must be of type string.');\n }\n var ns = namespace || 'default';\n if (!this.metadata) {\n this.metadata = {};\n }\n if (!this.metadata[ns]) {\n this.metadata[ns] = {};\n }\n this.metadata[ns][key] = value;\n};\n/**\n * Adds data about the AWS X-Ray SDK onto the segment.\n * @param {Object} data - Object that contains the version of the SDK, and other information.\n */\nSegment.prototype.setSDKData = function setSDKData(data) {\n if (!data) {\n logger.getLogger().error('Add SDK data: ' + data + ' failed.' +\n 'Must not be empty.');\n return;\n }\n if (!this.aws)\n this.aws = {};\n this.aws.xray = data;\n};\nSegment.prototype.setMatchedSamplingRule = function setMatchedSamplingRule(ruleName) {\n if (this.aws)\n this.aws = JSON.parse(JSON.stringify(this.aws));\n if (this.aws && this.aws['xray'])\n this.aws.xray['rule_name'] = ruleName;\n else\n this.aws = { xray: { 'rule_name': ruleName } };\n};\n/**\n * Adds data about the service into the segment.\n * @param {Object} data - Object that contains the version of the application, and other information.\n */\nSegment.prototype.setServiceData = function setServiceData(data) {\n if (!data) {\n logger.getLogger().error('Add service data: ' + data + ' failed.' +\n 'Must not be empty.');\n return;\n }\n this.service = data;\n};\n/**\n * Adds a service with associated version data into the segment.\n * @param {Object} data - The associated AWS data.\n */\nSegment.prototype.addPluginData = function addPluginData(data) {\n if (this.aws === undefined)\n this.aws = {};\n Object.assign(this.aws, data);\n};\n/**\n * Adds a new subsegment to the array of subsegments.\n * @param {string} name - The name of the new subsegment to append.\n */\nSegment.prototype.addNewSubsegment = function addNewSubsegment(name) {\n var subsegment = new Subsegment(name);\n this.addSubsegment(subsegment);\n return subsegment;\n};\n/**\n * Adds a subsegment to the array of subsegments.\n * @param {Subsegment} subsegment - The subsegment to append.\n */\nSegment.prototype.addSubsegment = function addSubsegment(subsegment) {\n if (!(subsegment instanceof Subsegment))\n throw new Error('Cannot add subsegment: ' + subsegment + '. Not a subsegment.');\n if (this.subsegments === undefined)\n this.subsegments = [];\n subsegment.segment = this;\n subsegment.parent = this;\n this.subsegments.push(subsegment);\n if (!subsegment.end_time)\n this.incrementCounter(subsegment.counter);\n};\n/**\n * Removes the subsegment from the subsegments array, used in subsegment streaming.\n */\nSegment.prototype.removeSubsegment = function removeSubsegment(subsegment) {\n if (!(subsegment instanceof Subsegment)) {\n throw new Error('Failed to remove subsegment:' + subsegment + ' from subsegment \"' + this.name +\n '\". Not a subsegment.');\n }\n if (this.subsegments !== undefined) {\n var index = this.subsegments.indexOf(subsegment);\n if (index >= 0)\n this.subsegments.splice(index, 1);\n }\n};\n/**\n * Adds error data into the segment.\n * @param {Error|string} err - The error to capture.\n * @param {boolean} [remote] - Flag for whether the exception caught was remote or not.\n */\nSegment.prototype.addError = function addError(err, remote) {\n if (err == null || typeof err !== 'object' && typeof (err) !== 'string') {\n throw new Error('Failed to add error:' + err + ' to subsegment \"' + this.name +\n '\". Not an object or string literal.');\n }\n this.addFaultFlag();\n if (this.exception) {\n if (err === this.exception.ex) {\n this.cause = { id: this.exception.cause };\n delete this.exception;\n return;\n }\n delete this.exception;\n }\n if (this.cause === undefined) {\n this.cause = {\n working_directory: process.cwd(),\n exceptions: []\n };\n }\n this.cause.exceptions.push(new CapturedException(err, remote));\n};\n/**\n * Adds fault flag to the subsegment.\n */\nSegment.prototype.addFaultFlag = function addFaultFlag() {\n this.fault = true;\n};\n/**\n * Adds error flag to the subsegment.\n */\nSegment.prototype.addErrorFlag = function addErrorFlag() {\n this.error = true;\n};\n/**\n * Adds throttle flag to the subsegment.\n */\nSegment.prototype.addThrottleFlag = function addThrottleFlag() {\n this.throttle = true;\n};\n/**\n * Returns a boolean indicating whether or not the segment has been closed.\n * @returns {boolean} - Returns true if the subsegment is closed.\n */\nSegment.prototype.isClosed = function isClosed() {\n return !this.in_progress;\n};\n/**\n * Each segment holds a counter of open subsegments. This increments the counter.\n * @param {Number} [additional] - An additional amount to increment. Used when adding subsegment trees.\n */\nSegment.prototype.incrementCounter = function incrementCounter(additional) {\n this.counter = additional ? this.counter + additional + 1 : this.counter + 1;\n if (this.counter > SegmentUtils.streamingThreshold && this.subsegments && this.subsegments.length > 0) {\n var open = [];\n this.subsegments.forEach(function (child) {\n if (!child.streamSubsegments())\n open.push(child);\n });\n this.subsegments = open;\n }\n};\n/**\n * Each segment holds a counter of open subsegments. This decrements\n * the counter such that it can be called from a child and propagate up.\n */\nSegment.prototype.decrementCounter = function decrementCounter() {\n this.counter--;\n if (this.counter <= 0 && this.isClosed()) {\n this.flush();\n }\n};\n/**\n * Closes the current segment. This automatically sets the end time.\n * @param {Error|string} [err] - The error to capture.\n * @param {boolean} [remote] - Flag for whether the exception caught was remote or not.\n */\nSegment.prototype.close = function (err, remote) {\n if (!this.end_time)\n this.end_time = SegmentUtils.getCurrentTime();\n if (err !== undefined)\n this.addError(err, remote);\n delete this.in_progress;\n delete this.exception;\n if (this.counter <= 0) {\n this.flush();\n }\n};\n/**\n * Sends the segment to the daemon.\n */\nSegment.prototype.flush = function flush() {\n if (this.notTraced !== true) {\n delete this.exception;\n var thisCopy = Utils.objectWithoutProperties(this, ['counter', 'notTraced'], true);\n SegmentEmitter.send(thisCopy);\n }\n};\nSegment.prototype.format = function format() {\n var ignore = ['segment', 'parent', 'counter'];\n if (this.subsegments == null || this.subsegments.length === 0)\n ignore.push('subsegments');\n var thisCopy = Utils.objectWithoutProperties(this, ignore, false);\n return JSON.stringify(thisCopy);\n};\nSegment.prototype.toString = function toString() {\n return JSON.stringify(this);\n};\nmodule.exports = Segment;\n", "\"use strict\";\n/**\n * @module context_utils\n */\nvar cls = require('cls-hooked/context');\nvar logger = require('./logger');\nvar Segment = require('./segments/segment');\nvar Subsegment = require('./segments/attributes/subsegment');\nvar cls_mode = true;\nvar NAMESPACE = 'AWSXRay';\nvar SEGMENT = 'segment';\nvar contextOverride = false;\nvar contextUtils = {\n CONTEXT_MISSING_STRATEGY: {\n RUNTIME_ERROR: {\n contextMissing: function contextMissingRuntimeError(message) {\n throw new Error(message);\n }\n },\n LOG_ERROR: {\n contextMissing: function contextMissingLogError(message) {\n var err = new Error(message);\n logger.getLogger().error(err.stack);\n }\n },\n IGNORE_ERROR: {\n contextMissing: function contextMissingIgnoreError(message) {\n }\n }\n },\n contextMissingStrategy: {},\n /**\n * Resolves the segment or subsegment given manual mode and params on the call required.\n * @param [Segment|Subsegment] segment - The segment manually provided via params.XraySegment, if provided.\n * @returns {Segment|Subsegment}\n * @alias module:context_utils.resolveManualSegmentParams\n */\n resolveManualSegmentParams: function resolveManualSegmentParams(params) {\n if (params && !contextUtils.isAutomaticMode()) {\n var xraySegment = params.XRaySegment || params.XraySegment;\n var segment = params.Segment;\n var found = null;\n if (xraySegment && (xraySegment instanceof Segment || xraySegment instanceof Subsegment)) {\n found = xraySegment;\n delete params.XRaySegment;\n delete params.XraySegment;\n }\n else if (segment && (segment instanceof Segment || segment instanceof Subsegment)) {\n found = segment;\n delete params.Segment;\n }\n return found;\n }\n },\n /**\n * Gets current CLS namespace for X-Ray SDK or creates one if absent.\n * @returns {Namespace}\n * @alias module:context_utils.getNamespace\n */\n getNamespace: function getNamespace() {\n return cls.getNamespace(NAMESPACE) || cls.createNamespace(NAMESPACE);\n },\n /**\n * Resolves the segment or subsegment given manual or automatic mode.\n * @param [Segment|Subsegment] segment - The segment manually provided, if provided.\n * @returns {Segment|Subsegment}\n * @alias module:context_utils.resolveSegment\n */\n resolveSegment: function resolveSegment(segment) {\n if (cls_mode) {\n return this.getSegment();\n }\n else if (segment && !cls_mode) {\n return segment;\n }\n else if (!segment && !cls_mode) {\n contextUtils.contextMissingStrategy.contextMissing('No sub/segment specified. A sub/segment must be provided for manual mode.');\n }\n },\n /**\n * Returns the current segment or subsegment. For use with in automatic mode only.\n * @returns {Segment|Subsegment}\n * @alias module:context_utils.getSegment\n */\n getSegment: function getSegment() {\n if (cls_mode) {\n var segment = contextUtils.getNamespace(NAMESPACE).get(SEGMENT);\n if (!segment) {\n contextUtils.contextMissingStrategy.contextMissing('Failed to get the current sub/segment from the context.');\n }\n else if (segment instanceof Segment && process.env.LAMBDA_TASK_ROOT && segment.facade == true) {\n segment.resolveLambdaTraceData();\n }\n return segment;\n }\n else {\n contextUtils.contextMissingStrategy.contextMissing('Cannot get sub/segment from context. Not supported in manual mode.');\n }\n },\n /**\n * Sets the current segment or subsegment. For use with in automatic mode only.\n * @param [Segment|Subsegment] segment - The sub/segment to set.\n * @returns {Segment|Subsegment}\n * @alias module:context_utils.setSegment\n */\n setSegment: function setSegment(segment) {\n if (cls_mode) {\n if (!contextUtils.getNamespace(NAMESPACE).set(SEGMENT, segment))\n logger.getLogger().warn('Failed to set the current sub/segment on the context.');\n }\n else {\n contextUtils.contextMissingStrategy.contextMissing('Cannot set sub/segment on context. Not supported in manual mode.');\n }\n },\n /**\n * Returns true if in automatic mode, otherwise false.\n * @returns {Segment|Subsegment}\n * @alias module:context_utils.isAutomaticMode\n */\n isAutomaticMode: function isAutomaticMode() {\n return cls_mode;\n },\n /**\n * Enables automatic mode. Automatic mode uses 'cls-hooked'.\n * @see https://github.com/jeff-lewis/cls-hooked\n * @alias module:context_utils.enableAutomaticMode\n */\n enableAutomaticMode: function enableAutomaticMode() {\n cls_mode = true;\n contextUtils.getNamespace(NAMESPACE);\n logger.getLogger().debug('Overriding AWS X-Ray SDK mode. Set to automatic mode.');\n },\n /**\n * Disables automatic mode. Current segment or subsegment then must be passed manually\n * via the parent optional on captureFunc, captureAsyncFunc etc.\n * @alias module:context_utils.enableManualMode\n */\n enableManualMode: function enableManualMode() {\n cls_mode = false;\n if (cls.getNamespace(NAMESPACE))\n cls.destroyNamespace(NAMESPACE);\n logger.getLogger().debug('Overriding AWS X-Ray SDK mode. Set to manual mode.');\n },\n /**\n * Sets the context missing strategy if no context missing strategy is set using the environment variable with\n * key AWS_XRAY_CONTEXT_MISSING. The context missing strategy's contextMissing function will be called whenever\n * trace context is not found.\n * @param {string|function} strategy - The strategy to set. Valid string values are 'LOG_ERROR' and 'RUNTIME_ERROR'.\n * Alternatively, a custom function can be supplied, which takes a error message string.\n */\n setContextMissingStrategy: function setContextMissingStrategy(strategy) {\n if (!contextOverride) {\n if (typeof strategy === 'string') {\n var lookupStrategy = contextUtils.CONTEXT_MISSING_STRATEGY[strategy.toUpperCase()];\n if (lookupStrategy) {\n contextUtils.contextMissingStrategy.contextMissing = lookupStrategy.contextMissing;\n if (process.env.AWS_XRAY_CONTEXT_MISSING)\n logger.getLogger().debug('AWS_XRAY_CONTEXT_MISSING is set. Configured context missing strategy to ' +\n process.env.AWS_XRAY_CONTEXT_MISSING + '.');\n else\n logger.getLogger().debug('Configured context missing strategy to: ' + strategy);\n }\n else {\n throw new Error('Invalid context missing strategy: ' + strategy + '. Valid values are ' +\n Object.keys(contextUtils.CONTEXT_MISSING_STRATEGY) + '.');\n }\n }\n else if (typeof strategy === 'function') {\n contextUtils.contextMissingStrategy.contextMissing = strategy;\n logger.getLogger().info('Configured custom context missing strategy to function: ' + strategy.name);\n }\n else {\n throw new Error('Context missing strategy must be either a string or a custom function.');\n }\n }\n else {\n logger.getLogger().warn('Ignoring call to setContextMissingStrategy as AWS_XRAY_CONTEXT_MISSING is set. ' +\n 'The current context missing strategy will not be changed.');\n }\n }\n};\ncls.createNamespace(NAMESPACE);\nlogger.getLogger().debug('Starting the AWS X-Ray SDK in automatic mode (default).');\nif (process.env.AWS_XRAY_CONTEXT_MISSING) {\n contextUtils.setContextMissingStrategy(process.env.AWS_XRAY_CONTEXT_MISSING);\n contextOverride = true;\n}\nelse {\n contextUtils.contextMissingStrategy.contextMissing = contextUtils.CONTEXT_MISSING_STRATEGY.RUNTIME_ERROR.contextMissing;\n logger.getLogger().debug('Using default context missing strategy: RUNTIME_ERROR');\n}\nmodule.exports = contextUtils;\n", "\"use strict\";\nvar { getHttpResponseData } = require('../segments/segment_utils');\n/**\n * Represents an incoming HTTP/HTTPS call.\n * @constructor\n * @param {http.IncomingMessage|https.IncomingMessage} req - The request object from the HTTP/HTTPS call.\n */\nfunction IncomingRequestData(req) {\n this.init(req);\n}\nIncomingRequestData.prototype.init = function init(req) {\n var forwarded = !!req.headers['x-forwarded-for'];\n var url;\n if (req.connection)\n url = ((req.connection.secure || req.connection.encrypted) ? 'https://' : 'http://') +\n ((req.headers['host'] || '') + (req.url || ''));\n this.request = {\n method: req.method || '',\n user_agent: req.headers['user-agent'] || '',\n client_ip: getClientIp(req) || '',\n url: url || '',\n };\n if (forwarded)\n this.request.x_forwarded_for = forwarded;\n};\nvar getClientIp = function getClientIp(req) {\n var clientIp;\n if (req.headers['x-forwarded-for'])\n clientIp = (req.headers['x-forwarded-for'] || '').split(',')[0];\n else if (req.connection && req.connection.remoteAddress)\n clientIp = req.connection.remoteAddress;\n else if (req.socket && req.socket.remoteAddress)\n clientIp = req.socket.remoteAddress;\n else if (req.connection && req.connection.socket && req.connection.socket.remoteAddress)\n clientIp = req.connection.socket.remoteAddress;\n return clientIp;\n};\n/**\n * Closes the local and automatically captures the response data.\n * @param {http.ServerResponse|https.ServerResponse} res - The response object from the HTTP/HTTPS call.\n */\nIncomingRequestData.prototype.close = function close(res) {\n this.response = getHttpResponseData(res);\n};\nmodule.exports = IncomingRequestData;\n", "\"use strict\";\n/**\n * Represents a LocalReservoir object that keeps track of the number of traces per second sampled and\n * the fixed rate for a given sampling rule defined locally.\n * It also decides if a given trace should be sampled or not based on the state of current second.\n * @constructor\n * @param {number} fixedTarget - An integer value to specify the maximum number of traces per second to sample.\n * @param {number} fallbackRate - A value between 0 and 1 indicating the sampling rate after the maximum traces per second has been hit.\n */\nfunction LocalReservoir(fixedTarget, fallbackRate) {\n this.init(fixedTarget, fallbackRate);\n}\nLocalReservoir.prototype.init = function init(fixedTarget, fallbackRate) {\n this.usedThisSecond = 0;\n if (typeof fixedTarget === 'number' && fixedTarget % 1 === 0 && fixedTarget >= 0)\n this.fixedTarget = fixedTarget;\n else\n throw new Error('Error in sampling file. Rule attribute \"fixed_target\" must be a non-negative integer.');\n if (typeof fallbackRate === 'number' && fallbackRate >= 0 && fallbackRate <= 1)\n this.fallbackRate = fallbackRate;\n else\n throw new Error('Error in sampling file. Rule attribute \"rate\" must be a number between 0 and 1 inclusive.');\n};\nLocalReservoir.prototype.isSampled = function isSampled() {\n var now = Math.round(new Date().getTime() / 1000);\n if (now !== this.thisSecond) {\n this.usedThisSecond = 0;\n this.thisSecond = now;\n }\n if (this.usedThisSecond >= this.fixedTarget)\n return Math.random() < this.fallbackRate;\n this.usedThisSecond++;\n return true;\n};\nmodule.exports = LocalReservoir;\n", "\"use strict\";\nvar fs = require('fs');\nvar LocalReservoir = require('./local_reservoir');\nvar Utils = require('../../utils');\nvar defaultRules = require('../../resources/default_sampling_rules.json');\nvar logger = require('../../logger');\n/**\n * The local sampler used to make sampling decisions when the decisions are absent in the incoming requests\n * and the default sampler needs to fall back on local rules. It will also be the primary sampler\n * if the default sampler is disabled.\n * @module LocalSampler\n */\nvar LocalSampler = {\n /**\n * Makes a sample decision based on the sample request.\n * @param {object} sampleRequest - Contains information for rules matching.\n * @module LocalSampler\n * @function shouldSample\n */\n shouldSample: function shouldSample(sampleRequest) {\n var host = sampleRequest.host;\n var httpMethod = sampleRequest.httpMethod;\n var urlPath = sampleRequest.urlPath;\n var formatted = '{ http_method: ' + httpMethod + ', host: ' + host + ', url_path: ' + urlPath + ' }';\n var matched;\n this.rules.some(function (rule) {\n // Any null parameters provided will be considered an implicit match.\n if (rule.default || (host == null || (Utils.wildcardMatch(rule.host, host))\n && (httpMethod == null || Utils.wildcardMatch(rule.http_method, httpMethod))\n && (urlPath == null || Utils.wildcardMatch(rule.url_path, urlPath)))) {\n matched = rule.reservoir;\n logger.getLogger().debug('Local sampling rule match found for ' + formatted + '. Matched ' + (rule.default ?\n 'default' : '{ http_method: ' + rule.http_method + ', host: ' + rule.host + ', url_path: ' +\n rule.url_path + ' }') + '. Using fixed_target: ' + matched.fixedTarget + ' and rate: ' + matched.fallbackRate + '.');\n return true;\n }\n });\n if (matched) {\n return matched.isSampled();\n }\n else {\n logger.getLogger().debug('No sampling rule matched for ' + formatted);\n return false;\n }\n },\n /**\n * Set local rules for making sampling decisions.\n * @module LocalSampler\n * @function setLocalRules\n */\n setLocalRules: function setLocalRules(source) {\n if (source) {\n if (typeof source === 'string') {\n logger.getLogger().info('Using custom sampling rules file: ' + source);\n this.rules = loadRulesConfig(JSON.parse(fs.readFileSync(source, 'utf8')));\n }\n else {\n logger.getLogger().info('Using custom sampling rules source.');\n this.rules = loadRulesConfig(source);\n }\n }\n else\n this.rules = parseRulesConfig(defaultRules);\n }\n};\nvar loadRulesConfig = function loadRulesConfig(config) {\n if (!config.version)\n throw new Error('Error in sampling file. Missing \"version\" attribute.');\n if (config.version === 1 || config.version === 2)\n return parseRulesConfig(config);\n else\n throw new Error('Error in sampling file. Unknown version \"' + config.version + '\".');\n};\nvar parseRulesConfig = function parseRulesConfig(config) {\n var defaultRule;\n var rules = [];\n if (config.default) {\n var missing = [];\n for (var key in config.default) {\n if (key !== 'fixed_target' && key !== 'rate') {\n throw new Error('Error in sampling file. Invalid attribute for default: ' + key +\n '. Valid attributes for default are \"fixed_target\" and \"rate\".');\n }\n else if (typeof config.default[key] !== 'number') {\n throw new Error('Error in sampling file. Default ' + key + ' must be a number.');\n }\n }\n if (typeof config.default.fixed_target === 'undefined')\n missing.push('fixed_target');\n if (typeof config.default.rate === 'undefined')\n missing.push('rate');\n if (missing.length !== 0)\n throw new Error('Error in sampling file. Missing required attributes for default: ' + missing + '.');\n defaultRule = { default: true, reservoir: new LocalReservoir(config.default.fixed_target, config.default.rate) };\n }\n else {\n throw new Error('Error in sampling file. Expecting \"default\" object to be defined with attributes \"fixed_target\" and \"rate\".');\n }\n if (Array.isArray(config.rules)) {\n config.rules.forEach(function (rawRule) {\n var params = {};\n var required;\n if (config.version === 2)\n required = { host: 1, http_method: 1, url_path: 1, fixed_target: 1, rate: 1 };\n if (config.version === 1)\n required = { service_name: 1, http_method: 1, url_path: 1, fixed_target: 1, rate: 1 };\n for (var key in rawRule) {\n var value = rawRule[key];\n if (!required[key] && key != 'description')\n throw new Error('Error in sampling file. Rule ' + JSON.stringify(rawRule) + ' has invalid attribute: ' + key + '.');\n else if (key != 'description' && !value && value !== 0)\n throw new Error('Error in sampling file. Rule ' + JSON.stringify(rawRule) + ' attribute \"' + key + '\" has invalid value: ' + value + '.');\n else {\n if (config.version === 2)\n params[key] = value;\n if (config.version === 1 && key === 'service_name')\n params['host'] = value;\n else\n params[key] = value;\n delete required[key];\n }\n }\n if (Object.keys(required).length !== 0 && required.constructor === Object)\n throw new Error('Error in sampling file. Rule ' + JSON.stringify(rawRule) + ' is missing required attributes: ' + Object.keys(required) + '.');\n var rule = params;\n rule.reservoir = new LocalReservoir(rawRule.fixed_target, rawRule.rate);\n rules.push(rule);\n });\n }\n rules.push(defaultRule);\n return rules;\n};\nLocalSampler.setLocalRules();\nmodule.exports = LocalSampler;\n", "\"use strict\";\n/**\n * Represents a Reservoir object that keeps track of the number of traces per second sampled and\n * the fixed rate for a given sampling rule. This information is fetched from X-Ray serivce.\n * It decides if a given trace should be borrowed or sampled or not sampled based on the state of current second.\n * @constructor\n */\nfunction Reservoir() {\n this.init();\n}\nReservoir.prototype.init = function init() {\n this.quota = null;\n this.TTL = null;\n this.takenThisSec = 0;\n this.borrowedThisSec = 0;\n this.reportInterval = 1;\n this.reportElapsed = 0;\n};\nReservoir.prototype.borrowOrTake = function borrowOrTake(now, canBorrow) {\n this.adjustThisSec(now);\n // Don't borrow if the quota is available and fresh.\n if (this.quota >= 0 && this.TTL >= now) {\n if (this.takenThisSec >= this.quota)\n return false;\n this.takenThisSec++;\n return 'take';\n }\n // Otherwise try to borrow if the quota is not present or expired.\n if (canBorrow) {\n if (this.borrowedThisSec >= 1)\n return false;\n this.borrowedThisSec++;\n return 'borrow';\n }\n};\nReservoir.prototype.adjustThisSec = function adjustThisSec(now) {\n if (now !== this.thisSec) {\n this.takenThisSec = 0;\n this.borrowedThisSec = 0;\n this.thisSec = now;\n }\n};\nReservoir.prototype.loadNewQuota = function loadNewQuota(quota, TTL, interval) {\n if (quota)\n this.quota = quota;\n if (TTL)\n this.TTL = TTL;\n if (interval)\n this.reportInterval = interval / 10; // Report interval is always time of 10.\n};\nReservoir.prototype.timeToReport = function timeToReport() {\n if (this.reportElapsed + 1 >= this.reportInterval) {\n this.reportElapsed = 0;\n return true;\n }\n else {\n this.reportElapsed += 1;\n return false;\n }\n};\nmodule.exports = Reservoir;\n", "\"use strict\";\nvar Utils = require('../../utils');\nvar Reservoir = require('./reservoir');\n/**\n * The data model for a sampling rule defined using X-Ray API CreateSamplingRules.\n * It should be only instantiated directly from the X-Ray API response.\n * @constructor\n */\nfunction SamplingRule(name, priority, rate, reservoirSize, host, httpMethod, urlPath, serviceName, serviceType) {\n this.init(name, priority, rate, reservoirSize, host, httpMethod, urlPath, serviceName, serviceType);\n}\nSamplingRule.prototype.init = function init(name, priority, rate, reservoirSize, host, httpMethod, urlPath, serviceName, serviceType) {\n this.name = name;\n this.priority = priority;\n this.rate = rate;\n this.host = host;\n this.httpMethod = httpMethod;\n this.urlPath = urlPath;\n this.serviceName = serviceName;\n this.serviceType = serviceType;\n this.reservoir = new Reservoir();\n this.borrow = !!reservoirSize;\n this.resetStatistics();\n};\nSamplingRule.prototype.match = function match(sampleRequest) {\n var host = sampleRequest.host;\n var httpMethod = sampleRequest.httpMethod;\n var serviceName = sampleRequest.serviceName;\n var urlPath = sampleRequest.urlPath;\n var serviceType = sampleRequest.serviceType;\n return this.isDefault() || (!host || Utils.wildcardMatch(this.host, host))\n && (!httpMethod || Utils.wildcardMatch(this.httpMethod, httpMethod))\n && (!serviceName || Utils.wildcardMatch(this.serviceName, serviceName))\n && (!urlPath || Utils.wildcardMatch(this.urlPath, urlPath))\n && (!serviceType || Utils.wildcardMatch(this.serviceType, serviceType));\n};\nSamplingRule.prototype.snapshotStatistics = function snapshotStatistics() {\n var statistics = {\n requestCount: this.requestCount,\n borrowCount: this.borrowCount,\n sampledCount: this.sampledCount\n };\n this.resetStatistics();\n return statistics;\n};\nSamplingRule.prototype.merge = function merge(rule) {\n this.reservoir = rule.reservoir;\n this.requestCount = rule.requestCount;\n this.borrowCount = rule.borrowCount;\n this.sampledCount = rule.sampledCount;\n rule = null; // unref the old rule so it can be garbage collected.\n};\nSamplingRule.prototype.isDefault = function isDefault() {\n return this.name === 'Default'; // \"Default\" is a reserved keyword from X-Ray back-end.\n};\nSamplingRule.prototype.incrementRequestCount = function incrementRequestCount() {\n this.requestCount++;\n};\nSamplingRule.prototype.incrementBorrowCount = function incrementBorrowCount() {\n this.borrowCount++;\n};\nSamplingRule.prototype.incrementSampledCount = function incrementSampledCount() {\n this.sampledCount++;\n};\nSamplingRule.prototype.setRate = function setRate(rate) {\n this.rate = rate;\n};\nSamplingRule.prototype.getRate = function getRate() {\n return this.rate;\n};\nSamplingRule.prototype.getName = function getName() {\n return this.name;\n};\nSamplingRule.prototype.getPriority = function getPriority() {\n return this.priority;\n};\nSamplingRule.prototype.getReservoir = function getReservoir() {\n return this.reservoir;\n};\nSamplingRule.prototype.resetStatistics = function resetStatistics() {\n this.requestCount = 0;\n this.borrowCount = 0;\n this.sampledCount = 0;\n};\nSamplingRule.prototype.canBorrow = function canBorrow() {\n return this.borrow;\n};\nSamplingRule.prototype.everMatched = function everMatched() {\n return this.requestCount > 0;\n};\nSamplingRule.prototype.timeToReport = function timeToReport() {\n return this.reservoir.timeToReport();\n};\nmodule.exports = SamplingRule;\n", "\"use strict\";\nvar crypto = require('crypto');\nvar logger = require('../../logger');\nvar SamplingRule = require('./sampling_rule');\nvar DaemonConfig = require('../../daemon_config');\nconst util = require('util');\nconst http = require('http');\n/**\n * The ServiceConnector that calls X-Ray service and convert the API response bodies to data models\n * defined in the X-Ray SDK and return them to the pollers.\n * @module ServiceConnector\n */\nvar ServiceConnector = {\n // client_id is a 12 byte cryptographically secure random hex\n // identifying the SDK instance and is generated during SDK initialization/\n // This is required when reporting sampling to X-Ray back-end.\n clientId: crypto.randomBytes(12).toString('hex'),\n samplingRulesPath: '/GetSamplingRules',\n samplingTargetsPath: '/SamplingTargets',\n logger: logger,\n httpClient: http,\n fetchSamplingRules: function fetchSamplingRules(callback) {\n const body = '{}'; // Payload needed for GetSamplingRules POST request\n const options = getOptions(this.samplingRulesPath, body.length);\n const httpReq = this.httpClient.__request ? this.httpClient.__request : this.httpClient.request;\n const req = httpReq(options, res => {\n var data = '';\n res.on('data', d => {\n data += d;\n });\n res.on('error', error => {\n callback(error);\n });\n res.on('end', () => {\n var dataObj;\n try {\n dataObj = JSON.parse(data);\n }\n catch (err) {\n callback(err);\n return;\n }\n if (!dataObj) {\n callback(new Error('AWS X-Ray GetSamplingRules API returned empty response'));\n return;\n }\n var newRules = assembleRules(dataObj);\n callback(null, newRules);\n });\n });\n req.on('error', (err) => {\n callback(new Error(`Failed to connect to X-Ray daemon at ${options.hostname}:${options.port} to get sampling rules.`));\n });\n req.write(body);\n req.end();\n },\n fetchTargets: function fetchTargets(rules, callback) {\n const body = JSON.stringify(constructStatisticsDocs(rules));\n const options = getOptions(this.samplingTargetsPath, body.length);\n const httpReq = this.httpClient.__request ? this.httpClient.__request : this.httpClient.request;\n const req = httpReq(options, res => {\n var data = '';\n res.on('data', d => {\n data += d;\n });\n res.on('error', error => {\n callback(error);\n });\n res.on('end', () => {\n var dataObj;\n try {\n dataObj = JSON.parse(data);\n }\n catch (err) {\n callback(err);\n return;\n }\n if (!dataObj || typeof dataObj['LastRuleModification'] != 'number') {\n callback(new Error('AWS X-Ray SamplingTargets API returned invalid response'));\n return;\n }\n var targetsMapping = assembleTargets(dataObj);\n var ruleFreshness = dateToEpoch(dataObj['LastRuleModification']);\n callback(null, targetsMapping, ruleFreshness);\n });\n });\n req.on('error', (err) => {\n callback(new Error(`Failed to connect to X-Ray daemon at ${options.hostname}:${options.port} to get sampling targets.`));\n });\n req.write(body);\n req.end();\n }\n};\nvar constructStatisticsDocs = function constructStatisticsDocs(rules) {\n var documents = [];\n var now = Math.floor(new Date().getTime() / 1000);\n rules.forEach(function (rule) {\n var statistics = rule.snapshotStatistics();\n var doc = {\n 'RuleName': rule.getName(),\n 'ClientID': ServiceConnector.clientId,\n 'RequestCount': statistics.requestCount,\n 'BorrowCount': statistics.borrowCount,\n 'SampledCount': statistics.sampledCount,\n 'Timestamp': now\n };\n documents.push(doc);\n });\n return { SamplingStatisticsDocuments: documents };\n};\nvar assembleRules = function assembleRules(data) {\n var newRules = [];\n var ruleList = data['SamplingRuleRecords'] || [];\n ruleList.forEach(function (ruleRecord) {\n ruleRecord = ruleRecord['SamplingRule'];\n // For forward compatibility reason right now it only\n // deals with version 1 sampling rules.\n if (isRuleValid(ruleRecord)) {\n var newRule = new SamplingRule(ruleRecord['RuleName'], ruleRecord['Priority'], ruleRecord['FixedRate'], ruleRecord['ReservoirSize'], ruleRecord['Host'], ruleRecord['HTTPMethod'], ruleRecord['URLPath'], ruleRecord['ServiceName'], ruleRecord['ServiceType']);\n newRules.push(newRule);\n }\n });\n return newRules;\n};\nvar assembleTargets = function assembleTargets(data) {\n var docs = data['SamplingTargetDocuments'] || [];\n var targetsMapping = {};\n docs.forEach(function (doc) {\n var newTarget = {\n rate: doc['FixedRate'],\n quota: doc['ReservoirQuota'],\n TTL: dateToEpoch(doc['ReservoirQuotaTTL']),\n interval: doc['Interval']\n };\n targetsMapping[doc['RuleName']] = newTarget;\n });\n return targetsMapping;\n};\nvar isRuleValid = function isRuleValid(record) {\n return record['Version'] === 1\n && record['ResourceARN'] === '*'\n && record['Attributes'] && Object.keys(record['Attributes']).length === 0\n && record['ServiceType']\n && record['RuleName']\n && record['Priority']\n && typeof record['FixedRate'] == 'number';\n};\nvar dateToEpoch = function dateToEpoch(date) {\n return new Date(date).getTime() / 1000;\n};\nvar getOptions = function getOptions(path, contentLength) {\n const options = {\n hostname: DaemonConfig.tcp_ip,\n port: DaemonConfig.tcp_port,\n method: 'POST',\n path: path,\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': contentLength,\n 'Host': util.format('%s:%d', DaemonConfig.tcp_ip, DaemonConfig.tcp_port)\n }\n };\n return options;\n};\nmodule.exports = ServiceConnector;\n", "\"use strict\";\nvar TTL = 60 * 60; // The cache expires 1 hour after the last refresh time.\n/**\n * The rule cache that stores sampling rules fetched from X-Ray service.\n * @module RuleCache\n */\nvar RuleCache = {\n rules: [],\n lastUpdated: null,\n /**\n * Tries to find a valid rule that matches the sample request.\n * @param {object} sampleRequest - Contains information for rules matching.\n * @param {number} now - Current epoch in seconds.\n * @module RuleCache\n * @function getMatchedRule\n */\n getMatchedRule: function getMatchedRule(sampleRequest, now) {\n if (isExpired(now))\n return null;\n var matchedRule;\n this.rules.forEach(function (rule) {\n if (!matchedRule && rule.match(sampleRequest))\n matchedRule = rule;\n if (rule.isDefault() && !matchedRule)\n matchedRule = rule;\n });\n return matchedRule;\n },\n /**\n * Load rules fetched from X-Ray service in order sorted by priorities.\n * @param {object} rules - Newly fetched rules to load.\n * @module RuleCache\n * @function loadRules\n */\n loadRules: function loadRules(rules) {\n // Record the old rules for later merging.\n var oldRules = {};\n this.rules.forEach(function (rule) {\n oldRules[rule.getName()] = rule;\n });\n // Update the rules in the cache.\n this.rules = rules;\n // Transfer state information to refreshed rules.\n this.rules.forEach(function (rule) {\n var oldRule = oldRules[rule.getName()];\n if (oldRule)\n rule.merge(oldRule);\n });\n // The cache should maintain the order of the rules based on\n // priority. If priority is the same we sort name by alphabet\n // as rule name is unique.\n this.rules.sort(function (a, b) {\n var v = a.getPriority() - b.getPriority();\n if (v !== 0)\n return v;\n if (a.getName() > b.getName())\n return 1;\n else\n return -1;\n });\n },\n /**\n * Load targets fetched from X-Ray service.\n * @param {object} targetsMapping - Newly fetched targets map with rule name as key.\n * @module RuleCache\n * @function loadTargets\n */\n loadTargets: function loadTargets(targetsMapping) {\n this.rules.forEach(function (rule) {\n var target = targetsMapping[rule.getName()];\n if (target) {\n rule.getReservoir().loadNewQuota(target.quota, target.TTL, target.interval);\n rule.setRate(target.rate);\n }\n });\n },\n getRules: function getRules() {\n return this.rules;\n },\n timestamp: function timestamp(now) {\n this.lastUpdated = now;\n },\n getLastUpdated: function getLastUpdated() {\n return this.lastUpdated;\n }\n};\nvar isExpired = function isExpired(now) {\n // The cache is considered expired if it is never loaded.\n if (!RuleCache.getLastUpdated())\n return true;\n return now > RuleCache.getLastUpdated() + TTL;\n};\nmodule.exports = RuleCache;\n", "\"use strict\";\nvar logger = require('../../logger');\nvar ServiceConnector = require('./service_connector');\nvar ruleCache = require('./rule_cache');\nvar DEFAULT_INTERVAL = 5 * 60 * 1000; // 5 minutes on sampling rules fetch\n/**\n * The RulePoller that periodically fetch sampling rules from X-Ray service\n * and load them into RuleCache.\n * @module RulePoller\n */\nvar RulePoller = {\n start: function start() {\n if (this.poller)\n clearInterval(this.poller);\n // Refresh sampling rules cache with no jitter upon start.\n refresh(false);\n this.poller = setInterval(refresh, DEFAULT_INTERVAL);\n this.poller.unref();\n },\n};\nvar refresh = function refresh(jitter) {\n // Add jitter by default unless explicitly told not to.\n jitter = typeof jitter === 'undefined' ? true : jitter;\n if (jitter) {\n var delay = getJitter();\n setTimeout(refreshWithFirewall, delay);\n }\n else\n refreshWithFirewall();\n};\nvar refreshWithFirewall = function refreshWithFirewall() {\n try {\n refreshCache();\n }\n catch (e) {\n logger.getLogger().warn('Encountered unexpected exception when fetching sampling rules: ' + e);\n }\n};\nvar refreshCache = function refreshCache() {\n // Timestamp should be generated *before* the actual outbound call to ensure\n // we don't mark the cache as being fresher than it actually is.\n var now = Math.floor(new Date().getTime() / 1000);\n // Pass a callback that only runs when the new rules are\n // successfully fetched. \n ServiceConnector.fetchSamplingRules(function (err, newRules) {\n if (err) {\n logger.getLogger().warn('Failed to retrieve sampling rules from X-Ray service:', err);\n }\n else if (newRules.length !== 0) {\n ruleCache.loadRules(newRules);\n ruleCache.timestamp(now);\n logger.getLogger().info('Successfully refreshed centralized sampling rule cache.');\n }\n });\n};\n// A random jitter of up to 5 seconds is injected after every run to ensure\n// the calls eventually get evenly distributed over the 5 minute window.\nvar getJitter = function getJitter() {\n return Math.random() * 5;\n};\nmodule.exports = RulePoller;\n", "\"use strict\";\nvar rulePoller = require('./rule_poller');\nvar serviceConnector = require('./service_connector');\nvar ruleCache = require('./rule_cache');\nvar logger = require('../../logger');\nvar DEFAULT_INTERVAL = 10 * 1000; // 10 seconds on sampling targets fetch\n/**\n * The TargetPoller that periodically fetch sampling targets from X-Ray service\n * and load them into RuleCache.\n * @module TargetPoller\n */\nvar TargetPoller = {\n interval: DEFAULT_INTERVAL,\n start: function start() {\n this.poller = setInterval(refreshWithFirewall, DEFAULT_INTERVAL + getJitter());\n this.poller.unref();\n },\n};\nvar refreshWithFirewall = function refreshWithFirewall() {\n try {\n refresh();\n }\n catch (e) {\n logger.getLogger().warn('Encountered unexpected exception when fetching sampling targets: ' + e);\n }\n};\nvar refresh = function refresh() {\n var candidates = getCandidates();\n if (candidates && candidates.length > 0) {\n serviceConnector.fetchTargets(candidates, function (err, targetsMapping, ruleFreshness) {\n if (err) {\n logger.getLogger().warn('Failed to retrieve sampling targets from X-Ray service:', err);\n return;\n }\n ruleCache.loadTargets(targetsMapping);\n if (ruleFreshness > ruleCache.getLastUpdated()) {\n logger.getLogger().info('Performing out-of-band sampling rule polling to fetch updated rules.');\n rulePoller.start();\n }\n logger.getLogger().info('Successfully reported rule statistics to get new sampling quota.');\n });\n }\n};\n// Don't report a rule statistics if any of the conditions is met:\n// 1. The report time hasn't come (some rules might have larger report intervals).\n// 2. The rule is never matched.\nvar getCandidates = function getCandidates() {\n var rules = ruleCache.getRules();\n var candidates = [];\n rules.forEach(function (rule) {\n if (rule.everMatched() && rule.timeToReport())\n candidates.push(rule);\n });\n return candidates;\n};\n// A random jitter of up to 0.1 seconds is injected after every run to ensure\n// the calls eventually get evenly distributed over the 10 second window.\nvar getJitter = function getJitter() {\n return Math.random() / TargetPoller.interval;\n};\nmodule.exports = TargetPoller;\n", "\"use strict\";\nvar logger = require('../../logger');\nconst util = require('util');\nvar SegmentUtils = require('../../segments/segment_utils');\n/**\n * The default sampler used to make sampling decisions when the decisions are absent in the incoming requests.\n * The sampler use pollers to poll sampling rules from X-Ray service.\n * @module DefaultSampler\n */\nvar DefaultSampler = {\n localSampler: require('./local_sampler'),\n rulePoller: require('./rule_poller'),\n targetPoller: require('./target_poller'),\n ruleCache: require('./rule_cache'),\n started: false,\n /**\n * Makes a sample decision based on the sample request.\n * @param {object} sampleRequest - Contains information for rules matching.\n * @module DefaultSampler\n * @function shouldSample\n */\n shouldSample: function shouldSample(sampleRequest) {\n try {\n if (!this.started)\n this.start();\n if (!sampleRequest.serviceType)\n sampleRequest.serviceType = SegmentUtils.origin;\n var now = Math.floor(new Date().getTime() / 1000);\n var matchedRule = this.ruleCache.getMatchedRule(sampleRequest, now);\n if (matchedRule) {\n logger.getLogger().debug(util.format('Rule %s is matched.', matchedRule.getName()));\n return processMatchedRule(matchedRule, now);\n }\n else {\n logger.getLogger().info('No effective centralized sampling rule match. Fallback to local rules.');\n return this.localSampler.shouldSample(sampleRequest);\n }\n }\n catch (err) {\n logger.getLogger().error('Unhandled exception by the SDK during making sampling decisions: ' + err);\n }\n },\n /**\n * Set local rules in case there is a need to fallback.\n * @module DefaultSampler\n * @function setLocalRules\n */\n setLocalRules: function setLocalRules(source) {\n this.localSampler.setLocalRules(source);\n },\n /**\n * Start the pollers to poll sampling rules and targets from X-Ray service.\n * @module DefaultSampler\n * @function start\n */\n start: function start() {\n if (!this.started) {\n this.rulePoller.start();\n this.targetPoller.start();\n this.started = true;\n }\n }\n};\nvar processMatchedRule = function processMatchedRule(rule, now) {\n // As long as a rule is matched we increment request counter.\n rule.incrementRequestCount();\n var reservoir = rule.getReservoir();\n var sample = true;\n // We check if we can borrow or take from reservoir first.\n var decision = reservoir.borrowOrTake(now, rule.canBorrow());\n if (decision === 'borrow')\n rule.incrementBorrowCount();\n else if (decision === 'take')\n rule.incrementSampledCount();\n // Otherwise we compute based on FixedRate of this sampling rule.\n else if (Math.random() <= rule.getRate())\n rule.incrementSampledCount();\n else\n sample = false;\n if (sample)\n return rule.getName();\n else\n return false;\n};\nmodule.exports = DefaultSampler;\n", "\"use strict\";\n/**\n * Middleware Utils module.\n *\n * Exposes various configuration and helper methods to be used by the middleware.\n * @module mw_utils\n */\nvar Segment = require('../segments/segment');\nvar IncomingRequestData = require('./incoming_request_data');\nvar logger = require('../logger');\nvar coreUtils = require('../utils');\nvar wildcardMatch = require('../utils').wildcardMatch;\nvar processTraceData = require('../utils').processTraceData;\n//headers are case-insensitive\nvar XRAY_HEADER = 'x-amzn-trace-id';\nvar overrideFlag = !!process.env.AWS_XRAY_TRACING_NAME;\nvar utils = {\n defaultName: process.env.AWS_XRAY_TRACING_NAME,\n dynamicNaming: false,\n hostPattern: null,\n sampler: require('./sampling/default_sampler'),\n /**\n * Enables dynamic naming for segments via the middleware. Use 'AWSXRay.middleware.enableDynamicNaming()'.\n * @param {string} [hostPattern] - The pattern to match the host header. See the README on dynamic and fixed naming modes.\n * @alias module:mw_utils.enableDynamicNaming\n */\n enableDynamicNaming: function (hostPattern) {\n this.dynamicNaming = true;\n if (hostPattern && typeof hostPattern !== 'string')\n throw new Error('Host pattern must be a string.');\n this.hostPattern = hostPattern || null;\n },\n /**\n * Splits out the 'x-amzn-trace-id' header params from the incoming request. Used by the middleware.\n * @param {http.IncomingMessage|https.IncomingMessage} req - The request object from the incoming call.\n * @returns {object}\n * @alias module:mw_utils.processHeaders\n */\n processHeaders: function processHeaders(req) {\n var amznTraceHeader = {};\n if (req && req.headers && req.headers[XRAY_HEADER]) {\n amznTraceHeader = processTraceData(req.headers[XRAY_HEADER]);\n }\n return amznTraceHeader;\n },\n /**\n * Resolves the name of the segment as determined by fixed or dynamic mode options. Used by the middleware.\n * @param {string} hostHeader - The string from the request.headers.host property.\n * @returns {string}\n * @alias module:mw_utils.resolveName\n */\n resolveName: function resolveName(hostHeader) {\n var name;\n if (this.dynamicNaming && hostHeader)\n name = this.hostPattern ? (wildcardMatch(this.hostPattern, hostHeader) ? hostHeader : this.defaultName) : hostHeader;\n else\n name = this.defaultName;\n return name;\n },\n /**\n * Resolves the sampling decision as determined by the values given and options set. Used by the middleware.\n * @param {object} amznTraceHeader - The object as returned by the processHeaders function.\n * @param {Segment} segment - The string from the request.headers.host property.\n * @param {http.ServerResponse|https.ServerResponse} res - The response object from the incoming call.\n * @returns {boolean}\n * @alias module:mw_utils.resolveSampling\n */\n resolveSampling: function resolveSampling(amznTraceHeader, segment, res) {\n var isSampled;\n if (amznTraceHeader.sampled === '1')\n isSampled = true;\n else if (amznTraceHeader.sampled === '0')\n isSampled = false;\n else {\n var sampleRequest = {\n host: res.req.headers.host,\n httpMethod: res.req.method,\n urlPath: res.req.url,\n serviceName: segment.name\n };\n isSampled = this.sampler.shouldSample(sampleRequest);\n if (isSampled instanceof String || typeof isSampled === 'string') {\n segment.setMatchedSamplingRule(isSampled);\n isSampled = true;\n }\n }\n if (amznTraceHeader.sampled === '?')\n res.header[XRAY_HEADER] = 'Root=' + amznTraceHeader.root + ';Sampled=' + (isSampled ? '1' : '0');\n if (!isSampled)\n segment.notTraced = true;\n },\n /**\n * Sets the default name of created segments. Used with the middleware.\n * Can be overridden by the AWS_XRAY_TRACING_NAME environment variable.\n * @param {string} name - The default name for segments created in the middleware.\n * @alias module:mw_utils.setDefaultName\n */\n setDefaultName: function setDefaultName(name) {\n if (!overrideFlag)\n this.defaultName = name;\n },\n disableCentralizedSampling: function disableCentralizedSampling() {\n this.sampler = require('./sampling/local_sampler');\n },\n /**\n * Overrides the default sampling rules file to specify at what rate to sample at for specific routes.\n * The base sampling rules file can be found at /lib/resources/default_sampling_rules.json\n * @param {string|Object} source - The path to the custom sampling rules file, or the source JSON object.\n * @memberof AWSXRay\n */\n setSamplingRules: function setSamplingRules(source) {\n if (!source || source instanceof String || !(typeof source === 'string' || (source instanceof Object)))\n throw new Error('Please specify a path to the local sampling rules file, or supply an object containing the rules.');\n this.sampler.setLocalRules(source);\n },\n /**\n * Logs a debug message including core request and segment information\n * @param {string} message - The message to be logged\n * @param {string} url - The request url being traced\n * @param {Segment} - The current segment\n */\n middlewareLog: function middlewareLog(message, url, segment) {\n logger.getLogger().debug(message + ': { url: ' + url + ', name: ' + segment.name + ', trace_id: ' +\n segment.trace_id + ', id: ' + segment.id + ', sampled: ' + !segment.notTraced + ' }');\n },\n /**\n * Traces the request/response cycle of an http.IncomingMessage / http.ServerResponse pair.\n * Resolves sampling rules, creates a segment, adds the core request / response data adding\n * throttling / error / fault flags based on the response status code.\n * @param {http.IncomingMessage} req - The incoming request.\n * @param {http.ServerResponse} res - The server response.\n * @returns {Segment}\n * @memberof AWSXRay\n */\n traceRequestResponseCycle: function traceRequestResponseCycle(req, res) {\n var amznTraceHeader = this.processHeaders(req);\n var name = this.resolveName(req.headers.host);\n var segment = new Segment(name, amznTraceHeader.root, amznTraceHeader.parent);\n var responseWithEmbeddedRequest = Object.assign({}, res, { req: req });\n this.resolveSampling(amznTraceHeader, segment, responseWithEmbeddedRequest);\n segment.addIncomingRequestData(new IncomingRequestData(req));\n this.middlewareLog('Starting middleware segment', req.url, segment);\n var middlewareLog = this.middlewareLog;\n var didEnd = false;\n var endSegment = function () {\n // ensure `endSegment` is only called once\n // in some versions of node.js 10.x and in all versions of node.js 11.x and higher,\n // the 'finish' and 'close' event are BOTH triggered.\n // Previously, only one or the other was triggered:\n // https://github.com/nodejs/node/pull/20611\n if (didEnd)\n return;\n didEnd = true;\n if (res.statusCode === 429) {\n segment.addThrottleFlag();\n }\n const cause = coreUtils.getCauseTypeFromHttpStatus(res.statusCode);\n if (cause) {\n segment[cause] = true;\n }\n segment.http.close(res);\n segment.close();\n middlewareLog('Closed middleware segment successfully', req.url, segment);\n };\n res.on('finish', endSegment);\n res.on('close', endSegment);\n return segment;\n }\n};\nmodule.exports = utils;\n", "\"use strict\";\nvar contextUtils = require('../context_utils');\nvar mwUtils = require('../middleware/mw_utils');\nvar LambdaUtils = require('../utils').LambdaUtils;\nvar Segment = require('../segments/segment');\nvar SegmentEmitter = require('../segment_emitter');\nvar SegmentUtils = require('../segments/segment_utils');\nvar logger = require('../logger');\nconst TraceID = require('../segments/attributes/trace_id');\n/**\n * @namespace\n * @ignore\n */\nvar xAmznTraceIdPrev = null;\n/**\n* Used to initialize segments on AWS Lambda with extra data from the context.\n*/\nmodule.exports.init = function init() {\n contextUtils.enableManualMode = function () {\n logger.getLogger().warn('AWS Lambda does not support AWS X-Ray manual mode.');\n };\n SegmentEmitter.disableReusableSocket();\n SegmentUtils.setStreamingThreshold(0);\n /**\n * Disabling all centralized sampling in Lambda environments. The sampling decisions would be\n * uselessly applied to the facade segment, and the sampling pollers were causing errors.\n *\n * See: https://github.com/aws/aws-xray-sdk-node/issues/217\n */\n logger.getLogger().info('Disabling centralized sampling in Lambda environment.');\n mwUtils.disableCentralizedSampling();\n var namespace = contextUtils.getNamespace();\n namespace.enter(namespace.createContext());\n contextUtils.setSegment(facadeSegment());\n};\nvar facadeSegment = function facadeSegment() {\n var segment = new Segment('facade');\n var whitelistFcn = ['addNewSubsegment', 'addSubsegment', 'removeSubsegment', 'toString'];\n var silentFcn = ['incrementCounter', 'decrementCounter', 'isClosed', 'close', 'format', 'flush'];\n var xAmznTraceId = process.env._X_AMZN_TRACE_ID;\n for (var key in segment) {\n if (typeof segment[key] === 'function' && whitelistFcn.indexOf(key) === -1) {\n if (silentFcn.indexOf(key) === -1) {\n segment[key] = (function () {\n var func = key;\n return function facade() {\n logger.getLogger().warn('Function \"' + func + '\" cannot be called on an AWS Lambda segment. Please use a subsegment to record data.');\n return;\n };\n })();\n }\n else {\n segment[key] = function facade() { return; };\n }\n }\n }\n segment.trace_id = TraceID.Invalid().toString();\n segment.isClosed = function () { return true; };\n segment.in_progress = false;\n segment.counter = 1;\n segment.notTraced = true;\n segment.facade = true;\n segment.reset = function reset() {\n this.trace_id = TraceID.Invalid().toString();\n this.id = '00000000';\n delete this.subsegments;\n this.notTraced = true;\n };\n segment.resolveLambdaTraceData = function resolveLambdaTraceData() {\n var xAmznLambda = process.env._X_AMZN_TRACE_ID;\n if (xAmznLambda) {\n // This check resets the trace data whenever a new trace header is read to not leak data between invocations\n if (xAmznLambda != xAmznTraceIdPrev) {\n this.reset();\n if (LambdaUtils.populateTraceData(segment, xAmznLambda))\n xAmznTraceIdPrev = xAmznLambda;\n }\n }\n else {\n this.reset();\n contextUtils.contextMissingStrategy.contextMissing('Missing AWS Lambda trace data for X-Ray. ' +\n 'Ensure Active Tracing is enabled and no subsegments are created outside the function handler.');\n }\n };\n // Test for valid trace data during SDK startup. It's likely we're still in the cold-start portion of the\n // code at this point and a valid trace header has not been set\n if (LambdaUtils.validTraceData(xAmznTraceId)) {\n if (LambdaUtils.populateTraceData(segment, xAmznTraceId))\n xAmznTraceIdPrev = xAmznTraceId;\n }\n return segment;\n};\n", "\"use strict\";\nvar http = require('http');\nvar Plugin = {\n METADATA_TIMEOUT: 1000,\n /**\n * Asynchronously retrieves metadata from on-instance endpoint with an HTTP request using retries for\n * requests that time out.\n * @param {object} options - The HTTP options to make the request with\n * @param {function} callback - callback to plugin\n */\n getPluginMetadata: function (options, callback) {\n const METADATA_RETRY_TIMEOUT = 250; // Millis\n const METADATA_RETRIES = 5;\n var retries = METADATA_RETRIES;\n var getMetadata = function () {\n var httpReq = http.__request ? http.__request : http.request;\n var req = httpReq(options, function (res) {\n var body = '';\n res.on('data', function (chunk) {\n body += chunk;\n });\n res.on('end', function () {\n if (this.statusCode === 200 || this.statusCode === 300) {\n try {\n body = JSON.parse(body);\n }\n catch (e) {\n callback(e);\n return;\n }\n callback(null, body);\n }\n else if (retries > 0 && Math.floor(this.statusCode / 100) === 5) {\n retries--;\n setTimeout(getMetadata, METADATA_RETRY_TIMEOUT);\n }\n else {\n callback(new Error(`Failed to retrieve metadata with options: ${options}`));\n }\n });\n });\n req.on('error', function (err) {\n callback(err);\n });\n req.on('timeout', function () {\n req.abort();\n });\n req.setTimeout(Plugin.METADATA_TIMEOUT);\n req.end();\n };\n getMetadata();\n }\n};\nmodule.exports = Plugin;\n", "\"use strict\";\nvar Plugin = require('./plugin');\nvar logger = require('../../logger');\nvar http = require('http');\nvar EC2Plugin = {\n /**\n * A function to get the instance data from the EC2 metadata service.\n * @param {function} callback - The callback for the plugin loader.\n */\n getData: function (callback) {\n const METADATA_PATH = '/latest/dynamic/instance-identity/document';\n function populateMetadata(token) {\n const options = getOptions(METADATA_PATH, 'GET', token ? { 'X-aws-ec2-metadata-token': token } : {});\n Plugin.getPluginMetadata(options, function (err, data) {\n if (err || !data) {\n logger.getLogger().error('Error loading EC2 plugin metadata: ', err ? err.toString() : 'Could not retrieve data from IMDS.');\n callback();\n return;\n }\n const metadata = {\n ec2: {\n instance_id: data.instanceId,\n availability_zone: data.availabilityZone,\n instance_size: data.instanceType,\n ami_id: data.imageId\n }\n };\n callback(metadata);\n });\n }\n /**\n * This kicks off a requet to get a token used for requests to IMDSv2. If the request for the token\n * fails, we fall back to IMDSv1. Otherwise, the token will be used for an IMDSv2 request.\n */\n getToken(function (token) {\n if (token === null) {\n logger.getLogger().debug('EC2Plugin failed to get token from IMDSv2. Falling back to IMDSv1.');\n }\n populateMetadata(token);\n });\n },\n originName: 'AWS::EC2::Instance'\n};\n/**\n * Asynchronously retrieves a token used in requests to EC2 instance metadata service.\n * @param {function} callback - callback to plugin\n */\nfunction getToken(callback) {\n const httpReq = http.__request ? http.__request : http.request;\n const TTL = 60; //seconds\n const TOKEN_PATH = '/latest/api/token';\n const options = getOptions(TOKEN_PATH, 'PUT', {\n 'X-aws-ec2-metadata-token-ttl-seconds': TTL\n });\n let req = httpReq(options, function (res) {\n let body = '';\n res.on('data', function (chunk) {\n body += chunk;\n });\n res.on('end', function () {\n if (this.statusCode === 200 || this.statusCode === 300) {\n callback(body);\n }\n else {\n callback(null);\n }\n });\n });\n req.on('error', function () {\n callback(null);\n });\n req.on('timeout', function () {\n req.abort();\n callback(null);\n });\n req.setTimeout(Plugin.METADATA_TIMEOUT);\n req.end();\n}\nfunction getOptions(path, method, headers) {\n if (!method) {\n method = 'GET';\n }\n if (!headers) {\n headers = {};\n }\n return {\n host: '169.254.169.254',\n path: path,\n method: method,\n headers: headers\n };\n}\nmodule.exports = EC2Plugin;\n", "\"use strict\";\nvar os = require('os');\nvar ECSPlugin = {\n /**\n * A function to get the instance data from the ECS instance.\n * @param {function} callback - The callback for the plugin loader.\n */\n getData: function (callback) {\n callback({ ecs: { container: os.hostname() } });\n },\n originName: 'AWS::ECS::Container'\n};\nmodule.exports = ECSPlugin;\n", "\"use strict\";\nvar fs = require('fs');\nvar logger = require('../../logger');\nvar ENV_CONFIG_LOCATION = '/var/elasticbeanstalk/xray/environment.conf';\nvar ElasticBeanstalkPlugin = {\n /**\n * A function to get data from the Elastic Beanstalk environment configuration file.\n * @param {function} callback - The callback for the plugin loader.\n */\n getData: function (callback) {\n fs.readFile(ENV_CONFIG_LOCATION, 'utf8', function (err, rawData) {\n if (err) {\n logger.getLogger().error('Error loading Elastic Beanstalk plugin:', err.stack);\n callback();\n }\n else {\n var data = JSON.parse(rawData);\n var metadata = {\n elastic_beanstalk: {\n environment: data.environment_name,\n version_label: data.version_label,\n deployment_id: data.deployment_id\n }\n };\n callback(metadata);\n }\n });\n },\n originName: 'AWS::ElasticBeanstalk::Environment'\n};\nmodule.exports = ElasticBeanstalkPlugin;\n", "\"use strict\";\nvar fs = require('fs');\nvar logger = require('../logger');\nvar whitelist = require('../resources/aws_whitelist.json');\nvar paramTypes = {\n REQ_DESC: 'request_descriptors',\n REQ_PARAMS: 'request_parameters',\n RES_DESC: 'response_descriptors',\n RES_PARAMS: 'response_parameters'\n};\n/**\n * Represents a set of AWS services, operations and keys or params to capture.\n * @constructor\n * @param {string|Object} [source] - The location or source JSON object of the custom AWS whitelist file. If none is provided, the default file will be used.\n */\nfunction CallCapturer(source) {\n this.init(source);\n}\nCallCapturer.prototype.init = function init(source) {\n if (source) {\n if (typeof source === 'string') {\n logger.getLogger().info('Using custom AWS whitelist file: ' + source);\n this.services = loadWhitelist(JSON.parse(fs.readFileSync(source, 'utf8')));\n }\n else {\n logger.getLogger().info('Using custom AWS whitelist source.');\n this.services = loadWhitelist(source);\n }\n }\n else\n this.services = whitelist.services;\n};\nCallCapturer.prototype.append = function append(source) {\n var newServices = {};\n if (typeof source === 'string') {\n logger.getLogger().info('Appending AWS whitelist with custom file: ' + source);\n newServices = loadWhitelist(JSON.parse(fs.readFileSync(source, 'utf8')));\n }\n else {\n logger.getLogger().info('Appending AWS whitelist with a custom source.');\n newServices = loadWhitelist(source);\n }\n for (var attribute in newServices) {\n this.services[attribute] = newServices[attribute];\n }\n};\nCallCapturer.prototype.capture = function capture(serviceName, response) {\n var operation = response.request.operation;\n var call = this.services[serviceName] !== undefined ? this.services[serviceName].operations[operation] : null;\n if (call === null) {\n logger.getLogger().debug('Call \"' + serviceName + '.' + operation + '\" is not whitelisted for additional data capturing. Ignoring.');\n return;\n }\n var dataCaptured = {};\n for (var paramType in call) {\n var params = call[paramType];\n if (paramType === paramTypes.REQ_PARAMS) {\n captureCallParams(params, response.request.params, dataCaptured);\n }\n else if (paramType === paramTypes.REQ_DESC) {\n captureDescriptors(params, response.request.params, dataCaptured);\n }\n else if (paramType === paramTypes.RES_PARAMS) {\n if (response.data) {\n captureCallParams(params, response.data, dataCaptured);\n }\n }\n else if (paramType === paramTypes.RES_DESC) {\n if (response.data) {\n captureDescriptors(params, response.data, dataCaptured);\n }\n }\n else {\n logger.getLogger().error('Unknown parameter type \"' + paramType + '\". Must be \"request_descriptors\", \"response_descriptors\", ' +\n '\"request_parameters\" or \"response_parameters\".');\n }\n }\n return dataCaptured;\n};\nfunction captureCallParams(params, call, data) {\n params.forEach(function (param) {\n if (typeof call[param] !== 'undefined') {\n var formatted = toSnakeCase(param);\n this[formatted] = call[param];\n }\n }, data);\n}\nfunction captureDescriptors(descriptors, params, data) {\n for (var paramName in descriptors) {\n var attributes = descriptors[paramName];\n if (typeof params[paramName] !== 'undefined') {\n var paramData;\n if (attributes.list && attributes.get_count)\n paramData = params[paramName] ? params[paramName].length : 0;\n else\n paramData = attributes.get_keys === true ? Object.keys(params[paramName]) : params[paramName];\n if (typeof attributes.rename_to === 'string') {\n data[attributes.rename_to] = paramData;\n }\n else {\n var formatted = toSnakeCase(paramName);\n data[formatted] = paramData;\n }\n }\n }\n}\nfunction toSnakeCase(param) {\n if (param === 'IPAddress')\n return 'ip_address';\n else\n return param.split(/(?=[A-Z])/).join('_').toLowerCase();\n}\nfunction loadWhitelist(source) {\n var doc = source;\n if (doc.services === undefined)\n throw new Error('Document formatting is incorrect. Expecting \"services\" param.');\n return doc.services;\n}\nmodule.exports = CallCapturer;\n", "\"use strict\";\nvar CallCapturer = require('../../patchers/call_capturer.js');\nvar capturer = new CallCapturer();\n/**\n * Represents a AWS client call. Automatically captures data from the supplied response object,\n * Data captured depends on the whitelisting file supplied.\n * The base whitelisting file can be found at /lib/resources/aws_whitelist.json.\n * @constructor\n * @param {any} res - The response object from the AWS call. Typed as any to avoid AWS SDK dependency. Otherwise would be AWS.Response.\n * @param {string} serviceName - The service name of the AWS client.\n * @see https://github.com/aws/aws-sdk-js/blob/master/lib/response.js\n */\nfunction Aws(res, serviceName) {\n this.init(res, serviceName);\n}\nAws.prototype.init = function init(res, serviceName) {\n //TODO: account ID\n this.operation = formatOperation(res.request.operation) || '';\n if (res && res.request && res.request.httpRequest && res.request.httpRequest.region) {\n this.region = res.request.httpRequest.region;\n }\n if (res && res.requestId) {\n this.request_id = res.requestId;\n }\n this.retries = res.retryCount || 0;\n if (res.extendedRequestId && serviceName && serviceName.toLowerCase() === 's3')\n this.id_2 = res.extendedRequestId;\n this.addData(capturer.capture(serviceName, res));\n};\nAws.prototype.addData = function addData(data) {\n for (var attribute in data) {\n this[attribute] = data[attribute];\n }\n};\n/**\n * Overrides the default whitelisting file to specify what params to capture on each AWS Service call.\n * @param {string|Object} source - The path to the custom whitelist file, or a whitelist source JSON object.\n * @exports setAWSWhitelist\n */\nvar setAWSWhitelist = function setAWSWhitelist(source) {\n if (!source || source instanceof String || !(typeof source === 'string' || (source instanceof Object)))\n throw new Error('Please specify a path to the local whitelist file, or supply a whitelist source object.');\n capturer = new CallCapturer(source);\n};\n/**\n * Appends to the default whitelisting file to specify what params to capture on each AWS Service call.\n * @param {string|Object} source - The path to the custom whitelist file, or a whitelist source JSON object.\n * @exports appendAWSWhitelist\n */\nvar appendAWSWhitelist = function appendAWSWhitelist(source) {\n if (!source || source instanceof String || !(typeof source === 'string' || (source instanceof Object)))\n throw new Error('Please specify a path to the local whitelist file, or supply a whitelist source object.');\n capturer.append(source);\n};\nfunction formatOperation(operation) {\n if (!operation)\n return;\n return operation.charAt(0).toUpperCase() + operation.slice(1);\n}\nmodule.exports = Aws;\nmodule.exports.appendAWSWhitelist = appendAWSWhitelist;\nmodule.exports.setAWSWhitelist = setAWSWhitelist;\n", "\"use strict\";\n/**\n * Capture module.\n * @module capture\n */\nvar contextUtils = require('./context_utils');\nvar logger = require('./logger');\n/**\n * Wrap to automatically capture information for the segment.\n * @param {string} name - The name of the new subsegment.\n * @param {function} fcn - The function context to wrap. Can take a single 'subsegment' argument.\n * @param {Segment|Subsegment} [parent] - The parent for the new subsegment, for manual mode.\n * @alias module:capture.captureFunc\n * @return {*} - Returns the result if any by executing the provided function.\n */\nvar captureFunc = function captureFunc(name, fcn, parent) {\n validate(name, fcn);\n var current, executeFcn;\n var parentSeg = contextUtils.resolveSegment(parent);\n if (!parentSeg) {\n logger.getLogger().warn('Failed to capture function.');\n return fcn();\n }\n current = parentSeg.addNewSubsegment(name);\n executeFcn = captureFcn(fcn, current);\n try {\n const response = executeFcn(current);\n current.close();\n return response;\n }\n catch (e) {\n current.close(e);\n throw (e);\n }\n};\n/**\n * Wrap to automatically capture information for the sub/segment. You must close the segment\n * manually from within the function.\n * @param {string} name - The name of the new subsegment.\n * @param {function} fcn - The function context to wrap. Must take a single 'subsegment' argument and call 'subsegment.close([optional error])' when the async function completes.\n * @param {Segment|Subsegment} [parent] - The parent for the new subsegment, for manual mode.\n * @alias module:capture.captureAsyncFunc\n * @return {*} - Returns a promise by executing the provided async function.\n */\nvar captureAsyncFunc = function captureAsyncFunc(name, fcn, parent) {\n validate(name, fcn);\n var current, executeFcn;\n var parentSeg = contextUtils.resolveSegment(parent);\n if (!parentSeg) {\n logger.getLogger().warn('Failed to capture async function.');\n return fcn();\n }\n current = parentSeg.addNewSubsegment(name);\n executeFcn = captureFcn(fcn, current);\n try {\n return executeFcn(current);\n }\n catch (e) {\n current.close(e);\n throw (e);\n }\n};\n/**\n * Wrap to automatically capture information for the sub/segment. This wraps the callback and returns a function.\n * when executed, all arguments are passed through accordingly. An additional argument is appended to gain access to the newly created subsegment.\n * For this reason, always call the captured callback with the full list of arguments.\n * @param {string} name - The name of the new subsegment.\n * @param {function} fcn - The function context to wrap. Can take a single 'subsegment' argument.\n * @param {Segment|Subsegment} [parent] - The parent for the new subsegment, for manual mode.\n * @alias module:capture.captureCallbackFunc\n */\nvar captureCallbackFunc = function captureCallbackFunc(name, fcn, parent) {\n validate(name, fcn);\n var base = contextUtils.resolveSegment(parent);\n if (!base) {\n logger.getLogger().warn('Failed to capture callback function.');\n return fcn;\n }\n base.incrementCounter();\n return function () {\n var parentSeg = contextUtils.resolveSegment(parent);\n var args = Array.prototype.slice.call(arguments);\n captureFunc(name, fcn.bind.apply(fcn, [null].concat(args)), parentSeg);\n base.decrementCounter();\n }.bind(this);\n};\nfunction captureFcn(fcn, current) {\n var executeFcn;\n if (contextUtils.isAutomaticMode()) {\n var session = contextUtils.getNamespace();\n var contextFcn = function () {\n var value;\n session.run(function () {\n contextUtils.setSegment(current);\n value = fcn(current);\n });\n return value;\n };\n executeFcn = contextFcn;\n }\n else {\n executeFcn = fcn;\n }\n return executeFcn;\n}\nfunction validate(name, fcn) {\n var error;\n if (!name || typeof name !== 'string') {\n error = 'Param \"name\" must be a non-empty string.';\n logger.getLogger().error(error);\n throw new Error(error);\n }\n else if (typeof fcn !== 'function') {\n error = 'Param \"fcn\" must be a function.';\n logger.getLogger().error(error);\n throw new Error(error);\n }\n}\nmodule.exports.captureFunc = captureFunc;\nmodule.exports.captureAsyncFunc = captureAsyncFunc;\nmodule.exports.captureCallbackFunc = captureCallbackFunc;\n", "exports = module.exports = SemVer\n\nvar debug\n/* istanbul ignore next */\nif (typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)) {\n debug = function () {\n var args = Array.prototype.slice.call(arguments, 0)\n args.unshift('SEMVER')\n console.log.apply(console, args)\n }\n} else {\n debug = function () {}\n}\n\n// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nexports.SEMVER_SPEC_VERSION = '2.0.0'\n\nvar MAX_LENGTH = 256\nvar MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n /* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nvar MAX_SAFE_COMPONENT_LENGTH = 16\n\n// The actual regexps go on exports.re\nvar re = exports.re = []\nvar src = exports.src = []\nvar R = 0\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\nvar NUMERICIDENTIFIER = R++\nsrc[NUMERICIDENTIFIER] = '0|[1-9]\\\\d*'\nvar NUMERICIDENTIFIERLOOSE = R++\nsrc[NUMERICIDENTIFIERLOOSE] = '[0-9]+'\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\nvar NONNUMERICIDENTIFIER = R++\nsrc[NONNUMERICIDENTIFIER] = '\\\\d*[a-zA-Z-][a-zA-Z0-9-]*'\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\nvar MAINVERSION = R++\nsrc[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\\\.' +\n '(' + src[NUMERICIDENTIFIER] + ')\\\\.' +\n '(' + src[NUMERICIDENTIFIER] + ')'\n\nvar MAINVERSIONLOOSE = R++\nsrc[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\\\.' +\n '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\\\.' +\n '(' + src[NUMERICIDENTIFIERLOOSE] + ')'\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n\nvar PRERELEASEIDENTIFIER = R++\nsrc[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] +\n '|' + src[NONNUMERICIDENTIFIER] + ')'\n\nvar PRERELEASEIDENTIFIERLOOSE = R++\nsrc[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] +\n '|' + src[NONNUMERICIDENTIFIER] + ')'\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\nvar PRERELEASE = R++\nsrc[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] +\n '(?:\\\\.' + src[PRERELEASEIDENTIFIER] + ')*))'\n\nvar PRERELEASELOOSE = R++\nsrc[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] +\n '(?:\\\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\nvar BUILDIDENTIFIER = R++\nsrc[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\nvar BUILD = R++\nsrc[BUILD] = '(?:\\\\+(' + src[BUILDIDENTIFIER] +\n '(?:\\\\.' + src[BUILDIDENTIFIER] + ')*))'\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\nvar FULL = R++\nvar FULLPLAIN = 'v?' + src[MAINVERSION] +\n src[PRERELEASE] + '?' +\n src[BUILD] + '?'\n\nsrc[FULL] = '^' + FULLPLAIN + '$'\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\nvar LOOSEPLAIN = '[v=\\\\s]*' + src[MAINVERSIONLOOSE] +\n src[PRERELEASELOOSE] + '?' +\n src[BUILD] + '?'\n\nvar LOOSE = R++\nsrc[LOOSE] = '^' + LOOSEPLAIN + '$'\n\nvar GTLT = R++\nsrc[GTLT] = '((?:<|>)?=?)'\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifer, meaning \"any version\"\n// Only the first item is strictly required.\nvar XRANGEIDENTIFIERLOOSE = R++\nsrc[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\\\*'\nvar XRANGEIDENTIFIER = R++\nsrc[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\\\*'\n\nvar XRANGEPLAIN = R++\nsrc[XRANGEPLAIN] = '[v=\\\\s]*(' + src[XRANGEIDENTIFIER] + ')' +\n '(?:\\\\.(' + src[XRANGEIDENTIFIER] + ')' +\n '(?:\\\\.(' + src[XRANGEIDENTIFIER] + ')' +\n '(?:' + src[PRERELEASE] + ')?' +\n src[BUILD] + '?' +\n ')?)?'\n\nvar XRANGEPLAINLOOSE = R++\nsrc[XRANGEPLAINLOOSE] = '[v=\\\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' +\n '(?:\\\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +\n '(?:\\\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +\n '(?:' + src[PRERELEASELOOSE] + ')?' +\n src[BUILD] + '?' +\n ')?)?'\n\nvar XRANGE = R++\nsrc[XRANGE] = '^' + src[GTLT] + '\\\\s*' + src[XRANGEPLAIN] + '$'\nvar XRANGELOOSE = R++\nsrc[XRANGELOOSE] = '^' + src[GTLT] + '\\\\s*' + src[XRANGEPLAINLOOSE] + '$'\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\nvar COERCE = R++\nsrc[COERCE] = '(?:^|[^\\\\d])' +\n '(\\\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' +\n '(?:\\\\.(\\\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +\n '(?:\\\\.(\\\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +\n '(?:$|[^\\\\d])'\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\nvar LONETILDE = R++\nsrc[LONETILDE] = '(?:~>?)'\n\nvar TILDETRIM = R++\nsrc[TILDETRIM] = '(\\\\s*)' + src[LONETILDE] + '\\\\s+'\nre[TILDETRIM] = new RegExp(src[TILDETRIM], 'g')\nvar tildeTrimReplace = '$1~'\n\nvar TILDE = R++\nsrc[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'\nvar TILDELOOSE = R++\nsrc[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\nvar LONECARET = R++\nsrc[LONECARET] = '(?:\\\\^)'\n\nvar CARETTRIM = R++\nsrc[CARETTRIM] = '(\\\\s*)' + src[LONECARET] + '\\\\s+'\nre[CARETTRIM] = new RegExp(src[CARETTRIM], 'g')\nvar caretTrimReplace = '$1^'\n\nvar CARET = R++\nsrc[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'\nvar CARETLOOSE = R++\nsrc[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\nvar COMPARATORLOOSE = R++\nsrc[COMPARATORLOOSE] = '^' + src[GTLT] + '\\\\s*(' + LOOSEPLAIN + ')$|^$'\nvar COMPARATOR = R++\nsrc[COMPARATOR] = '^' + src[GTLT] + '\\\\s*(' + FULLPLAIN + ')$|^$'\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\nvar COMPARATORTRIM = R++\nsrc[COMPARATORTRIM] = '(\\\\s*)' + src[GTLT] +\n '\\\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'\n\n// this one has to use the /g flag\nre[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g')\nvar comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\nvar HYPHENRANGE = R++\nsrc[HYPHENRANGE] = '^\\\\s*(' + src[XRANGEPLAIN] + ')' +\n '\\\\s+-\\\\s+' +\n '(' + src[XRANGEPLAIN] + ')' +\n '\\\\s*$'\n\nvar HYPHENRANGELOOSE = R++\nsrc[HYPHENRANGELOOSE] = '^\\\\s*(' + src[XRANGEPLAINLOOSE] + ')' +\n '\\\\s+-\\\\s+' +\n '(' + src[XRANGEPLAINLOOSE] + ')' +\n '\\\\s*$'\n\n// Star ranges basically just allow anything at all.\nvar STAR = R++\nsrc[STAR] = '(<|>)?=?\\\\s*\\\\*'\n\n// Compile to actual regexp objects.\n// All are flag-free, unless they were created above with a flag.\nfor (var i = 0; i < R; i++) {\n debug(i, src[i])\n if (!re[i]) {\n re[i] = new RegExp(src[i])\n }\n}\n\nexports.parse = parse\nfunction parse (version, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n if (version.length > MAX_LENGTH) {\n return null\n }\n\n var r = options.loose ? re[LOOSE] : re[FULL]\n if (!r.test(version)) {\n return null\n }\n\n try {\n return new SemVer(version, options)\n } catch (er) {\n return null\n }\n}\n\nexports.valid = valid\nfunction valid (version, options) {\n var v = parse(version, options)\n return v ? v.version : null\n}\n\nexports.clean = clean\nfunction clean (version, options) {\n var s = parse(version.trim().replace(/^[=v]+/, ''), options)\n return s ? s.version : null\n}\n\nexports.SemVer = SemVer\n\nfunction SemVer (version, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n if (version instanceof SemVer) {\n if (version.loose === options.loose) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError('Invalid Version: ' + version)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters')\n }\n\n if (!(this instanceof SemVer)) {\n return new SemVer(version, options)\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n\n var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL])\n\n if (!m) {\n throw new TypeError('Invalid Version: ' + version)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map(function (id) {\n if (/^[0-9]+$/.test(id)) {\n var num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n}\n\nSemVer.prototype.format = function () {\n this.version = this.major + '.' + this.minor + '.' + this.patch\n if (this.prerelease.length) {\n this.version += '-' + this.prerelease.join('.')\n }\n return this.version\n}\n\nSemVer.prototype.toString = function () {\n return this.version\n}\n\nSemVer.prototype.compare = function (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n return this.compareMain(other) || this.comparePre(other)\n}\n\nSemVer.prototype.compareMain = function (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n return compareIdentifiers(this.major, other.major) ||\n compareIdentifiers(this.minor, other.minor) ||\n compareIdentifiers(this.patch, other.patch)\n}\n\nSemVer.prototype.comparePre = function (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n var i = 0\n do {\n var a = this.prerelease[i]\n var b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n}\n\n// preminor will bump the version up to the next minor release, and immediately\n// down to pre-release. premajor and prepatch work the same way.\nSemVer.prototype.inc = function (release, identifier) {\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier)\n this.inc('pre', identifier)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier)\n }\n this.inc('pre', identifier)\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 \"pre\" would become 1.0.0-0 which is the wrong direction.\n case 'pre':\n if (this.prerelease.length === 0) {\n this.prerelease = [0]\n } else {\n var i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n this.prerelease.push(0)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n if (this.prerelease[0] === identifier) {\n if (isNaN(this.prerelease[1])) {\n this.prerelease = [identifier, 0]\n }\n } else {\n this.prerelease = [identifier, 0]\n }\n }\n break\n\n default:\n throw new Error('invalid increment argument: ' + release)\n }\n this.format()\n this.raw = this.version\n return this\n}\n\nexports.inc = inc\nfunction inc (version, release, loose, identifier) {\n if (typeof (loose) === 'string') {\n identifier = loose\n loose = undefined\n }\n\n try {\n return new SemVer(version, loose).inc(release, identifier).version\n } catch (er) {\n return null\n }\n}\n\nexports.diff = diff\nfunction diff (version1, version2) {\n if (eq(version1, version2)) {\n return null\n } else {\n var v1 = parse(version1)\n var v2 = parse(version2)\n var prefix = ''\n if (v1.prerelease.length || v2.prerelease.length) {\n prefix = 'pre'\n var defaultResult = 'prerelease'\n }\n for (var key in v1) {\n if (key === 'major' || key === 'minor' || key === 'patch') {\n if (v1[key] !== v2[key]) {\n return prefix + key\n }\n }\n }\n return defaultResult // may be undefined\n }\n}\n\nexports.compareIdentifiers = compareIdentifiers\n\nvar numeric = /^[0-9]+$/\nfunction compareIdentifiers (a, b) {\n var anum = numeric.test(a)\n var bnum = numeric.test(b)\n\n if (anum && bnum) {\n a = +a\n b = +b\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n}\n\nexports.rcompareIdentifiers = rcompareIdentifiers\nfunction rcompareIdentifiers (a, b) {\n return compareIdentifiers(b, a)\n}\n\nexports.major = major\nfunction major (a, loose) {\n return new SemVer(a, loose).major\n}\n\nexports.minor = minor\nfunction minor (a, loose) {\n return new SemVer(a, loose).minor\n}\n\nexports.patch = patch\nfunction patch (a, loose) {\n return new SemVer(a, loose).patch\n}\n\nexports.compare = compare\nfunction compare (a, b, loose) {\n return new SemVer(a, loose).compare(new SemVer(b, loose))\n}\n\nexports.compareLoose = compareLoose\nfunction compareLoose (a, b) {\n return compare(a, b, true)\n}\n\nexports.rcompare = rcompare\nfunction rcompare (a, b, loose) {\n return compare(b, a, loose)\n}\n\nexports.sort = sort\nfunction sort (list, loose) {\n return list.sort(function (a, b) {\n return exports.compare(a, b, loose)\n })\n}\n\nexports.rsort = rsort\nfunction rsort (list, loose) {\n return list.sort(function (a, b) {\n return exports.rcompare(a, b, loose)\n })\n}\n\nexports.gt = gt\nfunction gt (a, b, loose) {\n return compare(a, b, loose) > 0\n}\n\nexports.lt = lt\nfunction lt (a, b, loose) {\n return compare(a, b, loose) < 0\n}\n\nexports.eq = eq\nfunction eq (a, b, loose) {\n return compare(a, b, loose) === 0\n}\n\nexports.neq = neq\nfunction neq (a, b, loose) {\n return compare(a, b, loose) !== 0\n}\n\nexports.gte = gte\nfunction gte (a, b, loose) {\n return compare(a, b, loose) >= 0\n}\n\nexports.lte = lte\nfunction lte (a, b, loose) {\n return compare(a, b, loose) <= 0\n}\n\nexports.cmp = cmp\nfunction cmp (a, op, b, loose) {\n switch (op) {\n case '===':\n if (typeof a === 'object')\n a = a.version\n if (typeof b === 'object')\n b = b.version\n return a === b\n\n case '!==':\n if (typeof a === 'object')\n a = a.version\n if (typeof b === 'object')\n b = b.version\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt(a, b, loose)\n\n case '>=':\n return gte(a, b, loose)\n\n case '<':\n return lt(a, b, loose)\n\n case '<=':\n return lte(a, b, loose)\n\n default:\n throw new TypeError('Invalid operator: ' + op)\n }\n}\n\nexports.Comparator = Comparator\nfunction Comparator (comp, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n if (!(this instanceof Comparator)) {\n return new Comparator(comp, options)\n }\n\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n}\n\nvar ANY = {}\nComparator.prototype.parse = function (comp) {\n var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]\n var m = comp.match(r)\n\n if (!m) {\n throw new TypeError('Invalid comparator: ' + comp)\n }\n\n this.operator = m[1]\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n}\n\nComparator.prototype.toString = function () {\n return this.value\n}\n\nComparator.prototype.test = function (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n version = new SemVer(version, this.options)\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n}\n\nComparator.prototype.intersects = function (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n var rangeTmp\n\n if (this.operator === '') {\n rangeTmp = new Range(comp.value, options)\n return satisfies(this.value, rangeTmp, options)\n } else if (comp.operator === '') {\n rangeTmp = new Range(this.value, options)\n return satisfies(comp.semver, rangeTmp, options)\n }\n\n var sameDirectionIncreasing =\n (this.operator === '>=' || this.operator === '>') &&\n (comp.operator === '>=' || comp.operator === '>')\n var sameDirectionDecreasing =\n (this.operator === '<=' || this.operator === '<') &&\n (comp.operator === '<=' || comp.operator === '<')\n var sameSemVer = this.semver.version === comp.semver.version\n var differentDirectionsInclusive =\n (this.operator === '>=' || this.operator === '<=') &&\n (comp.operator === '>=' || comp.operator === '<=')\n var oppositeDirectionsLessThan =\n cmp(this.semver, '<', comp.semver, options) &&\n ((this.operator === '>=' || this.operator === '>') &&\n (comp.operator === '<=' || comp.operator === '<'))\n var oppositeDirectionsGreaterThan =\n cmp(this.semver, '>', comp.semver, options) &&\n ((this.operator === '<=' || this.operator === '<') &&\n (comp.operator === '>=' || comp.operator === '>'))\n\n return sameDirectionIncreasing || sameDirectionDecreasing ||\n (sameSemVer && differentDirectionsInclusive) ||\n oppositeDirectionsLessThan || oppositeDirectionsGreaterThan\n}\n\nexports.Range = Range\nfunction Range (range, options) {\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n if (range instanceof Range) {\n if (range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n return new Range(range.value, options)\n }\n\n if (!(this instanceof Range)) {\n return new Range(range, options)\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First, split based on boolean or ||\n this.raw = range\n this.set = range.split(/\\s*\\|\\|\\s*/).map(function (range) {\n return this.parseRange(range.trim())\n }, this).filter(function (c) {\n // throw out any that are not relevant for whatever reason\n return c.length\n })\n\n if (!this.set.length) {\n throw new TypeError('Invalid SemVer Range: ' + range)\n }\n\n this.format()\n}\n\nRange.prototype.format = function () {\n this.range = this.set.map(function (comps) {\n return comps.join(' ').trim()\n }).join('||').trim()\n return this.range\n}\n\nRange.prototype.toString = function () {\n return this.range\n}\n\nRange.prototype.parseRange = function (range) {\n var loose = this.options.loose\n range = range.trim()\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]\n range = range.replace(hr, hyphenReplace)\n debug('hyphen replace', range)\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range, re[COMPARATORTRIM])\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[TILDETRIM], tildeTrimReplace)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[CARETTRIM], caretTrimReplace)\n\n // normalize spaces\n range = range.split(/\\s+/).join(' ')\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]\n var set = range.split(' ').map(function (comp) {\n return parseComparator(comp, this.options)\n }, this).join(' ').split(/\\s+/)\n if (this.options.loose) {\n // in loose mode, throw out any that are not valid comparators\n set = set.filter(function (comp) {\n return !!comp.match(compRe)\n })\n }\n set = set.map(function (comp) {\n return new Comparator(comp, this.options)\n }, this)\n\n return set\n}\n\nRange.prototype.intersects = function (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some(function (thisComparators) {\n return thisComparators.every(function (thisComparator) {\n return range.set.some(function (rangeComparators) {\n return rangeComparators.every(function (rangeComparator) {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n })\n })\n}\n\n// Mostly just for testing and legacy API reasons\nexports.toComparators = toComparators\nfunction toComparators (range, options) {\n return new Range(range, options).set.map(function (comp) {\n return comp.map(function (c) {\n return c.value\n }).join(' ').trim().split(' ')\n })\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nfunction parseComparator (comp, options) {\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nfunction isX (id) {\n return !id || id.toLowerCase() === 'x' || id === '*'\n}\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0\nfunction replaceTildes (comp, options) {\n return comp.trim().split(/\\s+/).map(function (comp) {\n return replaceTilde(comp, options)\n }).join(' ')\n}\n\nfunction replaceTilde (comp, options) {\n var r = options.loose ? re[TILDELOOSE] : re[TILDE]\n return comp.replace(r, function (_, M, m, p, pr) {\n debug('tilde', comp, _, M, m, p, pr)\n var ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0\n ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + M + '.' + (+m + 1) + '.0'\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + M + '.' + (+m + 1) + '.0'\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0\n// ^1.2.3 --> >=1.2.3 <2.0.0\n// ^1.2.0 --> >=1.2.0 <2.0.0\nfunction replaceCarets (comp, options) {\n return comp.trim().split(/\\s+/).map(function (comp) {\n return replaceCaret(comp, options)\n }).join(' ')\n}\n\nfunction replaceCaret (comp, options) {\n debug('caret', comp, options)\n var r = options.loose ? re[CARETLOOSE] : re[CARET]\n return comp.replace(r, function (_, M, m, p, pr) {\n debug('caret', comp, _, M, m, p, pr)\n var ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'\n } else if (isX(p)) {\n if (M === '0') {\n ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'\n } else {\n ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + M + '.' + m + '.' + (+p + 1)\n } else {\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + M + '.' + (+m + 1) + '.0'\n }\n } else {\n ret = '>=' + M + '.' + m + '.' + p + '-' + pr +\n ' <' + (+M + 1) + '.0.0'\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + M + '.' + m + '.' + (+p + 1)\n } else {\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + M + '.' + (+m + 1) + '.0'\n }\n } else {\n ret = '>=' + M + '.' + m + '.' + p +\n ' <' + (+M + 1) + '.0.0'\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nfunction replaceXRanges (comp, options) {\n debug('replaceXRanges', comp, options)\n return comp.split(/\\s+/).map(function (comp) {\n return replaceXRange(comp, options)\n }).join(' ')\n}\n\nfunction replaceXRange (comp, options) {\n comp = comp.trim()\n var r = options.loose ? re[XRANGELOOSE] : re[XRANGE]\n return comp.replace(r, function (ret, gtlt, M, m, p, pr) {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n var xM = isX(M)\n var xm = xM || isX(m)\n var xp = xm || isX(p)\n var anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n // >1.2.3 => >= 1.2.4\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n ret = gtlt + M + '.' + m + '.' + p\n } else if (xm) {\n ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'\n } else if (xp) {\n ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nfunction replaceStars (comp, options) {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp.trim().replace(re[STAR], '')\n}\n\n// This function is passed to string.replace(re[HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0\nfunction hyphenReplace ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr, tb) {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = '>=' + fM + '.0.0'\n } else if (isX(fp)) {\n from = '>=' + fM + '.' + fm + '.0'\n } else {\n from = '>=' + from\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = '<' + (+tM + 1) + '.0.0'\n } else if (isX(tp)) {\n to = '<' + tM + '.' + (+tm + 1) + '.0'\n } else if (tpr) {\n to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr\n } else {\n to = '<=' + to\n }\n\n return (from + ' ' + to).trim()\n}\n\n// if ANY of the sets match ALL of its comparators, then pass\nRange.prototype.test = function (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n version = new SemVer(version, this.options)\n }\n\n for (var i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n}\n\nfunction testSet (set, version, options) {\n for (var i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n var allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n\nexports.satisfies = satisfies\nfunction satisfies (version, range, options) {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\n\nexports.maxSatisfying = maxSatisfying\nfunction maxSatisfying (versions, range, options) {\n var max = null\n var maxSV = null\n try {\n var rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach(function (v) {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!max || maxSV.compare(v) === -1) {\n // compare(max, v, true)\n max = v\n maxSV = new SemVer(max, options)\n }\n }\n })\n return max\n}\n\nexports.minSatisfying = minSatisfying\nfunction minSatisfying (versions, range, options) {\n var min = null\n var minSV = null\n try {\n var rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach(function (v) {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!min || minSV.compare(v) === 1) {\n // compare(min, v, true)\n min = v\n minSV = new SemVer(min, options)\n }\n }\n })\n return min\n}\n\nexports.minVersion = minVersion\nfunction minVersion (range, loose) {\n range = new Range(range, loose)\n\n var minver = new SemVer('0.0.0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = new SemVer('0.0.0-0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = null\n for (var i = 0; i < range.set.length; ++i) {\n var comparators = range.set[i]\n\n comparators.forEach(function (comparator) {\n // Clone to avoid manipulating the comparator's semver object.\n var compver = new SemVer(comparator.semver.version)\n switch (comparator.operator) {\n case '>':\n if (compver.prerelease.length === 0) {\n compver.patch++\n } else {\n compver.prerelease.push(0)\n }\n compver.raw = compver.format()\n /* fallthrough */\n case '':\n case '>=':\n if (!minver || gt(minver, compver)) {\n minver = compver\n }\n break\n case '<':\n case '<=':\n /* Ignore maximum versions */\n break\n /* istanbul ignore next */\n default:\n throw new Error('Unexpected operation: ' + comparator.operator)\n }\n })\n }\n\n if (minver && range.test(minver)) {\n return minver\n }\n\n return null\n}\n\nexports.validRange = validRange\nfunction validRange (range, options) {\n try {\n // Return '*' instead of '' so that truthiness works.\n // This will throw if it's invalid anyway\n return new Range(range, options).range || '*'\n } catch (er) {\n return null\n }\n}\n\n// Determine if version is less than all the versions possible in the range\nexports.ltr = ltr\nfunction ltr (version, range, options) {\n return outside(version, range, '<', options)\n}\n\n// Determine if version is greater than all the versions possible in the range.\nexports.gtr = gtr\nfunction gtr (version, range, options) {\n return outside(version, range, '>', options)\n}\n\nexports.outside = outside\nfunction outside (version, range, hilo, options) {\n version = new SemVer(version, options)\n range = new Range(range, options)\n\n var gtfn, ltefn, ltfn, comp, ecomp\n switch (hilo) {\n case '>':\n gtfn = gt\n ltefn = lte\n ltfn = lt\n comp = '>'\n ecomp = '>='\n break\n case '<':\n gtfn = lt\n ltefn = gte\n ltfn = gt\n comp = '<'\n ecomp = '<='\n break\n default:\n throw new TypeError('Must provide a hilo val of \"<\" or \">\"')\n }\n\n // If it satisifes the range it is not outside\n if (satisfies(version, range, options)) {\n return false\n }\n\n // From now on, variable terms are as if we're in \"gtr\" mode.\n // but note that everything is flipped for the \"ltr\" function.\n\n for (var i = 0; i < range.set.length; ++i) {\n var comparators = range.set[i]\n\n var high = null\n var low = null\n\n comparators.forEach(function (comparator) {\n if (comparator.semver === ANY) {\n comparator = new Comparator('>=0.0.0')\n }\n high = high || comparator\n low = low || comparator\n if (gtfn(comparator.semver, high.semver, options)) {\n high = comparator\n } else if (ltfn(comparator.semver, low.semver, options)) {\n low = comparator\n }\n })\n\n // If the edge version comparator has a operator then our version\n // isn't outside it\n if (high.operator === comp || high.operator === ecomp) {\n return false\n }\n\n // If the lowest version comparator has an operator and our version\n // is less than it then it isn't higher than the range\n if ((!low.operator || low.operator === comp) &&\n ltefn(version, low.semver)) {\n return false\n } else if (low.operator === ecomp && ltfn(version, low.semver)) {\n return false\n }\n }\n return true\n}\n\nexports.prerelease = prerelease\nfunction prerelease (version, options) {\n var parsed = parse(version, options)\n return (parsed && parsed.prerelease.length) ? parsed.prerelease : null\n}\n\nexports.intersects = intersects\nfunction intersects (r1, r2, options) {\n r1 = new Range(r1, options)\n r2 = new Range(r2, options)\n return r1.intersects(r2)\n}\n\nexports.coerce = coerce\nfunction coerce (version) {\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n var match = version.match(re[COERCE])\n\n if (match == null) {\n return null\n }\n\n return parse(match[1] +\n '.' + (match[2] || '0') +\n '.' + (match[3] || '0'))\n}\n", "\"use strict\";\n/**\n * Capture module.\n * @module aws_p\n */\nvar semver = require('semver');\nvar Aws = require('../segments/attributes/aws');\nvar contextUtils = require('../context_utils');\nvar Utils = require('../utils');\nvar logger = require('../logger');\nvar minVersion = '2.7.15';\nvar throttledErrorDefault = function throttledErrorDefault() {\n return false; // If the customer doesn't provide an aws-sdk with a throttled error function, we can't make assumptions.\n};\n/**\n * Configures the AWS SDK to automatically capture information for the segment.\n * All created clients will automatically be captured. See 'captureAWSClient'\n * for additional details.\n * @param {AWS} awssdk - The Javascript AWS SDK.\n * @alias module:aws_p.captureAWS\n * @returns {AWS}\n * @see https://github.com/aws/aws-sdk-js\n */\nvar captureAWS = function captureAWS(awssdk) {\n if (!semver.gte(awssdk.VERSION, minVersion))\n throw new Error('AWS SDK version ' + minVersion + ' or greater required.');\n for (var prop in awssdk) {\n if (awssdk[prop].serviceIdentifier) {\n var Service = awssdk[prop];\n Service.prototype.customizeRequests(captureAWSRequest);\n }\n }\n return awssdk;\n};\n/**\n * Configures any AWS Client instance to automatically capture information for the segment.\n * For manual mode, a param with key called 'Segment' is required as a part of the AWS\n * call paramaters, and must reference a Segment or Subsegment object.\n * @param {AWS.Service} service - An instance of a AWS service to wrap.\n * @alias module:aws_p.captureAWSClient\n * @returns {AWS.Service}\n * @see https://github.com/aws/aws-sdk-js\n */\nvar captureAWSClient = function captureAWSClient(service) {\n service.customizeRequests(captureAWSRequest);\n return service;\n};\nfunction captureAWSRequest(req) {\n var parent = contextUtils.resolveSegment(contextUtils.resolveManualSegmentParams(req.params));\n if (!parent) {\n var output = this.serviceIdentifier + '.' + req.operation;\n if (!contextUtils.isAutomaticMode()) {\n logger.getLogger().info('Call ' + output + ' requires a segment object' +\n ' on the request params as \"XRaySegment\" for tracing in manual mode. Ignoring.');\n }\n else {\n logger.getLogger().info('Call ' + output +\n ' is missing the sub/segment context for automatic mode. Ignoring.');\n }\n return req;\n }\n var throttledError = this.throttledError || throttledErrorDefault;\n var stack = (new Error()).stack;\n var subsegment = parent.addNewSubsegment(this.serviceIdentifier);\n var traceId = parent.segment ? parent.segment.trace_id : parent.trace_id;\n var buildListener = function (req) {\n req.httpRequest.headers['X-Amzn-Trace-Id'] = 'Root=' + traceId + ';Parent=' + subsegment.id +\n ';Sampled=' + (subsegment.segment.notTraced ? '0' : '1');\n };\n var completeListener = function (res) {\n subsegment.addAttribute('namespace', 'aws');\n subsegment.addAttribute('aws', new Aws(res, subsegment.name));\n var httpRes = res.httpResponse;\n if (httpRes) {\n subsegment.addAttribute('http', new HttpResponse(httpRes));\n if (httpRes.statusCode === 429 || (res.error && throttledError(res.error)))\n subsegment.addThrottleFlag();\n }\n if (res.error) {\n var err = { message: res.error.message, name: res.error.code, stack: stack };\n if (httpRes && httpRes.statusCode) {\n if (Utils.getCauseTypeFromHttpStatus(httpRes.statusCode) == 'error') {\n subsegment.addErrorFlag();\n }\n subsegment.close(err, true);\n }\n else\n subsegment.close(err);\n }\n else {\n if (httpRes && httpRes.statusCode) {\n var cause = Utils.getCauseTypeFromHttpStatus(httpRes.statusCode);\n if (cause)\n subsegment[cause] = true;\n }\n subsegment.close();\n }\n };\n req.on('beforePresign', function (req) {\n // Only the AWS Presigner triggers this event,\n // so we can rely on this event to notify us when\n // a request is for a presigned url\n parent.removeSubsegment(subsegment);\n parent.decrementCounter();\n req.removeListener('build', buildListener);\n req.removeListener('complete', completeListener);\n });\n req.on('build', buildListener).on('complete', completeListener);\n if (!req.__send) {\n req.__send = req.send;\n req.send = function (callback) {\n if (contextUtils.isAutomaticMode()) {\n var session = contextUtils.getNamespace();\n session.run(function () {\n contextUtils.setSegment(subsegment);\n req.__send(callback);\n });\n }\n else {\n req.__send(callback);\n }\n };\n }\n}\nfunction HttpResponse(res) {\n this.init(res);\n}\nHttpResponse.prototype.init = function init(res) {\n this.response = {\n status: res.statusCode || '',\n };\n if (res.headers && res.headers['content-length'])\n this.response.content_length = res.headers['content-length'];\n};\nmodule.exports.captureAWSClient = captureAWSClient;\nmodule.exports.captureAWS = captureAWS;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TRANSIENT_ERROR_STATUS_CODES = exports.TRANSIENT_ERROR_CODES = exports.THROTTLING_ERROR_CODES = exports.CLOCK_SKEW_ERROR_CODES = void 0;\nexports.CLOCK_SKEW_ERROR_CODES = [\n \"AuthFailure\",\n \"InvalidSignatureException\",\n \"RequestExpired\",\n \"RequestInTheFuture\",\n \"RequestTimeTooSkewed\",\n \"SignatureDoesNotMatch\",\n];\nexports.THROTTLING_ERROR_CODES = [\n \"BandwidthLimitExceeded\",\n \"EC2ThrottledException\",\n \"LimitExceededException\",\n \"PriorRequestNotComplete\",\n \"ProvisionedThroughputExceededException\",\n \"RequestLimitExceeded\",\n \"RequestThrottled\",\n \"RequestThrottledException\",\n \"SlowDown\",\n \"ThrottledException\",\n \"Throttling\",\n \"ThrottlingException\",\n \"TooManyRequestsException\",\n \"TransactionInProgressException\",\n];\nexports.TRANSIENT_ERROR_CODES = [\"AbortError\", \"TimeoutError\", \"RequestTimeout\", \"RequestTimeoutException\"];\nexports.TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504];\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isTransientError = exports.isThrottlingError = exports.isClockSkewError = exports.isRetryableByTrait = void 0;\nconst constants_1 = require(\"./constants\");\nconst isRetryableByTrait = (error) => error.$retryable !== undefined;\nexports.isRetryableByTrait = isRetryableByTrait;\nconst isClockSkewError = (error) => constants_1.CLOCK_SKEW_ERROR_CODES.includes(error.name);\nexports.isClockSkewError = isClockSkewError;\nconst isThrottlingError = (error) => {\n var _a, _b;\n return ((_a = error.$metadata) === null || _a === void 0 ? void 0 : _a.httpStatusCode) === 429 ||\n constants_1.THROTTLING_ERROR_CODES.includes(error.name) ||\n ((_b = error.$retryable) === null || _b === void 0 ? void 0 : _b.throttling) == true;\n};\nexports.isThrottlingError = isThrottlingError;\nconst isTransientError = (error) => {\n var _a;\n return constants_1.TRANSIENT_ERROR_CODES.includes(error.name) ||\n constants_1.TRANSIENT_ERROR_STATUS_CODES.includes(((_a = error.$metadata) === null || _a === void 0 ? void 0 : _a.httpStatusCode) || 0);\n};\nexports.isTransientError = isTransientError;\n", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.captureAWSClient = void 0;\nconst service_error_classification_1 = require(\"@aws-sdk/service-error-classification\");\nconst aws_1 = __importDefault(require(\"../segments/attributes/aws\"));\nconst querystring_1 = require(\"querystring\");\nconst subsegment_1 = __importDefault(require(\"../segments/attributes/subsegment\"));\nconst contextUtils = require('../context_utils');\nconst logger = require('../logger');\nconst { safeParseInt } = require('../utils');\nconst utils_1 = require(\"../utils\");\nconst XRAY_PLUGIN_NAME = 'XRaySDKInstrumentation';\n;\nconst buildAttributesFromMetadata = async (service, operation, region, res, error) => {\n var _a, _b, _c;\n const { extendedRequestId, requestId, httpStatusCode: statusCode, attempts } = ((_a = res === null || res === void 0 ? void 0 : res.output) === null || _a === void 0 ? void 0 : _a.$metadata) || (error === null || error === void 0 ? void 0 : error.$metadata);\n const aws = new aws_1.default({\n extendedRequestId,\n requestId,\n retryCount: attempts,\n request: {\n operation,\n httpRequest: {\n region,\n statusCode,\n },\n },\n }, service);\n const http = {};\n if (statusCode) {\n http.response = {};\n http.response.status = statusCode;\n }\n if (((_b = res === null || res === void 0 ? void 0 : res.response) === null || _b === void 0 ? void 0 : _b.headers) && ((_c = res === null || res === void 0 ? void 0 : res.response) === null || _c === void 0 ? void 0 : _c.headers['content-length']) !== undefined) {\n if (!http.response) {\n http.response = {};\n }\n http.response.content_length = safeParseInt(res.response.headers['content-length']);\n }\n return [aws, http];\n};\nfunction addFlags(http, subsegment, err) {\n var _a, _b, _c;\n if (err && service_error_classification_1.isThrottlingError(err)) {\n subsegment.addThrottleFlag();\n }\n else if (safeParseInt((_a = http.response) === null || _a === void 0 ? void 0 : _a.status) === 429 || safeParseInt((_b = err === null || err === void 0 ? void 0 : err.$metadata) === null || _b === void 0 ? void 0 : _b.httpStatusCode) === 429) {\n subsegment.addThrottleFlag();\n }\n const cause = utils_1.getCauseTypeFromHttpStatus(safeParseInt((_c = http.response) === null || _c === void 0 ? void 0 : _c.status));\n if (cause === 'fault') {\n subsegment.addFaultFlag();\n }\n else if (cause === 'error') {\n subsegment.addErrorFlag();\n }\n}\n;\nconst getXRayMiddleware = (config, manualSegment) => (next, context) => async (args) => {\n const segment = contextUtils.isAutomaticMode() ? contextUtils.resolveSegment() : manualSegment;\n const { clientName, commandName } = context;\n const operation = commandName.slice(0, -7); // Strip trailing \"Command\" string\n const service = clientName.slice(0, -6); // Strip trailing \"Client\" string\n if (!segment) {\n const output = service + '.' + operation.charAt(0).toLowerCase() + operation.slice(1);\n if (!contextUtils.isAutomaticMode()) {\n logger.getLogger().info('Call ' + output + ' requires a segment object' +\n ' passed to captureAWSv3Client for tracing in manual mode. Ignoring.');\n }\n else {\n logger.getLogger().info('Call ' + output +\n ' is missing the sub/segment context for automatic mode. Ignoring.');\n }\n return next(args);\n }\n const subsegment = segment.addNewSubsegment(service);\n subsegment.addAttribute('namespace', 'aws');\n const parent = (segment instanceof subsegment_1.default ? segment.segment : segment);\n args.request.headers['X-Amzn-Trace-Id'] = querystring_1.stringify({\n Root: parent.trace_id,\n Parent: subsegment.id,\n Sampled: parent.notTraced ? '0' : '1',\n }, ';');\n let res;\n try {\n res = await next(args);\n if (!res)\n throw new Error('Failed to get response from instrumented AWS Client.');\n const [aws, http] = await buildAttributesFromMetadata(service, operation, await config.region(), res, null);\n subsegment.addAttribute('aws', aws);\n subsegment.addAttribute('http', http);\n addFlags(http, subsegment);\n subsegment.close();\n return res;\n }\n catch (err) {\n if (err.$metadata) {\n const [aws, http] = await buildAttributesFromMetadata(service, operation, await config.region(), null, err);\n subsegment.addAttribute('aws', aws);\n subsegment.addAttribute('http', http);\n addFlags(http, subsegment, err);\n }\n const errObj = { message: err.message, name: err.name, stack: err.stack || new Error().stack };\n subsegment.close(errObj, true);\n throw err;\n }\n};\nconst xRayMiddlewareOptions = {\n name: XRAY_PLUGIN_NAME,\n step: 'build',\n};\nconst getXRayPlugin = (config, manualSegment) => ({\n applyToStack: (stack) => {\n stack.add(getXRayMiddleware(config, manualSegment), xRayMiddlewareOptions);\n },\n});\n/**\n * Instruments AWS SDK V3 clients with X-Ray via middleware.\n *\n * @param client - AWS SDK V3 client to instrument\n * @param manualSegment - Parent segment or subsegment that is passed in for manual mode users\n * @returns - the client with the X-Ray instrumentation middleware added to its middleware stack\n */\nfunction captureAWSClient(client, manualSegment) {\n // Remove existing middleware to ensure operation is idempotent\n client.middlewareStack.remove(XRAY_PLUGIN_NAME);\n client.middlewareStack.use(getXRayPlugin(client.config, manualSegment));\n return client;\n}\nexports.captureAWSClient = captureAWSClient;\n", "\"use strict\";\n/**\n * @module http_p\n */\n/**\n * This module patches the HTTP and HTTPS node built-in libraries and returns a copy of the module with tracing enabled.\n */\nvar url = require('url');\nvar contextUtils = require('../context_utils');\nvar Utils = require('../utils');\nvar logger = require('../logger');\nvar events = require('events');\n/**\n * Wraps the http/https.request() and .get() calls to automatically capture information for the segment.\n * This patches the built-in HTTP and HTTPS modules globally. If using a 3rd party HTTP library,\n * it should still use HTTP under the hood. Be sure to patch globally before requiring the 3rd party library.\n * 3rd party library compatibility is best effort. Some incompatibility issues may arise.\n * @param {http|https} module - The built in Node.js HTTP or HTTPS module.\n * @param {boolean} downstreamXRayEnabled - when true, adds a \"traced:true\" property to the subsegment\n * so the AWS X-Ray service expects a corresponding segment from the downstream service.\n * @param {function} subsegmentCallback - a callback that is called with the subsegment, the Node.js\n * http.ClientRequest, the Node.js http.IncomingMessage (if a response was received) and any error issued,\n * allowing custom annotations and metadata to be added.\n * to be added to the subsegment.\n * @alias module:http_p.captureHTTPsGlobal\n */\nvar captureHTTPsGlobal = function captureHTTPsGlobal(module, downstreamXRayEnabled, subsegmentCallback) {\n if (!module.__request)\n enableCapture(module, downstreamXRayEnabled, subsegmentCallback);\n};\n/**\n * Wraps the http/https.request() and .get() calls to automatically capture information for the segment.\n * Returns an instance of the HTTP or HTTPS module that is patched.\n * @param {http|https} module - The built in Node.js HTTP or HTTPS module.\n * @param {boolean} downstreamXRayEnabled - when true, adds a \"traced:true\" property to the subsegment\n * so the AWS X-Ray service expects a corresponding segment from the downstream service.\n * @param {function} subsegmentCallback - a callback that is called with the subsegment, the Node.js\n * http.ClientRequest, and the Node.js http.IncomingMessage to allow custom annotations and metadata\n * to be added to the subsegment.\n * @alias module:http_p.captureHTTPs\n * @returns {http|https}\n */\nvar captureHTTPs = function captureHTTPs(module, downstreamXRayEnabled, subsegmentCallback) {\n if (module.__request)\n return module;\n var tracedModule = {};\n Object.keys(module).forEach(function (val) {\n tracedModule[val] = module[val];\n });\n enableCapture(tracedModule, downstreamXRayEnabled, subsegmentCallback);\n return tracedModule;\n};\nfunction enableCapture(module, downstreamXRayEnabled, subsegmentCallback) {\n function captureOutgoingHTTPs(baseFunc, ...args) {\n let options;\n let callback;\n let hasUrl;\n let urlObj;\n let arg0 = args[0];\n if (typeof args[1] === 'object') {\n hasUrl = true;\n urlObj = typeof arg0 === 'string' ? new url.URL(arg0) : arg0;\n options = args[1],\n callback = args[2];\n }\n else {\n hasUrl = false;\n options = arg0;\n callback = args[1];\n }\n // Short circuit if the HTTP request has no options or is already being captured\n if (!options || (options.headers && (options.headers['X-Amzn-Trace-Id']))) {\n return baseFunc(...args);\n }\n // Case of calling a string URL without options, e.g.: http.request('http://amazon.com', callback)\n if (typeof options === 'string') {\n options = new url.URL(options);\n }\n if (!hasUrl) {\n urlObj = options;\n }\n const parent = contextUtils.resolveSegment(contextUtils.resolveManualSegmentParams(options));\n const hostname = options.hostname || options.host || urlObj.hostname || urlObj.host || 'Unknown host';\n if (!parent) {\n let output = '[ host: ' + hostname;\n output = options.method ? (output + ', method: ' + options.method) : output;\n output += ', path: ' + (urlObj.pathname || Utils.stripQueryStringFromPath(options.path)) + ' ]';\n if (!contextUtils.isAutomaticMode()) {\n logger.getLogger().info('Options for request ' + output +\n ' requires a segment object on the options params as \"XRaySegment\" for tracing in manual mode. Ignoring.');\n }\n else {\n logger.getLogger().info('Options for request ' + output +\n ' is missing the sub/segment context for automatic mode. Ignoring.');\n }\n // Options are not modified, only parsed for logging. We can pass in the original arguments.\n return baseFunc(...args);\n }\n const subsegment = parent.addNewSubsegment(hostname);\n const root = parent.segment ? parent.segment : parent;\n subsegment.namespace = 'remote';\n if (!options.headers)\n options.headers = {};\n options.headers['X-Amzn-Trace-Id'] = 'Root=' + root.trace_id + ';Parent=' + subsegment.id +\n ';Sampled=' + (!root.notTraced ? '1' : '0');\n const errorCapturer = function errorCapturer(e) {\n if (subsegmentCallback)\n subsegmentCallback(subsegment, this, null, e);\n if (subsegment.http && subsegment.http.response) {\n if (Utils.getCauseTypeFromHttpStatus(subsegment.http.response.status) === 'error') {\n subsegment.addErrorFlag();\n }\n subsegment.close(e, true);\n }\n else {\n const madeItToDownstream = (e.code !== 'ECONNREFUSED');\n subsegment.addRemoteRequestData(this, null, madeItToDownstream && downstreamXRayEnabled);\n subsegment.close(e);\n }\n // Only need to remove our listener & re-emit if we're not listening using the errorMonitor,\n // e.g. the app is running on Node 10. Otherwise the errorMonitor will re-emit automatically.\n // See: https://github.com/aws/aws-xray-sdk-node/issues/318\n // TODO: Remove this logic once node 12 support is deprecated\n if (!events.errorMonitor && this.listenerCount('error') <= 1) {\n this.removeListener('error', errorCapturer);\n this.emit('error', e);\n }\n };\n const optionsCopy = Utils.objectWithoutProperties(options, ['Segment'], true);\n let req = baseFunc(...(hasUrl ? [arg0, optionsCopy] : [options]), function (res) {\n res.on('end', function () {\n if (subsegmentCallback)\n subsegmentCallback(subsegment, this.req, res);\n if (res.statusCode === 429)\n subsegment.addThrottleFlag();\n const cause = Utils.getCauseTypeFromHttpStatus(res.statusCode);\n if (cause)\n subsegment[cause] = true;\n subsegment.addRemoteRequestData(res.req, res, !!downstreamXRayEnabled);\n subsegment.close();\n });\n if (typeof callback === 'function') {\n if (contextUtils.isAutomaticMode()) {\n const session = contextUtils.getNamespace();\n session.run(function () {\n contextUtils.setSegment(subsegment);\n callback(res);\n });\n }\n else {\n callback(res);\n }\n // if no callback provided by user application, AND no explicit response listener\n // added by user application, then we consume the response so the 'end' event fires\n // See: https://nodejs.org/api/http.html#http_class_http_clientrequest\n }\n else if (res.req && res.req.listenerCount('response') === 0) {\n res.resume();\n }\n });\n // Use errorMonitor if available (in Node 12.17+), otherwise fall back to standard error listener\n // See: https://nodejs.org/dist/latest-v12.x/docs/api/events.html#events_eventemitter_errormonitor\n req.on(events.errorMonitor || 'error', errorCapturer);\n return req;\n }\n module.__request = module.request;\n module.request = function captureHTTPsRequest(...args) {\n return captureOutgoingHTTPs(module.__request, ...args);\n };\n module.__get = module.get;\n module.get = function captureHTTPsGet(...args) {\n return captureOutgoingHTTPs(module.__get, ...args);\n };\n}\nmodule.exports.captureHTTPsGlobal = captureHTTPsGlobal;\nmodule.exports.captureHTTPs = captureHTTPs;\n", "\"use strict\";\n/**\n * @module promise_p\n */\n/**\n * This module patches native Promise libraries provided by V8 engine\n * so all subsegments generated within Promise are attached to the correct parent.\n */\nconst contextUtils = require('../context_utils');\nconst originalThen = Symbol('original then');\nconst originalCatch = Symbol('original catch');\nfunction patchPromise(Promise) {\n const then = Promise.prototype.then;\n if (!then[originalThen]) {\n Promise.prototype.then = function (onFulfilled, onRejected) {\n if (contextUtils.isAutomaticMode()\n && tryGetCurrentSegment()) {\n const ns = contextUtils.getNamespace();\n onFulfilled = onFulfilled && ns.bind(onFulfilled);\n onRejected = onRejected && ns.bind(onRejected);\n }\n return then.call(this, onFulfilled, onRejected);\n };\n Promise.prototype.then[originalThen] = then;\n }\n const origCatch = Promise.prototype.catch;\n if (origCatch && !origCatch[originalCatch]) {\n Promise.prototype.catch = function (onRejected) {\n if (contextUtils.isAutomaticMode()\n && tryGetCurrentSegment()) {\n const ns = contextUtils.getNamespace();\n onRejected = onRejected && ns.bind(onRejected);\n }\n return origCatch.call(this, onRejected);\n };\n Promise.prototype.catch[originalCatch] = origCatch;\n }\n}\nfunction unpatchPromise(Promise) {\n const then = Promise.prototype.then;\n if (then[originalThen]) {\n Promise.prototype.then = then[originalThen];\n }\n const origCatch = Promise.prototype.catch;\n if (origCatch && origCatch[originalCatch]) {\n Promise.prototype.catch = origCatch[originalCatch];\n }\n}\nfunction tryGetCurrentSegment() {\n try {\n return contextUtils.getSegment();\n }\n catch (e) {\n return undefined;\n }\n}\nfunction capturePromise() {\n patchPromise(Promise);\n}\nfunction uncapturePromise() {\n unpatchPromise(Promise);\n}\ncapturePromise.patchThirdPartyPromise = patchPromise;\nmodule.exports.capturePromise = capturePromise;\nmodule.exports.uncapturePromise = uncapturePromise;\n", "\"use strict\";\n/**\n * Represents a SQL database call.\n * @constructor\n * @param {string} databaseVer - The version on the database (user supplied).\n * @param {string} driverVer - The version on the database driver (user supplied).\n * @param {string} user - The user associated to the database call.\n * @param {string} queryType - The SQL query type.\n */\nfunction SqlData(databaseVer, driverVer, user, url, queryType) {\n this.init(databaseVer, driverVer, user, url, queryType);\n}\nSqlData.prototype.init = function init(databaseVer, driverVer, user, url, queryType) {\n if (databaseVer)\n this.database_version = databaseVer;\n if (driverVer)\n this.driver_version = driverVer;\n if (queryType)\n this.preparation = queryType;\n this.url = url;\n this.user = user;\n};\nmodule.exports = SqlData;\n", "\"use strict\";\nvar contextUtils = require('./context_utils');\nvar logging = require('./logger');\nvar segmentUtils = require('./segments/segment_utils');\nvar utils = require('./utils');\nvar LambdaEnv = require('./env/aws_lambda');\n// Import Data from package.json,\n// If the importing of package.json fails leave\n// pkginfo as an empty object\nvar pkginfo = {};\ntry {\n pkginfo = require('../../package.json');\n}\ncatch (err) {\n logging.getLogger().debug('Failed to load SDK data:', err);\n}\nvar UNKNOWN = 'unknown';\n/**\n * A module representing the AWSXRay SDK.\n * @namespace AWSXRay\n */\nvar AWSXRay = {\n /**\n * @memberof AWSXRay\n * @type {object}\n * @namespace AWSXRay.plugins\n */\n plugins: {\n /**\n * Exposes the AWS EC2 plugin.\n * @memberof AWSXRay.plugins\n */\n EC2Plugin: require('./segments/plugins/ec2_plugin'),\n /**\n * Exposes the AWS ECS plugin.\n * @memberof AWSXRay.plugins\n */\n ECSPlugin: require('./segments/plugins/ecs_plugin'),\n /**\n * Exposes the AWS Elastic Beanstalk plugin.\n * @memberof AWSXRay.plugins\n */\n ElasticBeanstalkPlugin: require('./segments/plugins/elastic_beanstalk_plugin'),\n },\n /**\n * Enables use of plugins to capture additional data for segments.\n * @param {Array} plugins - A configurable subset of AWSXRay.plugins.\n * @memberof AWSXRay\n * @see AWSXRay.plugins\n */\n config: function (plugins) {\n var pluginData = {};\n plugins.forEach(function (plugin) {\n plugin.getData(function (data) {\n if (data) {\n for (var attribute in data) {\n pluginData[attribute] = data[attribute];\n }\n }\n });\n segmentUtils.setOrigin(plugin.originName);\n segmentUtils.setPluginData(pluginData);\n });\n },\n /**\n * Overrides the default whitelisting file to specify what params to capture on each AWS Service call.\n * If a service or API is not listed, no additional data is captured.\n * The base whitelisting file can be found at /lib/resources/aws_whitelist.json\n * @param {string|Object} source - The path to the custom whitelist file, or a whitelist source JSON object.\n * @memberof AWSXRay\n */\n setAWSWhitelist: require('./segments/attributes/aws').setAWSWhitelist,\n /**\n * Appends to the current whitelisting file.\n * In the case of a duplicate service API listed, the new source will override the previous values.\n * @param {string|Object} source - The path to the custom whitelist file, or a whitelist source JSON object.\n * @memberof AWSXRay\n */\n appendAWSWhitelist: require('./segments/attributes/aws').appendAWSWhitelist,\n /**\n * Overrides the default streaming threshold (100).\n * The threshold represents the maximum number of subsegments on a single segment before\n * the SDK begins to send the completed subsegments out of band of the main segment.\n * Reduce this threshold if you see the 'Segment too large to send' error.\n * @param {number} threshold - The new threshold to use.\n * @memberof AWSXRay\n */\n setStreamingThreshold: segmentUtils.setStreamingThreshold,\n /**\n * Set your own logger for the SDK.\n * @param {Object} logger - A logger which responds to debug/info/warn/error calls.\n * @memberof AWSXRay\n */\n setLogger: logging.setLogger,\n /**\n * Gets the set logger for the SDK.\n * @memberof AWSXRay\n */\n getLogger: logging.getLogger,\n /**\n * Configures the address and port the daemon is expected to be on.\n * @param {string} address - Address of the daemon the segments should be sent to. Expects 'x.x.x.x', ':yyyy' or 'x.x.x.x:yyyy' IPv4 formats.\n * @module DaemonConfig\n * @memberof AWSXRay\n * @function\n * @see module:DaemonConfig.setDaemonAddress\n */\n setDaemonAddress: require('./daemon_config').setDaemonAddress,\n /**\n * @param {string} name - The name of the new subsegment.\n * @param {function} fcn - The function conext to wrap.\n * @param {Segment|Subsegment} [parent] - The parent for the new subsegment, for manual mode.\n * @memberof AWSXRay\n * @function\n * @see module:capture.captureFunc\n */\n captureFunc: require('./capture').captureFunc,\n /**\n * @param {string} name - The name of the new subsegment.\n * @param {function} fcn - The function conext to wrap.\n * @param {Segment|Subsegment} [parent] - The parent for the new subsegment, for manual mode.\n * @memberof AWSXRay\n * @function\n * @see module:capture.captureAsyncFunc\n */\n captureAsyncFunc: require('./capture').captureAsyncFunc,\n /**\n * @param {string} name - The name of the new subsegment.\n * @param {function} fcn - The function conext to wrap.\n * @param {Segment|Subsegment} [parent] - The parent for the new subsegment, for manual mode.\n * @memberof AWSXRay\n * @function\n * @see module:capture.captureCallbackFunc\n */\n captureCallbackFunc: require('./capture').captureCallbackFunc,\n /**\n * @param {AWS} awssdk - The Javascript AWS SDK.\n * @memberof AWSXRay\n * @function\n * @see module:aws_p.captureAWS\n */\n captureAWS: require('./patchers/aws_p').captureAWS,\n /**\n * @param {AWS.Service} service - An instance of a AWS service to wrap.\n * @memberof AWSXRay\n * @function\n * @see module:aws_p.captureAWSClient\n */\n captureAWSClient: require('./patchers/aws_p').captureAWSClient,\n /**\n * @param {AWSv3.Service} service - An instance of a AWS SDK v3 service to wrap.\n * @param {Segment|Subsegment} segment - Optional segment for manual mode.\n * @memberof AWSXRay\n * @function\n * @see module:aws3_p.captureAWSClient\n */\n captureAWSv3Client: require('./patchers/aws3_p').captureAWSClient,\n /**\n * @param {http|https} module - The built in Node.js HTTP or HTTPS module.\n * @memberof AWSXRay\n * @function\n * @returns {http|https}\n * @see module:http_p.captureHTTPs\n */\n captureHTTPs: require('./patchers/http_p').captureHTTPs,\n /**\n * @param {http|https} module - The built in Node.js HTTP or HTTPS module.\n * @memberof AWSXRay\n * @function\n * @see module:http_p.captureHTTPsGlobal\n */\n captureHTTPsGlobal: require('./patchers/http_p').captureHTTPsGlobal,\n /**\n * @memberof AWSXRay\n * @function\n * @see module:promise_p.capturePromise\n */\n capturePromise: require('./patchers/promise_p').capturePromise,\n /**\n * Exposes various helper methods.\n * @memberof AWSXRay\n * @function\n * @see module:utils\n */\n utils: utils,\n /**\n * @memberof AWSXRay\n * @type {object}\n * @namespace AWSXRay.database\n */\n database: {\n /**\n * Exposes the SqlData class.\n * @memberof AWSXRay.database\n * @see SqlData\n */\n SqlData: require('./database/sql_data'),\n },\n /**\n * Exposes the Middleware Utils class.\n * @memberof AWSXRay\n * @function\n * @see module:mw_utils\n */\n middleware: require('./middleware/mw_utils'),\n /**\n * Gets the current namespace of the context.\n * Used for supporting functions that can be used in automatic mode.\n * @memberof AWSXRay\n * @function\n * @returns {Segment|Subsegment}\n * @see module:context_utils.getNamespace\n */\n getNamespace: contextUtils.getNamespace,\n /**\n * Resolves the current segment or subsegment, checks manual and automatic modes.\n * Used for supporting functions that can be used in both manual and automatic modes.\n * @memberof AWSXRay\n * @function\n * @returns {Segment|Subsegment}\n * @see module:context_utils.resolveSegment\n */\n resolveSegment: contextUtils.resolveSegment,\n /**\n * Returns the current segment or subsegment. For use with automatic mode only.\n * @memberof AWSXRay\n * @function\n * @returns {Segment|Subsegment}\n * @see module:context_utils.getSegment\n */\n getSegment: contextUtils.getSegment,\n /**\n * Sets the current segment or subsegment. For use with automatic mode only.\n * @memberof AWSXRay\n * @function\n * @see module:context_utils.setSegment\n */\n setSegment: contextUtils.setSegment,\n /**\n * Returns true if automatic mode is enabled, otherwise false.\n * @memberof AWSXRay\n * @function\n * @see module:context_utils.isAutomaticMode\n */\n isAutomaticMode: contextUtils.isAutomaticMode,\n /**\n * Enables automatic mode. Automatic mode uses 'cls-hooked'.\n * @see https://github.com/jeff-lewis/cls-hooked\n * @memberof AWSXRay\n * @function\n * @see module:context_utils.enableAutomaticMode\n */\n enableAutomaticMode: contextUtils.enableAutomaticMode,\n /**\n * Disables automatic mode. Current segment or subsegment must be passed manually\n * via the parent optional on captureFunc, captureAsyncFunc etc.\n * @memberof AWSXRay\n * @function\n * @see module:context_utils.enableManualMode\n */\n enableManualMode: contextUtils.enableManualMode,\n /**\n * Sets the context missing strategy.\n * @param {Object} strategy - The strategy to set. This object's contextMissing function will be called whenever trace context is not found.\n */\n setContextMissingStrategy: contextUtils.setContextMissingStrategy,\n /**\n * Exposes the segment class.\n * @memberof AWSXRay\n * @function\n */\n Segment: require('./segments/segment'),\n /**\n * Exposes the subsegment class.\n * @memberof AWSXRay\n * @see Subsegment\n */\n Subsegment: require('./segments/attributes/subsegment'),\n SegmentUtils: segmentUtils\n};\n/**\n * Exposes the IncomingRequestData, to capture incoming request data.\n * For use with middleware.\n * @memberof AWSXRay.middleware\n * @see IncomingRequestData\n */\nAWSXRay.middleware.IncomingRequestData = require('./middleware/incoming_request_data'),\n (function () {\n var data = {\n runtime: (process.release && process.release.name) ? process.release.name : UNKNOWN,\n runtime_version: process.version,\n version: process.env.npm_package_version || UNKNOWN,\n name: process.env.npm_package_name || UNKNOWN\n };\n var sdkData = {\n sdk: 'X-Ray for Node.js',\n sdk_version: pkginfo.version ? pkginfo.version : UNKNOWN,\n package: pkginfo.name ? pkginfo.name : UNKNOWN,\n };\n segmentUtils.setSDKData(sdkData);\n segmentUtils.setServiceData(data);\n if (process.env.LAMBDA_TASK_ROOT)\n LambdaEnv.init();\n })();\nmodule.exports = AWSXRay;\n", "\"use strict\";\n// Convenience file to require the SDK from the root of the repository\nmodule.exports = require('./aws-xray');\n", "import { metricScope, Unit } from 'aws-embedded-metrics';\nimport type { Context } from 'aws-lambda';\nimport got from 'got';\nimport { CatalogClient } from '../catalog-builder/client.lambda-shared';\nimport * as aws from '../shared/aws.lambda-shared';\nimport { requireEnv } from '../shared/env.lambda-shared';\nimport { MetricName, METRICS_NAMESPACE } from './constants';\nimport { NpmDownloadsClient, NpmDownloadsEntry, NpmDownloadsPeriod } from './npm-downloads.lambda-shared';\n\n/**\n * Rebuilds the `stats.json` object in the configured S3 bucket.\n * Validates that the number of packages on a full rebuild should not decrease\n * significantly (due to network errors from e.g. NPM) - can be ignored\n * by passing { ignoreValidation: true }.\n *\n * @param event configuration for the rebuild job.\n * @param context the lambda context in which this execution runs.\n *\n * @returns the information about the updated S3 object.\n */\nexport async function handler(event: any, context: Context) {\n console.log(JSON.stringify(event, null, 2));\n\n const STATS_BUCKET_NAME = requireEnv('STATS_BUCKET_NAME');\n const STATS_OBJECT_KEY = requireEnv('STATS_OBJECT_KEY');\n\n const catalogClient = await CatalogClient.newClient();\n const catalog = catalogClient.packages;\n if (catalog.length === 0) {\n throw new Error('No packages found.');\n }\n\n const currentDate = new Date().toISOString();\n const stats: PackageStatsOutput = { packages: {}, updated: currentDate };\n const npmClient = new NpmDownloadsClient(got);\n\n // remove duplicates from different major versions\n const packageNames = [...new Set(catalog.map(pkg => pkg.name)).values()];\n\n console.log(`Retrieving download stats for all ${packageNames.length} registered packages: [${packageNames.join(',')}].`);\n const npmDownloads = await npmClient.getDownloads(packageNames, {\n period: NpmDownloadsPeriod.LAST_WEEK,\n throwErrors: false,\n });\n\n for (const [pkgName, entry] of npmDownloads.entries()) {\n updateStats(stats, pkgName, entry);\n }\n\n // Update metrics\n const statsCount = Object.keys(stats.packages).length;\n console.log(`There are now ${statsCount} packages with NPM stats stored.`);\n await metricScope((metrics) => async () => {\n // Clear out default dimensions as we don't need those. See https://github.com/awslabs/aws-embedded-metrics-node/issues/73\n metrics.setDimensions();\n\n metrics.setNamespace(METRICS_NAMESPACE);\n metrics.putMetric(MetricName.REGISTERED_PACKAGES_WITH_STATS, statsCount, Unit.Count);\n })();\n\n // Upload the result to S3 and exit.\n return aws.s3().putObject({\n Bucket: STATS_BUCKET_NAME,\n Key: STATS_OBJECT_KEY,\n Body: JSON.stringify(stats, null, 2),\n ContentType: 'application/json',\n CacheControl: 'public, max-age=300, must-revalidate, proxy-revalidate', // Expire from cache after 5 minutes\n Metadata: {\n 'Lambda-Log-Group': context.logGroupName,\n 'Lambda-Log-Stream': context.logStreamName,\n 'Lambda-Run-Id': context.awsRequestId,\n 'Package-Stats-Count': `${statsCount}`,\n },\n }).promise();\n}\n\nfunction updateStats(stats: PackageStatsOutput, pkgName: string, entry: NpmDownloadsEntry) {\n stats.packages[pkgName] = {\n ...(stats.packages[pkgName] ?? {}),\n downloads: {\n ...(stats.packages[pkgName]?.downloads ?? {}),\n npm: entry.downloads,\n },\n };\n}\n\nexport interface PackageStatsOutput {\n readonly packages: { [key: string]: PackageStatsEntry };\n readonly updated: string;\n}\n\nexport interface PackageStatsEntry {\n readonly downloads: PackageStatsDownloads;\n}\n\nexport interface PackageStatsDownloads {\n readonly npm: number;\n}\n", "import * as _AWS from 'aws-sdk';\nimport * as AWSXRay from 'aws-xray-sdk-core';\n\n// Do nothing if there is no XRay trace context\nAWSXRay.setContextMissingStrategy(() => {});\n\nconst AWS = AWSXRay.captureAWS(_AWS);\n\nlet _s3: AWS.S3 | undefined;\nlet _sqs: AWS.SQS | undefined;\nlet _sfn: AWS.StepFunctions | undefined;\nlet _lambda: AWS.Lambda | undefined;\nlet _codeArtifact: AWS.CodeArtifact | undefined;\n\nexport function s3(): AWS.S3 {\n if (_s3 == null) {\n _s3 = new AWS.S3();\n }\n return _s3;\n}\n\n/**\n * Checks whether an object exists in S3 at the provided bucket and key.\n */\nexport function s3ObjectExists(bucket: string, key: string): Promise<boolean> {\n return s3().headObject({\n Bucket: bucket,\n Key: key,\n }).promise()\n .then(\n () => true,\n (cause) => {\n if (cause.code === 'NotFound') {\n return false;\n }\n return Promise.reject(cause);\n },\n );\n}\n\nexport function sqs(): AWS.SQS {\n if (_sqs == null) {\n _sqs = new AWS.SQS();\n }\n return _sqs;\n}\n\nexport function stepFunctions(): AWS.StepFunctions {\n if (_sfn == null) {\n _sfn = new AWS.StepFunctions();\n }\n return _sfn;\n}\n\nexport function lambda(): AWS.Lambda {\n if (_lambda == null) {\n _lambda = new AWS.Lambda();\n }\n return _lambda;\n}\n\nexport function codeArtifact(): AWS.CodeArtifact {\n if (_codeArtifact == null) {\n _codeArtifact = new AWS.CodeArtifact();\n }\n return _codeArtifact;\n}\n\n/**\n * Resets all clients vended by this module. This is useful in unit tests when\n * `aws-sdk-mocks` is used, so that new mocks are injected as intended.\n */\nexport function reset(): void {\n _s3 = _sqs = _sfn = _lambda = _codeArtifact = undefined;\n}\n", "import { env } from 'process';\n\nexport function requireEnv(name: string): string {\n const result = env[name];\n if (!result) {\n throw new Error(`No value specified for required environment variable: ${name}`);\n }\n return result;\n}\n", "import * as AWS from 'aws-sdk';\nimport { CatalogModel, PackageInfo } from '.';\nimport { s3 } from '../shared/aws.lambda-shared';\nimport { requireEnv } from '../shared/env.lambda-shared';\n\n/**\n * A client for working with the catalog.\n */\nexport class CatalogClient {\n /**\n * Creates a new client for accessing the catalog.\n */\n public static async newClient() {\n const client = new CatalogClient();\n await client.init();\n return client;\n }\n\n private readonly s3: AWS.S3;\n private readonly bucketName: string;\n private readonly objectKey: string;\n\n private _packages: PackageInfo[] | undefined;\n\n private constructor() {\n this.bucketName = requireEnv('CATALOG_BUCKET_NAME');\n this.objectKey = requireEnv('CATALOG_OBJECT_KEY');\n this.s3 = s3();\n }\n\n /**\n * Downloads the catalog object and stores it in memory.\n */\n private async init() {\n if (this._packages) {\n throw new Error('init() cannot be called twice');\n }\n\n this._packages = [];\n\n const params = {\n Bucket: this.bucketName,\n Key: this.objectKey,\n };\n\n let body: AWS.S3.Body | undefined;\n try {\n const data = await this.s3.getObject(params).promise();\n body = data.Body;\n } catch (e) {\n throw new Error(`No catalog was found at ${this.bucketName}/${this.objectKey}`);\n }\n\n if (!body) {\n throw new Error(`Catalog body is empty at ${this.bucketName}/${this.objectKey}`);\n }\n\n const contents = body.toString('utf-8');\n\n try {\n const data = JSON.parse(contents) as CatalogModel;\n if (typeof(data) != 'object') {\n throw new Error('Invalid format in catalog file. Expecting a map');\n }\n this._packages = data.packages;\n } catch (e) {\n throw new Error(`Unable to parse catalog file ${this.bucketName}/${this.objectKey}: ${e}`);\n }\n }\n\n /**\n * Returns a copy of the catalog list.\n */\n public get packages() {\n if (!this._packages) {\n throw new Error('CatalogClient must be initialized');\n }\n\n return [...this._packages];\n }\n}\n", "export const METRICS_NAMESPACE = 'ConstructHub/PackageStats';\n\nexport const enum MetricName {\n REGISTERED_PACKAGES_WITH_STATS = 'RegisteredPackagesWithStats',\n}\n", "import type { Got } from 'got/dist/source/types';\n\nexport enum NpmDownloadsPeriod {\n /**\n * Gets downloads for the last available day. In practice, this will usually\n * be \"yesterday\" (in GMT) but if stats for that day have not yet landed, it\n * will be the day before.\n */\n LAST_DAY = 'last-day',\n\n /**\n * Gets downloads for the last 7 available days.\n */\n LAST_WEEK = 'last-week',\n\n /**\n * Gets downloads for the last 30 available days.\n */\n LAST_MONTH = 'last-month'\n}\n\nexport interface NpmDownloadsEntry {\n readonly downloads: number;\n readonly start: string;\n readonly end: string;\n readonly package: string;\n}\n\nexport type NpmDownloadsOutput = Map<string, NpmDownloadsEntry>;\n\nexport interface NpmDownloadsOptions {\n /**\n * The period to query for package download counts.\n * @default NpmDownloadsPeriod.LAST_WEEK\n */\n readonly period?: NpmDownloadsPeriod;\n\n /**\n * Throw an error when any package's download metrics are not available.\n * @default true\n */\n readonly throwErrors?: boolean;\n}\n\nexport class NpmDownloadsClient {\n public static readonly NPM_DOWNLOADS_API_URL = 'https://api.npmjs.org/downloads/point';\n public static readonly MAX_PACKAGES_PER_QUERY = 128; // this is a limitation from npm's API! do not change\n\n private readonly got: Got;\n\n constructor(gotService: Got) {\n this.got = gotService;\n }\n\n private async getDownloadsRaw(\n packages: readonly string[],\n period: NpmDownloadsPeriod,\n throwErrors: boolean,\n ): Promise<NpmDownloadsOutput> {\n if (packages.length > NpmDownloadsClient.MAX_PACKAGES_PER_QUERY) {\n throw new Error(`Too many packages were provided (max: ${NpmDownloadsClient.MAX_PACKAGES_PER_QUERY})`);\n }\n if (packages.some((pkg) => this.isScopedPackage(pkg)) && packages.length > 1) {\n throw new Error('Scoped packages aren\\'t supported by the bulk query API.');\n }\n if (packages.length === 0) return new Map();\n\n console.log(`Querying NPM for ${packages.length} package(s): [${packages.join(', ')}]`);\n const result = await this.got(`${NpmDownloadsClient.NPM_DOWNLOADS_API_URL}/${period}/${packages.join(',')}`, {\n timeout: 5 * 1000, // 5 seconds\n }).catch((err) => {\n if (throwErrors) {\n throw err;\n } else {\n return { body: JSON.stringify({ error: JSON.stringify(err) }) };\n }\n });\n\n const data: NpmApiResult = JSON.parse(result.body);\n\n // single package query error\n // ex. { \"error\": \"package foo not found\" }\n if ('error' in data) {\n if (throwErrors) {\n throw new Error(`Could not retrieve download metrics: ${data.error}`);\n } else {\n console.error(`Could not retrieve download metrics: ${data.error}`);\n return new Map();\n }\n }\n\n // only a single package was returned\n if (isSingleDownloadsEntry(data)) {\n return new Map([[packages[0], data]]);\n }\n\n // bulk query result\n for (const key of Object.keys(data)) {\n if (data[key] === null) {\n if (throwErrors) {\n throw new Error(`Could not retrieve download metrics for package ${key}`);\n } else {\n console.error(`Could not retrieve download metrics for package ${key}`);\n delete data[key];\n }\n }\n }\n\n // typescript can't figure out that we removed all null values\n // @ts-ignore\n return new Map(Object.entries(data));\n }\n\n /**\n * Retrieves the number of downloads each package has on npm in the latest period.\n * Output is not guaranteed to be returned in a specific order.\n * If throwErrors option is specified, an error is thrown when a package's\n * download count is unavailable - otherwise, it's just omitted from\n * the output.\n */\n public async getDownloads(\n packages: string[],\n options: NpmDownloadsOptions = {},\n ): Promise<NpmDownloadsOutput> {\n const period = options.period ?? NpmDownloadsPeriod.LAST_WEEK;\n const throwErrors = options.throwErrors ?? true;\n\n // separate scoped and unscoped packages since scoped packages are not\n // supported by the bulk query API\n const scopedPackages = [];\n const unscopedPackages = [];\n for (const pkg of packages) {\n if (this.isScopedPackage(pkg)) {\n scopedPackages.push(pkg);\n } else {\n unscopedPackages.push(pkg);\n }\n }\n\n // we could parallelize this, but then it's more likely we get throttled\n const output: NpmDownloadsOutput = new Map();\n for (const pkg of scopedPackages) {\n const partialResults = await this.getDownloadsRaw([pkg], period, throwErrors);\n for (const [key, value] of partialResults) {\n output.set(key, value);\n }\n }\n for (let i = 0; i < unscopedPackages.length; i += NpmDownloadsClient.MAX_PACKAGES_PER_QUERY) {\n const batch = unscopedPackages.slice(i, i + NpmDownloadsClient.MAX_PACKAGES_PER_QUERY);\n const partialResults = await this.getDownloadsRaw(batch, period, throwErrors);\n for (const [key, value] of partialResults) {\n output.set(key, value);\n }\n }\n\n return output;\n }\n\n private isScopedPackage(packageName: string) {\n return packageName.startsWith('@');\n }\n}\n\n// Types for the output of NPM's API.\ntype NpmApiResult = NpmApiError | NpmApiSingleResult | NpmApiMultipleResult;\ntype NpmApiError = { error: string };\ntype NpmApiSingleResult = NpmDownloadsEntry;\ntype NpmApiMultipleResult = { [key: string]: NpmApiSingleResult | null };\n\nfunction isSingleDownloadsEntry(data: any): data is NpmDownloadsEntry {\n return 'downloads' in data && typeof data.downloads === 'number';\n}\n"],
|
5
5
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAeA,WAAO,eAAe,SAAS,cAAc,EAAE,OAAO;AACtD,QAAI;AACJ,IAAC,UAAU,YAAW;AAClB,iBAAU,WAAU,oBAAoB,KAAK;AAC7C,iBAAU,uBAAuB;AACjC,iBAAU,WAAU,2BAA2B,OAAO;AACtD,iBAAU,wBAAwB;AAClC,iBAAU,WAAU,wBAAwB,SAAS;AAAA,OACtD,YAAY,QAAQ,aAAc,SAAQ,YAAY;AAAA;AAAA;;;ACvBzD;AAAA;AAAA;AACA,WAAO,eAAe,SAAS,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