construct-hub 0.2.55 → 0.2.59
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 +78 -11
- package/API.md +44 -0
- package/README.md +7 -0
- 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/orchestration/index.js +3 -2
- 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 +6 -6
- package/lib/backend/transliterator/transliterator.bundle/index.js.map +1 -1
- package/lib/backend/transliterator/transliterator.ecstask.js +2 -2
- package/lib/construct-hub.d.ts +7 -1
- package/lib/construct-hub.js +3 -2
- package/lib/index.d.ts +1 -1
- package/lib/index.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/config.d.ts +5 -1
- package/lib/webapp/config.js +2 -1
- package/lib/webapp/index.d.ts +16 -0
- package/lib/webapp/index.js +11 -4
- package/package.json +3 -4
- 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/semver/internal/constants.js", "../../../../node_modules/semver/internal/debug.js", "../../../../node_modules/semver/internal/re.js", "../../../../node_modules/semver/internal/parse-options.js", "../../../../node_modules/semver/internal/identifiers.js", "../../../../node_modules/semver/classes/semver.js", "../../../../node_modules/semver/functions/parse.js", "../../../../node_modules/semver/functions/valid.js", "../../../../node_modules/semver/functions/clean.js", "../../../../node_modules/semver/functions/inc.js", "../../../../node_modules/semver/functions/compare.js", "../../../../node_modules/semver/functions/eq.js", "../../../../node_modules/semver/functions/diff.js", "../../../../node_modules/semver/functions/major.js", "../../../../node_modules/semver/functions/minor.js", "../../../../node_modules/semver/functions/patch.js", "../../../../node_modules/semver/functions/prerelease.js", "../../../../node_modules/semver/functions/rcompare.js", "../../../../node_modules/semver/functions/compare-loose.js", "../../../../node_modules/semver/functions/compare-build.js", "../../../../node_modules/semver/functions/sort.js", "../../../../node_modules/semver/functions/rsort.js", "../../../../node_modules/semver/functions/gt.js", "../../../../node_modules/semver/functions/lt.js", "../../../../node_modules/semver/functions/neq.js", "../../../../node_modules/semver/functions/gte.js", "../../../../node_modules/semver/functions/lte.js", "../../../../node_modules/semver/functions/cmp.js", "../../../../node_modules/semver/functions/coerce.js", "../../../../node_modules/yallist/iterator.js", "../../../../node_modules/yallist/yallist.js", "../../../../node_modules/lru-cache/index.js", "../../../../node_modules/semver/classes/range.js", "../../../../node_modules/semver/classes/comparator.js", "../../../../node_modules/semver/functions/satisfies.js", "../../../../node_modules/semver/ranges/to-comparators.js", "../../../../node_modules/semver/ranges/max-satisfying.js", "../../../../node_modules/semver/ranges/min-satisfying.js", "../../../../node_modules/semver/ranges/min-version.js", "../../../../node_modules/semver/ranges/valid.js", "../../../../node_modules/semver/ranges/outside.js", "../../../../node_modules/semver/ranges/gtr.js", "../../../../node_modules/semver/ranges/ltr.js", "../../../../node_modules/semver/ranges/intersects.js", "../../../../node_modules/semver/ranges/simplify.js", "../../../../node_modules/semver/ranges/subset.js", "../../../../node_modules/semver/index.js", "../../../../node_modules/bl/node_modules/readable-stream/lib/internal/streams/stream.js", "../../../../node_modules/bl/node_modules/readable-stream/lib/internal/streams/buffer_list.js", "../../../../node_modules/bl/node_modules/readable-stream/lib/internal/streams/destroy.js", "../../../../node_modules/bl/node_modules/readable-stream/errors.js", "../../../../node_modules/bl/node_modules/readable-stream/lib/internal/streams/state.js", "../../../../node_modules/inherits/inherits_browser.js", "../../../../node_modules/inherits/inherits.js", "../../../../node_modules/util-deprecate/node.js", "../../../../node_modules/bl/node_modules/readable-stream/lib/_stream_writable.js", "../../../../node_modules/bl/node_modules/readable-stream/lib/_stream_duplex.js", "../../../../node_modules/safe-buffer/index.js", "../../../../node_modules/string_decoder/lib/string_decoder.js", "../../../../node_modules/bl/node_modules/readable-stream/lib/internal/streams/end-of-stream.js", "../../../../node_modules/bl/node_modules/readable-stream/lib/internal/streams/async_iterator.js", "../../../../node_modules/bl/node_modules/readable-stream/lib/internal/streams/from.js", "../../../../node_modules/bl/node_modules/readable-stream/lib/_stream_readable.js", "../../../../node_modules/bl/node_modules/readable-stream/lib/_stream_transform.js", "../../../../node_modules/bl/node_modules/readable-stream/lib/_stream_passthrough.js", "../../../../node_modules/bl/node_modules/readable-stream/lib/internal/streams/pipeline.js", "../../../../node_modules/bl/node_modules/readable-stream/readable.js", "../../../../node_modules/bl/BufferList.js", "../../../../node_modules/bl/bl.js", "../../../../node_modules/tar-stream/headers.js", "../../../../node_modules/tar-stream/node_modules/readable-stream/lib/internal/streams/stream.js", "../../../../node_modules/tar-stream/node_modules/readable-stream/lib/internal/streams/buffer_list.js", "../../../../node_modules/tar-stream/node_modules/readable-stream/lib/internal/streams/destroy.js", "../../../../node_modules/tar-stream/node_modules/readable-stream/errors.js", "../../../../node_modules/tar-stream/node_modules/readable-stream/lib/internal/streams/state.js", "../../../../node_modules/tar-stream/node_modules/readable-stream/lib/_stream_writable.js", "../../../../node_modules/tar-stream/node_modules/readable-stream/lib/_stream_duplex.js", "../../../../node_modules/tar-stream/node_modules/readable-stream/lib/internal/streams/end-of-stream.js", "../../../../node_modules/tar-stream/node_modules/readable-stream/lib/internal/streams/async_iterator.js", "../../../../node_modules/tar-stream/node_modules/readable-stream/lib/internal/streams/from.js", "../../../../node_modules/tar-stream/node_modules/readable-stream/lib/_stream_readable.js", "../../../../node_modules/tar-stream/node_modules/readable-stream/lib/_stream_transform.js", "../../../../node_modules/tar-stream/node_modules/readable-stream/lib/_stream_passthrough.js", "../../../../node_modules/tar-stream/node_modules/readable-stream/lib/internal/streams/pipeline.js", "../../../../node_modules/tar-stream/node_modules/readable-stream/readable.js", "../../../../node_modules/tar-stream/extract.js", "../../../../node_modules/fs-constants/index.js", "../../../../node_modules/wrappy/wrappy.js", "../../../../node_modules/once/once.js", "../../../../node_modules/end-of-stream/index.js", "../../../../node_modules/tar-stream/pack.js", "../../../../node_modules/tar-stream/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/catalog-builder/catalog-builder.lambda.ts", "../../../../src/backend/shared/aws.lambda-shared.ts", "../../../../src/backend/shared/env.lambda-shared.ts", "../../../../src/backend/deny-list/constants.ts", "../../../../src/backend/deny-list/client.lambda-shared.ts", "../../../../src/backend/shared/language.ts", "../../../../src/backend/shared/constants.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", "// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0'\n\nconst MAX_LENGTH = 256\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n /* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16\n\nmodule.exports = {\n SEMVER_SPEC_VERSION,\n MAX_LENGTH,\n MAX_SAFE_INTEGER,\n MAX_SAFE_COMPONENT_LENGTH\n}\n", "const debug = (\n typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n : () => {}\n\nmodule.exports = debug\n", "const { MAX_SAFE_COMPONENT_LENGTH } = require('./constants')\nconst debug = require('./debug')\nexports = module.exports = {}\n\n// The actual regexps go on exports.re\nconst re = exports.re = []\nconst src = exports.src = []\nconst t = exports.t = {}\nlet R = 0\n\nconst createToken = (name, value, isGlobal) => {\n const index = R++\n debug(index, value)\n t[name] = index\n src[index] = value\n re[index] = new RegExp(value, isGlobal ? 'g' : undefined)\n}\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\ncreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*')\ncreateToken('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\ncreateToken('NONNUMERICIDENTIFIER', '\\\\d*[a-zA-Z-][a-zA-Z0-9-]*')\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ncreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n\ncreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]\n}|${src[t.NONNUMERICIDENTIFIER]})`)\n\ncreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]\n}|${src[t.NONNUMERICIDENTIFIER]})`)\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ncreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`)\n\ncreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ncreateToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+')\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ncreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n}(?:\\\\.${src[t.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\ncreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n}${src[t.PRERELEASE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('FULL', `^${src[t.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.\ncreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n}${src[t.PRERELEASELOOSE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)\n\ncreateToken('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.\ncreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`)\ncreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`)\n\ncreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:${src[t.PRERELEASE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:${src[t.PRERELEASELOOSE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`)\ncreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ncreateToken('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])`)\ncreateToken('COERCERTL', src[t.COERCE], true)\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ncreateToken('LONETILDE', '(?:~>?)')\n\ncreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true)\nexports.tildeTrimReplace = '$1~'\n\ncreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ncreateToken('LONECARET', '(?:\\\\^)')\n\ncreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true)\nexports.caretTrimReplace = '$1^'\n\ncreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ncreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`)\ncreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.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`\ncreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)\nexports.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.\ncreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAIN]})` +\n `\\\\s*$`)\n\ncreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s*$`)\n\n// Star ranges basically just allow anything at all.\ncreateToken('STAR', '(<|>)?=?\\\\s*\\\\*')\n// >=0.0.0 is like a star\ncreateToken('GTE0', '^\\\\s*>=\\\\s*0\\.0\\.0\\\\s*$')\ncreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\.0\\.0-0\\\\s*$')\n", "// parse out just the options we care about so we always get a consistent\n// obj with keys in a consistent order.\nconst opts = ['includePrerelease', 'loose', 'rtl']\nconst parseOptions = options =>\n !options ? {}\n : typeof options !== 'object' ? { loose: true }\n : opts.filter(k => options[k]).reduce((options, k) => {\n options[k] = true\n return options\n }, {})\nmodule.exports = parseOptions\n", "const numeric = /^[0-9]+$/\nconst compareIdentifiers = (a, b) => {\n const anum = numeric.test(a)\n const 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\nconst rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)\n\nmodule.exports = {\n compareIdentifiers,\n rcompareIdentifiers\n}\n", "const debug = require('../internal/debug')\nconst { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')\nconst { re, t } = require('../internal/re')\n\nconst parseOptions = require('../internal/parse-options')\nconst { compareIdentifiers } = require('../internal/identifiers')\nclass SemVer {\n constructor (version, options) {\n options = parseOptions(options)\n\n if (version instanceof SemVer) {\n if (version.loose === !!options.loose &&\n version.includePrerelease === !!options.includePrerelease) {\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(\n `version is longer than ${MAX_LENGTH} characters`\n )\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n // this isn't actually relevant for versions, but keep it so that we\n // don't run into trouble passing this.options around.\n this.includePrerelease = !!options.includePrerelease\n\n const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.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((id) => {\n if (/^[0-9]+$/.test(id)) {\n const 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\n format () {\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\n toString () {\n return this.version\n }\n\n compare (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n if (typeof other === 'string' && other === this.version) {\n return 0\n }\n other = new SemVer(other, this.options)\n }\n\n if (other.version === this.version) {\n return 0\n }\n\n return this.compareMain(other) || this.comparePre(other)\n }\n\n compareMain (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n return (\n compareIdentifiers(this.major, other.major) ||\n compareIdentifiers(this.minor, other.minor) ||\n compareIdentifiers(this.patch, other.patch)\n )\n }\n\n comparePre (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 let i = 0\n do {\n const a = this.prerelease[i]\n const 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 compareBuild (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n let i = 0\n do {\n const a = this.build[i]\n const b = other.build[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.\n inc (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 (\n this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0\n ) {\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 let 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}\n\nmodule.exports = SemVer\n", "const {MAX_LENGTH} = require('../internal/constants')\nconst { re, t } = require('../internal/re')\nconst SemVer = require('../classes/semver')\n\nconst parseOptions = require('../internal/parse-options')\nconst parse = (version, options) => {\n options = parseOptions(options)\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 const r = options.loose ? re[t.LOOSE] : re[t.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\nmodule.exports = parse\n", "const parse = require('./parse')\nconst valid = (version, options) => {\n const v = parse(version, options)\n return v ? v.version : null\n}\nmodule.exports = valid\n", "const parse = require('./parse')\nconst clean = (version, options) => {\n const s = parse(version.trim().replace(/^[=v]+/, ''), options)\n return s ? s.version : null\n}\nmodule.exports = clean\n", "const SemVer = require('../classes/semver')\n\nconst inc = (version, release, options, identifier) => {\n if (typeof (options) === 'string') {\n identifier = options\n options = undefined\n }\n\n try {\n return new SemVer(version, options).inc(release, identifier).version\n } catch (er) {\n return null\n }\n}\nmodule.exports = inc\n", "const SemVer = require('../classes/semver')\nconst compare = (a, b, loose) =>\n new SemVer(a, loose).compare(new SemVer(b, loose))\n\nmodule.exports = compare\n", "const compare = require('./compare')\nconst eq = (a, b, loose) => compare(a, b, loose) === 0\nmodule.exports = eq\n", "const parse = require('./parse')\nconst eq = require('./eq')\n\nconst diff = (version1, version2) => {\n if (eq(version1, version2)) {\n return null\n } else {\n const v1 = parse(version1)\n const v2 = parse(version2)\n const hasPre = v1.prerelease.length || v2.prerelease.length\n const prefix = hasPre ? 'pre' : ''\n const defaultResult = hasPre ? 'prerelease' : ''\n for (const 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}\nmodule.exports = diff\n", "const SemVer = require('../classes/semver')\nconst major = (a, loose) => new SemVer(a, loose).major\nmodule.exports = major\n", "const SemVer = require('../classes/semver')\nconst minor = (a, loose) => new SemVer(a, loose).minor\nmodule.exports = minor\n", "const SemVer = require('../classes/semver')\nconst patch = (a, loose) => new SemVer(a, loose).patch\nmodule.exports = patch\n", "const parse = require('./parse')\nconst prerelease = (version, options) => {\n const parsed = parse(version, options)\n return (parsed && parsed.prerelease.length) ? parsed.prerelease : null\n}\nmodule.exports = prerelease\n", "const compare = require('./compare')\nconst rcompare = (a, b, loose) => compare(b, a, loose)\nmodule.exports = rcompare\n", "const compare = require('./compare')\nconst compareLoose = (a, b) => compare(a, b, true)\nmodule.exports = compareLoose\n", "const SemVer = require('../classes/semver')\nconst compareBuild = (a, b, loose) => {\n const versionA = new SemVer(a, loose)\n const versionB = new SemVer(b, loose)\n return versionA.compare(versionB) || versionA.compareBuild(versionB)\n}\nmodule.exports = compareBuild\n", "const compareBuild = require('./compare-build')\nconst sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))\nmodule.exports = sort\n", "const compareBuild = require('./compare-build')\nconst rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))\nmodule.exports = rsort\n", "const compare = require('./compare')\nconst gt = (a, b, loose) => compare(a, b, loose) > 0\nmodule.exports = gt\n", "const compare = require('./compare')\nconst lt = (a, b, loose) => compare(a, b, loose) < 0\nmodule.exports = lt\n", "const compare = require('./compare')\nconst neq = (a, b, loose) => compare(a, b, loose) !== 0\nmodule.exports = neq\n", "const compare = require('./compare')\nconst gte = (a, b, loose) => compare(a, b, loose) >= 0\nmodule.exports = gte\n", "const compare = require('./compare')\nconst lte = (a, b, loose) => compare(a, b, loose) <= 0\nmodule.exports = lte\n", "const eq = require('./eq')\nconst neq = require('./neq')\nconst gt = require('./gt')\nconst gte = require('./gte')\nconst lt = require('./lt')\nconst lte = require('./lte')\n\nconst 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}\nmodule.exports = cmp\n", "const SemVer = require('../classes/semver')\nconst parse = require('./parse')\nconst {re, t} = require('../internal/re')\n\nconst coerce = (version, options) => {\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version === 'number') {\n version = String(version)\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n options = options || {}\n\n let match = null\n if (!options.rtl) {\n match = version.match(re[t.COERCE])\n } else {\n // Find the right-most coercible string that does not share\n // a terminus with a more left-ward coercible string.\n // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'\n //\n // Walk through the string checking with a /g regexp\n // Manually set the index so as to pick up overlapping matches.\n // Stop when we get a match that ends at the string end, since no\n // coercible string can be more right-ward without the same terminus.\n let next\n while ((next = re[t.COERCERTL].exec(version)) &&\n (!match || match.index + match[0].length !== version.length)\n ) {\n if (!match ||\n next.index + next[0].length !== match.index + match[0].length) {\n match = next\n }\n re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length\n }\n // leave it in a clean state\n re[t.COERCERTL].lastIndex = -1\n }\n\n if (match === null)\n return null\n\n return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options)\n}\nmodule.exports = coerce\n", "'use strict'\nmodule.exports = function (Yallist) {\n Yallist.prototype[Symbol.iterator] = function* () {\n for (let walker = this.head; walker; walker = walker.next) {\n yield walker.value\n }\n }\n}\n", "'use strict'\nmodule.exports = Yallist\n\nYallist.Node = Node\nYallist.create = Yallist\n\nfunction Yallist (list) {\n var self = this\n if (!(self instanceof Yallist)) {\n self = new Yallist()\n }\n\n self.tail = null\n self.head = null\n self.length = 0\n\n if (list && typeof list.forEach === 'function') {\n list.forEach(function (item) {\n self.push(item)\n })\n } else if (arguments.length > 0) {\n for (var i = 0, l = arguments.length; i < l; i++) {\n self.push(arguments[i])\n }\n }\n\n return self\n}\n\nYallist.prototype.removeNode = function (node) {\n if (node.list !== this) {\n throw new Error('removing node which does not belong to this list')\n }\n\n var next = node.next\n var prev = node.prev\n\n if (next) {\n next.prev = prev\n }\n\n if (prev) {\n prev.next = next\n }\n\n if (node === this.head) {\n this.head = next\n }\n if (node === this.tail) {\n this.tail = prev\n }\n\n node.list.length--\n node.next = null\n node.prev = null\n node.list = null\n\n return next\n}\n\nYallist.prototype.unshiftNode = function (node) {\n if (node === this.head) {\n return\n }\n\n if (node.list) {\n node.list.removeNode(node)\n }\n\n var head = this.head\n node.list = this\n node.next = head\n if (head) {\n head.prev = node\n }\n\n this.head = node\n if (!this.tail) {\n this.tail = node\n }\n this.length++\n}\n\nYallist.prototype.pushNode = function (node) {\n if (node === this.tail) {\n return\n }\n\n if (node.list) {\n node.list.removeNode(node)\n }\n\n var tail = this.tail\n node.list = this\n node.prev = tail\n if (tail) {\n tail.next = node\n }\n\n this.tail = node\n if (!this.head) {\n this.head = node\n }\n this.length++\n}\n\nYallist.prototype.push = function () {\n for (var i = 0, l = arguments.length; i < l; i++) {\n push(this, arguments[i])\n }\n return this.length\n}\n\nYallist.prototype.unshift = function () {\n for (var i = 0, l = arguments.length; i < l; i++) {\n unshift(this, arguments[i])\n }\n return this.length\n}\n\nYallist.prototype.pop = function () {\n if (!this.tail) {\n return undefined\n }\n\n var res = this.tail.value\n this.tail = this.tail.prev\n if (this.tail) {\n this.tail.next = null\n } else {\n this.head = null\n }\n this.length--\n return res\n}\n\nYallist.prototype.shift = function () {\n if (!this.head) {\n return undefined\n }\n\n var res = this.head.value\n this.head = this.head.next\n if (this.head) {\n this.head.prev = null\n } else {\n this.tail = null\n }\n this.length--\n return res\n}\n\nYallist.prototype.forEach = function (fn, thisp) {\n thisp = thisp || this\n for (var walker = this.head, i = 0; walker !== null; i++) {\n fn.call(thisp, walker.value, i, this)\n walker = walker.next\n }\n}\n\nYallist.prototype.forEachReverse = function (fn, thisp) {\n thisp = thisp || this\n for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {\n fn.call(thisp, walker.value, i, this)\n walker = walker.prev\n }\n}\n\nYallist.prototype.get = function (n) {\n for (var i = 0, walker = this.head; walker !== null && i < n; i++) {\n // abort out of the list early if we hit a cycle\n walker = walker.next\n }\n if (i === n && walker !== null) {\n return walker.value\n }\n}\n\nYallist.prototype.getReverse = function (n) {\n for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {\n // abort out of the list early if we hit a cycle\n walker = walker.prev\n }\n if (i === n && walker !== null) {\n return walker.value\n }\n}\n\nYallist.prototype.map = function (fn, thisp) {\n thisp = thisp || this\n var res = new Yallist()\n for (var walker = this.head; walker !== null;) {\n res.push(fn.call(thisp, walker.value, this))\n walker = walker.next\n }\n return res\n}\n\nYallist.prototype.mapReverse = function (fn, thisp) {\n thisp = thisp || this\n var res = new Yallist()\n for (var walker = this.tail; walker !== null;) {\n res.push(fn.call(thisp, walker.value, this))\n walker = walker.prev\n }\n return res\n}\n\nYallist.prototype.reduce = function (fn, initial) {\n var acc\n var walker = this.head\n if (arguments.length > 1) {\n acc = initial\n } else if (this.head) {\n walker = this.head.next\n acc = this.head.value\n } else {\n throw new TypeError('Reduce of empty list with no initial value')\n }\n\n for (var i = 0; walker !== null; i++) {\n acc = fn(acc, walker.value, i)\n walker = walker.next\n }\n\n return acc\n}\n\nYallist.prototype.reduceReverse = function (fn, initial) {\n var acc\n var walker = this.tail\n if (arguments.length > 1) {\n acc = initial\n } else if (this.tail) {\n walker = this.tail.prev\n acc = this.tail.value\n } else {\n throw new TypeError('Reduce of empty list with no initial value')\n }\n\n for (var i = this.length - 1; walker !== null; i--) {\n acc = fn(acc, walker.value, i)\n walker = walker.prev\n }\n\n return acc\n}\n\nYallist.prototype.toArray = function () {\n var arr = new Array(this.length)\n for (var i = 0, walker = this.head; walker !== null; i++) {\n arr[i] = walker.value\n walker = walker.next\n }\n return arr\n}\n\nYallist.prototype.toArrayReverse = function () {\n var arr = new Array(this.length)\n for (var i = 0, walker = this.tail; walker !== null; i++) {\n arr[i] = walker.value\n walker = walker.prev\n }\n return arr\n}\n\nYallist.prototype.slice = function (from, to) {\n to = to || this.length\n if (to < 0) {\n to += this.length\n }\n from = from || 0\n if (from < 0) {\n from += this.length\n }\n var ret = new Yallist()\n if (to < from || to < 0) {\n return ret\n }\n if (from < 0) {\n from = 0\n }\n if (to > this.length) {\n to = this.length\n }\n for (var i = 0, walker = this.head; walker !== null && i < from; i++) {\n walker = walker.next\n }\n for (; walker !== null && i < to; i++, walker = walker.next) {\n ret.push(walker.value)\n }\n return ret\n}\n\nYallist.prototype.sliceReverse = function (from, to) {\n to = to || this.length\n if (to < 0) {\n to += this.length\n }\n from = from || 0\n if (from < 0) {\n from += this.length\n }\n var ret = new Yallist()\n if (to < from || to < 0) {\n return ret\n }\n if (from < 0) {\n from = 0\n }\n if (to > this.length) {\n to = this.length\n }\n for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {\n walker = walker.prev\n }\n for (; walker !== null && i > from; i--, walker = walker.prev) {\n ret.push(walker.value)\n }\n return ret\n}\n\nYallist.prototype.splice = function (start, deleteCount, ...nodes) {\n if (start > this.length) {\n start = this.length - 1\n }\n if (start < 0) {\n start = this.length + start;\n }\n\n for (var i = 0, walker = this.head; walker !== null && i < start; i++) {\n walker = walker.next\n }\n\n var ret = []\n for (var i = 0; walker && i < deleteCount; i++) {\n ret.push(walker.value)\n walker = this.removeNode(walker)\n }\n if (walker === null) {\n walker = this.tail\n }\n\n if (walker !== this.head && walker !== this.tail) {\n walker = walker.prev\n }\n\n for (var i = 0; i < nodes.length; i++) {\n walker = insert(this, walker, nodes[i])\n }\n return ret;\n}\n\nYallist.prototype.reverse = function () {\n var head = this.head\n var tail = this.tail\n for (var walker = head; walker !== null; walker = walker.prev) {\n var p = walker.prev\n walker.prev = walker.next\n walker.next = p\n }\n this.head = tail\n this.tail = head\n return this\n}\n\nfunction insert (self, node, value) {\n var inserted = node === self.head ?\n new Node(value, null, node, self) :\n new Node(value, node, node.next, self)\n\n if (inserted.next === null) {\n self.tail = inserted\n }\n if (inserted.prev === null) {\n self.head = inserted\n }\n\n self.length++\n\n return inserted\n}\n\nfunction push (self, item) {\n self.tail = new Node(item, self.tail, null, self)\n if (!self.head) {\n self.head = self.tail\n }\n self.length++\n}\n\nfunction unshift (self, item) {\n self.head = new Node(item, null, self.head, self)\n if (!self.tail) {\n self.tail = self.head\n }\n self.length++\n}\n\nfunction Node (value, prev, next, list) {\n if (!(this instanceof Node)) {\n return new Node(value, prev, next, list)\n }\n\n this.list = list\n this.value = value\n\n if (prev) {\n prev.next = this\n this.prev = prev\n } else {\n this.prev = null\n }\n\n if (next) {\n next.prev = this\n this.next = next\n } else {\n this.next = null\n }\n}\n\ntry {\n // add if support for Symbol.iterator is present\n require('./iterator.js')(Yallist)\n} catch (er) {}\n", "'use strict'\n\n// A linked list to keep track of recently-used-ness\nconst Yallist = require('yallist')\n\nconst MAX = Symbol('max')\nconst LENGTH = Symbol('length')\nconst LENGTH_CALCULATOR = Symbol('lengthCalculator')\nconst ALLOW_STALE = Symbol('allowStale')\nconst MAX_AGE = Symbol('maxAge')\nconst DISPOSE = Symbol('dispose')\nconst NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet')\nconst LRU_LIST = Symbol('lruList')\nconst CACHE = Symbol('cache')\nconst UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet')\n\nconst naiveLength = () => 1\n\n// lruList is a yallist where the head is the youngest\n// item, and the tail is the oldest. the list contains the Hit\n// objects as the entries.\n// Each Hit object has a reference to its Yallist.Node. This\n// never changes.\n//\n// cache is a Map (or PseudoMap) that matches the keys to\n// the Yallist.Node object.\nclass LRUCache {\n constructor (options) {\n if (typeof options === 'number')\n options = { max: options }\n\n if (!options)\n options = {}\n\n if (options.max && (typeof options.max !== 'number' || options.max < 0))\n throw new TypeError('max must be a non-negative number')\n // Kind of weird to have a default max of Infinity, but oh well.\n const max = this[MAX] = options.max || Infinity\n\n const lc = options.length || naiveLength\n this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc\n this[ALLOW_STALE] = options.stale || false\n if (options.maxAge && typeof options.maxAge !== 'number')\n throw new TypeError('maxAge must be a number')\n this[MAX_AGE] = options.maxAge || 0\n this[DISPOSE] = options.dispose\n this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false\n this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false\n this.reset()\n }\n\n // resize the cache when the max changes.\n set max (mL) {\n if (typeof mL !== 'number' || mL < 0)\n throw new TypeError('max must be a non-negative number')\n\n this[MAX] = mL || Infinity\n trim(this)\n }\n get max () {\n return this[MAX]\n }\n\n set allowStale (allowStale) {\n this[ALLOW_STALE] = !!allowStale\n }\n get allowStale () {\n return this[ALLOW_STALE]\n }\n\n set maxAge (mA) {\n if (typeof mA !== 'number')\n throw new TypeError('maxAge must be a non-negative number')\n\n this[MAX_AGE] = mA\n trim(this)\n }\n get maxAge () {\n return this[MAX_AGE]\n }\n\n // resize the cache when the lengthCalculator changes.\n set lengthCalculator (lC) {\n if (typeof lC !== 'function')\n lC = naiveLength\n\n if (lC !== this[LENGTH_CALCULATOR]) {\n this[LENGTH_CALCULATOR] = lC\n this[LENGTH] = 0\n this[LRU_LIST].forEach(hit => {\n hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key)\n this[LENGTH] += hit.length\n })\n }\n trim(this)\n }\n get lengthCalculator () { return this[LENGTH_CALCULATOR] }\n\n get length () { return this[LENGTH] }\n get itemCount () { return this[LRU_LIST].length }\n\n rforEach (fn, thisp) {\n thisp = thisp || this\n for (let walker = this[LRU_LIST].tail; walker !== null;) {\n const prev = walker.prev\n forEachStep(this, fn, walker, thisp)\n walker = prev\n }\n }\n\n forEach (fn, thisp) {\n thisp = thisp || this\n for (let walker = this[LRU_LIST].head; walker !== null;) {\n const next = walker.next\n forEachStep(this, fn, walker, thisp)\n walker = next\n }\n }\n\n keys () {\n return this[LRU_LIST].toArray().map(k => k.key)\n }\n\n values () {\n return this[LRU_LIST].toArray().map(k => k.value)\n }\n\n reset () {\n if (this[DISPOSE] &&\n this[LRU_LIST] &&\n this[LRU_LIST].length) {\n this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value))\n }\n\n this[CACHE] = new Map() // hash of items by key\n this[LRU_LIST] = new Yallist() // list of items in order of use recency\n this[LENGTH] = 0 // length of items in the list\n }\n\n dump () {\n return this[LRU_LIST].map(hit =>\n isStale(this, hit) ? false : {\n k: hit.key,\n v: hit.value,\n e: hit.now + (hit.maxAge || 0)\n }).toArray().filter(h => h)\n }\n\n dumpLru () {\n return this[LRU_LIST]\n }\n\n set (key, value, maxAge) {\n maxAge = maxAge || this[MAX_AGE]\n\n if (maxAge && typeof maxAge !== 'number')\n throw new TypeError('maxAge must be a number')\n\n const now = maxAge ? Date.now() : 0\n const len = this[LENGTH_CALCULATOR](value, key)\n\n if (this[CACHE].has(key)) {\n if (len > this[MAX]) {\n del(this, this[CACHE].get(key))\n return false\n }\n\n const node = this[CACHE].get(key)\n const item = node.value\n\n // dispose of the old one before overwriting\n // split out into 2 ifs for better coverage tracking\n if (this[DISPOSE]) {\n if (!this[NO_DISPOSE_ON_SET])\n this[DISPOSE](key, item.value)\n }\n\n item.now = now\n item.maxAge = maxAge\n item.value = value\n this[LENGTH] += len - item.length\n item.length = len\n this.get(key)\n trim(this)\n return true\n }\n\n const hit = new Entry(key, value, len, now, maxAge)\n\n // oversized objects fall out of cache automatically.\n if (hit.length > this[MAX]) {\n if (this[DISPOSE])\n this[DISPOSE](key, value)\n\n return false\n }\n\n this[LENGTH] += hit.length\n this[LRU_LIST].unshift(hit)\n this[CACHE].set(key, this[LRU_LIST].head)\n trim(this)\n return true\n }\n\n has (key) {\n if (!this[CACHE].has(key)) return false\n const hit = this[CACHE].get(key).value\n return !isStale(this, hit)\n }\n\n get (key) {\n return get(this, key, true)\n }\n\n peek (key) {\n return get(this, key, false)\n }\n\n pop () {\n const node = this[LRU_LIST].tail\n if (!node)\n return null\n\n del(this, node)\n return node.value\n }\n\n del (key) {\n del(this, this[CACHE].get(key))\n }\n\n load (arr) {\n // reset the cache\n this.reset()\n\n const now = Date.now()\n // A previous serialized cache has the most recent items first\n for (let l = arr.length - 1; l >= 0; l--) {\n const hit = arr[l]\n const expiresAt = hit.e || 0\n if (expiresAt === 0)\n // the item was created without expiration in a non aged cache\n this.set(hit.k, hit.v)\n else {\n const maxAge = expiresAt - now\n // dont add already expired items\n if (maxAge > 0) {\n this.set(hit.k, hit.v, maxAge)\n }\n }\n }\n }\n\n prune () {\n this[CACHE].forEach((value, key) => get(this, key, false))\n }\n}\n\nconst get = (self, key, doUse) => {\n const node = self[CACHE].get(key)\n if (node) {\n const hit = node.value\n if (isStale(self, hit)) {\n del(self, node)\n if (!self[ALLOW_STALE])\n return undefined\n } else {\n if (doUse) {\n if (self[UPDATE_AGE_ON_GET])\n node.value.now = Date.now()\n self[LRU_LIST].unshiftNode(node)\n }\n }\n return hit.value\n }\n}\n\nconst isStale = (self, hit) => {\n if (!hit || (!hit.maxAge && !self[MAX_AGE]))\n return false\n\n const diff = Date.now() - hit.now\n return hit.maxAge ? diff > hit.maxAge\n : self[MAX_AGE] && (diff > self[MAX_AGE])\n}\n\nconst trim = self => {\n if (self[LENGTH] > self[MAX]) {\n for (let walker = self[LRU_LIST].tail;\n self[LENGTH] > self[MAX] && walker !== null;) {\n // We know that we're about to delete this one, and also\n // what the next least recently used key will be, so just\n // go ahead and set it now.\n const prev = walker.prev\n del(self, walker)\n walker = prev\n }\n }\n}\n\nconst del = (self, node) => {\n if (node) {\n const hit = node.value\n if (self[DISPOSE])\n self[DISPOSE](hit.key, hit.value)\n\n self[LENGTH] -= hit.length\n self[CACHE].delete(hit.key)\n self[LRU_LIST].removeNode(node)\n }\n}\n\nclass Entry {\n constructor (key, value, length, now, maxAge) {\n this.key = key\n this.value = value\n this.length = length\n this.now = now\n this.maxAge = maxAge || 0\n }\n}\n\nconst forEachStep = (self, fn, node, thisp) => {\n let hit = node.value\n if (isStale(self, hit)) {\n del(self, node)\n if (!self[ALLOW_STALE])\n hit = undefined\n }\n if (hit)\n fn.call(thisp, hit.value, hit.key, self)\n}\n\nmodule.exports = LRUCache\n", "// hoisted class for cyclic dependency\nclass Range {\n constructor (range, options) {\n options = parseOptions(options)\n\n if (range instanceof Range) {\n if (\n range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease\n ) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n // just put it in the set and return\n this.raw = range.value\n this.set = [[range]]\n this.format()\n return this\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\n .split(/\\s*\\|\\|\\s*/)\n // map the range to a 2d array of comparators\n .map(range => this.parseRange(range.trim()))\n // throw out any comparator lists that are empty\n // this generally means that it was not a valid range, which is allowed\n // in loose mode, but will still throw if the WHOLE range is invalid.\n .filter(c => c.length)\n\n if (!this.set.length) {\n throw new TypeError(`Invalid SemVer Range: ${range}`)\n }\n\n // if we have any that are not the null set, throw out null sets.\n if (this.set.length > 1) {\n // keep the first one, in case they're all null sets\n const first = this.set[0]\n this.set = this.set.filter(c => !isNullSet(c[0]))\n if (this.set.length === 0)\n this.set = [first]\n else if (this.set.length > 1) {\n // if we have any that are *, then the range is just *\n for (const c of this.set) {\n if (c.length === 1 && isAny(c[0])) {\n this.set = [c]\n break\n }\n }\n }\n }\n\n this.format()\n }\n\n format () {\n this.range = this.set\n .map((comps) => {\n return comps.join(' ').trim()\n })\n .join('||')\n .trim()\n return this.range\n }\n\n toString () {\n return this.range\n }\n\n parseRange (range) {\n range = range.trim()\n\n // memoize range parsing for performance.\n // this is a very hot path, and fully deterministic.\n const memoOpts = Object.keys(this.options).join(',')\n const memoKey = `parseRange:${memoOpts}:${range}`\n const cached = cache.get(memoKey)\n if (cached)\n return cached\n\n const loose = this.options.loose\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n range = range.replace(hr, hyphenReplace(this.options.includePrerelease))\n debug('hyphen replace', range)\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range, re[t.COMPARATORTRIM])\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[t.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 const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const rangeList = range\n .split(' ')\n .map(comp => parseComparator(comp, this.options))\n .join(' ')\n .split(/\\s+/)\n // >=0.0.0 is equivalent to *\n .map(comp => replaceGTE0(comp, this.options))\n // in loose mode, throw out any that are not valid comparators\n .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true)\n .map(comp => new Comparator(comp, this.options))\n\n // if any comparators are the null set, then replace with JUST null set\n // if more than one comparator, remove any * comparators\n // also, don't include the same comparator more than once\n const l = rangeList.length\n const rangeMap = new Map()\n for (const comp of rangeList) {\n if (isNullSet(comp))\n return [comp]\n rangeMap.set(comp.value, comp)\n }\n if (rangeMap.size > 1 && rangeMap.has(''))\n rangeMap.delete('')\n\n const result = [...rangeMap.values()]\n cache.set(memoKey, result)\n return result\n }\n\n intersects (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some((thisComparators) => {\n return (\n isSatisfiable(thisComparators, options) &&\n range.set.some((rangeComparators) => {\n return (\n isSatisfiable(rangeComparators, options) &&\n thisComparators.every((thisComparator) => {\n return rangeComparators.every((rangeComparator) => {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n )\n })\n )\n })\n }\n\n // if ANY of the sets match ALL of its comparators, then pass\n test (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n for (let 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}\nmodule.exports = Range\n\nconst LRU = require('lru-cache')\nconst cache = new LRU({ max: 1000 })\n\nconst parseOptions = require('../internal/parse-options')\nconst Comparator = require('./comparator')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst {\n re,\n t,\n comparatorTrimReplace,\n tildeTrimReplace,\n caretTrimReplace\n} = require('../internal/re')\n\nconst isNullSet = c => c.value === '<0.0.0-0'\nconst isAny = c => c.value === ''\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nconst isSatisfiable = (comparators, options) => {\n let result = true\n const remainingComparators = comparators.slice()\n let testComparator = remainingComparators.pop()\n\n while (result && remainingComparators.length) {\n result = remainingComparators.every((otherComparator) => {\n return testComparator.intersects(otherComparator, options)\n })\n\n testComparator = remainingComparators.pop()\n }\n\n return result\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.\nconst 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\nconst isX = id => !id || id.toLowerCase() === 'x' || id === '*'\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\nconst replaceTildes = (comp, options) =>\n comp.trim().split(/\\s+/).map((comp) => {\n return replaceTilde(comp, options)\n }).join(' ')\n\nconst replaceTilde = (comp, options) => {\n const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('tilde', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0 <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0-0\n ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0-0\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-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-0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n// ^1.2.3 --> >=1.2.3 <2.0.0-0\n// ^1.2.0 --> >=1.2.0 <2.0.0-0\nconst replaceCarets = (comp, options) =>\n comp.trim().split(/\\s+/).map((comp) => {\n return replaceCaret(comp, options)\n }).join(' ')\n\nconst replaceCaret = (comp, options) => {\n debug('caret', comp, options)\n const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('caret', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n if (M === '0') {\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else {\n ret = `>=${M}.${m}.0${z} <${+M + 1}.0.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}-0`\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${+M + 1}.0.0-0`\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p\n } <${+M + 1}.0.0-0`\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nconst replaceXRanges = (comp, options) => {\n debug('replaceXRanges', comp, options)\n return comp.split(/\\s+/).map((comp) => {\n return replaceXRange(comp, options)\n }).join(' ')\n}\n\nconst replaceXRange = (comp, options) => {\n comp = comp.trim()\n const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n const xM = isX(M)\n const xm = xM || isX(m)\n const xp = xm || isX(p)\n const anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n // if we're including prereleases in the match, then we need\n // to fix this to -0, the lowest possible prerelease value\n pr = options.includePrerelease ? '-0' : ''\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.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 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 if (gtlt === '<')\n pr = '-0'\n\n ret = `${gtlt + M}.${m}.${p}${pr}`\n } else if (xm) {\n ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`\n } else if (xp) {\n ret = `>=${M}.${m}.0${pr\n } <${M}.${+m + 1}.0-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.\nconst 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[t.STAR], '')\n}\n\nconst replaceGTE0 = (comp, options) => {\n debug('replaceGTE0', comp, options)\n return comp.trim()\n .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n}\n\n// This function is passed to string.replace(re[t.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-0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\nconst hyphenReplace = incPr => ($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${incPr ? '-0' : ''}`\n } else if (isX(fp)) {\n from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`\n } else if (fpr) {\n from = `>=${from}`\n } else {\n from = `>=${from}${incPr ? '-0' : ''}`\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = `<${+tM + 1}.0.0-0`\n } else if (isX(tp)) {\n to = `<${tM}.${+tm + 1}.0-0`\n } else if (tpr) {\n to = `<=${tM}.${tm}.${tp}-${tpr}`\n } else if (incPr) {\n to = `<${tM}.${tm}.${+tp + 1}-0`\n } else {\n to = `<=${to}`\n }\n\n return (`${from} ${to}`).trim()\n}\n\nconst testSet = (set, version, options) => {\n for (let 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 (let i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === Comparator.ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n const 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", "const ANY = Symbol('SemVer ANY')\n// hoisted class for cyclic dependency\nclass Comparator {\n static get ANY () {\n return ANY\n }\n constructor (comp, options) {\n options = parseOptions(options)\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 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\n parse (comp) {\n const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const m = comp.match(r)\n\n if (!m) {\n throw new TypeError(`Invalid comparator: ${comp}`)\n }\n\n this.operator = m[1] !== undefined ? 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\n toString () {\n return this.value\n }\n\n test (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY || version === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n }\n\n intersects (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 if (this.operator === '') {\n if (this.value === '') {\n return true\n }\n return new Range(comp.value, options).test(this.value)\n } else if (comp.operator === '') {\n if (comp.value === '') {\n return true\n }\n return new Range(this.value, options).test(comp.semver)\n }\n\n const sameDirectionIncreasing =\n (this.operator === '>=' || this.operator === '>') &&\n (comp.operator === '>=' || comp.operator === '>')\n const sameDirectionDecreasing =\n (this.operator === '<=' || this.operator === '<') &&\n (comp.operator === '<=' || comp.operator === '<')\n const sameSemVer = this.semver.version === comp.semver.version\n const differentDirectionsInclusive =\n (this.operator === '>=' || this.operator === '<=') &&\n (comp.operator === '>=' || comp.operator === '<=')\n const oppositeDirectionsLessThan =\n cmp(this.semver, '<', comp.semver, options) &&\n (this.operator === '>=' || this.operator === '>') &&\n (comp.operator === '<=' || comp.operator === '<')\n const oppositeDirectionsGreaterThan =\n cmp(this.semver, '>', comp.semver, options) &&\n (this.operator === '<=' || this.operator === '<') &&\n (comp.operator === '>=' || comp.operator === '>')\n\n return (\n sameDirectionIncreasing ||\n sameDirectionDecreasing ||\n (sameSemVer && differentDirectionsInclusive) ||\n oppositeDirectionsLessThan ||\n oppositeDirectionsGreaterThan\n )\n }\n}\n\nmodule.exports = Comparator\n\nconst parseOptions = require('../internal/parse-options')\nconst {re, t} = require('../internal/re')\nconst cmp = require('../functions/cmp')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst Range = require('./range')\n", "const Range = require('../classes/range')\nconst 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}\nmodule.exports = satisfies\n", "const Range = require('../classes/range')\n\n// Mostly just for testing and legacy API reasons\nconst toComparators = (range, options) =>\n new Range(range, options).set\n .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))\n\nmodule.exports = toComparators\n", "const SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\n\nconst maxSatisfying = (versions, range, options) => {\n let max = null\n let maxSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((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}\nmodule.exports = maxSatisfying\n", "const SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst minSatisfying = (versions, range, options) => {\n let min = null\n let minSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((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}\nmodule.exports = minSatisfying\n", "const SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst gt = require('../functions/gt')\n\nconst minVersion = (range, loose) => {\n range = new Range(range, loose)\n\n let 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 (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let setMin = null\n comparators.forEach((comparator) => {\n // Clone to avoid manipulating the comparator's semver object.\n const 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 (!setMin || gt(compver, setMin)) {\n setMin = 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 if (setMin && (!minver || gt(minver, setMin)))\n minver = setMin\n }\n\n if (minver && range.test(minver)) {\n return minver\n }\n\n return null\n}\nmodule.exports = minVersion\n", "const Range = require('../classes/range')\nconst 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}\nmodule.exports = validRange\n", "const SemVer = require('../classes/semver')\nconst Comparator = require('../classes/comparator')\nconst {ANY} = Comparator\nconst Range = require('../classes/range')\nconst satisfies = require('../functions/satisfies')\nconst gt = require('../functions/gt')\nconst lt = require('../functions/lt')\nconst lte = require('../functions/lte')\nconst gte = require('../functions/gte')\n\nconst outside = (version, range, hilo, options) => {\n version = new SemVer(version, options)\n range = new Range(range, options)\n\n let 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 satisfies 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 (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let high = null\n let low = null\n\n comparators.forEach((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\nmodule.exports = outside\n", "// Determine if version is greater than all the versions possible in the range.\nconst outside = require('./outside')\nconst gtr = (version, range, options) => outside(version, range, '>', options)\nmodule.exports = gtr\n", "const outside = require('./outside')\n// Determine if version is less than all the versions possible in the range\nconst ltr = (version, range, options) => outside(version, range, '<', options)\nmodule.exports = ltr\n", "const Range = require('../classes/range')\nconst intersects = (r1, r2, options) => {\n r1 = new Range(r1, options)\n r2 = new Range(r2, options)\n return r1.intersects(r2)\n}\nmodule.exports = intersects\n", "// given a set of versions and a range, create a \"simplified\" range\n// that includes the same versions that the original range does\n// If the original range is shorter than the simplified one, return that.\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\nmodule.exports = (versions, range, options) => {\n const set = []\n let min = null\n let prev = null\n const v = versions.sort((a, b) => compare(a, b, options))\n for (const version of v) {\n const included = satisfies(version, range, options)\n if (included) {\n prev = version\n if (!min)\n min = version\n } else {\n if (prev) {\n set.push([min, prev])\n }\n prev = null\n min = null\n }\n }\n if (min)\n set.push([min, null])\n\n const ranges = []\n for (const [min, max] of set) {\n if (min === max)\n ranges.push(min)\n else if (!max && min === v[0])\n ranges.push('*')\n else if (!max)\n ranges.push(`>=${min}`)\n else if (min === v[0])\n ranges.push(`<=${max}`)\n else\n ranges.push(`${min} - ${max}`)\n }\n const simplified = ranges.join(' || ')\n const original = typeof range.raw === 'string' ? range.raw : String(range)\n return simplified.length < original.length ? simplified : range\n}\n", "const Range = require('../classes/range.js')\nconst Comparator = require('../classes/comparator.js')\nconst { ANY } = Comparator\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\n\n// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:\n// - Every simple range `r1, r2, ...` is a null set, OR\n// - Every simple range `r1, r2, ...` which is not a null set is a subset of\n// some `R1, R2, ...`\n//\n// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:\n// - If c is only the ANY comparator\n// - If C is only the ANY comparator, return true\n// - Else if in prerelease mode, return false\n// - else replace c with `[>=0.0.0]`\n// - If C is only the ANY comparator\n// - if in prerelease mode, return true\n// - else replace C with `[>=0.0.0]`\n// - Let EQ be the set of = comparators in c\n// - If EQ is more than one, return true (null set)\n// - Let GT be the highest > or >= comparator in c\n// - Let LT be the lowest < or <= comparator in c\n// - If GT and LT, and GT.semver > LT.semver, return true (null set)\n// - If any C is a = range, and GT or LT are set, return false\n// - If EQ\n// - If GT, and EQ does not satisfy GT, return true (null set)\n// - If LT, and EQ does not satisfy LT, return true (null set)\n// - If EQ satisfies every C, return true\n// - Else return false\n// - If GT\n// - If GT.semver is lower than any > or >= comp in C, return false\n// - If GT is >=, and GT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the GT.semver tuple, return false\n// - If LT\n// - If LT.semver is greater than any < or <= comp in C, return false\n// - If LT is <=, and LT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the LT.semver tuple, return false\n// - Else return true\n\nconst subset = (sub, dom, options = {}) => {\n if (sub === dom)\n return true\n\n sub = new Range(sub, options)\n dom = new Range(dom, options)\n let sawNonNull = false\n\n OUTER: for (const simpleSub of sub.set) {\n for (const simpleDom of dom.set) {\n const isSub = simpleSubset(simpleSub, simpleDom, options)\n sawNonNull = sawNonNull || isSub !== null\n if (isSub)\n continue OUTER\n }\n // the null set is a subset of everything, but null simple ranges in\n // a complex range should be ignored. so if we saw a non-null range,\n // then we know this isn't a subset, but if EVERY simple range was null,\n // then it is a subset.\n if (sawNonNull)\n return false\n }\n return true\n}\n\nconst simpleSubset = (sub, dom, options) => {\n if (sub === dom)\n return true\n\n if (sub.length === 1 && sub[0].semver === ANY) {\n if (dom.length === 1 && dom[0].semver === ANY)\n return true\n else if (options.includePrerelease)\n sub = [ new Comparator('>=0.0.0-0') ]\n else\n sub = [ new Comparator('>=0.0.0') ]\n }\n\n if (dom.length === 1 && dom[0].semver === ANY) {\n if (options.includePrerelease)\n return true\n else\n dom = [ new Comparator('>=0.0.0') ]\n }\n\n const eqSet = new Set()\n let gt, lt\n for (const c of sub) {\n if (c.operator === '>' || c.operator === '>=')\n gt = higherGT(gt, c, options)\n else if (c.operator === '<' || c.operator === '<=')\n lt = lowerLT(lt, c, options)\n else\n eqSet.add(c.semver)\n }\n\n if (eqSet.size > 1)\n return null\n\n let gtltComp\n if (gt && lt) {\n gtltComp = compare(gt.semver, lt.semver, options)\n if (gtltComp > 0)\n return null\n else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<='))\n return null\n }\n\n // will iterate one or zero times\n for (const eq of eqSet) {\n if (gt && !satisfies(eq, String(gt), options))\n return null\n\n if (lt && !satisfies(eq, String(lt), options))\n return null\n\n for (const c of dom) {\n if (!satisfies(eq, String(c), options))\n return false\n }\n\n return true\n }\n\n let higher, lower\n let hasDomLT, hasDomGT\n // if the subset has a prerelease, we need a comparator in the superset\n // with the same tuple and a prerelease, or it's not a subset\n let needDomLTPre = lt &&\n !options.includePrerelease &&\n lt.semver.prerelease.length ? lt.semver : false\n let needDomGTPre = gt &&\n !options.includePrerelease &&\n gt.semver.prerelease.length ? gt.semver : false\n // exception: <1.2.3-0 is the same as <1.2.3\n if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&\n lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {\n needDomLTPre = false\n }\n\n for (const c of dom) {\n hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='\n hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='\n if (gt) {\n if (needDomGTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomGTPre.major &&\n c.semver.minor === needDomGTPre.minor &&\n c.semver.patch === needDomGTPre.patch) {\n needDomGTPre = false\n }\n }\n if (c.operator === '>' || c.operator === '>=') {\n higher = higherGT(gt, c, options)\n if (higher === c && higher !== gt)\n return false\n } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options))\n return false\n }\n if (lt) {\n if (needDomLTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomLTPre.major &&\n c.semver.minor === needDomLTPre.minor &&\n c.semver.patch === needDomLTPre.patch) {\n needDomLTPre = false\n }\n }\n if (c.operator === '<' || c.operator === '<=') {\n lower = lowerLT(lt, c, options)\n if (lower === c && lower !== lt)\n return false\n } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options))\n return false\n }\n if (!c.operator && (lt || gt) && gtltComp !== 0)\n return false\n }\n\n // if there was a < or >, and nothing in the dom, then must be false\n // UNLESS it was limited by another range in the other direction.\n // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0\n if (gt && hasDomLT && !lt && gtltComp !== 0)\n return false\n\n if (lt && hasDomGT && !gt && gtltComp !== 0)\n return false\n\n // we needed a prerelease range in a specific tuple, but didn't get one\n // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,\n // because it includes prereleases in the 1.2.3 tuple\n if (needDomGTPre || needDomLTPre)\n return false\n\n return true\n}\n\n// >=1.2.3 is lower than >1.2.3\nconst higherGT = (a, b, options) => {\n if (!a)\n return b\n const comp = compare(a.semver, b.semver, options)\n return comp > 0 ? a\n : comp < 0 ? b\n : b.operator === '>' && a.operator === '>=' ? b\n : a\n}\n\n// <=1.2.3 is higher than <1.2.3\nconst lowerLT = (a, b, options) => {\n if (!a)\n return b\n const comp = compare(a.semver, b.semver, options)\n return comp < 0 ? a\n : comp > 0 ? b\n : b.operator === '<' && a.operator === '<=' ? b\n : a\n}\n\nmodule.exports = subset\n", "// just pre-load all the stuff that index.js lazily exports\nconst internalRe = require('./internal/re')\nmodule.exports = {\n re: internalRe.re,\n src: internalRe.src,\n tokens: internalRe.t,\n SEMVER_SPEC_VERSION: require('./internal/constants').SEMVER_SPEC_VERSION,\n SemVer: require('./classes/semver'),\n compareIdentifiers: require('./internal/identifiers').compareIdentifiers,\n rcompareIdentifiers: require('./internal/identifiers').rcompareIdentifiers,\n parse: require('./functions/parse'),\n valid: require('./functions/valid'),\n clean: require('./functions/clean'),\n inc: require('./functions/inc'),\n diff: require('./functions/diff'),\n major: require('./functions/major'),\n minor: require('./functions/minor'),\n patch: require('./functions/patch'),\n prerelease: require('./functions/prerelease'),\n compare: require('./functions/compare'),\n rcompare: require('./functions/rcompare'),\n compareLoose: require('./functions/compare-loose'),\n compareBuild: require('./functions/compare-build'),\n sort: require('./functions/sort'),\n rsort: require('./functions/rsort'),\n gt: require('./functions/gt'),\n lt: require('./functions/lt'),\n eq: require('./functions/eq'),\n neq: require('./functions/neq'),\n gte: require('./functions/gte'),\n lte: require('./functions/lte'),\n cmp: require('./functions/cmp'),\n coerce: require('./functions/coerce'),\n Comparator: require('./classes/comparator'),\n Range: require('./classes/range'),\n satisfies: require('./functions/satisfies'),\n toComparators: require('./ranges/to-comparators'),\n maxSatisfying: require('./ranges/max-satisfying'),\n minSatisfying: require('./ranges/min-satisfying'),\n minVersion: require('./ranges/min-version'),\n validRange: require('./ranges/valid'),\n outside: require('./ranges/outside'),\n gtr: require('./ranges/gtr'),\n ltr: require('./ranges/ltr'),\n intersects: require('./ranges/intersects'),\n simplifyRange: require('./ranges/simplify'),\n subset: require('./ranges/subset'),\n}\n", "module.exports = require('stream');\n", "'use strict';\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nvar _require = require('buffer'),\n Buffer = _require.Buffer;\n\nvar _require2 = require('util'),\n inspect = _require2.inspect;\n\nvar custom = inspect && inspect.custom || 'inspect';\n\nfunction copyBuffer(src, target, offset) {\n Buffer.prototype.copy.call(src, target, offset);\n}\n\nmodule.exports =\n/*#__PURE__*/\nfunction () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n _createClass(BufferList, [{\n key: \"push\",\n value: function push(v) {\n var entry = {\n data: v,\n next: null\n };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n }\n }, {\n key: \"unshift\",\n value: function unshift(v) {\n var entry = {\n data: v,\n next: this.head\n };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n }\n }, {\n key: \"shift\",\n value: function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n }\n }, {\n key: \"clear\",\n value: function clear() {\n this.head = this.tail = null;\n this.length = 0;\n }\n }, {\n key: \"join\",\n value: function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n\n while (p = p.next) {\n ret += s + p.data;\n }\n\n return ret;\n }\n }, {\n key: \"concat\",\n value: function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n\n return ret;\n } // Consumes a specified amount of bytes or characters from the buffered data.\n\n }, {\n key: \"consume\",\n value: function consume(n, hasStrings) {\n var ret;\n\n if (n < this.head.data.length) {\n // `slice` is the same for buffers and strings.\n ret = this.head.data.slice(0, n);\n this.head.data = this.head.data.slice(n);\n } else if (n === this.head.data.length) {\n // First chunk is a perfect match.\n ret = this.shift();\n } else {\n // Result spans more than one buffer.\n ret = hasStrings ? this._getString(n) : this._getBuffer(n);\n }\n\n return ret;\n }\n }, {\n key: \"first\",\n value: function first() {\n return this.head.data;\n } // Consumes a specified amount of characters from the buffered data.\n\n }, {\n key: \"_getString\",\n value: function _getString(n) {\n var p = this.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = str.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Consumes a specified amount of bytes from the buffered data.\n\n }, {\n key: \"_getBuffer\",\n value: function _getBuffer(n) {\n var ret = Buffer.allocUnsafe(n);\n var p = this.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = buf.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Make sure the linked list only shows the minimal necessary information.\n\n }, {\n key: custom,\n value: function value(_, options) {\n return inspect(this, _objectSpread({}, options, {\n // Only inspect one level.\n depth: 0,\n // It should not recurse.\n customInspect: false\n }));\n }\n }]);\n\n return BufferList;\n}();", "'use strict'; // undocumented cb() API, needed for core, not for public API\n\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n process.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n process.nextTick(emitErrorNT, this, err);\n }\n }\n\n return this;\n } // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n } // if this is a duplex stream mark the writable part as destroyed as well\n\n\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n } else if (cb) {\n process.nextTick(emitCloseNT, _this);\n cb(err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n });\n\n return this;\n}\n\nfunction emitErrorAndCloseNT(self, err) {\n emitErrorNT(self, err);\n emitCloseNT(self);\n}\n\nfunction emitCloseNT(self) {\n if (self._writableState && !self._writableState.emitClose) return;\n if (self._readableState && !self._readableState.emitClose) return;\n self.emit('close');\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nfunction errorOrDestroy(stream, err) {\n // We have tests that rely on errors being emitted\n // in the same tick, so changing this is semver major.\n // For now when you opt-in to autoDestroy we allow\n // the error to be emitted nextTick. In a future\n // semver major update we should change the default to this.\n var rState = stream._readableState;\n var wState = stream._writableState;\n if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy,\n errorOrDestroy: errorOrDestroy\n};", "'use strict';\n\nconst codes = {};\n\nfunction createErrorType(code, message, Base) {\n if (!Base) {\n Base = Error\n }\n\n function getMessage (arg1, arg2, arg3) {\n if (typeof message === 'string') {\n return message\n } else {\n return message(arg1, arg2, arg3)\n }\n }\n\n class NodeError extends Base {\n constructor (arg1, arg2, arg3) {\n super(getMessage(arg1, arg2, arg3));\n }\n }\n\n NodeError.prototype.name = Base.name;\n NodeError.prototype.code = code;\n\n codes[code] = NodeError;\n}\n\n// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js\nfunction oneOf(expected, thing) {\n if (Array.isArray(expected)) {\n const len = expected.length;\n expected = expected.map((i) => String(i));\n if (len > 2) {\n return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` +\n expected[len - 1];\n } else if (len === 2) {\n return `one of ${thing} ${expected[0]} or ${expected[1]}`;\n } else {\n return `of ${thing} ${expected[0]}`;\n }\n } else {\n return `of ${thing} ${String(expected)}`;\n }\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith\nfunction startsWith(str, search, pos) {\n\treturn str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\nfunction endsWith(str, search, this_len) {\n\tif (this_len === undefined || this_len > str.length) {\n\t\tthis_len = str.length;\n\t}\n\treturn str.substring(this_len - search.length, this_len) === search;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\nfunction includes(str, search, start) {\n if (typeof start !== 'number') {\n start = 0;\n }\n\n if (start + search.length > str.length) {\n return false;\n } else {\n return str.indexOf(search, start) !== -1;\n }\n}\n\ncreateErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {\n return 'The value \"' + value + '\" is invalid for option \"' + name + '\"'\n}, TypeError);\ncreateErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {\n // determiner: 'must be' or 'must not be'\n let determiner;\n if (typeof expected === 'string' && startsWith(expected, 'not ')) {\n determiner = 'must not be';\n expected = expected.replace(/^not /, '');\n } else {\n determiner = 'must be';\n }\n\n let msg;\n if (endsWith(name, ' argument')) {\n // For cases like 'first argument'\n msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;\n } else {\n const type = includes(name, '.') ? 'property' : 'argument';\n msg = `The \"${name}\" ${type} ${determiner} ${oneOf(expected, 'type')}`;\n }\n\n msg += `. Received type ${typeof actual}`;\n return msg;\n}, TypeError);\ncreateErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');\ncreateErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {\n return 'The ' + name + ' method is not implemented'\n});\ncreateErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');\ncreateErrorType('ERR_STREAM_DESTROYED', function (name) {\n return 'Cannot call ' + name + ' after a stream was destroyed';\n});\ncreateErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');\ncreateErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');\ncreateErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');\ncreateErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);\ncreateErrorType('ERR_UNKNOWN_ENCODING', function (arg) {\n return 'Unknown encoding: ' + arg\n}, TypeError);\ncreateErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');\n\nmodule.exports.codes = codes;\n", "'use strict';\n\nvar ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;\n\nfunction highWaterMarkFrom(options, isDuplex, duplexKey) {\n return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;\n}\n\nfunction getHighWaterMark(state, options, duplexKey, isDuplex) {\n var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);\n\n if (hwm != null) {\n if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {\n var name = isDuplex ? duplexKey : 'highWaterMark';\n throw new ERR_INVALID_OPT_VALUE(name, hwm);\n }\n\n return Math.floor(hwm);\n } // Default value\n\n\n return state.objectMode ? 16 : 16 * 1024;\n}\n\nmodule.exports = {\n getHighWaterMark: getHighWaterMark\n};", "if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n", "try {\n var util = require('util');\n /* istanbul ignore next */\n if (typeof util.inherits !== 'function') throw '';\n module.exports = util.inherits;\n} catch (e) {\n /* istanbul ignore next */\n module.exports = require('./inherits_browser.js');\n}\n", "\n/**\n * For Node.js, simply re-export the core `util.deprecate` function.\n */\n\nmodule.exports = require('util').deprecate;\n", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n'use strict';\n\nmodule.exports = Writable;\n/* <replacement> */\n\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n} // It seems a linked list but it is not\n// there will be only 2 of these for each stream\n\n\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* </replacement> */\n\n/*<replacement>*/\n\n\nvar Duplex;\n/*</replacement>*/\n\nWritable.WritableState = WritableState;\n/*<replacement>*/\n\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/*</replacement>*/\n\n/*<replacement>*/\n\nvar Stream = require('./internal/streams/stream');\n/*</replacement>*/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,\n ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,\n ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,\n ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\n\nrequire('inherits')(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream,\n // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n\n this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called\n\n this.finalCalled = false; // drain event flag.\n\n this.needDrain = false; // at the start of calling end()\n\n this.ending = false; // when end() has been called, and returned\n\n this.ended = false; // when 'finish' is emitted\n\n this.finished = false; // has it been destroyed\n\n this.destroyed = false; // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n\n this.length = 0; // a flag to see when we're in the middle of a write.\n\n this.writing = false; // when true all writes will be buffered until .uncork() call\n\n this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n\n this.sync = true; // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n\n this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)\n\n this.onwrite = function (er) {\n onwrite(stream, er);\n }; // the callback that the user supplies to write(chunk,encoding,cb)\n\n\n this.writecb = null; // the amount that is being written when _write is called.\n\n this.writelen = 0;\n this.bufferedRequest = null;\n this.lastBufferedRequest = null; // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n\n this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n\n this.prefinished = false; // True if the error was already emitted and should not be thrown again\n\n this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')\n\n this.autoDestroy = !!options.autoDestroy; // count buffered requests\n\n this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n\n while (current) {\n out.push(current);\n current = current.next;\n }\n\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function writableStateBufferGetter() {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})(); // Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\n\n\nvar realHasInstance;\n\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function value(object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function realHasInstance(object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the WritableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);\n this._writableState = new WritableState(options, this, isDuplex); // legacy.\n\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n if (typeof options.writev === 'function') this._writev = options.writev;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n} // Otherwise people can pipe Writable streams, which is just wrong.\n\n\nWritable.prototype.pipe = function () {\n errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb\n\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n} // Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\n\n\nfunction validChunk(stream, state, chunk, cb) {\n var er;\n\n if (chunk === null) {\n er = new ERR_STREAM_NULL_VALUES();\n } else if (typeof chunk !== 'string' && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);\n }\n\n if (er) {\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n return false;\n }\n\n return true;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n if (typeof cb !== 'function') cb = nop;\n if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n return ret;\n};\n\nWritable.prototype.cork = function () {\n this._writableState.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n}); // if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\n\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n\n var len = state.objectMode ? 1 : chunk.length;\n state.length += len;\n var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.\n\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n process.nextTick(cb, er); // this can emit finish, and it will always happen\n // after error\n\n process.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er); // this can emit finish, but finish must\n // always follow error\n\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();\n onwriteStateUpdate(state);\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state) || stream.destroyed;\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n process.nextTick(afterWrite, stream, state, finished, cb);\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n} // Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\n\n\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n} // if there's something in the buffer waiting, then process it\n\n\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n var count = 0;\n var allBuffers = true;\n\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n\n buffer.allBuffers = allBuffers;\n doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n\n state.pendingcb++;\n state.lastBufferedRequest = null;\n\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks\n\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n } // ignore unnecessary end() calls.\n\n\n if (!state.ending) endWritable(this, state, cb);\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n});\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\n\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n\n if (err) {\n errorOrDestroy(stream, err);\n }\n\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\n\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function' && !state.destroyed) {\n state.pendingcb++;\n state.finalCalled = true;\n process.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n\n if (need) {\n prefinish(stream, state);\n\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the readable side is ready for autoDestroy as well\n var rState = stream._readableState;\n\n if (!rState || rState.autoDestroy && rState.endEmitted) {\n stream.destroy();\n }\n }\n }\n }\n\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n\n if (cb) {\n if (state.finished) process.nextTick(cb);else stream.once('finish', cb);\n }\n\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n } // reuse the free corkReq.\n\n\n state.corkedRequestsFree.next = corkReq;\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._writableState === undefined) {\n return false;\n }\n\n return this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._writableState.destroyed = value;\n }\n});\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\n\nWritable.prototype._destroy = function (err, cb) {\n cb(err);\n};", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n'use strict';\n/*<replacement>*/\n\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n\n for (var key in obj) {\n keys.push(key);\n }\n\n return keys;\n};\n/*</replacement>*/\n\n\nmodule.exports = Duplex;\n\nvar Readable = require('./_stream_readable');\n\nvar Writable = require('./_stream_writable');\n\nrequire('inherits')(Duplex, Readable);\n\n{\n // Allow the keys array to be GC'ed.\n var keys = objectKeys(Writable.prototype);\n\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n Readable.call(this, options);\n Writable.call(this, options);\n this.allowHalfOpen = true;\n\n if (options) {\n if (options.readable === false) this.readable = false;\n if (options.writable === false) this.writable = false;\n\n if (options.allowHalfOpen === false) {\n this.allowHalfOpen = false;\n this.once('end', onend);\n }\n }\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n}); // the no-half-open enforcer\n\nfunction onend() {\n // If the writable side ended, then we're ok.\n if (this._writableState.ended) return; // no more data can be written.\n // But allow more writes to happen in this tick.\n\n process.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});", "/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/*<replacement>*/\n\nvar Buffer = require('safe-buffer').Buffer;\n/*</replacement>*/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}", "// Ported from https://github.com/mafintosh/end-of-stream with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n callback.apply(this, args);\n };\n}\n\nfunction noop() {}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction eos(stream, opts, callback) {\n if (typeof opts === 'function') return eos(stream, null, opts);\n if (!opts) opts = {};\n callback = once(callback || noop);\n var readable = opts.readable || opts.readable !== false && stream.readable;\n var writable = opts.writable || opts.writable !== false && stream.writable;\n\n var onlegacyfinish = function onlegacyfinish() {\n if (!stream.writable) onfinish();\n };\n\n var writableEnded = stream._writableState && stream._writableState.finished;\n\n var onfinish = function onfinish() {\n writable = false;\n writableEnded = true;\n if (!readable) callback.call(stream);\n };\n\n var readableEnded = stream._readableState && stream._readableState.endEmitted;\n\n var onend = function onend() {\n readable = false;\n readableEnded = true;\n if (!writable) callback.call(stream);\n };\n\n var onerror = function onerror(err) {\n callback.call(stream, err);\n };\n\n var onclose = function onclose() {\n var err;\n\n if (readable && !readableEnded) {\n if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n\n if (writable && !writableEnded) {\n if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n };\n\n var onrequest = function onrequest() {\n stream.req.on('finish', onfinish);\n };\n\n if (isRequest(stream)) {\n stream.on('complete', onfinish);\n stream.on('abort', onclose);\n if (stream.req) onrequest();else stream.on('request', onrequest);\n } else if (writable && !stream._writableState) {\n // legacy streams\n stream.on('end', onlegacyfinish);\n stream.on('close', onlegacyfinish);\n }\n\n stream.on('end', onend);\n stream.on('finish', onfinish);\n if (opts.error !== false) stream.on('error', onerror);\n stream.on('close', onclose);\n return function () {\n stream.removeListener('complete', onfinish);\n stream.removeListener('abort', onclose);\n stream.removeListener('request', onrequest);\n if (stream.req) stream.req.removeListener('finish', onfinish);\n stream.removeListener('end', onlegacyfinish);\n stream.removeListener('close', onlegacyfinish);\n stream.removeListener('finish', onfinish);\n stream.removeListener('end', onend);\n stream.removeListener('error', onerror);\n stream.removeListener('close', onclose);\n };\n}\n\nmodule.exports = eos;", "'use strict';\n\nvar _Object$setPrototypeO;\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar finished = require('./end-of-stream');\n\nvar kLastResolve = Symbol('lastResolve');\nvar kLastReject = Symbol('lastReject');\nvar kError = Symbol('error');\nvar kEnded = Symbol('ended');\nvar kLastPromise = Symbol('lastPromise');\nvar kHandlePromise = Symbol('handlePromise');\nvar kStream = Symbol('stream');\n\nfunction createIterResult(value, done) {\n return {\n value: value,\n done: done\n };\n}\n\nfunction readAndResolve(iter) {\n var resolve = iter[kLastResolve];\n\n if (resolve !== null) {\n var data = iter[kStream].read(); // we defer if data is null\n // we can be expecting either 'end' or\n // 'error'\n\n if (data !== null) {\n iter[kLastPromise] = null;\n iter[kLastResolve] = null;\n iter[kLastReject] = null;\n resolve(createIterResult(data, false));\n }\n }\n}\n\nfunction onReadable(iter) {\n // we wait for the next tick, because it might\n // emit an error with process.nextTick\n process.nextTick(readAndResolve, iter);\n}\n\nfunction wrapForNext(lastPromise, iter) {\n return function (resolve, reject) {\n lastPromise.then(function () {\n if (iter[kEnded]) {\n resolve(createIterResult(undefined, true));\n return;\n }\n\n iter[kHandlePromise](resolve, reject);\n }, reject);\n };\n}\n\nvar AsyncIteratorPrototype = Object.getPrototypeOf(function () {});\nvar ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {\n get stream() {\n return this[kStream];\n },\n\n next: function next() {\n var _this = this;\n\n // if we have detected an error in the meanwhile\n // reject straight away\n var error = this[kError];\n\n if (error !== null) {\n return Promise.reject(error);\n }\n\n if (this[kEnded]) {\n return Promise.resolve(createIterResult(undefined, true));\n }\n\n if (this[kStream].destroyed) {\n // We need to defer via nextTick because if .destroy(err) is\n // called, the error will be emitted via nextTick, and\n // we cannot guarantee that there is no error lingering around\n // waiting to be emitted.\n return new Promise(function (resolve, reject) {\n process.nextTick(function () {\n if (_this[kError]) {\n reject(_this[kError]);\n } else {\n resolve(createIterResult(undefined, true));\n }\n });\n });\n } // if we have multiple next() calls\n // we will wait for the previous Promise to finish\n // this logic is optimized to support for await loops,\n // where next() is only called once at a time\n\n\n var lastPromise = this[kLastPromise];\n var promise;\n\n if (lastPromise) {\n promise = new Promise(wrapForNext(lastPromise, this));\n } else {\n // fast path needed to support multiple this.push()\n // without triggering the next() queue\n var data = this[kStream].read();\n\n if (data !== null) {\n return Promise.resolve(createIterResult(data, false));\n }\n\n promise = new Promise(this[kHandlePromise]);\n }\n\n this[kLastPromise] = promise;\n return promise;\n }\n}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {\n return this;\n}), _defineProperty(_Object$setPrototypeO, \"return\", function _return() {\n var _this2 = this;\n\n // destroy(err, cb) is a private API\n // we can guarantee we have that here, because we control the\n // Readable class this is attached to\n return new Promise(function (resolve, reject) {\n _this2[kStream].destroy(null, function (err) {\n if (err) {\n reject(err);\n return;\n }\n\n resolve(createIterResult(undefined, true));\n });\n });\n}), _Object$setPrototypeO), AsyncIteratorPrototype);\n\nvar createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {\n var _Object$create;\n\n var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {\n value: stream,\n writable: true\n }), _defineProperty(_Object$create, kLastResolve, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kLastReject, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kError, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kEnded, {\n value: stream._readableState.endEmitted,\n writable: true\n }), _defineProperty(_Object$create, kHandlePromise, {\n value: function value(resolve, reject) {\n var data = iterator[kStream].read();\n\n if (data) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(data, false));\n } else {\n iterator[kLastResolve] = resolve;\n iterator[kLastReject] = reject;\n }\n },\n writable: true\n }), _Object$create));\n iterator[kLastPromise] = null;\n finished(stream, function (err) {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise\n // returned by next() and store the error\n\n if (reject !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n reject(err);\n }\n\n iterator[kError] = err;\n return;\n }\n\n var resolve = iterator[kLastResolve];\n\n if (resolve !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(undefined, true));\n }\n\n iterator[kEnded] = true;\n });\n stream.on('readable', onReadable.bind(null, iterator));\n return iterator;\n};\n\nmodule.exports = createReadableStreamAsyncIterator;", "'use strict';\n\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }\n\nfunction _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err); } _next(undefined); }); }; }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE;\n\nfunction from(Readable, iterable, opts) {\n var iterator;\n\n if (iterable && typeof iterable.next === 'function') {\n iterator = iterable;\n } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable);\n\n var readable = new Readable(_objectSpread({\n objectMode: true\n }, opts)); // Reading boolean to protect against _read\n // being called before last iteration completion.\n\n var reading = false;\n\n readable._read = function () {\n if (!reading) {\n reading = true;\n next();\n }\n };\n\n function next() {\n return _next2.apply(this, arguments);\n }\n\n function _next2() {\n _next2 = _asyncToGenerator(function* () {\n try {\n var _ref = yield iterator.next(),\n value = _ref.value,\n done = _ref.done;\n\n if (done) {\n readable.push(null);\n } else if (readable.push((yield value))) {\n next();\n } else {\n reading = false;\n }\n } catch (err) {\n readable.destroy(err);\n }\n });\n return _next2.apply(this, arguments);\n }\n\n return readable;\n}\n\nmodule.exports = from;", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n'use strict';\n\nmodule.exports = Readable;\n/*<replacement>*/\n\nvar Duplex;\n/*</replacement>*/\n\nReadable.ReadableState = ReadableState;\n/*<replacement>*/\n\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function EElistenerCount(emitter, type) {\n return emitter.listeners(type).length;\n};\n/*</replacement>*/\n\n/*<replacement>*/\n\n\nvar Stream = require('./internal/streams/stream');\n/*</replacement>*/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n/*<replacement>*/\n\n\nvar debugUtil = require('util');\n\nvar debug;\n\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function debug() {};\n}\n/*</replacement>*/\n\n\nvar BufferList = require('./internal/streams/buffer_list');\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.\n\n\nvar StringDecoder;\nvar createReadableStreamAsyncIterator;\nvar from;\n\nrequire('inherits')(Readable, Stream);\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n\n this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n\n this.sync = true; // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n this.paused = true; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')\n\n this.autoDestroy = !!options.autoDestroy; // has it been destroyed\n\n this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s\n\n this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled\n\n this.readingMore = false;\n this.decoder = null;\n this.encoding = null;\n\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside\n // the ReadableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n this._readableState = new ReadableState(options, this, isDuplex); // legacy\n\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n }\n});\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\n\nReadable.prototype._destroy = function (err, cb) {\n cb(err);\n}; // Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\n\n\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n}; // Unshift should *always* be something directly out of read()\n\n\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n debug('readableAddChunk', chunk);\n var state = stream._readableState;\n\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n\n if (er) {\n errorOrDestroy(stream, er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());\n } else if (state.destroyed) {\n return false;\n } else {\n state.reading = false;\n\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n maybeReadMore(stream, state);\n }\n } // We can push more data if we are below the highWaterMark.\n // Also, if we have no data yet, we can stand some more bytes.\n // This is to work around cases where hwm=0, such as the repl.\n\n\n return !state.ended && (state.length < state.highWaterMark || state.length === 0);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n state.awaitDrain = 0;\n stream.emit('data', chunk);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n if (state.needReadable) emitReadable(stream);\n }\n\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);\n }\n\n return er;\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n}; // backwards compatibility.\n\n\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n var decoder = new StringDecoder(enc);\n this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8\n\n this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:\n\n var p = this._readableState.buffer.head;\n var content = '';\n\n while (p !== null) {\n content += decoder.write(p.data);\n p = p.next;\n }\n\n this._readableState.buffer.clear();\n\n if (content !== '') this._readableState.buffer.push(content);\n this._readableState.length = content.length;\n return this;\n}; // Don't raise the hwm > 1GB\n\n\nvar MAX_HWM = 0x40000000;\n\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n\n return n;\n} // This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\n\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n } // If we're asking for more than the current hwm, then raise the hwm.\n\n\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n; // Don't have enough\n\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n\n return state.length;\n} // you can override either this method, or the async _read(n) below.\n\n\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n\n if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.\n\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n } // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n // if we need a readable event, then we need to do some reading.\n\n\n var doRead = state.needReadable;\n debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some\n\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n } // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n\n\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true; // if the length is currently zero, then we *need* a readable event.\n\n if (state.length === 0) state.needReadable = true; // call internal read method\n\n this._read(state.highWaterMark);\n\n state.sync = false; // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = state.length <= state.highWaterMark;\n n = 0;\n } else {\n state.length -= n;\n state.awaitDrain = 0;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.\n\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n debug('onEofChunk');\n if (state.ended) return;\n\n if (state.decoder) {\n var chunk = state.decoder.end();\n\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n\n state.ended = true;\n\n if (state.sync) {\n // if we are sync, wait until next tick to emit the data.\n // Otherwise we risk emitting data in the flow()\n // the readable code triggers during a read() call\n emitReadable(stream);\n } else {\n // emit 'readable' now to make sure it gets picked up.\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n state.emittedReadable = true;\n emitReadable_(stream);\n }\n }\n} // Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\n\n\nfunction emitReadable(stream) {\n var state = stream._readableState;\n debug('emitReadable', state.needReadable, state.emittedReadable);\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n process.nextTick(emitReadable_, stream);\n }\n}\n\nfunction emitReadable_(stream) {\n var state = stream._readableState;\n debug('emitReadable_', state.destroyed, state.length, state.ended);\n\n if (!state.destroyed && (state.length || state.ended)) {\n stream.emit('readable');\n state.emittedReadable = false;\n } // The stream needs another readable event if\n // 1. It is not flowing, as the flow mechanism will take\n // care of it.\n // 2. It is not ended.\n // 3. It is below the highWaterMark, so we can schedule\n // another readable later.\n\n\n state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;\n flow(stream);\n} // at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\n\n\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n process.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n // Attempt to read more data if we should.\n //\n // The conditions for reading more data are (one of):\n // - Not enough data buffered (state.length < state.highWaterMark). The loop\n // is responsible for filling the buffer with enough data if such data\n // is available. If highWaterMark is 0 and we are not in the flowing mode\n // we should _not_ attempt to buffer any extra data. We'll get more data\n // when the stream consumer calls read() instead.\n // - No data in the buffer, and the stream is in flowing mode. In this mode\n // the loop below is responsible for ensuring read() is called. Failing to\n // call read here would abort the flow and there's no other mechanism for\n // continuing the flow if the stream consumer has just subscribed to the\n // 'data' event.\n //\n // In addition to the above conditions to keep reading data, the following\n // conditions prevent the data from being read:\n // - The stream has ended (state.ended).\n // - There is already a pending 'read' operation (state.reading). This is a\n // case where the the stream has called the implementation defined _read()\n // method, but they are processing the call asynchronously and have _not_\n // called push() with new data. In this case we skip performing more\n // read()s. The execution ends in this method again after the _read() ends\n // up calling push() with more data.\n while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {\n var len = state.length;\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length) // didn't get any data, stop spinning.\n break;\n }\n\n state.readingMore = false;\n} // abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\n\n\nReadable.prototype._read = function (n) {\n errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n\n default:\n state.pipes.push(dest);\n break;\n }\n\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);\n dest.on('unpipe', onunpipe);\n\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n } // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n\n\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n var cleanedUp = false;\n\n function cleanup() {\n debug('cleanup'); // cleanup event handlers once the pipe is broken\n\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n cleanedUp = true; // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n src.on('data', ondata);\n\n function ondata(chunk) {\n debug('ondata');\n var ret = dest.write(chunk);\n debug('dest.write', ret);\n\n if (ret === false) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n }\n\n src.pause();\n }\n } // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n\n\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);\n } // Make sure our error handler is attached before userland ones.\n\n\n prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.\n\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n\n dest.once('close', onclose);\n\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n } // tell the dest that it's being piped to\n\n\n dest.emit('pipe', src); // start the flow if it hasn't been started already.\n\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function pipeOnDrainFunctionResult() {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = {\n hasUnpiped: false\n }; // if we're not piping anywhere, then do nothing.\n\n if (state.pipesCount === 0) return this; // just one destination. most common case.\n\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n if (!dest) dest = state.pipes; // got a match.\n\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n } // slow case. multiple pipe destinations.\n\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, {\n hasUnpiped: false\n });\n }\n\n return this;\n } // try to find the right one.\n\n\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n dest.emit('unpipe', this, unpipeInfo);\n return this;\n}; // set up data events if they are asked for\n// Ensure readable listeners eventually get something\n\n\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n var state = this._readableState;\n\n if (ev === 'data') {\n // update readableListening so that resume() may be a no-op\n // a few lines down. This is needed to support once('readable').\n state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused\n\n if (state.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.flowing = false;\n state.emittedReadable = false;\n debug('on readable', state.length, state.reading);\n\n if (state.length) {\n emitReadable(this);\n } else if (!state.reading) {\n process.nextTick(nReadingNextTick, this);\n }\n }\n }\n\n return res;\n};\n\nReadable.prototype.addListener = Readable.prototype.on;\n\nReadable.prototype.removeListener = function (ev, fn) {\n var res = Stream.prototype.removeListener.call(this, ev, fn);\n\n if (ev === 'readable') {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nReadable.prototype.removeAllListeners = function (ev) {\n var res = Stream.prototype.removeAllListeners.apply(this, arguments);\n\n if (ev === 'readable' || ev === undefined) {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nfunction updateReadableListening(self) {\n var state = self._readableState;\n state.readableListening = self.listenerCount('readable') > 0;\n\n if (state.resumeScheduled && !state.paused) {\n // flowing needs to be set to true now, otherwise\n // the upcoming resume will not flow.\n state.flowing = true; // crude way to check if we should resume\n } else if (self.listenerCount('data') > 0) {\n self.resume();\n }\n}\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n} // pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\n\n\nReadable.prototype.resume = function () {\n var state = this._readableState;\n\n if (!state.flowing) {\n debug('resume'); // we flow only if there is no one listening\n // for readable, but we still have to call\n // resume()\n\n state.flowing = !state.readableListening;\n resume(this, state);\n }\n\n state.paused = false;\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n process.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n debug('resume', state.reading);\n\n if (!state.reading) {\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n\n if (this._readableState.flowing !== false) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n\n this._readableState.paused = true;\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n\n while (state.flowing && stream.read() !== null) {\n ;\n }\n} // wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\n\n\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n stream.on('end', function () {\n debug('wrapped end');\n\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode\n\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n\n if (!ret) {\n paused = true;\n stream.pause();\n }\n }); // proxy all the other methods.\n // important when wrapping filters and duplexes.\n\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function methodWrap(method) {\n return function methodWrapReturnFunction() {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n } // proxy certain important events.\n\n\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n } // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n\n\n this._read = function (n) {\n debug('wrapped _read', n);\n\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nif (typeof Symbol === 'function') {\n Readable.prototype[Symbol.asyncIterator] = function () {\n if (createReadableStreamAsyncIterator === undefined) {\n createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');\n }\n\n return createReadableStreamAsyncIterator(this);\n };\n}\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.highWaterMark;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState && this._readableState.buffer;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableFlowing', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.flowing;\n },\n set: function set(state) {\n if (this._readableState) {\n this._readableState.flowing = state;\n }\n }\n}); // exposed for testing purposes only.\n\nReadable._fromList = fromList;\nObject.defineProperty(Readable.prototype, 'readableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.length;\n }\n}); // Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = state.buffer.consume(n, state.decoder);\n }\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n debug('endReadable', state.endEmitted);\n\n if (!state.endEmitted) {\n state.ended = true;\n process.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.\n\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the writable side is ready for autoDestroy as well\n var wState = stream._writableState;\n\n if (!wState || wState.autoDestroy && wState.finished) {\n stream.destroy();\n }\n }\n }\n}\n\nif (typeof Symbol === 'function') {\n Readable.from = function (iterable, opts) {\n if (from === undefined) {\n from = require('./internal/streams/from');\n }\n\n return from(Readable, iterable, opts);\n };\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n\n return -1;\n}", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n'use strict';\n\nmodule.exports = Transform;\n\nvar _require$codes = require('../errors').codes,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,\n ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;\n\nvar Duplex = require('./_stream_duplex');\n\nrequire('inherits')(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n var cb = ts.writecb;\n\n if (cb === null) {\n return this.emit('error', new ERR_MULTIPLE_CALLBACK());\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n cb(er);\n var rs = this._readableState;\n rs.reading = false;\n\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n Duplex.call(this, options);\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n }; // start out asking for a readable event once data is transformed.\n\n this._readableState.needReadable = true; // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n if (typeof options.flush === 'function') this._flush = options.flush;\n } // When the writable side finishes, then flush out anything remaining.\n\n\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function' && !this._readableState.destroyed) {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n}; // This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\n\n\nTransform.prototype._transform = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n}; // Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\n\n\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && !ts.transforming) {\n ts.transforming = true;\n\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data); // TODO(BridgeAR): Write a test for these two error cases\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n\n if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();\n if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();\n return stream.push(null);\n}", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\nrequire('inherits')(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};", "// Ported from https://github.com/mafintosh/pump with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar eos;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n callback.apply(void 0, arguments);\n };\n}\n\nvar _require$codes = require('../../../errors').codes,\n ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;\n\nfunction noop(err) {\n // Rethrow the error if it exists to avoid swallowing it\n if (err) throw err;\n}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction destroyer(stream, reading, writing, callback) {\n callback = once(callback);\n var closed = false;\n stream.on('close', function () {\n closed = true;\n });\n if (eos === undefined) eos = require('./end-of-stream');\n eos(stream, {\n readable: reading,\n writable: writing\n }, function (err) {\n if (err) return callback(err);\n closed = true;\n callback();\n });\n var destroyed = false;\n return function (err) {\n if (closed) return;\n if (destroyed) return;\n destroyed = true; // request.destroy just do .end - .abort is what we want\n\n if (isRequest(stream)) return stream.abort();\n if (typeof stream.destroy === 'function') return stream.destroy();\n callback(err || new ERR_STREAM_DESTROYED('pipe'));\n };\n}\n\nfunction call(fn) {\n fn();\n}\n\nfunction pipe(from, to) {\n return from.pipe(to);\n}\n\nfunction popCallback(streams) {\n if (!streams.length) return noop;\n if (typeof streams[streams.length - 1] !== 'function') return noop;\n return streams.pop();\n}\n\nfunction pipeline() {\n for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {\n streams[_key] = arguments[_key];\n }\n\n var callback = popCallback(streams);\n if (Array.isArray(streams[0])) streams = streams[0];\n\n if (streams.length < 2) {\n throw new ERR_MISSING_ARGS('streams');\n }\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 return streams.reduce(pipe);\n}\n\nmodule.exports = pipeline;", "var Stream = require('stream');\nif (process.env.READABLE_STREAM === 'disable' && Stream) {\n module.exports = Stream.Readable;\n Object.assign(module.exports, Stream);\n module.exports.Stream = Stream;\n} else {\n exports = module.exports = require('./lib/_stream_readable.js');\n exports.Stream = Stream || exports;\n exports.Readable = exports;\n exports.Writable = require('./lib/_stream_writable.js');\n exports.Duplex = require('./lib/_stream_duplex.js');\n exports.Transform = require('./lib/_stream_transform.js');\n exports.PassThrough = require('./lib/_stream_passthrough.js');\n exports.finished = require('./lib/internal/streams/end-of-stream.js');\n exports.pipeline = require('./lib/internal/streams/pipeline.js');\n}\n", "'use strict'\n\nconst { Buffer } = require('buffer')\nconst symbol = Symbol.for('BufferList')\n\nfunction BufferList (buf) {\n if (!(this instanceof BufferList)) {\n return new BufferList(buf)\n }\n\n BufferList._init.call(this, buf)\n}\n\nBufferList._init = function _init (buf) {\n Object.defineProperty(this, symbol, { value: true })\n\n this._bufs = []\n this.length = 0\n\n if (buf) {\n this.append(buf)\n }\n}\n\nBufferList.prototype._new = function _new (buf) {\n return new BufferList(buf)\n}\n\nBufferList.prototype._offset = function _offset (offset) {\n if (offset === 0) {\n return [0, 0]\n }\n\n let tot = 0\n\n for (let i = 0; i < this._bufs.length; i++) {\n const _t = tot + this._bufs[i].length\n if (offset < _t || i === this._bufs.length - 1) {\n return [i, offset - tot]\n }\n tot = _t\n }\n}\n\nBufferList.prototype._reverseOffset = function (blOffset) {\n const bufferId = blOffset[0]\n let offset = blOffset[1]\n\n for (let i = 0; i < bufferId; i++) {\n offset += this._bufs[i].length\n }\n\n return offset\n}\n\nBufferList.prototype.get = function get (index) {\n if (index > this.length || index < 0) {\n return undefined\n }\n\n const offset = this._offset(index)\n\n return this._bufs[offset[0]][offset[1]]\n}\n\nBufferList.prototype.slice = function slice (start, end) {\n if (typeof start === 'number' && start < 0) {\n start += this.length\n }\n\n if (typeof end === 'number' && end < 0) {\n end += this.length\n }\n\n return this.copy(null, 0, start, end)\n}\n\nBufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {\n if (typeof srcStart !== 'number' || srcStart < 0) {\n srcStart = 0\n }\n\n if (typeof srcEnd !== 'number' || srcEnd > this.length) {\n srcEnd = this.length\n }\n\n if (srcStart >= this.length) {\n return dst || Buffer.alloc(0)\n }\n\n if (srcEnd <= 0) {\n return dst || Buffer.alloc(0)\n }\n\n const copy = !!dst\n const off = this._offset(srcStart)\n const len = srcEnd - srcStart\n let bytes = len\n let bufoff = (copy && dstStart) || 0\n let start = off[1]\n\n // copy/slice everything\n if (srcStart === 0 && srcEnd === this.length) {\n if (!copy) {\n // slice, but full concat if multiple buffers\n return this._bufs.length === 1\n ? this._bufs[0]\n : Buffer.concat(this._bufs, this.length)\n }\n\n // copy, need to copy individual buffers\n for (let i = 0; i < this._bufs.length; i++) {\n this._bufs[i].copy(dst, bufoff)\n bufoff += this._bufs[i].length\n }\n\n return dst\n }\n\n // easy, cheap case where it's a subset of one of the buffers\n if (bytes <= this._bufs[off[0]].length - start) {\n return copy\n ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)\n : this._bufs[off[0]].slice(start, start + bytes)\n }\n\n if (!copy) {\n // a slice, we need something to copy in to\n dst = Buffer.allocUnsafe(len)\n }\n\n for (let i = off[0]; i < this._bufs.length; i++) {\n const l = this._bufs[i].length - start\n\n if (bytes > l) {\n this._bufs[i].copy(dst, bufoff, start)\n bufoff += l\n } else {\n this._bufs[i].copy(dst, bufoff, start, start + bytes)\n bufoff += l\n break\n }\n\n bytes -= l\n\n if (start) {\n start = 0\n }\n }\n\n // safeguard so that we don't return uninitialized memory\n if (dst.length > bufoff) return dst.slice(0, bufoff)\n\n return dst\n}\n\nBufferList.prototype.shallowSlice = function shallowSlice (start, end) {\n start = start || 0\n end = typeof end !== 'number' ? this.length : end\n\n if (start < 0) {\n start += this.length\n }\n\n if (end < 0) {\n end += this.length\n }\n\n if (start === end) {\n return this._new()\n }\n\n const startOffset = this._offset(start)\n const endOffset = this._offset(end)\n const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)\n\n if (endOffset[1] === 0) {\n buffers.pop()\n } else {\n buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1])\n }\n\n if (startOffset[1] !== 0) {\n buffers[0] = buffers[0].slice(startOffset[1])\n }\n\n return this._new(buffers)\n}\n\nBufferList.prototype.toString = function toString (encoding, start, end) {\n return this.slice(start, end).toString(encoding)\n}\n\nBufferList.prototype.consume = function consume (bytes) {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) return this\n\n while (this._bufs.length) {\n if (bytes >= this._bufs[0].length) {\n bytes -= this._bufs[0].length\n this.length -= this._bufs[0].length\n this._bufs.shift()\n } else {\n this._bufs[0] = this._bufs[0].slice(bytes)\n this.length -= bytes\n break\n }\n }\n\n return this\n}\n\nBufferList.prototype.duplicate = function duplicate () {\n const copy = this._new()\n\n for (let i = 0; i < this._bufs.length; i++) {\n copy.append(this._bufs[i])\n }\n\n return copy\n}\n\nBufferList.prototype.append = function append (buf) {\n if (buf == null) {\n return this\n }\n\n if (buf.buffer) {\n // append a view of the underlying ArrayBuffer\n this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength))\n } else if (Array.isArray(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.append(buf[i])\n }\n } else if (this._isBufferList(buf)) {\n // unwrap argument into individual BufferLists\n for (let i = 0; i < buf._bufs.length; i++) {\n this.append(buf._bufs[i])\n }\n } else {\n // coerce number arguments to strings, since Buffer(number) does\n // uninitialized memory allocation\n if (typeof buf === 'number') {\n buf = buf.toString()\n }\n\n this._appendBuffer(Buffer.from(buf))\n }\n\n return this\n}\n\nBufferList.prototype._appendBuffer = function appendBuffer (buf) {\n this._bufs.push(buf)\n this.length += buf.length\n}\n\nBufferList.prototype.indexOf = function (search, offset, encoding) {\n if (encoding === undefined && typeof offset === 'string') {\n encoding = offset\n offset = undefined\n }\n\n if (typeof search === 'function' || Array.isArray(search)) {\n throw new TypeError('The \"value\" argument must be one of type string, Buffer, BufferList, or Uint8Array.')\n } else if (typeof search === 'number') {\n search = Buffer.from([search])\n } else if (typeof search === 'string') {\n search = Buffer.from(search, encoding)\n } else if (this._isBufferList(search)) {\n search = search.slice()\n } else if (Array.isArray(search.buffer)) {\n search = Buffer.from(search.buffer, search.byteOffset, search.byteLength)\n } else if (!Buffer.isBuffer(search)) {\n search = Buffer.from(search)\n }\n\n offset = Number(offset || 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n const blOffset = this._offset(offset)\n let blIndex = blOffset[0] // index of which internal buffer we're working on\n let buffOffset = blOffset[1] // offset of the internal buffer we're working on\n\n // scan over each buffer\n for (; blIndex < this._bufs.length; blIndex++) {\n const buff = this._bufs[blIndex]\n\n while (buffOffset < buff.length) {\n const availableWindow = buff.length - buffOffset\n\n if (availableWindow >= search.length) {\n const nativeSearchResult = buff.indexOf(search, buffOffset)\n\n if (nativeSearchResult !== -1) {\n return this._reverseOffset([blIndex, nativeSearchResult])\n }\n\n buffOffset = buff.length - search.length + 1 // end of native search window\n } else {\n const revOffset = this._reverseOffset([blIndex, buffOffset])\n\n if (this._match(revOffset, search)) {\n return revOffset\n }\n\n buffOffset++\n }\n }\n\n buffOffset = 0\n }\n\n return -1\n}\n\nBufferList.prototype._match = function (offset, search) {\n if (this.length - offset < search.length) {\n return false\n }\n\n for (let searchOffset = 0; searchOffset < search.length; searchOffset++) {\n if (this.get(offset + searchOffset) !== search[searchOffset]) {\n return false\n }\n }\n return true\n}\n\n;(function () {\n const methods = {\n readDoubleBE: 8,\n readDoubleLE: 8,\n readFloatBE: 4,\n readFloatLE: 4,\n readInt32BE: 4,\n readInt32LE: 4,\n readUInt32BE: 4,\n readUInt32LE: 4,\n readInt16BE: 2,\n readInt16LE: 2,\n readUInt16BE: 2,\n readUInt16LE: 2,\n readInt8: 1,\n readUInt8: 1,\n readIntBE: null,\n readIntLE: null,\n readUIntBE: null,\n readUIntLE: null\n }\n\n for (const m in methods) {\n (function (m) {\n if (methods[m] === null) {\n BufferList.prototype[m] = function (offset, byteLength) {\n return this.slice(offset, offset + byteLength)[m](0, byteLength)\n }\n } else {\n BufferList.prototype[m] = function (offset = 0) {\n return this.slice(offset, offset + methods[m])[m](0)\n }\n }\n }(m))\n }\n}())\n\n// Used internally by the class and also as an indicator of this object being\n// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser\n// environment because there could be multiple different copies of the\n// BufferList class and some `BufferList`s might be `BufferList`s.\nBufferList.prototype._isBufferList = function _isBufferList (b) {\n return b instanceof BufferList || BufferList.isBufferList(b)\n}\n\nBufferList.isBufferList = function isBufferList (b) {\n return b != null && b[symbol]\n}\n\nmodule.exports = BufferList\n", "'use strict'\n\nconst DuplexStream = require('readable-stream').Duplex\nconst inherits = require('inherits')\nconst BufferList = require('./BufferList')\n\nfunction BufferListStream (callback) {\n if (!(this instanceof BufferListStream)) {\n return new BufferListStream(callback)\n }\n\n if (typeof callback === 'function') {\n this._callback = callback\n\n const piper = function piper (err) {\n if (this._callback) {\n this._callback(err)\n this._callback = null\n }\n }.bind(this)\n\n this.on('pipe', function onPipe (src) {\n src.on('error', piper)\n })\n this.on('unpipe', function onUnpipe (src) {\n src.removeListener('error', piper)\n })\n\n callback = null\n }\n\n BufferList._init.call(this, callback)\n DuplexStream.call(this)\n}\n\ninherits(BufferListStream, DuplexStream)\nObject.assign(BufferListStream.prototype, BufferList.prototype)\n\nBufferListStream.prototype._new = function _new (callback) {\n return new BufferListStream(callback)\n}\n\nBufferListStream.prototype._write = function _write (buf, encoding, callback) {\n this._appendBuffer(buf)\n\n if (typeof callback === 'function') {\n callback()\n }\n}\n\nBufferListStream.prototype._read = function _read (size) {\n if (!this.length) {\n return this.push(null)\n }\n\n size = Math.min(size, this.length)\n this.push(this.slice(0, size))\n this.consume(size)\n}\n\nBufferListStream.prototype.end = function end (chunk) {\n DuplexStream.prototype.end.call(this, chunk)\n\n if (this._callback) {\n this._callback(null, this.slice())\n this._callback = null\n }\n}\n\nBufferListStream.prototype._destroy = function _destroy (err, cb) {\n this._bufs.length = 0\n this.length = 0\n cb(err)\n}\n\nBufferListStream.prototype._isBufferList = function _isBufferList (b) {\n return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b)\n}\n\nBufferListStream.isBufferList = BufferList.isBufferList\n\nmodule.exports = BufferListStream\nmodule.exports.BufferListStream = BufferListStream\nmodule.exports.BufferList = BufferList\n", "var alloc = Buffer.alloc\n\nvar ZEROS = '0000000000000000000'\nvar SEVENS = '7777777777777777777'\nvar ZERO_OFFSET = '0'.charCodeAt(0)\nvar USTAR_MAGIC = Buffer.from('ustar\\x00', 'binary')\nvar USTAR_VER = Buffer.from('00', 'binary')\nvar GNU_MAGIC = Buffer.from('ustar\\x20', 'binary')\nvar GNU_VER = Buffer.from('\\x20\\x00', 'binary')\nvar MASK = parseInt('7777', 8)\nvar MAGIC_OFFSET = 257\nvar VERSION_OFFSET = 263\n\nvar clamp = function (index, len, defaultValue) {\n if (typeof index !== 'number') return defaultValue\n index = ~~index // Coerce to integer.\n if (index >= len) return len\n if (index >= 0) return index\n index += len\n if (index >= 0) return index\n return 0\n}\n\nvar toType = function (flag) {\n switch (flag) {\n case 0:\n return 'file'\n case 1:\n return 'link'\n case 2:\n return 'symlink'\n case 3:\n return 'character-device'\n case 4:\n return 'block-device'\n case 5:\n return 'directory'\n case 6:\n return 'fifo'\n case 7:\n return 'contiguous-file'\n case 72:\n return 'pax-header'\n case 55:\n return 'pax-global-header'\n case 27:\n return 'gnu-long-link-path'\n case 28:\n case 30:\n return 'gnu-long-path'\n }\n\n return null\n}\n\nvar toTypeflag = function (flag) {\n switch (flag) {\n case 'file':\n return 0\n case 'link':\n return 1\n case 'symlink':\n return 2\n case 'character-device':\n return 3\n case 'block-device':\n return 4\n case 'directory':\n return 5\n case 'fifo':\n return 6\n case 'contiguous-file':\n return 7\n case 'pax-header':\n return 72\n }\n\n return 0\n}\n\nvar indexOf = function (block, num, offset, end) {\n for (; offset < end; offset++) {\n if (block[offset] === num) return offset\n }\n return end\n}\n\nvar cksum = function (block) {\n var sum = 8 * 32\n for (var i = 0; i < 148; i++) sum += block[i]\n for (var j = 156; j < 512; j++) sum += block[j]\n return sum\n}\n\nvar encodeOct = function (val, n) {\n val = val.toString(8)\n if (val.length > n) return SEVENS.slice(0, n) + ' '\n else return ZEROS.slice(0, n - val.length) + val + ' '\n}\n\n/* Copied from the node-tar repo and modified to meet\n * tar-stream coding standard.\n *\n * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349\n */\nfunction parse256 (buf) {\n // first byte MUST be either 80 or FF\n // 80 for positive, FF for 2's comp\n var positive\n if (buf[0] === 0x80) positive = true\n else if (buf[0] === 0xFF) positive = false\n else return null\n\n // build up a base-256 tuple from the least sig to the highest\n var tuple = []\n for (var i = buf.length - 1; i > 0; i--) {\n var byte = buf[i]\n if (positive) tuple.push(byte)\n else tuple.push(0xFF - byte)\n }\n\n var sum = 0\n var l = tuple.length\n for (i = 0; i < l; i++) {\n sum += tuple[i] * Math.pow(256, i)\n }\n\n return positive ? sum : -1 * sum\n}\n\nvar decodeOct = function (val, offset, length) {\n val = val.slice(offset, offset + length)\n offset = 0\n\n // If prefixed with 0x80 then parse as a base-256 integer\n if (val[offset] & 0x80) {\n return parse256(val)\n } else {\n // Older versions of tar can prefix with spaces\n while (offset < val.length && val[offset] === 32) offset++\n var end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length)\n while (offset < end && val[offset] === 0) offset++\n if (end === offset) return 0\n return parseInt(val.slice(offset, end).toString(), 8)\n }\n}\n\nvar decodeStr = function (val, offset, length, encoding) {\n return val.slice(offset, indexOf(val, 0, offset, offset + length)).toString(encoding)\n}\n\nvar addLength = function (str) {\n var len = Buffer.byteLength(str)\n var digits = Math.floor(Math.log(len) / Math.log(10)) + 1\n if (len + digits >= Math.pow(10, digits)) digits++\n\n return (len + digits) + str\n}\n\nexports.decodeLongPath = function (buf, encoding) {\n return decodeStr(buf, 0, buf.length, encoding)\n}\n\nexports.encodePax = function (opts) { // TODO: encode more stuff in pax\n var result = ''\n if (opts.name) result += addLength(' path=' + opts.name + '\\n')\n if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\\n')\n var pax = opts.pax\n if (pax) {\n for (var key in pax) {\n result += addLength(' ' + key + '=' + pax[key] + '\\n')\n }\n }\n return Buffer.from(result)\n}\n\nexports.decodePax = function (buf) {\n var result = {}\n\n while (buf.length) {\n var i = 0\n while (i < buf.length && buf[i] !== 32) i++\n var len = parseInt(buf.slice(0, i).toString(), 10)\n if (!len) return result\n\n var b = buf.slice(i + 1, len - 1).toString()\n var keyIndex = b.indexOf('=')\n if (keyIndex === -1) return result\n result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1)\n\n buf = buf.slice(len)\n }\n\n return result\n}\n\nexports.encode = function (opts) {\n var buf = alloc(512)\n var name = opts.name\n var prefix = ''\n\n if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/'\n if (Buffer.byteLength(name) !== name.length) return null // utf-8\n\n while (Buffer.byteLength(name) > 100) {\n var i = name.indexOf('/')\n if (i === -1) return null\n prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i)\n name = name.slice(i + 1)\n }\n\n if (Buffer.byteLength(name) > 100 || Buffer.byteLength(prefix) > 155) return null\n if (opts.linkname && Buffer.byteLength(opts.linkname) > 100) return null\n\n buf.write(name)\n buf.write(encodeOct(opts.mode & MASK, 6), 100)\n buf.write(encodeOct(opts.uid, 6), 108)\n buf.write(encodeOct(opts.gid, 6), 116)\n buf.write(encodeOct(opts.size, 11), 124)\n buf.write(encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136)\n\n buf[156] = ZERO_OFFSET + toTypeflag(opts.type)\n\n if (opts.linkname) buf.write(opts.linkname, 157)\n\n USTAR_MAGIC.copy(buf, MAGIC_OFFSET)\n USTAR_VER.copy(buf, VERSION_OFFSET)\n if (opts.uname) buf.write(opts.uname, 265)\n if (opts.gname) buf.write(opts.gname, 297)\n buf.write(encodeOct(opts.devmajor || 0, 6), 329)\n buf.write(encodeOct(opts.devminor || 0, 6), 337)\n\n if (prefix) buf.write(prefix, 345)\n\n buf.write(encodeOct(cksum(buf), 6), 148)\n\n return buf\n}\n\nexports.decode = function (buf, filenameEncoding, allowUnknownFormat) {\n var typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET\n\n var name = decodeStr(buf, 0, 100, filenameEncoding)\n var mode = decodeOct(buf, 100, 8)\n var uid = decodeOct(buf, 108, 8)\n var gid = decodeOct(buf, 116, 8)\n var size = decodeOct(buf, 124, 12)\n var mtime = decodeOct(buf, 136, 12)\n var type = toType(typeflag)\n var linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding)\n var uname = decodeStr(buf, 265, 32)\n var gname = decodeStr(buf, 297, 32)\n var devmajor = decodeOct(buf, 329, 8)\n var devminor = decodeOct(buf, 337, 8)\n\n var c = cksum(buf)\n\n // checksum is still initial value if header was null.\n if (c === 8 * 32) return null\n\n // valid checksum\n if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?')\n\n if (USTAR_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0) {\n // ustar (posix) format.\n // prepend prefix, if present.\n if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + '/' + name\n } else if (GNU_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0 &&\n GNU_VER.compare(buf, VERSION_OFFSET, VERSION_OFFSET + 2) === 0) {\n // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and\n // multi-volume tarballs.\n } else {\n if (!allowUnknownFormat) {\n throw new Error('Invalid tar header: unknown format.')\n }\n }\n\n // to support old tar versions that use trailing / to indicate dirs\n if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5\n\n return {\n name,\n mode,\n uid,\n gid,\n size,\n mtime: new Date(1000 * mtime),\n type,\n linkname,\n uname,\n gname,\n devmajor,\n devminor\n }\n}\n", "module.exports = require('stream');\n", "'use strict';\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nvar _require = require('buffer'),\n Buffer = _require.Buffer;\n\nvar _require2 = require('util'),\n inspect = _require2.inspect;\n\nvar custom = inspect && inspect.custom || 'inspect';\n\nfunction copyBuffer(src, target, offset) {\n Buffer.prototype.copy.call(src, target, offset);\n}\n\nmodule.exports =\n/*#__PURE__*/\nfunction () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n _createClass(BufferList, [{\n key: \"push\",\n value: function push(v) {\n var entry = {\n data: v,\n next: null\n };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n }\n }, {\n key: \"unshift\",\n value: function unshift(v) {\n var entry = {\n data: v,\n next: this.head\n };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n }\n }, {\n key: \"shift\",\n value: function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n }\n }, {\n key: \"clear\",\n value: function clear() {\n this.head = this.tail = null;\n this.length = 0;\n }\n }, {\n key: \"join\",\n value: function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n\n while (p = p.next) {\n ret += s + p.data;\n }\n\n return ret;\n }\n }, {\n key: \"concat\",\n value: function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n\n return ret;\n } // Consumes a specified amount of bytes or characters from the buffered data.\n\n }, {\n key: \"consume\",\n value: function consume(n, hasStrings) {\n var ret;\n\n if (n < this.head.data.length) {\n // `slice` is the same for buffers and strings.\n ret = this.head.data.slice(0, n);\n this.head.data = this.head.data.slice(n);\n } else if (n === this.head.data.length) {\n // First chunk is a perfect match.\n ret = this.shift();\n } else {\n // Result spans more than one buffer.\n ret = hasStrings ? this._getString(n) : this._getBuffer(n);\n }\n\n return ret;\n }\n }, {\n key: \"first\",\n value: function first() {\n return this.head.data;\n } // Consumes a specified amount of characters from the buffered data.\n\n }, {\n key: \"_getString\",\n value: function _getString(n) {\n var p = this.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = str.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Consumes a specified amount of bytes from the buffered data.\n\n }, {\n key: \"_getBuffer\",\n value: function _getBuffer(n) {\n var ret = Buffer.allocUnsafe(n);\n var p = this.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = buf.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Make sure the linked list only shows the minimal necessary information.\n\n }, {\n key: custom,\n value: function value(_, options) {\n return inspect(this, _objectSpread({}, options, {\n // Only inspect one level.\n depth: 0,\n // It should not recurse.\n customInspect: false\n }));\n }\n }]);\n\n return BufferList;\n}();", "'use strict'; // undocumented cb() API, needed for core, not for public API\n\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n process.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n process.nextTick(emitErrorNT, this, err);\n }\n }\n\n return this;\n } // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n } // if this is a duplex stream mark the writable part as destroyed as well\n\n\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n } else if (cb) {\n process.nextTick(emitCloseNT, _this);\n cb(err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n });\n\n return this;\n}\n\nfunction emitErrorAndCloseNT(self, err) {\n emitErrorNT(self, err);\n emitCloseNT(self);\n}\n\nfunction emitCloseNT(self) {\n if (self._writableState && !self._writableState.emitClose) return;\n if (self._readableState && !self._readableState.emitClose) return;\n self.emit('close');\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nfunction errorOrDestroy(stream, err) {\n // We have tests that rely on errors being emitted\n // in the same tick, so changing this is semver major.\n // For now when you opt-in to autoDestroy we allow\n // the error to be emitted nextTick. In a future\n // semver major update we should change the default to this.\n var rState = stream._readableState;\n var wState = stream._writableState;\n if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy,\n errorOrDestroy: errorOrDestroy\n};", "'use strict';\n\nconst codes = {};\n\nfunction createErrorType(code, message, Base) {\n if (!Base) {\n Base = Error\n }\n\n function getMessage (arg1, arg2, arg3) {\n if (typeof message === 'string') {\n return message\n } else {\n return message(arg1, arg2, arg3)\n }\n }\n\n class NodeError extends Base {\n constructor (arg1, arg2, arg3) {\n super(getMessage(arg1, arg2, arg3));\n }\n }\n\n NodeError.prototype.name = Base.name;\n NodeError.prototype.code = code;\n\n codes[code] = NodeError;\n}\n\n// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js\nfunction oneOf(expected, thing) {\n if (Array.isArray(expected)) {\n const len = expected.length;\n expected = expected.map((i) => String(i));\n if (len > 2) {\n return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` +\n expected[len - 1];\n } else if (len === 2) {\n return `one of ${thing} ${expected[0]} or ${expected[1]}`;\n } else {\n return `of ${thing} ${expected[0]}`;\n }\n } else {\n return `of ${thing} ${String(expected)}`;\n }\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith\nfunction startsWith(str, search, pos) {\n\treturn str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\nfunction endsWith(str, search, this_len) {\n\tif (this_len === undefined || this_len > str.length) {\n\t\tthis_len = str.length;\n\t}\n\treturn str.substring(this_len - search.length, this_len) === search;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\nfunction includes(str, search, start) {\n if (typeof start !== 'number') {\n start = 0;\n }\n\n if (start + search.length > str.length) {\n return false;\n } else {\n return str.indexOf(search, start) !== -1;\n }\n}\n\ncreateErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {\n return 'The value \"' + value + '\" is invalid for option \"' + name + '\"'\n}, TypeError);\ncreateErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {\n // determiner: 'must be' or 'must not be'\n let determiner;\n if (typeof expected === 'string' && startsWith(expected, 'not ')) {\n determiner = 'must not be';\n expected = expected.replace(/^not /, '');\n } else {\n determiner = 'must be';\n }\n\n let msg;\n if (endsWith(name, ' argument')) {\n // For cases like 'first argument'\n msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;\n } else {\n const type = includes(name, '.') ? 'property' : 'argument';\n msg = `The \"${name}\" ${type} ${determiner} ${oneOf(expected, 'type')}`;\n }\n\n msg += `. Received type ${typeof actual}`;\n return msg;\n}, TypeError);\ncreateErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');\ncreateErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {\n return 'The ' + name + ' method is not implemented'\n});\ncreateErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');\ncreateErrorType('ERR_STREAM_DESTROYED', function (name) {\n return 'Cannot call ' + name + ' after a stream was destroyed';\n});\ncreateErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');\ncreateErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');\ncreateErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');\ncreateErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);\ncreateErrorType('ERR_UNKNOWN_ENCODING', function (arg) {\n return 'Unknown encoding: ' + arg\n}, TypeError);\ncreateErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');\n\nmodule.exports.codes = codes;\n", "'use strict';\n\nvar ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;\n\nfunction highWaterMarkFrom(options, isDuplex, duplexKey) {\n return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;\n}\n\nfunction getHighWaterMark(state, options, duplexKey, isDuplex) {\n var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);\n\n if (hwm != null) {\n if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {\n var name = isDuplex ? duplexKey : 'highWaterMark';\n throw new ERR_INVALID_OPT_VALUE(name, hwm);\n }\n\n return Math.floor(hwm);\n } // Default value\n\n\n return state.objectMode ? 16 : 16 * 1024;\n}\n\nmodule.exports = {\n getHighWaterMark: getHighWaterMark\n};", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n'use strict';\n\nmodule.exports = Writable;\n/* <replacement> */\n\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n} // It seems a linked list but it is not\n// there will be only 2 of these for each stream\n\n\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* </replacement> */\n\n/*<replacement>*/\n\n\nvar Duplex;\n/*</replacement>*/\n\nWritable.WritableState = WritableState;\n/*<replacement>*/\n\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/*</replacement>*/\n\n/*<replacement>*/\n\nvar Stream = require('./internal/streams/stream');\n/*</replacement>*/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,\n ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,\n ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,\n ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\n\nrequire('inherits')(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream,\n // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n\n this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called\n\n this.finalCalled = false; // drain event flag.\n\n this.needDrain = false; // at the start of calling end()\n\n this.ending = false; // when end() has been called, and returned\n\n this.ended = false; // when 'finish' is emitted\n\n this.finished = false; // has it been destroyed\n\n this.destroyed = false; // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n\n this.length = 0; // a flag to see when we're in the middle of a write.\n\n this.writing = false; // when true all writes will be buffered until .uncork() call\n\n this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n\n this.sync = true; // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n\n this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)\n\n this.onwrite = function (er) {\n onwrite(stream, er);\n }; // the callback that the user supplies to write(chunk,encoding,cb)\n\n\n this.writecb = null; // the amount that is being written when _write is called.\n\n this.writelen = 0;\n this.bufferedRequest = null;\n this.lastBufferedRequest = null; // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n\n this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n\n this.prefinished = false; // True if the error was already emitted and should not be thrown again\n\n this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')\n\n this.autoDestroy = !!options.autoDestroy; // count buffered requests\n\n this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n\n while (current) {\n out.push(current);\n current = current.next;\n }\n\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function writableStateBufferGetter() {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})(); // Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\n\n\nvar realHasInstance;\n\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function value(object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function realHasInstance(object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the WritableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);\n this._writableState = new WritableState(options, this, isDuplex); // legacy.\n\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n if (typeof options.writev === 'function') this._writev = options.writev;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n} // Otherwise people can pipe Writable streams, which is just wrong.\n\n\nWritable.prototype.pipe = function () {\n errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb\n\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n} // Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\n\n\nfunction validChunk(stream, state, chunk, cb) {\n var er;\n\n if (chunk === null) {\n er = new ERR_STREAM_NULL_VALUES();\n } else if (typeof chunk !== 'string' && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);\n }\n\n if (er) {\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n return false;\n }\n\n return true;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n if (typeof cb !== 'function') cb = nop;\n if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n return ret;\n};\n\nWritable.prototype.cork = function () {\n this._writableState.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n}); // if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\n\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n\n var len = state.objectMode ? 1 : chunk.length;\n state.length += len;\n var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.\n\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n process.nextTick(cb, er); // this can emit finish, and it will always happen\n // after error\n\n process.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er); // this can emit finish, but finish must\n // always follow error\n\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();\n onwriteStateUpdate(state);\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state) || stream.destroyed;\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n process.nextTick(afterWrite, stream, state, finished, cb);\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n} // Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\n\n\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n} // if there's something in the buffer waiting, then process it\n\n\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n var count = 0;\n var allBuffers = true;\n\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n\n buffer.allBuffers = allBuffers;\n doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n\n state.pendingcb++;\n state.lastBufferedRequest = null;\n\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks\n\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n } // ignore unnecessary end() calls.\n\n\n if (!state.ending) endWritable(this, state, cb);\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n});\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\n\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n\n if (err) {\n errorOrDestroy(stream, err);\n }\n\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\n\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function' && !state.destroyed) {\n state.pendingcb++;\n state.finalCalled = true;\n process.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n\n if (need) {\n prefinish(stream, state);\n\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the readable side is ready for autoDestroy as well\n var rState = stream._readableState;\n\n if (!rState || rState.autoDestroy && rState.endEmitted) {\n stream.destroy();\n }\n }\n }\n }\n\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n\n if (cb) {\n if (state.finished) process.nextTick(cb);else stream.once('finish', cb);\n }\n\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n } // reuse the free corkReq.\n\n\n state.corkedRequestsFree.next = corkReq;\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._writableState === undefined) {\n return false;\n }\n\n return this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._writableState.destroyed = value;\n }\n});\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\n\nWritable.prototype._destroy = function (err, cb) {\n cb(err);\n};", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n'use strict';\n/*<replacement>*/\n\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n\n for (var key in obj) {\n keys.push(key);\n }\n\n return keys;\n};\n/*</replacement>*/\n\n\nmodule.exports = Duplex;\n\nvar Readable = require('./_stream_readable');\n\nvar Writable = require('./_stream_writable');\n\nrequire('inherits')(Duplex, Readable);\n\n{\n // Allow the keys array to be GC'ed.\n var keys = objectKeys(Writable.prototype);\n\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n Readable.call(this, options);\n Writable.call(this, options);\n this.allowHalfOpen = true;\n\n if (options) {\n if (options.readable === false) this.readable = false;\n if (options.writable === false) this.writable = false;\n\n if (options.allowHalfOpen === false) {\n this.allowHalfOpen = false;\n this.once('end', onend);\n }\n }\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n}); // the no-half-open enforcer\n\nfunction onend() {\n // If the writable side ended, then we're ok.\n if (this._writableState.ended) return; // no more data can be written.\n // But allow more writes to happen in this tick.\n\n process.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});", "// Ported from https://github.com/mafintosh/end-of-stream with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n callback.apply(this, args);\n };\n}\n\nfunction noop() {}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction eos(stream, opts, callback) {\n if (typeof opts === 'function') return eos(stream, null, opts);\n if (!opts) opts = {};\n callback = once(callback || noop);\n var readable = opts.readable || opts.readable !== false && stream.readable;\n var writable = opts.writable || opts.writable !== false && stream.writable;\n\n var onlegacyfinish = function onlegacyfinish() {\n if (!stream.writable) onfinish();\n };\n\n var writableEnded = stream._writableState && stream._writableState.finished;\n\n var onfinish = function onfinish() {\n writable = false;\n writableEnded = true;\n if (!readable) callback.call(stream);\n };\n\n var readableEnded = stream._readableState && stream._readableState.endEmitted;\n\n var onend = function onend() {\n readable = false;\n readableEnded = true;\n if (!writable) callback.call(stream);\n };\n\n var onerror = function onerror(err) {\n callback.call(stream, err);\n };\n\n var onclose = function onclose() {\n var err;\n\n if (readable && !readableEnded) {\n if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n\n if (writable && !writableEnded) {\n if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n };\n\n var onrequest = function onrequest() {\n stream.req.on('finish', onfinish);\n };\n\n if (isRequest(stream)) {\n stream.on('complete', onfinish);\n stream.on('abort', onclose);\n if (stream.req) onrequest();else stream.on('request', onrequest);\n } else if (writable && !stream._writableState) {\n // legacy streams\n stream.on('end', onlegacyfinish);\n stream.on('close', onlegacyfinish);\n }\n\n stream.on('end', onend);\n stream.on('finish', onfinish);\n if (opts.error !== false) stream.on('error', onerror);\n stream.on('close', onclose);\n return function () {\n stream.removeListener('complete', onfinish);\n stream.removeListener('abort', onclose);\n stream.removeListener('request', onrequest);\n if (stream.req) stream.req.removeListener('finish', onfinish);\n stream.removeListener('end', onlegacyfinish);\n stream.removeListener('close', onlegacyfinish);\n stream.removeListener('finish', onfinish);\n stream.removeListener('end', onend);\n stream.removeListener('error', onerror);\n stream.removeListener('close', onclose);\n };\n}\n\nmodule.exports = eos;", "'use strict';\n\nvar _Object$setPrototypeO;\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar finished = require('./end-of-stream');\n\nvar kLastResolve = Symbol('lastResolve');\nvar kLastReject = Symbol('lastReject');\nvar kError = Symbol('error');\nvar kEnded = Symbol('ended');\nvar kLastPromise = Symbol('lastPromise');\nvar kHandlePromise = Symbol('handlePromise');\nvar kStream = Symbol('stream');\n\nfunction createIterResult(value, done) {\n return {\n value: value,\n done: done\n };\n}\n\nfunction readAndResolve(iter) {\n var resolve = iter[kLastResolve];\n\n if (resolve !== null) {\n var data = iter[kStream].read(); // we defer if data is null\n // we can be expecting either 'end' or\n // 'error'\n\n if (data !== null) {\n iter[kLastPromise] = null;\n iter[kLastResolve] = null;\n iter[kLastReject] = null;\n resolve(createIterResult(data, false));\n }\n }\n}\n\nfunction onReadable(iter) {\n // we wait for the next tick, because it might\n // emit an error with process.nextTick\n process.nextTick(readAndResolve, iter);\n}\n\nfunction wrapForNext(lastPromise, iter) {\n return function (resolve, reject) {\n lastPromise.then(function () {\n if (iter[kEnded]) {\n resolve(createIterResult(undefined, true));\n return;\n }\n\n iter[kHandlePromise](resolve, reject);\n }, reject);\n };\n}\n\nvar AsyncIteratorPrototype = Object.getPrototypeOf(function () {});\nvar ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {\n get stream() {\n return this[kStream];\n },\n\n next: function next() {\n var _this = this;\n\n // if we have detected an error in the meanwhile\n // reject straight away\n var error = this[kError];\n\n if (error !== null) {\n return Promise.reject(error);\n }\n\n if (this[kEnded]) {\n return Promise.resolve(createIterResult(undefined, true));\n }\n\n if (this[kStream].destroyed) {\n // We need to defer via nextTick because if .destroy(err) is\n // called, the error will be emitted via nextTick, and\n // we cannot guarantee that there is no error lingering around\n // waiting to be emitted.\n return new Promise(function (resolve, reject) {\n process.nextTick(function () {\n if (_this[kError]) {\n reject(_this[kError]);\n } else {\n resolve(createIterResult(undefined, true));\n }\n });\n });\n } // if we have multiple next() calls\n // we will wait for the previous Promise to finish\n // this logic is optimized to support for await loops,\n // where next() is only called once at a time\n\n\n var lastPromise = this[kLastPromise];\n var promise;\n\n if (lastPromise) {\n promise = new Promise(wrapForNext(lastPromise, this));\n } else {\n // fast path needed to support multiple this.push()\n // without triggering the next() queue\n var data = this[kStream].read();\n\n if (data !== null) {\n return Promise.resolve(createIterResult(data, false));\n }\n\n promise = new Promise(this[kHandlePromise]);\n }\n\n this[kLastPromise] = promise;\n return promise;\n }\n}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {\n return this;\n}), _defineProperty(_Object$setPrototypeO, \"return\", function _return() {\n var _this2 = this;\n\n // destroy(err, cb) is a private API\n // we can guarantee we have that here, because we control the\n // Readable class this is attached to\n return new Promise(function (resolve, reject) {\n _this2[kStream].destroy(null, function (err) {\n if (err) {\n reject(err);\n return;\n }\n\n resolve(createIterResult(undefined, true));\n });\n });\n}), _Object$setPrototypeO), AsyncIteratorPrototype);\n\nvar createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {\n var _Object$create;\n\n var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {\n value: stream,\n writable: true\n }), _defineProperty(_Object$create, kLastResolve, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kLastReject, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kError, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kEnded, {\n value: stream._readableState.endEmitted,\n writable: true\n }), _defineProperty(_Object$create, kHandlePromise, {\n value: function value(resolve, reject) {\n var data = iterator[kStream].read();\n\n if (data) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(data, false));\n } else {\n iterator[kLastResolve] = resolve;\n iterator[kLastReject] = reject;\n }\n },\n writable: true\n }), _Object$create));\n iterator[kLastPromise] = null;\n finished(stream, function (err) {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise\n // returned by next() and store the error\n\n if (reject !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n reject(err);\n }\n\n iterator[kError] = err;\n return;\n }\n\n var resolve = iterator[kLastResolve];\n\n if (resolve !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(undefined, true));\n }\n\n iterator[kEnded] = true;\n });\n stream.on('readable', onReadable.bind(null, iterator));\n return iterator;\n};\n\nmodule.exports = createReadableStreamAsyncIterator;", "'use strict';\n\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }\n\nfunction _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err); } _next(undefined); }); }; }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE;\n\nfunction from(Readable, iterable, opts) {\n var iterator;\n\n if (iterable && typeof iterable.next === 'function') {\n iterator = iterable;\n } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable);\n\n var readable = new Readable(_objectSpread({\n objectMode: true\n }, opts)); // Reading boolean to protect against _read\n // being called before last iteration completion.\n\n var reading = false;\n\n readable._read = function () {\n if (!reading) {\n reading = true;\n next();\n }\n };\n\n function next() {\n return _next2.apply(this, arguments);\n }\n\n function _next2() {\n _next2 = _asyncToGenerator(function* () {\n try {\n var _ref = yield iterator.next(),\n value = _ref.value,\n done = _ref.done;\n\n if (done) {\n readable.push(null);\n } else if (readable.push((yield value))) {\n next();\n } else {\n reading = false;\n }\n } catch (err) {\n readable.destroy(err);\n }\n });\n return _next2.apply(this, arguments);\n }\n\n return readable;\n}\n\nmodule.exports = from;", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n'use strict';\n\nmodule.exports = Readable;\n/*<replacement>*/\n\nvar Duplex;\n/*</replacement>*/\n\nReadable.ReadableState = ReadableState;\n/*<replacement>*/\n\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function EElistenerCount(emitter, type) {\n return emitter.listeners(type).length;\n};\n/*</replacement>*/\n\n/*<replacement>*/\n\n\nvar Stream = require('./internal/streams/stream');\n/*</replacement>*/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n/*<replacement>*/\n\n\nvar debugUtil = require('util');\n\nvar debug;\n\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function debug() {};\n}\n/*</replacement>*/\n\n\nvar BufferList = require('./internal/streams/buffer_list');\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.\n\n\nvar StringDecoder;\nvar createReadableStreamAsyncIterator;\nvar from;\n\nrequire('inherits')(Readable, Stream);\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n\n this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n\n this.sync = true; // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n this.paused = true; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')\n\n this.autoDestroy = !!options.autoDestroy; // has it been destroyed\n\n this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s\n\n this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled\n\n this.readingMore = false;\n this.decoder = null;\n this.encoding = null;\n\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside\n // the ReadableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n this._readableState = new ReadableState(options, this, isDuplex); // legacy\n\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n }\n});\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\n\nReadable.prototype._destroy = function (err, cb) {\n cb(err);\n}; // Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\n\n\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n}; // Unshift should *always* be something directly out of read()\n\n\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n debug('readableAddChunk', chunk);\n var state = stream._readableState;\n\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n\n if (er) {\n errorOrDestroy(stream, er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());\n } else if (state.destroyed) {\n return false;\n } else {\n state.reading = false;\n\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n maybeReadMore(stream, state);\n }\n } // We can push more data if we are below the highWaterMark.\n // Also, if we have no data yet, we can stand some more bytes.\n // This is to work around cases where hwm=0, such as the repl.\n\n\n return !state.ended && (state.length < state.highWaterMark || state.length === 0);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n state.awaitDrain = 0;\n stream.emit('data', chunk);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n if (state.needReadable) emitReadable(stream);\n }\n\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);\n }\n\n return er;\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n}; // backwards compatibility.\n\n\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n var decoder = new StringDecoder(enc);\n this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8\n\n this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:\n\n var p = this._readableState.buffer.head;\n var content = '';\n\n while (p !== null) {\n content += decoder.write(p.data);\n p = p.next;\n }\n\n this._readableState.buffer.clear();\n\n if (content !== '') this._readableState.buffer.push(content);\n this._readableState.length = content.length;\n return this;\n}; // Don't raise the hwm > 1GB\n\n\nvar MAX_HWM = 0x40000000;\n\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n\n return n;\n} // This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\n\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n } // If we're asking for more than the current hwm, then raise the hwm.\n\n\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n; // Don't have enough\n\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n\n return state.length;\n} // you can override either this method, or the async _read(n) below.\n\n\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n\n if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.\n\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n } // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n // if we need a readable event, then we need to do some reading.\n\n\n var doRead = state.needReadable;\n debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some\n\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n } // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n\n\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true; // if the length is currently zero, then we *need* a readable event.\n\n if (state.length === 0) state.needReadable = true; // call internal read method\n\n this._read(state.highWaterMark);\n\n state.sync = false; // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = state.length <= state.highWaterMark;\n n = 0;\n } else {\n state.length -= n;\n state.awaitDrain = 0;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.\n\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n debug('onEofChunk');\n if (state.ended) return;\n\n if (state.decoder) {\n var chunk = state.decoder.end();\n\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n\n state.ended = true;\n\n if (state.sync) {\n // if we are sync, wait until next tick to emit the data.\n // Otherwise we risk emitting data in the flow()\n // the readable code triggers during a read() call\n emitReadable(stream);\n } else {\n // emit 'readable' now to make sure it gets picked up.\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n state.emittedReadable = true;\n emitReadable_(stream);\n }\n }\n} // Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\n\n\nfunction emitReadable(stream) {\n var state = stream._readableState;\n debug('emitReadable', state.needReadable, state.emittedReadable);\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n process.nextTick(emitReadable_, stream);\n }\n}\n\nfunction emitReadable_(stream) {\n var state = stream._readableState;\n debug('emitReadable_', state.destroyed, state.length, state.ended);\n\n if (!state.destroyed && (state.length || state.ended)) {\n stream.emit('readable');\n state.emittedReadable = false;\n } // The stream needs another readable event if\n // 1. It is not flowing, as the flow mechanism will take\n // care of it.\n // 2. It is not ended.\n // 3. It is below the highWaterMark, so we can schedule\n // another readable later.\n\n\n state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;\n flow(stream);\n} // at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\n\n\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n process.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n // Attempt to read more data if we should.\n //\n // The conditions for reading more data are (one of):\n // - Not enough data buffered (state.length < state.highWaterMark). The loop\n // is responsible for filling the buffer with enough data if such data\n // is available. If highWaterMark is 0 and we are not in the flowing mode\n // we should _not_ attempt to buffer any extra data. We'll get more data\n // when the stream consumer calls read() instead.\n // - No data in the buffer, and the stream is in flowing mode. In this mode\n // the loop below is responsible for ensuring read() is called. Failing to\n // call read here would abort the flow and there's no other mechanism for\n // continuing the flow if the stream consumer has just subscribed to the\n // 'data' event.\n //\n // In addition to the above conditions to keep reading data, the following\n // conditions prevent the data from being read:\n // - The stream has ended (state.ended).\n // - There is already a pending 'read' operation (state.reading). This is a\n // case where the the stream has called the implementation defined _read()\n // method, but they are processing the call asynchronously and have _not_\n // called push() with new data. In this case we skip performing more\n // read()s. The execution ends in this method again after the _read() ends\n // up calling push() with more data.\n while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {\n var len = state.length;\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length) // didn't get any data, stop spinning.\n break;\n }\n\n state.readingMore = false;\n} // abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\n\n\nReadable.prototype._read = function (n) {\n errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n\n default:\n state.pipes.push(dest);\n break;\n }\n\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);\n dest.on('unpipe', onunpipe);\n\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n } // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n\n\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n var cleanedUp = false;\n\n function cleanup() {\n debug('cleanup'); // cleanup event handlers once the pipe is broken\n\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n cleanedUp = true; // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n src.on('data', ondata);\n\n function ondata(chunk) {\n debug('ondata');\n var ret = dest.write(chunk);\n debug('dest.write', ret);\n\n if (ret === false) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n }\n\n src.pause();\n }\n } // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n\n\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);\n } // Make sure our error handler is attached before userland ones.\n\n\n prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.\n\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n\n dest.once('close', onclose);\n\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n } // tell the dest that it's being piped to\n\n\n dest.emit('pipe', src); // start the flow if it hasn't been started already.\n\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function pipeOnDrainFunctionResult() {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = {\n hasUnpiped: false\n }; // if we're not piping anywhere, then do nothing.\n\n if (state.pipesCount === 0) return this; // just one destination. most common case.\n\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n if (!dest) dest = state.pipes; // got a match.\n\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n } // slow case. multiple pipe destinations.\n\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, {\n hasUnpiped: false\n });\n }\n\n return this;\n } // try to find the right one.\n\n\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n dest.emit('unpipe', this, unpipeInfo);\n return this;\n}; // set up data events if they are asked for\n// Ensure readable listeners eventually get something\n\n\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n var state = this._readableState;\n\n if (ev === 'data') {\n // update readableListening so that resume() may be a no-op\n // a few lines down. This is needed to support once('readable').\n state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused\n\n if (state.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.flowing = false;\n state.emittedReadable = false;\n debug('on readable', state.length, state.reading);\n\n if (state.length) {\n emitReadable(this);\n } else if (!state.reading) {\n process.nextTick(nReadingNextTick, this);\n }\n }\n }\n\n return res;\n};\n\nReadable.prototype.addListener = Readable.prototype.on;\n\nReadable.prototype.removeListener = function (ev, fn) {\n var res = Stream.prototype.removeListener.call(this, ev, fn);\n\n if (ev === 'readable') {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nReadable.prototype.removeAllListeners = function (ev) {\n var res = Stream.prototype.removeAllListeners.apply(this, arguments);\n\n if (ev === 'readable' || ev === undefined) {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nfunction updateReadableListening(self) {\n var state = self._readableState;\n state.readableListening = self.listenerCount('readable') > 0;\n\n if (state.resumeScheduled && !state.paused) {\n // flowing needs to be set to true now, otherwise\n // the upcoming resume will not flow.\n state.flowing = true; // crude way to check if we should resume\n } else if (self.listenerCount('data') > 0) {\n self.resume();\n }\n}\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n} // pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\n\n\nReadable.prototype.resume = function () {\n var state = this._readableState;\n\n if (!state.flowing) {\n debug('resume'); // we flow only if there is no one listening\n // for readable, but we still have to call\n // resume()\n\n state.flowing = !state.readableListening;\n resume(this, state);\n }\n\n state.paused = false;\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n process.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n debug('resume', state.reading);\n\n if (!state.reading) {\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n\n if (this._readableState.flowing !== false) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n\n this._readableState.paused = true;\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n\n while (state.flowing && stream.read() !== null) {\n ;\n }\n} // wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\n\n\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n stream.on('end', function () {\n debug('wrapped end');\n\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode\n\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n\n if (!ret) {\n paused = true;\n stream.pause();\n }\n }); // proxy all the other methods.\n // important when wrapping filters and duplexes.\n\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function methodWrap(method) {\n return function methodWrapReturnFunction() {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n } // proxy certain important events.\n\n\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n } // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n\n\n this._read = function (n) {\n debug('wrapped _read', n);\n\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nif (typeof Symbol === 'function') {\n Readable.prototype[Symbol.asyncIterator] = function () {\n if (createReadableStreamAsyncIterator === undefined) {\n createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');\n }\n\n return createReadableStreamAsyncIterator(this);\n };\n}\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.highWaterMark;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState && this._readableState.buffer;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableFlowing', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.flowing;\n },\n set: function set(state) {\n if (this._readableState) {\n this._readableState.flowing = state;\n }\n }\n}); // exposed for testing purposes only.\n\nReadable._fromList = fromList;\nObject.defineProperty(Readable.prototype, 'readableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.length;\n }\n}); // Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = state.buffer.consume(n, state.decoder);\n }\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n debug('endReadable', state.endEmitted);\n\n if (!state.endEmitted) {\n state.ended = true;\n process.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.\n\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the writable side is ready for autoDestroy as well\n var wState = stream._writableState;\n\n if (!wState || wState.autoDestroy && wState.finished) {\n stream.destroy();\n }\n }\n }\n}\n\nif (typeof Symbol === 'function') {\n Readable.from = function (iterable, opts) {\n if (from === undefined) {\n from = require('./internal/streams/from');\n }\n\n return from(Readable, iterable, opts);\n };\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n\n return -1;\n}", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n'use strict';\n\nmodule.exports = Transform;\n\nvar _require$codes = require('../errors').codes,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,\n ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;\n\nvar Duplex = require('./_stream_duplex');\n\nrequire('inherits')(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n var cb = ts.writecb;\n\n if (cb === null) {\n return this.emit('error', new ERR_MULTIPLE_CALLBACK());\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n cb(er);\n var rs = this._readableState;\n rs.reading = false;\n\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n Duplex.call(this, options);\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n }; // start out asking for a readable event once data is transformed.\n\n this._readableState.needReadable = true; // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n if (typeof options.flush === 'function') this._flush = options.flush;\n } // When the writable side finishes, then flush out anything remaining.\n\n\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function' && !this._readableState.destroyed) {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n}; // This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\n\n\nTransform.prototype._transform = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n}; // Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\n\n\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && !ts.transforming) {\n ts.transforming = true;\n\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data); // TODO(BridgeAR): Write a test for these two error cases\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n\n if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();\n if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();\n return stream.push(null);\n}", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\nrequire('inherits')(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};", "// Ported from https://github.com/mafintosh/pump with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar eos;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n callback.apply(void 0, arguments);\n };\n}\n\nvar _require$codes = require('../../../errors').codes,\n ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;\n\nfunction noop(err) {\n // Rethrow the error if it exists to avoid swallowing it\n if (err) throw err;\n}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction destroyer(stream, reading, writing, callback) {\n callback = once(callback);\n var closed = false;\n stream.on('close', function () {\n closed = true;\n });\n if (eos === undefined) eos = require('./end-of-stream');\n eos(stream, {\n readable: reading,\n writable: writing\n }, function (err) {\n if (err) return callback(err);\n closed = true;\n callback();\n });\n var destroyed = false;\n return function (err) {\n if (closed) return;\n if (destroyed) return;\n destroyed = true; // request.destroy just do .end - .abort is what we want\n\n if (isRequest(stream)) return stream.abort();\n if (typeof stream.destroy === 'function') return stream.destroy();\n callback(err || new ERR_STREAM_DESTROYED('pipe'));\n };\n}\n\nfunction call(fn) {\n fn();\n}\n\nfunction pipe(from, to) {\n return from.pipe(to);\n}\n\nfunction popCallback(streams) {\n if (!streams.length) return noop;\n if (typeof streams[streams.length - 1] !== 'function') return noop;\n return streams.pop();\n}\n\nfunction pipeline() {\n for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {\n streams[_key] = arguments[_key];\n }\n\n var callback = popCallback(streams);\n if (Array.isArray(streams[0])) streams = streams[0];\n\n if (streams.length < 2) {\n throw new ERR_MISSING_ARGS('streams');\n }\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 return streams.reduce(pipe);\n}\n\nmodule.exports = pipeline;", "var Stream = require('stream');\nif (process.env.READABLE_STREAM === 'disable' && Stream) {\n module.exports = Stream.Readable;\n Object.assign(module.exports, Stream);\n module.exports.Stream = Stream;\n} else {\n exports = module.exports = require('./lib/_stream_readable.js');\n exports.Stream = Stream || exports;\n exports.Readable = exports;\n exports.Writable = require('./lib/_stream_writable.js');\n exports.Duplex = require('./lib/_stream_duplex.js');\n exports.Transform = require('./lib/_stream_transform.js');\n exports.PassThrough = require('./lib/_stream_passthrough.js');\n exports.finished = require('./lib/internal/streams/end-of-stream.js');\n exports.pipeline = require('./lib/internal/streams/pipeline.js');\n}\n", "var util = require('util')\nvar bl = require('bl')\nvar headers = require('./headers')\n\nvar Writable = require('readable-stream').Writable\nvar PassThrough = require('readable-stream').PassThrough\n\nvar noop = function () {}\n\nvar overflow = function (size) {\n size &= 511\n return size && 512 - size\n}\n\nvar emptyStream = function (self, offset) {\n var s = new Source(self, offset)\n s.end()\n return s\n}\n\nvar mixinPax = function (header, pax) {\n if (pax.path) header.name = pax.path\n if (pax.linkpath) header.linkname = pax.linkpath\n if (pax.size) header.size = parseInt(pax.size, 10)\n header.pax = pax\n return header\n}\n\nvar Source = function (self, offset) {\n this._parent = self\n this.offset = offset\n PassThrough.call(this, { autoDestroy: false })\n}\n\nutil.inherits(Source, PassThrough)\n\nSource.prototype.destroy = function (err) {\n this._parent.destroy(err)\n}\n\nvar Extract = function (opts) {\n if (!(this instanceof Extract)) return new Extract(opts)\n Writable.call(this, opts)\n\n opts = opts || {}\n\n this._offset = 0\n this._buffer = bl()\n this._missing = 0\n this._partial = false\n this._onparse = noop\n this._header = null\n this._stream = null\n this._overflow = null\n this._cb = null\n this._locked = false\n this._destroyed = false\n this._pax = null\n this._paxGlobal = null\n this._gnuLongPath = null\n this._gnuLongLinkPath = null\n\n var self = this\n var b = self._buffer\n\n var oncontinue = function () {\n self._continue()\n }\n\n var onunlock = function (err) {\n self._locked = false\n if (err) return self.destroy(err)\n if (!self._stream) oncontinue()\n }\n\n var onstreamend = function () {\n self._stream = null\n var drain = overflow(self._header.size)\n if (drain) self._parse(drain, ondrain)\n else self._parse(512, onheader)\n if (!self._locked) oncontinue()\n }\n\n var ondrain = function () {\n self._buffer.consume(overflow(self._header.size))\n self._parse(512, onheader)\n oncontinue()\n }\n\n var onpaxglobalheader = function () {\n var size = self._header.size\n self._paxGlobal = headers.decodePax(b.slice(0, size))\n b.consume(size)\n onstreamend()\n }\n\n var onpaxheader = function () {\n var size = self._header.size\n self._pax = headers.decodePax(b.slice(0, size))\n if (self._paxGlobal) self._pax = Object.assign({}, self._paxGlobal, self._pax)\n b.consume(size)\n onstreamend()\n }\n\n var ongnulongpath = function () {\n var size = self._header.size\n this._gnuLongPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding)\n b.consume(size)\n onstreamend()\n }\n\n var ongnulonglinkpath = function () {\n var size = self._header.size\n this._gnuLongLinkPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding)\n b.consume(size)\n onstreamend()\n }\n\n var onheader = function () {\n var offset = self._offset\n var header\n try {\n header = self._header = headers.decode(b.slice(0, 512), opts.filenameEncoding, opts.allowUnknownFormat)\n } catch (err) {\n self.emit('error', err)\n }\n b.consume(512)\n\n if (!header) {\n self._parse(512, onheader)\n oncontinue()\n return\n }\n if (header.type === 'gnu-long-path') {\n self._parse(header.size, ongnulongpath)\n oncontinue()\n return\n }\n if (header.type === 'gnu-long-link-path') {\n self._parse(header.size, ongnulonglinkpath)\n oncontinue()\n return\n }\n if (header.type === 'pax-global-header') {\n self._parse(header.size, onpaxglobalheader)\n oncontinue()\n return\n }\n if (header.type === 'pax-header') {\n self._parse(header.size, onpaxheader)\n oncontinue()\n return\n }\n\n if (self._gnuLongPath) {\n header.name = self._gnuLongPath\n self._gnuLongPath = null\n }\n\n if (self._gnuLongLinkPath) {\n header.linkname = self._gnuLongLinkPath\n self._gnuLongLinkPath = null\n }\n\n if (self._pax) {\n self._header = header = mixinPax(header, self._pax)\n self._pax = null\n }\n\n self._locked = true\n\n if (!header.size || header.type === 'directory') {\n self._parse(512, onheader)\n self.emit('entry', header, emptyStream(self, offset), onunlock)\n return\n }\n\n self._stream = new Source(self, offset)\n\n self.emit('entry', header, self._stream, onunlock)\n self._parse(header.size, onstreamend)\n oncontinue()\n }\n\n this._onheader = onheader\n this._parse(512, onheader)\n}\n\nutil.inherits(Extract, Writable)\n\nExtract.prototype.destroy = function (err) {\n if (this._destroyed) return\n this._destroyed = true\n\n if (err) this.emit('error', err)\n this.emit('close')\n if (this._stream) this._stream.emit('close')\n}\n\nExtract.prototype._parse = function (size, onparse) {\n if (this._destroyed) return\n this._offset += size\n this._missing = size\n if (onparse === this._onheader) this._partial = false\n this._onparse = onparse\n}\n\nExtract.prototype._continue = function () {\n if (this._destroyed) return\n var cb = this._cb\n this._cb = noop\n if (this._overflow) this._write(this._overflow, undefined, cb)\n else cb()\n}\n\nExtract.prototype._write = function (data, enc, cb) {\n if (this._destroyed) return\n\n var s = this._stream\n var b = this._buffer\n var missing = this._missing\n if (data.length) this._partial = true\n\n // we do not reach end-of-chunk now. just forward it\n\n if (data.length < missing) {\n this._missing -= data.length\n this._overflow = null\n if (s) return s.write(data, cb)\n b.append(data)\n return cb()\n }\n\n // end-of-chunk. the parser should call cb.\n\n this._cb = cb\n this._missing = 0\n\n var overflow = null\n if (data.length > missing) {\n overflow = data.slice(missing)\n data = data.slice(0, missing)\n }\n\n if (s) s.end(data)\n else b.append(data)\n\n this._overflow = overflow\n this._onparse()\n}\n\nExtract.prototype._final = function (cb) {\n if (this._partial) return this.destroy(new Error('Unexpected end of data'))\n cb()\n}\n\nmodule.exports = Extract\n", "module.exports = require('fs').constants || require('constants')\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 constants = require('fs-constants')\nvar eos = require('end-of-stream')\nvar inherits = require('inherits')\nvar alloc = Buffer.alloc\n\nvar Readable = require('readable-stream').Readable\nvar Writable = require('readable-stream').Writable\nvar StringDecoder = require('string_decoder').StringDecoder\n\nvar headers = require('./headers')\n\nvar DMODE = parseInt('755', 8)\nvar FMODE = parseInt('644', 8)\n\nvar END_OF_TAR = alloc(1024)\n\nvar noop = function () {}\n\nvar overflow = function (self, size) {\n size &= 511\n if (size) self.push(END_OF_TAR.slice(0, 512 - size))\n}\n\nfunction modeToType (mode) {\n switch (mode & constants.S_IFMT) {\n case constants.S_IFBLK: return 'block-device'\n case constants.S_IFCHR: return 'character-device'\n case constants.S_IFDIR: return 'directory'\n case constants.S_IFIFO: return 'fifo'\n case constants.S_IFLNK: return 'symlink'\n }\n\n return 'file'\n}\n\nvar Sink = function (to) {\n Writable.call(this)\n this.written = 0\n this._to = to\n this._destroyed = false\n}\n\ninherits(Sink, Writable)\n\nSink.prototype._write = function (data, enc, cb) {\n this.written += data.length\n if (this._to.push(data)) return cb()\n this._to._drain = cb\n}\n\nSink.prototype.destroy = function () {\n if (this._destroyed) return\n this._destroyed = true\n this.emit('close')\n}\n\nvar LinkSink = function () {\n Writable.call(this)\n this.linkname = ''\n this._decoder = new StringDecoder('utf-8')\n this._destroyed = false\n}\n\ninherits(LinkSink, Writable)\n\nLinkSink.prototype._write = function (data, enc, cb) {\n this.linkname += this._decoder.write(data)\n cb()\n}\n\nLinkSink.prototype.destroy = function () {\n if (this._destroyed) return\n this._destroyed = true\n this.emit('close')\n}\n\nvar Void = function () {\n Writable.call(this)\n this._destroyed = false\n}\n\ninherits(Void, Writable)\n\nVoid.prototype._write = function (data, enc, cb) {\n cb(new Error('No body allowed for this entry'))\n}\n\nVoid.prototype.destroy = function () {\n if (this._destroyed) return\n this._destroyed = true\n this.emit('close')\n}\n\nvar Pack = function (opts) {\n if (!(this instanceof Pack)) return new Pack(opts)\n Readable.call(this, opts)\n\n this._drain = noop\n this._finalized = false\n this._finalizing = false\n this._destroyed = false\n this._stream = null\n}\n\ninherits(Pack, Readable)\n\nPack.prototype.entry = function (header, buffer, callback) {\n if (this._stream) throw new Error('already piping an entry')\n if (this._finalized || this._destroyed) return\n\n if (typeof buffer === 'function') {\n callback = buffer\n buffer = null\n }\n\n if (!callback) callback = noop\n\n var self = this\n\n if (!header.size || header.type === 'symlink') header.size = 0\n if (!header.type) header.type = modeToType(header.mode)\n if (!header.mode) header.mode = header.type === 'directory' ? DMODE : FMODE\n if (!header.uid) header.uid = 0\n if (!header.gid) header.gid = 0\n if (!header.mtime) header.mtime = new Date()\n\n if (typeof buffer === 'string') buffer = Buffer.from(buffer)\n if (Buffer.isBuffer(buffer)) {\n header.size = buffer.length\n this._encode(header)\n var ok = this.push(buffer)\n overflow(self, header.size)\n if (ok) process.nextTick(callback)\n else this._drain = callback\n return new Void()\n }\n\n if (header.type === 'symlink' && !header.linkname) {\n var linkSink = new LinkSink()\n eos(linkSink, function (err) {\n if (err) { // stream was closed\n self.destroy()\n return callback(err)\n }\n\n header.linkname = linkSink.linkname\n self._encode(header)\n callback()\n })\n\n return linkSink\n }\n\n this._encode(header)\n\n if (header.type !== 'file' && header.type !== 'contiguous-file') {\n process.nextTick(callback)\n return new Void()\n }\n\n var sink = new Sink(this)\n\n this._stream = sink\n\n eos(sink, function (err) {\n self._stream = null\n\n if (err) { // stream was closed\n self.destroy()\n return callback(err)\n }\n\n if (sink.written !== header.size) { // corrupting tar\n self.destroy()\n return callback(new Error('size mismatch'))\n }\n\n overflow(self, header.size)\n if (self._finalizing) self.finalize()\n callback()\n })\n\n return sink\n}\n\nPack.prototype.finalize = function () {\n if (this._stream) {\n this._finalizing = true\n return\n }\n\n if (this._finalized) return\n this._finalized = true\n this.push(END_OF_TAR)\n this.push(null)\n}\n\nPack.prototype.destroy = function (err) {\n if (this._destroyed) return\n this._destroyed = true\n\n if (err) this.emit('error', err)\n this.emit('close')\n if (this._stream && this._stream.destroy) this._stream.destroy()\n}\n\nPack.prototype._encode = function (header) {\n if (!header.pax) {\n var buf = headers.encode(header)\n if (buf) {\n this.push(buf)\n return\n }\n }\n this._encodePax(header)\n}\n\nPack.prototype._encodePax = function (header) {\n var paxHeader = headers.encodePax({\n name: header.name,\n linkname: header.linkname,\n pax: header.pax\n })\n\n var newHeader = {\n name: 'PaxHeader',\n mode: header.mode,\n uid: header.uid,\n gid: header.gid,\n size: paxHeader.length,\n mtime: header.mtime,\n type: 'pax-header',\n linkname: header.linkname && 'PaxHeader',\n uname: header.uname,\n gname: header.gname,\n devmajor: header.devmajor,\n devminor: header.devminor\n }\n\n this.push(headers.encode(newHeader))\n this.push(paxHeader)\n overflow(this, paxHeader.length)\n\n newHeader.size = header.size\n newHeader.type = header.type\n this.push(headers.encode(newHeader))\n}\n\nPack.prototype._read = function (n) {\n var drain = this._drain\n this._drain = noop\n drain()\n}\n\nmodule.exports = Pack\n", "exports.extract = require('./extract')\nexports.pack = require('./pack')\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 { gunzip } from 'zlib';\n\nimport { metricScope, Unit } from 'aws-embedded-metrics';\nimport type { Context } from 'aws-lambda';\nimport { AWSError, S3 } from 'aws-sdk';\nimport { SemVer } from 'semver';\nimport { extract } from 'tar-stream';\nimport { CatalogModel, PackageInfo } from '.';\nimport { DenyListClient } from '../deny-list/client.lambda-shared';\nimport type { CatalogBuilderInput } from '../payload-schema';\nimport * as aws from '../shared/aws.lambda-shared';\nimport * as constants from '../shared/constants';\nimport { requireEnv } from '../shared/env.lambda-shared';\n\nconst METRICS_NAMESPACE = 'ConstructHub/CatalogBuilder';\n\n/**\n * Regenerates the `catalog.json` object in the configured S3 bucket.\n *\n * @param event configuration for the rebuild job. In particular, the `rebuild`\n * property can be set to `true` in order to trigger a full (i.e:\n * non-incremental) rebuild of the object.\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: CatalogBuilderInput, context: Context) {\n console.log(JSON.stringify(event, null, 2));\n\n const BUCKET_NAME = requireEnv('BUCKET_NAME');\n\n const packages = new Map<string, Map<number, PackageInfo>>();\n const denyList = await DenyListClient.newClient();\n\n console.log('Loading existing catalog (if present)...');\n\n const data = await aws.s3().getObject({ Bucket: BUCKET_NAME, Key: constants.CATALOG_KEY }).promise()\n .catch((err: AWSError) => err.code !== 'NoSuchKey'\n ? Promise.reject(err)\n : Promise.resolve({ /* no data */ } as S3.GetObjectOutput));\n\n if (data.Body) {\n console.log('Catalog found. Loading...');\n const catalog: CatalogModel = JSON.parse(data.Body.toString('utf-8'));\n for (const info of catalog.packages) {\n if (!packages.has(info.name)) {\n packages.set(info.name, new Map());\n }\n packages.get(info.name)!.set(info.major, info);\n }\n }\n\n // If defined, the function will invoke itself again to resume the work from that key (this\n // happens only in \"from scratch\" or \"rebuild\" cases).\n let nextStartAfter: string | undefined;\n\n if (event.package) {\n if (!event.package.key.endsWith(constants.PACKAGE_KEY_SUFFIX)) {\n throw new Error(`The provided package key is invalid: ${event.package.key} does not end in ${constants.PACKAGE_KEY_SUFFIX}`);\n }\n\n console.log('Registering new packages...');\n // note that we intentionally don't catch errors here to let these\n // event go to the DLQ for manual inspection.\n await appendPackage(packages, event.package.key, BUCKET_NAME, denyList);\n }\n\n // If we don't have a package in event, then we're refreshing the catalog. This is also true if we\n // don't have a catalog body (from scratch) or if \"startAfter\" is set (continuation of from\n // scratch).\n if (!event?.package || !data.Body || event.startAfter) {\n\n console.log('Recreating or refreshing catalog...');\n const failures: any = {};\n for await (const { Key: pkgKey } of relevantObjects(BUCKET_NAME, event.startAfter)) {\n try {\n await appendPackage(packages, pkgKey!, BUCKET_NAME, denyList);\n } catch (e) {\n failures[pkgKey!] = e;\n }\n // If we're getting short on time (1 minute out of 15 left), we'll be continuing in a new\n // invocation after writing what we've done so far to S3...\n if (context.getRemainingTimeInMillis() <= 60_000) {\n nextStartAfter = pkgKey;\n break;\n }\n }\n for (const [key, error] of Object.entries(failures)) {\n console.log(`Failed processing ${key}: ${error}`);\n }\n\n await metricScope((metrics) => async () => {\n metrics.setNamespace(METRICS_NAMESPACE);\n const failedCount = Object.keys(failures).length;\n console.log(`Marking ${failedCount} failed packages`);\n metrics.putMetric('FailedPackagesOnRecreation', failedCount, Unit.Count);\n })();\n }\n\n // Build the final data package...\n console.log('Consolidating catalog...');\n const catalog: CatalogModel = { packages: new Array<PackageInfo>(), updated: new Date().toISOString() };\n for (const majors of packages.values()) {\n for (const pkg of majors.values()) {\n catalog.packages.push(pkg);\n }\n }\n\n console.log(`There are now ${catalog.packages.length} registered package major versions`);\n await metricScope((metrics) => async () => {\n metrics.setNamespace(METRICS_NAMESPACE);\n metrics.putMetric('RegisteredPackagesMajorVersion', catalog.packages.length, Unit.Count);\n })();\n\n\n // Clean up existing entries if necessary. In particular, remove the license texts as they make\n // the catalog unnecessarily large, and may hinder some search queries' result quality.\n for (const entry of catalog.packages) {\n if (entry.metadata) {\n delete (entry.metadata as any).licenseText;\n }\n }\n\n // Upload the result to S3 and exit.\n const result = await aws.s3().putObject({\n Bucket: BUCKET_NAME,\n Key: constants.CATALOG_KEY,\n Body: JSON.stringify(catalog, 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-Count': `${catalog.packages.length}`,\n },\n }).promise();\n\n if (nextStartAfter != null) {\n console.log(`Will continue from ${nextStartAfter} in new invocation...`);\n const nextEvent: CatalogBuilderInput = { ...event, startAfter: nextStartAfter };\n // We start it asynchronously, as this function has a provisionned\n // concurrency of 1 (so a synchronous attempt would always be throttled).\n await aws.lambda().invokeAsync({\n FunctionName: context.functionName,\n InvokeArgs: JSON.stringify(nextEvent, null, 2),\n }).promise();\n }\n\n return result;\n}\n\n/**\n * A generator that asynchronously traverses the set of \"interesting\" objects\n * found by listing the configured S3 bucket. Those objects correspond to all\n * npm package tarballs present under the `packages/` prefix in the bucket.\n *\n * @param bucket the bucket in which to list objects\n * @param startAfter the key to start reading from, if provided.\n */\nasync function* relevantObjects(bucket: string, startAfter?: string) {\n const request: S3.ListObjectsV2Request = {\n Bucket: bucket,\n Prefix: constants.STORAGE_KEY_PREFIX,\n StartAfter: startAfter,\n };\n do {\n const result = await aws.s3().listObjectsV2(request).promise();\n for (const object of result.Contents ?? []) {\n if (!object.Key?.endsWith(constants.PACKAGE_KEY_SUFFIX)) {\n continue;\n }\n // We only register packages if they have AT LEAST docs in one language.\n const tsDocs = `${object.Key.substring(0, object.Key.length - constants.PACKAGE_KEY_SUFFIX.length)}${constants.DOCS_KEY_SUFFIX_TYPESCRIPT}`;\n const pyDocs = `${object.Key.substring(0, object.Key.length - constants.PACKAGE_KEY_SUFFIX.length)}${constants.DOCS_KEY_SUFFIX_PYTHON}`;\n const javaDocs = `${object.Key.substring(0, object.Key.length - constants.PACKAGE_KEY_SUFFIX.length)}${constants.DOCS_KEY_SUFFIX_JAVA}`;\n if (!(await aws.s3ObjectExists(bucket, tsDocs)) &&\n !(await aws.s3ObjectExists(bucket, pyDocs)) &&\n !(await aws.s3ObjectExists(bucket, javaDocs))) {\n continue;\n }\n yield object;\n }\n request.ContinuationToken = result.NextContinuationToken;\n } while (request.ContinuationToken != null);\n}\n\nasync function appendPackage(packages: any, pkgKey: string, bucketName: string, denyList: DenyListClient) {\n console.log(`Processing key: ${pkgKey}`);\n const [, packageName, versionStr] = constants.STORAGE_KEY_FORMAT_REGEX.exec(pkgKey)!;\n const version = new SemVer(versionStr);\n const found = packages.get(packageName)?.get(version.major);\n // If the version is === to the current latest, we'll be replacing that (so re-generated metadata are taken into account)\n if (found != null && version.compare(found.version) < 0) {\n console.log(`Skipping ${packageName}@${version} because it is not newer than the existing ${found.version}`);\n return;\n }\n\n console.log(`Checking if ${packageName}@${version.version} matches a deny list rule`);\n const blocked = denyList.lookup(packageName, version.version);\n if (blocked) {\n console.log(`Skipping ${packageName}@${version.version} because it is blocked by the deny list rule: ${JSON.stringify(blocked)}`);\n return;\n }\n\n console.log(`Registering ${packageName}@${version}`);\n\n // Donwload the tarball to inspect the `package.json` data therein.\n const pkg = await aws.s3().getObject({ Bucket: bucketName, Key: pkgKey }).promise();\n const metadataKey = pkgKey.replace(constants.PACKAGE_KEY_SUFFIX, constants.METADATA_KEY_SUFFIX);\n const metadataResponse = await aws.s3().getObject({ Bucket: bucketName, Key: metadataKey }).promise();\n const manifest = await new Promise<Buffer>((ok, ko) => {\n gunzip(Buffer.from(pkg.Body!), (err, tar) => {\n if (err) {\n return ko(err);\n }\n extract()\n .on('entry', (header, stream, next) => {\n if (header.name !== 'package/package.json') {\n // Not the file we are looking for, skip ahead (next run-loop tick).\n return setImmediate(next);\n }\n const chunks = new Array<Buffer>();\n return stream\n .on('data', (chunk) => chunks.push(Buffer.from(chunk)))\n .once('end', () => {\n ok(Buffer.concat(chunks));\n next();\n })\n .resume();\n })\n .once('finish', () => {\n ko(new Error('Could not find package/package.json in tarball!'));\n })\n .write(tar, (writeErr) => {\n if (writeErr) {\n ko(writeErr);\n }\n });\n });\n });\n // Add the PackageInfo into the working set\n const pkgMetadata = JSON.parse(manifest.toString('utf-8'));\n const npmMetadata = JSON.parse(metadataResponse?.Body?.toString('utf-8') ?? '{}');\n const major = new SemVer(pkgMetadata.version).major;\n if (!packages.has(pkgMetadata.name)) {\n packages.set(pkgMetadata.name, new Map());\n }\n packages.get(pkgMetadata.name)!.set(major, {\n author: pkgMetadata.author,\n description: pkgMetadata.description,\n keywords: pkgMetadata.keywords,\n languages: pkgMetadata.jsii.targets,\n license: pkgMetadata.license,\n major,\n metadata: npmMetadata,\n name: pkgMetadata.name,\n version: pkgMetadata.version,\n });\n\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", "/**\n * The name of an environment variable that contains the bucket name that includes the deny list.\n */\nexport const ENV_DENY_LIST_BUCKET_NAME = 'DENY_LIST_BUCKET_NAME';\n\n/**\n * The object key of the deny list in the bucket.\n */\nexport const ENV_DENY_LIST_OBJECT_KEY = 'DENY_LIST_OBJECT_KEY';\n\nexport const ENV_PRUNE_PACKAGE_DATA_BUCKET_NAME = 'PACKAGE_DATA_BUCKET_NAME';\nexport const ENV_PRUNE_PACKAGE_DATA_KEY_PREFIX = 'PACKAGE_DATA_KEY_PREFIX';\nexport const ENV_PRUNE_QUEUE_URL = 'PRUNE_QUEUE_URL';\nexport const ENV_PRUNE_ON_CHANGE_FUNCTION_NAME = 'ON_CHANGE_FUNCTION_NAME';\n\nexport const ENV_DELETE_OBJECT_DATA_BUCKET_NAME = 'PACKAGE_DATA_BUCKET_NAME';\n\nexport const METRICS_NAMESPACE = 'ConstructHub/DenyList';\n\nexport const enum MetricName {\n DENY_LIST_RULE_COUNT = 'DenyListRuleCount',\n}\n", "import * as AWS from 'aws-sdk';\nimport { s3 } from '../shared/aws.lambda-shared';\nimport { requireEnv } from '../shared/env.lambda-shared';\nimport { DenyListMap, DenyListRule } from './api';\nimport { ENV_DENY_LIST_BUCKET_NAME, ENV_DENY_LIST_OBJECT_KEY } from './constants';\n\n/**\n * A client for working with the deny list.\n */\nexport class DenyListClient {\n /**\n * Creates a new client for accessing the deny list.\n */\n public static async newClient() {\n const client = new DenyListClient();\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 _map: DenyListMap | undefined;\n\n private constructor() {\n this.bucketName = requireEnv(ENV_DENY_LIST_BUCKET_NAME);\n this.objectKey = requireEnv(ENV_DENY_LIST_OBJECT_KEY);\n this.s3 = s3();\n }\n\n /**\n * Downloads the deny list and stores it in memory.\n *\n * This must be called before `lookup()`.\n */\n private async init() {\n if (this._map) {\n throw new Error('init() cannot be called twice');\n }\n\n this._map = {};\n\n try {\n const params = {\n Bucket: this.bucketName,\n Key: this.objectKey,\n };\n\n const { Body: body } = await this.s3.getObject(params).promise();\n if (!body) {\n console.log(`WARNING: deny list body is empty at ${this.bucketName}/${this.objectKey}`);\n return;\n }\n\n const contents = body.toString('utf-8');\n\n // an empty string is a valid (empty) deny list\n if (contents.length === 0) {\n return;\n }\n\n const data = JSON.parse(contents) as DenyListMap;\n if (typeof(data) != 'object') {\n throw new Error(`Invalid format in deny list file at ${this.bucketName}/${this.objectKey}. Expecting a map`);\n }\n\n this._map = data;\n } catch (e) {\n if (e.code === 'NoSuchKey' || e.code === 'NoSuchBucket') {\n return;\n }\n\n throw new Error(`Unable to parse deny list file ${this.bucketName}/${this.objectKey}: ${e}`);\n }\n }\n\n /**\n * Checks if a package (name + version) is in the deny list.\n * @param name The name of the package\n * @param version The package version\n * @returns `undefined` if the package is not in the deny list or a\n * `DenyListRule` otherwise.\n */\n public lookup(name: string, version: string): DenyListRule | undefined {\n if (!this._map) {\n throw new Error('DenyListClient must be initialized');\n }\n\n return this._map[name] ?? this._map[`${name}/v${version}`];\n }\n\n /**\n * Returns a copy of the deny list map.\n */\n public get map() {\n if (!this._map) {\n throw new Error('DenyListClient must be initialized');\n }\n\n return this._map;\n }\n}\n", "/**\n * Supported languages to generate documentation in.\n */\nexport class DocumentationLanguage {\n /**\n * TypeScript.\n */\n public static readonly TYPESCRIPT = new DocumentationLanguage('typescript');\n\n /**\n * Python.\n */\n public static readonly PYTHON = new DocumentationLanguage('python');\n\n /**\n * Java.\n */\n public static readonly JAVA = new DocumentationLanguage('java');\n\n /**\n * All supported languages.\n */\n public static readonly ALL = [\n DocumentationLanguage.TYPESCRIPT,\n DocumentationLanguage.PYTHON,\n DocumentationLanguage.JAVA,\n ] as const;\n\n /**\n * Transform a literal string to the `DocumentationLanguage` object.\n *\n * Throws an `UnsupportedLanguageError` if the language is not supported.\n */\n public static fromString(lang: string) {\n switch (lang) {\n case DocumentationLanguage.TYPESCRIPT.toString():\n return DocumentationLanguage.TYPESCRIPT;\n case DocumentationLanguage.PYTHON.toString():\n return DocumentationLanguage.PYTHON;\n case DocumentationLanguage.JAVA.toString():\n return DocumentationLanguage.JAVA;\n default:\n throw new UnsupportedLanguageError(lang, DocumentationLanguage.ALL);\n }\n }\n\n private constructor(private readonly lang: string) {}\n\n public toString() {\n return this.lang;\n }\n}\n\nexport class UnsupportedLanguageError extends Error {\n constructor(lang: string, supported: readonly DocumentationLanguage[]) {\n super(`Unsupported language: ${lang}. Supported languages are: [${supported}]`);\n }\n}\n", "/*\n * IMPORTANT: This file is used both by bundled lambda functions and by\n * constructs. This means it should not directly or transitively import anything\n * not part of the package's `dependencies`, such as the `aws-sdk`.\n */\n\nimport { DocumentationLanguage } from './language';\n\n/**\n * Key prefix for the package data storage.\n */\nexport const STORAGE_KEY_PREFIX = 'data/';\n\n/**\n * Key suffix for storing npm package bundles.\n */\nexport const PACKAGE_KEY_SUFFIX = '/package.tgz';\n\n/**\n * Key suffix for storing npm package metadata.\n */\nexport const METADATA_KEY_SUFFIX = '/metadata.json';\n\n/**\n * The key suffix for (TypeScript) assembly files\n */\nexport const ASSEMBLY_KEY_SUFFIX = '/assembly.json';\n\n/**\n * The key suffix for a TypeScript doc artifact (root module).\n */\nexport const DOCS_KEY_SUFFIX_TYPESCRIPT = docsKeySuffix(DocumentationLanguage.TYPESCRIPT);\n\n/**\n * The key suffix for a Python doc artifact (root module).\n */\nexport const DOCS_KEY_SUFFIX_PYTHON = docsKeySuffix(DocumentationLanguage.PYTHON);\n\n/**\n * The key suffix for a Python doc artifact (root module).\n */\nexport const DOCS_KEY_SUFFIX_JAVA = docsKeySuffix(DocumentationLanguage.JAVA);\n\n/**\n * The key suffix matching any documentation artifact.\n */\nexport const DOCS_KEY_SUFFIX_ANY = docsKeySuffix('*');\n\n/**\n * Return the S3 object key prefix for a specific package name and optionally a\n * version. Note that the prefix does not end with a \"/\" so you will likely want\n * to add that if you want to match a specific set of objects.\n */\nexport function getObjectKeyPrefix(packageName: string, packageVersion?: string) {\n let key = `${STORAGE_KEY_PREFIX}${packageName}`;\n if (packageVersion) {\n key += `/v${packageVersion}`;\n }\n\n return key;\n}\n\n/**\n * Resolves the set of S3 object keys use for a specific package/version.\n */\nexport function getObjectKeys(packageName: string, packageVersion: string) {\n const prefix = getObjectKeyPrefix(packageName, packageVersion);\n return {\n assemblyKey: `${prefix}${ASSEMBLY_KEY_SUFFIX}`,\n packageKey: `${prefix}${PACKAGE_KEY_SUFFIX}`,\n metadataKey: `${prefix}${METADATA_KEY_SUFFIX}`,\n };\n}\n\n/**\n * The key suffix for documentation artifacts by language and submodule.\n */\nexport function docsKeySuffix(lang?: DocumentationLanguage | '*', submodule?: string) {\n return `/docs-${submodule ? `${submodule}-` : ''}${lang}.md`;\n}\n\n/**\n * Key suffix for beacon files when a particular feature is not supported for\n * the particular package (i.e: Python docs for a package that does not have a\n * Python target configured).\n */\nexport const NOT_SUPPORTED_SUFFIX = '.not-supported';\n\n/**\n * The key for the catalog document.\n */\nexport const CATALOG_KEY = 'catalog.json';\n\n/**\n * A regular expression that can be used to parse out a storage key.\n */\nexport const STORAGE_KEY_FORMAT_REGEX = new RegExp(`^${STORAGE_KEY_PREFIX}((?:@[^/]+/)?[^/]+)/v([^/]+)/.*$`);\n// Capture groups: \u2517\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u25011\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u251B \u2517\u2501\u25012\u2501\u2501\u251B\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", "// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0'\n\nconst MAX_LENGTH = 256\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n /* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16\n\nmodule.exports = {\n SEMVER_SPEC_VERSION,\n MAX_LENGTH,\n MAX_SAFE_INTEGER,\n MAX_SAFE_COMPONENT_LENGTH\n}\n", "const debug = (\n typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n : () => {}\n\nmodule.exports = debug\n", "const { MAX_SAFE_COMPONENT_LENGTH } = require('./constants')\nconst debug = require('./debug')\nexports = module.exports = {}\n\n// The actual regexps go on exports.re\nconst re = exports.re = []\nconst src = exports.src = []\nconst t = exports.t = {}\nlet R = 0\n\nconst createToken = (name, value, isGlobal) => {\n const index = R++\n debug(index, value)\n t[name] = index\n src[index] = value\n re[index] = new RegExp(value, isGlobal ? 'g' : undefined)\n}\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\ncreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*')\ncreateToken('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\ncreateToken('NONNUMERICIDENTIFIER', '\\\\d*[a-zA-Z-][a-zA-Z0-9-]*')\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ncreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n\ncreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]\n}|${src[t.NONNUMERICIDENTIFIER]})`)\n\ncreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]\n}|${src[t.NONNUMERICIDENTIFIER]})`)\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ncreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`)\n\ncreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ncreateToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+')\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ncreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n}(?:\\\\.${src[t.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\ncreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n}${src[t.PRERELEASE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('FULL', `^${src[t.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.\ncreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n}${src[t.PRERELEASELOOSE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)\n\ncreateToken('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.\ncreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`)\ncreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`)\n\ncreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:${src[t.PRERELEASE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:${src[t.PRERELEASELOOSE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`)\ncreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ncreateToken('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])`)\ncreateToken('COERCERTL', src[t.COERCE], true)\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ncreateToken('LONETILDE', '(?:~>?)')\n\ncreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true)\nexports.tildeTrimReplace = '$1~'\n\ncreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ncreateToken('LONECARET', '(?:\\\\^)')\n\ncreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true)\nexports.caretTrimReplace = '$1^'\n\ncreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ncreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`)\ncreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.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`\ncreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)\nexports.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.\ncreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAIN]})` +\n `\\\\s*$`)\n\ncreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s*$`)\n\n// Star ranges basically just allow anything at all.\ncreateToken('STAR', '(<|>)?=?\\\\s*\\\\*')\n// >=0.0.0 is like a star\ncreateToken('GTE0', '^\\\\s*>=\\\\s*0\\.0\\.0\\\\s*$')\ncreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\.0\\.0-0\\\\s*$')\n", "// parse out just the options we care about so we always get a consistent\n// obj with keys in a consistent order.\nconst opts = ['includePrerelease', 'loose', 'rtl']\nconst parseOptions = options =>\n !options ? {}\n : typeof options !== 'object' ? { loose: true }\n : opts.filter(k => options[k]).reduce((options, k) => {\n options[k] = true\n return options\n }, {})\nmodule.exports = parseOptions\n", "const numeric = /^[0-9]+$/\nconst compareIdentifiers = (a, b) => {\n const anum = numeric.test(a)\n const 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\nconst rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)\n\nmodule.exports = {\n compareIdentifiers,\n rcompareIdentifiers\n}\n", "const debug = require('../internal/debug')\nconst { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')\nconst { re, t } = require('../internal/re')\n\nconst parseOptions = require('../internal/parse-options')\nconst { compareIdentifiers } = require('../internal/identifiers')\nclass SemVer {\n constructor (version, options) {\n options = parseOptions(options)\n\n if (version instanceof SemVer) {\n if (version.loose === !!options.loose &&\n version.includePrerelease === !!options.includePrerelease) {\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(\n `version is longer than ${MAX_LENGTH} characters`\n )\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n // this isn't actually relevant for versions, but keep it so that we\n // don't run into trouble passing this.options around.\n this.includePrerelease = !!options.includePrerelease\n\n const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.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((id) => {\n if (/^[0-9]+$/.test(id)) {\n const 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\n format () {\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\n toString () {\n return this.version\n }\n\n compare (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n if (typeof other === 'string' && other === this.version) {\n return 0\n }\n other = new SemVer(other, this.options)\n }\n\n if (other.version === this.version) {\n return 0\n }\n\n return this.compareMain(other) || this.comparePre(other)\n }\n\n compareMain (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n return (\n compareIdentifiers(this.major, other.major) ||\n compareIdentifiers(this.minor, other.minor) ||\n compareIdentifiers(this.patch, other.patch)\n )\n }\n\n comparePre (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 let i = 0\n do {\n const a = this.prerelease[i]\n const 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 compareBuild (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n let i = 0\n do {\n const a = this.build[i]\n const b = other.build[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.\n inc (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 (\n this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0\n ) {\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 let 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}\n\nmodule.exports = SemVer\n", "const {MAX_LENGTH} = require('../internal/constants')\nconst { re, t } = require('../internal/re')\nconst SemVer = require('../classes/semver')\n\nconst parseOptions = require('../internal/parse-options')\nconst parse = (version, options) => {\n options = parseOptions(options)\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 const r = options.loose ? re[t.LOOSE] : re[t.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\nmodule.exports = parse\n", "const parse = require('./parse')\nconst valid = (version, options) => {\n const v = parse(version, options)\n return v ? v.version : null\n}\nmodule.exports = valid\n", "const parse = require('./parse')\nconst clean = (version, options) => {\n const s = parse(version.trim().replace(/^[=v]+/, ''), options)\n return s ? s.version : null\n}\nmodule.exports = clean\n", "const SemVer = require('../classes/semver')\n\nconst inc = (version, release, options, identifier) => {\n if (typeof (options) === 'string') {\n identifier = options\n options = undefined\n }\n\n try {\n return new SemVer(version, options).inc(release, identifier).version\n } catch (er) {\n return null\n }\n}\nmodule.exports = inc\n", "const SemVer = require('../classes/semver')\nconst compare = (a, b, loose) =>\n new SemVer(a, loose).compare(new SemVer(b, loose))\n\nmodule.exports = compare\n", "const compare = require('./compare')\nconst eq = (a, b, loose) => compare(a, b, loose) === 0\nmodule.exports = eq\n", "const parse = require('./parse')\nconst eq = require('./eq')\n\nconst diff = (version1, version2) => {\n if (eq(version1, version2)) {\n return null\n } else {\n const v1 = parse(version1)\n const v2 = parse(version2)\n const hasPre = v1.prerelease.length || v2.prerelease.length\n const prefix = hasPre ? 'pre' : ''\n const defaultResult = hasPre ? 'prerelease' : ''\n for (const 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}\nmodule.exports = diff\n", "const SemVer = require('../classes/semver')\nconst major = (a, loose) => new SemVer(a, loose).major\nmodule.exports = major\n", "const SemVer = require('../classes/semver')\nconst minor = (a, loose) => new SemVer(a, loose).minor\nmodule.exports = minor\n", "const SemVer = require('../classes/semver')\nconst patch = (a, loose) => new SemVer(a, loose).patch\nmodule.exports = patch\n", "const parse = require('./parse')\nconst prerelease = (version, options) => {\n const parsed = parse(version, options)\n return (parsed && parsed.prerelease.length) ? parsed.prerelease : null\n}\nmodule.exports = prerelease\n", "const compare = require('./compare')\nconst rcompare = (a, b, loose) => compare(b, a, loose)\nmodule.exports = rcompare\n", "const compare = require('./compare')\nconst compareLoose = (a, b) => compare(a, b, true)\nmodule.exports = compareLoose\n", "const SemVer = require('../classes/semver')\nconst compareBuild = (a, b, loose) => {\n const versionA = new SemVer(a, loose)\n const versionB = new SemVer(b, loose)\n return versionA.compare(versionB) || versionA.compareBuild(versionB)\n}\nmodule.exports = compareBuild\n", "const compareBuild = require('./compare-build')\nconst sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))\nmodule.exports = sort\n", "const compareBuild = require('./compare-build')\nconst rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))\nmodule.exports = rsort\n", "const compare = require('./compare')\nconst gt = (a, b, loose) => compare(a, b, loose) > 0\nmodule.exports = gt\n", "const compare = require('./compare')\nconst lt = (a, b, loose) => compare(a, b, loose) < 0\nmodule.exports = lt\n", "const compare = require('./compare')\nconst neq = (a, b, loose) => compare(a, b, loose) !== 0\nmodule.exports = neq\n", "const compare = require('./compare')\nconst gte = (a, b, loose) => compare(a, b, loose) >= 0\nmodule.exports = gte\n", "const compare = require('./compare')\nconst lte = (a, b, loose) => compare(a, b, loose) <= 0\nmodule.exports = lte\n", "const eq = require('./eq')\nconst neq = require('./neq')\nconst gt = require('./gt')\nconst gte = require('./gte')\nconst lt = require('./lt')\nconst lte = require('./lte')\n\nconst 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}\nmodule.exports = cmp\n", "const SemVer = require('../classes/semver')\nconst parse = require('./parse')\nconst {re, t} = require('../internal/re')\n\nconst coerce = (version, options) => {\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version === 'number') {\n version = String(version)\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n options = options || {}\n\n let match = null\n if (!options.rtl) {\n match = version.match(re[t.COERCE])\n } else {\n // Find the right-most coercible string that does not share\n // a terminus with a more left-ward coercible string.\n // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'\n //\n // Walk through the string checking with a /g regexp\n // Manually set the index so as to pick up overlapping matches.\n // Stop when we get a match that ends at the string end, since no\n // coercible string can be more right-ward without the same terminus.\n let next\n while ((next = re[t.COERCERTL].exec(version)) &&\n (!match || match.index + match[0].length !== version.length)\n ) {\n if (!match ||\n next.index + next[0].length !== match.index + match[0].length) {\n match = next\n }\n re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length\n }\n // leave it in a clean state\n re[t.COERCERTL].lastIndex = -1\n }\n\n if (match === null)\n return null\n\n return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options)\n}\nmodule.exports = coerce\n", "'use strict'\nmodule.exports = function (Yallist) {\n Yallist.prototype[Symbol.iterator] = function* () {\n for (let walker = this.head; walker; walker = walker.next) {\n yield walker.value\n }\n }\n}\n", "'use strict'\nmodule.exports = Yallist\n\nYallist.Node = Node\nYallist.create = Yallist\n\nfunction Yallist (list) {\n var self = this\n if (!(self instanceof Yallist)) {\n self = new Yallist()\n }\n\n self.tail = null\n self.head = null\n self.length = 0\n\n if (list && typeof list.forEach === 'function') {\n list.forEach(function (item) {\n self.push(item)\n })\n } else if (arguments.length > 0) {\n for (var i = 0, l = arguments.length; i < l; i++) {\n self.push(arguments[i])\n }\n }\n\n return self\n}\n\nYallist.prototype.removeNode = function (node) {\n if (node.list !== this) {\n throw new Error('removing node which does not belong to this list')\n }\n\n var next = node.next\n var prev = node.prev\n\n if (next) {\n next.prev = prev\n }\n\n if (prev) {\n prev.next = next\n }\n\n if (node === this.head) {\n this.head = next\n }\n if (node === this.tail) {\n this.tail = prev\n }\n\n node.list.length--\n node.next = null\n node.prev = null\n node.list = null\n\n return next\n}\n\nYallist.prototype.unshiftNode = function (node) {\n if (node === this.head) {\n return\n }\n\n if (node.list) {\n node.list.removeNode(node)\n }\n\n var head = this.head\n node.list = this\n node.next = head\n if (head) {\n head.prev = node\n }\n\n this.head = node\n if (!this.tail) {\n this.tail = node\n }\n this.length++\n}\n\nYallist.prototype.pushNode = function (node) {\n if (node === this.tail) {\n return\n }\n\n if (node.list) {\n node.list.removeNode(node)\n }\n\n var tail = this.tail\n node.list = this\n node.prev = tail\n if (tail) {\n tail.next = node\n }\n\n this.tail = node\n if (!this.head) {\n this.head = node\n }\n this.length++\n}\n\nYallist.prototype.push = function () {\n for (var i = 0, l = arguments.length; i < l; i++) {\n push(this, arguments[i])\n }\n return this.length\n}\n\nYallist.prototype.unshift = function () {\n for (var i = 0, l = arguments.length; i < l; i++) {\n unshift(this, arguments[i])\n }\n return this.length\n}\n\nYallist.prototype.pop = function () {\n if (!this.tail) {\n return undefined\n }\n\n var res = this.tail.value\n this.tail = this.tail.prev\n if (this.tail) {\n this.tail.next = null\n } else {\n this.head = null\n }\n this.length--\n return res\n}\n\nYallist.prototype.shift = function () {\n if (!this.head) {\n return undefined\n }\n\n var res = this.head.value\n this.head = this.head.next\n if (this.head) {\n this.head.prev = null\n } else {\n this.tail = null\n }\n this.length--\n return res\n}\n\nYallist.prototype.forEach = function (fn, thisp) {\n thisp = thisp || this\n for (var walker = this.head, i = 0; walker !== null; i++) {\n fn.call(thisp, walker.value, i, this)\n walker = walker.next\n }\n}\n\nYallist.prototype.forEachReverse = function (fn, thisp) {\n thisp = thisp || this\n for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {\n fn.call(thisp, walker.value, i, this)\n walker = walker.prev\n }\n}\n\nYallist.prototype.get = function (n) {\n for (var i = 0, walker = this.head; walker !== null && i < n; i++) {\n // abort out of the list early if we hit a cycle\n walker = walker.next\n }\n if (i === n && walker !== null) {\n return walker.value\n }\n}\n\nYallist.prototype.getReverse = function (n) {\n for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {\n // abort out of the list early if we hit a cycle\n walker = walker.prev\n }\n if (i === n && walker !== null) {\n return walker.value\n }\n}\n\nYallist.prototype.map = function (fn, thisp) {\n thisp = thisp || this\n var res = new Yallist()\n for (var walker = this.head; walker !== null;) {\n res.push(fn.call(thisp, walker.value, this))\n walker = walker.next\n }\n return res\n}\n\nYallist.prototype.mapReverse = function (fn, thisp) {\n thisp = thisp || this\n var res = new Yallist()\n for (var walker = this.tail; walker !== null;) {\n res.push(fn.call(thisp, walker.value, this))\n walker = walker.prev\n }\n return res\n}\n\nYallist.prototype.reduce = function (fn, initial) {\n var acc\n var walker = this.head\n if (arguments.length > 1) {\n acc = initial\n } else if (this.head) {\n walker = this.head.next\n acc = this.head.value\n } else {\n throw new TypeError('Reduce of empty list with no initial value')\n }\n\n for (var i = 0; walker !== null; i++) {\n acc = fn(acc, walker.value, i)\n walker = walker.next\n }\n\n return acc\n}\n\nYallist.prototype.reduceReverse = function (fn, initial) {\n var acc\n var walker = this.tail\n if (arguments.length > 1) {\n acc = initial\n } else if (this.tail) {\n walker = this.tail.prev\n acc = this.tail.value\n } else {\n throw new TypeError('Reduce of empty list with no initial value')\n }\n\n for (var i = this.length - 1; walker !== null; i--) {\n acc = fn(acc, walker.value, i)\n walker = walker.prev\n }\n\n return acc\n}\n\nYallist.prototype.toArray = function () {\n var arr = new Array(this.length)\n for (var i = 0, walker = this.head; walker !== null; i++) {\n arr[i] = walker.value\n walker = walker.next\n }\n return arr\n}\n\nYallist.prototype.toArrayReverse = function () {\n var arr = new Array(this.length)\n for (var i = 0, walker = this.tail; walker !== null; i++) {\n arr[i] = walker.value\n walker = walker.prev\n }\n return arr\n}\n\nYallist.prototype.slice = function (from, to) {\n to = to || this.length\n if (to < 0) {\n to += this.length\n }\n from = from || 0\n if (from < 0) {\n from += this.length\n }\n var ret = new Yallist()\n if (to < from || to < 0) {\n return ret\n }\n if (from < 0) {\n from = 0\n }\n if (to > this.length) {\n to = this.length\n }\n for (var i = 0, walker = this.head; walker !== null && i < from; i++) {\n walker = walker.next\n }\n for (; walker !== null && i < to; i++, walker = walker.next) {\n ret.push(walker.value)\n }\n return ret\n}\n\nYallist.prototype.sliceReverse = function (from, to) {\n to = to || this.length\n if (to < 0) {\n to += this.length\n }\n from = from || 0\n if (from < 0) {\n from += this.length\n }\n var ret = new Yallist()\n if (to < from || to < 0) {\n return ret\n }\n if (from < 0) {\n from = 0\n }\n if (to > this.length) {\n to = this.length\n }\n for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {\n walker = walker.prev\n }\n for (; walker !== null && i > from; i--, walker = walker.prev) {\n ret.push(walker.value)\n }\n return ret\n}\n\nYallist.prototype.splice = function (start, deleteCount, ...nodes) {\n if (start > this.length) {\n start = this.length - 1\n }\n if (start < 0) {\n start = this.length + start;\n }\n\n for (var i = 0, walker = this.head; walker !== null && i < start; i++) {\n walker = walker.next\n }\n\n var ret = []\n for (var i = 0; walker && i < deleteCount; i++) {\n ret.push(walker.value)\n walker = this.removeNode(walker)\n }\n if (walker === null) {\n walker = this.tail\n }\n\n if (walker !== this.head && walker !== this.tail) {\n walker = walker.prev\n }\n\n for (var i = 0; i < nodes.length; i++) {\n walker = insert(this, walker, nodes[i])\n }\n return ret;\n}\n\nYallist.prototype.reverse = function () {\n var head = this.head\n var tail = this.tail\n for (var walker = head; walker !== null; walker = walker.prev) {\n var p = walker.prev\n walker.prev = walker.next\n walker.next = p\n }\n this.head = tail\n this.tail = head\n return this\n}\n\nfunction insert (self, node, value) {\n var inserted = node === self.head ?\n new Node(value, null, node, self) :\n new Node(value, node, node.next, self)\n\n if (inserted.next === null) {\n self.tail = inserted\n }\n if (inserted.prev === null) {\n self.head = inserted\n }\n\n self.length++\n\n return inserted\n}\n\nfunction push (self, item) {\n self.tail = new Node(item, self.tail, null, self)\n if (!self.head) {\n self.head = self.tail\n }\n self.length++\n}\n\nfunction unshift (self, item) {\n self.head = new Node(item, null, self.head, self)\n if (!self.tail) {\n self.tail = self.head\n }\n self.length++\n}\n\nfunction Node (value, prev, next, list) {\n if (!(this instanceof Node)) {\n return new Node(value, prev, next, list)\n }\n\n this.list = list\n this.value = value\n\n if (prev) {\n prev.next = this\n this.prev = prev\n } else {\n this.prev = null\n }\n\n if (next) {\n next.prev = this\n this.next = next\n } else {\n this.next = null\n }\n}\n\ntry {\n // add if support for Symbol.iterator is present\n require('./iterator.js')(Yallist)\n} catch (er) {}\n", "'use strict'\n\n// A linked list to keep track of recently-used-ness\nconst Yallist = require('yallist')\n\nconst MAX = Symbol('max')\nconst LENGTH = Symbol('length')\nconst LENGTH_CALCULATOR = Symbol('lengthCalculator')\nconst ALLOW_STALE = Symbol('allowStale')\nconst MAX_AGE = Symbol('maxAge')\nconst DISPOSE = Symbol('dispose')\nconst NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet')\nconst LRU_LIST = Symbol('lruList')\nconst CACHE = Symbol('cache')\nconst UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet')\n\nconst naiveLength = () => 1\n\n// lruList is a yallist where the head is the youngest\n// item, and the tail is the oldest. the list contains the Hit\n// objects as the entries.\n// Each Hit object has a reference to its Yallist.Node. This\n// never changes.\n//\n// cache is a Map (or PseudoMap) that matches the keys to\n// the Yallist.Node object.\nclass LRUCache {\n constructor (options) {\n if (typeof options === 'number')\n options = { max: options }\n\n if (!options)\n options = {}\n\n if (options.max && (typeof options.max !== 'number' || options.max < 0))\n throw new TypeError('max must be a non-negative number')\n // Kind of weird to have a default max of Infinity, but oh well.\n const max = this[MAX] = options.max || Infinity\n\n const lc = options.length || naiveLength\n this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc\n this[ALLOW_STALE] = options.stale || false\n if (options.maxAge && typeof options.maxAge !== 'number')\n throw new TypeError('maxAge must be a number')\n this[MAX_AGE] = options.maxAge || 0\n this[DISPOSE] = options.dispose\n this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false\n this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false\n this.reset()\n }\n\n // resize the cache when the max changes.\n set max (mL) {\n if (typeof mL !== 'number' || mL < 0)\n throw new TypeError('max must be a non-negative number')\n\n this[MAX] = mL || Infinity\n trim(this)\n }\n get max () {\n return this[MAX]\n }\n\n set allowStale (allowStale) {\n this[ALLOW_STALE] = !!allowStale\n }\n get allowStale () {\n return this[ALLOW_STALE]\n }\n\n set maxAge (mA) {\n if (typeof mA !== 'number')\n throw new TypeError('maxAge must be a non-negative number')\n\n this[MAX_AGE] = mA\n trim(this)\n }\n get maxAge () {\n return this[MAX_AGE]\n }\n\n // resize the cache when the lengthCalculator changes.\n set lengthCalculator (lC) {\n if (typeof lC !== 'function')\n lC = naiveLength\n\n if (lC !== this[LENGTH_CALCULATOR]) {\n this[LENGTH_CALCULATOR] = lC\n this[LENGTH] = 0\n this[LRU_LIST].forEach(hit => {\n hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key)\n this[LENGTH] += hit.length\n })\n }\n trim(this)\n }\n get lengthCalculator () { return this[LENGTH_CALCULATOR] }\n\n get length () { return this[LENGTH] }\n get itemCount () { return this[LRU_LIST].length }\n\n rforEach (fn, thisp) {\n thisp = thisp || this\n for (let walker = this[LRU_LIST].tail; walker !== null;) {\n const prev = walker.prev\n forEachStep(this, fn, walker, thisp)\n walker = prev\n }\n }\n\n forEach (fn, thisp) {\n thisp = thisp || this\n for (let walker = this[LRU_LIST].head; walker !== null;) {\n const next = walker.next\n forEachStep(this, fn, walker, thisp)\n walker = next\n }\n }\n\n keys () {\n return this[LRU_LIST].toArray().map(k => k.key)\n }\n\n values () {\n return this[LRU_LIST].toArray().map(k => k.value)\n }\n\n reset () {\n if (this[DISPOSE] &&\n this[LRU_LIST] &&\n this[LRU_LIST].length) {\n this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value))\n }\n\n this[CACHE] = new Map() // hash of items by key\n this[LRU_LIST] = new Yallist() // list of items in order of use recency\n this[LENGTH] = 0 // length of items in the list\n }\n\n dump () {\n return this[LRU_LIST].map(hit =>\n isStale(this, hit) ? false : {\n k: hit.key,\n v: hit.value,\n e: hit.now + (hit.maxAge || 0)\n }).toArray().filter(h => h)\n }\n\n dumpLru () {\n return this[LRU_LIST]\n }\n\n set (key, value, maxAge) {\n maxAge = maxAge || this[MAX_AGE]\n\n if (maxAge && typeof maxAge !== 'number')\n throw new TypeError('maxAge must be a number')\n\n const now = maxAge ? Date.now() : 0\n const len = this[LENGTH_CALCULATOR](value, key)\n\n if (this[CACHE].has(key)) {\n if (len > this[MAX]) {\n del(this, this[CACHE].get(key))\n return false\n }\n\n const node = this[CACHE].get(key)\n const item = node.value\n\n // dispose of the old one before overwriting\n // split out into 2 ifs for better coverage tracking\n if (this[DISPOSE]) {\n if (!this[NO_DISPOSE_ON_SET])\n this[DISPOSE](key, item.value)\n }\n\n item.now = now\n item.maxAge = maxAge\n item.value = value\n this[LENGTH] += len - item.length\n item.length = len\n this.get(key)\n trim(this)\n return true\n }\n\n const hit = new Entry(key, value, len, now, maxAge)\n\n // oversized objects fall out of cache automatically.\n if (hit.length > this[MAX]) {\n if (this[DISPOSE])\n this[DISPOSE](key, value)\n\n return false\n }\n\n this[LENGTH] += hit.length\n this[LRU_LIST].unshift(hit)\n this[CACHE].set(key, this[LRU_LIST].head)\n trim(this)\n return true\n }\n\n has (key) {\n if (!this[CACHE].has(key)) return false\n const hit = this[CACHE].get(key).value\n return !isStale(this, hit)\n }\n\n get (key) {\n return get(this, key, true)\n }\n\n peek (key) {\n return get(this, key, false)\n }\n\n pop () {\n const node = this[LRU_LIST].tail\n if (!node)\n return null\n\n del(this, node)\n return node.value\n }\n\n del (key) {\n del(this, this[CACHE].get(key))\n }\n\n load (arr) {\n // reset the cache\n this.reset()\n\n const now = Date.now()\n // A previous serialized cache has the most recent items first\n for (let l = arr.length - 1; l >= 0; l--) {\n const hit = arr[l]\n const expiresAt = hit.e || 0\n if (expiresAt === 0)\n // the item was created without expiration in a non aged cache\n this.set(hit.k, hit.v)\n else {\n const maxAge = expiresAt - now\n // dont add already expired items\n if (maxAge > 0) {\n this.set(hit.k, hit.v, maxAge)\n }\n }\n }\n }\n\n prune () {\n this[CACHE].forEach((value, key) => get(this, key, false))\n }\n}\n\nconst get = (self, key, doUse) => {\n const node = self[CACHE].get(key)\n if (node) {\n const hit = node.value\n if (isStale(self, hit)) {\n del(self, node)\n if (!self[ALLOW_STALE])\n return undefined\n } else {\n if (doUse) {\n if (self[UPDATE_AGE_ON_GET])\n node.value.now = Date.now()\n self[LRU_LIST].unshiftNode(node)\n }\n }\n return hit.value\n }\n}\n\nconst isStale = (self, hit) => {\n if (!hit || (!hit.maxAge && !self[MAX_AGE]))\n return false\n\n const diff = Date.now() - hit.now\n return hit.maxAge ? diff > hit.maxAge\n : self[MAX_AGE] && (diff > self[MAX_AGE])\n}\n\nconst trim = self => {\n if (self[LENGTH] > self[MAX]) {\n for (let walker = self[LRU_LIST].tail;\n self[LENGTH] > self[MAX] && walker !== null;) {\n // We know that we're about to delete this one, and also\n // what the next least recently used key will be, so just\n // go ahead and set it now.\n const prev = walker.prev\n del(self, walker)\n walker = prev\n }\n }\n}\n\nconst del = (self, node) => {\n if (node) {\n const hit = node.value\n if (self[DISPOSE])\n self[DISPOSE](hit.key, hit.value)\n\n self[LENGTH] -= hit.length\n self[CACHE].delete(hit.key)\n self[LRU_LIST].removeNode(node)\n }\n}\n\nclass Entry {\n constructor (key, value, length, now, maxAge) {\n this.key = key\n this.value = value\n this.length = length\n this.now = now\n this.maxAge = maxAge || 0\n }\n}\n\nconst forEachStep = (self, fn, node, thisp) => {\n let hit = node.value\n if (isStale(self, hit)) {\n del(self, node)\n if (!self[ALLOW_STALE])\n hit = undefined\n }\n if (hit)\n fn.call(thisp, hit.value, hit.key, self)\n}\n\nmodule.exports = LRUCache\n", "// hoisted class for cyclic dependency\nclass Range {\n constructor (range, options) {\n options = parseOptions(options)\n\n if (range instanceof Range) {\n if (\n range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease\n ) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n // just put it in the set and return\n this.raw = range.value\n this.set = [[range]]\n this.format()\n return this\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\n .split(/\\s*\\|\\|\\s*/)\n // map the range to a 2d array of comparators\n .map(range => this.parseRange(range.trim()))\n // throw out any comparator lists that are empty\n // this generally means that it was not a valid range, which is allowed\n // in loose mode, but will still throw if the WHOLE range is invalid.\n .filter(c => c.length)\n\n if (!this.set.length) {\n throw new TypeError(`Invalid SemVer Range: ${range}`)\n }\n\n // if we have any that are not the null set, throw out null sets.\n if (this.set.length > 1) {\n // keep the first one, in case they're all null sets\n const first = this.set[0]\n this.set = this.set.filter(c => !isNullSet(c[0]))\n if (this.set.length === 0)\n this.set = [first]\n else if (this.set.length > 1) {\n // if we have any that are *, then the range is just *\n for (const c of this.set) {\n if (c.length === 1 && isAny(c[0])) {\n this.set = [c]\n break\n }\n }\n }\n }\n\n this.format()\n }\n\n format () {\n this.range = this.set\n .map((comps) => {\n return comps.join(' ').trim()\n })\n .join('||')\n .trim()\n return this.range\n }\n\n toString () {\n return this.range\n }\n\n parseRange (range) {\n range = range.trim()\n\n // memoize range parsing for performance.\n // this is a very hot path, and fully deterministic.\n const memoOpts = Object.keys(this.options).join(',')\n const memoKey = `parseRange:${memoOpts}:${range}`\n const cached = cache.get(memoKey)\n if (cached)\n return cached\n\n const loose = this.options.loose\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n range = range.replace(hr, hyphenReplace(this.options.includePrerelease))\n debug('hyphen replace', range)\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range, re[t.COMPARATORTRIM])\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[t.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 const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const rangeList = range\n .split(' ')\n .map(comp => parseComparator(comp, this.options))\n .join(' ')\n .split(/\\s+/)\n // >=0.0.0 is equivalent to *\n .map(comp => replaceGTE0(comp, this.options))\n // in loose mode, throw out any that are not valid comparators\n .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true)\n .map(comp => new Comparator(comp, this.options))\n\n // if any comparators are the null set, then replace with JUST null set\n // if more than one comparator, remove any * comparators\n // also, don't include the same comparator more than once\n const l = rangeList.length\n const rangeMap = new Map()\n for (const comp of rangeList) {\n if (isNullSet(comp))\n return [comp]\n rangeMap.set(comp.value, comp)\n }\n if (rangeMap.size > 1 && rangeMap.has(''))\n rangeMap.delete('')\n\n const result = [...rangeMap.values()]\n cache.set(memoKey, result)\n return result\n }\n\n intersects (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some((thisComparators) => {\n return (\n isSatisfiable(thisComparators, options) &&\n range.set.some((rangeComparators) => {\n return (\n isSatisfiable(rangeComparators, options) &&\n thisComparators.every((thisComparator) => {\n return rangeComparators.every((rangeComparator) => {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n )\n })\n )\n })\n }\n\n // if ANY of the sets match ALL of its comparators, then pass\n test (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n for (let 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}\nmodule.exports = Range\n\nconst LRU = require('lru-cache')\nconst cache = new LRU({ max: 1000 })\n\nconst parseOptions = require('../internal/parse-options')\nconst Comparator = require('./comparator')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst {\n re,\n t,\n comparatorTrimReplace,\n tildeTrimReplace,\n caretTrimReplace\n} = require('../internal/re')\n\nconst isNullSet = c => c.value === '<0.0.0-0'\nconst isAny = c => c.value === ''\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nconst isSatisfiable = (comparators, options) => {\n let result = true\n const remainingComparators = comparators.slice()\n let testComparator = remainingComparators.pop()\n\n while (result && remainingComparators.length) {\n result = remainingComparators.every((otherComparator) => {\n return testComparator.intersects(otherComparator, options)\n })\n\n testComparator = remainingComparators.pop()\n }\n\n return result\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.\nconst 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\nconst isX = id => !id || id.toLowerCase() === 'x' || id === '*'\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\nconst replaceTildes = (comp, options) =>\n comp.trim().split(/\\s+/).map((comp) => {\n return replaceTilde(comp, options)\n }).join(' ')\n\nconst replaceTilde = (comp, options) => {\n const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('tilde', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0 <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0-0\n ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0-0\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-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-0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n// ^1.2.3 --> >=1.2.3 <2.0.0-0\n// ^1.2.0 --> >=1.2.0 <2.0.0-0\nconst replaceCarets = (comp, options) =>\n comp.trim().split(/\\s+/).map((comp) => {\n return replaceCaret(comp, options)\n }).join(' ')\n\nconst replaceCaret = (comp, options) => {\n debug('caret', comp, options)\n const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('caret', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n if (M === '0') {\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else {\n ret = `>=${M}.${m}.0${z} <${+M + 1}.0.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}-0`\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${+M + 1}.0.0-0`\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p\n } <${+M + 1}.0.0-0`\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nconst replaceXRanges = (comp, options) => {\n debug('replaceXRanges', comp, options)\n return comp.split(/\\s+/).map((comp) => {\n return replaceXRange(comp, options)\n }).join(' ')\n}\n\nconst replaceXRange = (comp, options) => {\n comp = comp.trim()\n const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n const xM = isX(M)\n const xm = xM || isX(m)\n const xp = xm || isX(p)\n const anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n // if we're including prereleases in the match, then we need\n // to fix this to -0, the lowest possible prerelease value\n pr = options.includePrerelease ? '-0' : ''\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.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 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 if (gtlt === '<')\n pr = '-0'\n\n ret = `${gtlt + M}.${m}.${p}${pr}`\n } else if (xm) {\n ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`\n } else if (xp) {\n ret = `>=${M}.${m}.0${pr\n } <${M}.${+m + 1}.0-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.\nconst 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[t.STAR], '')\n}\n\nconst replaceGTE0 = (comp, options) => {\n debug('replaceGTE0', comp, options)\n return comp.trim()\n .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n}\n\n// This function is passed to string.replace(re[t.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-0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\nconst hyphenReplace = incPr => ($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${incPr ? '-0' : ''}`\n } else if (isX(fp)) {\n from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`\n } else if (fpr) {\n from = `>=${from}`\n } else {\n from = `>=${from}${incPr ? '-0' : ''}`\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = `<${+tM + 1}.0.0-0`\n } else if (isX(tp)) {\n to = `<${tM}.${+tm + 1}.0-0`\n } else if (tpr) {\n to = `<=${tM}.${tm}.${tp}-${tpr}`\n } else if (incPr) {\n to = `<${tM}.${tm}.${+tp + 1}-0`\n } else {\n to = `<=${to}`\n }\n\n return (`${from} ${to}`).trim()\n}\n\nconst testSet = (set, version, options) => {\n for (let 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 (let i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === Comparator.ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n const 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", "const ANY = Symbol('SemVer ANY')\n// hoisted class for cyclic dependency\nclass Comparator {\n static get ANY () {\n return ANY\n }\n constructor (comp, options) {\n options = parseOptions(options)\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 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\n parse (comp) {\n const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const m = comp.match(r)\n\n if (!m) {\n throw new TypeError(`Invalid comparator: ${comp}`)\n }\n\n this.operator = m[1] !== undefined ? 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\n toString () {\n return this.value\n }\n\n test (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY || version === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n }\n\n intersects (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 if (this.operator === '') {\n if (this.value === '') {\n return true\n }\n return new Range(comp.value, options).test(this.value)\n } else if (comp.operator === '') {\n if (comp.value === '') {\n return true\n }\n return new Range(this.value, options).test(comp.semver)\n }\n\n const sameDirectionIncreasing =\n (this.operator === '>=' || this.operator === '>') &&\n (comp.operator === '>=' || comp.operator === '>')\n const sameDirectionDecreasing =\n (this.operator === '<=' || this.operator === '<') &&\n (comp.operator === '<=' || comp.operator === '<')\n const sameSemVer = this.semver.version === comp.semver.version\n const differentDirectionsInclusive =\n (this.operator === '>=' || this.operator === '<=') &&\n (comp.operator === '>=' || comp.operator === '<=')\n const oppositeDirectionsLessThan =\n cmp(this.semver, '<', comp.semver, options) &&\n (this.operator === '>=' || this.operator === '>') &&\n (comp.operator === '<=' || comp.operator === '<')\n const oppositeDirectionsGreaterThan =\n cmp(this.semver, '>', comp.semver, options) &&\n (this.operator === '<=' || this.operator === '<') &&\n (comp.operator === '>=' || comp.operator === '>')\n\n return (\n sameDirectionIncreasing ||\n sameDirectionDecreasing ||\n (sameSemVer && differentDirectionsInclusive) ||\n oppositeDirectionsLessThan ||\n oppositeDirectionsGreaterThan\n )\n }\n}\n\nmodule.exports = Comparator\n\nconst parseOptions = require('../internal/parse-options')\nconst {re, t} = require('../internal/re')\nconst cmp = require('../functions/cmp')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst Range = require('./range')\n", "const Range = require('../classes/range')\nconst 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}\nmodule.exports = satisfies\n", "const Range = require('../classes/range')\n\n// Mostly just for testing and legacy API reasons\nconst toComparators = (range, options) =>\n new Range(range, options).set\n .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))\n\nmodule.exports = toComparators\n", "const SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\n\nconst maxSatisfying = (versions, range, options) => {\n let max = null\n let maxSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((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}\nmodule.exports = maxSatisfying\n", "const SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst minSatisfying = (versions, range, options) => {\n let min = null\n let minSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((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}\nmodule.exports = minSatisfying\n", "const SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst gt = require('../functions/gt')\n\nconst minVersion = (range, loose) => {\n range = new Range(range, loose)\n\n let 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 (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let setMin = null\n comparators.forEach((comparator) => {\n // Clone to avoid manipulating the comparator's semver object.\n const 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 (!setMin || gt(compver, setMin)) {\n setMin = 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 if (setMin && (!minver || gt(minver, setMin)))\n minver = setMin\n }\n\n if (minver && range.test(minver)) {\n return minver\n }\n\n return null\n}\nmodule.exports = minVersion\n", "const Range = require('../classes/range')\nconst 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}\nmodule.exports = validRange\n", "const SemVer = require('../classes/semver')\nconst Comparator = require('../classes/comparator')\nconst {ANY} = Comparator\nconst Range = require('../classes/range')\nconst satisfies = require('../functions/satisfies')\nconst gt = require('../functions/gt')\nconst lt = require('../functions/lt')\nconst lte = require('../functions/lte')\nconst gte = require('../functions/gte')\n\nconst outside = (version, range, hilo, options) => {\n version = new SemVer(version, options)\n range = new Range(range, options)\n\n let 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 satisfies 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 (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let high = null\n let low = null\n\n comparators.forEach((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\nmodule.exports = outside\n", "// Determine if version is greater than all the versions possible in the range.\nconst outside = require('./outside')\nconst gtr = (version, range, options) => outside(version, range, '>', options)\nmodule.exports = gtr\n", "const outside = require('./outside')\n// Determine if version is less than all the versions possible in the range\nconst ltr = (version, range, options) => outside(version, range, '<', options)\nmodule.exports = ltr\n", "const Range = require('../classes/range')\nconst intersects = (r1, r2, options) => {\n r1 = new Range(r1, options)\n r2 = new Range(r2, options)\n return r1.intersects(r2)\n}\nmodule.exports = intersects\n", "// given a set of versions and a range, create a \"simplified\" range\n// that includes the same versions that the original range does\n// If the original range is shorter than the simplified one, return that.\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\nmodule.exports = (versions, range, options) => {\n const set = []\n let min = null\n let prev = null\n const v = versions.sort((a, b) => compare(a, b, options))\n for (const version of v) {\n const included = satisfies(version, range, options)\n if (included) {\n prev = version\n if (!min)\n min = version\n } else {\n if (prev) {\n set.push([min, prev])\n }\n prev = null\n min = null\n }\n }\n if (min)\n set.push([min, null])\n\n const ranges = []\n for (const [min, max] of set) {\n if (min === max)\n ranges.push(min)\n else if (!max && min === v[0])\n ranges.push('*')\n else if (!max)\n ranges.push(`>=${min}`)\n else if (min === v[0])\n ranges.push(`<=${max}`)\n else\n ranges.push(`${min} - ${max}`)\n }\n const simplified = ranges.join(' || ')\n const original = typeof range.raw === 'string' ? range.raw : String(range)\n return simplified.length < original.length ? simplified : range\n}\n", "const Range = require('../classes/range.js')\nconst Comparator = require('../classes/comparator.js')\nconst { ANY } = Comparator\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\n\n// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:\n// - Every simple range `r1, r2, ...` is a null set, OR\n// - Every simple range `r1, r2, ...` which is not a null set is a subset of\n// some `R1, R2, ...`\n//\n// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:\n// - If c is only the ANY comparator\n// - If C is only the ANY comparator, return true\n// - Else if in prerelease mode, return false\n// - else replace c with `[>=0.0.0]`\n// - If C is only the ANY comparator\n// - if in prerelease mode, return true\n// - else replace C with `[>=0.0.0]`\n// - Let EQ be the set of = comparators in c\n// - If EQ is more than one, return true (null set)\n// - Let GT be the highest > or >= comparator in c\n// - Let LT be the lowest < or <= comparator in c\n// - If GT and LT, and GT.semver > LT.semver, return true (null set)\n// - If any C is a = range, and GT or LT are set, return false\n// - If EQ\n// - If GT, and EQ does not satisfy GT, return true (null set)\n// - If LT, and EQ does not satisfy LT, return true (null set)\n// - If EQ satisfies every C, return true\n// - Else return false\n// - If GT\n// - If GT.semver is lower than any > or >= comp in C, return false\n// - If GT is >=, and GT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the GT.semver tuple, return false\n// - If LT\n// - If LT.semver is greater than any < or <= comp in C, return false\n// - If LT is <=, and LT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the LT.semver tuple, return false\n// - Else return true\n\nconst subset = (sub, dom, options = {}) => {\n if (sub === dom)\n return true\n\n sub = new Range(sub, options)\n dom = new Range(dom, options)\n let sawNonNull = false\n\n OUTER: for (const simpleSub of sub.set) {\n for (const simpleDom of dom.set) {\n const isSub = simpleSubset(simpleSub, simpleDom, options)\n sawNonNull = sawNonNull || isSub !== null\n if (isSub)\n continue OUTER\n }\n // the null set is a subset of everything, but null simple ranges in\n // a complex range should be ignored. so if we saw a non-null range,\n // then we know this isn't a subset, but if EVERY simple range was null,\n // then it is a subset.\n if (sawNonNull)\n return false\n }\n return true\n}\n\nconst simpleSubset = (sub, dom, options) => {\n if (sub === dom)\n return true\n\n if (sub.length === 1 && sub[0].semver === ANY) {\n if (dom.length === 1 && dom[0].semver === ANY)\n return true\n else if (options.includePrerelease)\n sub = [ new Comparator('>=0.0.0-0') ]\n else\n sub = [ new Comparator('>=0.0.0') ]\n }\n\n if (dom.length === 1 && dom[0].semver === ANY) {\n if (options.includePrerelease)\n return true\n else\n dom = [ new Comparator('>=0.0.0') ]\n }\n\n const eqSet = new Set()\n let gt, lt\n for (const c of sub) {\n if (c.operator === '>' || c.operator === '>=')\n gt = higherGT(gt, c, options)\n else if (c.operator === '<' || c.operator === '<=')\n lt = lowerLT(lt, c, options)\n else\n eqSet.add(c.semver)\n }\n\n if (eqSet.size > 1)\n return null\n\n let gtltComp\n if (gt && lt) {\n gtltComp = compare(gt.semver, lt.semver, options)\n if (gtltComp > 0)\n return null\n else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<='))\n return null\n }\n\n // will iterate one or zero times\n for (const eq of eqSet) {\n if (gt && !satisfies(eq, String(gt), options))\n return null\n\n if (lt && !satisfies(eq, String(lt), options))\n return null\n\n for (const c of dom) {\n if (!satisfies(eq, String(c), options))\n return false\n }\n\n return true\n }\n\n let higher, lower\n let hasDomLT, hasDomGT\n // if the subset has a prerelease, we need a comparator in the superset\n // with the same tuple and a prerelease, or it's not a subset\n let needDomLTPre = lt &&\n !options.includePrerelease &&\n lt.semver.prerelease.length ? lt.semver : false\n let needDomGTPre = gt &&\n !options.includePrerelease &&\n gt.semver.prerelease.length ? gt.semver : false\n // exception: <1.2.3-0 is the same as <1.2.3\n if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&\n lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {\n needDomLTPre = false\n }\n\n for (const c of dom) {\n hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='\n hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='\n if (gt) {\n if (needDomGTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomGTPre.major &&\n c.semver.minor === needDomGTPre.minor &&\n c.semver.patch === needDomGTPre.patch) {\n needDomGTPre = false\n }\n }\n if (c.operator === '>' || c.operator === '>=') {\n higher = higherGT(gt, c, options)\n if (higher === c && higher !== gt)\n return false\n } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options))\n return false\n }\n if (lt) {\n if (needDomLTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomLTPre.major &&\n c.semver.minor === needDomLTPre.minor &&\n c.semver.patch === needDomLTPre.patch) {\n needDomLTPre = false\n }\n }\n if (c.operator === '<' || c.operator === '<=') {\n lower = lowerLT(lt, c, options)\n if (lower === c && lower !== lt)\n return false\n } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options))\n return false\n }\n if (!c.operator && (lt || gt) && gtltComp !== 0)\n return false\n }\n\n // if there was a < or >, and nothing in the dom, then must be false\n // UNLESS it was limited by another range in the other direction.\n // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0\n if (gt && hasDomLT && !lt && gtltComp !== 0)\n return false\n\n if (lt && hasDomGT && !gt && gtltComp !== 0)\n return false\n\n // we needed a prerelease range in a specific tuple, but didn't get one\n // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,\n // because it includes prereleases in the 1.2.3 tuple\n if (needDomGTPre || needDomLTPre)\n return false\n\n return true\n}\n\n// >=1.2.3 is lower than >1.2.3\nconst higherGT = (a, b, options) => {\n if (!a)\n return b\n const comp = compare(a.semver, b.semver, options)\n return comp > 0 ? a\n : comp < 0 ? b\n : b.operator === '>' && a.operator === '>=' ? b\n : a\n}\n\n// <=1.2.3 is higher than <1.2.3\nconst lowerLT = (a, b, options) => {\n if (!a)\n return b\n const comp = compare(a.semver, b.semver, options)\n return comp < 0 ? a\n : comp > 0 ? b\n : b.operator === '<' && a.operator === '<=' ? b\n : a\n}\n\nmodule.exports = subset\n", "// just pre-load all the stuff that index.js lazily exports\nconst internalRe = require('./internal/re')\nmodule.exports = {\n re: internalRe.re,\n src: internalRe.src,\n tokens: internalRe.t,\n SEMVER_SPEC_VERSION: require('./internal/constants').SEMVER_SPEC_VERSION,\n SemVer: require('./classes/semver'),\n compareIdentifiers: require('./internal/identifiers').compareIdentifiers,\n rcompareIdentifiers: require('./internal/identifiers').rcompareIdentifiers,\n parse: require('./functions/parse'),\n valid: require('./functions/valid'),\n clean: require('./functions/clean'),\n inc: require('./functions/inc'),\n diff: require('./functions/diff'),\n major: require('./functions/major'),\n minor: require('./functions/minor'),\n patch: require('./functions/patch'),\n prerelease: require('./functions/prerelease'),\n compare: require('./functions/compare'),\n rcompare: require('./functions/rcompare'),\n compareLoose: require('./functions/compare-loose'),\n compareBuild: require('./functions/compare-build'),\n sort: require('./functions/sort'),\n rsort: require('./functions/rsort'),\n gt: require('./functions/gt'),\n lt: require('./functions/lt'),\n eq: require('./functions/eq'),\n neq: require('./functions/neq'),\n gte: require('./functions/gte'),\n lte: require('./functions/lte'),\n cmp: require('./functions/cmp'),\n coerce: require('./functions/coerce'),\n Comparator: require('./classes/comparator'),\n Range: require('./classes/range'),\n satisfies: require('./functions/satisfies'),\n toComparators: require('./ranges/to-comparators'),\n maxSatisfying: require('./ranges/max-satisfying'),\n minSatisfying: require('./ranges/min-satisfying'),\n minVersion: require('./ranges/min-version'),\n validRange: require('./ranges/valid'),\n outside: require('./ranges/outside'),\n gtr: require('./ranges/gtr'),\n ltr: require('./ranges/ltr'),\n intersects: require('./ranges/intersects'),\n simplifyRange: require('./ranges/simplify'),\n subset: require('./ranges/subset'),\n}\n", "module.exports = require('stream');\n", "'use strict';\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nvar _require = require('buffer'),\n Buffer = _require.Buffer;\n\nvar _require2 = require('util'),\n inspect = _require2.inspect;\n\nvar custom = inspect && inspect.custom || 'inspect';\n\nfunction copyBuffer(src, target, offset) {\n Buffer.prototype.copy.call(src, target, offset);\n}\n\nmodule.exports =\n/*#__PURE__*/\nfunction () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n _createClass(BufferList, [{\n key: \"push\",\n value: function push(v) {\n var entry = {\n data: v,\n next: null\n };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n }\n }, {\n key: \"unshift\",\n value: function unshift(v) {\n var entry = {\n data: v,\n next: this.head\n };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n }\n }, {\n key: \"shift\",\n value: function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n }\n }, {\n key: \"clear\",\n value: function clear() {\n this.head = this.tail = null;\n this.length = 0;\n }\n }, {\n key: \"join\",\n value: function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n\n while (p = p.next) {\n ret += s + p.data;\n }\n\n return ret;\n }\n }, {\n key: \"concat\",\n value: function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n\n return ret;\n } // Consumes a specified amount of bytes or characters from the buffered data.\n\n }, {\n key: \"consume\",\n value: function consume(n, hasStrings) {\n var ret;\n\n if (n < this.head.data.length) {\n // `slice` is the same for buffers and strings.\n ret = this.head.data.slice(0, n);\n this.head.data = this.head.data.slice(n);\n } else if (n === this.head.data.length) {\n // First chunk is a perfect match.\n ret = this.shift();\n } else {\n // Result spans more than one buffer.\n ret = hasStrings ? this._getString(n) : this._getBuffer(n);\n }\n\n return ret;\n }\n }, {\n key: \"first\",\n value: function first() {\n return this.head.data;\n } // Consumes a specified amount of characters from the buffered data.\n\n }, {\n key: \"_getString\",\n value: function _getString(n) {\n var p = this.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = str.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Consumes a specified amount of bytes from the buffered data.\n\n }, {\n key: \"_getBuffer\",\n value: function _getBuffer(n) {\n var ret = Buffer.allocUnsafe(n);\n var p = this.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = buf.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Make sure the linked list only shows the minimal necessary information.\n\n }, {\n key: custom,\n value: function value(_, options) {\n return inspect(this, _objectSpread({}, options, {\n // Only inspect one level.\n depth: 0,\n // It should not recurse.\n customInspect: false\n }));\n }\n }]);\n\n return BufferList;\n}();", "'use strict'; // undocumented cb() API, needed for core, not for public API\n\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n process.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n process.nextTick(emitErrorNT, this, err);\n }\n }\n\n return this;\n } // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n } // if this is a duplex stream mark the writable part as destroyed as well\n\n\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n } else if (cb) {\n process.nextTick(emitCloseNT, _this);\n cb(err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n });\n\n return this;\n}\n\nfunction emitErrorAndCloseNT(self, err) {\n emitErrorNT(self, err);\n emitCloseNT(self);\n}\n\nfunction emitCloseNT(self) {\n if (self._writableState && !self._writableState.emitClose) return;\n if (self._readableState && !self._readableState.emitClose) return;\n self.emit('close');\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nfunction errorOrDestroy(stream, err) {\n // We have tests that rely on errors being emitted\n // in the same tick, so changing this is semver major.\n // For now when you opt-in to autoDestroy we allow\n // the error to be emitted nextTick. In a future\n // semver major update we should change the default to this.\n var rState = stream._readableState;\n var wState = stream._writableState;\n if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy,\n errorOrDestroy: errorOrDestroy\n};", "'use strict';\n\nconst codes = {};\n\nfunction createErrorType(code, message, Base) {\n if (!Base) {\n Base = Error\n }\n\n function getMessage (arg1, arg2, arg3) {\n if (typeof message === 'string') {\n return message\n } else {\n return message(arg1, arg2, arg3)\n }\n }\n\n class NodeError extends Base {\n constructor (arg1, arg2, arg3) {\n super(getMessage(arg1, arg2, arg3));\n }\n }\n\n NodeError.prototype.name = Base.name;\n NodeError.prototype.code = code;\n\n codes[code] = NodeError;\n}\n\n// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js\nfunction oneOf(expected, thing) {\n if (Array.isArray(expected)) {\n const len = expected.length;\n expected = expected.map((i) => String(i));\n if (len > 2) {\n return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` +\n expected[len - 1];\n } else if (len === 2) {\n return `one of ${thing} ${expected[0]} or ${expected[1]}`;\n } else {\n return `of ${thing} ${expected[0]}`;\n }\n } else {\n return `of ${thing} ${String(expected)}`;\n }\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith\nfunction startsWith(str, search, pos) {\n\treturn str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\nfunction endsWith(str, search, this_len) {\n\tif (this_len === undefined || this_len > str.length) {\n\t\tthis_len = str.length;\n\t}\n\treturn str.substring(this_len - search.length, this_len) === search;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\nfunction includes(str, search, start) {\n if (typeof start !== 'number') {\n start = 0;\n }\n\n if (start + search.length > str.length) {\n return false;\n } else {\n return str.indexOf(search, start) !== -1;\n }\n}\n\ncreateErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {\n return 'The value \"' + value + '\" is invalid for option \"' + name + '\"'\n}, TypeError);\ncreateErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {\n // determiner: 'must be' or 'must not be'\n let determiner;\n if (typeof expected === 'string' && startsWith(expected, 'not ')) {\n determiner = 'must not be';\n expected = expected.replace(/^not /, '');\n } else {\n determiner = 'must be';\n }\n\n let msg;\n if (endsWith(name, ' argument')) {\n // For cases like 'first argument'\n msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;\n } else {\n const type = includes(name, '.') ? 'property' : 'argument';\n msg = `The \"${name}\" ${type} ${determiner} ${oneOf(expected, 'type')}`;\n }\n\n msg += `. Received type ${typeof actual}`;\n return msg;\n}, TypeError);\ncreateErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');\ncreateErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {\n return 'The ' + name + ' method is not implemented'\n});\ncreateErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');\ncreateErrorType('ERR_STREAM_DESTROYED', function (name) {\n return 'Cannot call ' + name + ' after a stream was destroyed';\n});\ncreateErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');\ncreateErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');\ncreateErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');\ncreateErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);\ncreateErrorType('ERR_UNKNOWN_ENCODING', function (arg) {\n return 'Unknown encoding: ' + arg\n}, TypeError);\ncreateErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');\n\nmodule.exports.codes = codes;\n", "'use strict';\n\nvar ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;\n\nfunction highWaterMarkFrom(options, isDuplex, duplexKey) {\n return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;\n}\n\nfunction getHighWaterMark(state, options, duplexKey, isDuplex) {\n var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);\n\n if (hwm != null) {\n if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {\n var name = isDuplex ? duplexKey : 'highWaterMark';\n throw new ERR_INVALID_OPT_VALUE(name, hwm);\n }\n\n return Math.floor(hwm);\n } // Default value\n\n\n return state.objectMode ? 16 : 16 * 1024;\n}\n\nmodule.exports = {\n getHighWaterMark: getHighWaterMark\n};", "if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n", "try {\n var util = require('util');\n /* istanbul ignore next */\n if (typeof util.inherits !== 'function') throw '';\n module.exports = util.inherits;\n} catch (e) {\n /* istanbul ignore next */\n module.exports = require('./inherits_browser.js');\n}\n", "\n/**\n * For Node.js, simply re-export the core `util.deprecate` function.\n */\n\nmodule.exports = require('util').deprecate;\n", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n'use strict';\n\nmodule.exports = Writable;\n/* <replacement> */\n\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n} // It seems a linked list but it is not\n// there will be only 2 of these for each stream\n\n\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* </replacement> */\n\n/*<replacement>*/\n\n\nvar Duplex;\n/*</replacement>*/\n\nWritable.WritableState = WritableState;\n/*<replacement>*/\n\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/*</replacement>*/\n\n/*<replacement>*/\n\nvar Stream = require('./internal/streams/stream');\n/*</replacement>*/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,\n ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,\n ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,\n ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\n\nrequire('inherits')(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream,\n // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n\n this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called\n\n this.finalCalled = false; // drain event flag.\n\n this.needDrain = false; // at the start of calling end()\n\n this.ending = false; // when end() has been called, and returned\n\n this.ended = false; // when 'finish' is emitted\n\n this.finished = false; // has it been destroyed\n\n this.destroyed = false; // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n\n this.length = 0; // a flag to see when we're in the middle of a write.\n\n this.writing = false; // when true all writes will be buffered until .uncork() call\n\n this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n\n this.sync = true; // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n\n this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)\n\n this.onwrite = function (er) {\n onwrite(stream, er);\n }; // the callback that the user supplies to write(chunk,encoding,cb)\n\n\n this.writecb = null; // the amount that is being written when _write is called.\n\n this.writelen = 0;\n this.bufferedRequest = null;\n this.lastBufferedRequest = null; // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n\n this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n\n this.prefinished = false; // True if the error was already emitted and should not be thrown again\n\n this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')\n\n this.autoDestroy = !!options.autoDestroy; // count buffered requests\n\n this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n\n while (current) {\n out.push(current);\n current = current.next;\n }\n\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function writableStateBufferGetter() {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})(); // Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\n\n\nvar realHasInstance;\n\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function value(object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function realHasInstance(object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the WritableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);\n this._writableState = new WritableState(options, this, isDuplex); // legacy.\n\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n if (typeof options.writev === 'function') this._writev = options.writev;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n} // Otherwise people can pipe Writable streams, which is just wrong.\n\n\nWritable.prototype.pipe = function () {\n errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb\n\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n} // Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\n\n\nfunction validChunk(stream, state, chunk, cb) {\n var er;\n\n if (chunk === null) {\n er = new ERR_STREAM_NULL_VALUES();\n } else if (typeof chunk !== 'string' && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);\n }\n\n if (er) {\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n return false;\n }\n\n return true;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n if (typeof cb !== 'function') cb = nop;\n if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n return ret;\n};\n\nWritable.prototype.cork = function () {\n this._writableState.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n}); // if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\n\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n\n var len = state.objectMode ? 1 : chunk.length;\n state.length += len;\n var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.\n\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n process.nextTick(cb, er); // this can emit finish, and it will always happen\n // after error\n\n process.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er); // this can emit finish, but finish must\n // always follow error\n\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();\n onwriteStateUpdate(state);\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state) || stream.destroyed;\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n process.nextTick(afterWrite, stream, state, finished, cb);\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n} // Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\n\n\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n} // if there's something in the buffer waiting, then process it\n\n\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n var count = 0;\n var allBuffers = true;\n\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n\n buffer.allBuffers = allBuffers;\n doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n\n state.pendingcb++;\n state.lastBufferedRequest = null;\n\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks\n\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n } // ignore unnecessary end() calls.\n\n\n if (!state.ending) endWritable(this, state, cb);\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n});\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\n\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n\n if (err) {\n errorOrDestroy(stream, err);\n }\n\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\n\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function' && !state.destroyed) {\n state.pendingcb++;\n state.finalCalled = true;\n process.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n\n if (need) {\n prefinish(stream, state);\n\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the readable side is ready for autoDestroy as well\n var rState = stream._readableState;\n\n if (!rState || rState.autoDestroy && rState.endEmitted) {\n stream.destroy();\n }\n }\n }\n }\n\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n\n if (cb) {\n if (state.finished) process.nextTick(cb);else stream.once('finish', cb);\n }\n\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n } // reuse the free corkReq.\n\n\n state.corkedRequestsFree.next = corkReq;\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._writableState === undefined) {\n return false;\n }\n\n return this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._writableState.destroyed = value;\n }\n});\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\n\nWritable.prototype._destroy = function (err, cb) {\n cb(err);\n};", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n'use strict';\n/*<replacement>*/\n\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n\n for (var key in obj) {\n keys.push(key);\n }\n\n return keys;\n};\n/*</replacement>*/\n\n\nmodule.exports = Duplex;\n\nvar Readable = require('./_stream_readable');\n\nvar Writable = require('./_stream_writable');\n\nrequire('inherits')(Duplex, Readable);\n\n{\n // Allow the keys array to be GC'ed.\n var keys = objectKeys(Writable.prototype);\n\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n Readable.call(this, options);\n Writable.call(this, options);\n this.allowHalfOpen = true;\n\n if (options) {\n if (options.readable === false) this.readable = false;\n if (options.writable === false) this.writable = false;\n\n if (options.allowHalfOpen === false) {\n this.allowHalfOpen = false;\n this.once('end', onend);\n }\n }\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n}); // the no-half-open enforcer\n\nfunction onend() {\n // If the writable side ended, then we're ok.\n if (this._writableState.ended) return; // no more data can be written.\n // But allow more writes to happen in this tick.\n\n process.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});", "/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/*<replacement>*/\n\nvar Buffer = require('safe-buffer').Buffer;\n/*</replacement>*/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}", "// Ported from https://github.com/mafintosh/end-of-stream with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n callback.apply(this, args);\n };\n}\n\nfunction noop() {}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction eos(stream, opts, callback) {\n if (typeof opts === 'function') return eos(stream, null, opts);\n if (!opts) opts = {};\n callback = once(callback || noop);\n var readable = opts.readable || opts.readable !== false && stream.readable;\n var writable = opts.writable || opts.writable !== false && stream.writable;\n\n var onlegacyfinish = function onlegacyfinish() {\n if (!stream.writable) onfinish();\n };\n\n var writableEnded = stream._writableState && stream._writableState.finished;\n\n var onfinish = function onfinish() {\n writable = false;\n writableEnded = true;\n if (!readable) callback.call(stream);\n };\n\n var readableEnded = stream._readableState && stream._readableState.endEmitted;\n\n var onend = function onend() {\n readable = false;\n readableEnded = true;\n if (!writable) callback.call(stream);\n };\n\n var onerror = function onerror(err) {\n callback.call(stream, err);\n };\n\n var onclose = function onclose() {\n var err;\n\n if (readable && !readableEnded) {\n if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n\n if (writable && !writableEnded) {\n if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n };\n\n var onrequest = function onrequest() {\n stream.req.on('finish', onfinish);\n };\n\n if (isRequest(stream)) {\n stream.on('complete', onfinish);\n stream.on('abort', onclose);\n if (stream.req) onrequest();else stream.on('request', onrequest);\n } else if (writable && !stream._writableState) {\n // legacy streams\n stream.on('end', onlegacyfinish);\n stream.on('close', onlegacyfinish);\n }\n\n stream.on('end', onend);\n stream.on('finish', onfinish);\n if (opts.error !== false) stream.on('error', onerror);\n stream.on('close', onclose);\n return function () {\n stream.removeListener('complete', onfinish);\n stream.removeListener('abort', onclose);\n stream.removeListener('request', onrequest);\n if (stream.req) stream.req.removeListener('finish', onfinish);\n stream.removeListener('end', onlegacyfinish);\n stream.removeListener('close', onlegacyfinish);\n stream.removeListener('finish', onfinish);\n stream.removeListener('end', onend);\n stream.removeListener('error', onerror);\n stream.removeListener('close', onclose);\n };\n}\n\nmodule.exports = eos;", "'use strict';\n\nvar _Object$setPrototypeO;\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar finished = require('./end-of-stream');\n\nvar kLastResolve = Symbol('lastResolve');\nvar kLastReject = Symbol('lastReject');\nvar kError = Symbol('error');\nvar kEnded = Symbol('ended');\nvar kLastPromise = Symbol('lastPromise');\nvar kHandlePromise = Symbol('handlePromise');\nvar kStream = Symbol('stream');\n\nfunction createIterResult(value, done) {\n return {\n value: value,\n done: done\n };\n}\n\nfunction readAndResolve(iter) {\n var resolve = iter[kLastResolve];\n\n if (resolve !== null) {\n var data = iter[kStream].read(); // we defer if data is null\n // we can be expecting either 'end' or\n // 'error'\n\n if (data !== null) {\n iter[kLastPromise] = null;\n iter[kLastResolve] = null;\n iter[kLastReject] = null;\n resolve(createIterResult(data, false));\n }\n }\n}\n\nfunction onReadable(iter) {\n // we wait for the next tick, because it might\n // emit an error with process.nextTick\n process.nextTick(readAndResolve, iter);\n}\n\nfunction wrapForNext(lastPromise, iter) {\n return function (resolve, reject) {\n lastPromise.then(function () {\n if (iter[kEnded]) {\n resolve(createIterResult(undefined, true));\n return;\n }\n\n iter[kHandlePromise](resolve, reject);\n }, reject);\n };\n}\n\nvar AsyncIteratorPrototype = Object.getPrototypeOf(function () {});\nvar ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {\n get stream() {\n return this[kStream];\n },\n\n next: function next() {\n var _this = this;\n\n // if we have detected an error in the meanwhile\n // reject straight away\n var error = this[kError];\n\n if (error !== null) {\n return Promise.reject(error);\n }\n\n if (this[kEnded]) {\n return Promise.resolve(createIterResult(undefined, true));\n }\n\n if (this[kStream].destroyed) {\n // We need to defer via nextTick because if .destroy(err) is\n // called, the error will be emitted via nextTick, and\n // we cannot guarantee that there is no error lingering around\n // waiting to be emitted.\n return new Promise(function (resolve, reject) {\n process.nextTick(function () {\n if (_this[kError]) {\n reject(_this[kError]);\n } else {\n resolve(createIterResult(undefined, true));\n }\n });\n });\n } // if we have multiple next() calls\n // we will wait for the previous Promise to finish\n // this logic is optimized to support for await loops,\n // where next() is only called once at a time\n\n\n var lastPromise = this[kLastPromise];\n var promise;\n\n if (lastPromise) {\n promise = new Promise(wrapForNext(lastPromise, this));\n } else {\n // fast path needed to support multiple this.push()\n // without triggering the next() queue\n var data = this[kStream].read();\n\n if (data !== null) {\n return Promise.resolve(createIterResult(data, false));\n }\n\n promise = new Promise(this[kHandlePromise]);\n }\n\n this[kLastPromise] = promise;\n return promise;\n }\n}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {\n return this;\n}), _defineProperty(_Object$setPrototypeO, \"return\", function _return() {\n var _this2 = this;\n\n // destroy(err, cb) is a private API\n // we can guarantee we have that here, because we control the\n // Readable class this is attached to\n return new Promise(function (resolve, reject) {\n _this2[kStream].destroy(null, function (err) {\n if (err) {\n reject(err);\n return;\n }\n\n resolve(createIterResult(undefined, true));\n });\n });\n}), _Object$setPrototypeO), AsyncIteratorPrototype);\n\nvar createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {\n var _Object$create;\n\n var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {\n value: stream,\n writable: true\n }), _defineProperty(_Object$create, kLastResolve, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kLastReject, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kError, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kEnded, {\n value: stream._readableState.endEmitted,\n writable: true\n }), _defineProperty(_Object$create, kHandlePromise, {\n value: function value(resolve, reject) {\n var data = iterator[kStream].read();\n\n if (data) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(data, false));\n } else {\n iterator[kLastResolve] = resolve;\n iterator[kLastReject] = reject;\n }\n },\n writable: true\n }), _Object$create));\n iterator[kLastPromise] = null;\n finished(stream, function (err) {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise\n // returned by next() and store the error\n\n if (reject !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n reject(err);\n }\n\n iterator[kError] = err;\n return;\n }\n\n var resolve = iterator[kLastResolve];\n\n if (resolve !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(undefined, true));\n }\n\n iterator[kEnded] = true;\n });\n stream.on('readable', onReadable.bind(null, iterator));\n return iterator;\n};\n\nmodule.exports = createReadableStreamAsyncIterator;", "'use strict';\n\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }\n\nfunction _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err); } _next(undefined); }); }; }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE;\n\nfunction from(Readable, iterable, opts) {\n var iterator;\n\n if (iterable && typeof iterable.next === 'function') {\n iterator = iterable;\n } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable);\n\n var readable = new Readable(_objectSpread({\n objectMode: true\n }, opts)); // Reading boolean to protect against _read\n // being called before last iteration completion.\n\n var reading = false;\n\n readable._read = function () {\n if (!reading) {\n reading = true;\n next();\n }\n };\n\n function next() {\n return _next2.apply(this, arguments);\n }\n\n function _next2() {\n _next2 = _asyncToGenerator(function* () {\n try {\n var _ref = yield iterator.next(),\n value = _ref.value,\n done = _ref.done;\n\n if (done) {\n readable.push(null);\n } else if (readable.push((yield value))) {\n next();\n } else {\n reading = false;\n }\n } catch (err) {\n readable.destroy(err);\n }\n });\n return _next2.apply(this, arguments);\n }\n\n return readable;\n}\n\nmodule.exports = from;", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n'use strict';\n\nmodule.exports = Readable;\n/*<replacement>*/\n\nvar Duplex;\n/*</replacement>*/\n\nReadable.ReadableState = ReadableState;\n/*<replacement>*/\n\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function EElistenerCount(emitter, type) {\n return emitter.listeners(type).length;\n};\n/*</replacement>*/\n\n/*<replacement>*/\n\n\nvar Stream = require('./internal/streams/stream');\n/*</replacement>*/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n/*<replacement>*/\n\n\nvar debugUtil = require('util');\n\nvar debug;\n\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function debug() {};\n}\n/*</replacement>*/\n\n\nvar BufferList = require('./internal/streams/buffer_list');\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.\n\n\nvar StringDecoder;\nvar createReadableStreamAsyncIterator;\nvar from;\n\nrequire('inherits')(Readable, Stream);\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n\n this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n\n this.sync = true; // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n this.paused = true; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')\n\n this.autoDestroy = !!options.autoDestroy; // has it been destroyed\n\n this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s\n\n this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled\n\n this.readingMore = false;\n this.decoder = null;\n this.encoding = null;\n\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside\n // the ReadableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n this._readableState = new ReadableState(options, this, isDuplex); // legacy\n\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n }\n});\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\n\nReadable.prototype._destroy = function (err, cb) {\n cb(err);\n}; // Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\n\n\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n}; // Unshift should *always* be something directly out of read()\n\n\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n debug('readableAddChunk', chunk);\n var state = stream._readableState;\n\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n\n if (er) {\n errorOrDestroy(stream, er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());\n } else if (state.destroyed) {\n return false;\n } else {\n state.reading = false;\n\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n maybeReadMore(stream, state);\n }\n } // We can push more data if we are below the highWaterMark.\n // Also, if we have no data yet, we can stand some more bytes.\n // This is to work around cases where hwm=0, such as the repl.\n\n\n return !state.ended && (state.length < state.highWaterMark || state.length === 0);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n state.awaitDrain = 0;\n stream.emit('data', chunk);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n if (state.needReadable) emitReadable(stream);\n }\n\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);\n }\n\n return er;\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n}; // backwards compatibility.\n\n\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n var decoder = new StringDecoder(enc);\n this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8\n\n this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:\n\n var p = this._readableState.buffer.head;\n var content = '';\n\n while (p !== null) {\n content += decoder.write(p.data);\n p = p.next;\n }\n\n this._readableState.buffer.clear();\n\n if (content !== '') this._readableState.buffer.push(content);\n this._readableState.length = content.length;\n return this;\n}; // Don't raise the hwm > 1GB\n\n\nvar MAX_HWM = 0x40000000;\n\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n\n return n;\n} // This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\n\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n } // If we're asking for more than the current hwm, then raise the hwm.\n\n\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n; // Don't have enough\n\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n\n return state.length;\n} // you can override either this method, or the async _read(n) below.\n\n\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n\n if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.\n\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n } // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n // if we need a readable event, then we need to do some reading.\n\n\n var doRead = state.needReadable;\n debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some\n\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n } // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n\n\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true; // if the length is currently zero, then we *need* a readable event.\n\n if (state.length === 0) state.needReadable = true; // call internal read method\n\n this._read(state.highWaterMark);\n\n state.sync = false; // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = state.length <= state.highWaterMark;\n n = 0;\n } else {\n state.length -= n;\n state.awaitDrain = 0;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.\n\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n debug('onEofChunk');\n if (state.ended) return;\n\n if (state.decoder) {\n var chunk = state.decoder.end();\n\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n\n state.ended = true;\n\n if (state.sync) {\n // if we are sync, wait until next tick to emit the data.\n // Otherwise we risk emitting data in the flow()\n // the readable code triggers during a read() call\n emitReadable(stream);\n } else {\n // emit 'readable' now to make sure it gets picked up.\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n state.emittedReadable = true;\n emitReadable_(stream);\n }\n }\n} // Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\n\n\nfunction emitReadable(stream) {\n var state = stream._readableState;\n debug('emitReadable', state.needReadable, state.emittedReadable);\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n process.nextTick(emitReadable_, stream);\n }\n}\n\nfunction emitReadable_(stream) {\n var state = stream._readableState;\n debug('emitReadable_', state.destroyed, state.length, state.ended);\n\n if (!state.destroyed && (state.length || state.ended)) {\n stream.emit('readable');\n state.emittedReadable = false;\n } // The stream needs another readable event if\n // 1. It is not flowing, as the flow mechanism will take\n // care of it.\n // 2. It is not ended.\n // 3. It is below the highWaterMark, so we can schedule\n // another readable later.\n\n\n state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;\n flow(stream);\n} // at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\n\n\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n process.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n // Attempt to read more data if we should.\n //\n // The conditions for reading more data are (one of):\n // - Not enough data buffered (state.length < state.highWaterMark). The loop\n // is responsible for filling the buffer with enough data if such data\n // is available. If highWaterMark is 0 and we are not in the flowing mode\n // we should _not_ attempt to buffer any extra data. We'll get more data\n // when the stream consumer calls read() instead.\n // - No data in the buffer, and the stream is in flowing mode. In this mode\n // the loop below is responsible for ensuring read() is called. Failing to\n // call read here would abort the flow and there's no other mechanism for\n // continuing the flow if the stream consumer has just subscribed to the\n // 'data' event.\n //\n // In addition to the above conditions to keep reading data, the following\n // conditions prevent the data from being read:\n // - The stream has ended (state.ended).\n // - There is already a pending 'read' operation (state.reading). This is a\n // case where the the stream has called the implementation defined _read()\n // method, but they are processing the call asynchronously and have _not_\n // called push() with new data. In this case we skip performing more\n // read()s. The execution ends in this method again after the _read() ends\n // up calling push() with more data.\n while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {\n var len = state.length;\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length) // didn't get any data, stop spinning.\n break;\n }\n\n state.readingMore = false;\n} // abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\n\n\nReadable.prototype._read = function (n) {\n errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n\n default:\n state.pipes.push(dest);\n break;\n }\n\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);\n dest.on('unpipe', onunpipe);\n\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n } // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n\n\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n var cleanedUp = false;\n\n function cleanup() {\n debug('cleanup'); // cleanup event handlers once the pipe is broken\n\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n cleanedUp = true; // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n src.on('data', ondata);\n\n function ondata(chunk) {\n debug('ondata');\n var ret = dest.write(chunk);\n debug('dest.write', ret);\n\n if (ret === false) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n }\n\n src.pause();\n }\n } // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n\n\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);\n } // Make sure our error handler is attached before userland ones.\n\n\n prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.\n\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n\n dest.once('close', onclose);\n\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n } // tell the dest that it's being piped to\n\n\n dest.emit('pipe', src); // start the flow if it hasn't been started already.\n\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function pipeOnDrainFunctionResult() {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = {\n hasUnpiped: false\n }; // if we're not piping anywhere, then do nothing.\n\n if (state.pipesCount === 0) return this; // just one destination. most common case.\n\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n if (!dest) dest = state.pipes; // got a match.\n\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n } // slow case. multiple pipe destinations.\n\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, {\n hasUnpiped: false\n });\n }\n\n return this;\n } // try to find the right one.\n\n\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n dest.emit('unpipe', this, unpipeInfo);\n return this;\n}; // set up data events if they are asked for\n// Ensure readable listeners eventually get something\n\n\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n var state = this._readableState;\n\n if (ev === 'data') {\n // update readableListening so that resume() may be a no-op\n // a few lines down. This is needed to support once('readable').\n state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused\n\n if (state.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.flowing = false;\n state.emittedReadable = false;\n debug('on readable', state.length, state.reading);\n\n if (state.length) {\n emitReadable(this);\n } else if (!state.reading) {\n process.nextTick(nReadingNextTick, this);\n }\n }\n }\n\n return res;\n};\n\nReadable.prototype.addListener = Readable.prototype.on;\n\nReadable.prototype.removeListener = function (ev, fn) {\n var res = Stream.prototype.removeListener.call(this, ev, fn);\n\n if (ev === 'readable') {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nReadable.prototype.removeAllListeners = function (ev) {\n var res = Stream.prototype.removeAllListeners.apply(this, arguments);\n\n if (ev === 'readable' || ev === undefined) {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nfunction updateReadableListening(self) {\n var state = self._readableState;\n state.readableListening = self.listenerCount('readable') > 0;\n\n if (state.resumeScheduled && !state.paused) {\n // flowing needs to be set to true now, otherwise\n // the upcoming resume will not flow.\n state.flowing = true; // crude way to check if we should resume\n } else if (self.listenerCount('data') > 0) {\n self.resume();\n }\n}\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n} // pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\n\n\nReadable.prototype.resume = function () {\n var state = this._readableState;\n\n if (!state.flowing) {\n debug('resume'); // we flow only if there is no one listening\n // for readable, but we still have to call\n // resume()\n\n state.flowing = !state.readableListening;\n resume(this, state);\n }\n\n state.paused = false;\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n process.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n debug('resume', state.reading);\n\n if (!state.reading) {\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n\n if (this._readableState.flowing !== false) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n\n this._readableState.paused = true;\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n\n while (state.flowing && stream.read() !== null) {\n ;\n }\n} // wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\n\n\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n stream.on('end', function () {\n debug('wrapped end');\n\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode\n\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n\n if (!ret) {\n paused = true;\n stream.pause();\n }\n }); // proxy all the other methods.\n // important when wrapping filters and duplexes.\n\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function methodWrap(method) {\n return function methodWrapReturnFunction() {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n } // proxy certain important events.\n\n\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n } // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n\n\n this._read = function (n) {\n debug('wrapped _read', n);\n\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nif (typeof Symbol === 'function') {\n Readable.prototype[Symbol.asyncIterator] = function () {\n if (createReadableStreamAsyncIterator === undefined) {\n createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');\n }\n\n return createReadableStreamAsyncIterator(this);\n };\n}\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.highWaterMark;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState && this._readableState.buffer;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableFlowing', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.flowing;\n },\n set: function set(state) {\n if (this._readableState) {\n this._readableState.flowing = state;\n }\n }\n}); // exposed for testing purposes only.\n\nReadable._fromList = fromList;\nObject.defineProperty(Readable.prototype, 'readableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.length;\n }\n}); // Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = state.buffer.consume(n, state.decoder);\n }\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n debug('endReadable', state.endEmitted);\n\n if (!state.endEmitted) {\n state.ended = true;\n process.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.\n\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the writable side is ready for autoDestroy as well\n var wState = stream._writableState;\n\n if (!wState || wState.autoDestroy && wState.finished) {\n stream.destroy();\n }\n }\n }\n}\n\nif (typeof Symbol === 'function') {\n Readable.from = function (iterable, opts) {\n if (from === undefined) {\n from = require('./internal/streams/from');\n }\n\n return from(Readable, iterable, opts);\n };\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n\n return -1;\n}", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n'use strict';\n\nmodule.exports = Transform;\n\nvar _require$codes = require('../errors').codes,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,\n ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;\n\nvar Duplex = require('./_stream_duplex');\n\nrequire('inherits')(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n var cb = ts.writecb;\n\n if (cb === null) {\n return this.emit('error', new ERR_MULTIPLE_CALLBACK());\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n cb(er);\n var rs = this._readableState;\n rs.reading = false;\n\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n Duplex.call(this, options);\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n }; // start out asking for a readable event once data is transformed.\n\n this._readableState.needReadable = true; // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n if (typeof options.flush === 'function') this._flush = options.flush;\n } // When the writable side finishes, then flush out anything remaining.\n\n\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function' && !this._readableState.destroyed) {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n}; // This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\n\n\nTransform.prototype._transform = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n}; // Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\n\n\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && !ts.transforming) {\n ts.transforming = true;\n\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data); // TODO(BridgeAR): Write a test for these two error cases\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n\n if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();\n if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();\n return stream.push(null);\n}", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\nrequire('inherits')(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};", "// Ported from https://github.com/mafintosh/pump with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar eos;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n callback.apply(void 0, arguments);\n };\n}\n\nvar _require$codes = require('../../../errors').codes,\n ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;\n\nfunction noop(err) {\n // Rethrow the error if it exists to avoid swallowing it\n if (err) throw err;\n}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction destroyer(stream, reading, writing, callback) {\n callback = once(callback);\n var closed = false;\n stream.on('close', function () {\n closed = true;\n });\n if (eos === undefined) eos = require('./end-of-stream');\n eos(stream, {\n readable: reading,\n writable: writing\n }, function (err) {\n if (err) return callback(err);\n closed = true;\n callback();\n });\n var destroyed = false;\n return function (err) {\n if (closed) return;\n if (destroyed) return;\n destroyed = true; // request.destroy just do .end - .abort is what we want\n\n if (isRequest(stream)) return stream.abort();\n if (typeof stream.destroy === 'function') return stream.destroy();\n callback(err || new ERR_STREAM_DESTROYED('pipe'));\n };\n}\n\nfunction call(fn) {\n fn();\n}\n\nfunction pipe(from, to) {\n return from.pipe(to);\n}\n\nfunction popCallback(streams) {\n if (!streams.length) return noop;\n if (typeof streams[streams.length - 1] !== 'function') return noop;\n return streams.pop();\n}\n\nfunction pipeline() {\n for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {\n streams[_key] = arguments[_key];\n }\n\n var callback = popCallback(streams);\n if (Array.isArray(streams[0])) streams = streams[0];\n\n if (streams.length < 2) {\n throw new ERR_MISSING_ARGS('streams');\n }\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 return streams.reduce(pipe);\n}\n\nmodule.exports = pipeline;", "var Stream = require('stream');\nif (process.env.READABLE_STREAM === 'disable' && Stream) {\n module.exports = Stream.Readable;\n Object.assign(module.exports, Stream);\n module.exports.Stream = Stream;\n} else {\n exports = module.exports = require('./lib/_stream_readable.js');\n exports.Stream = Stream || exports;\n exports.Readable = exports;\n exports.Writable = require('./lib/_stream_writable.js');\n exports.Duplex = require('./lib/_stream_duplex.js');\n exports.Transform = require('./lib/_stream_transform.js');\n exports.PassThrough = require('./lib/_stream_passthrough.js');\n exports.finished = require('./lib/internal/streams/end-of-stream.js');\n exports.pipeline = require('./lib/internal/streams/pipeline.js');\n}\n", "'use strict'\n\nconst { Buffer } = require('buffer')\nconst symbol = Symbol.for('BufferList')\n\nfunction BufferList (buf) {\n if (!(this instanceof BufferList)) {\n return new BufferList(buf)\n }\n\n BufferList._init.call(this, buf)\n}\n\nBufferList._init = function _init (buf) {\n Object.defineProperty(this, symbol, { value: true })\n\n this._bufs = []\n this.length = 0\n\n if (buf) {\n this.append(buf)\n }\n}\n\nBufferList.prototype._new = function _new (buf) {\n return new BufferList(buf)\n}\n\nBufferList.prototype._offset = function _offset (offset) {\n if (offset === 0) {\n return [0, 0]\n }\n\n let tot = 0\n\n for (let i = 0; i < this._bufs.length; i++) {\n const _t = tot + this._bufs[i].length\n if (offset < _t || i === this._bufs.length - 1) {\n return [i, offset - tot]\n }\n tot = _t\n }\n}\n\nBufferList.prototype._reverseOffset = function (blOffset) {\n const bufferId = blOffset[0]\n let offset = blOffset[1]\n\n for (let i = 0; i < bufferId; i++) {\n offset += this._bufs[i].length\n }\n\n return offset\n}\n\nBufferList.prototype.get = function get (index) {\n if (index > this.length || index < 0) {\n return undefined\n }\n\n const offset = this._offset(index)\n\n return this._bufs[offset[0]][offset[1]]\n}\n\nBufferList.prototype.slice = function slice (start, end) {\n if (typeof start === 'number' && start < 0) {\n start += this.length\n }\n\n if (typeof end === 'number' && end < 0) {\n end += this.length\n }\n\n return this.copy(null, 0, start, end)\n}\n\nBufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {\n if (typeof srcStart !== 'number' || srcStart < 0) {\n srcStart = 0\n }\n\n if (typeof srcEnd !== 'number' || srcEnd > this.length) {\n srcEnd = this.length\n }\n\n if (srcStart >= this.length) {\n return dst || Buffer.alloc(0)\n }\n\n if (srcEnd <= 0) {\n return dst || Buffer.alloc(0)\n }\n\n const copy = !!dst\n const off = this._offset(srcStart)\n const len = srcEnd - srcStart\n let bytes = len\n let bufoff = (copy && dstStart) || 0\n let start = off[1]\n\n // copy/slice everything\n if (srcStart === 0 && srcEnd === this.length) {\n if (!copy) {\n // slice, but full concat if multiple buffers\n return this._bufs.length === 1\n ? this._bufs[0]\n : Buffer.concat(this._bufs, this.length)\n }\n\n // copy, need to copy individual buffers\n for (let i = 0; i < this._bufs.length; i++) {\n this._bufs[i].copy(dst, bufoff)\n bufoff += this._bufs[i].length\n }\n\n return dst\n }\n\n // easy, cheap case where it's a subset of one of the buffers\n if (bytes <= this._bufs[off[0]].length - start) {\n return copy\n ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)\n : this._bufs[off[0]].slice(start, start + bytes)\n }\n\n if (!copy) {\n // a slice, we need something to copy in to\n dst = Buffer.allocUnsafe(len)\n }\n\n for (let i = off[0]; i < this._bufs.length; i++) {\n const l = this._bufs[i].length - start\n\n if (bytes > l) {\n this._bufs[i].copy(dst, bufoff, start)\n bufoff += l\n } else {\n this._bufs[i].copy(dst, bufoff, start, start + bytes)\n bufoff += l\n break\n }\n\n bytes -= l\n\n if (start) {\n start = 0\n }\n }\n\n // safeguard so that we don't return uninitialized memory\n if (dst.length > bufoff) return dst.slice(0, bufoff)\n\n return dst\n}\n\nBufferList.prototype.shallowSlice = function shallowSlice (start, end) {\n start = start || 0\n end = typeof end !== 'number' ? this.length : end\n\n if (start < 0) {\n start += this.length\n }\n\n if (end < 0) {\n end += this.length\n }\n\n if (start === end) {\n return this._new()\n }\n\n const startOffset = this._offset(start)\n const endOffset = this._offset(end)\n const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)\n\n if (endOffset[1] === 0) {\n buffers.pop()\n } else {\n buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1])\n }\n\n if (startOffset[1] !== 0) {\n buffers[0] = buffers[0].slice(startOffset[1])\n }\n\n return this._new(buffers)\n}\n\nBufferList.prototype.toString = function toString (encoding, start, end) {\n return this.slice(start, end).toString(encoding)\n}\n\nBufferList.prototype.consume = function consume (bytes) {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) return this\n\n while (this._bufs.length) {\n if (bytes >= this._bufs[0].length) {\n bytes -= this._bufs[0].length\n this.length -= this._bufs[0].length\n this._bufs.shift()\n } else {\n this._bufs[0] = this._bufs[0].slice(bytes)\n this.length -= bytes\n break\n }\n }\n\n return this\n}\n\nBufferList.prototype.duplicate = function duplicate () {\n const copy = this._new()\n\n for (let i = 0; i < this._bufs.length; i++) {\n copy.append(this._bufs[i])\n }\n\n return copy\n}\n\nBufferList.prototype.append = function append (buf) {\n if (buf == null) {\n return this\n }\n\n if (buf.buffer) {\n // append a view of the underlying ArrayBuffer\n this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength))\n } else if (Array.isArray(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.append(buf[i])\n }\n } else if (this._isBufferList(buf)) {\n // unwrap argument into individual BufferLists\n for (let i = 0; i < buf._bufs.length; i++) {\n this.append(buf._bufs[i])\n }\n } else {\n // coerce number arguments to strings, since Buffer(number) does\n // uninitialized memory allocation\n if (typeof buf === 'number') {\n buf = buf.toString()\n }\n\n this._appendBuffer(Buffer.from(buf))\n }\n\n return this\n}\n\nBufferList.prototype._appendBuffer = function appendBuffer (buf) {\n this._bufs.push(buf)\n this.length += buf.length\n}\n\nBufferList.prototype.indexOf = function (search, offset, encoding) {\n if (encoding === undefined && typeof offset === 'string') {\n encoding = offset\n offset = undefined\n }\n\n if (typeof search === 'function' || Array.isArray(search)) {\n throw new TypeError('The \"value\" argument must be one of type string, Buffer, BufferList, or Uint8Array.')\n } else if (typeof search === 'number') {\n search = Buffer.from([search])\n } else if (typeof search === 'string') {\n search = Buffer.from(search, encoding)\n } else if (this._isBufferList(search)) {\n search = search.slice()\n } else if (Array.isArray(search.buffer)) {\n search = Buffer.from(search.buffer, search.byteOffset, search.byteLength)\n } else if (!Buffer.isBuffer(search)) {\n search = Buffer.from(search)\n }\n\n offset = Number(offset || 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n const blOffset = this._offset(offset)\n let blIndex = blOffset[0] // index of which internal buffer we're working on\n let buffOffset = blOffset[1] // offset of the internal buffer we're working on\n\n // scan over each buffer\n for (; blIndex < this._bufs.length; blIndex++) {\n const buff = this._bufs[blIndex]\n\n while (buffOffset < buff.length) {\n const availableWindow = buff.length - buffOffset\n\n if (availableWindow >= search.length) {\n const nativeSearchResult = buff.indexOf(search, buffOffset)\n\n if (nativeSearchResult !== -1) {\n return this._reverseOffset([blIndex, nativeSearchResult])\n }\n\n buffOffset = buff.length - search.length + 1 // end of native search window\n } else {\n const revOffset = this._reverseOffset([blIndex, buffOffset])\n\n if (this._match(revOffset, search)) {\n return revOffset\n }\n\n buffOffset++\n }\n }\n\n buffOffset = 0\n }\n\n return -1\n}\n\nBufferList.prototype._match = function (offset, search) {\n if (this.length - offset < search.length) {\n return false\n }\n\n for (let searchOffset = 0; searchOffset < search.length; searchOffset++) {\n if (this.get(offset + searchOffset) !== search[searchOffset]) {\n return false\n }\n }\n return true\n}\n\n;(function () {\n const methods = {\n readDoubleBE: 8,\n readDoubleLE: 8,\n readFloatBE: 4,\n readFloatLE: 4,\n readInt32BE: 4,\n readInt32LE: 4,\n readUInt32BE: 4,\n readUInt32LE: 4,\n readInt16BE: 2,\n readInt16LE: 2,\n readUInt16BE: 2,\n readUInt16LE: 2,\n readInt8: 1,\n readUInt8: 1,\n readIntBE: null,\n readIntLE: null,\n readUIntBE: null,\n readUIntLE: null\n }\n\n for (const m in methods) {\n (function (m) {\n if (methods[m] === null) {\n BufferList.prototype[m] = function (offset, byteLength) {\n return this.slice(offset, offset + byteLength)[m](0, byteLength)\n }\n } else {\n BufferList.prototype[m] = function (offset = 0) {\n return this.slice(offset, offset + methods[m])[m](0)\n }\n }\n }(m))\n }\n}())\n\n// Used internally by the class and also as an indicator of this object being\n// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser\n// environment because there could be multiple different copies of the\n// BufferList class and some `BufferList`s might be `BufferList`s.\nBufferList.prototype._isBufferList = function _isBufferList (b) {\n return b instanceof BufferList || BufferList.isBufferList(b)\n}\n\nBufferList.isBufferList = function isBufferList (b) {\n return b != null && b[symbol]\n}\n\nmodule.exports = BufferList\n", "'use strict'\n\nconst DuplexStream = require('readable-stream').Duplex\nconst inherits = require('inherits')\nconst BufferList = require('./BufferList')\n\nfunction BufferListStream (callback) {\n if (!(this instanceof BufferListStream)) {\n return new BufferListStream(callback)\n }\n\n if (typeof callback === 'function') {\n this._callback = callback\n\n const piper = function piper (err) {\n if (this._callback) {\n this._callback(err)\n this._callback = null\n }\n }.bind(this)\n\n this.on('pipe', function onPipe (src) {\n src.on('error', piper)\n })\n this.on('unpipe', function onUnpipe (src) {\n src.removeListener('error', piper)\n })\n\n callback = null\n }\n\n BufferList._init.call(this, callback)\n DuplexStream.call(this)\n}\n\ninherits(BufferListStream, DuplexStream)\nObject.assign(BufferListStream.prototype, BufferList.prototype)\n\nBufferListStream.prototype._new = function _new (callback) {\n return new BufferListStream(callback)\n}\n\nBufferListStream.prototype._write = function _write (buf, encoding, callback) {\n this._appendBuffer(buf)\n\n if (typeof callback === 'function') {\n callback()\n }\n}\n\nBufferListStream.prototype._read = function _read (size) {\n if (!this.length) {\n return this.push(null)\n }\n\n size = Math.min(size, this.length)\n this.push(this.slice(0, size))\n this.consume(size)\n}\n\nBufferListStream.prototype.end = function end (chunk) {\n DuplexStream.prototype.end.call(this, chunk)\n\n if (this._callback) {\n this._callback(null, this.slice())\n this._callback = null\n }\n}\n\nBufferListStream.prototype._destroy = function _destroy (err, cb) {\n this._bufs.length = 0\n this.length = 0\n cb(err)\n}\n\nBufferListStream.prototype._isBufferList = function _isBufferList (b) {\n return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b)\n}\n\nBufferListStream.isBufferList = BufferList.isBufferList\n\nmodule.exports = BufferListStream\nmodule.exports.BufferListStream = BufferListStream\nmodule.exports.BufferList = BufferList\n", "var alloc = Buffer.alloc\n\nvar ZEROS = '0000000000000000000'\nvar SEVENS = '7777777777777777777'\nvar ZERO_OFFSET = '0'.charCodeAt(0)\nvar USTAR_MAGIC = Buffer.from('ustar\\x00', 'binary')\nvar USTAR_VER = Buffer.from('00', 'binary')\nvar GNU_MAGIC = Buffer.from('ustar\\x20', 'binary')\nvar GNU_VER = Buffer.from('\\x20\\x00', 'binary')\nvar MASK = parseInt('7777', 8)\nvar MAGIC_OFFSET = 257\nvar VERSION_OFFSET = 263\n\nvar clamp = function (index, len, defaultValue) {\n if (typeof index !== 'number') return defaultValue\n index = ~~index // Coerce to integer.\n if (index >= len) return len\n if (index >= 0) return index\n index += len\n if (index >= 0) return index\n return 0\n}\n\nvar toType = function (flag) {\n switch (flag) {\n case 0:\n return 'file'\n case 1:\n return 'link'\n case 2:\n return 'symlink'\n case 3:\n return 'character-device'\n case 4:\n return 'block-device'\n case 5:\n return 'directory'\n case 6:\n return 'fifo'\n case 7:\n return 'contiguous-file'\n case 72:\n return 'pax-header'\n case 55:\n return 'pax-global-header'\n case 27:\n return 'gnu-long-link-path'\n case 28:\n case 30:\n return 'gnu-long-path'\n }\n\n return null\n}\n\nvar toTypeflag = function (flag) {\n switch (flag) {\n case 'file':\n return 0\n case 'link':\n return 1\n case 'symlink':\n return 2\n case 'character-device':\n return 3\n case 'block-device':\n return 4\n case 'directory':\n return 5\n case 'fifo':\n return 6\n case 'contiguous-file':\n return 7\n case 'pax-header':\n return 72\n }\n\n return 0\n}\n\nvar indexOf = function (block, num, offset, end) {\n for (; offset < end; offset++) {\n if (block[offset] === num) return offset\n }\n return end\n}\n\nvar cksum = function (block) {\n var sum = 8 * 32\n for (var i = 0; i < 148; i++) sum += block[i]\n for (var j = 156; j < 512; j++) sum += block[j]\n return sum\n}\n\nvar encodeOct = function (val, n) {\n val = val.toString(8)\n if (val.length > n) return SEVENS.slice(0, n) + ' '\n else return ZEROS.slice(0, n - val.length) + val + ' '\n}\n\n/* Copied from the node-tar repo and modified to meet\n * tar-stream coding standard.\n *\n * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349\n */\nfunction parse256 (buf) {\n // first byte MUST be either 80 or FF\n // 80 for positive, FF for 2's comp\n var positive\n if (buf[0] === 0x80) positive = true\n else if (buf[0] === 0xFF) positive = false\n else return null\n\n // build up a base-256 tuple from the least sig to the highest\n var tuple = []\n for (var i = buf.length - 1; i > 0; i--) {\n var byte = buf[i]\n if (positive) tuple.push(byte)\n else tuple.push(0xFF - byte)\n }\n\n var sum = 0\n var l = tuple.length\n for (i = 0; i < l; i++) {\n sum += tuple[i] * Math.pow(256, i)\n }\n\n return positive ? sum : -1 * sum\n}\n\nvar decodeOct = function (val, offset, length) {\n val = val.slice(offset, offset + length)\n offset = 0\n\n // If prefixed with 0x80 then parse as a base-256 integer\n if (val[offset] & 0x80) {\n return parse256(val)\n } else {\n // Older versions of tar can prefix with spaces\n while (offset < val.length && val[offset] === 32) offset++\n var end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length)\n while (offset < end && val[offset] === 0) offset++\n if (end === offset) return 0\n return parseInt(val.slice(offset, end).toString(), 8)\n }\n}\n\nvar decodeStr = function (val, offset, length, encoding) {\n return val.slice(offset, indexOf(val, 0, offset, offset + length)).toString(encoding)\n}\n\nvar addLength = function (str) {\n var len = Buffer.byteLength(str)\n var digits = Math.floor(Math.log(len) / Math.log(10)) + 1\n if (len + digits >= Math.pow(10, digits)) digits++\n\n return (len + digits) + str\n}\n\nexports.decodeLongPath = function (buf, encoding) {\n return decodeStr(buf, 0, buf.length, encoding)\n}\n\nexports.encodePax = function (opts) { // TODO: encode more stuff in pax\n var result = ''\n if (opts.name) result += addLength(' path=' + opts.name + '\\n')\n if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\\n')\n var pax = opts.pax\n if (pax) {\n for (var key in pax) {\n result += addLength(' ' + key + '=' + pax[key] + '\\n')\n }\n }\n return Buffer.from(result)\n}\n\nexports.decodePax = function (buf) {\n var result = {}\n\n while (buf.length) {\n var i = 0\n while (i < buf.length && buf[i] !== 32) i++\n var len = parseInt(buf.slice(0, i).toString(), 10)\n if (!len) return result\n\n var b = buf.slice(i + 1, len - 1).toString()\n var keyIndex = b.indexOf('=')\n if (keyIndex === -1) return result\n result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1)\n\n buf = buf.slice(len)\n }\n\n return result\n}\n\nexports.encode = function (opts) {\n var buf = alloc(512)\n var name = opts.name\n var prefix = ''\n\n if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/'\n if (Buffer.byteLength(name) !== name.length) return null // utf-8\n\n while (Buffer.byteLength(name) > 100) {\n var i = name.indexOf('/')\n if (i === -1) return null\n prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i)\n name = name.slice(i + 1)\n }\n\n if (Buffer.byteLength(name) > 100 || Buffer.byteLength(prefix) > 155) return null\n if (opts.linkname && Buffer.byteLength(opts.linkname) > 100) return null\n\n buf.write(name)\n buf.write(encodeOct(opts.mode & MASK, 6), 100)\n buf.write(encodeOct(opts.uid, 6), 108)\n buf.write(encodeOct(opts.gid, 6), 116)\n buf.write(encodeOct(opts.size, 11), 124)\n buf.write(encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136)\n\n buf[156] = ZERO_OFFSET + toTypeflag(opts.type)\n\n if (opts.linkname) buf.write(opts.linkname, 157)\n\n USTAR_MAGIC.copy(buf, MAGIC_OFFSET)\n USTAR_VER.copy(buf, VERSION_OFFSET)\n if (opts.uname) buf.write(opts.uname, 265)\n if (opts.gname) buf.write(opts.gname, 297)\n buf.write(encodeOct(opts.devmajor || 0, 6), 329)\n buf.write(encodeOct(opts.devminor || 0, 6), 337)\n\n if (prefix) buf.write(prefix, 345)\n\n buf.write(encodeOct(cksum(buf), 6), 148)\n\n return buf\n}\n\nexports.decode = function (buf, filenameEncoding, allowUnknownFormat) {\n var typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET\n\n var name = decodeStr(buf, 0, 100, filenameEncoding)\n var mode = decodeOct(buf, 100, 8)\n var uid = decodeOct(buf, 108, 8)\n var gid = decodeOct(buf, 116, 8)\n var size = decodeOct(buf, 124, 12)\n var mtime = decodeOct(buf, 136, 12)\n var type = toType(typeflag)\n var linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding)\n var uname = decodeStr(buf, 265, 32)\n var gname = decodeStr(buf, 297, 32)\n var devmajor = decodeOct(buf, 329, 8)\n var devminor = decodeOct(buf, 337, 8)\n\n var c = cksum(buf)\n\n // checksum is still initial value if header was null.\n if (c === 8 * 32) return null\n\n // valid checksum\n if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?')\n\n if (USTAR_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0) {\n // ustar (posix) format.\n // prepend prefix, if present.\n if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + '/' + name\n } else if (GNU_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0 &&\n GNU_VER.compare(buf, VERSION_OFFSET, VERSION_OFFSET + 2) === 0) {\n // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and\n // multi-volume tarballs.\n } else {\n if (!allowUnknownFormat) {\n throw new Error('Invalid tar header: unknown format.')\n }\n }\n\n // to support old tar versions that use trailing / to indicate dirs\n if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5\n\n return {\n name,\n mode,\n uid,\n gid,\n size,\n mtime: new Date(1000 * mtime),\n type,\n linkname,\n uname,\n gname,\n devmajor,\n devminor\n }\n}\n", "module.exports = require('stream');\n", "'use strict';\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nvar _require = require('buffer'),\n Buffer = _require.Buffer;\n\nvar _require2 = require('util'),\n inspect = _require2.inspect;\n\nvar custom = inspect && inspect.custom || 'inspect';\n\nfunction copyBuffer(src, target, offset) {\n Buffer.prototype.copy.call(src, target, offset);\n}\n\nmodule.exports =\n/*#__PURE__*/\nfunction () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n _createClass(BufferList, [{\n key: \"push\",\n value: function push(v) {\n var entry = {\n data: v,\n next: null\n };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n }\n }, {\n key: \"unshift\",\n value: function unshift(v) {\n var entry = {\n data: v,\n next: this.head\n };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n }\n }, {\n key: \"shift\",\n value: function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n }\n }, {\n key: \"clear\",\n value: function clear() {\n this.head = this.tail = null;\n this.length = 0;\n }\n }, {\n key: \"join\",\n value: function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n\n while (p = p.next) {\n ret += s + p.data;\n }\n\n return ret;\n }\n }, {\n key: \"concat\",\n value: function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n\n return ret;\n } // Consumes a specified amount of bytes or characters from the buffered data.\n\n }, {\n key: \"consume\",\n value: function consume(n, hasStrings) {\n var ret;\n\n if (n < this.head.data.length) {\n // `slice` is the same for buffers and strings.\n ret = this.head.data.slice(0, n);\n this.head.data = this.head.data.slice(n);\n } else if (n === this.head.data.length) {\n // First chunk is a perfect match.\n ret = this.shift();\n } else {\n // Result spans more than one buffer.\n ret = hasStrings ? this._getString(n) : this._getBuffer(n);\n }\n\n return ret;\n }\n }, {\n key: \"first\",\n value: function first() {\n return this.head.data;\n } // Consumes a specified amount of characters from the buffered data.\n\n }, {\n key: \"_getString\",\n value: function _getString(n) {\n var p = this.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = str.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Consumes a specified amount of bytes from the buffered data.\n\n }, {\n key: \"_getBuffer\",\n value: function _getBuffer(n) {\n var ret = Buffer.allocUnsafe(n);\n var p = this.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = buf.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Make sure the linked list only shows the minimal necessary information.\n\n }, {\n key: custom,\n value: function value(_, options) {\n return inspect(this, _objectSpread({}, options, {\n // Only inspect one level.\n depth: 0,\n // It should not recurse.\n customInspect: false\n }));\n }\n }]);\n\n return BufferList;\n}();", "'use strict'; // undocumented cb() API, needed for core, not for public API\n\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n process.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n process.nextTick(emitErrorNT, this, err);\n }\n }\n\n return this;\n } // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n } // if this is a duplex stream mark the writable part as destroyed as well\n\n\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n } else if (cb) {\n process.nextTick(emitCloseNT, _this);\n cb(err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n });\n\n return this;\n}\n\nfunction emitErrorAndCloseNT(self, err) {\n emitErrorNT(self, err);\n emitCloseNT(self);\n}\n\nfunction emitCloseNT(self) {\n if (self._writableState && !self._writableState.emitClose) return;\n if (self._readableState && !self._readableState.emitClose) return;\n self.emit('close');\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nfunction errorOrDestroy(stream, err) {\n // We have tests that rely on errors being emitted\n // in the same tick, so changing this is semver major.\n // For now when you opt-in to autoDestroy we allow\n // the error to be emitted nextTick. In a future\n // semver major update we should change the default to this.\n var rState = stream._readableState;\n var wState = stream._writableState;\n if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy,\n errorOrDestroy: errorOrDestroy\n};", "'use strict';\n\nconst codes = {};\n\nfunction createErrorType(code, message, Base) {\n if (!Base) {\n Base = Error\n }\n\n function getMessage (arg1, arg2, arg3) {\n if (typeof message === 'string') {\n return message\n } else {\n return message(arg1, arg2, arg3)\n }\n }\n\n class NodeError extends Base {\n constructor (arg1, arg2, arg3) {\n super(getMessage(arg1, arg2, arg3));\n }\n }\n\n NodeError.prototype.name = Base.name;\n NodeError.prototype.code = code;\n\n codes[code] = NodeError;\n}\n\n// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js\nfunction oneOf(expected, thing) {\n if (Array.isArray(expected)) {\n const len = expected.length;\n expected = expected.map((i) => String(i));\n if (len > 2) {\n return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` +\n expected[len - 1];\n } else if (len === 2) {\n return `one of ${thing} ${expected[0]} or ${expected[1]}`;\n } else {\n return `of ${thing} ${expected[0]}`;\n }\n } else {\n return `of ${thing} ${String(expected)}`;\n }\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith\nfunction startsWith(str, search, pos) {\n\treturn str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\nfunction endsWith(str, search, this_len) {\n\tif (this_len === undefined || this_len > str.length) {\n\t\tthis_len = str.length;\n\t}\n\treturn str.substring(this_len - search.length, this_len) === search;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\nfunction includes(str, search, start) {\n if (typeof start !== 'number') {\n start = 0;\n }\n\n if (start + search.length > str.length) {\n return false;\n } else {\n return str.indexOf(search, start) !== -1;\n }\n}\n\ncreateErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {\n return 'The value \"' + value + '\" is invalid for option \"' + name + '\"'\n}, TypeError);\ncreateErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {\n // determiner: 'must be' or 'must not be'\n let determiner;\n if (typeof expected === 'string' && startsWith(expected, 'not ')) {\n determiner = 'must not be';\n expected = expected.replace(/^not /, '');\n } else {\n determiner = 'must be';\n }\n\n let msg;\n if (endsWith(name, ' argument')) {\n // For cases like 'first argument'\n msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;\n } else {\n const type = includes(name, '.') ? 'property' : 'argument';\n msg = `The \"${name}\" ${type} ${determiner} ${oneOf(expected, 'type')}`;\n }\n\n msg += `. Received type ${typeof actual}`;\n return msg;\n}, TypeError);\ncreateErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');\ncreateErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {\n return 'The ' + name + ' method is not implemented'\n});\ncreateErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');\ncreateErrorType('ERR_STREAM_DESTROYED', function (name) {\n return 'Cannot call ' + name + ' after a stream was destroyed';\n});\ncreateErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');\ncreateErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');\ncreateErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');\ncreateErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);\ncreateErrorType('ERR_UNKNOWN_ENCODING', function (arg) {\n return 'Unknown encoding: ' + arg\n}, TypeError);\ncreateErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');\n\nmodule.exports.codes = codes;\n", "'use strict';\n\nvar ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;\n\nfunction highWaterMarkFrom(options, isDuplex, duplexKey) {\n return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;\n}\n\nfunction getHighWaterMark(state, options, duplexKey, isDuplex) {\n var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);\n\n if (hwm != null) {\n if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {\n var name = isDuplex ? duplexKey : 'highWaterMark';\n throw new ERR_INVALID_OPT_VALUE(name, hwm);\n }\n\n return Math.floor(hwm);\n } // Default value\n\n\n return state.objectMode ? 16 : 16 * 1024;\n}\n\nmodule.exports = {\n getHighWaterMark: getHighWaterMark\n};", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n'use strict';\n\nmodule.exports = Writable;\n/* <replacement> */\n\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n} // It seems a linked list but it is not\n// there will be only 2 of these for each stream\n\n\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* </replacement> */\n\n/*<replacement>*/\n\n\nvar Duplex;\n/*</replacement>*/\n\nWritable.WritableState = WritableState;\n/*<replacement>*/\n\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/*</replacement>*/\n\n/*<replacement>*/\n\nvar Stream = require('./internal/streams/stream');\n/*</replacement>*/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,\n ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,\n ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,\n ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\n\nrequire('inherits')(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream,\n // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n\n this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called\n\n this.finalCalled = false; // drain event flag.\n\n this.needDrain = false; // at the start of calling end()\n\n this.ending = false; // when end() has been called, and returned\n\n this.ended = false; // when 'finish' is emitted\n\n this.finished = false; // has it been destroyed\n\n this.destroyed = false; // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n\n this.length = 0; // a flag to see when we're in the middle of a write.\n\n this.writing = false; // when true all writes will be buffered until .uncork() call\n\n this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n\n this.sync = true; // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n\n this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)\n\n this.onwrite = function (er) {\n onwrite(stream, er);\n }; // the callback that the user supplies to write(chunk,encoding,cb)\n\n\n this.writecb = null; // the amount that is being written when _write is called.\n\n this.writelen = 0;\n this.bufferedRequest = null;\n this.lastBufferedRequest = null; // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n\n this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n\n this.prefinished = false; // True if the error was already emitted and should not be thrown again\n\n this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')\n\n this.autoDestroy = !!options.autoDestroy; // count buffered requests\n\n this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n\n while (current) {\n out.push(current);\n current = current.next;\n }\n\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function writableStateBufferGetter() {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})(); // Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\n\n\nvar realHasInstance;\n\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function value(object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function realHasInstance(object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the WritableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);\n this._writableState = new WritableState(options, this, isDuplex); // legacy.\n\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n if (typeof options.writev === 'function') this._writev = options.writev;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n} // Otherwise people can pipe Writable streams, which is just wrong.\n\n\nWritable.prototype.pipe = function () {\n errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb\n\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n} // Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\n\n\nfunction validChunk(stream, state, chunk, cb) {\n var er;\n\n if (chunk === null) {\n er = new ERR_STREAM_NULL_VALUES();\n } else if (typeof chunk !== 'string' && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);\n }\n\n if (er) {\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n return false;\n }\n\n return true;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n if (typeof cb !== 'function') cb = nop;\n if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n return ret;\n};\n\nWritable.prototype.cork = function () {\n this._writableState.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n}); // if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\n\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n\n var len = state.objectMode ? 1 : chunk.length;\n state.length += len;\n var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.\n\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n process.nextTick(cb, er); // this can emit finish, and it will always happen\n // after error\n\n process.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er); // this can emit finish, but finish must\n // always follow error\n\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();\n onwriteStateUpdate(state);\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state) || stream.destroyed;\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n process.nextTick(afterWrite, stream, state, finished, cb);\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n} // Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\n\n\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n} // if there's something in the buffer waiting, then process it\n\n\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n var count = 0;\n var allBuffers = true;\n\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n\n buffer.allBuffers = allBuffers;\n doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n\n state.pendingcb++;\n state.lastBufferedRequest = null;\n\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks\n\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n } // ignore unnecessary end() calls.\n\n\n if (!state.ending) endWritable(this, state, cb);\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n});\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\n\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n\n if (err) {\n errorOrDestroy(stream, err);\n }\n\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\n\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function' && !state.destroyed) {\n state.pendingcb++;\n state.finalCalled = true;\n process.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n\n if (need) {\n prefinish(stream, state);\n\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the readable side is ready for autoDestroy as well\n var rState = stream._readableState;\n\n if (!rState || rState.autoDestroy && rState.endEmitted) {\n stream.destroy();\n }\n }\n }\n }\n\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n\n if (cb) {\n if (state.finished) process.nextTick(cb);else stream.once('finish', cb);\n }\n\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n } // reuse the free corkReq.\n\n\n state.corkedRequestsFree.next = corkReq;\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._writableState === undefined) {\n return false;\n }\n\n return this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._writableState.destroyed = value;\n }\n});\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\n\nWritable.prototype._destroy = function (err, cb) {\n cb(err);\n};", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n'use strict';\n/*<replacement>*/\n\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n\n for (var key in obj) {\n keys.push(key);\n }\n\n return keys;\n};\n/*</replacement>*/\n\n\nmodule.exports = Duplex;\n\nvar Readable = require('./_stream_readable');\n\nvar Writable = require('./_stream_writable');\n\nrequire('inherits')(Duplex, Readable);\n\n{\n // Allow the keys array to be GC'ed.\n var keys = objectKeys(Writable.prototype);\n\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n Readable.call(this, options);\n Writable.call(this, options);\n this.allowHalfOpen = true;\n\n if (options) {\n if (options.readable === false) this.readable = false;\n if (options.writable === false) this.writable = false;\n\n if (options.allowHalfOpen === false) {\n this.allowHalfOpen = false;\n this.once('end', onend);\n }\n }\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n}); // the no-half-open enforcer\n\nfunction onend() {\n // If the writable side ended, then we're ok.\n if (this._writableState.ended) return; // no more data can be written.\n // But allow more writes to happen in this tick.\n\n process.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});", "// Ported from https://github.com/mafintosh/end-of-stream with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n callback.apply(this, args);\n };\n}\n\nfunction noop() {}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction eos(stream, opts, callback) {\n if (typeof opts === 'function') return eos(stream, null, opts);\n if (!opts) opts = {};\n callback = once(callback || noop);\n var readable = opts.readable || opts.readable !== false && stream.readable;\n var writable = opts.writable || opts.writable !== false && stream.writable;\n\n var onlegacyfinish = function onlegacyfinish() {\n if (!stream.writable) onfinish();\n };\n\n var writableEnded = stream._writableState && stream._writableState.finished;\n\n var onfinish = function onfinish() {\n writable = false;\n writableEnded = true;\n if (!readable) callback.call(stream);\n };\n\n var readableEnded = stream._readableState && stream._readableState.endEmitted;\n\n var onend = function onend() {\n readable = false;\n readableEnded = true;\n if (!writable) callback.call(stream);\n };\n\n var onerror = function onerror(err) {\n callback.call(stream, err);\n };\n\n var onclose = function onclose() {\n var err;\n\n if (readable && !readableEnded) {\n if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n\n if (writable && !writableEnded) {\n if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n };\n\n var onrequest = function onrequest() {\n stream.req.on('finish', onfinish);\n };\n\n if (isRequest(stream)) {\n stream.on('complete', onfinish);\n stream.on('abort', onclose);\n if (stream.req) onrequest();else stream.on('request', onrequest);\n } else if (writable && !stream._writableState) {\n // legacy streams\n stream.on('end', onlegacyfinish);\n stream.on('close', onlegacyfinish);\n }\n\n stream.on('end', onend);\n stream.on('finish', onfinish);\n if (opts.error !== false) stream.on('error', onerror);\n stream.on('close', onclose);\n return function () {\n stream.removeListener('complete', onfinish);\n stream.removeListener('abort', onclose);\n stream.removeListener('request', onrequest);\n if (stream.req) stream.req.removeListener('finish', onfinish);\n stream.removeListener('end', onlegacyfinish);\n stream.removeListener('close', onlegacyfinish);\n stream.removeListener('finish', onfinish);\n stream.removeListener('end', onend);\n stream.removeListener('error', onerror);\n stream.removeListener('close', onclose);\n };\n}\n\nmodule.exports = eos;", "'use strict';\n\nvar _Object$setPrototypeO;\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar finished = require('./end-of-stream');\n\nvar kLastResolve = Symbol('lastResolve');\nvar kLastReject = Symbol('lastReject');\nvar kError = Symbol('error');\nvar kEnded = Symbol('ended');\nvar kLastPromise = Symbol('lastPromise');\nvar kHandlePromise = Symbol('handlePromise');\nvar kStream = Symbol('stream');\n\nfunction createIterResult(value, done) {\n return {\n value: value,\n done: done\n };\n}\n\nfunction readAndResolve(iter) {\n var resolve = iter[kLastResolve];\n\n if (resolve !== null) {\n var data = iter[kStream].read(); // we defer if data is null\n // we can be expecting either 'end' or\n // 'error'\n\n if (data !== null) {\n iter[kLastPromise] = null;\n iter[kLastResolve] = null;\n iter[kLastReject] = null;\n resolve(createIterResult(data, false));\n }\n }\n}\n\nfunction onReadable(iter) {\n // we wait for the next tick, because it might\n // emit an error with process.nextTick\n process.nextTick(readAndResolve, iter);\n}\n\nfunction wrapForNext(lastPromise, iter) {\n return function (resolve, reject) {\n lastPromise.then(function () {\n if (iter[kEnded]) {\n resolve(createIterResult(undefined, true));\n return;\n }\n\n iter[kHandlePromise](resolve, reject);\n }, reject);\n };\n}\n\nvar AsyncIteratorPrototype = Object.getPrototypeOf(function () {});\nvar ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {\n get stream() {\n return this[kStream];\n },\n\n next: function next() {\n var _this = this;\n\n // if we have detected an error in the meanwhile\n // reject straight away\n var error = this[kError];\n\n if (error !== null) {\n return Promise.reject(error);\n }\n\n if (this[kEnded]) {\n return Promise.resolve(createIterResult(undefined, true));\n }\n\n if (this[kStream].destroyed) {\n // We need to defer via nextTick because if .destroy(err) is\n // called, the error will be emitted via nextTick, and\n // we cannot guarantee that there is no error lingering around\n // waiting to be emitted.\n return new Promise(function (resolve, reject) {\n process.nextTick(function () {\n if (_this[kError]) {\n reject(_this[kError]);\n } else {\n resolve(createIterResult(undefined, true));\n }\n });\n });\n } // if we have multiple next() calls\n // we will wait for the previous Promise to finish\n // this logic is optimized to support for await loops,\n // where next() is only called once at a time\n\n\n var lastPromise = this[kLastPromise];\n var promise;\n\n if (lastPromise) {\n promise = new Promise(wrapForNext(lastPromise, this));\n } else {\n // fast path needed to support multiple this.push()\n // without triggering the next() queue\n var data = this[kStream].read();\n\n if (data !== null) {\n return Promise.resolve(createIterResult(data, false));\n }\n\n promise = new Promise(this[kHandlePromise]);\n }\n\n this[kLastPromise] = promise;\n return promise;\n }\n}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {\n return this;\n}), _defineProperty(_Object$setPrototypeO, \"return\", function _return() {\n var _this2 = this;\n\n // destroy(err, cb) is a private API\n // we can guarantee we have that here, because we control the\n // Readable class this is attached to\n return new Promise(function (resolve, reject) {\n _this2[kStream].destroy(null, function (err) {\n if (err) {\n reject(err);\n return;\n }\n\n resolve(createIterResult(undefined, true));\n });\n });\n}), _Object$setPrototypeO), AsyncIteratorPrototype);\n\nvar createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {\n var _Object$create;\n\n var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {\n value: stream,\n writable: true\n }), _defineProperty(_Object$create, kLastResolve, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kLastReject, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kError, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kEnded, {\n value: stream._readableState.endEmitted,\n writable: true\n }), _defineProperty(_Object$create, kHandlePromise, {\n value: function value(resolve, reject) {\n var data = iterator[kStream].read();\n\n if (data) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(data, false));\n } else {\n iterator[kLastResolve] = resolve;\n iterator[kLastReject] = reject;\n }\n },\n writable: true\n }), _Object$create));\n iterator[kLastPromise] = null;\n finished(stream, function (err) {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise\n // returned by next() and store the error\n\n if (reject !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n reject(err);\n }\n\n iterator[kError] = err;\n return;\n }\n\n var resolve = iterator[kLastResolve];\n\n if (resolve !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(undefined, true));\n }\n\n iterator[kEnded] = true;\n });\n stream.on('readable', onReadable.bind(null, iterator));\n return iterator;\n};\n\nmodule.exports = createReadableStreamAsyncIterator;", "'use strict';\n\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }\n\nfunction _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err); } _next(undefined); }); }; }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE;\n\nfunction from(Readable, iterable, opts) {\n var iterator;\n\n if (iterable && typeof iterable.next === 'function') {\n iterator = iterable;\n } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable);\n\n var readable = new Readable(_objectSpread({\n objectMode: true\n }, opts)); // Reading boolean to protect against _read\n // being called before last iteration completion.\n\n var reading = false;\n\n readable._read = function () {\n if (!reading) {\n reading = true;\n next();\n }\n };\n\n function next() {\n return _next2.apply(this, arguments);\n }\n\n function _next2() {\n _next2 = _asyncToGenerator(function* () {\n try {\n var _ref = yield iterator.next(),\n value = _ref.value,\n done = _ref.done;\n\n if (done) {\n readable.push(null);\n } else if (readable.push((yield value))) {\n next();\n } else {\n reading = false;\n }\n } catch (err) {\n readable.destroy(err);\n }\n });\n return _next2.apply(this, arguments);\n }\n\n return readable;\n}\n\nmodule.exports = from;", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n'use strict';\n\nmodule.exports = Readable;\n/*<replacement>*/\n\nvar Duplex;\n/*</replacement>*/\n\nReadable.ReadableState = ReadableState;\n/*<replacement>*/\n\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function EElistenerCount(emitter, type) {\n return emitter.listeners(type).length;\n};\n/*</replacement>*/\n\n/*<replacement>*/\n\n\nvar Stream = require('./internal/streams/stream');\n/*</replacement>*/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n/*<replacement>*/\n\n\nvar debugUtil = require('util');\n\nvar debug;\n\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function debug() {};\n}\n/*</replacement>*/\n\n\nvar BufferList = require('./internal/streams/buffer_list');\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.\n\n\nvar StringDecoder;\nvar createReadableStreamAsyncIterator;\nvar from;\n\nrequire('inherits')(Readable, Stream);\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n\n this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n\n this.sync = true; // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n this.paused = true; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')\n\n this.autoDestroy = !!options.autoDestroy; // has it been destroyed\n\n this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s\n\n this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled\n\n this.readingMore = false;\n this.decoder = null;\n this.encoding = null;\n\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside\n // the ReadableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n this._readableState = new ReadableState(options, this, isDuplex); // legacy\n\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n }\n});\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\n\nReadable.prototype._destroy = function (err, cb) {\n cb(err);\n}; // Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\n\n\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n}; // Unshift should *always* be something directly out of read()\n\n\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n debug('readableAddChunk', chunk);\n var state = stream._readableState;\n\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n\n if (er) {\n errorOrDestroy(stream, er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());\n } else if (state.destroyed) {\n return false;\n } else {\n state.reading = false;\n\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n maybeReadMore(stream, state);\n }\n } // We can push more data if we are below the highWaterMark.\n // Also, if we have no data yet, we can stand some more bytes.\n // This is to work around cases where hwm=0, such as the repl.\n\n\n return !state.ended && (state.length < state.highWaterMark || state.length === 0);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n state.awaitDrain = 0;\n stream.emit('data', chunk);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n if (state.needReadable) emitReadable(stream);\n }\n\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);\n }\n\n return er;\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n}; // backwards compatibility.\n\n\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n var decoder = new StringDecoder(enc);\n this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8\n\n this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:\n\n var p = this._readableState.buffer.head;\n var content = '';\n\n while (p !== null) {\n content += decoder.write(p.data);\n p = p.next;\n }\n\n this._readableState.buffer.clear();\n\n if (content !== '') this._readableState.buffer.push(content);\n this._readableState.length = content.length;\n return this;\n}; // Don't raise the hwm > 1GB\n\n\nvar MAX_HWM = 0x40000000;\n\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n\n return n;\n} // This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\n\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n } // If we're asking for more than the current hwm, then raise the hwm.\n\n\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n; // Don't have enough\n\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n\n return state.length;\n} // you can override either this method, or the async _read(n) below.\n\n\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n\n if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.\n\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n } // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n // if we need a readable event, then we need to do some reading.\n\n\n var doRead = state.needReadable;\n debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some\n\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n } // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n\n\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true; // if the length is currently zero, then we *need* a readable event.\n\n if (state.length === 0) state.needReadable = true; // call internal read method\n\n this._read(state.highWaterMark);\n\n state.sync = false; // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = state.length <= state.highWaterMark;\n n = 0;\n } else {\n state.length -= n;\n state.awaitDrain = 0;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.\n\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n debug('onEofChunk');\n if (state.ended) return;\n\n if (state.decoder) {\n var chunk = state.decoder.end();\n\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n\n state.ended = true;\n\n if (state.sync) {\n // if we are sync, wait until next tick to emit the data.\n // Otherwise we risk emitting data in the flow()\n // the readable code triggers during a read() call\n emitReadable(stream);\n } else {\n // emit 'readable' now to make sure it gets picked up.\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n state.emittedReadable = true;\n emitReadable_(stream);\n }\n }\n} // Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\n\n\nfunction emitReadable(stream) {\n var state = stream._readableState;\n debug('emitReadable', state.needReadable, state.emittedReadable);\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n process.nextTick(emitReadable_, stream);\n }\n}\n\nfunction emitReadable_(stream) {\n var state = stream._readableState;\n debug('emitReadable_', state.destroyed, state.length, state.ended);\n\n if (!state.destroyed && (state.length || state.ended)) {\n stream.emit('readable');\n state.emittedReadable = false;\n } // The stream needs another readable event if\n // 1. It is not flowing, as the flow mechanism will take\n // care of it.\n // 2. It is not ended.\n // 3. It is below the highWaterMark, so we can schedule\n // another readable later.\n\n\n state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;\n flow(stream);\n} // at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\n\n\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n process.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n // Attempt to read more data if we should.\n //\n // The conditions for reading more data are (one of):\n // - Not enough data buffered (state.length < state.highWaterMark). The loop\n // is responsible for filling the buffer with enough data if such data\n // is available. If highWaterMark is 0 and we are not in the flowing mode\n // we should _not_ attempt to buffer any extra data. We'll get more data\n // when the stream consumer calls read() instead.\n // - No data in the buffer, and the stream is in flowing mode. In this mode\n // the loop below is responsible for ensuring read() is called. Failing to\n // call read here would abort the flow and there's no other mechanism for\n // continuing the flow if the stream consumer has just subscribed to the\n // 'data' event.\n //\n // In addition to the above conditions to keep reading data, the following\n // conditions prevent the data from being read:\n // - The stream has ended (state.ended).\n // - There is already a pending 'read' operation (state.reading). This is a\n // case where the the stream has called the implementation defined _read()\n // method, but they are processing the call asynchronously and have _not_\n // called push() with new data. In this case we skip performing more\n // read()s. The execution ends in this method again after the _read() ends\n // up calling push() with more data.\n while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {\n var len = state.length;\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length) // didn't get any data, stop spinning.\n break;\n }\n\n state.readingMore = false;\n} // abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\n\n\nReadable.prototype._read = function (n) {\n errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n\n default:\n state.pipes.push(dest);\n break;\n }\n\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);\n dest.on('unpipe', onunpipe);\n\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n } // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n\n\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n var cleanedUp = false;\n\n function cleanup() {\n debug('cleanup'); // cleanup event handlers once the pipe is broken\n\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n cleanedUp = true; // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n src.on('data', ondata);\n\n function ondata(chunk) {\n debug('ondata');\n var ret = dest.write(chunk);\n debug('dest.write', ret);\n\n if (ret === false) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n }\n\n src.pause();\n }\n } // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n\n\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);\n } // Make sure our error handler is attached before userland ones.\n\n\n prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.\n\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n\n dest.once('close', onclose);\n\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n } // tell the dest that it's being piped to\n\n\n dest.emit('pipe', src); // start the flow if it hasn't been started already.\n\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function pipeOnDrainFunctionResult() {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = {\n hasUnpiped: false\n }; // if we're not piping anywhere, then do nothing.\n\n if (state.pipesCount === 0) return this; // just one destination. most common case.\n\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n if (!dest) dest = state.pipes; // got a match.\n\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n } // slow case. multiple pipe destinations.\n\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, {\n hasUnpiped: false\n });\n }\n\n return this;\n } // try to find the right one.\n\n\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n dest.emit('unpipe', this, unpipeInfo);\n return this;\n}; // set up data events if they are asked for\n// Ensure readable listeners eventually get something\n\n\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n var state = this._readableState;\n\n if (ev === 'data') {\n // update readableListening so that resume() may be a no-op\n // a few lines down. This is needed to support once('readable').\n state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused\n\n if (state.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.flowing = false;\n state.emittedReadable = false;\n debug('on readable', state.length, state.reading);\n\n if (state.length) {\n emitReadable(this);\n } else if (!state.reading) {\n process.nextTick(nReadingNextTick, this);\n }\n }\n }\n\n return res;\n};\n\nReadable.prototype.addListener = Readable.prototype.on;\n\nReadable.prototype.removeListener = function (ev, fn) {\n var res = Stream.prototype.removeListener.call(this, ev, fn);\n\n if (ev === 'readable') {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nReadable.prototype.removeAllListeners = function (ev) {\n var res = Stream.prototype.removeAllListeners.apply(this, arguments);\n\n if (ev === 'readable' || ev === undefined) {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nfunction updateReadableListening(self) {\n var state = self._readableState;\n state.readableListening = self.listenerCount('readable') > 0;\n\n if (state.resumeScheduled && !state.paused) {\n // flowing needs to be set to true now, otherwise\n // the upcoming resume will not flow.\n state.flowing = true; // crude way to check if we should resume\n } else if (self.listenerCount('data') > 0) {\n self.resume();\n }\n}\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n} // pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\n\n\nReadable.prototype.resume = function () {\n var state = this._readableState;\n\n if (!state.flowing) {\n debug('resume'); // we flow only if there is no one listening\n // for readable, but we still have to call\n // resume()\n\n state.flowing = !state.readableListening;\n resume(this, state);\n }\n\n state.paused = false;\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n process.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n debug('resume', state.reading);\n\n if (!state.reading) {\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n\n if (this._readableState.flowing !== false) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n\n this._readableState.paused = true;\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n\n while (state.flowing && stream.read() !== null) {\n ;\n }\n} // wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\n\n\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n stream.on('end', function () {\n debug('wrapped end');\n\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode\n\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n\n if (!ret) {\n paused = true;\n stream.pause();\n }\n }); // proxy all the other methods.\n // important when wrapping filters and duplexes.\n\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function methodWrap(method) {\n return function methodWrapReturnFunction() {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n } // proxy certain important events.\n\n\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n } // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n\n\n this._read = function (n) {\n debug('wrapped _read', n);\n\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nif (typeof Symbol === 'function') {\n Readable.prototype[Symbol.asyncIterator] = function () {\n if (createReadableStreamAsyncIterator === undefined) {\n createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');\n }\n\n return createReadableStreamAsyncIterator(this);\n };\n}\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.highWaterMark;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState && this._readableState.buffer;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableFlowing', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.flowing;\n },\n set: function set(state) {\n if (this._readableState) {\n this._readableState.flowing = state;\n }\n }\n}); // exposed for testing purposes only.\n\nReadable._fromList = fromList;\nObject.defineProperty(Readable.prototype, 'readableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.length;\n }\n}); // Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = state.buffer.consume(n, state.decoder);\n }\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n debug('endReadable', state.endEmitted);\n\n if (!state.endEmitted) {\n state.ended = true;\n process.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.\n\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the writable side is ready for autoDestroy as well\n var wState = stream._writableState;\n\n if (!wState || wState.autoDestroy && wState.finished) {\n stream.destroy();\n }\n }\n }\n}\n\nif (typeof Symbol === 'function') {\n Readable.from = function (iterable, opts) {\n if (from === undefined) {\n from = require('./internal/streams/from');\n }\n\n return from(Readable, iterable, opts);\n };\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n\n return -1;\n}", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n'use strict';\n\nmodule.exports = Transform;\n\nvar _require$codes = require('../errors').codes,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,\n ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;\n\nvar Duplex = require('./_stream_duplex');\n\nrequire('inherits')(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n var cb = ts.writecb;\n\n if (cb === null) {\n return this.emit('error', new ERR_MULTIPLE_CALLBACK());\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n cb(er);\n var rs = this._readableState;\n rs.reading = false;\n\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n Duplex.call(this, options);\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n }; // start out asking for a readable event once data is transformed.\n\n this._readableState.needReadable = true; // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n if (typeof options.flush === 'function') this._flush = options.flush;\n } // When the writable side finishes, then flush out anything remaining.\n\n\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function' && !this._readableState.destroyed) {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n}; // This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\n\n\nTransform.prototype._transform = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n}; // Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\n\n\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && !ts.transforming) {\n ts.transforming = true;\n\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data); // TODO(BridgeAR): Write a test for these two error cases\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n\n if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();\n if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();\n return stream.push(null);\n}", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\nrequire('inherits')(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};", "// Ported from https://github.com/mafintosh/pump with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar eos;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n callback.apply(void 0, arguments);\n };\n}\n\nvar _require$codes = require('../../../errors').codes,\n ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;\n\nfunction noop(err) {\n // Rethrow the error if it exists to avoid swallowing it\n if (err) throw err;\n}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction destroyer(stream, reading, writing, callback) {\n callback = once(callback);\n var closed = false;\n stream.on('close', function () {\n closed = true;\n });\n if (eos === undefined) eos = require('./end-of-stream');\n eos(stream, {\n readable: reading,\n writable: writing\n }, function (err) {\n if (err) return callback(err);\n closed = true;\n callback();\n });\n var destroyed = false;\n return function (err) {\n if (closed) return;\n if (destroyed) return;\n destroyed = true; // request.destroy just do .end - .abort is what we want\n\n if (isRequest(stream)) return stream.abort();\n if (typeof stream.destroy === 'function') return stream.destroy();\n callback(err || new ERR_STREAM_DESTROYED('pipe'));\n };\n}\n\nfunction call(fn) {\n fn();\n}\n\nfunction pipe(from, to) {\n return from.pipe(to);\n}\n\nfunction popCallback(streams) {\n if (!streams.length) return noop;\n if (typeof streams[streams.length - 1] !== 'function') return noop;\n return streams.pop();\n}\n\nfunction pipeline() {\n for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {\n streams[_key] = arguments[_key];\n }\n\n var callback = popCallback(streams);\n if (Array.isArray(streams[0])) streams = streams[0];\n\n if (streams.length < 2) {\n throw new ERR_MISSING_ARGS('streams');\n }\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 return streams.reduce(pipe);\n}\n\nmodule.exports = pipeline;", "var Stream = require('stream');\nif (process.env.READABLE_STREAM === 'disable' && Stream) {\n module.exports = Stream.Readable;\n Object.assign(module.exports, Stream);\n module.exports.Stream = Stream;\n} else {\n exports = module.exports = require('./lib/_stream_readable.js');\n exports.Stream = Stream || exports;\n exports.Readable = exports;\n exports.Writable = require('./lib/_stream_writable.js');\n exports.Duplex = require('./lib/_stream_duplex.js');\n exports.Transform = require('./lib/_stream_transform.js');\n exports.PassThrough = require('./lib/_stream_passthrough.js');\n exports.finished = require('./lib/internal/streams/end-of-stream.js');\n exports.pipeline = require('./lib/internal/streams/pipeline.js');\n}\n", "var util = require('util')\nvar bl = require('bl')\nvar headers = require('./headers')\n\nvar Writable = require('readable-stream').Writable\nvar PassThrough = require('readable-stream').PassThrough\n\nvar noop = function () {}\n\nvar overflow = function (size) {\n size &= 511\n return size && 512 - size\n}\n\nvar emptyStream = function (self, offset) {\n var s = new Source(self, offset)\n s.end()\n return s\n}\n\nvar mixinPax = function (header, pax) {\n if (pax.path) header.name = pax.path\n if (pax.linkpath) header.linkname = pax.linkpath\n if (pax.size) header.size = parseInt(pax.size, 10)\n header.pax = pax\n return header\n}\n\nvar Source = function (self, offset) {\n this._parent = self\n this.offset = offset\n PassThrough.call(this, { autoDestroy: false })\n}\n\nutil.inherits(Source, PassThrough)\n\nSource.prototype.destroy = function (err) {\n this._parent.destroy(err)\n}\n\nvar Extract = function (opts) {\n if (!(this instanceof Extract)) return new Extract(opts)\n Writable.call(this, opts)\n\n opts = opts || {}\n\n this._offset = 0\n this._buffer = bl()\n this._missing = 0\n this._partial = false\n this._onparse = noop\n this._header = null\n this._stream = null\n this._overflow = null\n this._cb = null\n this._locked = false\n this._destroyed = false\n this._pax = null\n this._paxGlobal = null\n this._gnuLongPath = null\n this._gnuLongLinkPath = null\n\n var self = this\n var b = self._buffer\n\n var oncontinue = function () {\n self._continue()\n }\n\n var onunlock = function (err) {\n self._locked = false\n if (err) return self.destroy(err)\n if (!self._stream) oncontinue()\n }\n\n var onstreamend = function () {\n self._stream = null\n var drain = overflow(self._header.size)\n if (drain) self._parse(drain, ondrain)\n else self._parse(512, onheader)\n if (!self._locked) oncontinue()\n }\n\n var ondrain = function () {\n self._buffer.consume(overflow(self._header.size))\n self._parse(512, onheader)\n oncontinue()\n }\n\n var onpaxglobalheader = function () {\n var size = self._header.size\n self._paxGlobal = headers.decodePax(b.slice(0, size))\n b.consume(size)\n onstreamend()\n }\n\n var onpaxheader = function () {\n var size = self._header.size\n self._pax = headers.decodePax(b.slice(0, size))\n if (self._paxGlobal) self._pax = Object.assign({}, self._paxGlobal, self._pax)\n b.consume(size)\n onstreamend()\n }\n\n var ongnulongpath = function () {\n var size = self._header.size\n this._gnuLongPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding)\n b.consume(size)\n onstreamend()\n }\n\n var ongnulonglinkpath = function () {\n var size = self._header.size\n this._gnuLongLinkPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding)\n b.consume(size)\n onstreamend()\n }\n\n var onheader = function () {\n var offset = self._offset\n var header\n try {\n header = self._header = headers.decode(b.slice(0, 512), opts.filenameEncoding, opts.allowUnknownFormat)\n } catch (err) {\n self.emit('error', err)\n }\n b.consume(512)\n\n if (!header) {\n self._parse(512, onheader)\n oncontinue()\n return\n }\n if (header.type === 'gnu-long-path') {\n self._parse(header.size, ongnulongpath)\n oncontinue()\n return\n }\n if (header.type === 'gnu-long-link-path') {\n self._parse(header.size, ongnulonglinkpath)\n oncontinue()\n return\n }\n if (header.type === 'pax-global-header') {\n self._parse(header.size, onpaxglobalheader)\n oncontinue()\n return\n }\n if (header.type === 'pax-header') {\n self._parse(header.size, onpaxheader)\n oncontinue()\n return\n }\n\n if (self._gnuLongPath) {\n header.name = self._gnuLongPath\n self._gnuLongPath = null\n }\n\n if (self._gnuLongLinkPath) {\n header.linkname = self._gnuLongLinkPath\n self._gnuLongLinkPath = null\n }\n\n if (self._pax) {\n self._header = header = mixinPax(header, self._pax)\n self._pax = null\n }\n\n self._locked = true\n\n if (!header.size || header.type === 'directory') {\n self._parse(512, onheader)\n self.emit('entry', header, emptyStream(self, offset), onunlock)\n return\n }\n\n self._stream = new Source(self, offset)\n\n self.emit('entry', header, self._stream, onunlock)\n self._parse(header.size, onstreamend)\n oncontinue()\n }\n\n this._onheader = onheader\n this._parse(512, onheader)\n}\n\nutil.inherits(Extract, Writable)\n\nExtract.prototype.destroy = function (err) {\n if (this._destroyed) return\n this._destroyed = true\n\n if (err) this.emit('error', err)\n this.emit('close')\n if (this._stream) this._stream.emit('close')\n}\n\nExtract.prototype._parse = function (size, onparse) {\n if (this._destroyed) return\n this._offset += size\n this._missing = size\n if (onparse === this._onheader) this._partial = false\n this._onparse = onparse\n}\n\nExtract.prototype._continue = function () {\n if (this._destroyed) return\n var cb = this._cb\n this._cb = noop\n if (this._overflow) this._write(this._overflow, undefined, cb)\n else cb()\n}\n\nExtract.prototype._write = function (data, enc, cb) {\n if (this._destroyed) return\n\n var s = this._stream\n var b = this._buffer\n var missing = this._missing\n if (data.length) this._partial = true\n\n // we do not reach end-of-chunk now. just forward it\n\n if (data.length < missing) {\n this._missing -= data.length\n this._overflow = null\n if (s) return s.write(data, cb)\n b.append(data)\n return cb()\n }\n\n // end-of-chunk. the parser should call cb.\n\n this._cb = cb\n this._missing = 0\n\n var overflow = null\n if (data.length > missing) {\n overflow = data.slice(missing)\n data = data.slice(0, missing)\n }\n\n if (s) s.end(data)\n else b.append(data)\n\n this._overflow = overflow\n this._onparse()\n}\n\nExtract.prototype._final = function (cb) {\n if (this._partial) return this.destroy(new Error('Unexpected end of data'))\n cb()\n}\n\nmodule.exports = Extract\n", "module.exports = require('fs').constants || require('constants')\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 constants = require('fs-constants')\nvar eos = require('end-of-stream')\nvar inherits = require('inherits')\nvar alloc = Buffer.alloc\n\nvar Readable = require('readable-stream').Readable\nvar Writable = require('readable-stream').Writable\nvar StringDecoder = require('string_decoder').StringDecoder\n\nvar headers = require('./headers')\n\nvar DMODE = parseInt('755', 8)\nvar FMODE = parseInt('644', 8)\n\nvar END_OF_TAR = alloc(1024)\n\nvar noop = function () {}\n\nvar overflow = function (self, size) {\n size &= 511\n if (size) self.push(END_OF_TAR.slice(0, 512 - size))\n}\n\nfunction modeToType (mode) {\n switch (mode & constants.S_IFMT) {\n case constants.S_IFBLK: return 'block-device'\n case constants.S_IFCHR: return 'character-device'\n case constants.S_IFDIR: return 'directory'\n case constants.S_IFIFO: return 'fifo'\n case constants.S_IFLNK: return 'symlink'\n }\n\n return 'file'\n}\n\nvar Sink = function (to) {\n Writable.call(this)\n this.written = 0\n this._to = to\n this._destroyed = false\n}\n\ninherits(Sink, Writable)\n\nSink.prototype._write = function (data, enc, cb) {\n this.written += data.length\n if (this._to.push(data)) return cb()\n this._to._drain = cb\n}\n\nSink.prototype.destroy = function () {\n if (this._destroyed) return\n this._destroyed = true\n this.emit('close')\n}\n\nvar LinkSink = function () {\n Writable.call(this)\n this.linkname = ''\n this._decoder = new StringDecoder('utf-8')\n this._destroyed = false\n}\n\ninherits(LinkSink, Writable)\n\nLinkSink.prototype._write = function (data, enc, cb) {\n this.linkname += this._decoder.write(data)\n cb()\n}\n\nLinkSink.prototype.destroy = function () {\n if (this._destroyed) return\n this._destroyed = true\n this.emit('close')\n}\n\nvar Void = function () {\n Writable.call(this)\n this._destroyed = false\n}\n\ninherits(Void, Writable)\n\nVoid.prototype._write = function (data, enc, cb) {\n cb(new Error('No body allowed for this entry'))\n}\n\nVoid.prototype.destroy = function () {\n if (this._destroyed) return\n this._destroyed = true\n this.emit('close')\n}\n\nvar Pack = function (opts) {\n if (!(this instanceof Pack)) return new Pack(opts)\n Readable.call(this, opts)\n\n this._drain = noop\n this._finalized = false\n this._finalizing = false\n this._destroyed = false\n this._stream = null\n}\n\ninherits(Pack, Readable)\n\nPack.prototype.entry = function (header, buffer, callback) {\n if (this._stream) throw new Error('already piping an entry')\n if (this._finalized || this._destroyed) return\n\n if (typeof buffer === 'function') {\n callback = buffer\n buffer = null\n }\n\n if (!callback) callback = noop\n\n var self = this\n\n if (!header.size || header.type === 'symlink') header.size = 0\n if (!header.type) header.type = modeToType(header.mode)\n if (!header.mode) header.mode = header.type === 'directory' ? DMODE : FMODE\n if (!header.uid) header.uid = 0\n if (!header.gid) header.gid = 0\n if (!header.mtime) header.mtime = new Date()\n\n if (typeof buffer === 'string') buffer = Buffer.from(buffer)\n if (Buffer.isBuffer(buffer)) {\n header.size = buffer.length\n this._encode(header)\n var ok = this.push(buffer)\n overflow(self, header.size)\n if (ok) process.nextTick(callback)\n else this._drain = callback\n return new Void()\n }\n\n if (header.type === 'symlink' && !header.linkname) {\n var linkSink = new LinkSink()\n eos(linkSink, function (err) {\n if (err) { // stream was closed\n self.destroy()\n return callback(err)\n }\n\n header.linkname = linkSink.linkname\n self._encode(header)\n callback()\n })\n\n return linkSink\n }\n\n this._encode(header)\n\n if (header.type !== 'file' && header.type !== 'contiguous-file') {\n process.nextTick(callback)\n return new Void()\n }\n\n var sink = new Sink(this)\n\n this._stream = sink\n\n eos(sink, function (err) {\n self._stream = null\n\n if (err) { // stream was closed\n self.destroy()\n return callback(err)\n }\n\n if (sink.written !== header.size) { // corrupting tar\n self.destroy()\n return callback(new Error('size mismatch'))\n }\n\n overflow(self, header.size)\n if (self._finalizing) self.finalize()\n callback()\n })\n\n return sink\n}\n\nPack.prototype.finalize = function () {\n if (this._stream) {\n this._finalizing = true\n return\n }\n\n if (this._finalized) return\n this._finalized = true\n this.push(END_OF_TAR)\n this.push(null)\n}\n\nPack.prototype.destroy = function (err) {\n if (this._destroyed) return\n this._destroyed = true\n\n if (err) this.emit('error', err)\n this.emit('close')\n if (this._stream && this._stream.destroy) this._stream.destroy()\n}\n\nPack.prototype._encode = function (header) {\n if (!header.pax) {\n var buf = headers.encode(header)\n if (buf) {\n this.push(buf)\n return\n }\n }\n this._encodePax(header)\n}\n\nPack.prototype._encodePax = function (header) {\n var paxHeader = headers.encodePax({\n name: header.name,\n linkname: header.linkname,\n pax: header.pax\n })\n\n var newHeader = {\n name: 'PaxHeader',\n mode: header.mode,\n uid: header.uid,\n gid: header.gid,\n size: paxHeader.length,\n mtime: header.mtime,\n type: 'pax-header',\n linkname: header.linkname && 'PaxHeader',\n uname: header.uname,\n gname: header.gname,\n devmajor: header.devmajor,\n devminor: header.devminor\n }\n\n this.push(headers.encode(newHeader))\n this.push(paxHeader)\n overflow(this, paxHeader.length)\n\n newHeader.size = header.size\n newHeader.type = header.type\n this.push(headers.encode(newHeader))\n}\n\nPack.prototype._read = function (n) {\n var drain = this._drain\n this._drain = noop\n drain()\n}\n\nmodule.exports = Pack\n", "exports.extract = require('./extract')\nexports.pack = require('./pack')\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 { gunzip } from 'zlib';\n\nimport { metricScope, Unit } from 'aws-embedded-metrics';\nimport type { Context } from 'aws-lambda';\nimport { AWSError, S3 } from 'aws-sdk';\nimport { SemVer } from 'semver';\nimport { extract } from 'tar-stream';\nimport { CatalogModel, PackageInfo } from '.';\nimport { DenyListClient } from '../deny-list/client.lambda-shared';\nimport type { CatalogBuilderInput } from '../payload-schema';\nimport * as aws from '../shared/aws.lambda-shared';\nimport * as constants from '../shared/constants';\nimport { requireEnv } from '../shared/env.lambda-shared';\n\nconst METRICS_NAMESPACE = 'ConstructHub/CatalogBuilder';\n\n/**\n * Regenerates the `catalog.json` object in the configured S3 bucket.\n *\n * @param event configuration for the rebuild job. In particular, the `rebuild`\n * property can be set to `true` in order to trigger a full (i.e:\n * non-incremental) rebuild of the object.\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: CatalogBuilderInput, context: Context) {\n console.log(JSON.stringify(event, null, 2));\n\n const BUCKET_NAME = requireEnv('BUCKET_NAME');\n\n const packages = new Map<string, Map<number, PackageInfo>>();\n const denyList = await DenyListClient.newClient();\n\n console.log('Loading existing catalog (if present)...');\n\n const data = await aws.s3().getObject({ Bucket: BUCKET_NAME, Key: constants.CATALOG_KEY }).promise()\n .catch((err: AWSError) => err.code !== 'NoSuchKey'\n ? Promise.reject(err)\n : Promise.resolve({ /* no data */ } as S3.GetObjectOutput));\n\n if (data.Body) {\n console.log('Catalog found. Loading...');\n const catalog: CatalogModel = JSON.parse(data.Body.toString('utf-8'));\n for (const info of catalog.packages) {\n if (!packages.has(info.name)) {\n packages.set(info.name, new Map());\n }\n packages.get(info.name)!.set(info.major, info);\n }\n }\n\n // If defined, the function will invoke itself again to resume the work from that key (this\n // happens only in \"from scratch\" or \"rebuild\" cases).\n let nextStartAfter: string | undefined;\n\n if (event.package) {\n if (!event.package.key.endsWith(constants.PACKAGE_KEY_SUFFIX)) {\n throw new Error(`The provided package key is invalid: ${event.package.key} does not end in ${constants.PACKAGE_KEY_SUFFIX}`);\n }\n\n console.log('Registering new packages...');\n // note that we intentionally don't catch errors here to let these\n // event go to the DLQ for manual inspection.\n await appendPackage(packages, event.package.key, BUCKET_NAME, denyList);\n }\n\n // If we don't have a package in event, then we're refreshing the catalog. This is also true if we\n // don't have a catalog body (from scratch) or if \"startAfter\" is set (continuation of from\n // scratch).\n if (!event?.package || !data.Body || event.startAfter) {\n\n console.log('Recreating or refreshing catalog...');\n const failures: any = {};\n for await (const { Key: pkgKey } of relevantObjects(BUCKET_NAME, event.startAfter)) {\n try {\n await appendPackage(packages, pkgKey!, BUCKET_NAME, denyList);\n } catch (e) {\n failures[pkgKey!] = e;\n }\n // If we're getting short on time (1 minute out of 15 left), we'll be continuing in a new\n // invocation after writing what we've done so far to S3...\n if (context.getRemainingTimeInMillis() <= 60_000) {\n nextStartAfter = pkgKey;\n break;\n }\n }\n for (const [key, error] of Object.entries(failures)) {\n console.log(`Failed processing ${key}: ${error}`);\n }\n\n await metricScope((metrics) => async () => {\n metrics.setNamespace(METRICS_NAMESPACE);\n const failedCount = Object.keys(failures).length;\n console.log(`Marking ${failedCount} failed packages`);\n metrics.putMetric('FailedPackagesOnRecreation', failedCount, Unit.Count);\n })();\n }\n\n // Build the final data package...\n console.log('Consolidating catalog...');\n const catalog: CatalogModel = { packages: new Array<PackageInfo>(), updated: new Date().toISOString() };\n for (const majors of packages.values()) {\n for (const pkg of majors.values()) {\n catalog.packages.push(pkg);\n }\n }\n\n console.log(`There are now ${catalog.packages.length} registered package major versions`);\n await metricScope((metrics) => async () => {\n metrics.setNamespace(METRICS_NAMESPACE);\n metrics.putMetric('RegisteredPackagesMajorVersion', catalog.packages.length, Unit.Count);\n })();\n\n\n // Clean up existing entries if necessary. In particular, remove the license texts as they make\n // the catalog unnecessarily large, and may hinder some search queries' result quality.\n for (const entry of catalog.packages) {\n if (entry.metadata) {\n delete (entry.metadata as any).licenseText;\n }\n }\n\n // Upload the result to S3 and exit.\n const result = await aws.s3().putObject({\n Bucket: BUCKET_NAME,\n Key: constants.CATALOG_KEY,\n Body: JSON.stringify(catalog, 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-Count': `${catalog.packages.length}`,\n },\n }).promise();\n\n if (nextStartAfter != null) {\n console.log(`Will continue from ${nextStartAfter} in new invocation...`);\n const nextEvent: CatalogBuilderInput = { ...event, startAfter: nextStartAfter };\n // We start it asynchronously, as this function has a provisionned\n // concurrency of 1 (so a synchronous attempt would always be throttled).\n await aws.lambda().invokeAsync({\n FunctionName: context.functionName,\n InvokeArgs: JSON.stringify(nextEvent, null, 2),\n }).promise();\n }\n\n return result;\n}\n\n/**\n * A generator that asynchronously traverses the set of \"interesting\" objects\n * found by listing the configured S3 bucket. Those objects correspond to all\n * npm package tarballs present under the `packages/` prefix in the bucket.\n *\n * @param bucket the bucket in which to list objects\n * @param startAfter the key to start reading from, if provided.\n */\nasync function* relevantObjects(bucket: string, startAfter?: string) {\n const request: S3.ListObjectsV2Request = {\n Bucket: bucket,\n Prefix: constants.STORAGE_KEY_PREFIX,\n StartAfter: startAfter,\n };\n do {\n const result = await aws.s3().listObjectsV2(request).promise();\n for (const object of result.Contents ?? []) {\n if (!object.Key?.endsWith(constants.PACKAGE_KEY_SUFFIX)) {\n continue;\n }\n // We only register packages if they have AT LEAST docs in one language.\n const tsDocs = `${object.Key.substring(0, object.Key.length - constants.PACKAGE_KEY_SUFFIX.length)}${constants.DOCS_KEY_SUFFIX_TYPESCRIPT}`;\n const pyDocs = `${object.Key.substring(0, object.Key.length - constants.PACKAGE_KEY_SUFFIX.length)}${constants.DOCS_KEY_SUFFIX_PYTHON}`;\n const javaDocs = `${object.Key.substring(0, object.Key.length - constants.PACKAGE_KEY_SUFFIX.length)}${constants.DOCS_KEY_SUFFIX_JAVA}`;\n if (!(await aws.s3ObjectExists(bucket, tsDocs)) &&\n !(await aws.s3ObjectExists(bucket, pyDocs)) &&\n !(await aws.s3ObjectExists(bucket, javaDocs))) {\n continue;\n }\n yield object;\n }\n request.ContinuationToken = result.NextContinuationToken;\n } while (request.ContinuationToken != null);\n}\n\nasync function appendPackage(packages: any, pkgKey: string, bucketName: string, denyList: DenyListClient) {\n console.log(`Processing key: ${pkgKey}`);\n const [, packageName, versionStr] = constants.STORAGE_KEY_FORMAT_REGEX.exec(pkgKey)!;\n const version = new SemVer(versionStr);\n const found = packages.get(packageName)?.get(version.major);\n // If the version is === to the current latest, we'll be replacing that (so re-generated metadata are taken into account)\n if (found != null && version.compare(found.version) < 0) {\n console.log(`Skipping ${packageName}@${version} because it is not newer than the existing ${found.version}`);\n return;\n }\n\n console.log(`Checking if ${packageName}@${version.version} matches a deny list rule`);\n const blocked = denyList.lookup(packageName, version.version);\n if (blocked) {\n console.log(`Skipping ${packageName}@${version.version} because it is blocked by the deny list rule: ${JSON.stringify(blocked)}`);\n return;\n }\n\n console.log(`Registering ${packageName}@${version}`);\n\n // Donwload the tarball to inspect the `package.json` data therein.\n const pkg = await aws.s3().getObject({ Bucket: bucketName, Key: pkgKey }).promise();\n const metadataKey = pkgKey.replace(constants.PACKAGE_KEY_SUFFIX, constants.METADATA_KEY_SUFFIX);\n const metadataResponse = await aws.s3().getObject({ Bucket: bucketName, Key: metadataKey }).promise();\n const manifest = await new Promise<Buffer>((ok, ko) => {\n gunzip(Buffer.from(pkg.Body!), (err, tar) => {\n if (err) {\n return ko(err);\n }\n extract()\n .on('entry', (header, stream, next) => {\n if (header.name !== 'package/package.json') {\n // Not the file we are looking for, skip ahead (next run-loop tick).\n return setImmediate(next);\n }\n const chunks = new Array<Buffer>();\n return stream\n .on('data', (chunk) => chunks.push(Buffer.from(chunk)))\n .once('end', () => {\n ok(Buffer.concat(chunks));\n next();\n })\n .resume();\n })\n .once('finish', () => {\n ko(new Error('Could not find package/package.json in tarball!'));\n })\n .write(tar, (writeErr) => {\n if (writeErr) {\n ko(writeErr);\n }\n });\n });\n });\n // Add the PackageInfo into the working set\n const pkgMetadata = JSON.parse(manifest.toString('utf-8'));\n const npmMetadata = JSON.parse(metadataResponse?.Body?.toString('utf-8') ?? '{}');\n const major = new SemVer(pkgMetadata.version).major;\n if (!packages.has(pkgMetadata.name)) {\n packages.set(pkgMetadata.name, new Map());\n }\n packages.get(pkgMetadata.name)!.set(major, {\n author: pkgMetadata.author,\n description: pkgMetadata.description,\n keywords: pkgMetadata.keywords,\n languages: pkgMetadata.jsii.targets,\n license: pkgMetadata.license,\n major,\n metadata: npmMetadata,\n name: pkgMetadata.name,\n version: pkgMetadata.version,\n });\n\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", "/**\n * The name of an environment variable that contains the bucket name that includes the deny list.\n */\nexport const ENV_DENY_LIST_BUCKET_NAME = 'DENY_LIST_BUCKET_NAME';\n\n/**\n * The object key of the deny list in the bucket.\n */\nexport const ENV_DENY_LIST_OBJECT_KEY = 'DENY_LIST_OBJECT_KEY';\n\nexport const ENV_PRUNE_PACKAGE_DATA_BUCKET_NAME = 'PACKAGE_DATA_BUCKET_NAME';\nexport const ENV_PRUNE_PACKAGE_DATA_KEY_PREFIX = 'PACKAGE_DATA_KEY_PREFIX';\nexport const ENV_PRUNE_QUEUE_URL = 'PRUNE_QUEUE_URL';\nexport const ENV_PRUNE_ON_CHANGE_FUNCTION_NAME = 'ON_CHANGE_FUNCTION_NAME';\n\nexport const ENV_DELETE_OBJECT_DATA_BUCKET_NAME = 'PACKAGE_DATA_BUCKET_NAME';\n\nexport const METRICS_NAMESPACE = 'ConstructHub/DenyList';\n\nexport const enum MetricName {\n DENY_LIST_RULE_COUNT = 'DenyListRuleCount',\n}\n", "import * as AWS from 'aws-sdk';\nimport { s3 } from '../shared/aws.lambda-shared';\nimport { requireEnv } from '../shared/env.lambda-shared';\nimport { DenyListMap, DenyListRule } from './api';\nimport { ENV_DENY_LIST_BUCKET_NAME, ENV_DENY_LIST_OBJECT_KEY } from './constants';\n\n/**\n * A client for working with the deny list.\n */\nexport class DenyListClient {\n /**\n * Creates a new client for accessing the deny list.\n */\n public static async newClient() {\n const client = new DenyListClient();\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 _map: DenyListMap | undefined;\n\n private constructor() {\n this.bucketName = requireEnv(ENV_DENY_LIST_BUCKET_NAME);\n this.objectKey = requireEnv(ENV_DENY_LIST_OBJECT_KEY);\n this.s3 = s3();\n }\n\n /**\n * Downloads the deny list and stores it in memory.\n *\n * This must be called before `lookup()`.\n */\n private async init() {\n if (this._map) {\n throw new Error('init() cannot be called twice');\n }\n\n this._map = {};\n\n try {\n const params = {\n Bucket: this.bucketName,\n Key: this.objectKey,\n };\n\n const { Body: body } = await this.s3.getObject(params).promise();\n if (!body) {\n console.log(`WARNING: deny list body is empty at ${this.bucketName}/${this.objectKey}`);\n return;\n }\n\n const contents = body.toString('utf-8');\n\n // an empty string is a valid (empty) deny list\n if (contents.length === 0) {\n return;\n }\n\n const data = JSON.parse(contents) as DenyListMap;\n if (typeof(data) != 'object') {\n throw new Error(`Invalid format in deny list file at ${this.bucketName}/${this.objectKey}. Expecting a map`);\n }\n\n this._map = data;\n } catch (e) {\n if (e.code === 'NoSuchKey' || e.code === 'NoSuchBucket') {\n return;\n }\n\n throw new Error(`Unable to parse deny list file ${this.bucketName}/${this.objectKey}: ${e}`);\n }\n }\n\n /**\n * Checks if a package (name + version) is in the deny list.\n * @param name The name of the package\n * @param version The package version\n * @returns `undefined` if the package is not in the deny list or a\n * `DenyListRule` otherwise.\n */\n public lookup(name: string, version: string): DenyListRule | undefined {\n if (!this._map) {\n throw new Error('DenyListClient must be initialized');\n }\n\n return this._map[name] ?? this._map[`${name}/v${version}`];\n }\n\n /**\n * Returns a copy of the deny list map.\n */\n public get map() {\n if (!this._map) {\n throw new Error('DenyListClient must be initialized');\n }\n\n return this._map;\n }\n}\n", "/**\n * Supported languages to generate documentation in.\n */\nexport class DocumentationLanguage {\n /**\n * TypeScript.\n */\n public static readonly TYPESCRIPT = new DocumentationLanguage('typescript');\n\n /**\n * Python.\n */\n public static readonly PYTHON = new DocumentationLanguage('python');\n\n /**\n * Java.\n */\n public static readonly JAVA = new DocumentationLanguage('java');\n\n /**\n * All supported languages.\n */\n public static readonly ALL = [\n DocumentationLanguage.TYPESCRIPT,\n DocumentationLanguage.PYTHON,\n DocumentationLanguage.JAVA,\n ] as const;\n\n /**\n * Transform a literal string to the `DocumentationLanguage` object.\n *\n * Throws an `UnsupportedLanguageError` if the language is not supported.\n */\n public static fromString(lang: string) {\n switch (lang) {\n case DocumentationLanguage.TYPESCRIPT.toString():\n return DocumentationLanguage.TYPESCRIPT;\n case DocumentationLanguage.PYTHON.toString():\n return DocumentationLanguage.PYTHON;\n case DocumentationLanguage.JAVA.toString():\n return DocumentationLanguage.JAVA;\n default:\n throw new UnsupportedLanguageError(lang, DocumentationLanguage.ALL);\n }\n }\n\n private constructor(private readonly lang: string) {}\n\n public toString() {\n return this.lang;\n }\n}\n\nexport class UnsupportedLanguageError extends Error {\n constructor(lang: string, supported: readonly DocumentationLanguage[]) {\n super(`Unsupported language: ${lang}. Supported languages are: [${supported}]`);\n }\n}\n", "/*\n * IMPORTANT: This file is used both by bundled lambda functions and by\n * constructs. This means it should not directly or transitively import anything\n * not part of the package's `dependencies`, such as the `aws-sdk`.\n */\n\nimport { DocumentationLanguage } from './language';\n\n/**\n * Key prefix for the package data storage.\n */\nexport const STORAGE_KEY_PREFIX = 'data/';\n\n/**\n * Key suffix for storing npm package bundles.\n */\nexport const PACKAGE_KEY_SUFFIX = '/package.tgz';\n\n/**\n * Key suffix for storing npm package metadata.\n */\nexport const METADATA_KEY_SUFFIX = '/metadata.json';\n\n/**\n * The key suffix for (TypeScript) assembly files\n */\nexport const ASSEMBLY_KEY_SUFFIX = '/assembly.json';\n\n/**\n * The key suffix for a TypeScript doc artifact (root module).\n */\nexport const DOCS_KEY_SUFFIX_TYPESCRIPT = docsKeySuffix(DocumentationLanguage.TYPESCRIPT);\n\n/**\n * The key suffix for a Python doc artifact (root module).\n */\nexport const DOCS_KEY_SUFFIX_PYTHON = docsKeySuffix(DocumentationLanguage.PYTHON);\n\n/**\n * The key suffix for a Python doc artifact (root module).\n */\nexport const DOCS_KEY_SUFFIX_JAVA = docsKeySuffix(DocumentationLanguage.JAVA);\n\n/**\n * The key suffix matching any documentation artifact.\n */\nexport const DOCS_KEY_SUFFIX_ANY = docsKeySuffix('*');\n\n/**\n * Return the S3 object key prefix for a specific package name and optionally a\n * version. Note that the prefix does not end with a \"/\" so you will likely want\n * to add that if you want to match a specific set of objects.\n */\nexport function getObjectKeyPrefix(packageName: string, packageVersion?: string) {\n let key = `${STORAGE_KEY_PREFIX}${packageName}`;\n if (packageVersion) {\n key += `/v${packageVersion}`;\n }\n\n return key;\n}\n\n/**\n * Resolves the set of S3 object keys use for a specific package/version.\n */\nexport function getObjectKeys(packageName: string, packageVersion: string) {\n const prefix = getObjectKeyPrefix(packageName, packageVersion);\n return {\n assemblyKey: `${prefix}${ASSEMBLY_KEY_SUFFIX}`,\n packageKey: `${prefix}${PACKAGE_KEY_SUFFIX}`,\n metadataKey: `${prefix}${METADATA_KEY_SUFFIX}`,\n };\n}\n\n/**\n * The key suffix for documentation artifacts by language and submodule.\n */\nexport function docsKeySuffix(lang?: DocumentationLanguage | '*', submodule?: string) {\n return `/docs-${submodule ? `${submodule}-` : ''}${lang}.md`;\n}\n\n/**\n * Key suffix for beacon files when a particular feature is not supported for\n * the particular package (i.e: Python docs for a package that does not have a\n * Python target configured).\n */\nexport const NOT_SUPPORTED_SUFFIX = '.not-supported';\n\n/**\n * The key for the catalog document.\n */\nexport const CATALOG_KEY = 'catalog.json';\n\n/**\n * A regular expression that can be used to parse out a storage key.\n */\nexport const STORAGE_KEY_FORMAT_REGEX = new RegExp(`^${STORAGE_KEY_PREFIX}((?:@[^/]+/)?[^/]+)/v([^/]+)/.*$`);\n// Capture groups: \u2517\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u25011\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u251B \u2517\u2501\u25012\u2501\u2501\u251B\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,2BAA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