diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 000000000..b67ee85ea --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,43 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: bug, triage +assignees: '' + +--- + + + + +**What were you trying to accomplish?** + +## Expected Behavior + + + +## Current Behavior + + + +## Possible Solution + + + +## Steps to Reproduce (for bugs) + + +1. +2. +3. +4. + +## Environment + +* **Powertools version used**: +* **AWS Lambda function runtime:** +* **Debugging logs** + +```csharp +# paste logs here +``` diff --git a/.github/ISSUE_TEMPLATE/documentation-improvements.md b/.github/ISSUE_TEMPLATE/documentation-improvements.md new file mode 100644 index 000000000..8341ae4e0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/documentation-improvements.md @@ -0,0 +1,17 @@ +--- +name: Documentation improvements +about: Suggest a documentation update +title: '' +labels: documentation +assignees: '' + +--- + +**What were you initially searching for in the docs?** + + +**Is this related to an existing part of the documentation? Please share a link** + +**Describe how we could make it clearer** + +**If you have a proposed update, please share it here** diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 000000000..b837b7ad5 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: feature-request, triage +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** + + +**Describe the solution you'd like** + + +**Describe alternatives you've considered** + + +**Additional context** + diff --git a/.github/ISSUE_TEMPLATE/rfc.md b/.github/ISSUE_TEMPLATE/rfc.md new file mode 100644 index 000000000..a521ff873 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/rfc.md @@ -0,0 +1,62 @@ +--- +name: RFC +about: Feature design and proposals +title: 'RFC: ' +labels: RFC, triage +assignees: '' +approved by: '' +--- + +## Key information + +* RFC PR: (leave this empty) +* Related issue(s), if known: +* Area: (i.e. Tracer, Metrics, Logger, etc.) +* Meet [tenets](https://awslabs.github.io/aws-lambda-powertools-dotnet/#tenets): (Yes/no) +* Approved by: '' +* Reviewed by: '' + +## Summary +[summary]: #summary + +> One paragraph explanation of the feature. + +## Motivation +[motivation]: #motivation + +> Why are we doing this? What use cases does it support? What is the expected outcome? + +## Proposal +[proposal]: #proposal + +> This is the bulk of the RFC. + +> Explain the design in enough detail for somebody familiar with Powertools to understand it, and for somebody familiar with the implementation to implement it. + +**If this feature should be available in other runtimes (e.g. Java, Typescript), how would this look like to ensure consistency?** + +## User Experience + +**How would customers use it?** + +**Any configuration or corner cases you'd expect?** + +**Demonstration of before and after on how the experience will be better** + +## Drawbacks +[drawbacks]: #drawbacks + +> Why should we *not* do this? + +> Do we need additional dependencies? Impact performance/package size? + +## Rationale and alternatives +[rationale-and-alternatives]: #rationale-and-alternatives + +* **What other designs have been considered? Why not them?** +* **What is the impact of not doing this?** + +## Unresolved questions +[unresolved-questions]: #unresolved-questions + +> Optional, stash area for topics that need further development e.g. TBD diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..003e92265 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,25 @@ +**Issue #, if available:** + +## Description of changes: + + + +**Checklist** + + + +* [ ] [Meet tenets criteria](https://awslabs.github.io/aws-lambda-powertools-dotnet/#tenets) +* [ ] Update tests +* [ ] Update docs +* [ ] PR title follows [conventional commit semantics](https://github.com/awslabs/aws-lambda-powertools-dotnet/blob/develop/.github/semantic.yml) + +## Breaking change checklist + + + +**RFC issue #**: + +* [ ] Migration process documented +* [ ] Implement warnings (if it can live side by side) + +By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice. diff --git a/.github/auto_assign-issues.yml b/.github/auto_assign-issues.yml new file mode 100644 index 000000000..f5f16997b --- /dev/null +++ b/.github/auto_assign-issues.yml @@ -0,0 +1,8 @@ +addAssignees: true + +# The list of users to assign to new issues. +# If empty or not provided, the repository owner is assigned +assignees: + - t1agob + - sliedig + - amirkaws diff --git a/.github/boring-cyborg.yml b/.github/boring-cyborg.yml new file mode 100644 index 000000000..458c4b1b7 --- /dev/null +++ b/.github/boring-cyborg.yml @@ -0,0 +1,45 @@ +##### Labeler ########################################################################################################## +labelPRBasedOnFilePath: + area/logger: + - libraries/src/AWS.Lambda.Powertools.Logging/* + - libraries/src/AWS.Lambda.Powertools.Logging/**/* + area/tracer: + - libraries/src/AWS.Lambda.Powertools.Tracing/* + - libraries/src/AWS.Lambda.Powertools.Tracing/**/* + area/metrics: + - libraries/src/AWS.Lambda.Powertools.Metrics/* + - libraries/src/AWS.Lambda.Powertools.Metrics/**/* + + documentation: + - docs/* + - docs/**/* + - mkdocs.yml + + internal: + - .github/* + - .github/**/* + - .chglog/* + - .flake8 + - .gitignore + - .pre-commit-config.yaml + - Makefile + - CONTRIBUTING.md + - CODE_OF_CONDUCT.md + - LICENSE + + tests: + - libraries/tests/* + - libraries/tests/**/* + + +##### Greetings ######################################################################################################## +firstPRWelcomeComment: > + Thanks a lot for your first contribution! Please check out our contributing guidelines and don't hesitate to ask whatever you need. + +# Comment to be posted to congratulate user on their first merged PR +firstPRMergeComment: > + Awesome work, congrats on your first merged pull request and thank you for helping improve everyone's experience! + +# Comment to be posted to on first time issues +firstIssueWelcomeComment: > + Thanks for opening your first issue here! We'll come back to you as soon as we can. \ No newline at end of file diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml new file mode 100644 index 000000000..4fb0323ff --- /dev/null +++ b/.github/release-drafter.yml @@ -0,0 +1,39 @@ +change-template: "* $TITLE (#$NUMBER) by @$AUTHOR" +categories: + - title: '⚡ Breaking Changes' + labels: + - 'breaking-change' + - title: '🌟New features and non-breaking changes' + labels: + - 'major' + - 'feature' + - title: '🌟 Minor Changes' + labels: + - 'enhancement' + - title: '📜 Documentation updates' + labels: + - 'documentation' + - title: '🐛 Bug and hot fixes' + labels: + - 'bug' + - 'fix' + - title: '🚒 Deprecations' + labels: + - 'deprecated' + - title: '🔧 Maintenance' + labels: + - 'internal' + - 'dependencies' +exclude-labels: + - 'skip-changelog' +tag-template: 'v$NEXT_PATCH_VERSION' +template: | + ## Changes + + **[Human readable summary of changes]** + + $CHANGES + + ## This release was made possible by the following contributors: + + $CONTRIBUTORS diff --git a/.github/semantic.yml b/.github/semantic.yml new file mode 100644 index 000000000..39119da8d --- /dev/null +++ b/.github/semantic.yml @@ -0,0 +1,19 @@ +# conventional commit types: https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json +types: + - feat + - fix + - docs + - style + - refactor + - perf + - test + - build + - ci + - chore + - revert + - improv + +# Always validate the PR title +# and ignore the commits to lower the entry bar for contribution +# while titles make up the Release notes to ease maintenance overhead +titleOnly: true diff --git a/.github/stale.yml b/.github/stale.yml new file mode 100644 index 000000000..1bb42057e --- /dev/null +++ b/.github/stale.yml @@ -0,0 +1,17 @@ +only: issues +daysUntilStale: 30 +daysUntilClose: 7 +exemptLabels: + - bug + - documentation + - enhancement + - feature-request + - RFC +staleLabel: pending-close-response-required +markComment: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed if no further activity occurs. Thank you + for your contributions. +closeComment: > + This issue has been automatically closed because of inactivity. + Please open a new issue if you are still encountering problems. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 000000000..32c71566c --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,37 @@ +name: Build .NET + +on: + push: + branches: [ develop, main ] + pull_request: + branches: [ develop, main ] + +defaults: + run: + working-directory: ./libraries + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + - name: Setup .NET 6.0 + uses: actions/setup-dotnet@v1 + with: + dotnet-version: 6.0.x + - name: Install solution dependencies + run: dotnet restore + - name: Build + run: dotnet build --configuration Release --no-restore + - name: Test & Code Coverage + run: dotnet test --collect:"XPlat Code Coverage" -r ./codecov --no-restore --verbosity normal + - name: Codecov + uses: codecov/codecov-action@v2.1.0 + with: + token: ${{ secrets.CODECOV_TOKEN }} + flags: unittests + fail_ci_if_error: true + name: codecov-lambda-powertools-dotnet + verbose: true + directory: ./libraries/codecov diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 000000000..7ada67bfc --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,48 @@ +name: Docs + +on: + push: + branches: + - develop + - main + +jobs: + docs: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 0 + - name: Set up Python + uses: actions/setup-python@v2.2.2 + with: + python-version: "3.8" + - name: Capture branch and tag + id: branch_name + run: | + echo "SOURCE_BRANCH=${GITHUB_REF#refs/heads/}" >> $GITHUB_ENV + echo "SOURCE_TAG=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV + - name: Build docs website + run: make build-docs-website + - name: Deploy all docs + uses: peaceiris/actions-gh-pages@v3 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_dir: ./dist + apidocs: + runs-on: macos-latest + steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 0 + - name: Configure and build api docs generator + run: | + brew install -f docfx --skip-cask-deps --ignore-dependencies + docfx apidocs/docfx.json + - name: Release API docs to latest + uses: peaceiris/actions-gh-pages@v3 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_dir: ./apidocs/_site + keep_files: true + destination_dir: api diff --git a/.github/workflows/label_pr_on_title.yml b/.github/workflows/label_pr_on_title.yml new file mode 100644 index 000000000..45adc1af3 --- /dev/null +++ b/.github/workflows/label_pr_on_title.yml @@ -0,0 +1,87 @@ +name: Label PR based on title + +on: + workflow_run: + workflows: ["Record PR number"] + types: + - completed + +jobs: + upload: + runs-on: ubuntu-latest + # Guardrails to only ever run if PR recording workflow was indeed + # run in a PR event and ran successfully + if: > + ${{ github.event.workflow_run.event == 'pull_request' && + github.event.workflow_run.conclusion == 'success' }} + steps: + - name: 'Download artifact' + uses: actions/github-script@v5 + # For security, we only download artifacts tied to the successful PR recording workflow + with: + script: | + const fs = require('fs'); + + const artifacts = await github.rest.actions.listWorkflowRunArtifacts({ + owner: context.repo.owner, + repo: context.repo.repo, + run_id: ${{github.event.workflow_run.id }}, + }); + + const matchArtifact = artifacts.data.artifacts.filter(artifact => artifact.name == "pr")[0]; + + const artifact = await github.rest.actions.downloadArtifact({ + owner: context.repo.owner, + repo: context.repo.repo, + artifact_id: matchArtifact.id, + archive_format: 'zip', + }); + + fs.writeFileSync('${{github.workspace}}/pr.zip', Buffer.from(artifact.data)); + # NodeJS standard library doesn't provide ZIP capabilities; use system `unzip` command instead + - run: unzip pr.zip + + - name: 'Label PR based on title' + uses: actions/github-script@v5 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + # This safely runs in our base repo, not on fork + # thus allowing us to provide a write access token to label based on PR title + # and label PR based on semantic title accordingly + script: | + const fs = require('fs'); + const pr_number = Number(fs.readFileSync('./number')); + const pr_title = fs.readFileSync('./title', 'utf-8').trim(); + + const FEAT_REGEX = /feat(\((\w+)\))?(\:.+)/ + const BUG_REGEX = /(fix|bug)(\((\w+)\))?(\:.+)/ + const DOCS_REGEX = /(docs|doc)(\((\w+)\))?(\:.+)/ + const CHORE_REGEX = /(chore)(\((\w+)\))?(\:.+)/ + const DEPRECATED_REGEX = /(deprecated)(\((\w+)\))?(\:.+)/ + const REFACTOR_REGEX = /(refactor)(\((\w+)\))?(\:.+)/ + + const labels = { + "feature": FEAT_REGEX, + "bug": BUG_REGEX, + "documentation": DOCS_REGEX, + "internal": CHORE_REGEX, + "enhancement": REFACTOR_REGEX, + "deprecated": DEPRECATED_REGEX, + } + + for (const label in labels) { + const matcher = new RegExp(labels[label]) + const isMatch = matcher.exec(pr_title) + if (isMatch != null) { + console.info(`Auto-labeling PR ${pr_number} with ${label}`) + + await github.rest.issues.addLabels({ + issue_number: pr_number, + owner: context.repo.owner, + repo: context.repo.repo, + labels: [label] + }) + + break + } + } \ No newline at end of file diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 000000000..f903c9a7a --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,62 @@ +name: Publish new package version + +on: + push: + paths: + - 'version.json' + +jobs: + release: + if: ${{ github.ref == 'refs/heads/main' }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 0 + - name: Read AWS.Lambda.Powertools.Common version + id: common-version + uses: notiz-dev/github-action-json-property@release + with: + path: 'version.json' + prop_path: 'Core.Common' + - name: Read AWS.Lambda.Powertools.Logging version + id: logging-version + uses: notiz-dev/github-action-json-property@release + with: + path: 'version.json' + prop_path: 'Core.Logging' + - name: Read AWS.Lambda.Powertools.Tracing version + id: tracing-version + uses: notiz-dev/github-action-json-property@release + with: + path: 'version.json' + prop_path: 'Core.Tracing' + - name: Read AWS.Lambda.Powertools.Metrics version + id: metrics-version + uses: notiz-dev/github-action-json-property@release + with: + path: 'version.json' + prop_path: 'Core.Metrics' + - name: Setup .NET 6.0 + uses: actions/setup-dotnet@v1 + with: + dotnet-version: 6.0.x + - name: Setup semver + run: dotnet tool install -g dotnet-setversion + - name: Set assembly version in all projects + run: | + setversion ${{steps.common-version.outputs.prop}} libraries/src/AWS.Lambda.Powertools.Common/AWS.Lambda.Powertools.Common.csproj + setversion ${{steps.logging-version.outputs.prop}} libraries/src/AWS.Lambda.Powertools.Logging/AWS.Lambda.Powertools.Logging.csproj + setversion ${{steps.metrics-version.outputs.prop}} libraries/src/AWS.Lambda.Powertools.Metrics/AWS.Lambda.Powertools.Metrics.csproj + setversion ${{steps.tracing-version.outputs.prop}} libraries/src/AWS.Lambda.Powertools.Tracing/AWS.Lambda.Powertools.Tracing.csproj + - name: Authenticate to GitHub packages # Temporary package repository for publishing validation + run: dotnet nuget add source --username ${{ secrets.PUBLISH_USERNAME }} --password ${{ secrets.GITHUB_TOKEN }} --store-password-in-clear-text --name nuget ${{ secrets.NUGET_SOURCE }} + - name: Generate Nuget Packages + run: | + cd buildtools + dotnet build -c Release + - name: Publish Nuget Packages + run: | + cd deploy/nuget-packages + dotnet nuget push "*.nupkg" -k ${{ secrets.NUGET_API_KEY }} --skip-duplicate -s nuget + diff --git a/.github/workflows/record_pr.yml b/.github/workflows/record_pr.yml new file mode 100644 index 000000000..88edce19f --- /dev/null +++ b/.github/workflows/record_pr.yml @@ -0,0 +1,21 @@ +name: Record PR number + +on: + pull_request: + types: [opened, edited] + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + - name: Save PR number + run: | + mkdir -p ./pr + echo ${{ github.event.number }} > ./pr/number + echo "${{ github.event.pull_request.title }}" > ./pr/title + - uses: actions/upload-artifact@v2 + with: + name: pr + path: pr/ \ No newline at end of file diff --git a/.github/workflows/release-drafter.yml b/.github/workflows/release-drafter.yml new file mode 100644 index 000000000..59633a634 --- /dev/null +++ b/.github/workflows/release-drafter.yml @@ -0,0 +1,15 @@ +name: Release Drafter + +on: + push: + # branches to consider in the event; optional, defaults to all + branches: + - develop + +jobs: + update_release_draft: + runs-on: ubuntu-latest + steps: + - uses: release-drafter/release-drafter@v5 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..fba2714b2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,20 @@ +docs/node_modules +docs/.cache +docs/public + +apidocs/_site +apidocs/obj + +deploy/** + +.idea +.vscode +.vs/ + +examples/SimpleLambda/.aws-sam +examples/SimpleLambda/samconfig.toml + +AWS.Lambda.Powertools.sln.DotSettings.user +[Oo]bj/** +[Bb]in/** +.DS_Store diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 000000000..c97d51b40 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,27 @@ +{ + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "version": "0.2.0", + "configurations": [ + { + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/libraries/tests/Amazon.LambdaPowertools.Logging.Tests/bin/Debug/netcoreapp3.1/Amazon.LambdaPowertools.Logging.Tests.dll", + "args": [], + "cwd": "${workspaceFolder}/libraries/tests/Amazon.LambdaPowertools.Logging.Tests", + // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console + "console": "internalConsole", + "stopAtEntry": false + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach", + "processId": "${command:pickProcess}" + } + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..7a73a41bf --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,2 @@ +{ +} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 000000000..c258fc978 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,42 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/libraries/tests/Amazon.LambdaPowertools.Logging.Tests/Amazon.LambdaPowertools.Logging.Tests.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/libraries/tests/Amazon.LambdaPowertools.Logging.Tests/Amazon.LambdaPowertools.Logging.Tests.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "${workspaceFolder}/libraries/tests/Amazon.LambdaPowertools.Logging.Tests/Amazon.LambdaPowertools.Logging.Tests.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file diff --git a/404.html b/404.html new file mode 100644 index 000000000..5ab03a082 --- /dev/null +++ b/404.html @@ -0,0 +1,20 @@ + + + + + + + + + + + diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..398953761 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,12 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +This project follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) format for changes and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + + +## [Unreleased] + +## [0.1.0] - 2021-11-15 +### Added +- Public beta release diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..da8dca0c5 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,26 @@ +FROM mcr.microsoft.com/dotnet/sdk:6.0-bullseye-slim AS build-image + +ARG FUNCTION_DIR="/build" +ARG SAM_BUILD_MODE="run" +ENV PATH="/root/.dotnet/tools:${PATH}" + +RUN apt-get update && apt-get -y install zip + +RUN mkdir $FUNCTION_DIR +WORKDIR $FUNCTION_DIR +COPY examples/SimpleLambda/src/HelloWorld/Function.cs examples/SimpleLambda/src/HelloWorld/HelloWorld.csproj examples/SimpleLambda/src/HelloWorld/aws-lambda-tools-defaults.json $FUNCTION_DIR/examples/SimpleLambda/src/HelloWorld/ +COPY libraries/src/ $FUNCTION_DIR/libraries/src/ +COPY libraries/*.png $FUNCTION_DIR/libraries/ +RUN dotnet tool install -g Amazon.Lambda.Tools + +# Build and Copy artifacts depending on build mode. +RUN mkdir -p build_artifacts +WORKDIR $FUNCTION_DIR/examples/SimpleLambda/src/HelloWorld/ +RUN if [ "$SAM_BUILD_MODE" = "debug" ]; then dotnet lambda package --configuration Debug; else dotnet lambda package --configuration Release; fi +RUN if [ "$SAM_BUILD_MODE" = "debug" ]; then cp -r /bin/Debug/net6.0/publish/* /build/build_artifacts; else cp -r bin/Release/net6.0/publish/* /build/build_artifacts; fi + +FROM public.ecr.aws/lambda/dotnet:6 + +COPY --from=build-image /build/build_artifacts/ /var/task/ +# Command can be overwritten by providing a different command in the template directly. +CMD ["HelloWorld::HelloWorld.Function::FunctionHandler"] diff --git a/LICENSE b/LICENSE index 67db85882..12ad443cd 100644 --- a/LICENSE +++ b/LICENSE @@ -1,175 +1,14 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. +Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 000000000..3158dcef7 --- /dev/null +++ b/Makefile @@ -0,0 +1,17 @@ +.PHONY: build-docs build-docs-website docs-local docs-local-docker + +build-docs: + @$(MAKE) build-docs-website + +build-docs-website: + mkdir -p dist + docker build -t squidfunk/mkdocs-material ./docs/ + docker run --rm -t -v ${PWD}:/docs squidfunk/mkdocs-material build + cp -R site/* dist/ + +docs-local: + poetry run mkdocs serve + +docs-local-docker: + docker build -t squidfunk/mkdocs-material ./docs/ + docker run --rm -it -p 8000:8000 -v ${PWD}:/docs squidfunk/mkdocs-material \ No newline at end of file diff --git a/README.md b/README.md index 847260ca5..900107d4c 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,65 @@ -## My Project +# AWS Lambda Powertools for .NET -TODO: Fill this README out! +![aws provider](https://img.shields.io/badge/provider-AWS-orange?logo=amazon-aws&color=ff9900) [![Build](https://github.com/awslabs/aws-lambda-powertools-dotnet/actions/workflows/build.yml/badge.svg?branch=develop)](https://github.com/awslabs/aws-lambda-powertools-dotnet/actions/workflows/build.yml) -Be sure to: +AWS Lambda Powertools for .NET (C#) is suite of utilities for AWS Lambda functions to simplify implementation of serverless observability best practices such as tracing, structured logging, custom metrics. -* Change the title in this README -* Edit your repository description on GitHub +**[📜 Documentation](https://awslabs.github.io/aws-lambda-powertools-dotnet/)** | **[NuGet](https://www.nuget.org/)** | **[Roadmap](https://github.com/awslabs/aws-lambda-powertools-roadmap/projects/1)** | **[Examples](#examples)** | **[Blog post](https://aws.amazon.com/blogs/opensource/simplifying-serverless-best-practices-with-lambda-powertools/)** -## Security +> **Join us on the AWS Developers Slack at `#lambda-powertools`** - **[Invite, if you don't have an account](https://join.slack.com/t/awsdevelopers/shared_invite/zt-gu30gquv-EhwIYq3kHhhysaZ2aIX7ew)** -See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information. +## Features + +Lambda Powertools provides three core utilities: + +* **[Logging](https://awslabs.github.io/aws-lambda-powertools-dotnet/core/logging/)** - provides a custom logger class that outputs structured JSON. It allows you to pass in strings or more complex objects, and will take care of serializing the log output. Common use cases—such as logging the Lambda event payload and capturing cold start information—are handled for you, including appending custom keys to the logger at anytime. + +* **[Metrics](https://awslabs.github.io/aws-lambda-powertools-dotnet/core/metrics/)** - makes collecting custom metrics from your application simple, without the need to make synchronous requests to external systems. This functionality is powered by [Amazon CloudWatch Embedded Metric Format (EMF)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format.html), which allows for capturing metrics asynchronously. + +* **[Tracing](https://awslabs.github.io/aws-lambda-powertools-dotnet/core/tracing/)** - provides a simple way to send traces from functions to AWS X-Ray to provide visibility into function calls, interactions with other AWS services, or external HTTP requests. Annotations easily can be added to traces to allow filtering traces based on key information. For example, when using Tracer, a ColdStart annotation is created for you, so you can easily group and analyze traces where there was an initialization overhead. + +### Installation + +The AWS Lambda Powertools for .NET utilities (.NET 6) are available as Nuget packages. You can install the packages from Nuget gallery or from Visual Studio editor. Search `AWS.Lambda.Powertools*` to see various utilities available.Powertools is available on NuGet. + +* [AWS.Lambda.Powertools.Logging](https://www.nuget.org/packages?q=AWS.Lambda.Powertools.Logging): + + `dotnet nuget add AWS.Lambda.Powertools.Logging` + +* [AWS.Lambda.Powertools.Metrics](https://www.nuget.org/packages?q=AWS.Lambda.Powertools.Metrics): + + `dotnet nuget add AWS.Lambda.Powertools.Metrics` + +* [AWS.Lambda.Powertools.Tracing](https://www.nuget.org/packages?q=AWS.Lambda.Powertools.Tracing): + + `dotnet nuget add AWS.Lambda.Powertools.Tracing` + +## Examples + +We have provided examples focused specifically on each of the utilities. Each solution comes with AWS Serverless Application Model (AWS SAM) templates to run your functions as Zip package using the AWS Lambda .NET 6 managed runtime, or as a container package using the AWS base images for .NET. + +* **[Logging example](examples/Logging/README.md)** +* **[Metrics example](examples/Metrics/README.md)** +* **[Tracing example](examples/Tracing/README.md)** + +## Other members of the AWS Lambda Powertools family + +Not using .NET? No problem we have you covered. Here are the other members of the AWS Lambda Powertools family: + +* [AWS Lambda Powertools for Python](https://github.com/awslabs/aws-lambda-powertools-python) +* [AWS Lambda Powertools for Java](https://github.com/awslabs/aws-lambda-powertools-java) +* [AWS Lambda Powertools for TypeScript](https://github.com/awslabs/aws-lambda-powertools-typescript) + +## Credits + +* Structured logging initial implementation from [aws-lambda-logging](https://gitlab.com/hadrien/aws_lambda_logging) +* Powertools idea [DAZN Powertools](https://github.com/getndazn/dazn-lambda-powertools/) + +## Connect + +* **AWS Developers Slack**: `#lambda-powertools` - **[Invite, if you don't have an account](https://join.slack.com/t/awsdevelopers/shared_invite/zt-yryddays-C9fkWrmguDv0h2EEDzCqvw)** +* **Email**: aws-lambda-powertools-feedback@amazon.com ## License This project is licensed under the Apache-2.0 License. - diff --git a/apidocs/api/.gitignore b/apidocs/api/.gitignore new file mode 100644 index 000000000..f798527e6 --- /dev/null +++ b/apidocs/api/.gitignore @@ -0,0 +1,5 @@ +############### +# temp file # +############### +*.yml +.manifest diff --git a/apidocs/api/index.md b/apidocs/api/index.md new file mode 100644 index 000000000..e69de29bb diff --git a/apidocs/docfx.json b/apidocs/docfx.json new file mode 100644 index 000000000..00f5ca4fb --- /dev/null +++ b/apidocs/docfx.json @@ -0,0 +1,60 @@ +{ + "metadata": [ + { + "src": [ + { + "files": [ + "**/*.csproj" + ], + "src": "../libraries/src/", + "force": true + } + ], + "dest": "api", + "disableGitFeatures": false, + "disableDefaultFilter": false + } + ], + "build": { + "content": [ + { + "files": ["api/**.yml", "api/index.md"] + }, + { + "files": ["toc.yml", "*.md"] + } + ], + "resource": [ + { + "files": [ + "images/**" + ] + } + ], + "overwrite": [ + { + "files": ["apidoc/**.md"], + "exclude": ["obj/**", "_site/**"] + } + ], + "dest": "_site", + "globalMetadataFiles": [], + "globalMetadata": { + "_appTitle": "AWS Lambda Powertools for .NET", + "_appFaviconPath": "images/favicon.ico", + "_appLogoPath": "images/img.svg", + "_enableNewTab": true, + "_disableContribution": true, + "_enableSearch": "true", + "_appFooter": "AWS Lambda Powertools for .NET" + }, + "fileMetadataFiles": [], + "template": ["default", "templates/material"], + "postProcessors": ["ExtractSearchIndex"], + "markdownEngineName": "markdig", + "noLangKeyword": false, + "keepFileLink": false, + "cleanupCacheHistory": false, + "disableGitFeatures": false + } +} \ No newline at end of file diff --git a/apidocs/images/favicon.ico b/apidocs/images/favicon.ico new file mode 100644 index 000000000..dba84c499 Binary files /dev/null and b/apidocs/images/favicon.ico differ diff --git a/apidocs/images/img.svg b/apidocs/images/img.svg new file mode 100644 index 000000000..8d3ee48d7 --- /dev/null +++ b/apidocs/images/img.svg @@ -0,0 +1,38 @@ + + + + + + + + + + + + diff --git a/apidocs/index.md b/apidocs/index.md new file mode 100644 index 000000000..ab3e571d6 --- /dev/null +++ b/apidocs/index.md @@ -0,0 +1,14 @@ +# AWS Lambda Powertools for .NET API + +Welcome to the *AWS Lambda Powertools for .NET* API reference. This documentation contains the API details for all supported utilities. + +To get started use the `API` menu on the navigation bar, or search for specific keywords on the search box on top-right corner of your screen. + +> [!NOTE] +> Are you looking for documentation on how to use AWS Lambda Powertools for .NET utilities and code samples? +> +> 👉 [Here](https://awslabs.github.io/aws-lambda-powertools-dotnet/) is the perfect place to start. + +## Feedback + +If you have any feedback, create a new issue in the *AWS Lambda Powertools for .NET* repository on [GitHub](https://github.com/awslabs/aws-lambda-powertools-dotnet/issues). diff --git a/apidocs/templates/material/partials/head.tmpl.partial b/apidocs/templates/material/partials/head.tmpl.partial new file mode 100644 index 000000000..8d9c10c7e --- /dev/null +++ b/apidocs/templates/material/partials/head.tmpl.partial @@ -0,0 +1,21 @@ +{{!Copyright (c) Oscar Vasquez. All rights reserved. Licensed under the MIT license. See LICENSE file in the project root for full license information.}} + + + + + {{#title}}{{title}}{{/title}}{{^title}}{{>partials/title}}{{/title}} {{#_appTitle}}| {{_appTitle}} {{/_appTitle}} + + + + {{#_description}}{{/_description}} + + + + + + + + {{#_noindex}}{{/_noindex}} + {{#_enableSearch}}{{/_enableSearch}} + {{#_enableNewTab}}{{/_enableNewTab}} + \ No newline at end of file diff --git a/apidocs/templates/material/styles/main.css b/apidocs/templates/material/styles/main.css new file mode 100644 index 000000000..1314f563b --- /dev/null +++ b/apidocs/templates/material/styles/main.css @@ -0,0 +1,310 @@ +/* COLOR VARIABLES*/ +:root { + --header-bg-color: #2094F3; + --header-ft-color: #fff; + --highlight-light: #5e92f3; + --highlight-dark: #003c8f; + --accent-dim: #e0e0e0; + --accent-super-dim: #f3f3f3; + --font-color: #34393e; + --card-box-shadow: 0 1px 2px 0 rgba(61, 65, 68, 0.06), 0 1px 3px 1px rgba(61, 65, 68, 0.16); + --search-box-shadow: 0 1px 2px 0 rgba(41, 45, 48, 0.36), 0 1px 3px 1px rgba(41, 45, 48, 0.46); + --transition: 350ms; +} + +body { + color: var(--font-color); + font-family: "Roboto", sans-serif; + line-height: 1.5; + font-size: 16px; + -ms-text-size-adjust: 100%; + -webkit-text-size-adjust: 100%; + word-wrap: break-word; +} + +/* HIGHLIGHT COLOR */ + +button, +a { + color: var(--highlight-dark); + cursor: pointer; +} + +button:hover, +button:focus, +a:hover, +a:focus { + color: var(--highlight-light); + text-decoration: none; +} + +.toc .nav > li.active > a { + color: var(--highlight-dark); +} + +.toc .nav > li.active > a:hover, +.toc .nav > li.active > a:focus { + color: var(--highlight-light); +} + +.pagination > .active > a { + background-color: var(--header-bg-color); + border-color: var(--header-bg-color); +} + +.pagination > .active > a, +.pagination > .active > a:focus, +.pagination > .active > a:hover, +.pagination > .active > span, +.pagination > .active > span:focus, +.pagination > .active > span:hover { + background-color: var(--highlight-light); + border-color: var(--highlight-light); +} + +/* HEADINGS */ + +h1 { + font-weight: 600; + font-size: 32px; +} + +h2 { + font-weight: 600; + font-size: 24px; + line-height: 1.8; +} + +h3 { + font-weight: 600; + font-size: 20px; + line-height: 1.8; +} + +h5 { + font-size: 14px; + padding: 10px 0px; +} + +article h1, +article h2, +article h3, +article h4 { + margin-top: 35px; + margin-bottom: 15px; +} + +article h4 { + padding-bottom: 8px; + border-bottom: 2px solid #ddd; +} + +/* NAVBAR */ + +.navbar-brand { + margin-right: 20px; +} + +.navbar-brand > img { + color: var(--header-ft-color); +} + +.navbar { + border: none; + /* Both navbars use box-shadow */ + -webkit-box-shadow: var(--card-box-shadow); + -moz-box-shadow: var(--card-box-shadow); + box-shadow: var(--card-box-shadow); +} + +.subnav { + border-top: 1px solid #ddd; + background-color: #fff; +} + +.navbar-inverse { + background-color: var(--header-bg-color); + z-index: 100; +} + +.navbar-inverse .navbar-nav > li > a, +.navbar-inverse .navbar-text { + color: var(--header-ft-color); + background-color: var(--header-bg-color); + border-bottom: 3px solid transparent; + padding-bottom: 12px; + transition: 350ms; +} + +.navbar-inverse .navbar-nav > li > a:focus, +.navbar-inverse .navbar-nav > li > a:hover { + color: var(--header-ft-color); + background-color: var(--header-bg-color); + border-bottom: 3px solid white; +} + +.navbar-inverse .navbar-nav > .active > a, +.navbar-inverse .navbar-nav > .active > a:focus, +.navbar-inverse .navbar-nav > .active > a:hover { + color: var(--header-ft-color); + background-color: var(--header-bg-color); + border-bottom: 3px solid white; +} + +.navbar-form .form-control { + border: 0; + border-radius: 4px; + box-shadow: var(--search-box-shadow); + transition:var(--transition); +} + +.navbar-form .form-control:hover { + background-color: var(--accent-dim); +} + +/* NAVBAR TOGGLED (small screens) */ + +.navbar-inverse .navbar-collapse, .navbar-inverse .navbar-form { + border: none; +} +.navbar-inverse .navbar-toggle { + box-shadow: var(--card-box-shadow); + border: none; +} + +.navbar-inverse .navbar-toggle:focus, +.navbar-inverse .navbar-toggle:hover { + background-color: var(--highlight-dark); +} + +/* SIDEBAR */ + +.toc .level1 > li { + font-weight: 400; +} + +.toc .nav > li > a { + color: var(--font-color); +} + +.sidefilter { + background-color: #fff; + border-left: none; + border-right: none; +} + +.sidefilter { + background-color: #fff; + border-left: none; + border-right: none; +} + +.toc-filter { + padding: 5px; + margin: 0; + box-shadow: var(--card-box-shadow); + transition:var(--transition); +} + +.toc-filter:hover { + background-color: var(--accent-super-dim); +} + +.toc-filter > input { + border: none; + background-color: inherit; + transition: inherit; +} + +.toc-filter > .filter-icon { + display: none; +} + +.sidetoc > .toc { + background-color: #fff; + overflow-x: hidden; +} + +.sidetoc { + background-color: #fff; + border: none; +} + +/* ALERTS */ + +.alert { + padding: 0px 0px 5px 0px; + color: inherit; + background-color: inherit; + border: none; + box-shadow: var(--card-box-shadow); +} + +.alert > p { + margin-bottom: 0; + padding: 5px 10px; +} + +.alert > ul { + margin-bottom: 0; + padding: 5px 40px; +} + +.alert > h5 { + padding: 10px 15px; + margin-top: 0; + text-transform: uppercase; + font-weight: bold; + border-radius: 4px 4px 0 0; +} + +.alert-info > h5 { + color: #1976d2; + border-bottom: 4px solid #1976d2; + background-color: #e3f2fd; +} + +.alert-warning > h5 { + color: #f57f17; + border-bottom: 4px solid #f57f17; + background-color: #fff3e0; +} + +.alert-danger > h5 { + color: #d32f2f; + border-bottom: 4px solid #d32f2f; + background-color: #ffebee; +} + +/* CODE HIGHLIGHT */ +pre { + padding: 9.5px; + margin: 0 0 10px; + font-size: 13px; + word-break: break-all; + word-wrap: break-word; + background-color: #fffaef; + border-radius: 4px; + border: none; + box-shadow: var(--card-box-shadow); +} + +/* STYLE FOR IMAGES */ + +.article .small-image { + margin-top: 15px; + box-shadow: var(--card-box-shadow); + max-width: 350px; +} + +.article .medium-image { + margin-top: 15px; + box-shadow: var(--card-box-shadow); + max-width: 550px; +} + +.article .large-image { + margin-top: 15px; + box-shadow: var(--card-box-shadow); + max-width: 700px; +} \ No newline at end of file diff --git a/apidocs/toc.yml b/apidocs/toc.yml new file mode 100644 index 000000000..2ce0a61f3 --- /dev/null +++ b/apidocs/toc.yml @@ -0,0 +1,3 @@ +- name: API + href: api/ + homepage: api/index.md diff --git a/buildtools/NuGet.Config b/buildtools/NuGet.Config new file mode 100644 index 000000000..7ca4b2b80 --- /dev/null +++ b/buildtools/NuGet.Config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/buildtools/build.proj b/buildtools/build.proj new file mode 100644 index 000000000..8e0a9718b --- /dev/null +++ b/buildtools/build.proj @@ -0,0 +1,54 @@ + + + + + + + + Release + dotnet pack --no-build -c $(Configuration) -o $(MSBuildThisFileDirectory)/../deploy/nuget-packages + dotnet pack --no-build -o $(MSBuildThisFileDirectory)/../deploy/nuget-packages + false + + + + + + + + + + + + + + + + + + + + + dotnet test -c $(Configuration) + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/buildtools/common.props b/buildtools/common.props new file mode 100644 index 000000000..8b94a290b --- /dev/null +++ b/buildtools/common.props @@ -0,0 +1,25 @@ + + + + Amazon Web Services + + Library + false + + true + + Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + https://github.com/awslabs/aws-lambda-powertools-dotnet + Apache-2.0 + + + false + false + false + false + false + false + false + + + \ No newline at end of file diff --git a/buildtools/nuget.exe b/buildtools/nuget.exe new file mode 100644 index 000000000..1a67d80c9 Binary files /dev/null and b/buildtools/nuget.exe differ diff --git a/docs/Dockerfile b/docs/Dockerfile new file mode 100644 index 000000000..7bf267f4f --- /dev/null +++ b/docs/Dockerfile @@ -0,0 +1,2 @@ +FROM squidfunk/mkdocs-material +RUN pip install mkdocs-git-revision-date-plugin diff --git a/docs/changelog.md b/docs/changelog.md new file mode 100644 index 000000000..c2705ba58 --- /dev/null +++ b/docs/changelog.md @@ -0,0 +1,2 @@ +[comment]: <> (Includes Changelog content entire file as a snippet) +--8<-- "CHANGELOG.md" diff --git a/docs/core/logging.md b/docs/core/logging.md new file mode 100644 index 000000000..2b77a2c5e --- /dev/null +++ b/docs/core/logging.md @@ -0,0 +1,459 @@ +--- +title: Logging +description: Core utility +--- + +Logging provides an opinionated logger with output structured as JSON. + +## Key features + +* Capture key fields from Lambda context, cold start and structures logging output as JSON +* Log Lambda event when instructed (disabled by default) +* Log sampling enables DEBUG log level for a percentage of requests (disabled by default) +* Append additional keys to structured log at any point in time + +## Getting started + +Logging requires two settings: + +Setting | Description | Environment variable | Attribute parameter +------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------- +**Logging level** | Sets how verbose Logger should be (Information, by default) | `LOG_LEVEL` | `LogLevel` +**Service** | Sets **Service** key that will be present across all log statements | `POWERTOOLS_SERVICE_NAME` | `Service` + +### Example using AWS Serverless Application Model (AWS SAM) + +You can also override log level by setting **`POWERTOOLS_LOG_LEVEL`** env var. Here is an example using AWS Serverless Application Model (AWS SAM) + +=== "template.yaml" + + ```yaml hl_lines="8 9" + Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function + Properties: + ... + Environment: + Variables: + POWERTOOLS_LOG_LEVEL: Debug + POWERTOOLS_SERVICE_NAME: example + ``` + +You can also explicitly set a service name via **`POWERTOOLS_SERVICE_NAME`** env var. This sets **service** key that will be present across all log statements. + +## Standard structured keys + +Your logs will always include the following keys to your structured logging: + +Key | Type | Example | Description +------------------------------------------------- | ------------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------- +**Timestamp** | string | "2020-05-24 18:17:33,774" | Timestamp of actual log statement +**Level** | string | "Information" | Logging level +**Name** | string | "Powertools Logger" | Logger name +**ColdStart** | bool | true| ColdStart value. +**Service** | string | "payment" | Service name defined. "service_undefined" will be used if unknown +**SamplingRate** | int | 0.1 | Debug logging sampling rate in percentage e.g. 10% in this case +**Message** | string | "Collecting payment" | Log statement value. Unserializable JSON values will be casted to string +**FunctionName**| string | "example-powertools-HelloWorldFunction-1P1Z6B39FLU73" +**FunctionVersion**| string | "12" +**FunctionMemorySize**| string | "128" +**FunctionArn**| string | "arn:aws:lambda:eu-west-1:012345678910:function:example-powertools-HelloWorldFunction-1P1Z6B39FLU73" +**XRayTraceId**| string | "1-5759e988-bd862e3fe1be46a994272793" | X-Ray Trace ID when Lambda function has enabled Tracing +**FunctionRequestId**| string | "899856cb-83d1-40d7-8611-9e78f15f32f4" | AWS Request ID from lambda context + +## Logging incoming event + +When debugging in non-production environments, you can instruct Logger to log the incoming event with `LogEvent` parameter or via POWERTOOLS_LOGGER_LOG_EVENT environment variable. + +!!! warning + Log event is disabled by default to prevent sensitive info being logged. + +=== "Function.cs" + + ```c# hl_lines="6" + /** + * Handler for requests to Lambda function. + */ + public class Function + { + [Logging(LogEvent = true)] + public async Task FunctionHandler + (APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + ... + } + } + ``` + +## Setting a Correlation ID + +You can set a Correlation ID using `CorrelationIdPath` parameter by passing a [JSON Pointer expression](https://datatracker.ietf.org/doc/html/draft-ietf-appsawg-json-pointer-03){target="_blank"}. + +=== "Function.cs" + + ```c# hl_lines="6" + /** + * Handler for requests to Lambda function. + */ + public class Function + { + [Logging(CorrelationIdPath = "/headers/my_request_id_header")] + public async Task FunctionHandler + (APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + ... + } + } + ``` +=== "Example Event" + + ```json hl_lines="3" + { + "headers": { + "my_request_id_header": "correlation_id_value" + } + } + ``` + +=== "Example CloudWatch Logs excerpt" + + ```json hl_lines="15" + { + "cold_start": true, + "xray_trace_id": "1-61b7add4-66532bb81441e1b060389429", + "function_name": "test", + "function_version": "$LATEST", + "function_memory_size": 128, + "function_arn": "arn:aws:lambda:eu-west-1:12345678910:function:test", + "function_request_id": "52fdfc07-2182-154f-163f-5f0f9a621d72", + "timestamp": "2021-12-13T20:32:22.5774262Z", + "level": "Information", + "service": "lambda-example", + "name": "AWS.Lambda.Powertools.Logging.Logger", + "message": "Collecting payment", + "sampling_rate": 0.7, + "correlation_id": "correlation_id_value", + } + ``` +We provide [built-in JSON Pointer expression](https://datatracker.ietf.org/doc/html/draft-ietf-appsawg-json-pointer-03){target="_blank"} +for known event sources, where either a request ID or X-Ray Trace ID are present. + +=== "Function.cs" + + ```c# hl_lines="6" + /** + * Handler for requests to Lambda function. + */ + public class Function + { + [Logging(CorrelationIdPath = CorrelationIdPaths.API_GATEWAY_REST)] + public async Task FunctionHandler + (APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + ... + } + } + ``` + +=== "Example Event" + + ```json hl_lines="3" + { + "RequestContext": { + "RequestId": "correlation_id_value" + } + } + ``` + +=== "Example CloudWatch Logs excerpt" + + ```json hl_lines="15" + { + "cold_start": true, + "xray_trace_id": "1-61b7add4-66532bb81441e1b060389429", + "function_name": "test", + "function_version": "$LATEST", + "function_memory_size": 128, + "function_arn": "arn:aws:lambda:eu-west-1:12345678910:function:test", + "function_request_id": "52fdfc07-2182-154f-163f-5f0f9a621d72", + "timestamp": "2021-12-13T20:32:22.5774262Z", + "level": "Information", + "service": "lambda-example", + "name": "AWS.Lambda.Powertools.Logging.Logger", + "message": "Collecting payment", + "sampling_rate": 0.7, + "correlation_id": "correlation_id_value", + } + ``` + +## Appending additional keys + +!!! info "Custom keys are persisted across warm invocations" + Always set additional keys as part of your handler to ensure they have the latest value, or explicitly clear them with [`ClearState=true`](#clearing-all-state). + +You can append your own keys to your existing logs via `AppendKey`. + +=== "Function.cs" + + ```c# hl_lines="11 19" + /** + * Handler for requests to Lambda function. + */ + public class Function + { + [Logging(LogEvent = true)] + public async Task FunctionHandler + (APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + ... + Logger.AppendKey("test", "willBeLogged"); + ... + var customKeys = new Dictionary + { + {"test1", "value1"}, + {"test2", "value2"} + }; + + Logger.AppendKeys(customKeys); + ... + } + } + ``` + +### Removing additional keys + +You can remove any additional key from entry using `Logger.RemoveKeys()`. + +=== "Function.cs" + + ```c# hl_lines="21 22" + /** + * Handler for requests to Lambda function. + */ + public class Function + { + [Logging(LogEvent = true)] + public async Task FunctionHandler + (APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + ... + Logger.AppendKey("test", "willBeLogged"); + ... + var customKeys = new Dictionary + { + {"test1", "value1"}, + {"test2", "value2"} + }; + + Logger.AppendKeys(customKeys); + ... + Logger.RemoveKeys("test"); + Logger.RemoveKeys("test1", "test2"); + ... + } + } + ``` + +## Extra Keys + +Extra keys argument is available for all log levels' methods, as implemented in the standard logging library - e.g. Logger.Information, Logger.Warning. + +It accepts any dictionary, and all keyword arguments will be added as part of the root structure of the logs for that log statement. + +!!! info + Any keyword argument added using extra keys will not be persisted for subsequent messages. + +=== "Function.cs" + + ```c# hl_lines="16" + /** + * Handler for requests to Lambda function. + */ + public class Function + { + [Logging(LogEvent = true)] + public async Task FunctionHandler + (APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + ... + var extraKeys = new Dictionary + { + {"extraKey1", "value1"} + }; + + Logger.LogInformation(extraKeys, "Collecting payment"); + ... + } + } + ``` + +### Clearing all state + +Logger is commonly initialized in the global scope. Due to [Lambda Execution Context reuse](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-context.html), this means that custom keys can be persisted across invocations. If you want all custom keys to be deleted, you can use `ClearState=true` attribute on `[Logging]` attribute. + +=== "Function.cs" + + ```cs hl_lines="6 13" + /** + * Handler for requests to Lambda function. + */ + public class Function + { + [Logging(ClearState = true)] + public async Task FunctionHandler + (APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + ... + if (apigProxyEvent.Headers.ContainsKey("SomeSpecialHeader")) + { + Logger.AppendKey("SpecialKey", "value"); + } + + Logger.LogInformation("Collecting payment"); + ... + } + } + ``` +=== "#1 Request" + + ```json hl_lines="11" + { + "level": "Information", + "message": "Collecting payment", + "timestamp": "2021-12-13T20:32:22.5774262Z", + "service": "payment", + "cold_start": true, + "function_name": "test", + "function_memory_size": 128, + "function_arn": "arn:aws:lambda:eu-west-1:12345678910:function:test", + "function_request_id": "52fdfc07-2182-154f-163f-5f0f9a621d72", + "special_key": "value" + } + ``` + +=== "#2 Request" + + ```json + { + "level": "Information", + "message": "Collecting payment", + "timestamp": "2021-12-13T20:32:22.5774262Z", + "service": "payment", + "cold_start": true, + "function_name": "test", + "function_memory_size": 128, + "function_arn": "arn:aws:lambda:eu-west-1:12345678910:function:test", + "function_request_id": "52fdfc07-2182-154f-163f-5f0f9a621d72" + } + ``` + +## Sampling debug logs + +You can dynamically set a percentage of your logs to **DEBUG** level via env var `POWERTOOLS_LOGGER_SAMPLE_RATE` or +via `SamplingRate` parameter on attribute. + +!!! info + Configuration on environment variable is given precedence over sampling rate configuration on attribute, provided it's in valid value range. + +=== "Sampling via attribute parameter" + + ```c# hl_lines="6" + /** + * Handler for requests to Lambda function. + */ + public class Function + { + [Logging(SamplingRate = 0.5)] + public async Task FunctionHandler + (APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + ... + } + } + ``` + +=== "Sampling via environment variable" + + ```yaml hl_lines="8" + Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function + Properties: + ... + Environment: + Variables: + POWERTOOLS_LOGGER_SAMPLE_RATE: 0.5 + ``` + +## Configure Log Output Casing + +By definition *AWS Lambda Powertools for .NET* outputs logging keys using **snake case** (e.g. *"function_memory_size": 128*). This allows developers using different AWS Lambda Powertools runtimes, to search logs across services written in languages such as Python or TypeScript. + +If you want to override the default behaviour you can either set the desired casing through attributes, as described in the example below, or by setting the `POWERTOOLS_LOGGER_CASE` environment variable on your AWS Lambda function. Allowed values are: `CamelCase`, `PascalCase` and `SnakeCase`. + +=== "Output casing via attribute parameter" + + ```c# hl_lines="6" + /** + * Handler for requests to Lambda function. + */ + public class Function + { + [Logging(LoggerOutputCase = LoggerOutputCase.CamelCase)] + public async Task FunctionHandler + (APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + ... + } + } + ``` + +Below are some output examples for different casing. + +=== "Camel Case" + + ```json + { + "level": "Information", + "message": "Collecting payment", + "timestamp": "2021-12-13T20:32:22.5774262Z", + "service": "payment", + "coldStart": true, + "functionName": "test", + "functionMemorySize": 128, + "functionArn": "arn:aws:lambda:eu-west-1:12345678910:function:test", + "functionRequestId": "52fdfc07-2182-154f-163f-5f0f9a621d72" + } + ``` + +=== "Pascal Case" + + ```json + { + "Level": "Information", + "Message": "Collecting payment", + "Timestamp": "2021-12-13T20:32:22.5774262Z", + "Service": "payment", + "ColdStart": true, + "FunctionName": "test", + "FunctionMemorySize": 128, + "FunctionArn": "arn:aws:lambda:eu-west-1:12345678910:function:test", + "FunctionRequestId": "52fdfc07-2182-154f-163f-5f0f9a621d72" + } + ``` + +=== "Snake Case" + + ```json + { + "level": "Information", + "message": "Collecting payment", + "timestamp": "2021-12-13T20:32:22.5774262Z", + "service": "payment", + "cold_start": true, + "function_name": "test", + "function_memory_size": 128, + "function_arn": "arn:aws:lambda:eu-west-1:12345678910:function:test", + "function_request_id": "52fdfc07-2182-154f-163f-5f0f9a621d72" + } + ``` diff --git a/docs/core/metrics.md b/docs/core/metrics.md new file mode 100644 index 000000000..239c1b434 --- /dev/null +++ b/docs/core/metrics.md @@ -0,0 +1,333 @@ +--- +title: Metrics +description: Core utility +--- + +Metrics creates custom metrics asynchronously by logging metrics to standard output following [Amazon CloudWatch Embedded Metric Format (EMF)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format.html). + +These metrics can be visualized through [Amazon CloudWatch Console](https://console.aws.amazon.com/cloudwatch/). + +## Key features + +* Aggregate up to 100 metrics using a single CloudWatch EMF object (large JSON blob) +* Validate against common metric definitions mistakes (metric unit, values, max dimensions, max metrics, etc) +* Metrics are created asynchronously by CloudWatch service, no custom stacks needed +* Context manager to create a one off metric with a different dimension + +## Terminologies + +If you're new to Amazon CloudWatch, there are two terminologies you must be aware of before using this utility: + +* **Namespace**. It's the highest level container that will group multiple metrics from multiple services for a given application, for example `ServerlessEcommerce`. +* **Dimensions**. Metrics metadata in key-value format. They help you slice and dice metrics visualization, for example `ColdStart` metric by Payment `service`. + +
+ +
Metric terminology, visually explained
+
+ + +## Getting started + +Metric has two global settings that will be used across all metrics emitted: + +Setting | Description | Environment variable | Constructor parameter +------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------- +**Metric namespace** | Logical container where all metrics will be placed e.g. `ServerlessAirline` | `POWERTOOLS_METRICS_NAMESPACE` | `Namespace` +**Service** | Optionally, sets **service** metric dimension across all metrics e.g. `payment` | `POWERTOOLS_SERVICE_NAME` | `Service` + +!!! tip "Use your application or main service as the metric namespace to easily group all metrics" + +> Example using AWS Serverless Application Model (AWS SAM) + +=== "template.yml" + +```yaml hl_lines="9 10" +Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function + Properties: + ... + Environment: + Variables: + POWERTOOLS_SERVICE_NAME: Payment + POWERTOOLS_METRICS_NAMESPACE: ServerlessAirline +``` + +=== "Function.cs" + + ```csharp hl_lines="4" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + Metrics(Namespace = "ServerlessAirline", Service = "Orders", CaptureColdStart = true, RaiseOnEmptyMetrics = true)] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + ... + } + } + ``` + +!!! Warning "Metrics Attribute placement" + **`Metrics`** is implemented as a Singleton to keep track of your aggregate metrics in memory and make them accessible anywhere in your code. To guarantee that metrics are flushed properly the **`MetricsAttribute`** must be added on the lambda handler. + +!!! info "Autocomplete Metric Units" + All parameters in **`Metrics Attribute`** are optional. Following rules apply: + + - **Namespace:** **`Empty`** string by default. You can either specify it in code or environment variable. If not present before flushing metrics, a **`SchemaValidationException`** will be thrown. + - **Service:** **`service_undefined`** by default. You can either specify it in code or environment variable. + - **CaptureColdStart:** **`false`** by default. + - **RaiseOnEmptyMetrics:** **`false`** by default. + +### Creating metrics + +You can create metrics using **`AddMetric`**, and you can create dimensions for all your aggregate metrics using **`AddDimension`** method. + +=== "Metrics" + + ```csharp hl_lines="8" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + + [Metrics(Namespace = "ExampleApplication", Service = "Booking")] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + Metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.COUNT); + } + } + ``` +=== "Metrics with custom dimensions" + + ```csharp hl_lines="8-9" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + + [Metrics(Namespace = "ExampleApplication", Service = "Booking")] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + Metrics.AddDimension("Environment","Prod"); + Metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.COUNT); + } + } + ``` + +!!! tip "Autocomplete Metric Units" + `MetricUnit` enum facilitates finding a supported metric unit by CloudWatch. + +!!! note "Metrics overflow" + CloudWatch EMF supports a max of 100 metrics per batch. Metrics utility will flush all metrics when adding the 100th metric. Subsequent metrics, e.g. 101th, will be aggregated into a new EMF object, for your convenience. + +!!! warning "Metric value must be a positive number" + Metric values must be a positive number otherwise an `ArgumentException` will be thrown. + +!!! warning "Do not create metrics or dimensions outside the handler" + Metrics or dimensions added in the global scope will only be added during cold start. Disregard if that's the intended behaviour. + +### Adding default dimensions + +You can use **`SetDefaultDimensions`** method to persist dimensions across Lambda invocations. + +=== "SetDefaultDimensions method" + + ```csharp hl_lines="4 5 6 7 12" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + private Dictionary _defaultDimensions = new Dictionary{ + {"Environment", "Prod"}, + {"Another", "One"} + }; + + [Metrics(Namespace = "ExampleApplication", Service = "Booking")] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + Metrics.SetDefaultDimensions(_defaultDimensions); + Metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.COUNT); + } + } + ``` + +### Flushing metrics + +With **`MetricsAttribute`** all your metrics are validated, serialized and flushed to standard output when lambda handler completes execution or when you had the 100th metric to memory. + +During metrics validation, if no metrics are provided then a warning will be logged, but no exception will be raised. + +=== "Function.cs" + + ```csharp hl_lines="8" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + + [Metrics(Namespace = "ExampleApplication", Service = "Booking")] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + Metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.COUNT); + } + } + ``` +=== "Example CloudWatch Logs excerpt" + + ```json hl_lines="2 7 10 15 22" + { + "BookingConfirmation": 1.0, + "_aws": { + "Timestamp": 1592234975665, + "CloudWatchMetrics": [ + { + "Namespace": "ExampleApplication", + "Dimensions": [ + [ + "service" + ] + ], + "Metrics": [ + { + "Name": "BookingConfirmation", + "Unit": "Count" + } + ] + } + ] + }, + "service": "ExampleService" + } + ``` + +!!! tip "Metric validation" + If metrics are provided, and any of the following criteria are not met, **`SchemaValidationException`** will be raised: + + * Maximum of 9 dimensions + * Namespace is set + * Metric units must be [supported by CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html) + +!!! info "We do not emit 0 as a value for ColdStart metric for cost reasons. [Let us know](https://github.com/awslabs/aws-lambda-powertools-python/issues/new?assignees=&labels=feature-request%2C+triage&template=feature_request.md&title=) if you'd prefer a flag to override it" + +#### Raising SchemaValidationException on empty metrics + +If you want to ensure that at least one metric is emitted, you can pass **`RaiseOnEmptyMetrics`** to the Metrics attribute: + +=== "Function.cs" + + ```python hl_lines="5" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + + [Metrics(RaiseOnEmptyMetrics = true)] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + ... + ``` + +### Capturing cold start metric + +You can optionally capture cold start metrics by setting **`CaptureColdStart`** parameter to `true`. + +=== "Function.cs" + + ```csharp hl_lines="5" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + + [Metrics(CaptureColdStart = true)] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + ... + ``` + +If it's a cold start invocation, this feature will: + +* Create a separate EMF blob solely containing a metric named `ColdStart` +* Add `function_name` and `service` dimensions + +This has the advantage of keeping cold start metric separate from your application metrics, where you might have unrelated dimensions. + +## Advanced + +### Adding metadata + +You can add high-cardinality data as part of your Metrics log with `AddMetadata` method. This is useful when you want to search highly contextual information along with your metrics in your logs. + +!!! info + **This will not be available during metrics visualization** - Use **dimensions** for this purpose + +=== "Function.cs" + + ```csharp hl_lines="9" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + + [Metrics(Namespace = ExampleApplication, Service = "Booking")] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + Metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.COUNT); + Metrics.AddMetadata("BookingId", "683EEB2D-B2F3-4075-96EE-788E6E2EED45"); + ... + ``` + +=== "Example CloudWatch Logs excerpt" + + ```json hl_lines="23" + { + "SuccessfulBooking": 1.0, + "_aws": { + "Timestamp": 1592234975665, + "CloudWatchMetrics": [ + { + "Namespace": "ExampleApplication", + "Dimensions": [ + [ + "service" + ] + ], + "Metrics": [ + { + "Name": "SuccessfulBooking", + "Unit": "Count" + } + ] + } + ] + }, + "Service": "Booking", + "BookingId": "683EEB2D-B2F3-4075-96EE-788E6E2EED45" + } + ``` + +### Single metric with a different dimension + +CloudWatch EMF uses the same dimensions across all your metrics. Use **`PushSingleMetric`** if you have a metric that should have different dimensions. + +!!! info + Generally, this would be an edge case since you [pay for unique metric](https://aws.amazon.com/cloudwatch/pricing). Keep the following formula in mind: + + **unique metric = (metric_name + dimension_name + dimension_value)** + +=== "Function.cs" + + ```csharp hl_lines="8-17" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + + [Metrics(Namespace = ExampleApplication, Service = "Booking")] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + Metrics.PushSingleMetric( + metricName: "ColdStart", + value: 1, + unit: MetricUnit.COUNT, + nameSpace: "ExampleApplication", + service: "Booking", + defaultDimensions: new Dictionary + { + {"FunctionContext", "$LATEST"} + }); + ... + ``` diff --git a/docs/core/tracing.md b/docs/core/tracing.md new file mode 100644 index 000000000..b3ebd455e --- /dev/null +++ b/docs/core/tracing.md @@ -0,0 +1,230 @@ +--- +title: Tracing +description: Core utility +--- + +Powertools tracing is an opinionated thin wrapper for [AWS X-Ray .NET SDK](https://github.com/aws/aws-xray-sdk-dotnet/) +a provides functionality to reduce the overhead of performing common tracing tasks. + +![Tracing showcase](../media/tracer_utility_showcase.png) + +## Key Features + +* Helper methods to improve the developer experience for creating [custom AWS X-Ray subsegments](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-dotnet-subsegments.html). +* Capture cold start as annotation. +* Capture function responses and full exceptions as metadata. +* Better experience when developing with multiple threads. +* Auto-patch supported modules by AWS X-Ray + +## Initialization + +Before you use this utility, your AWS Lambda function [must have permissions](https://docs.aws.amazon.com/lambda/latest/dg/services-xray.html#services-xray-permissions) to send traces to AWS X-Ray. + +To enable active tracing on an AWS Serverless Application Model (AWS SAM) AWS::Serverless::Function resource, use the `Tracing` property. You can use the Globals section of the AWS SAM template to set this for all + +### Using AWS Serverless Application Model (AWS SAM) + +=== "template.yaml" + + ```yaml hl_lines="8 11" + Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function + Properties: + ... + Runtime: dotnet6.0 + + Tracing: Active + Environment: + Variables: + POWERTOOLS_SERVICE_NAME: example + ``` + +The Powertools service name is used as the X-Ray namespace. This can be set using the environment variable +`POWERTOOLS_SERVICE_NAME` + +### Lambda handler + +To enable Powertools tracing to your function add the `[Tracing]` attribute to your `FunctionHandler` method or on +any method will capture the method as a separate subsegment automatically. You can optionally choose to customize +segment name that appears in traces. + +=== "Tracing attribute" + + ```c# hl_lines="3 14 20" + public class Function + { + [Tracing] + public async Task FunctionHandler + (APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + await BusinessLogic1() + .ConfigureAwait(false); + + await BusinessLogic2() + .ConfigureAwait(false); + } + + [Tracing] + private async Task BusinessLogic1() + { + + } + + [Tracing] + private async Task BusinessLogic2() + { + + } + } + ``` + +=== "Custom Segment names" + + ```c# hl_lines="3" + public class Function + { + [Tracing(SegmentName = "YourCustomName")] + public async Task FunctionHandler + (APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + ... + } + } + ``` + +By default, this attribute will automatically record method responses and exceptions. You can change the default behavior by setting +the environment variables `POWERTOOLS_TRACER_CAPTURE_RESPONSE` and `POWERTOOLS_TRACER_CAPTURE_ERROR` as needed. Optionally, you can override behavior by +different supported `CaptureMode` to record response, exception or both. + +!!! warning "Returning sensitive information from your Lambda handler or functions, where `Tracing` is used?" + You can disable attribute from capturing their responses and exception as tracing metadata with **`captureMode=DISABLED`** + or globally by setting environment variables **`POWERTOOLS_TRACER_CAPTURE_RESPONSE`** and **`POWERTOOLS_TRACER_CAPTURE_ERROR`** to **`false`** + +=== "Disable on attribute" + + ```c# hl_lines="3" + public class Function + { + [Tracing(CaptureMode = TracingCaptureMode.Disabled)] + public async Task FunctionHandler + (APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + ... + } + } + ``` + +=== "Disable Globally" + + ```yaml hl_lines="11 12" + Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function + Properties: + ... + Runtime: dotnetcore3.1 + + Tracing: Active + Environment: + Variables: + POWERTOOLS_TRACER_CAPTURE_RESPONSE: false + POWERTOOLS_TRACER_CAPTURE_ERROR: false + ``` + +### Annotations & Metadata + +**Annotations** are key-values associated with traces and indexed by AWS X-Ray. You can use them to filter traces and to +create [Trace Groups](https://aws.amazon.com/about-aws/whats-new/2018/11/aws-xray-adds-the-ability-to-group-traces/) to slice and dice your transactions. + +**Metadata** are key-values also associated with traces but not indexed by AWS X-Ray. You can use them to add additional +context for an operation using any native object. + +=== "Annotations" + + You can add annotations using `AddAnnotation()` method from Tracing + ```c# hl_lines="9" + using AWS.Lambda.Powertools.Tracing; + + public class Function + { + [Tracing] + public async Task FunctionHandler + (APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + Tracing.AddAnnotation("annotation", "value"); + } + } + ``` + +=== "Metadata" + + You can add metadata using `AddMetadata()` method from Tracing + ```c# hl_lines="9" + using AWS.Lambda.Powertools.Tracing; + + public class Function + { + [Tracing] + public async Task FunctionHandler + (APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + Tracing.AddMetadata("content", "value"); + } + } + ``` + +## Utilities + +Tracing modules comes with certain utility method when you don't want to use attribute for capturing a code block +under a subsegment, or you are doing multithreaded programming. Refer examples below. + +=== "Functional Api" + + ```c# hl_lines="8 9 10 12 13 14" + using AWS.Lambda.Powertools.Tracing; + + public class Function + { + public async Task FunctionHandler + (APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + Tracing.WithSubsegment("loggingResponse", (subsegment) => { + // Some business logic + }); + + Tracing.WithSubsegment("localNamespace", "loggingResponse", (subsegment) => { + // Some business logic + }); + } + } + ``` + +=== "Multi Threaded Programming" + + ```c# hl_lines="13-16" + using AWS.Lambda.Powertools.Tracing; + + public class Function + { + public async Task FunctionHandler + (APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + // Extract existing trace data + var entity = Tracing.GetEntity(); + + var task = Task.Run(() => + { + Tracing.WithSubsegment("InlineLog", entity, (subsegment) => + { + // Business logic in separate task + }); + }); + } + } + ``` + +## Instrumenting SDK clients and HTTP calls + +User should make sure to instrument the SDK clients explicitly based on the function dependency. Refer details on +[how to instrument SDK client with Xray](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-dotnet-sdkclients.html) and [outgoing http calls](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-dotnet-httpclients.html). diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 000000000..82bec3373 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,84 @@ +--- +title: AWS Lambda Powertools for .NET (developer preview) +description: AWS Lambda Powertools for .NET (developer preview) +--- + +# AWS Lambda Powertools for .NET + +AWS Lambda Powertools for .NET is a suite of utilities for [AWS Lambda](https://aws.amazon.com/lambda/) functions to ease adopting best practices such as tracing, structured logging, custom metrics, and more. Please note, **Powertools for .NET is optimised for .NET 6 only**. + +The GitHub repository for this project can be found [here](https://github.com/awslabs/aws-lambda-powertools-dotnet). + +!!! warning "Do not use this library in production" + + **AWS Lambda Powertools for .NET is currently released as a alpha developer preview** and is intended strictly for feedback purposes only. This version is not stable, and significant breaking changes might incur as part of the upcoming production-ready release. + + Your support is much appreciated. If you encounter any problems, [please raise an issue](https://github.com/awslabs/aws-lambda-powertools-dotnet/issues/new/choose). + + **Do not use this library for production workloads.** + +## Available Powertools libraries + +| Utility | Description +| ------------------------------------------------- | --------------------------------------------------------------------------------- +[Tracing](./core/tracing.md) | Decorators and utilities to trace Lambda function handlers, and both synchronous and asynchronous functions +[Logger](./core/logging.md) | Structured logging made easier, and decorator to enrich structured logging with key Lambda context details +[Metrics](./core/metrics.md) | Custom AWS metrics created asynchronously via CloudWatch Embedded Metric Format (EMF) + +!!! info "Looking for a quick read through how the core features are used?" + Check out the [Simplifying serverless best practices with Lambda Powertools](https://aws.amazon.com/blogs/opensource/simplifying-serverless-best-practices-with-lambda-powertools/) blog post with a practical example. + +## Install + +The AWS Lambda Powertools for .NET utilities (.NET 6) are available as Nuget packages. You can install the packages from Nuget gallery or from Visual Studio editor. Search `AWS.Lambda.Powertools*` to see various utilities available.Powertools is available on NuGet. + +* [AWS.Lambda.Powertools.Tracing](https://www.nuget.org/packages?q=AWS.Lambda.Powertools.Tracing): + + `dotnet nuget add AWS.Lambda.Powertools.Tracing` + +* [AWS.Lambda.Powertools.Logging](https://www.nuget.org/packages?q=AWS.Lambda.Powertools.Logging): + + `dotnet nuget add AWS.Lambda.Powertools.Logging` + +* [AWS.Lambda.Powertools.Metrics](https://www.nuget.org/packages?q=AWS.Lambda.Powertools.Metrics): + + `dotnet nuget add AWS.Lambda.Powertools.Metrics` + +### SAM CLI custom template + +We have provided you with a custom template for the Serverless Application Model (AWS SAM) command-line interface (CLI). This generates a starter project that allows you to interactively choose the Powertools features that enables you to include in your project. + +```bash +sam init --location https://github.com/aws-samples/cookiecutter-aws-sam-dotnet +``` + +To use the SAM CLI, you need the following tools. + +* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) +* .NET 6.0 (LTS) - [Install .NET 6.0](https://www.microsoft.com/net/download) +* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community) + +### Examples + +We have provided a few examples that should you how to use the each of the core Powertools features. + +* [Tracer](https://github.com/awslabs/aws-lambda-powertools-dotnet/tree/main/examples/tracer){target="_blank"} example +* [Logger](https://github.com/awslabs/aws-lambda-powertools-dotnet/tree/main/examples/logger/){target="_blank"} example +* [Metrics](https://github.com/awslabs/aws-lambda-powertools-dotnet/tree/main/examples/metrics/){target="_blank"} example + +## Other members of the AWS Lambda Powertools family + +Not using .NET? No problem we have you covered. Here are the other members of the AWS Lambda Powertools family: + +* [AWS Lambda Powertools for Python](https://github.com/awslabs/aws-lambda-powertools-python) +* [AWS Lambda Powertools for Java](https://github.com/awslabs/aws-lambda-powertools-java) +* [AWS Lambda Powertools for TypeScript](https://github.com/awslabs/aws-lambda-powertools-typescript) + +## Connect + +* **AWS Developers Slack**: `#lambda-powertools` - [Invite, if you don't have an account](https://join.slack.com/t/awsdevelopers/shared_invite/zt-yryddays-C9fkWrmguDv0h2EEDzCqvw){target="_blank"} +* **Email**: aws-lambda-powertools-feedback@amazon.com + +## Credits + +* Credits for the Lambda Powertools idea go to [DAZN](https://github.com/getndazn){target="_blank"} and their [DAZN Lambda Powertools](https://github.com/getndazn/dazn-lambda-powertools/){target="_blank"}. diff --git a/docs/javascript/aws-amplify.min.js b/docs/javascript/aws-amplify.min.js new file mode 100644 index 000000000..f19b36a50 --- /dev/null +++ b/docs/javascript/aws-amplify.min.js @@ -0,0 +1,108 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("aws_amplify",[],t):"object"==typeof exports?exports.aws_amplify=t():e.aws_amplify=t()}(this,(function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=157)}([function(e,t,n){"use strict";n.d(t,"a",(function(){return a})),n.d(t,"b",(function(){return u})),n.d(t,"f",(function(){return c})),n.d(t,"g",(function(){return f})),n.d(t,"h",(function(){return l})),n.d(t,"c",(function(){return h})),n.d(t,"e",(function(){return g})),n.d(t,"d",(function(){return m}));var r=n(1),i=function(){var e=[],t=[],n=new Set,a=function(n){return e.forEach((function(e){n.add(e.middleware,Object(r.__assign)({},e))})),t.forEach((function(e){n.addRelativeTo(e.middleware,Object(r.__assign)({},e))})),n},u=function(e){var t=[];return e.before.forEach((function(e){0===e.before.length&&0===e.after.length?t.push(e):t.push.apply(t,Object(r.__spread)(u(e)))})),t.push(e),e.after.reverse().forEach((function(e){0===e.before.length&&0===e.after.length?t.push(e):t.push.apply(t,Object(r.__spread)(u(e)))})),t},c=function(){var n,i=[],a=[],c={};return e.forEach((function(e){var t=Object(r.__assign)(Object(r.__assign)({},e),{before:[],after:[]});t.name&&(c[t.name]=t),i.push(t)})),t.forEach((function(e){var t=Object(r.__assign)(Object(r.__assign)({},e),{before:[],after:[]});t.name&&(c[t.name]=t),a.push(t)})),a.forEach((function(e){if(e.toMiddleware){var t=c[e.toMiddleware];if(void 0===t)throw new Error(e.toMiddleware+" is not found when adding "+(e.name||"anonymous")+" middleware "+e.relation+" "+e.toMiddleware);"after"===e.relation&&t.after.push(e),"before"===e.relation&&t.before.push(e)}})),(n=i,n.sort((function(e,t){return o[t.step]-o[e.step]||s[t.priority||"normal"]-s[e.priority||"normal"]}))).map(u).reduce((function(e,t){return e.push.apply(e,Object(r.__spread)(t)),e}),[]).map((function(e){return e.middleware}))},f={add:function(t,i){void 0===i&&(i={});var o=i.name,s=Object(r.__assign)({step:"initialize",priority:"normal",middleware:t},i);if(o){if(n.has(o))throw new Error("Duplicate middleware name '"+o+"'");n.add(o)}e.push(s)},addRelativeTo:function(e,i){var o=i.name,s=Object(r.__assign)({middleware:e},i);if(o){if(n.has(o))throw new Error("Duplicated middleware name '"+o+"'");n.add(o)}t.push(s)},clone:function(){return a(i())},use:function(e){e.applyToStack(f)},remove:function(r){return"string"==typeof r?function(r){var i=!1,o=function(e){return!e.name||e.name!==r||(i=!0,n.delete(r),!1)};return e=e.filter(o),t=t.filter(o),i}(r):function(r){var i=!1,o=function(e){return e.middleware!==r||(i=!0,e.name&&n.delete(e.name),!1)};return e=e.filter(o),t=t.filter(o),i}(r)},removeByTag:function(r){var i=!1,o=function(e){var t=e.tags,o=e.name;return!t||!t.includes(r)||(o&&n.delete(o),i=!0,!1)};return e=e.filter(o),t=t.filter(o),i},concat:function(e){var t=a(i());return t.use(e),t},applyToStack:a,resolve:function(e,t){var n,i;try{for(var o=Object(r.__values)(c().reverse()),s=o.next();!s.done;s=o.next()){e=(0,s.value)(e,t)}}catch(e){n={error:e}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return e}};return f},o={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},s={high:3,normal:2,low:1},a=function(){function e(e){this.middlewareStack=i(),this.config=e}return e.prototype.send=function(e,t,n){var r="function"!=typeof t?t:void 0,i="function"==typeof t?t:n,o=e.resolveMiddleware(this.middlewareStack,this.config,r);if(!i)return o(e).then((function(e){return e.output}));o(e).then((function(e){return i(null,e.output)}),(function(e){return i(e)})).catch((function(){}))},e.prototype.destroy=function(){this.config.requestHandler.destroy&&this.config.requestHandler.destroy()},e}(),u=function(){this.middlewareStack=i()};function c(e){return encodeURIComponent(e).replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16)}))}var f=function(e){return Array.isArray(e)?e:[e]},l=function(e){for(var t in e)e.hasOwnProperty(t)&&void 0!==e[t]["#text"]?e[t]=e[t]["#text"]:"object"==typeof e[t]&&null!==e[t]&&(e[t]=l(e[t]));return e},d=function(){var e=Object.getPrototypeOf(this).constructor,t=Function.bind.apply(String,Object(r.__spread)([null],arguments)),n=new t;return Object.setPrototypeOf(n,e.prototype),n};d.prototype=Object.create(String.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf(d,String);var h=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(r.__extends)(t,e),t.prototype.deserializeJSON=function(){return JSON.parse(e.prototype.toString.call(this))},t.prototype.toJSON=function(){return e.prototype.toString.call(this)},t.fromObject=function(e){return e instanceof t?e:new t(e instanceof String||"string"==typeof e?e:JSON.stringify(e))},t}(d),p=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],v=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function g(e){var t=e.getUTCFullYear(),n=e.getUTCMonth(),r=e.getUTCDay(),i=e.getUTCDate(),o=e.getUTCHours(),s=e.getUTCMinutes(),a=e.getUTCSeconds();return p[r]+", "+(i<10?"0"+i:""+i)+" "+v[n]+" "+t+" "+(o<10?"0"+o:""+o)+":"+(s<10?"0"+s:""+s)+":"+(a<10?"0"+a:""+a)+" GMT"}var m="***SensitiveInformation***"},function(e,t,n){"use strict";n.r(t),n.d(t,"__extends",(function(){return i})),n.d(t,"__assign",(function(){return o})),n.d(t,"__rest",(function(){return s})),n.d(t,"__decorate",(function(){return a})),n.d(t,"__param",(function(){return u})),n.d(t,"__metadata",(function(){return c})),n.d(t,"__awaiter",(function(){return f})),n.d(t,"__generator",(function(){return l})),n.d(t,"__createBinding",(function(){return d})),n.d(t,"__exportStar",(function(){return h})),n.d(t,"__values",(function(){return p})),n.d(t,"__read",(function(){return v})),n.d(t,"__spread",(function(){return g})),n.d(t,"__spreadArrays",(function(){return m})),n.d(t,"__await",(function(){return b})),n.d(t,"__asyncGenerator",(function(){return y})),n.d(t,"__asyncDelegator",(function(){return w})),n.d(t,"__asyncValues",(function(){return _})),n.d(t,"__makeTemplateObject",(function(){return S})),n.d(t,"__importStar",(function(){return E})),n.d(t,"__importDefault",(function(){return M})),n.d(t,"__classPrivateFieldGet",(function(){return A})),n.d(t,"__classPrivateFieldSet",(function(){return I})); +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +var r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function i(e,t){function n(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var o=function(){return(o=Object.assign||function(e){for(var t,n=1,r=arguments.length;n=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s}function u(e,t){return function(n,r){t(n,r,e)}}function c(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function f(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))}function l(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function v(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s}function g(){for(var e=[],t=0;t1||a(e,t)}))})}function a(e,t){try{(n=i[e](t)).value instanceof b?Promise.resolve(n.value.v).then(u,c):f(o[0][2],n)}catch(e){f(o[0][3],e)}var n}function u(e){a("next",e)}function c(e){a("throw",e)}function f(e,t){e(t),o.shift(),o.length&&a(o[0][0],o[0][1])}}function w(e){var t,n;return t={},r("next"),r("throw",(function(e){throw e})),r("return"),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:b(e[r](t)),done:"return"===r}:i?i(t):t}:i}}function _(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=p(e),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise((function(r,i){(function(e,t,n,r){Promise.resolve(r).then((function(t){e({value:t,done:n})}),t)})(r,i,(t=e[n](t)).done,t.value)}))}}}function S(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function E(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function M(e){return e&&e.__esModule?e:{default:e}}function A(e,t){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return t.get(e)}function I(e,t,n){if(!t.has(e))throw new TypeError("attempted to set private field on non-instance");return t.set(e,n),n}},function(e,t,n){"use strict";n.d(t,"b",(function(){return r})),n.d(t,"a",(function(){return o}));var r=function(){function e(e){this.statusCode=e.statusCode,this.headers=e.headers||{},this.body=e.body}return e.isInstance=function(e){if(!e)return!1;var t=e;return"number"==typeof t.statusCode&&"object"==typeof t.headers},e}(),i=n(1),o=function(){function e(e){this.method=e.method||"GET",this.hostname=e.hostname||"localhost",this.port=e.port,this.query=e.query||{},this.headers=e.headers||{},this.body=e.body,this.protocol=e.protocol?":"!==e.protocol.substr(-1)?e.protocol+":":e.protocol:"https:",this.path=e.path?"/"!==e.path.charAt(0)?"/"+e.path:e.path:"/"}return e.isInstance=function(e){if(!e)return!1;var t=e;return"method"in t&&"protocol"in t&&"hostname"in t&&"path"in t&&"object"==typeof t.query&&"object"==typeof t.headers},e.prototype.clone=function(){var t,n=new e(Object(i.__assign)(Object(i.__assign)({},this),{headers:Object(i.__assign)({},this.headers)}));return n.query&&(n.query=(t=n.query,Object.keys(t).reduce((function(e,n){var r,o=t[n];return Object(i.__assign)(Object(i.__assign)({},e),((r={})[n]=Array.isArray(o)?Object(i.__spread)(o):o,r))}),{}))),n},e}()},function(e,t,n){"use strict";n.d(t,"f",(function(){return A})),n.d(t,"t",(function(){return I})),n.d(t,"y",(function(){return k})),n.d(t,"s",(function(){return x})),n.d(t,"e",(function(){return C})),n.d(t,"x",(function(){return P})),n.d(t,"g",(function(){return N})),n.d(t,"h",(function(){return R})),n.d(t,"d",(function(){return D})),n.d(t,"c",(function(){return U})),n.d(t,"b",(function(){return B})),n.d(t,"a",(function(){return j})),n.d(t,"u",(function(){return F})),n.d(t,"v",(function(){return q})),n.d(t,"i",(function(){return K})),n.d(t,"w",(function(){return H})),n.d(t,"j",(function(){return V})),n.d(t,"p",(function(){return G})),n.d(t,"k",(function(){return W})),n.d(t,"q",(function(){return $})),n.d(t,"l",(function(){return Y})),n.d(t,"n",(function(){return J})),n.d(t,"r",(function(){return Z})),n.d(t,"o",(function(){return X})),n.d(t,"m",(function(){return Q}));var r=n(6),i=n(32),o=n.n(i);function s(e){var t=new Error(e);return t.source="ulid",t}var a="0123456789ABCDEFGHJKMNPQRSTVWXYZ",u=a.length,c=Math.pow(2,48)-1;function f(e,t,n){return t>e.length-1?e:e.substr(0,t)+n+e.substr(t+1)}function l(e){var t=Math.floor(e()*u);return t===u&&(t=u-1),a.charAt(t)}function d(e,t){if(isNaN(e))throw new Error(e+" must be a number");if(e>c)throw s("cannot encode time greater than "+c);if(e<0)throw s("time must be positive");if(!1===Number.isInteger(e))throw s("time must be an integer");for(var n=void 0,r="";t>0;t--)r=a.charAt(n=e%u)+r,e=(e-n)/u;return r}function h(e,t){for(var n="";e>0;e--)n=l(t)+n;return n}function p(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments[1];t||(t="undefined"!=typeof window?window:null);var r=t&&(t.crypto||t.msCrypto);if(r)return function(){var e=new Uint8Array(1);return r.getRandomValues(e),e[0]/255};try{var i=n(485);return function(){return i.randomBytes(1).readUInt8()/255}}catch(e){}if(e){try{console.error("secure crypto unusable, falling back to insecure Math.random()!")}catch(e){}return function(){return Math.random()}}throw s("secure crypto unusable, insecure Math.random not allowed")}function v(e){e||(e=p());var t=0,n=void 0;return function(r){if(isNaN(r)&&(r=Date.now()),r<=t){var i=n=function(e){for(var t=void 0,n=e.length,r=void 0,i=void 0,o=u-1;!t&&n-- >=0;){if(r=e[n],-1===(i=a.indexOf(r)))throw s("incorrectly encoded string");i!==o?t=f(e,n,a[i+1]):e=f(e,n,a[0])}if("string"==typeof t)return t;throw s("cannot increment this string")}(n);return d(t,10)+i}t=r;var o=n=h(16,e);return d(r,10)+o}}g||(g=p());var g,m=n(109),b=n(4);function y(e){return(y="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var w,_=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))},S=function(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},M=function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},A=function(e,t){if(void 0===t&&(t=!0),t)throw new Error("Invalid "+e)},I=function(e){return void 0===e||null==e},k=function e(t,n,r){var i,o=!1;if(0===r.length)return!0;switch(n){case"not":i="every",o=!0;break;case"and":i="every";break;case"or":i="some";break;default:A(n)}var s=r[i]((function(n){if(Object(b.k)(n)){var r=n.field,i=n.operator,o=n.operand,s=t[r];return O(s,i,o)}if(Object(b.j)(n)){var a=n.type,u=n.predicates;return e(t,a,u)}throw new Error("Not a predicate or group")}));return o?!s:s},O=function(e,t,n){switch(t){case"ne":return e!==n;case"eq":return e===n;case"le":return e<=n;case"lt":return e=n;case"gt":return e>n;case"between":var r=E(n,2),i=r[0],o=r[1];return e>=i&&e<=o;case"beginsWith":return e.startsWith(n);case"contains":return e.indexOf(n)>-1;case"notContains":return-1===e.indexOf(n);default:return A(t,!1),!1}},x=function(e){return e&&"function"==typeof e.copyOf},C=function(e){var t={};return Object.keys(e.models).forEach((function(n){t[n]={indexes:[],relationTypes:[]};var r=e.models[n];Object.keys(r.fields).forEach((function(e){var i=r.fields[e];if("object"===y(i.type)&&"model"in i.type){var o=i.association.connectionType;t[n].relationTypes.push({fieldName:i.name,modelName:i.type.model,relationType:o,targetName:i.association.targetName,associatedWith:i.association.associatedWith}),"BELONGS_TO"===o&&t[n].indexes.push(i.association.targetName)}})),r.attributes&&r.attributes.forEach((function(e){if("key"===e.type){var r=e.properties.fields;r&&r.forEach((function(e){t[n].indexes.includes(e)||t[n].indexes.push(e)}))}}))})),t},T=new WeakMap,P=function(e,t,n,r,i){var o=n.relationships,s=i(n.name,e),a=o[e],u=[],c=s.copyOf(t,(function(e){a.relationTypes.forEach((function(o){var s=i(n.name,o.modelName);switch(o.relationType){case"HAS_ONE":if(t[o.fieldName]){var a=void 0;try{a=r(s,t[o.fieldName])}catch(e){}u.push({modelName:o.modelName,item:t[o.fieldName],instance:a}),e[o.fieldName]=e[o.fieldName].id}break;case"BELONGS_TO":if(t[o.fieldName]){a=void 0;try{a=r(s,t[o.fieldName])}catch(e){}e[o.fieldName]._deleted||u.push({modelName:o.modelName,item:t[o.fieldName],instance:a})}e[o.targetName]=e[o.fieldName]?e[o.fieldName].id:null,delete e[o.fieldName];break;case"HAS_MANY":break;default:A(o.relationType)}}))}));u.unshift({modelName:e,item:c,instance:c}),T.has(n)||T.set(n,Array.from(n.modelTopologicalOrdering.keys()));var f=T.get(n);return u.sort((function(e,t){return f.indexOf(e.modelName)-f.indexOf(t.modelName)})),u},N=function(e,t){var n="";return e.some((function(e){e.modelName===t&&(n=e.targetName)})),n},R=function(e,t){return e.find((function(e){return e===t}))};!function(e){e.DATASTORE="datastore",e.USER="user",e.SYNC="sync",e.STORAGE="storage"}(w||(w={}));var L,j=w.DATASTORE,D=w.USER,U=w.SYNC,B=w.STORAGE,F=function(){return new Promise((function(e){var t,n=Object(m.v4)(),r=function(){L=!1,e(!0)},i=function(){return _(void 0,void 0,void 0,(function(){return S(this,(function(r){switch(r.label){case 0:return t&&t.result&&"function"==typeof t.result.close?[4,t.result.close()]:[3,2];case 1:r.sent(),r.label=2;case 2:return[4,indexedDB.deleteDatabase(n)];case 3:return r.sent(),L=!0,[2,e(!1)]}}))}))};return!0===L?i():!1===L||null===indexedDB?r():((t=indexedDB.open(n)).onerror=r,void(t.onsuccess=i))}))},z=function(){return(e=1,r.Buffer.from(o.a.lib.WordArray.random(e).toString(),"hex")).readUInt8(0)/255;var e};function q(e){var t=v(z);return function(){return t(e)}}function K(){return"undefined"!=typeof performance&&performance&&"function"==typeof performance.now?0|performance.now():Date.now()}function H(e){return function(t,n){var r,i;try{for(var o=M(e),s=o.next();!s.done;s=o.next()){var a=s.value,u=a.field,c=a.sortDirection===b.e.ASCENDING?1:-1;if(t[u]n[u])return 1*c}}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(r)throw r.error}}return 0}}var V=function(e){return!!/^\d{4}-\d{2}-\d{2}(Z|[+-]\d{2}:\d{2}($|:\d{2}))?$/.exec(e)},G=function(e){return!!/^\d{2}:\d{2}(:\d{2}(.\d+)?)?(Z|[+-]\d{2}:\d{2}($|:\d{2}))?$/.exec(e)},W=function(e){return!!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(.\d+)?)?(Z|[+-]\d{2}:\d{2}($|:\d{2}))?$/.exec(e)},$=function(e){return!!/^\d+$/.exec(String(e))},Y=function(e){return!!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.exec(e)},J=function(e){try{return JSON.parse(e),!0}catch(e){return!1}},Z=function(e){try{return!!new URL(e)}catch(e){return!1}},X=function(e){return!!/^\+?\d[\d\s-]+$/.exec(e)},Q=function(e){return!!/((^((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))$)|(^((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?$))$/.exec(e)}},function(e,t,n){"use strict";n.d(t,"l",(function(){return f})),n.d(t,"m",(function(){return l})),n.d(t,"b",(function(){return r})),n.d(t,"g",(function(){return d})),n.d(t,"h",(function(){return h})),n.d(t,"i",(function(){return p})),n.d(t,"f",(function(){return v})),n.d(t,"c",(function(){return i})),n.d(t,"k",(function(){return g})),n.d(t,"j",(function(){return m})),n.d(t,"d",(function(){return o})),n.d(t,"e",(function(){return s})),n.d(t,"n",(function(){return b})),n.d(t,"a",(function(){return y}));var r,i,o,s,a=n(3),u=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))},c=function(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1] + * @license MIT + */ +var r=n(269),i=n(270),o=n(160);function s(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(e,t){if(s()=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|e}function p(e,t){if(u.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return F(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return z(e).length;default:if(r)return F(e).length;t=(""+t).toLowerCase(),r=!0}}function v(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return x(this,t,n);case"utf8":case"utf-8":return I(this,t,n);case"ascii":return k(this,t,n);case"latin1":case"binary":return O(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function g(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof t&&(t=u.from(t,r)),u.isBuffer(t))return 0===t.length?-1:b(e,t,n,r,i);if("number"==typeof t)return t&=255,u.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):b(e,[t],n,r,i);throw new TypeError("val must be string, number or Buffer")}function b(e,t,n,r,i){var o,s=1,a=e.length,u=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,a/=2,u/=2,n/=2}function c(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){var f=-1;for(o=n;oa&&(n=a-u),o=n;o>=0;o--){for(var l=!0,d=0;di&&(r=i):r=i;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");r>o/2&&(r=o/2);for(var s=0;s>8,i=n%256,o.push(i),o.push(r);return o}(t,e.length-n),e,n,r)}function A(e,t,n){return 0===t&&n===e.length?r.fromByteArray(e):r.fromByteArray(e.slice(t,n))}function I(e,t,n){n=Math.min(e.length,n);for(var r=[],i=t;i239?4:c>223?3:c>191?2:1;if(i+l<=n)switch(l){case 1:c<128&&(f=c);break;case 2:128==(192&(o=e[i+1]))&&(u=(31&c)<<6|63&o)>127&&(f=u);break;case 3:o=e[i+1],s=e[i+2],128==(192&o)&&128==(192&s)&&(u=(15&c)<<12|(63&o)<<6|63&s)>2047&&(u<55296||u>57343)&&(f=u);break;case 4:o=e[i+1],s=e[i+2],a=e[i+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(u=(15&c)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&u<1114112&&(f=u)}null===f?(f=65533,l=1):f>65535&&(f-=65536,r.push(f>>>10&1023|55296),f=56320|1023&f),r.push(f),i+=l}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);var n="",r=0;for(;r0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),""},u.prototype.compare=function(e,t,n,r,i){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===i&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(this===e)return 0;for(var o=(i>>>=0)-(r>>>=0),s=(n>>>=0)-(t>>>=0),a=Math.min(o,s),c=this.slice(r,i),f=e.slice(t,n),l=0;li)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return y(this,e,t,n);case"utf8":case"utf-8":return w(this,e,t,n);case"ascii":return _(this,e,t,n);case"latin1":case"binary":return S(this,e,t,n);case"base64":return E(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function k(e,t,n){var r="";n=Math.min(e.length,n);for(var i=t;ir)&&(n=r);for(var i="",o=t;on)throw new RangeError("Trying to access beyond buffer length")}function P(e,t,n,r,i,o){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function N(e,t,n,r){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-n,2);i>>8*(r?i:1-i)}function R(e,t,n,r){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-n,4);i>>8*(r?i:3-i)&255}function L(e,t,n,r,i,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function j(e,t,n,r,o){return o||L(e,0,n,4),i.write(e,t,n,r,23,4),n+4}function D(e,t,n,r,o){return o||L(e,0,n,8),i.write(e,t,n,r,52,8),n+8}u.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t0&&(i*=256);)r+=this[e+--t]*i;return r},u.prototype.readUInt8=function(e,t){return t||T(e,1,this.length),this[e]},u.prototype.readUInt16LE=function(e,t){return t||T(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUInt16BE=function(e,t){return t||T(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUInt32LE=function(e,t){return t||T(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUInt32BE=function(e,t){return t||T(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||T(e,t,this.length);for(var r=this[e],i=1,o=0;++o=(i*=128)&&(r-=Math.pow(2,8*t)),r},u.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||T(e,t,this.length);for(var r=t,i=1,o=this[e+--r];r>0&&(i*=256);)o+=this[e+--r]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},u.prototype.readInt8=function(e,t){return t||T(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){t||T(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},u.prototype.readInt16BE=function(e,t){t||T(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},u.prototype.readInt32LE=function(e,t){return t||T(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return t||T(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readFloatLE=function(e,t){return t||T(e,4,this.length),i.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return t||T(e,4,this.length),i.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return t||T(e,8,this.length),i.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return t||T(e,8,this.length),i.read(this,e,!1,52,8)},u.prototype.writeUIntLE=function(e,t,n,r){(e=+e,t|=0,n|=0,r)||P(this,e,t,n,Math.pow(2,8*n)-1,0);var i=1,o=0;for(this[t]=255&e;++o=0&&(o*=256);)this[t+i]=e/o&255;return t+n},u.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,1,255,0),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},u.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},u.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},u.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):R(this,e,t,!0),t+4},u.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):R(this,e,t,!1),t+4},u.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var i=Math.pow(2,8*n-1);P(this,e,t,n,i-1,-i)}var o=0,s=1,a=0;for(this[t]=255&e;++o>0)-a&255;return t+n},u.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var i=Math.pow(2,8*n-1);P(this,e,t,n,i-1,-i)}var o=n-1,s=1,a=0;for(this[t+o]=255&e;--o>=0&&(s*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/s>>0)-a&255;return t+n},u.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,1,127,-128),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},u.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},u.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):R(this,e,t,!0),t+4},u.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):R(this,e,t,!1),t+4},u.prototype.writeFloatLE=function(e,t,n){return j(this,e,t,!0,n)},u.prototype.writeFloatBE=function(e,t,n){return j(this,e,t,!1,n)},u.prototype.writeDoubleLE=function(e,t,n){return D(this,e,t,!0,n)},u.prototype.writeDoubleBE=function(e,t,n){return D(this,e,t,!1,n)},u.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--i)e[i+t]=this[i+n];else if(o<1e3||!u.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function z(e){return r.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(U,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function q(e,t,n,r){for(var i=0;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}}).call(this,n(31))},function(e,t){"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},function(e,t,n){ +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +var r=n(6),i=r.Buffer;function o(e,t){for(var n in e)t[n]=e[n]}function s(e,t,n){return i(e,t,n)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?e.exports=r:(o(r,t),t.Buffer=s),s.prototype=Object.create(i.prototype),o(i,s),s.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,n)},s.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=i(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}},function(e,t,n){"use strict";n.d(t,"c",(function(){return o})),n.d(t,"b",(function(){return s})),n.d(t,"a",(function(){return a}));var r=n(3),i=new WeakSet;function o(e){return i.has(e)}Symbol("A predicate that matches all records");var s=function(){function e(){}return Object.defineProperty(e,"ALL",{get:function(){var e=function(e){return e};return i.add(e),e},enumerable:!0,configurable:!0}),e}(),a=function(){function e(){}return e.createPredicateBuilder=function(t){var n,i=t.name,o=new Set(Object.keys(t.fields)),s=new Proxy({},n={get:function(t,s,a){var u=s;switch(u){case"and":case"or":case"not":return function(t){var r={type:u,predicates:[]},i=new Proxy({},n);return e.predicateGroupsMap.set(i,r),t(i),e.predicateGroupsMap.get(a).predicates.push(r),a};default:Object(r.f)(u,!1)}var c=s;if(!o.has(c))throw new Error("Invalid field for model. field: "+c+", model: "+i);return function(t,n){return e.predicateGroupsMap.get(a).predicates.push({field:c,operator:t,operand:n}),a}}});return e.predicateGroupsMap.set(s,{type:"and",predicates:[]}),s},e.isValidPredicate=function(t){return e.predicateGroupsMap.has(t)},e.getPredicates=function(t,n){if(void 0===n&&(n=!0),n&&!e.isValidPredicate(t))throw new Error("The predicate is not valid");return e.predicateGroupsMap.get(t)},e.createFromExisting=function(t,n){if(n&&t)return n(e.createPredicateBuilder(t))},e.createForId=function(t,n){return e.createPredicateBuilder(t).id("eq",n)},e.predicateGroupsMap=new WeakMap,e}()},function(e,t,n){"use strict";n.d(t,"a",(function(){return s}));var r=n(1),i={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"]},o={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"]};function s(e,t,n){return{applyToStack:function(s){s.add(function(e,t){return function(n,i){return function(o){return Object(r.__awaiter)(void 0,void 0,void 0,(function(){var s,a,u,c,f;return Object(r.__generator)(this,(function(l){switch(l.label){case 0:return s=i.logger,a=i.outputFilterSensitiveLog,[4,n(o)];case 1:return u=l.sent().response,"function"==typeof(null==s?void 0:s.debug)&&s.debug({httpResponse:u}),[4,t(u,e)];case 2:return c=l.sent(),c.$metadata,f=Object(r.__rest)(c,["$metadata"]),"function"==typeof(null==s?void 0:s.info)&&s.info({output:a(f)}),[2,{response:u,output:c}]}}))}))}}}(e,n),i),s.add(function(e,t){return function(n,i){return function(o){return Object(r.__awaiter)(void 0,void 0,void 0,(function(){var s,a,u;return Object(r.__generator)(this,(function(c){switch(c.label){case 0:return s=i.logger,a=i.inputFilterSensitiveLog,"function"==typeof(null==s?void 0:s.info)&&s.info({input:a(o.input)}),[4,t(o.input,e)];case 1:return u=c.sent(),"function"==typeof(null==s?void 0:s.debug)&&s.debug({httpRequest:u}),[2,n(Object(r.__assign)(Object(r.__assign)({},o),{request:u}))]}}))}))}}}(e,t),o)}}}},function(e,t,n){"use strict";n.d(t,"b",(function(){return o})),n.d(t,"a",(function(){return v})),n.d(t,"c",(function(){return m}));var r=n(1),i={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high"},o=function(e){return{applyToStack:function(t){t.add(function(e){return function(t){return function(n){return Object(r.__awaiter)(void 0,void 0,void 0,(function(){return Object(r.__generator)(this,(function(r){return[2,e.retryStrategy.retry(t,n)]}))}))}}}(e),i)}}},s=n(2),a=["AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"],u=["Throttling","ThrottlingException","ThrottledException","RequestThrottledException","TooManyRequestsException","ProvisionedThroughputExceededException","TransactionInProgressException","RequestLimitExceeded","BandwidthLimitExceeded","LimitExceededException","RequestThrottled","SlowDown","PriorRequestNotComplete","EC2ThrottledException"],c=["AbortError","TimeoutError","RequestTimeout","RequestTimeoutException"],f=[500,502,503,504],l=function(e){var t;return u.includes(e.name)||1==(null===(t=e.$retryable)||void 0===t?void 0:t.throttling)},d=n(27),h=function(e,t){return Math.floor(Math.min(2e4,Math.random()*Math.pow(2,t)*e))},p=function(e){return!!e&&(function(e){return void 0!==e.$retryable}(e)||function(e){return a.includes(e.name)}(e)||l(e)||function(e){var t;return c.includes(e.name)||f.includes((null===(t=e.$metadata)||void 0===t?void 0:t.httpStatusCode)||0)}(e))},v=3,g=function(){function e(e,t){var n,r,i,o,s,a,u,c;this.maxAttemptsProvider=e,this.retryDecider=null!==(n=null==t?void 0:t.retryDecider)&&void 0!==n?n:p,this.delayDecider=null!==(r=null==t?void 0:t.delayDecider)&&void 0!==r?r:h,this.retryQuota=null!==(i=null==t?void 0:t.retryQuota)&&void 0!==i?i:(s=o=500,a=o,u=function(e){return"TimeoutError"===e.name?10:5},c=function(e){return u(e)<=a},Object.freeze({hasRetryTokens:c,retrieveRetryTokens:function(e){if(!c(e))throw new Error("No retry token available");var t=u(e);return a-=t,t},releaseRetryTokens:function(e){a+=null!=e?e:1,a=Math.min(a,s)}}))}return e.prototype.shouldRetry=function(e,t,n){return t>6|192,63&i|128);else if(n+1>18|240,o>>12&63|128,o>>6&63|128,63&o|128)}else t.push(i>>12|224,i>>6&63|128,63&i|128)}return Uint8Array.from(t)}(e)},i=function(e){return"function"==typeof TextDecoder?function(e){return new TextDecoder("utf-8").decode(e)}(e):function(e){for(var t="",n=0,r=e.length;n",'"',"`"," ","\r","\n","\t"]),f=["'"].concat(c),l=["%","/","?",";","#"].concat(f),d=["/","?","#"],h=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,v={javascript:!0,"javascript:":!0},g={javascript:!0,"javascript:":!0},m={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=n(368);function y(e,t,n){if(e&&i.isObject(e)&&e instanceof o)return e;var r=new o;return r.parse(e,t,n),r}o.prototype.parse=function(e,t,n){if(!i.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var o=e.indexOf("?"),a=-1!==o&&o127?N+="x":N+=P[R];if(!N.match(h)){var j=C.slice(0,k),D=C.slice(k+1),U=P.match(p);U&&(j.push(U[1]),D.unshift(U[2])),D.length&&(y="/"+D.join(".")+y),this.hostname=j.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),x||(this.hostname=r.toASCII(this.hostname));var B=this.port?":"+this.port:"",F=this.hostname||"";this.host=F+B,this.href+=this.host,x&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==y[0]&&(y="/"+y))}if(!v[S])for(k=0,T=f.length;k0)&&n.host.split("@"))&&(n.auth=x.shift(),n.host=n.hostname=x.shift());return n.search=e.search,n.query=e.query,i.isNull(n.pathname)&&i.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n}if(!E.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var A=E.slice(-1)[0],I=(n.host||e.host||E.length>1)&&("."===A||".."===A)||""===A,k=0,O=E.length;O>=0;O--)"."===(A=E[O])?E.splice(O,1):".."===A?(E.splice(O,1),k++):k&&(E.splice(O,1),k--);if(!_&&!S)for(;k--;k)E.unshift("..");!_||""===E[0]||E[0]&&"/"===E[0].charAt(0)||E.unshift(""),I&&"/"!==E.join("/").substr(-1)&&E.push("");var x,C=""===E[0]||E[0]&&"/"===E[0].charAt(0);M&&(n.hostname=n.host=C?"":E.length?E.shift():"",(x=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=x.shift(),n.host=n.hostname=x.shift()));return(_=_||n.host&&E.length)&&!C&&E.unshift(""),E.length?n.pathname=E.join("/"):(n.pathname=null,n.path=null),i.isNull(n.pathname)&&i.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},o.prototype.parseHost=function(){var e=this.host,t=a.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},function(e,t,n){"use strict";n.d(t,"a",(function(){return f})),n.d(t,"b",(function(){return l}));for(var r={},i=new Array(64),o=0,s="A".charCodeAt(0),a="Z".charCodeAt(0);o+s<=a;o++){var u=String.fromCharCode(o+s);r[u]=o,i[o]=u}for(o=0,s="a".charCodeAt(0),a="z".charCodeAt(0);o+s<=a;o++){u=String.fromCharCode(o+s);var c=o+26;r[u]=c,i[c]=u}for(o=0;o<10;o++){r[o.toString(10)]=o+52;u=o.toString(10),c=o+52;r[u]=c,i[c]=u}r["+"]=62,i[62]="+",r["/"]=63,i[63]="/";function f(e){var t=e.length/4*3;"=="===e.substr(-2)?t-=2:"="===e.substr(-1)&&t--;for(var n=new ArrayBuffer(t),i=new DataView(n),o=0;o>=6;var f=o/4*3;s>>=a%8;for(var l=Math.floor(a/8),d=0;d>h)}}return new Uint8Array(n)}function l(e){for(var t="",n=0;n>f]}t+="==".slice(0,4-u)}return t}},function(e,t,n){"use strict";n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return u}));var r=n(1),i=n(2),o=n(74);var s=function(){function e(e){void 0===e&&(e={}),this.httpOptions=e}return e.prototype.destroy=function(){},e.prototype.handle=function(e,t){var n=null==t?void 0:t.abortSignal,s=this.httpOptions.requestTimeout;if(null==n?void 0:n.aborted){var a=new Error("Request aborted");return a.name="AbortError",Promise.reject(a)}var u=e.path;if(e.query){var c=Object(o.a)(e.query);c&&(u+="?"+c)}var f=e.port,l=e.protocol+"//"+e.hostname+(f?":"+f:"")+u,d={body:e.body,headers:new Headers(e.headers),method:e.method};"undefined"!=typeof AbortController&&(d.signal=n);var h,p=new Request(l,d),v=[fetch(p).then((function(e){var t,n,o=e.headers,s={};try{for(var a=Object(r.__values)(o.entries()),u=a.next();!u.done;u=a.next()){var c=u.value;s[c[0]]=c[1]}}catch(e){t={error:e}}finally{try{u&&!u.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return void 0!==e.body?{response:new i.b({headers:s,statusCode:e.status,body:e.body})}:e.blob().then((function(t){return{response:new i.b({headers:s,statusCode:e.status,body:t})}}))})),(h=s,void 0===h&&(h=0),new Promise((function(e,t){h&&setTimeout((function(){var e=new Error("Request did not complete within "+h+" ms");e.name="TimeoutError",t(e)}),h)})))];return n&&v.push(new Promise((function(e,t){n.onabort=function(){var e=new Error("Request aborted");e.name="AbortError",t(e)}}))),Promise.race(v)},e}(),a=n(17),u=function(e){return"function"==typeof Blob&&e instanceof Blob?function(e){return Object(r.__awaiter)(this,void 0,void 0,(function(){var t,n;return Object(r.__generator)(this,(function(r){switch(r.label){case 0:return[4,c(e)];case 1:return t=r.sent(),n=Object(a.a)(t),[2,new Uint8Array(n)]}}))}))}(e):function(e){return Object(r.__awaiter)(this,void 0,void 0,(function(){var t,n,i,o,s,a,u;return Object(r.__generator)(this,(function(r){switch(r.label){case 0:t=new Uint8Array(0),n=e.getReader(),i=!1,r.label=1;case 1:return i?[3,3]:[4,n.read()];case 2:return o=r.sent(),s=o.done,(a=o.value)&&(u=t,(t=new Uint8Array(u.length+a.length)).set(u),t.set(a,u.length)),i=s,[3,1];case 3:return[2,t]}}))}))}(e)};function c(e){return new Promise((function(t,n){var r=new FileReader;r.onloadend=function(){var e;if(2!==r.readyState)return n(new Error("Reader aborted too early"));var i=null!==(e=r.result)&&void 0!==e?e:"",o=i.indexOf(","),s=o>-1?o+1:i.length;t(i.substring(s))},r.onabort=function(){return n(new Error("Read aborted"))},r.onerror=function(){return n(r.error)},r.readAsDataURL(e)}))}},function(e,t,n){"use strict";n.d(t,"b",(function(){return s})),n.d(t,"a",(function(){return a}));var r=n(44),i=function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},o=new r.a("Amplify"),s=function(){function e(){this._components=[],this._config={},this._modules={},this.Auth=null,this.Analytics=null,this.API=null,this.Credentials=null,this.Storage=null,this.I18n=null,this.Cache=null,this.PubSub=null,this.Interactions=null,this.Pushnotification=null,this.UI=null,this.XR=null,this.Predictions=null,this.DataStore=null,this.Logger=r.a,this.ServiceWorker=null}return e.prototype.register=function(e){o.debug("component registered in amplify",e),this._components.push(e),"function"==typeof e.getModuleName?(this._modules[e.getModuleName()]=e,this[e.getModuleName()]=e):o.debug("no getModuleName method for component",e),e.configure(this._config)},e.prototype.configure=function(e){var t=this;return e?(this._config=Object.assign(this._config,e),o.debug("amplify config",this._config),Object.entries(this._modules).forEach((function(e){var n=i(e,2),r=(n[0],n[1]);Object.keys(r).forEach((function(e){t._modules[e]&&(r[e]=t._modules[e])}))})),this._components.map((function(e){e.configure(t._config)})),this._config):this._config},e.prototype.addPluggable=function(e){e&&e.getCategory&&"function"==typeof e.getCategory&&this._components.map((function(t){t.addPluggable&&"function"==typeof t.addPluggable&&t.addPluggable(e)}))},e}(),a=new s},function(e,t){var n,r,i=e.exports={};function o(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function a(e){if(n===setTimeout)return setTimeout(e,0);if((n===o||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:o}catch(e){n=o}try{r="function"==typeof clearTimeout?clearTimeout:s}catch(e){r=s}}();var u,c=[],f=!1,l=-1;function d(){f&&u&&(f=!1,u.length?c=u.concat(c):l=-1,c.length&&h())}function h(){if(!f){var e=a(d);f=!0;for(var t=c.length;t;){for(u=c,c=[];++l1)for(var n=1;n=0&&!o.headers[":authority"]?(delete o.headers.host,o.headers[":authority"]=""):o.headers.host||(o.headers.host=o.hostname),[2,t(n)]):[2,t(n)]}))}))}}}(e),s)}}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return i})),n.d(t,"b",(function(){return a}));var r=n(1),i=function(e){var t;return Object(r.__assign)(Object(r.__assign)({},e),{tls:null===(t=e.tls)||void 0===t||t,endpoint:e.endpoint?o(e):function(){return s(e)},isCustomEndpoint:!!e.endpoint})},o=function(e){var t=e.endpoint,n=e.urlParser;if("string"==typeof t){var r=Promise.resolve(n(t));return function(){return r}}if("object"==typeof t){var i=Promise.resolve(t);return function(){return i}}return t},s=function(e){return Object(r.__awaiter)(void 0,void 0,void 0,(function(){var t,n,i,o,s;return Object(r.__generator)(this,(function(r){switch(r.label){case 0:return t=e.tls,n=void 0===t||t,[4,e.region()];case 1:if(i=r.sent(),!new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/).test(i))throw new Error("Invalid region in client config");return[4,e.regionInfoProvider(i)];case 2:if(!(o=(null!==(s=r.sent())&&void 0!==s?s:{}).hostname))throw new Error("Cannot resolve hostname from client config");return[2,e.urlParser((n?"https:":"http:")+"//"+o)]}}))}))},a=function(e){if(!e.region)throw new Error("Region is missing");return Object(r.__assign)(Object(r.__assign)({},e),{region:u(e.region)})},u=function(e){if("string"==typeof e){var t=Promise.resolve(e);return function(){return t}}return e}},function(e,t,n){"use strict";function r(e){return e}n.d(t,"b",(function(){return r})),n.d(t,"a",(function(){return a}));var i=n(1),o=n(2);var s={name:"getUserAgentMiddleware",step:"build",tags:["SET_USER_AGENT","USER_AGENT"]},a=function(e){return{applyToStack:function(t){var n;t.add((n=e,function(e){return function(t){var r=t.request;if(!o.a.isInstance(r))return e(t);var s=r.headers,a="node"===n.runtime?"user-agent":"x-amz-user-agent";return s[a]?s[a]+=" "+n.defaultUserAgent:s[a]=""+n.defaultUserAgent,n.customUserAgent&&(s[a]+=" "+n.customUserAgent),e(Object(i.__assign)(Object(i.__assign)({},t),{request:r}))}}),s)}}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));var r=function(e){return function(){throw new Error(e)}}},function(e,t,n){"use strict";n.d(t,"b",(function(){return o})),n.d(t,"a",(function(){return l}));var r=n(1),i=n(111);function o(e){var t,n=this,o=s(e.credentials||e.credentialDefaultProvider(e)),a=e.signingEscapePath,u=void 0===a||a,c=e.systemClockOffset,f=void 0===c?e.systemClockOffset||0:c,l=e.sha256;return t=e.signer?s(e.signer):function(){return s(e.region)().then((function(t){return Object(r.__awaiter)(n,void 0,void 0,(function(){return Object(r.__generator)(this,(function(n){switch(n.label){case 0:return[4,e.regionInfoProvider(t)];case 1:return[2,[n.sent()||{},t]]}}))}))})).then((function(t){var n=Object(r.__read)(t,2),s=n[0],a=n[1],c=s.signingRegion,f=void 0===c?e.signingRegion:c,d=s.signingService,h=void 0===d?e.signingName:d;return e.signingRegion=e.signingRegion||f||a,e.signingName=e.signingName||h,new i.a({credentials:o,region:e.signingRegion,service:e.signingName,sha256:l,uriEscapePath:u})}))},Object(r.__assign)(Object(r.__assign)({},e),{systemClockOffset:f,signingEscapePath:u,credentials:o,signer:t})}function s(e){if("object"==typeof e){var t=Promise.resolve(e);return function(){return t}}return e}var a=n(2),u=function(e){return new Date(Date.now()+e)};function c(e){return function(t,n){return function(i){return Object(r.__awaiter)(this,void 0,void 0,(function(){var o,s,c,f,l,d,h,p,v;return Object(r.__generator)(this,(function(g){switch(g.label){case 0:return a.a.isInstance(i.request)?"function"!=typeof e.signer?[3,2]:[4,e.signer()]:[2,t(i)];case 1:return s=g.sent(),[3,3];case 2:s=e.signer,g.label=3;case 3:return o=s,f=t,l=[Object(r.__assign)({},i)],v={},[4,o.sign(i.request,{signingDate:new Date(Date.now()+e.systemClockOffset),signingRegion:n.signing_region,signingService:n.signing_service})];case 4:return[4,f.apply(void 0,[r.__assign.apply(void 0,l.concat([(v.request=g.sent(),v)]))])];case 5:return c=g.sent(),d=c.response.headers,(h=d&&(d.date||d.Date))&&(p=Date.parse(h),m=p,b=e.systemClockOffset,Math.abs(u(b).getTime()-m)>=3e5&&(e.systemClockOffset=p-Date.now())),[2,c]}var m,b}))}))}}}var f={name:"awsAuthMiddleware",tags:["SIGNATURE","AWSAUTH"],relation:"after",toMiddleware:"retryMiddleware"},l=function(e){return{applyToStack:function(t){t.addRelativeTo(c(e),f)}}}},function(e,t,n){"use strict";var r=n(19),i={keyPrefix:"aws-amplify-cache",capacityInBytes:1048576,itemMaxSize:21e4,defaultTTL:2592e5,defaultPriority:5,warningThreshold:.8,storage:(new(n(86).a)).getStorage()};function o(e){var t=0;t=e.length;for(var n=e.length;n>=0;n-=1){var r=e.charCodeAt(n);r>127&&r<=2047?t+=1:r>2047&&r<=65535&&(t+=2),r>=56320&&r<=57343&&(n-=1)}return t}function s(){return(new Date).getTime()}function a(e){return Number.isInteger?Number.isInteger(e):function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e}(e)}var u={},c=(function(){function e(){}e.clear=function(){u={}},e.getItem=function(e){return u[e]||null},e.setItem=function(e,t){u[e]=t},e.removeItem=function(e){delete u[e]}}(),n(44));function f(e){return(f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var l,d=new c.a("StorageCache"),h=function(){function e(e){this.config=Object.assign({},e),this.cacheCurSizeKey=this.config.keyPrefix+"CurSize",this.checkConfig()}return e.prototype.getModuleName=function(){return"Cache"},e.prototype.checkConfig=function(){a(this.config.capacityInBytes)||(d.error("Invalid parameter: capacityInBytes. It should be an Integer. Setting back to default."),this.config.capacityInBytes=i.capacityInBytes),a(this.config.itemMaxSize)||(d.error("Invalid parameter: itemMaxSize. It should be an Integer. Setting back to default."),this.config.itemMaxSize=i.itemMaxSize),a(this.config.defaultTTL)||(d.error("Invalid parameter: defaultTTL. It should be an Integer. Setting back to default."),this.config.defaultTTL=i.defaultTTL),a(this.config.defaultPriority)||(d.error("Invalid parameter: defaultPriority. It should be an Integer. Setting back to default."),this.config.defaultPriority=i.defaultPriority),this.config.itemMaxSize>this.config.capacityInBytes&&(d.error("Invalid parameter: itemMaxSize. It should be smaller than capacityInBytes. Setting back to default."),this.config.itemMaxSize=i.itemMaxSize),(this.config.defaultPriority>5||this.config.defaultPriority<1)&&(d.error("Invalid parameter: defaultPriority. It should be between 1 and 5. Setting back to default."),this.config.defaultPriority=i.defaultPriority),(Number(this.config.warningThreshold)>1||Number(this.config.warningThreshold)<0)&&(d.error("Invalid parameter: warningThreshold. It should be between 0 and 1. Setting back to default."),this.config.warningThreshold=i.warningThreshold);this.config.capacityInBytes>5242880&&(d.error("Cache Capacity should be less than 5MB. Setting back to default. Setting back to default."),this.config.capacityInBytes=i.capacityInBytes)},e.prototype.fillCacheItem=function(e,t,n){var r={key:e,data:t,timestamp:s(),visitedTime:s(),priority:n.priority,expires:n.expires,type:f(t),byteSize:0};return r.byteSize=o(JSON.stringify(r)),r.byteSize=o(JSON.stringify(r)),r},e.prototype.configure=function(e){return e?(e.keyPrefix&&d.warn("Don't try to configure keyPrefix!"),this.config=Object.assign({},this.config,e,e.Cache),this.checkConfig(),this.config):this.config},e}(),p=(l=function(e,t){return(l=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}l(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),v=new c.a("Cache"),g=new(function(e){function t(t){var n=this,r=t?Object.assign({},i,t):i;return(n=e.call(this,r)||this).config.storage=r.storage,n.getItem=n.getItem.bind(n),n.setItem=n.setItem.bind(n),n.removeItem=n.removeItem.bind(n),n}return p(t,e),t.prototype._decreaseCurSizeInBytes=function(e){var t=this.getCacheCurSize();this.config.storage.setItem(this.cacheCurSizeKey,(t-e).toString())},t.prototype._increaseCurSizeInBytes=function(e){var t=this.getCacheCurSize();this.config.storage.setItem(this.cacheCurSizeKey,(t+e).toString())},t.prototype._refreshItem=function(e,t){return e.visitedTime=s(),this.config.storage.setItem(t,JSON.stringify(e)),e},t.prototype._isExpired=function(e){var t=this.config.storage.getItem(e),n=JSON.parse(t);return s()>=n.expires},t.prototype._removeItem=function(e,t){var n=t||JSON.parse(this.config.storage.getItem(e)).byteSize;this._decreaseCurSizeInBytes(n),this.config.storage.removeItem(e)},t.prototype._setItem=function(e,t){this._increaseCurSizeInBytes(t.byteSize);try{this.config.storage.setItem(e,JSON.stringify(t))}catch(e){this._decreaseCurSizeInBytes(t.byteSize),v.error("Failed to set item "+e)}},t.prototype._sizeToPop=function(e){var t=this.getCacheCurSize()+e-this.config.capacityInBytes,n=(1-this.config.warningThreshold)*this.config.capacityInBytes;return t>n?t:n},t.prototype._isCacheFull=function(e){return e+this.getCacheCurSize()>this.config.capacityInBytes},t.prototype._findValidKeys=function(){for(var e=[],t=[],n=0;nt.priority?-1:e.priority5)v.warn("Invalid parameter: priority due to out or range. It should be within 1 and 5.");else{var o=this.fillCacheItem(r,t,i);if(o.byteSize>this.config.itemMaxSize)v.warn("Item with key: "+e+" you are trying to put into is too big!");else try{var a=this.config.storage.getItem(r);if(a&&this._removeItem(r,JSON.parse(a).byteSize),this._isCacheFull(o.byteSize)){var u=this._findValidKeys();if(this._isCacheFull(o.byteSize)){var c=this._sizeToPop(o.byteSize);this._popOutItems(u,c)}}this._setItem(r,o)}catch(e){v.warn("setItem failed! "+e)}}}else v.warn("The value of item should not be undefined!");else v.warn("Invalid key: should not be empty or 'CurSize'")},t.prototype.getItem=function(e,t){v.log("Get item: key is "+e+" with options "+t);var n=null,r=this.config.keyPrefix+e;if(r===this.config.keyPrefix||r===this.cacheCurSizeKey)return v.warn("Invalid key: should not be empty or 'CurSize'"),null;try{if(null!=(n=this.config.storage.getItem(r))){if(!this._isExpired(r)){var i=JSON.parse(n);return(i=this._refreshItem(i,r)).data}this._removeItem(r,JSON.parse(n).byteSize),n=null}if(t&&void 0!==t.callback){var o=t.callback();return null!==o&&this.setItem(e,o,t),o}return null}catch(e){return v.warn("getItem failed! "+e),null}},t.prototype.removeItem=function(e){v.log("Remove item: key is "+e);var t=this.config.keyPrefix+e;if(t!==this.config.keyPrefix&&t!==this.cacheCurSizeKey)try{var n=this.config.storage.getItem(t);n&&this._removeItem(t,JSON.parse(n).byteSize)}catch(e){v.warn("removeItem failed! "+e)}},t.prototype.clear=function(){v.log("Clear Cache");for(var e=[],t=0;t=49&&s<=54?s-49+10:s>=17&&s<=22?s-17+10:15&s}return r}function u(e,t,n,r){for(var i=0,o=Math.min(e.length,n),s=t;s=49?a-49+10:a>=17?a-17+10:a}return i}o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,n){if("number"==typeof e)return this._initNumber(e,t,n);if("object"==typeof e)return this._initArray(e,t,n);"hex"===t&&(t=16),r(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&i++,16===t?this._parseHex(e,i):this._parseBase(e,t,i),"-"===e[0]&&(this.negative=1),this.strip(),"le"===n&&this._initArray(this.toArray(),t,n)},o.prototype._initNumber=function(e,t,n){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(r(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),t,n)},o.prototype._initArray=function(e,t,n){if(r("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)s=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=s<>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);else if("le"===n)for(i=0,o=0;i>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);return this.strip()},o.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var n=0;n=t;n-=6)i=a(e,n,n+6),this.words[r]|=i<>>26-o&4194303,(o+=24)>=26&&(o-=26,r++);n+6!==t&&(i=a(e,t,n+6),this.words[r]|=i<>>26-o&4194303),this.strip()},o.prototype._parseBase=function(e,t,n){this.words=[0],this.length=1;for(var r=0,i=1;i<=67108863;i*=t)r++;r--,i=i/t|0;for(var o=e.length-n,s=o%r,a=Math.min(o,o-s)+n,c=0,f=n;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},o.prototype.inspect=function(){return(this.red?""};var c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],f=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],l=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function d(e,t,n){n.negative=t.negative^e.negative;var r=e.length+t.length|0;n.length=r,r=r-1|0;var i=0|e.words[0],o=0|t.words[0],s=i*o,a=67108863&s,u=s/67108864|0;n.words[0]=a;for(var c=1;c>>26,l=67108863&u,d=Math.min(c,t.length-1),h=Math.max(0,c-e.length+1);h<=d;h++){var p=c-h|0;f+=(s=(i=0|e.words[p])*(o=0|t.words[h])+l)/67108864|0,l=67108863&s}n.words[c]=0|l,u=0|f}return 0!==u?n.words[c]=0|u:n.length--,n.strip()}o.prototype.toString=function(e,t){var n;if(t=0|t||1,16===(e=e||10)||"hex"===e){n="";for(var i=0,o=0,s=0;s>>24-i&16777215)||s!==this.length-1?c[6-u.length]+u+n:u+n,(i+=2)>=26&&(i-=26,s--)}for(0!==o&&(n=o.toString(16)+n);n.length%t!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(e===(0|e)&&e>=2&&e<=36){var d=f[e],h=l[e];n="";var p=this.clone();for(p.negative=0;!p.isZero();){var v=p.modn(h).toString(e);n=(p=p.idivn(h)).isZero()?v+n:c[d-v.length]+v+n}for(this.isZero()&&(n="0"+n);n.length%t!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16)},o.prototype.toBuffer=function(e,t){return r(void 0!==s),this.toArrayLike(s,e,t)},o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,n){var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0"),this.strip();var s,a,u="le"===t,c=new e(o),f=this.clone();if(u){for(a=0;!f.isZero();a++)s=f.andln(255),f.iushrn(8),c[a]=s;for(;a=4096&&(n+=13,t>>>=13),t>=64&&(n+=7,t>>>=7),t>=8&&(n+=4,t>>>=4),t>=2&&(n+=2,t>>>=2),n+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,n=0;return 0==(8191&t)&&(n+=13,t>>>=13),0==(127&t)&&(n+=7,t>>>=7),0==(15&t)&&(n+=4,t>>>=4),0==(3&t)&&(n+=2,t>>>=2),0==(1&t)&&n++,n},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var n=0;ne.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,n;this.length>e.length?(t=this,n=e):(t=e,n=this);for(var r=0;re.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){r("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),n=e%26;this._expand(t),n>0&&t--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){r("number"==typeof e&&e>=0);var n=e/26|0,i=e%26;return this._expand(n+1),this.words[n]=t?this.words[n]|1<e.length?(n=this,r=e):(n=e,r=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=n.length,0!==i)this.words[this.length]=i,this.length++;else if(n!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var n,r,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(n=this,r=e):(n=e,r=this);for(var o=0,s=0;s>26,this.words[s]=67108863&t;for(;0!==o&&s>26,this.words[s]=67108863&t;if(0===o&&s>>13,h=0|s[1],p=8191&h,v=h>>>13,g=0|s[2],m=8191&g,b=g>>>13,y=0|s[3],w=8191&y,_=y>>>13,S=0|s[4],E=8191&S,M=S>>>13,A=0|s[5],I=8191&A,k=A>>>13,O=0|s[6],x=8191&O,C=O>>>13,T=0|s[7],P=8191&T,N=T>>>13,R=0|s[8],L=8191&R,j=R>>>13,D=0|s[9],U=8191&D,B=D>>>13,F=0|a[0],z=8191&F,q=F>>>13,K=0|a[1],H=8191&K,V=K>>>13,G=0|a[2],W=8191&G,$=G>>>13,Y=0|a[3],J=8191&Y,Z=Y>>>13,X=0|a[4],Q=8191&X,ee=X>>>13,te=0|a[5],ne=8191&te,re=te>>>13,ie=0|a[6],oe=8191&ie,se=ie>>>13,ae=0|a[7],ue=8191&ae,ce=ae>>>13,fe=0|a[8],le=8191&fe,de=fe>>>13,he=0|a[9],pe=8191&he,ve=he>>>13;n.negative=e.negative^t.negative,n.length=19;var ge=(c+(r=Math.imul(l,z))|0)+((8191&(i=(i=Math.imul(l,q))+Math.imul(d,z)|0))<<13)|0;c=((o=Math.imul(d,q))+(i>>>13)|0)+(ge>>>26)|0,ge&=67108863,r=Math.imul(p,z),i=(i=Math.imul(p,q))+Math.imul(v,z)|0,o=Math.imul(v,q);var me=(c+(r=r+Math.imul(l,H)|0)|0)+((8191&(i=(i=i+Math.imul(l,V)|0)+Math.imul(d,H)|0))<<13)|0;c=((o=o+Math.imul(d,V)|0)+(i>>>13)|0)+(me>>>26)|0,me&=67108863,r=Math.imul(m,z),i=(i=Math.imul(m,q))+Math.imul(b,z)|0,o=Math.imul(b,q),r=r+Math.imul(p,H)|0,i=(i=i+Math.imul(p,V)|0)+Math.imul(v,H)|0,o=o+Math.imul(v,V)|0;var be=(c+(r=r+Math.imul(l,W)|0)|0)+((8191&(i=(i=i+Math.imul(l,$)|0)+Math.imul(d,W)|0))<<13)|0;c=((o=o+Math.imul(d,$)|0)+(i>>>13)|0)+(be>>>26)|0,be&=67108863,r=Math.imul(w,z),i=(i=Math.imul(w,q))+Math.imul(_,z)|0,o=Math.imul(_,q),r=r+Math.imul(m,H)|0,i=(i=i+Math.imul(m,V)|0)+Math.imul(b,H)|0,o=o+Math.imul(b,V)|0,r=r+Math.imul(p,W)|0,i=(i=i+Math.imul(p,$)|0)+Math.imul(v,W)|0,o=o+Math.imul(v,$)|0;var ye=(c+(r=r+Math.imul(l,J)|0)|0)+((8191&(i=(i=i+Math.imul(l,Z)|0)+Math.imul(d,J)|0))<<13)|0;c=((o=o+Math.imul(d,Z)|0)+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,r=Math.imul(E,z),i=(i=Math.imul(E,q))+Math.imul(M,z)|0,o=Math.imul(M,q),r=r+Math.imul(w,H)|0,i=(i=i+Math.imul(w,V)|0)+Math.imul(_,H)|0,o=o+Math.imul(_,V)|0,r=r+Math.imul(m,W)|0,i=(i=i+Math.imul(m,$)|0)+Math.imul(b,W)|0,o=o+Math.imul(b,$)|0,r=r+Math.imul(p,J)|0,i=(i=i+Math.imul(p,Z)|0)+Math.imul(v,J)|0,o=o+Math.imul(v,Z)|0;var we=(c+(r=r+Math.imul(l,Q)|0)|0)+((8191&(i=(i=i+Math.imul(l,ee)|0)+Math.imul(d,Q)|0))<<13)|0;c=((o=o+Math.imul(d,ee)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,r=Math.imul(I,z),i=(i=Math.imul(I,q))+Math.imul(k,z)|0,o=Math.imul(k,q),r=r+Math.imul(E,H)|0,i=(i=i+Math.imul(E,V)|0)+Math.imul(M,H)|0,o=o+Math.imul(M,V)|0,r=r+Math.imul(w,W)|0,i=(i=i+Math.imul(w,$)|0)+Math.imul(_,W)|0,o=o+Math.imul(_,$)|0,r=r+Math.imul(m,J)|0,i=(i=i+Math.imul(m,Z)|0)+Math.imul(b,J)|0,o=o+Math.imul(b,Z)|0,r=r+Math.imul(p,Q)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,ee)|0;var _e=(c+(r=r+Math.imul(l,ne)|0)|0)+((8191&(i=(i=i+Math.imul(l,re)|0)+Math.imul(d,ne)|0))<<13)|0;c=((o=o+Math.imul(d,re)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,r=Math.imul(x,z),i=(i=Math.imul(x,q))+Math.imul(C,z)|0,o=Math.imul(C,q),r=r+Math.imul(I,H)|0,i=(i=i+Math.imul(I,V)|0)+Math.imul(k,H)|0,o=o+Math.imul(k,V)|0,r=r+Math.imul(E,W)|0,i=(i=i+Math.imul(E,$)|0)+Math.imul(M,W)|0,o=o+Math.imul(M,$)|0,r=r+Math.imul(w,J)|0,i=(i=i+Math.imul(w,Z)|0)+Math.imul(_,J)|0,o=o+Math.imul(_,Z)|0,r=r+Math.imul(m,Q)|0,i=(i=i+Math.imul(m,ee)|0)+Math.imul(b,Q)|0,o=o+Math.imul(b,ee)|0,r=r+Math.imul(p,ne)|0,i=(i=i+Math.imul(p,re)|0)+Math.imul(v,ne)|0,o=o+Math.imul(v,re)|0;var Se=(c+(r=r+Math.imul(l,oe)|0)|0)+((8191&(i=(i=i+Math.imul(l,se)|0)+Math.imul(d,oe)|0))<<13)|0;c=((o=o+Math.imul(d,se)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,r=Math.imul(P,z),i=(i=Math.imul(P,q))+Math.imul(N,z)|0,o=Math.imul(N,q),r=r+Math.imul(x,H)|0,i=(i=i+Math.imul(x,V)|0)+Math.imul(C,H)|0,o=o+Math.imul(C,V)|0,r=r+Math.imul(I,W)|0,i=(i=i+Math.imul(I,$)|0)+Math.imul(k,W)|0,o=o+Math.imul(k,$)|0,r=r+Math.imul(E,J)|0,i=(i=i+Math.imul(E,Z)|0)+Math.imul(M,J)|0,o=o+Math.imul(M,Z)|0,r=r+Math.imul(w,Q)|0,i=(i=i+Math.imul(w,ee)|0)+Math.imul(_,Q)|0,o=o+Math.imul(_,ee)|0,r=r+Math.imul(m,ne)|0,i=(i=i+Math.imul(m,re)|0)+Math.imul(b,ne)|0,o=o+Math.imul(b,re)|0,r=r+Math.imul(p,oe)|0,i=(i=i+Math.imul(p,se)|0)+Math.imul(v,oe)|0,o=o+Math.imul(v,se)|0;var Ee=(c+(r=r+Math.imul(l,ue)|0)|0)+((8191&(i=(i=i+Math.imul(l,ce)|0)+Math.imul(d,ue)|0))<<13)|0;c=((o=o+Math.imul(d,ce)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,r=Math.imul(L,z),i=(i=Math.imul(L,q))+Math.imul(j,z)|0,o=Math.imul(j,q),r=r+Math.imul(P,H)|0,i=(i=i+Math.imul(P,V)|0)+Math.imul(N,H)|0,o=o+Math.imul(N,V)|0,r=r+Math.imul(x,W)|0,i=(i=i+Math.imul(x,$)|0)+Math.imul(C,W)|0,o=o+Math.imul(C,$)|0,r=r+Math.imul(I,J)|0,i=(i=i+Math.imul(I,Z)|0)+Math.imul(k,J)|0,o=o+Math.imul(k,Z)|0,r=r+Math.imul(E,Q)|0,i=(i=i+Math.imul(E,ee)|0)+Math.imul(M,Q)|0,o=o+Math.imul(M,ee)|0,r=r+Math.imul(w,ne)|0,i=(i=i+Math.imul(w,re)|0)+Math.imul(_,ne)|0,o=o+Math.imul(_,re)|0,r=r+Math.imul(m,oe)|0,i=(i=i+Math.imul(m,se)|0)+Math.imul(b,oe)|0,o=o+Math.imul(b,se)|0,r=r+Math.imul(p,ue)|0,i=(i=i+Math.imul(p,ce)|0)+Math.imul(v,ue)|0,o=o+Math.imul(v,ce)|0;var Me=(c+(r=r+Math.imul(l,le)|0)|0)+((8191&(i=(i=i+Math.imul(l,de)|0)+Math.imul(d,le)|0))<<13)|0;c=((o=o+Math.imul(d,de)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,r=Math.imul(U,z),i=(i=Math.imul(U,q))+Math.imul(B,z)|0,o=Math.imul(B,q),r=r+Math.imul(L,H)|0,i=(i=i+Math.imul(L,V)|0)+Math.imul(j,H)|0,o=o+Math.imul(j,V)|0,r=r+Math.imul(P,W)|0,i=(i=i+Math.imul(P,$)|0)+Math.imul(N,W)|0,o=o+Math.imul(N,$)|0,r=r+Math.imul(x,J)|0,i=(i=i+Math.imul(x,Z)|0)+Math.imul(C,J)|0,o=o+Math.imul(C,Z)|0,r=r+Math.imul(I,Q)|0,i=(i=i+Math.imul(I,ee)|0)+Math.imul(k,Q)|0,o=o+Math.imul(k,ee)|0,r=r+Math.imul(E,ne)|0,i=(i=i+Math.imul(E,re)|0)+Math.imul(M,ne)|0,o=o+Math.imul(M,re)|0,r=r+Math.imul(w,oe)|0,i=(i=i+Math.imul(w,se)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,se)|0,r=r+Math.imul(m,ue)|0,i=(i=i+Math.imul(m,ce)|0)+Math.imul(b,ue)|0,o=o+Math.imul(b,ce)|0,r=r+Math.imul(p,le)|0,i=(i=i+Math.imul(p,de)|0)+Math.imul(v,le)|0,o=o+Math.imul(v,de)|0;var Ae=(c+(r=r+Math.imul(l,pe)|0)|0)+((8191&(i=(i=i+Math.imul(l,ve)|0)+Math.imul(d,pe)|0))<<13)|0;c=((o=o+Math.imul(d,ve)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,r=Math.imul(U,H),i=(i=Math.imul(U,V))+Math.imul(B,H)|0,o=Math.imul(B,V),r=r+Math.imul(L,W)|0,i=(i=i+Math.imul(L,$)|0)+Math.imul(j,W)|0,o=o+Math.imul(j,$)|0,r=r+Math.imul(P,J)|0,i=(i=i+Math.imul(P,Z)|0)+Math.imul(N,J)|0,o=o+Math.imul(N,Z)|0,r=r+Math.imul(x,Q)|0,i=(i=i+Math.imul(x,ee)|0)+Math.imul(C,Q)|0,o=o+Math.imul(C,ee)|0,r=r+Math.imul(I,ne)|0,i=(i=i+Math.imul(I,re)|0)+Math.imul(k,ne)|0,o=o+Math.imul(k,re)|0,r=r+Math.imul(E,oe)|0,i=(i=i+Math.imul(E,se)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,se)|0,r=r+Math.imul(w,ue)|0,i=(i=i+Math.imul(w,ce)|0)+Math.imul(_,ue)|0,o=o+Math.imul(_,ce)|0,r=r+Math.imul(m,le)|0,i=(i=i+Math.imul(m,de)|0)+Math.imul(b,le)|0,o=o+Math.imul(b,de)|0;var Ie=(c+(r=r+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,ve)|0)+Math.imul(v,pe)|0))<<13)|0;c=((o=o+Math.imul(v,ve)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,r=Math.imul(U,W),i=(i=Math.imul(U,$))+Math.imul(B,W)|0,o=Math.imul(B,$),r=r+Math.imul(L,J)|0,i=(i=i+Math.imul(L,Z)|0)+Math.imul(j,J)|0,o=o+Math.imul(j,Z)|0,r=r+Math.imul(P,Q)|0,i=(i=i+Math.imul(P,ee)|0)+Math.imul(N,Q)|0,o=o+Math.imul(N,ee)|0,r=r+Math.imul(x,ne)|0,i=(i=i+Math.imul(x,re)|0)+Math.imul(C,ne)|0,o=o+Math.imul(C,re)|0,r=r+Math.imul(I,oe)|0,i=(i=i+Math.imul(I,se)|0)+Math.imul(k,oe)|0,o=o+Math.imul(k,se)|0,r=r+Math.imul(E,ue)|0,i=(i=i+Math.imul(E,ce)|0)+Math.imul(M,ue)|0,o=o+Math.imul(M,ce)|0,r=r+Math.imul(w,le)|0,i=(i=i+Math.imul(w,de)|0)+Math.imul(_,le)|0,o=o+Math.imul(_,de)|0;var ke=(c+(r=r+Math.imul(m,pe)|0)|0)+((8191&(i=(i=i+Math.imul(m,ve)|0)+Math.imul(b,pe)|0))<<13)|0;c=((o=o+Math.imul(b,ve)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,r=Math.imul(U,J),i=(i=Math.imul(U,Z))+Math.imul(B,J)|0,o=Math.imul(B,Z),r=r+Math.imul(L,Q)|0,i=(i=i+Math.imul(L,ee)|0)+Math.imul(j,Q)|0,o=o+Math.imul(j,ee)|0,r=r+Math.imul(P,ne)|0,i=(i=i+Math.imul(P,re)|0)+Math.imul(N,ne)|0,o=o+Math.imul(N,re)|0,r=r+Math.imul(x,oe)|0,i=(i=i+Math.imul(x,se)|0)+Math.imul(C,oe)|0,o=o+Math.imul(C,se)|0,r=r+Math.imul(I,ue)|0,i=(i=i+Math.imul(I,ce)|0)+Math.imul(k,ue)|0,o=o+Math.imul(k,ce)|0,r=r+Math.imul(E,le)|0,i=(i=i+Math.imul(E,de)|0)+Math.imul(M,le)|0,o=o+Math.imul(M,de)|0;var Oe=(c+(r=r+Math.imul(w,pe)|0)|0)+((8191&(i=(i=i+Math.imul(w,ve)|0)+Math.imul(_,pe)|0))<<13)|0;c=((o=o+Math.imul(_,ve)|0)+(i>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,r=Math.imul(U,Q),i=(i=Math.imul(U,ee))+Math.imul(B,Q)|0,o=Math.imul(B,ee),r=r+Math.imul(L,ne)|0,i=(i=i+Math.imul(L,re)|0)+Math.imul(j,ne)|0,o=o+Math.imul(j,re)|0,r=r+Math.imul(P,oe)|0,i=(i=i+Math.imul(P,se)|0)+Math.imul(N,oe)|0,o=o+Math.imul(N,se)|0,r=r+Math.imul(x,ue)|0,i=(i=i+Math.imul(x,ce)|0)+Math.imul(C,ue)|0,o=o+Math.imul(C,ce)|0,r=r+Math.imul(I,le)|0,i=(i=i+Math.imul(I,de)|0)+Math.imul(k,le)|0,o=o+Math.imul(k,de)|0;var xe=(c+(r=r+Math.imul(E,pe)|0)|0)+((8191&(i=(i=i+Math.imul(E,ve)|0)+Math.imul(M,pe)|0))<<13)|0;c=((o=o+Math.imul(M,ve)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,r=Math.imul(U,ne),i=(i=Math.imul(U,re))+Math.imul(B,ne)|0,o=Math.imul(B,re),r=r+Math.imul(L,oe)|0,i=(i=i+Math.imul(L,se)|0)+Math.imul(j,oe)|0,o=o+Math.imul(j,se)|0,r=r+Math.imul(P,ue)|0,i=(i=i+Math.imul(P,ce)|0)+Math.imul(N,ue)|0,o=o+Math.imul(N,ce)|0,r=r+Math.imul(x,le)|0,i=(i=i+Math.imul(x,de)|0)+Math.imul(C,le)|0,o=o+Math.imul(C,de)|0;var Ce=(c+(r=r+Math.imul(I,pe)|0)|0)+((8191&(i=(i=i+Math.imul(I,ve)|0)+Math.imul(k,pe)|0))<<13)|0;c=((o=o+Math.imul(k,ve)|0)+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,r=Math.imul(U,oe),i=(i=Math.imul(U,se))+Math.imul(B,oe)|0,o=Math.imul(B,se),r=r+Math.imul(L,ue)|0,i=(i=i+Math.imul(L,ce)|0)+Math.imul(j,ue)|0,o=o+Math.imul(j,ce)|0,r=r+Math.imul(P,le)|0,i=(i=i+Math.imul(P,de)|0)+Math.imul(N,le)|0,o=o+Math.imul(N,de)|0;var Te=(c+(r=r+Math.imul(x,pe)|0)|0)+((8191&(i=(i=i+Math.imul(x,ve)|0)+Math.imul(C,pe)|0))<<13)|0;c=((o=o+Math.imul(C,ve)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,r=Math.imul(U,ue),i=(i=Math.imul(U,ce))+Math.imul(B,ue)|0,o=Math.imul(B,ce),r=r+Math.imul(L,le)|0,i=(i=i+Math.imul(L,de)|0)+Math.imul(j,le)|0,o=o+Math.imul(j,de)|0;var Pe=(c+(r=r+Math.imul(P,pe)|0)|0)+((8191&(i=(i=i+Math.imul(P,ve)|0)+Math.imul(N,pe)|0))<<13)|0;c=((o=o+Math.imul(N,ve)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,r=Math.imul(U,le),i=(i=Math.imul(U,de))+Math.imul(B,le)|0,o=Math.imul(B,de);var Ne=(c+(r=r+Math.imul(L,pe)|0)|0)+((8191&(i=(i=i+Math.imul(L,ve)|0)+Math.imul(j,pe)|0))<<13)|0;c=((o=o+Math.imul(j,ve)|0)+(i>>>13)|0)+(Ne>>>26)|0,Ne&=67108863;var Re=(c+(r=Math.imul(U,pe))|0)+((8191&(i=(i=Math.imul(U,ve))+Math.imul(B,pe)|0))<<13)|0;return c=((o=Math.imul(B,ve))+(i>>>13)|0)+(Re>>>26)|0,Re&=67108863,u[0]=ge,u[1]=me,u[2]=be,u[3]=ye,u[4]=we,u[5]=_e,u[6]=Se,u[7]=Ee,u[8]=Me,u[9]=Ae,u[10]=Ie,u[11]=ke,u[12]=Oe,u[13]=xe,u[14]=Ce,u[15]=Te,u[16]=Pe,u[17]=Ne,u[18]=Re,0!==c&&(u[19]=c,n.length++),n};function p(e,t,n){return(new v).mulp(e,t,n)}function v(e,t){this.x=e,this.y=t}Math.imul||(h=d),o.prototype.mulTo=function(e,t){var n=this.length+e.length;return 10===this.length&&10===e.length?h(this,e,t):n<63?d(this,e,t):n<1024?function(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var r=0,i=0,o=0;o>>26)|0)>>>26,s&=67108863}n.words[o]=a,r=s,s=i}return 0!==r?n.words[o]=r:n.length--,n.strip()}(this,e,t):p(this,e,t)},v.prototype.makeRBT=function(e){for(var t=new Array(e),n=o.prototype._countBits(e)-1,r=0;r>=1;return r},v.prototype.permute=function(e,t,n,r,i,o){for(var s=0;s>>=1)i++;return 1<>>=13,n[2*s+1]=8191&o,o>>>=13;for(s=2*t;s>=26,t+=i/67108864|0,t+=o>>>26,this.words[n]=67108863&o}return 0!==t&&(this.words[n]=t,this.length++),this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),n=0;n>>i}return t}(e);if(0===t.length)return new o(1);for(var n=this,r=0;r=0);var t,n=e%26,i=(e-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var s=0;for(t=0;t>>26-n}s&&(this.words[t]=s,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t=0),i=t?(t-t%26)/26:0;var o=e%26,s=Math.min((e-o)/26,this.length),a=67108863^67108863>>>o<s)for(this.length-=s,c=0;c=0&&(0!==f||c>=i);c--){var l=0|this.words[c];this.words[c]=f<<26-o|l>>>o,f=l&a}return u&&0!==f&&(u.words[u.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},o.prototype.ishrn=function(e,t,n){return r(0===this.negative),this.iushrn(e,t,n)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){r("number"==typeof e&&e>=0);var t=e%26,n=(e-t)/26,i=1<=0);var t=e%26,n=(e-t)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==t&&n++,this.length=Math.min(n,this.length),0!==t){var i=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(r("number"==typeof e),r(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(u/67108864|0),this.words[i+n]=67108863&o}for(;i>26,this.words[i+n]=67108863&o;if(0===a)return this.strip();for(r(-1===a),a=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},o.prototype._wordDiv=function(e,t){var n=(this.length,e.length),r=this.clone(),i=e,s=0|i.words[i.length-1];0!==(n=26-this._countBits(s))&&(i=i.ushln(n),r.iushln(n),s=0|i.words[i.length-1]);var a,u=r.length-i.length;if("mod"!==t){(a=new o(null)).length=u+1,a.words=new Array(a.length);for(var c=0;c=0;l--){var d=67108864*(0|r.words[i.length+l])+(0|r.words[i.length+l-1]);for(d=Math.min(d/s|0,67108863),r._ishlnsubmul(i,d,l);0!==r.negative;)d--,r.negative=0,r._ishlnsubmul(i,1,l),r.isZero()||(r.negative^=1);a&&(a.words[l]=d)}return a&&a.strip(),r.strip(),"div"!==t&&0!==n&&r.iushrn(n),{div:a||null,mod:r}},o.prototype.divmod=function(e,t,n){return r(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(i=a.div.neg()),"div"!==t&&(s=a.mod.neg(),n&&0!==s.negative&&s.iadd(e)),{div:i,mod:s}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(i=a.div.neg()),{div:i,mod:a.mod}):0!=(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(s=a.mod.neg(),n&&0!==s.negative&&s.isub(e)),{div:a.div,mod:s}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modn(e.words[0]))}:this._wordDiv(e,t);var i,s,a},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var n=0!==t.div.negative?t.mod.isub(e):t.mod,r=e.ushrn(1),i=e.andln(1),o=n.cmp(r);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modn=function(e){r(e<=67108863);for(var t=(1<<26)%e,n=0,i=this.length-1;i>=0;i--)n=(t*n+(0|this.words[i]))%e;return n},o.prototype.idivn=function(e){r(e<=67108863);for(var t=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*t;this.words[n]=i/e|0,t=i%e}return this.strip()},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){r(0===e.negative),r(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),s=new o(0),a=new o(0),u=new o(1),c=0;t.isEven()&&n.isEven();)t.iushrn(1),n.iushrn(1),++c;for(var f=n.clone(),l=t.clone();!t.isZero();){for(var d=0,h=1;0==(t.words[0]&h)&&d<26;++d,h<<=1);if(d>0)for(t.iushrn(d);d-- >0;)(i.isOdd()||s.isOdd())&&(i.iadd(f),s.isub(l)),i.iushrn(1),s.iushrn(1);for(var p=0,v=1;0==(n.words[0]&v)&&p<26;++p,v<<=1);if(p>0)for(n.iushrn(p);p-- >0;)(a.isOdd()||u.isOdd())&&(a.iadd(f),u.isub(l)),a.iushrn(1),u.iushrn(1);t.cmp(n)>=0?(t.isub(n),i.isub(a),s.isub(u)):(n.isub(t),a.isub(i),u.isub(s))}return{a:a,b:u,gcd:n.iushln(c)}},o.prototype._invmp=function(e){r(0===e.negative),r(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,s=new o(1),a=new o(0),u=n.clone();t.cmpn(1)>0&&n.cmpn(1)>0;){for(var c=0,f=1;0==(t.words[0]&f)&&c<26;++c,f<<=1);if(c>0)for(t.iushrn(c);c-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);for(var l=0,d=1;0==(n.words[0]&d)&&l<26;++l,d<<=1);if(l>0)for(n.iushrn(l);l-- >0;)a.isOdd()&&a.iadd(u),a.iushrn(1);t.cmp(n)>=0?(t.isub(n),s.isub(a)):(n.isub(t),a.isub(s))}return(i=0===t.cmpn(1)?s:a).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),n=e.clone();t.negative=0,n.negative=0;for(var r=0;t.isEven()&&n.isEven();r++)t.iushrn(1),n.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;n.isEven();)n.iushrn(1);var i=t.cmp(n);if(i<0){var o=t;t=n,n=o}else if(0===i||0===n.cmpn(1))break;t.isub(n)}return n.iushln(r)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){r("number"==typeof e);var t=e%26,n=(e-t)/26,i=1<>>26,a&=67108863,this.words[s]=a}return 0!==o&&(this.words[s]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,n=e<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)t=1;else{n&&(e=-e),r(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:ie.length)return 1;if(this.length=0;n--){var r=0|this.words[n],i=0|e.words[n];if(r!==i){ri&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new S(e)},o.prototype.toRed=function(e){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return r(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return r(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var g={k256:null,p224:null,p192:null,p25519:null};function m(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function b(){m.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function y(){m.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function w(){m.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){m.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function S(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else r(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function E(e){S.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}m.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},m.prototype.ireduce=function(e){var t,n=e;do{this.split(n,this.tmp),t=(n=(n=this.imulK(n)).iadd(this.tmp)).bitLength()}while(t>this.n);var r=t0?n.isub(this.p):void 0!==n.strip?n.strip():n._strip(),n},m.prototype.split=function(e,t){e.iushrn(this.n,0,t)},m.prototype.imulK=function(e){return e.imul(this.k)},i(b,m),b.prototype.split=function(e,t){for(var n=Math.min(e.length,9),r=0;r>>22,i=o}i>>>=22,e.words[r-10]=i,0===i&&e.length>10?e.length-=10:e.length-=9},b.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,n=0;n>>=26,e.words[n]=i,t=r}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(g[e])return g[e];var t;if("k256"===e)t=new b;else if("p224"===e)t=new y;else if("p192"===e)t=new w;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new _}return g[e]=t,t},S.prototype._verify1=function(e){r(0===e.negative,"red works only with positives"),r(e.red,"red works only with red numbers")},S.prototype._verify2=function(e,t){r(0==(e.negative|t.negative),"red works only with positives"),r(e.red&&e.red===t.red,"red works only with red numbers")},S.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},S.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},S.prototype.add=function(e,t){this._verify2(e,t);var n=e.add(t);return n.cmp(this.m)>=0&&n.isub(this.m),n._forceRed(this)},S.prototype.iadd=function(e,t){this._verify2(e,t);var n=e.iadd(t);return n.cmp(this.m)>=0&&n.isub(this.m),n},S.prototype.sub=function(e,t){this._verify2(e,t);var n=e.sub(t);return n.cmpn(0)<0&&n.iadd(this.m),n._forceRed(this)},S.prototype.isub=function(e,t){this._verify2(e,t);var n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n},S.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},S.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},S.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},S.prototype.isqr=function(e){return this.imul(e,e.clone())},S.prototype.sqr=function(e){return this.mul(e,e)},S.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(r(t%2==1),3===t){var n=this.m.add(new o(1)).iushrn(2);return this.pow(e,n)}for(var i=this.m.subn(1),s=0;!i.isZero()&&0===i.andln(1);)s++,i.iushrn(1);r(!i.isZero());var a=new o(1).toRed(this),u=a.redNeg(),c=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new o(2*f*f).toRed(this);0!==this.pow(f,c).cmp(u);)f.redIAdd(u);for(var l=this.pow(f,i),d=this.pow(e,i.addn(1).iushrn(1)),h=this.pow(e,i),p=s;0!==h.cmp(a);){for(var v=h,g=0;0!==v.cmp(a);g++)v=v.redSqr();r(g=0;r--){for(var c=t.words[r],f=u-1;f>=0;f--){var l=c>>f&1;i!==n[0]&&(i=this.sqr(i)),0!==l||0!==s?(s<<=1,s|=l,(4===++a||0===r&&0===f)&&(i=this.mul(i,n[s]),a=0,s=0)):a=0}u=26}return i},S.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},S.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new E(e)},i(E,S),E.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},E.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},E.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var n=e.imul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=n.isub(r).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},E.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var n=e.mul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=n.isub(r).iushrn(this.shift),s=i;return i.cmp(this.m)>=0?s=i.isub(this.m):i.cmpn(0)<0&&(s=i.iadd(this.m)),s._forceRed(this)},E.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(e,this)}).call(this,n(57)(e))},function(e,t,n){"use strict";n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return C})),n.d(t,"c",(function(){return P})),n.d(t,"d",(function(){return N})),n.d(t,"e",(function(){return V})),n.d(t,"f",(function(){return F})),n.d(t,"g",(function(){return te})),n.d(t,"h",(function(){return j})),n.d(t,"i",(function(){return re})); +/*! + * Copyright 2016 Amazon.com, + * Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Amazon Software License (the "License"). + * You may not use this file except in compliance with the + * License. A copy of the License is located at + * + * http://aws.amazon.com/asl/ + * + * or in the "license" file accompanying this file. This file is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, express or implied. See the License + * for the specific language governing permissions and + * limitations under the License. + */ +var r=function(){function e(e){var t=e||{},n=t.ValidationData,r=t.Username,i=t.Password,o=t.AuthParameters,s=t.ClientMetadata;this.validationData=n||{},this.authParameters=o||{},this.clientMetadata=s||{},this.username=r,this.password=i}var t=e.prototype;return t.getUsername=function(){return this.username},t.getPassword=function(){return this.password},t.getValidationData=function(){return this.validationData},t.getAuthParameters=function(){return this.authParameters},t.getClientMetadata=function(){return this.clientMetadata},e}(),i=n(6),o=n(32),s=n.n(o),a=(n(161),n(87)),u=n.n(a),c=n(75),f=n.n(c),l=n(250);var d,h=function(){function e(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length}var t=e.prototype;return t.random=function(t){for(var n=[],r=0;r>>2]>>>24-i%4*8&255;r.push((o>>>4).toString(16)),r.push((15&o).toString(16))}return r.join("")}(this)},e}(),p=v;function v(e,t){null!=e&&this.fromString(e,t)}function g(){return new v(null)}var m="undefined"!=typeof navigator;m&&"Microsoft Internet Explorer"==navigator.appName?(v.prototype.am=function(e,t,n,r,i,o){for(var s=32767&t,a=t>>15;--o>=0;){var u=32767&this[e],c=this[e++]>>15,f=a*u+c*s;i=((u=s*u+((32767&f)<<15)+n[r]+(1073741823&i))>>>30)+(f>>>15)+a*c+(i>>>30),n[r++]=1073741823&u}return i},d=30):m&&"Netscape"!=navigator.appName?(v.prototype.am=function(e,t,n,r,i,o){for(;--o>=0;){var s=t*this[e++]+n[r]+i;i=Math.floor(s/67108864),n[r++]=67108863&s}return i},d=26):(v.prototype.am=function(e,t,n,r,i,o){for(var s=16383&t,a=t>>14;--o>=0;){var u=16383&this[e],c=this[e++]>>14,f=a*u+c*s;i=((u=s*u+((16383&f)<<14)+n[r]+i)>>28)+(f>>14)+a*c,n[r++]=268435455&u}return i},d=28),v.prototype.DB=d,v.prototype.DM=(1<>>16)&&(e=t,n+=16),0!=(t=e>>8)&&(e=t,n+=8),0!=(t=e>>4)&&(e=t,n+=4),0!=(t=e>>2)&&(e=t,n+=2),0!=(t=e>>1)&&(e=t,n+=1),n}function A(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(t,t),t},A.prototype.revert=function(e){var t=g();return e.copyTo(t),this.reduce(t),t},A.prototype.reduce=function(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(e[n=t+this.m.t]+=this.m.am(0,r,e,t,0,this.m.t);e[n]>=e.DV;)e[n]-=e.DV,e[++n]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},A.prototype.mulTo=function(e,t,n){e.multiplyTo(t,n),this.reduce(n)},A.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},v.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e[t]=this[t];e.t=this.t,e.s=this.s},v.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0},v.prototype.fromString=function(e,t){var n;if(16==t)n=4;else if(8==t)n=3;else if(2==t)n=1;else if(32==t)n=5;else{if(4!=t)throw new Error("Only radix 2, 4, 8, 16, 32 are supported");n=2}this.t=0,this.s=0;for(var r=e.length,i=!1,o=0;--r>=0;){var s=S(e,r);s<0?"-"==e.charAt(r)&&(i=!0):(i=!1,0==o?this[this.t++]=s:o+n>this.DB?(this[this.t-1]|=(s&(1<>this.DB-o):this[this.t-1]|=s<=this.DB&&(o-=this.DB))}this.clamp(),i&&v.ZERO.subTo(this,this)},v.prototype.clamp=function(){for(var e=this.s&this.DM;this.t>0&&this[this.t-1]==e;)--this.t},v.prototype.dlShiftTo=function(e,t){var n;for(n=this.t-1;n>=0;--n)t[n+e]=this[n];for(n=e-1;n>=0;--n)t[n]=0;t.t=this.t+e,t.s=this.s},v.prototype.drShiftTo=function(e,t){for(var n=e;n=0;--n)t[n+s+1]=this[n]>>i|a,a=(this[n]&o)<=0;--n)t[n]=0;t[s]=a,t.t=this.t+s+1,t.s=this.s,t.clamp()},v.prototype.rShiftTo=function(e,t){t.s=this.s;var n=Math.floor(e/this.DB);if(n>=this.t)t.t=0;else{var r=e%this.DB,i=this.DB-r,o=(1<>r;for(var s=n+1;s>r;r>0&&(t[this.t-n-1]|=(this.s&o)<>=this.DB;if(e.t>=this.DB;r+=this.s}else{for(r+=this.s;n>=this.DB;r-=e.s}t.s=r<0?-1:0,r<-1?t[n++]=this.DV+r:r>0&&(t[n++]=r),t.t=n,t.clamp()},v.prototype.multiplyTo=function(e,t){var n=this.abs(),r=e.abs(),i=n.t;for(t.t=i+r.t;--i>=0;)t[i]=0;for(i=0;i=0;)e[n]=0;for(n=0;n=t.DV&&(e[n+t.t]-=t.DV,e[n+t.t+1]=1)}e.t>0&&(e[e.t-1]+=t.am(n,t[n],e,2*n,0,1)),e.s=0,e.clamp()},v.prototype.divRemTo=function(e,t,n){var r=e.abs();if(!(r.t<=0)){var i=this.abs();if(i.t0?(r.lShiftTo(u,o),i.lShiftTo(u,n)):(r.copyTo(o),i.copyTo(n));var c=o.t,f=o[c-1];if(0!=f){var l=f*(1<1?o[c-2]>>this.F2:0),d=this.FV/l,h=(1<=0&&(n[n.t++]=1,n.subTo(y,n)),v.ONE.dlShiftTo(c,y),y.subTo(o,o);o.t=0;){var w=n[--m]==f?this.DM:Math.floor(n[m]*d+(n[m-1]+p)*h);if((n[m]+=o.am(0,w,n,b,0,c))0&&n.rShiftTo(u,n),s<0&&v.ZERO.subTo(n,n)}}},v.prototype.invDigit=function(){if(this.t<1)return 0;var e=this[0];if(0==(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},v.prototype.addTo=function(e,t){for(var n=0,r=0,i=Math.min(e.t,this.t);n>=this.DB;if(e.t>=this.DB;r+=this.s}else{for(r+=this.s;n>=this.DB;r+=e.s}t.s=r<0?-1:0,r>0?t[n++]=r:r<-1&&(t[n++]=this.DV+r),t.t=n,t.clamp()},v.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)throw new Error("Only radix 2, 4, 8, 16, 32 are supported");t=2}var n,r=(1<0)for(a>a)>0&&(i=!0,o=_(n));s>=0;)a>(a+=this.DB-t)):(n=this[s]>>(a-=t)&r,a<=0&&(a+=this.DB,--s)),n>0&&(i=!0),i&&(o+=_(n));return i?o:"0"},v.prototype.negate=function(){var e=g();return v.ZERO.subTo(this,e),e},v.prototype.abs=function(){return this.s<0?this.negate():this},v.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var n=this.t;if(0!=(t=n-e.t))return this.s<0?-t:t;for(;--n>=0;)if(0!=(t=this[n]-e[n]))return t;return 0},v.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+M(this[this.t-1]^this.s&this.DM)},v.prototype.mod=function(e){var t=g();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(v.ZERO)>0&&e.subTo(t,t),t},v.prototype.equals=function(e){return 0==this.compareTo(e)},v.prototype.add=function(e){var t=g();return this.addTo(e,t),t},v.prototype.subtract=function(e){var t=g();return this.subTo(e,t),t},v.prototype.multiply=function(e){var t=g();return this.multiplyTo(e,t),t},v.prototype.divide=function(e){var t=g();return this.divRemTo(e,t,null),t},v.prototype.modPow=function(e,t,n){var r,i=e.bitLength(),o=E(1),s=new A(t);if(i<=0)return o;r=i<18?1:i<48?3:i<144?4:i<768?5:6;var a=new Array,u=3,c=r-1,f=(1<1){var l=g();for(s.sqrTo(a[1],l);u<=f;)a[u]=g(),s.mulTo(l,a[u-2],a[u]),u+=2}var d,h,p=e.t-1,v=!0,m=g();for(i=M(e[p])-1;p>=0;){for(i>=c?d=e[p]>>i-c&f:(d=(e[p]&(1<0&&(d|=e[p-1]>>this.DB+i-c)),u=r;0==(1&d);)d>>=1,--u;if((i-=u)<0&&(i+=this.DB,--p),v)a[d].copyTo(o),v=!1;else{for(;u>1;)s.sqrTo(o,m),s.sqrTo(m,o),u-=2;u>0?s.sqrTo(o,m):(h=o,o=m,m=h),s.mulTo(m,a[d],o)}for(;p>=0&&0==(e[p]&1<>>2]>>>24-o%4*8&255;t[r+o>>>2]|=s<<24-(r+o)%4*8}else for(o=0;o>>2]=n[o>>>2];return this.sigBytes+=i,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n,r=[],i=function(t){t=t;var n=987654321,r=4294967295;return function(){var i=((n=36969*(65535&n)+(n>>16)&r)<<16)+(t=18e3*(65535&t)+(t>>16)&r)&r;return i/=4294967296,(i+=.5)*(e.random()>.5?1:-1)}},o=0;o>>2]>>>24-i%4*8&255;r.push((o>>>4).toString(16)),r.push((15&o).toString(16))}return r.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new s.init(n,t/2)}},c=a.Latin1={stringify:function(e){for(var t=e.words,n=e.sigBytes,r=[],i=0;i>>2]>>>24-i%4*8&255;r.push(String.fromCharCode(o))}return r.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new s.init(n,t)}},f=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},l=i.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=f.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,i=n.sigBytes,o=this.blockSize,a=i/(4*o),u=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*o,c=e.min(4*u,i);if(u){for(var f=0;fo?1*r:0})),!0},s=function(e,t){var n=Object.assign({},e);return t&&("string"==typeof t?delete n[t]:t.forEach((function(e){delete n[e]}))),n},a=function(e,t){void 0===t&&(t="application/octet-stream");var n=e.toLowerCase(),i=r.filter((function(e){return n.endsWith("."+e.ext)}));return i.length>0?i[0].type:t},u=function(e){var t=e.toLowerCase();return!!t.startsWith("text/")||("application/json"===t||"application/xml"===t||"application/sh"===t)},c=function(){for(var e="",t="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",n=32;n>0;n-=1)e+=t[Math.floor(Math.random()*t.length)];return e},f=function(e){if(e.isResolved)return e;var t=!0,n=!1,r=!1,i=e.then((function(e){return r=!0,t=!1,e}),(function(e){throw n=!0,t=!1,e}));return i.isFullfilled=function(){return r},i.isPending=function(){return t},i.isRejected=function(){return n},i},l=function(){if("undefined"==typeof self)return!1;var e=self;return void 0!==e.WorkerGlobalScope&&self instanceof e.WorkerGlobalScope},d=function(){return{isBrowser:"undefined"!=typeof window&&void 0!==window.document,isNode:void 0!==e&&null!=e.versions&&null!=e.versions.node}},h=function e(t,n,r){if(void 0===n&&(n=[]),void 0===r&&(r=[]),!v(t))return t;var i={};for(var o in t){if(t.hasOwnProperty(o))i[n.includes(o)?o:o[0].toLowerCase()+o.slice(1)]=r.includes(o)?t[o]:e(t[o],n,r)}return i},p=function e(t,n,r){if(void 0===n&&(n=[]),void 0===r&&(r=[]),!v(t))return t;var i={};for(var o in t){if(t.hasOwnProperty(o))i[n.includes(o)?o:o[0].toUpperCase()+o.slice(1)]=r.includes(o)?t[o]:e(t[o],n,r)}return i},v=function(e){return!(!(e instanceof Object)||e instanceof Array||e instanceof Function||e instanceof Number||e instanceof String||e instanceof Boolean)},g=function(){function e(){}return e.isEmpty=i,e.sortByField=o,e.objectLessAttributes=s,e.filenameToContentType=a,e.isTextFile=u,e.generateRandomString=c,e.makeQuerablePromise=f,e.isWebWorker=l,e.browserOrNode=d,e.transferKeyToLowerCase=h,e.transferKeyToUpperCase=p,e.isStrictObject=v,e}()}).call(this,n(20))},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));var r,i=n(105);!function(e){e.CONNECTION_CLOSED="Connection closed",e.TIMEOUT_DISCONNECT="Timeout disconnect",e.SUBSCRIPTION_ACK="Subscription ack"}(r||(r={})),t.b=i.a},function(e,t,n){"use strict";var r;n.d(t,"a",(function(){return r})),function(e){e.DEFAULT_MSG="Authentication Error",e.EMPTY_USERNAME="Username cannot be empty",e.INVALID_USERNAME="The username should either be a string or one of the sign in types",e.EMPTY_PASSWORD="Password cannot be empty",e.EMPTY_CODE="Confirmation code cannot be empty",e.SIGN_UP_ERROR="Error creating account",e.NO_MFA="No valid MFA method provided",e.INVALID_MFA="Invalid MFA type",e.EMPTY_CHALLENGE="Challenge response cannot be empty",e.NO_USER_SESSION="Failed to get the session because the user is empty"}(r||(r={}))},function(e,t,n){var r=n(228),i=n(230),o=n(231),s=n(61),a=n(232),u=n(138),c=n(229),f=n(139),l=Object.prototype.hasOwnProperty;e.exports=function(e){if(null==e)return!0;if(a(e)&&(s(e)||"string"==typeof e||"function"==typeof e.splice||u(e)||f(e)||o(e)))return!e.length;var t=i(e);if("[object Map]"==t||"[object Set]"==t)return!e.size;if(c(e))return!r(e).length;for(var n in e)if(l.call(e,n))return!1;return!0}},function(e,t,n){"use strict";n.d(t,"a",(function(){return s}));var r=n(1),i=n(2);var o={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware"},s=function(e){return{applyToStack:function(t){t.add(function(e){var t=this;return function(n){return function(o){return Object(r.__awaiter)(t,void 0,void 0,(function(){var t,s,a,u,c;return Object(r.__generator)(this,(function(f){return t=o.request,i.a.isInstance(t)&&(s=t.body,a=t.headers,s&&-1===Object.keys(a).map((function(e){return e.toLowerCase()})).indexOf("content-length")&&void 0!==(u=e(s))&&(t.headers=Object(r.__assign)(Object(r.__assign)({},t.headers),((c={})["content-length"]=String(u),c)))),[2,n(Object(r.__assign)(Object(r.__assign)({},o),{request:t}))]}))}))}}}(e.bodyLengthChecker),o)}}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebCryptoSha256=t.Ie11Sha256=void 0,n(1).__exportStar(n(373),t);var r=n(216);Object.defineProperty(t,"Ie11Sha256",{enumerable:!0,get:function(){return r.Sha256}});var i=n(219);Object.defineProperty(t,"WebCryptoSha256",{enumerable:!0,get:function(){return i.Sha256}})},function(e,t,n){"use strict";n.d(t,"a",(function(){return i}));var r=n(106),i=function(e){var t,n=new URL(e),i=n.hostname,o=n.pathname,s=n.port,a=n.protocol,u=n.search;return u&&(t=Object(r.a)(u)),{hostname:i,port:s?parseInt(s):void 0,protocol:a,path:o,query:t}}},function(e,t,n){"use strict";function r(e){if("string"==typeof e){for(var t=e.length,n=t-1;n>=0;n--){var r=e.charCodeAt(n);r>127&&r<=2047?t++:r>2047&&r<=65535&&(t+=2)}return t}return"number"==typeof e.byteLength?e.byteLength:"number"==typeof e.size?e.size:void 0}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";function r(e,t){return"aws-sdk-js-v3-"+e+"/"+t+" "+("undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:"")}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";var r=n(63);n(30);t.a=r.a},function(e,t,n){"use strict";n.d(t,"a",(function(){return o}));var r=n(1),i={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize"},o=function(e){return{applyToStack:function(e){e.add((function(e,t){return function(n){return Object(r.__awaiter)(void 0,void 0,void 0,(function(){var i,o,s,a;return Object(r.__generator)(this,(function(r){switch(r.label){case 0:return i=t.logger,[4,e(n)];case 1:return o=r.sent(),i?(s=o.response,"function"==typeof i.info&&i.info({metadata:{statusCode:s.statusCode,requestId:null!==(a=s.headers["x-amzn-requestid"])&&void 0!==a?a:s.headers["x-amzn-request-id"],extendedRequestId:s.headers["x-amz-id-2"],cfId:s.headers["x-amz-cf-id"]}}),[2,o]):[2,o]}}))}))}}),i)}}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return s}));var r=function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},i=function(){for(var e=[],t=0;t=s){var u=console.log.bind(console);"ERROR"===t&&console.error&&(u=console.error.bind(console)),"WARN"===t&&console.warn&&(u=console.warn.bind(console));var c="["+t+"] "+this._ts()+" "+this.name;if(1===n.length&&"string"==typeof n[0])u(c+" - "+n[0]);else if(1===n.length)u(c,n[0]);else if("string"==typeof n[0]){var f=n.slice(1);1===f.length&&(f=f[0]),u(c+" - "+n[0],f)}else u(c,n)}},e.prototype.log=function(){for(var e=[],t=0;t(i>>1)-1?(i>>1)-u:u,o.isubn(a)):a=0,r[s]=a,o.iushrn(1)}return r},r.getJSF=function(e,t){var n=[[],[]];e=e.clone(),t=t.clone();for(var r,i=0,o=0;e.cmpn(-i)>0||t.cmpn(-o)>0;){var s,a,u=e.andln(3)+i&3,c=t.andln(3)+o&3;3===u&&(u=-1),3===c&&(c=-1),s=0==(1&u)?0:3!==(r=e.andln(7)+i&7)&&5!==r||2!==c?u:-u,n[0].push(s),a=0==(1&c)?0:3!==(r=t.andln(7)+o&7)&&5!==r||2!==u?c:-c,n[1].push(a),2*i===s+1&&(i=1-i),2*o===a+1&&(o=1-o),e.iushrn(1),t.iushrn(1)}return n},r.cachedProperty=function(e,t,n){var r="_"+t;e.prototype[t]=function(){return void 0!==this[r]?this[r]:this[r]=n.call(this)}},r.parseBytes=function(e){return"string"==typeof e?r.toArray(e,"hex"):e},r.intFromLE=function(e){return new i(e,"hex","le")}},,function(e,t,n){"use strict";var r,i="object"==typeof Reflect?Reflect:null,o=i&&"function"==typeof i.apply?i.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};r=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var s=Number.isNaN||function(e){return e!=e};function a(){a.init.call(this)}e.exports=a,e.exports.once=function(e,t){return new Promise((function(n,r){function i(){void 0!==o&&e.removeListener("error",o),n([].slice.call(arguments))}var o;"error"!==t&&(o=function(n){e.removeListener(t,i),r(n)},e.once("error",o)),e.once(t,i)}))},a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var u=10;function c(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function f(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function l(e,t,n,r){var i,o,s,a;if(c(n),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),s=o[t]),void 0===s)s=o[t]=n,++e._eventsCount;else if("function"==typeof s?s=o[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),(i=f(e))>0&&s.length>i&&!s.warned){s.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=s.length,a=u,console&&console.warn&&console.warn(a)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function h(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=d.bind(r);return i.listener=n,r.wrapFn=i,i}function p(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var u=i[e];if(void 0===u)return!1;if("function"==typeof u)o(u,this,t);else{var c=u.length,f=g(u,c);for(n=0;n=0;o--)if(n[o]===t||n[o].listener===t){s=n[o].listener,i=o;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1=0;r--)this.removeListener(e,t[r]);return this},a.prototype.listeners=function(e){return p(this,e,!0)},a.prototype.rawListeners=function(e){return p(this,e,!1)},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):v.call(e,t)},a.prototype.listenerCount=v,a.prototype.eventNames=function(){return this._eventsCount>0?r(this._events):[]}},function(e,t,n){"use strict";n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return i}));var r={userAgent:"aws-amplify/3.8.12 js",product:"",navigator:null,isReactNative:!1};if("undefined"!=typeof navigator&&navigator.product)switch(r.product=navigator.product||"",r.navigator=navigator||null,navigator.product){case"ReactNative":r.userAgent="aws-amplify/3.8.12 react-native",r.isReactNative=!0;break;default:r.userAgent="aws-amplify/3.8.12 js",r.isReactNative=!1}var i=function(){return r.userAgent}},function(e,t,n){"use strict";var r=n(46),i=n(7);function o(e,t){return 55296==(64512&e.charCodeAt(t))&&(!(t<0||t+1>=e.length)&&56320==(64512&e.charCodeAt(t+1)))}function s(e){return(e>>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}function a(e){return 1===e.length?"0"+e:e}function u(e){return 7===e.length?"0"+e:6===e.length?"00"+e:5===e.length?"000"+e:4===e.length?"0000"+e:3===e.length?"00000"+e:2===e.length?"000000"+e:1===e.length?"0000000"+e:e}t.inherits=i,t.toArray=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var n=[];if("string"==typeof e)if(t){if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),i=0;i>6|192,n[r++]=63&s|128):o(e,i)?(s=65536+((1023&s)<<10)+(1023&e.charCodeAt(++i)),n[r++]=s>>18|240,n[r++]=s>>12&63|128,n[r++]=s>>6&63|128,n[r++]=63&s|128):(n[r++]=s>>12|224,n[r++]=s>>6&63|128,n[r++]=63&s|128)}else for(i=0;i>>0}return s},t.split32=function(e,t){for(var n=new Array(4*e.length),r=0,i=0;r>>24,n[i+1]=o>>>16&255,n[i+2]=o>>>8&255,n[i+3]=255&o):(n[i+3]=o>>>24,n[i+2]=o>>>16&255,n[i+1]=o>>>8&255,n[i]=255&o)}return n},t.rotr32=function(e,t){return e>>>t|e<<32-t},t.rotl32=function(e,t){return e<>>32-t},t.sum32=function(e,t){return e+t>>>0},t.sum32_3=function(e,t,n){return e+t+n>>>0},t.sum32_4=function(e,t,n,r){return e+t+n+r>>>0},t.sum32_5=function(e,t,n,r,i){return e+t+n+r+i>>>0},t.sum64=function(e,t,n,r){var i=e[t],o=r+e[t+1]>>>0,s=(o>>0,e[t+1]=o},t.sum64_hi=function(e,t,n,r){return(t+r>>>0>>0},t.sum64_lo=function(e,t,n,r){return t+r>>>0},t.sum64_4_hi=function(e,t,n,r,i,o,s,a){var u=0,c=t;return u+=(c=c+r>>>0)>>0)>>0)>>0},t.sum64_4_lo=function(e,t,n,r,i,o,s,a){return t+r+o+a>>>0},t.sum64_5_hi=function(e,t,n,r,i,o,s,a,u,c){var f=0,l=t;return f+=(l=l+r>>>0)>>0)>>0)>>0)>>0},t.sum64_5_lo=function(e,t,n,r,i,o,s,a,u,c){return t+r+o+a+c>>>0},t.rotr64_hi=function(e,t,n){return(t<<32-n|e>>>n)>>>0},t.rotr64_lo=function(e,t,n){return(e<<32-n|t>>>n)>>>0},t.shr64_hi=function(e,t,n){return e>>>n},t.shr64_lo=function(e,t,n){return(e<<32-n|t>>>n)>>>0}},function(e,t,n){"use strict";var r=n(62);t.a=r.a},function(e,t,n){var r=n(223),i="object"==typeof self&&self&&self.Object===Object&&self,o=r||i||Function("return this")();e.exports=o},function(e,t,n){"use strict";const r=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",i="["+r+"][:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*",o=new RegExp("^"+i+"$");t.isExist=function(e){return void 0!==e},t.isEmptyObject=function(e){return 0===Object.keys(e).length},t.merge=function(e,t,n){if(t){const r=Object.keys(t),i=r.length;for(let o=0;o>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function a(e){var t=this.lastTotal-this.lastNeed,n=function(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function u(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function c(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function f(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function l(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function d(e){return e.toString(this.encoding)}function h(e){return e&&e.length?this.write(e):""}t.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n=0)return i>0&&(e.lastNeed=i-1),i;if(--r=0)return i>0&&(e.lastNeed=i-2),i;if(--r=0)return i>0&&(2===i?i=0:e.lastNeed=i-3),i;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},function(e,t,n){"use strict";var r=n(92),i=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};e.exports=l;var o=Object.create(n(80));o.inherits=n(7);var s=n(171),a=n(120);o.inherits(l,s);for(var u=i(a.prototype),c=0;c0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},M="undefined"!=typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("amplify_default"):"@@amplify_default",A=function(e,t,n){o.a.dispatch("auth",{event:e,data:t,message:n},"Auth",M)},I=new i.a("OAuth"),k=function(){function e(e){var t=e.config,n=e.cognitoClientId,r=e.scopes,i=void 0===r?[]:r;if(this._urlOpener=t.urlOpener||v,this._config=t,this._cognitoClientId=n,!this.isValidScopes(i))throw Error("scopes must be a String Array");this._scopes=i}return e.prototype.isValidScopes=function(e){return Array.isArray(e)&&e.every((function(e){return"string"==typeof e}))},e.prototype.oauthSignIn=function(e,t,n,i,o,s){void 0===e&&(e="code"),void 0===o&&(o=r.b.Cognito);var a=this._generateState(32),u=s?a+"-"+s.split("").map((function(e){return e.charCodeAt(0).toString(16).padStart(2,"0")})).join(""):a;!function(e){window.sessionStorage.setItem("oauth_state",e)}(u);var c,f=this._generateRandom(128);c=f,window.sessionStorage.setItem("ouath_pkce_key",c);var l=this._generateChallenge(f),d=this._scopes.join(" "),h="https://"+t+"/oauth2/authorize?"+Object.entries(w(w({redirect_uri:n,response_type:e,client_id:i,identity_provider:o,scope:d,state:u},"code"===e?{code_challenge:l}:{}),"code"===e?{code_challenge_method:"S256"}:{})).map((function(e){var t=E(e,2),n=t[0],r=t[1];return encodeURIComponent(n)+"="+encodeURIComponent(r)})).join("&");I.debug("Redirecting to "+h),this._urlOpener(h,n)},e.prototype._handleCodeFlow=function(e){return _(this,void 0,void 0,(function(){var t,n,i,o,s,a,u,c,f,l,d,h;return S(this,(function(v){switch(v.label){case 0:return(t=(Object(p.parse)(e).query||"").split("&").map((function(e){return e.split("=")})).reduce((function(e,t){var n,r=E(t,2),i=r[0],o=r[1];return w(w({},e),((n={})[i]=o,n))}),{code:void 0}).code)&&Object(p.parse)(e).pathname===Object(p.parse)(this._config.redirectSignIn).pathname?(n="https://"+this._config.domain+"/oauth2/token",A("codeFlow",{},"Retrieving tokens from "+n),i=Object(r.d)(this._config)?this._cognitoClientId:this._config.clientID,o=Object(r.d)(this._config)?this._config.redirectSignIn:this._config.redirectUri,g=window.sessionStorage.getItem("ouath_pkce_key"),window.sessionStorage.removeItem("ouath_pkce_key"),a=w({grant_type:"authorization_code",code:t,client_id:i,redirect_uri:o},(s=g)?{code_verifier:s}:{}),I.debug("Calling token endpoint: "+n+" with",a),u=Object.entries(a).map((function(e){var t=E(e,2),n=t[0],r=t[1];return encodeURIComponent(n)+"="+encodeURIComponent(r)})).join("&"),[4,fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:u})]):[2];case 1:return[4,v.sent().json()];case 2:if(c=v.sent(),f=c.access_token,l=c.refresh_token,d=c.id_token,h=c.error)throw new Error(h);return[2,{accessToken:f,refreshToken:l,idToken:d}]}var g}))}))},e.prototype._handleImplicitFlow=function(e){return _(this,void 0,void 0,(function(){var t,n,r;return S(this,(function(i){return t=(Object(p.parse)(e).hash||"#").substr(1).split("&").map((function(e){return e.split("=")})).reduce((function(e,t){var n,r=E(t,2),i=r[0],o=r[1];return w(w({},e),((n={})[i]=o,n))}),{id_token:void 0,access_token:void 0}),n=t.id_token,r=t.access_token,A("implicitFlow",{},"Got tokens from "+e),I.debug("Retrieving implicit tokens from "+e+" with"),[2,{accessToken:r,idToken:n,refreshToken:null}]}))}))},e.prototype.handleAuthResponse=function(e){return _(this,void 0,void 0,(function(){var t,n,r,i,o,s,a;return S(this,(function(u){switch(u.label){case 0:if(u.trys.push([0,5,,6]),t=e?w(w({},(Object(p.parse)(e).hash||"#").substr(1).split("&").map((function(e){return e.split("=")})).reduce((function(e,t){var n=E(t,2),r=n[0],i=n[1];return e[r]=i,e}),{})),(Object(p.parse)(e).query||"").split("&").map((function(e){return e.split("=")})).reduce((function(e,t){var n=E(t,2),r=n[0],i=n[1];return e[r]=i,e}),{})):{},n=t.error,r=t.error_description,n)throw new Error(r);return i=this._validateState(t),I.debug("Starting "+this._config.responseType+" flow with "+e),"code"!==this._config.responseType?[3,2]:(o=[{}],[4,this._handleCodeFlow(e)]);case 1:return[2,w.apply(void 0,[w.apply(void 0,o.concat([u.sent()])),{state:i}])];case 2:return s=[{}],[4,this._handleImplicitFlow(e)];case 3:return[2,w.apply(void 0,[w.apply(void 0,s.concat([u.sent()])),{state:i}])];case 4:return[3,6];case 5:throw a=u.sent(),I.error("Error handling auth response.",a),a;case 6:return[2]}}))}))},e.prototype._validateState=function(e){if(e){var t,n=(t=window.sessionStorage.getItem("oauth_state"),window.sessionStorage.removeItem("oauth_state"),t),r=e.state;if(n&&n!==r)throw new Error("Invalid state in OAuth flow");return r}},e.prototype.signOut=function(){return _(this,void 0,void 0,(function(){var e,t,n;return S(this,(function(i){return e="https://"+this._config.domain+"/logout?",t=Object(r.d)(this._config)?this._cognitoClientId:this._config.oauth.clientID,n=Object(r.d)(this._config)?this._config.redirectSignOut:this._config.returnTo,e+=Object.entries({client_id:t,logout_uri:encodeURIComponent(n)}).map((function(e){var t=E(e,2);return t[0]+"="+t[1]})).join("&"),A("oAuthSignOut",{oAuth:"signOut"},"Signing out from "+e),I.debug("Signing out from "+e),[2,this._urlOpener(e)]}))}))},e.prototype._generateState=function(e){for(var t="",n=e,r="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";n>0;--n)t+=r[Math.round(Math.random()*(r.length-1))];return t},e.prototype._generateChallenge=function(e){return this._base64URL(m()(e))},e.prototype._base64URL=function(e){return e.toString(y.a).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")},e.prototype._generateRandom=function(e){var t=new Uint8Array(e);if("undefined"!=typeof window&&window.crypto)window.crypto.getRandomValues(t);else for(var n=0;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},B=new i.a("AuthClass"),F="undefined"!=typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("amplify_default"):"@@amplify_default",z=function(e,t,n){o.a.dispatch("auth",{event:e,data:t,message:n},"Auth",F)},q=new(function(){function e(e){var t=this;this.userPool=null,this.user=null,this.oAuthFlowInProgress=!1,this.Credentials=s.a,this.wrapRefreshSessionCallback=function(e){return function(t,n){return n?z("tokenRefresh",void 0,"New token retrieved"):z("tokenRefresh_failure",t,"Failed to retrieve new token"),e(t,n)}},this.configure(e),this.currentCredentials=this.currentCredentials.bind(this),this.currentUserCredentials=this.currentUserCredentials.bind(this),o.a.listen("auth",(function(e){switch(e.payload.event){case"signIn":t._storage.setItem("amplify-signin-with-hostedUI","false");break;case"signOut":t._storage.removeItem("amplify-signin-with-hostedUI");break;case"cognitoHostedUI":t._storage.setItem("amplify-signin-with-hostedUI","true")}}))}return e.prototype.getModuleName=function(){return"Auth"},e.prototype.configure=function(e){var t=this;if(!e)return this._config||{};B.debug("configure Auth");var n=Object.assign({},this._config,a.a.parseMobilehubConfig(e).Auth,e);this._config=n;var i=this._config,o=i.userPoolId,s=i.userPoolWebClientId,l=i.cookieStorage,d=i.oauth,p=i.region,v=i.identityPoolId,g=i.mandatorySignIn,m=i.refreshHandlers,b=i.identityPoolRegion,y=i.clientMetadata,w=i.endpoint;if(this._config.storage){if(!this._isValidAuthStorage(this._config.storage))throw B.error("The storage in the Auth config is not valid!"),new Error("Empty storage object");this._storage=this._config.storage}else this._storage=l?new h.i(l):e.ssr?new u.a:(new c.a).getStorage();if(this._storageSync=Promise.resolve(),"function"==typeof this._storage.sync&&(this._storageSync=this._storage.sync()),o){var _={UserPoolId:o,ClientId:s,endpoint:w};_.Storage=this._storage,this.userPool=new h.g(_,this.wrapRefreshSessionCallback)}this.Credentials.configure({mandatorySignIn:g,region:b||p,userPoolId:o,identityPoolId:v,refreshHandlers:m,storage:this._storage});var S=d?Object(r.d)(this._config.oauth)?d:d.awsCognito:void 0;if(S){var E=Object.assign({cognitoClientId:s,UserPoolId:o,domain:S.domain,scopes:S.scope,redirectSignIn:S.redirectSignIn,redirectSignOut:S.redirectSignOut,responseType:S.responseType,Storage:this._storage,urlOpener:S.urlOpener,clientMetadata:y},S.options);this._oAuthHandler=new k({scopes:E.scopes,config:E,cognitoClientId:E.cognitoClientId});var M={};!function(e){if(f.a.browserOrNode().isBrowser&&window.location)e({url:window.location.href});else if(!f.a.browserOrNode().isNode)throw new Error("Not supported")}((function(e){var n=e.url;M[n]||(M[n]=!0,t._handleAuthResponse(n))}))}return z("configured",null,"The Auth category has been configured successfully"),this._config},e.prototype.signUp=function(e){for(var t=this,n=[],i=1;i4294967295)throw new RangeError("requested too many random bytes");var n=i.allocUnsafe(e);if(e>0)if(e>65536)for(var s=0;s2?"one of ".concat(t," ").concat(e.slice(0,n-1).join(", "),", or ")+e[n-1]:2===n?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}i("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),i("ERR_INVALID_ARG_TYPE",(function(e,t,n){var r,i,s,a;if("string"==typeof t&&(i="not ",t.substr(!s||s<0?0:+s,i.length)===i)?(r="must not be",t=t.replace(/^not /,"")):r="must be",function(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}(e," argument"))a="The ".concat(e," ").concat(r," ").concat(o(t,"type"));else{var u=function(e,t,n){return"number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}(e,".")?"property":"argument";a='The "'.concat(e,'" ').concat(u," ").concat(r," ").concat(o(t,"type"))}return a+=". Received type ".concat(typeof n)}),TypeError),i("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),i("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),i("ERR_STREAM_PREMATURE_CLOSE","Premature close"),i("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),i("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),i("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),i("ERR_STREAM_WRITE_AFTER_END","write after end"),i("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),i("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),i("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),e.exports.codes=r},function(e,t,n){"use strict";(function(t){var r=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};e.exports=c;var i=n(163),o=n(167);n(7)(c,i);for(var s=r(o.prototype),a=0;a=this._finalSize&&(this._update(this._block),this._block.fill(0));var n=8*this._len;if(n<=4294967295)this._block.writeUInt32BE(n,this._blockSize-4);else{var r=(4294967295&n)>>>0,i=(n-r)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(r,this._blockSize-4)}this._update(this._block);var o=this._hash();return e?o.toString(e):o},i.prototype._update=function(){throw new Error("_update must be implemented by subclass")},e.exports=i},function(e,t,n){"use strict";var r={};function i(e,t,n){n||(n=Error);var i=function(e){var n,r;function i(n,r,i){return e.call(this,function(e,n,r){return"string"==typeof t?t:t(e,n,r)}(n,r,i))||this}return r=e,(n=i).prototype=Object.create(r.prototype),n.prototype.constructor=n,n.__proto__=r,i}(n);i.prototype.name=n.name,i.prototype.code=e,r[e]=i}function o(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map((function(e){return String(e)})),n>2?"one of ".concat(t," ").concat(e.slice(0,n-1).join(", "),", or ")+e[n-1]:2===n?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}i("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),i("ERR_INVALID_ARG_TYPE",(function(e,t,n){var r,i,s,a;if("string"==typeof t&&(i="not ",t.substr(!s||s<0?0:+s,i.length)===i)?(r="must not be",t=t.replace(/^not /,"")):r="must be",function(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}(e," argument"))a="The ".concat(e," ").concat(r," ").concat(o(t,"type"));else{var u=function(e,t,n){return"number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}(e,".")?"property":"argument";a='The "'.concat(e,'" ').concat(u," ").concat(r," ").concat(o(t,"type"))}return a+=". Received type ".concat(typeof n)}),TypeError),i("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),i("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),i("ERR_STREAM_PREMATURE_CLOSE","Premature close"),i("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),i("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),i("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),i("ERR_STREAM_WRITE_AFTER_END","write after end"),i("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),i("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),i("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),e.exports.codes=r},function(e,t,n){"use strict";(function(t){var r=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};e.exports=c;var i=n(192),o=n(196);n(7)(c,i);for(var s=r(o.prototype),a=0;a0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},i={clockOffset:0,getDateWithClockOffset:function(){return i.clockOffset?new Date((new Date).getTime()+i.clockOffset):new Date},getClockOffset:function(){return i.clockOffset},getHeaderStringFromDate:function(e){return void 0===e&&(e=i.getDateWithClockOffset()),e.toISOString().replace(/[:\-]|\.\d{3}/g,"")},getDateFromHeaderString:function(e){var t=r(e.match(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2}).+/),7),n=t[1],i=t[2],o=t[3],s=t[4],a=t[5],u=t[6];return new Date(Date.UTC(Number(n),Number(i)-1,Number(o),Number(s),Number(a),Number(u)))},isClockSkewed:function(e){return Math.abs(e.getTime()-i.getDateWithClockOffset().getTime())>=3e5},isClockSkewError:function(e){if(!e.response||!e.response.headers)return!1;var t=e.response.headers;return Boolean("BadRequestException"===t["x-amzn-errortype"]&&(t.date||t.Date))},setClockOffset:function(e){i.clockOffset=e}}},,function(e,t,n){"use strict";var r=n(7),i=n(113),o=n(116),s=n(117),a=n(56);function u(e){a.call(this,"digest"),this._hash=e}r(u,a),u.prototype._update=function(e){this._hash.update(e)},u.prototype._final=function(){return this._hash.digest()},e.exports=function(e){return"md5"===(e=e.toLowerCase())?new i:"rmd160"===e||"ripemd160"===e?new o:new u(s(e))}},function(e,t,n){(function(e){function n(e){return Object.prototype.toString.call(e)}t.isArray=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===n(e)},t.isBoolean=function(e){return"boolean"==typeof e},t.isNull=function(e){return null===e},t.isNullOrUndefined=function(e){return null==e},t.isNumber=function(e){return"number"==typeof e},t.isString=function(e){return"string"==typeof e},t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=function(e){return void 0===e},t.isRegExp=function(e){return"[object RegExp]"===n(e)},t.isObject=function(e){return"object"==typeof e&&null!==e},t.isDate=function(e){return"[object Date]"===n(e)},t.isError=function(e){return"[object Error]"===n(e)||e instanceof Error},t.isFunction=function(e){return"function"==typeof e},t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=e.isBuffer}).call(this,n(6).Buffer)},function(e,t,n){(function(t){e.exports=function(e,n){for(var r=Math.min(e.length,n.length),i=new t(r),o=0;o=this._delta8){var n=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-n,e.length),0===this.pending.length&&(this.pending=null),e=r.join32(e,0,e.length-n,this.endian);for(var i=0;i>>24&255,r[i++]=e>>>16&255,r[i++]=e>>>8&255,r[i++]=255&e}else for(r[i++]=255&e,r[i++]=e>>>8&255,r[i++]=e>>>16&255,r[i++]=e>>>24&255,r[i++]=0,r[i++]=0,r[i++]=0,r[i++]=0,o=8;o>>7)^(p<<14|p>>>18)^p>>>3,g=c[h-2],m=(g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10;c[h]=v+c[h-7]+m+c[h-16]}var b=r&i^r&o^i&o,y=(r<<30|r>>>2)^(r<<19|r>>>13)^(r<<10|r>>>22),w=d+((a<<26|a>>>6)^(a<<21|a>>>11)^(a<<7|a>>>25))+(a&f^~a&l)+u[h]+c[h];d=l,l=f,f=a,a=s+w|0,s=o,o=i,i=r,r=w+(y+b)|0}n[0]=n[0]+r|0,n[1]=n[1]+i|0,n[2]=n[2]+o|0,n[3]=n[3]+s|0,n[4]=n[4]+a|0,n[5]=n[5]+f|0,n[6]=n[6]+l|0,n[7]=n[7]+d|0},_doFinalize:function(){var t=this._data,n=t.words,r=8*this._nDataBytes,i=8*t.sigBytes;return n[i>>>5]|=128<<24-i%32,n[14+(i+64>>>9<<4)]=e.floor(r/4294967296),n[15+(i+64>>>9<<4)]=r,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=o._createHelper(f),t.HmacSHA256=o._createHmacHelper(f)}(Math),r.SHA256)},function(e,t,n){"use strict";n.d(t,"a",(function(){return c}));var r=n(44),i=function(){return(i=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},s=function(){for(var e=[],t=0;t-1)&&(r===u||a.warn("WARNING: "+e+" is protected and dispatching on it can have unintended consequences"));var o={channel:e,payload:i({},t),source:n,patternInfo:[]};try{this._toListeners(o)}catch(e){a.error(e)}},e.prototype.listen=function(e,t,n){var r,i=this;if(void 0===n&&(n="noname"),function(e){return void 0!==e.onHubCapsule}(t))a.warn("WARNING onHubCapsule is Deprecated. Please pass in a callback."),r=t.onHubCapsule.bind(t);else{if("function"!=typeof t)throw new Error("No callback supplied to Hub");r=t}if(e instanceof RegExp)this.patterns.push({pattern:e,callback:r});else{var o=this.listeners[e];o||(o=[],this.listeners[e]=o),o.push({name:n,callback:r})}return function(){i.remove(e,r)}},e.prototype._toListeners=function(e){var t=e.channel,n=e.payload,r=this.listeners[t];if(r&&r.forEach((function(r){a.debug("Dispatching to "+t+" with ",n);try{r.callback(e)}catch(e){a.error(e)}})),this.patterns.length>0){if(!n.message)return void a.warn("Cannot perform pattern matching without a message key");var s=n.message;this.patterns.forEach((function(t){var n=s.match(t.pattern);if(n){var r=o(n).slice(1),u=i(i({},e),{patternInfo:r});try{t.callback(u)}catch(e){a.error(e)}}}))}},e}())("__default__")},function(e,t,n){"use strict";n.d(t,"a",(function(){return Lt}));var r=n(44),i=n(86),o=n(33),s=n(73),a=n(514),u=n(50),c=n(19),f=n(1),l=function(e,t){return(l=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(e,t)};function d(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}l(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var h=function(){return(h=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s}var m,b,y,w,_,S,E,M,A,I,k,O,x,C,T,P,N,R,L,j,D,U,B,F,z,q,K,H,V,G,W,$,Y,J,Z,X,Q,ee,te,ne,re,ie,oe,se,ae,ue,ce,fe,le,de,he,pe,ve,ge,me,be,ye;Object.create;!function(e){e.AUTHENTICATED_ROLE="AuthenticatedRole",e.DENY="Deny"}(m||(m={})),(b||(b={})).filterSensitiveLog=function(e){return h({},e)},(y||(y={})).filterSensitiveLog=function(e){return h({},e)},(w||(w={})).filterSensitiveLog=function(e){return h({},e)},(_||(_={})).filterSensitiveLog=function(e){return h({},e)},(S||(S={})).filterSensitiveLog=function(e){return h({},e)},(E||(E={})).filterSensitiveLog=function(e){return h({},e)},(M||(M={})).filterSensitiveLog=function(e){return h({},e)},(A||(A={})).filterSensitiveLog=function(e){return h({},e)},(I||(I={})).filterSensitiveLog=function(e){return h({},e)},(k||(k={})).filterSensitiveLog=function(e){return h({},e)},function(e){e.ACCESS_DENIED="AccessDenied",e.INTERNAL_SERVER_ERROR="InternalServerError"}(O||(O={})),(x||(x={})).filterSensitiveLog=function(e){return h({},e)},(C||(C={})).filterSensitiveLog=function(e){return h({},e)},(T||(T={})).filterSensitiveLog=function(e){return h({},e)},(P||(P={})).filterSensitiveLog=function(e){return h({},e)},(N||(N={})).filterSensitiveLog=function(e){return h({},e)},(R||(R={})).filterSensitiveLog=function(e){return h({},e)},(L||(L={})).filterSensitiveLog=function(e){return h({},e)},(j||(j={})).filterSensitiveLog=function(e){return h({},e)},(D||(D={})).filterSensitiveLog=function(e){return h({},e)},(U||(U={})).filterSensitiveLog=function(e){return h({},e)},(B||(B={})).filterSensitiveLog=function(e){return h({},e)},(F||(F={})).filterSensitiveLog=function(e){return h({},e)},(z||(z={})).filterSensitiveLog=function(e){return h({},e)},(q||(q={})).filterSensitiveLog=function(e){return h({},e)},(K||(K={})).filterSensitiveLog=function(e){return h({},e)},function(e){e.CONTAINS="Contains",e.EQUALS="Equals",e.NOT_EQUAL="NotEqual",e.STARTS_WITH="StartsWith"}(H||(H={})),(V||(V={})).filterSensitiveLog=function(e){return h({},e)},(G||(G={})).filterSensitiveLog=function(e){return h({},e)},function(e){e.RULES="Rules",e.TOKEN="Token"}(W||(W={})),($||($={})).filterSensitiveLog=function(e){return h({},e)},(Y||(Y={})).filterSensitiveLog=function(e){return h({},e)},(J||(J={})).filterSensitiveLog=function(e){return h({},e)},(Z||(Z={})).filterSensitiveLog=function(e){return h({},e)},(X||(X={})).filterSensitiveLog=function(e){return h({},e)},(Q||(Q={})).filterSensitiveLog=function(e){return h({},e)},(ee||(ee={})).filterSensitiveLog=function(e){return h({},e)},(te||(te={})).filterSensitiveLog=function(e){return h({},e)},(ne||(ne={})).filterSensitiveLog=function(e){return h({},e)},(re||(re={})).filterSensitiveLog=function(e){return h({},e)},(ie||(ie={})).filterSensitiveLog=function(e){return h({},e)},(oe||(oe={})).filterSensitiveLog=function(e){return h({},e)},(se||(se={})).filterSensitiveLog=function(e){return h({},e)},(ae||(ae={})).filterSensitiveLog=function(e){return h({},e)},(ue||(ue={})).filterSensitiveLog=function(e){return h({},e)},(ce||(ce={})).filterSensitiveLog=function(e){return h({},e)},(fe||(fe={})).filterSensitiveLog=function(e){return h({},e)},(le||(le={})).filterSensitiveLog=function(e){return h({},e)},(de||(de={})).filterSensitiveLog=function(e){return h({},e)},(he||(he={})).filterSensitiveLog=function(e){return h({},e)},(pe||(pe={})).filterSensitiveLog=function(e){return h({},e)},(ve||(ve={})).filterSensitiveLog=function(e){return h({},e)},(ge||(ge={})).filterSensitiveLog=function(e){return h({},e)},(me||(me={})).filterSensitiveLog=function(e){return h({},e)},(be||(be={})).filterSensitiveLog=function(e){return h({},e)},(ye||(ye={})).filterSensitiveLog=function(e){return h({},e)};var we=n(2),_e=function(e,t){return p(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,f,l,d,p,g,m,b,y;return v(this,(function(v){switch(v.label){case 0:return r=[h({},e)],y={},[4,Je(e.body,t)];case 1:switch(n=h.apply(void 0,r.concat([(y.body=v.sent(),y)])),o="UnknownError",s=n.body.__type.split("#"),o=void 0===s[1]?s[0]:s[1],o){case"ExternalServiceException":case"com.amazonaws.cognitoidentity#ExternalServiceException":return[3,2];case"InternalErrorException":case"com.amazonaws.cognitoidentity#InternalErrorException":return[3,4];case"InvalidIdentityPoolConfigurationException":case"com.amazonaws.cognitoidentity#InvalidIdentityPoolConfigurationException":return[3,6];case"InvalidParameterException":case"com.amazonaws.cognitoidentity#InvalidParameterException":return[3,8];case"NotAuthorizedException":case"com.amazonaws.cognitoidentity#NotAuthorizedException":return[3,10];case"ResourceConflictException":case"com.amazonaws.cognitoidentity#ResourceConflictException":return[3,12];case"ResourceNotFoundException":case"com.amazonaws.cognitoidentity#ResourceNotFoundException":return[3,14];case"TooManyRequestsException":case"com.amazonaws.cognitoidentity#TooManyRequestsException":return[3,16]}return[3,18];case 2:return a=[{}],[4,Ee(n,t)];case 3:return i=h.apply(void 0,[h.apply(void 0,a.concat([v.sent()])),{name:o,$metadata:We(e)}]),[3,19];case 4:return u=[{}],[4,Me(n,t)];case 5:return i=h.apply(void 0,[h.apply(void 0,u.concat([v.sent()])),{name:o,$metadata:We(e)}]),[3,19];case 6:return c=[{}],[4,Ae(n,t)];case 7:return i=h.apply(void 0,[h.apply(void 0,c.concat([v.sent()])),{name:o,$metadata:We(e)}]),[3,19];case 8:return f=[{}],[4,Ie(n,t)];case 9:return i=h.apply(void 0,[h.apply(void 0,f.concat([v.sent()])),{name:o,$metadata:We(e)}]),[3,19];case 10:return l=[{}],[4,Oe(n,t)];case 11:return i=h.apply(void 0,[h.apply(void 0,l.concat([v.sent()])),{name:o,$metadata:We(e)}]),[3,19];case 12:return d=[{}],[4,xe(n,t)];case 13:return i=h.apply(void 0,[h.apply(void 0,d.concat([v.sent()])),{name:o,$metadata:We(e)}]),[3,19];case 14:return p=[{}],[4,Ce(n,t)];case 15:return i=h.apply(void 0,[h.apply(void 0,p.concat([v.sent()])),{name:o,$metadata:We(e)}]),[3,19];case 16:return g=[{}],[4,Te(n,t)];case 17:return i=h.apply(void 0,[h.apply(void 0,g.concat([v.sent()])),{name:o,$metadata:We(e)}]),[3,19];case 18:m=n.body,o=m.code||m.Code||o,i=h(h({},m),{name:""+o,message:m.message||m.Message||o,$fault:"client",$metadata:We(e)}),v.label=19;case 19:return b=i.message||i.Message||o,i.message=b,delete i.Message,[2,Promise.reject(Object.assign(new Error(b),i))]}}))}))},Se=function(e,t){return p(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,f,l,d,p,g,m,b,y;return v(this,(function(v){switch(v.label){case 0:return r=[h({},e)],y={},[4,Je(e.body,t)];case 1:switch(n=h.apply(void 0,r.concat([(y.body=v.sent(),y)])),o="UnknownError",s=n.body.__type.split("#"),o=void 0===s[1]?s[0]:s[1],o){case"ExternalServiceException":case"com.amazonaws.cognitoidentity#ExternalServiceException":return[3,2];case"InternalErrorException":case"com.amazonaws.cognitoidentity#InternalErrorException":return[3,4];case"InvalidParameterException":case"com.amazonaws.cognitoidentity#InvalidParameterException":return[3,6];case"LimitExceededException":case"com.amazonaws.cognitoidentity#LimitExceededException":return[3,8];case"NotAuthorizedException":case"com.amazonaws.cognitoidentity#NotAuthorizedException":return[3,10];case"ResourceConflictException":case"com.amazonaws.cognitoidentity#ResourceConflictException":return[3,12];case"ResourceNotFoundException":case"com.amazonaws.cognitoidentity#ResourceNotFoundException":return[3,14];case"TooManyRequestsException":case"com.amazonaws.cognitoidentity#TooManyRequestsException":return[3,16]}return[3,18];case 2:return a=[{}],[4,Ee(n,t)];case 3:return i=h.apply(void 0,[h.apply(void 0,a.concat([v.sent()])),{name:o,$metadata:We(e)}]),[3,19];case 4:return u=[{}],[4,Me(n,t)];case 5:return i=h.apply(void 0,[h.apply(void 0,u.concat([v.sent()])),{name:o,$metadata:We(e)}]),[3,19];case 6:return c=[{}],[4,Ie(n,t)];case 7:return i=h.apply(void 0,[h.apply(void 0,c.concat([v.sent()])),{name:o,$metadata:We(e)}]),[3,19];case 8:return f=[{}],[4,ke(n,t)];case 9:return i=h.apply(void 0,[h.apply(void 0,f.concat([v.sent()])),{name:o,$metadata:We(e)}]),[3,19];case 10:return l=[{}],[4,Oe(n,t)];case 11:return i=h.apply(void 0,[h.apply(void 0,l.concat([v.sent()])),{name:o,$metadata:We(e)}]),[3,19];case 12:return d=[{}],[4,xe(n,t)];case 13:return i=h.apply(void 0,[h.apply(void 0,d.concat([v.sent()])),{name:o,$metadata:We(e)}]),[3,19];case 14:return p=[{}],[4,Ce(n,t)];case 15:return i=h.apply(void 0,[h.apply(void 0,p.concat([v.sent()])),{name:o,$metadata:We(e)}]),[3,19];case 16:return g=[{}],[4,Te(n,t)];case 17:return i=h.apply(void 0,[h.apply(void 0,g.concat([v.sent()])),{name:o,$metadata:We(e)}]),[3,19];case 18:m=n.body,o=m.code||m.Code||o,i=h(h({},m),{name:""+o,message:m.message||m.Message||o,$fault:"client",$metadata:We(e)}),v.label=19;case 19:return b=i.message||i.Message||o,i.message=b,delete i.Message,[2,Promise.reject(Object.assign(new Error(b),i))]}}))}))},Ee=function(e,t){return p(void 0,void 0,void 0,(function(){var n,r;return v(this,(function(i){return n=e.body,r=je(n,t),[2,h({name:"ExternalServiceException",$fault:"client",$metadata:We(e)},r)]}))}))},Me=function(e,t){return p(void 0,void 0,void 0,(function(){var n,r;return v(this,(function(i){return n=e.body,r=Be(n,t),[2,h({name:"InternalErrorException",$fault:"server",$metadata:We(e)},r)]}))}))},Ae=function(e,t){return p(void 0,void 0,void 0,(function(){var n,r;return v(this,(function(i){return n=e.body,r=Fe(n,t),[2,h({name:"InvalidIdentityPoolConfigurationException",$fault:"client",$metadata:We(e)},r)]}))}))},Ie=function(e,t){return p(void 0,void 0,void 0,(function(){var n,r;return v(this,(function(i){return n=e.body,r=ze(n,t),[2,h({name:"InvalidParameterException",$fault:"client",$metadata:We(e)},r)]}))}))},ke=function(e,t){return p(void 0,void 0,void 0,(function(){var n,r;return v(this,(function(i){return n=e.body,r=qe(n,t),[2,h({name:"LimitExceededException",$fault:"client",$metadata:We(e)},r)]}))}))},Oe=function(e,t){return p(void 0,void 0,void 0,(function(){var n,r;return v(this,(function(i){return n=e.body,r=Ke(n,t),[2,h({name:"NotAuthorizedException",$fault:"client",$metadata:We(e)},r)]}))}))},xe=function(e,t){return p(void 0,void 0,void 0,(function(){var n,r;return v(this,(function(i){return n=e.body,r=He(n,t),[2,h({name:"ResourceConflictException",$fault:"client",$metadata:We(e)},r)]}))}))},Ce=function(e,t){return p(void 0,void 0,void 0,(function(){var n,r;return v(this,(function(i){return n=e.body,r=Ve(n,t),[2,h({name:"ResourceNotFoundException",$fault:"client",$metadata:We(e)},r)]}))}))},Te=function(e,t){return p(void 0,void 0,void 0,(function(){var n,r;return v(this,(function(i){return n=e.body,r=Ge(n,t),[2,h({name:"TooManyRequestsException",$fault:"client",$metadata:We(e)},r)]}))}))},Pe=function(e,t){return h(h(h({},void 0!==e.CustomRoleArn&&{CustomRoleArn:e.CustomRoleArn}),void 0!==e.IdentityId&&{IdentityId:e.IdentityId}),void 0!==e.Logins&&{Logins:Re(e.Logins,t)})},Ne=function(e,t){return h(h(h({},void 0!==e.AccountId&&{AccountId:e.AccountId}),void 0!==e.IdentityPoolId&&{IdentityPoolId:e.IdentityPoolId}),void 0!==e.Logins&&{Logins:Re(e.Logins,t)})},Re=function(e,t){return Object.entries(e).reduce((function(e,t){var n,r=g(t,2),i=r[0],o=r[1];return h(h({},e),((n={})[i]=o,n))}),{})},Le=function(e,t){return{AccessKeyId:void 0!==e.AccessKeyId&&null!==e.AccessKeyId?e.AccessKeyId:void 0,Expiration:void 0!==e.Expiration&&null!==e.Expiration?new Date(Math.round(1e3*e.Expiration)):void 0,SecretKey:void 0!==e.SecretKey&&null!==e.SecretKey?e.SecretKey:void 0,SessionToken:void 0!==e.SessionToken&&null!==e.SessionToken?e.SessionToken:void 0}},je=function(e,t){return{message:void 0!==e.message&&null!==e.message?e.message:void 0}},De=function(e,t){return{Credentials:void 0!==e.Credentials&&null!==e.Credentials?Le(e.Credentials):void 0,IdentityId:void 0!==e.IdentityId&&null!==e.IdentityId?e.IdentityId:void 0}},Ue=function(e,t){return{IdentityId:void 0!==e.IdentityId&&null!==e.IdentityId?e.IdentityId:void 0}},Be=function(e,t){return{message:void 0!==e.message&&null!==e.message?e.message:void 0}},Fe=function(e,t){return{message:void 0!==e.message&&null!==e.message?e.message:void 0}},ze=function(e,t){return{message:void 0!==e.message&&null!==e.message?e.message:void 0}},qe=function(e,t){return{message:void 0!==e.message&&null!==e.message?e.message:void 0}},Ke=function(e,t){return{message:void 0!==e.message&&null!==e.message?e.message:void 0}},He=function(e,t){return{message:void 0!==e.message&&null!==e.message?e.message:void 0}},Ve=function(e,t){return{message:void 0!==e.message&&null!==e.message?e.message:void 0}},Ge=function(e,t){return{message:void 0!==e.message&&null!==e.message?e.message:void 0}},We=function(e){return{httpStatusCode:e.statusCode,httpHeaders:e.headers,requestId:e.headers["x-amzn-requestid"]}},$e=function(e,t){return void 0===e&&(e=new Uint8Array),e instanceof Uint8Array?Promise.resolve(e):t.streamCollector(e)||Promise.resolve(new Uint8Array)},Ye=function(e,t,n,r,i){return p(void 0,void 0,void 0,(function(){var o,s,a,u,c,f;return v(this,(function(l){switch(l.label){case 0:return[4,e.endpoint()];case 1:return o=l.sent(),s=o.hostname,a=o.protocol,u=void 0===a?"https":a,c=o.port,f={protocol:u,hostname:s,port:c,method:"POST",path:n,headers:t},void 0!==r&&(f.hostname=r),void 0!==i&&(f.body=i),[2,new we.a(f)]}}))}))},Je=function(e,t){return function(e,t){return $e(e,t).then((function(e){return t.utf8Encoder(e)}))}(e,t).then((function(e){return e.length?JSON.parse(e):{}}))},Ze=n(10),Xe=n(0),Qe=function(e){function t(t){var n=e.call(this)||this;return n.input=t,n}return d(t,e),t.prototype.resolveMiddleware=function(e,t,n){this.middlewareStack.use(Object(Ze.a)(t,this.serialize,this.deserialize));var r=e.concat(this.middlewareStack),i=t.logger,o={logger:i,clientName:"CognitoIdentityClient",commandName:"GetCredentialsForIdentityCommand",inputFilterSensitiveLog:D.filterSensitiveLog,outputFilterSensitiveLog:B.filterSensitiveLog};"function"==typeof i.info&&i.info({clientName:"CognitoIdentityClient",commandName:"GetCredentialsForIdentityCommand"});var s=t.requestHandler;return r.resolve((function(e){return s.handle(e.request,n||{})}),o)},t.prototype.serialize=function(e,t){return function(e,t){return p(void 0,void 0,void 0,(function(){var n,r;return v(this,(function(i){return n={"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AWSCognitoIdentityService.GetCredentialsForIdentity"},r=JSON.stringify(Pe(e,t)),[2,Ye(t,n,"/",void 0,r)]}))}))}(e,t)},t.prototype.deserialize=function(e,t){return function(e,t){return p(void 0,void 0,void 0,(function(){var n,r,i;return v(this,(function(o){switch(o.label){case 0:return e.statusCode>=300?[2,_e(e,t)]:[4,Je(e.body,t)];case 1:return n=o.sent(),{},r=De(n,t),i=h({$metadata:We(e)},r),[2,Promise.resolve(i)]}}))}))}(e,t)},t}(Xe.b),et=function(e){function t(t,n){void 0===n&&(n=!0);var r=e.call(this,t)||this;return r.tryNextLink=n,r}return Object(f.__extends)(t,e),t}(Error);function tt(e){return Promise.all(Object.keys(e).reduce((function(t,n){var r=e[n];return"string"==typeof r?t.push([n,r]):t.push(r().then((function(e){return[n,e]}))),t}),[])).then((function(e){return e.reduce((function(e,t){var n=Object(f.__read)(t,2),r=n[0],i=n[1];return e[r]=i,e}),{})}))}function nt(e){var t=this;return function(){return Object(f.__awaiter)(t,void 0,void 0,(function(){var t,n,r,i,o,s,a,u,c,l,d,h,p;return Object(f.__generator)(this,(function(f){switch(f.label){case 0:return l=(c=e.client).send,d=Qe.bind,p={CustomRoleArn:e.customRoleArn,IdentityId:e.identityId},e.logins?[4,tt(e.logins)]:[3,2];case 1:return h=f.sent(),[3,3];case 2:h=void 0,f.label=3;case 3:return[4,l.apply(c,[new(d.apply(Qe,[void 0,(p.Logins=h,p)]))])];case 4:return t=f.sent().Credentials,n=void 0===t?function(){throw new et("Response from Amazon Cognito contained no credentials")}():t,r=n.AccessKeyId,i=void 0===r?function(){throw new et("Response from Amazon Cognito contained no access key ID")}():r,o=n.Expiration,s=n.SecretKey,a=void 0===s?function(){throw new et("Response from Amazon Cognito contained no secret key")}():s,u=n.SessionToken,[2,{identityId:e.identityId,accessKeyId:i,secretAccessKey:a,sessionToken:u,expiration:o}]}}))}))}}var rt=function(e){function t(t){var n=e.call(this)||this;return n.input=t,n}return d(t,e),t.prototype.resolveMiddleware=function(e,t,n){this.middlewareStack.use(Object(Ze.a)(t,this.serialize,this.deserialize));var r=e.concat(this.middlewareStack),i=t.logger,o={logger:i,clientName:"CognitoIdentityClient",commandName:"GetIdCommand",inputFilterSensitiveLog:z.filterSensitiveLog,outputFilterSensitiveLog:q.filterSensitiveLog};"function"==typeof i.info&&i.info({clientName:"CognitoIdentityClient",commandName:"GetIdCommand"});var s=t.requestHandler;return r.resolve((function(e){return s.handle(e.request,n||{})}),o)},t.prototype.serialize=function(e,t){return function(e,t){return p(void 0,void 0,void 0,(function(){var n,r;return v(this,(function(i){return n={"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AWSCognitoIdentityService.GetId"},r=JSON.stringify(Ne(e,t)),[2,Ye(t,n,"/",void 0,r)]}))}))}(e,t)},t.prototype.deserialize=function(e,t){return function(e,t){return p(void 0,void 0,void 0,(function(){var n,r,i;return v(this,(function(o){switch(o.label){case 0:return e.statusCode>=300?[2,Se(e,t)]:[4,Je(e.body,t)];case 1:return n=o.sent(),{},r=Ue(n,t),i=h({$metadata:We(e)},r),[2,Promise.resolve(i)]}}))}))}(e,t)},t}(Xe.b),it=function(){function e(e){void 0===e&&(e="aws:cognito-identity-ids"),this.dbName=e}return e.prototype.getItem=function(e){return this.withObjectStore("readonly",(function(t){var n=t.get(e);return new Promise((function(e){n.onerror=function(){return e(null)},n.onsuccess=function(){return e(n.result?n.result.value:null)}}))})).catch((function(){return null}))},e.prototype.removeItem=function(e){return this.withObjectStore("readwrite",(function(t){var n=t.delete(e);return new Promise((function(e,t){n.onerror=function(){return t(n.error)},n.onsuccess=function(){return e()}}))}))},e.prototype.setItem=function(e,t){return this.withObjectStore("readwrite",(function(n){var r=n.put({id:e,value:t});return new Promise((function(e,t){r.onerror=function(){return t(r.error)},r.onsuccess=function(){return e()}}))}))},e.prototype.getDb=function(){var e=self.indexedDB.open(this.dbName,1);return new Promise((function(t,n){e.onsuccess=function(){t(e.result)},e.onerror=function(){n(e.error)},e.onblocked=function(){n(new Error("Unable to access DB"))},e.onupgradeneeded=function(){var t=e.result;t.onerror=function(){n(new Error("Failed to create object store"))},t.createObjectStore("IdentityIds",{keyPath:"id"})}}))},e.prototype.withObjectStore=function(e,t){return this.getDb().then((function(n){var r=n.transaction("IdentityIds",e);return r.oncomplete=function(){return n.close()},new Promise((function(e,n){r.onerror=function(){return n(r.error)},e(t(r.objectStore("IdentityIds")))})).catch((function(e){throw n.close(),e}))}))},e}(),ot=new(function(){function e(e){void 0===e&&(e={}),this.store=e}return e.prototype.getItem=function(e){return e in this.store?this.store[e]:null},e.prototype.removeItem=function(e){delete this.store[e]},e.prototype.setItem=function(e,t){this.store[e]=t},e}());function st(e){var t=this,n=e.accountId,r=e.cache,i=void 0===r?"object"==typeof self&&self.indexedDB?new it:"object"==typeof window&&window.localStorage?window.localStorage:ot:r,o=e.client,s=e.customRoleArn,a=e.identityPoolId,u=e.logins,c=e.userIdentifier,l=void 0===c?u&&0!==Object.keys(u).length?void 0:"ANONYMOUS":c,d=l?"aws:cognito-identity-credentials:"+a+":"+l:void 0,h=function(){return Object(f.__awaiter)(t,void 0,void 0,(function(){var e,t,r,c,l,p,v,g,m;return Object(f.__generator)(this,(function(f){switch(f.label){case 0:return(t=d)?[4,i.getItem(d)]:[3,2];case 1:t=f.sent(),f.label=2;case 2:return(e=t)?[3,7]:(p=(l=o).send,v=rt.bind,m={AccountId:n,IdentityPoolId:a},u?[4,tt(u)]:[3,4]);case 3:return g=f.sent(),[3,5];case 4:g=void 0,f.label=5;case 5:return[4,p.apply(l,[new(v.apply(rt,[void 0,(m.Logins=g,m)]))])];case 6:r=f.sent().IdentityId,c=void 0===r?function(){throw new et("Response from Amazon Cognito contained no identity ID")}():r,e=c,d&&Promise.resolve(i.setItem(d,e)).catch((function(){})),f.label=7;case 7:return[2,(h=nt({client:o,customRoleArn:s,logins:u,identityId:e}))()]}}))}))};return function(){return h().catch((function(e){return Object(f.__awaiter)(t,void 0,void 0,(function(){return Object(f.__generator)(this,(function(t){throw d&&Promise.resolve(i.removeItem(d)).catch((function(){})),e}))}))}))}}var at=n(147),ut=n(38),ct=n(18),ft=n(24),lt=n(11),dt=n(39),ht=n(17),pt=n(40),vt=n(41),gt=n(15),mt="cognito-identity.{region}.amazonaws.com",bt=new Set(["ap-east-1","ap-northeast-1","ap-northeast-2","ap-south-1","ap-southeast-1","ap-southeast-2","ca-central-1","eu-central-1","eu-north-1","eu-west-1","eu-west-2","eu-west-3","me-south-1","sa-east-1","us-east-1","us-east-2","us-west-1","us-west-2"]),yt=new Set(["cn-north-1","cn-northwest-1"]),wt=new Set(["us-iso-east-1"]),_t=new Set(["us-isob-east-1"]),St=new Set(["us-gov-east-1","us-gov-west-1"]),Et=h(h({},{apiVersion:"2014-06-30",disableHostPrefix:!1,logger:{},regionInfoProvider:function(e,t){var n=void 0;switch(e){case"ap-northeast-1":n={hostname:"cognito-identity.ap-northeast-1.amazonaws.com",partition:"aws"};break;case"ap-northeast-2":n={hostname:"cognito-identity.ap-northeast-2.amazonaws.com",partition:"aws"};break;case"ap-south-1":n={hostname:"cognito-identity.ap-south-1.amazonaws.com",partition:"aws"};break;case"ap-southeast-1":n={hostname:"cognito-identity.ap-southeast-1.amazonaws.com",partition:"aws"};break;case"ap-southeast-2":n={hostname:"cognito-identity.ap-southeast-2.amazonaws.com",partition:"aws"};break;case"ca-central-1":n={hostname:"cognito-identity.ca-central-1.amazonaws.com",partition:"aws"};break;case"cn-north-1":n={hostname:"cognito-identity.cn-north-1.amazonaws.com.cn",partition:"aws-cn"};break;case"eu-central-1":n={hostname:"cognito-identity.eu-central-1.amazonaws.com",partition:"aws"};break;case"eu-west-1":n={hostname:"cognito-identity.eu-west-1.amazonaws.com",partition:"aws"};break;case"eu-west-2":n={hostname:"cognito-identity.eu-west-2.amazonaws.com",partition:"aws"};break;case"us-east-1":n={hostname:"cognito-identity.us-east-1.amazonaws.com",partition:"aws"};break;case"us-east-2":n={hostname:"cognito-identity.us-east-2.amazonaws.com",partition:"aws"};break;case"us-west-2":n={hostname:"cognito-identity.us-west-2.amazonaws.com",partition:"aws"};break;default:bt.has(e)&&(n={hostname:mt.replace("{region}",e),partition:"aws"}),yt.has(e)&&(n={hostname:"cognito-identity.{region}.amazonaws.com.cn".replace("{region}",e),partition:"aws-cn"}),wt.has(e)&&(n={hostname:"cognito-identity.{region}.c2s.ic.gov".replace("{region}",e),partition:"aws-iso"}),_t.has(e)&&(n={hostname:"cognito-identity.{region}.sc2s.sgov.gov".replace("{region}",e),partition:"aws-iso-b"}),St.has(e)&&(n={hostname:"cognito-identity.{region}.amazonaws.com".replace("{region}",e),partition:"aws-us-gov"}),void 0===n&&(n={hostname:mt.replace("{region}",e),partition:"aws"})}return Promise.resolve(n)},signingName:"cognito-identity"}),{runtime:"browser",base64Decoder:ht.a,base64Encoder:ht.b,bodyLengthChecker:pt.a,credentialDefaultProvider:function(){},defaultUserAgent:Object(vt.a)(at.name,at.version),maxAttempts:lt.a,region:Object(ft.a)("Region is missing"),requestHandler:new ct.a,sha256:ut.Sha256,streamCollector:ct.b,urlParser:dt.a,utf8Decoder:gt.a,utf8Encoder:gt.b}),Mt=n(22),At=n(37),It=n(21),kt=n(43),Ot=n(25),xt=n(23),Ct=function(e){function t(t){var n=this,r=h(h({},Et),t),i=Object(Mt.b)(r),o=Object(Mt.a)(i),s=Object(Ot.b)(o),a=Object(lt.c)(s),u=Object(xt.b)(a),c=Object(It.b)(u);return(n=e.call(this,c)||this).config=c,n.middlewareStack.use(Object(lt.b)(n.config)),n.middlewareStack.use(Object(xt.a)(n.config)),n.middlewareStack.use(Object(At.a)(n.config)),n.middlewareStack.use(Object(It.a)(n.config)),n.middlewareStack.use(Object(kt.a)(n.config)),n}return d(t,e),t.prototype.destroy=function(){e.prototype.destroy.call(this)},t}(Xe.a),Tt=function(){return(Tt=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1](new Date).getTime()?(Rt.debug("token not expired"),this._setCredentialsFromFederation({provider:t,token:r,user:n,identity_id:i,expires_at:o})):this._refreshHandlers[t]&&"function"==typeof this._refreshHandlers[t]?(Rt.debug("getting refreshed jwt token from federation provider"),this._providerRefreshWithRetry({refreshHandler:this._refreshHandlers[t],provider:t,user:n})):(Rt.debug("no refresh handler for provider:",t),this.clear(),Promise.reject("no refresh handler for provider"))},e.prototype._providerRefreshWithRetry=function(e){var t=this,n=e.refreshHandler,r=e.provider,i=e.user;return Object(a.b)(n,[],1e4).then((function(e){return Rt.debug("refresh federated token sucessfully",e),t._setCredentialsFromFederation({provider:r,token:e.token,user:i,identity_id:e.identity_id,expires_at:e.expires_at})})).catch((function(e){return"string"==typeof e&&0===e.toLowerCase().lastIndexOf("network error",e.length)||t.clear(),Rt.debug("refresh federated token failed",e),Promise.reject("refreshing federation token failed: "+e)}))},e.prototype._isExpired=function(e){if(!e)return Rt.debug("no credentials for expiration check"),!0;Rt.debug("are these credentials expired?",e);var t=Date.now();return e.expiration.getTime()<=t},e.prototype._isPastTTL=function(){return this._nextCredentialsRefresh<=Date.now()},e.prototype._setCredentialsForGuest=function(){return Pt(this,void 0,void 0,(function(){var e,t,n,r,i,o,s,a=this;return Nt(this,(function(c){switch(c.label){case 0:if(Rt.debug("setting credentials for guest"),e=this._config,t=e.identityPoolId,n=e.region,e.mandatorySignIn)return[2,Promise.reject("cannot get guest credentials when mandatory signin enabled")];if(!t)return Rt.debug("No Cognito Identity pool provided for unauthenticated access"),[2,Promise.reject("No Cognito Identity pool provided for unauthenticated access")];if(!n)return Rt.debug("region is not configured for getting the credentials"),[2,Promise.reject("region is not configured for getting the credentials")];r=void 0,c.label=1;case 1:return c.trys.push([1,3,,4]),[4,this._storageSync];case 2:return c.sent(),r=this._storage.getItem("CognitoIdentityId-"+t),this._identityId=r,[3,4];case 3:return i=c.sent(),Rt.debug("Failed to get the cached identityId",i),[3,4];case 4:return o=new Ct({region:n,customUserAgent:Object(u.b)()}),s=void 0,s=r?nt({identityId:r,client:o})():function(){return Pt(a,void 0,void 0,(function(){var e;return Nt(this,(function(n){switch(n.label){case 0:return[4,o.send(new rt({IdentityPoolId:t}))];case 1:return e=n.sent().IdentityId,this._identityId=e,[2,nt({client:o,identityId:e})()]}}))}))}().catch((function(e){return Pt(a,void 0,void 0,(function(){return Nt(this,(function(t){throw e}))}))})),[2,this._loadCredentials(s,"guest",!1,null).then((function(e){return e})).catch((function(e){return Pt(a,void 0,void 0,(function(){var n=this;return Nt(this,(function(i){return"ResourceNotFoundException"===e.name&&e.message==="Identity '"+r+"' not found."?(Rt.debug("Failed to load guest credentials"),this._storage.removeItem("CognitoIdentityId-"+t),s=function(){return Pt(n,void 0,void 0,(function(){var e;return Nt(this,(function(n){switch(n.label){case 0:return[4,o.send(new rt({IdentityPoolId:t}))];case 1:return e=n.sent().IdentityId,this._identityId=e,[2,nt({client:o,identityId:e})()]}}))}))}().catch((function(e){return Pt(n,void 0,void 0,(function(){return Nt(this,(function(t){throw e}))}))})),[2,this._loadCredentials(s,"guest",!1,null)]):[2,e]}))}))}))]}}))}))},e.prototype._setCredentialsFromFederation=function(e){var t=e.provider,n=e.token,r=e.identity_id,i={google:"accounts.google.com",facebook:"graph.facebook.com",amazon:"www.amazon.com",developer:"cognito-identity.amazonaws.com"}[t]||t;if(!i)return Promise.reject("You must specify a federated provider");var o={};o[i]=n;var s=this._config,a=s.identityPoolId,c=s.region;if(!a)return Rt.debug("No Cognito Federated Identity pool provided"),Promise.reject("No Cognito Federated Identity pool provided");if(!c)return Rt.debug("region is not configured for getting the credentials"),Promise.reject("region is not configured for getting the credentials");var f=new Ct({region:c,customUserAgent:Object(u.b)()}),l=void 0;r?l=nt({identityId:r,logins:o,client:f})():l=st({logins:o,identityPoolId:a,client:f})();return this._loadCredentials(l,"federated",!0,e)},e.prototype._setCredentialsFromSession=function(e){var t=this;Rt.debug("set credentials from session");var n=e.getIdToken().getJwtToken(),r=this._config,i=r.region,o=r.userPoolId,s=r.identityPoolId;if(!s)return Rt.debug("No Cognito Federated Identity pool provided"),Promise.reject("No Cognito Federated Identity pool provided");if(!i)return Rt.debug("region is not configured for getting the credentials"),Promise.reject("region is not configured for getting the credentials");var a={};a["cognito-idp."+i+".amazonaws.com/"+o]=n;var c=new Ct({region:i,customUserAgent:Object(u.b)()}),f=Pt(t,void 0,void 0,(function(){var e;return Nt(this,(function(t){switch(t.label){case 0:return[4,c.send(new rt({IdentityPoolId:s,Logins:a}))];case 1:return e=t.sent().IdentityId,this._identityId=e,[2,nt({client:c,logins:a,identityId:e})()]}}))})).catch((function(e){return Pt(t,void 0,void 0,(function(){return Nt(this,(function(t){throw e}))}))}));return this._loadCredentials(f,"userPool",!0,null)},e.prototype._loadCredentials=function(e,t,n,r){var i=this,o=this,s=this._config.identityPoolId;return new Promise((function(a,u){e.then((function(e){return Pt(i,void 0,void 0,(function(){var i,u,c,f,l,d;return Nt(this,(function(h){switch(h.label){case 0:if(Rt.debug("Load credentials successfully",e),this._identityId&&!e.identityId&&(e.identityId=this._identityId),o._credentials=e,o._credentials.authenticated=n,o._credentials_source=t,o._nextCredentialsRefresh=(new Date).getTime()+3e6,"federated"===t){i=Object.assign({id:this._credentials.identityId},r.user),u=r.provider,c=r.token,f=r.expires_at,l=r.identity_id;try{this._storage.setItem("aws-amplify-federatedInfo",JSON.stringify({provider:u,token:c,user:i,expires_at:f,identity_id:l}))}catch(e){Rt.debug("Failed to put federated info into auth storage",e)}}if("guest"!==t)return[3,4];h.label=1;case 1:return h.trys.push([1,3,,4]),[4,this._storageSync];case 2:return h.sent(),this._storage.setItem("CognitoIdentityId-"+s,e.identityId),[3,4];case 3:return d=h.sent(),Rt.debug("Failed to cache identityId",d),[3,4];case 4:return a(o._credentials),[2]}}))}))})).catch((function(t){if(t)return Rt.debug("Failed to load credentials",e),Rt.debug("Error loading credentials",t),void u(t)}))}))},e.prototype.set=function(e,t){return"session"===t?this._setCredentialsFromSession(e):"federation"===t?this._setCredentialsFromFederation(e):"guest"===t?this._setCredentialsForGuest():(Rt.debug("no source specified for setting credentials"),Promise.reject("invalid source"))},e.prototype.clear=function(){return Pt(this,void 0,void 0,(function(){return Nt(this,(function(e){return this._credentials=null,this._credentials_source=null,Rt.debug("removing aws-amplify-federatedInfo from storage"),this._storage.removeItem("aws-amplify-federatedInfo"),[2]}))}))},e.prototype.shear=function(e){return{accessKeyId:e.accessKeyId,sessionToken:e.sessionToken,secretAccessKey:e.secretAccessKey,identityId:e.identityId,authenticated:e.authenticated}},e}())(null);c.a.register(Lt)},function(e,t,n){var r,i,o;e.exports=(o=n(32),i=(r=o).lib.WordArray,r.enc.Base64={stringify:function(e){var t=e.words,n=e.sigBytes,r=this._map;e.clamp();for(var i=[],o=0;o>>2]>>>24-o%4*8&255)<<16|(t[o+1>>>2]>>>24-(o+1)%4*8&255)<<8|t[o+2>>>2]>>>24-(o+2)%4*8&255,a=0;a<4&&o+.75*a>>6*(3-a)&63));var u=r.charAt(64);if(u)for(;i.length%4;)i.push(u);return i.join("")},parse:function(e){var t=e.length,n=this._map,r=this._reverseMap;if(!r){r=this._reverseMap=[];for(var o=0;o>>6-s%4*2;r[o>>>2]|=(a|u)<<24-o%4*8,o++}return i.create(r,o)}(e,t,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},o.enc.Base64)},function(e,t,n){"use strict";function r(e,t){for(var n,r=/\r\n|[\n\r]/g,i=1,o=t+1;(n=r.exec(e.body))&&n.index>>24]^f[p>>>16&255]^l[v>>>8&255]^d[255&g]^t[m++],s=c[p>>>24]^f[v>>>16&255]^l[g>>>8&255]^d[255&h]^t[m++],a=c[v>>>24]^f[g>>>16&255]^l[h>>>8&255]^d[255&p]^t[m++],u=c[g>>>24]^f[h>>>16&255]^l[p>>>8&255]^d[255&v]^t[m++],h=o,p=s,v=a,g=u;return o=(r[h>>>24]<<24|r[p>>>16&255]<<16|r[v>>>8&255]<<8|r[255&g])^t[m++],s=(r[p>>>24]<<24|r[v>>>16&255]<<16|r[g>>>8&255]<<8|r[255&h])^t[m++],a=(r[v>>>24]<<24|r[g>>>16&255]<<16|r[h>>>8&255]<<8|r[255&p])^t[m++],u=(r[g>>>24]<<24|r[h>>>16&255]<<16|r[p>>>8&255]<<8|r[255&v])^t[m++],[o>>>=0,s>>>=0,a>>>=0,u>>>=0]}var a=[0,1,2,4,8,16,32,64,128,27,54],u=function(){for(var e=new Array(256),t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;for(var n=[],r=[],i=[[],[],[],[]],o=[[],[],[],[]],s=0,a=0,u=0;u<256;++u){var c=a^a<<1^a<<2^a<<3^a<<4;c=c>>>8^255&c^99,n[s]=c,r[c]=s;var f=e[s],l=e[f],d=e[l],h=257*e[c]^16843008*c;i[0][s]=h<<24|h>>>8,i[1][s]=h<<16|h>>>16,i[2][s]=h<<8|h>>>24,i[3][s]=h,h=16843009*d^65537*l^257*f^16843008*s,o[0][c]=h<<24|h>>>8,o[1][c]=h<<16|h>>>16,o[2][c]=h<<8|h>>>24,o[3][c]=h,0===s?s=a=1:(s=f^e[e[e[d^f]]],a^=e[e[a]])}return{SBOX:n,INV_SBOX:r,SUB_MIX:i,INV_SUB_MIX:o}}();function c(e){this._key=i(e),this._reset()}c.blockSize=16,c.keySize=32,c.prototype.blockSize=c.blockSize,c.prototype.keySize=c.keySize,c.prototype._reset=function(){for(var e=this._key,t=e.length,n=t+6,r=4*(n+1),i=[],o=0;o>>24,s=u.SBOX[s>>>24]<<24|u.SBOX[s>>>16&255]<<16|u.SBOX[s>>>8&255]<<8|u.SBOX[255&s],s^=a[o/t|0]<<24):t>6&&o%t==4&&(s=u.SBOX[s>>>24]<<24|u.SBOX[s>>>16&255]<<16|u.SBOX[s>>>8&255]<<8|u.SBOX[255&s]),i[o]=i[o-t]^s}for(var c=[],f=0;f>>24]]^u.INV_SUB_MIX[1][u.SBOX[d>>>16&255]]^u.INV_SUB_MIX[2][u.SBOX[d>>>8&255]]^u.INV_SUB_MIX[3][u.SBOX[255&d]]}this._nRounds=n,this._keySchedule=i,this._invKeySchedule=c},c.prototype.encryptBlockRaw=function(e){return s(e=i(e),this._keySchedule,u.SUB_MIX,u.SBOX,this._nRounds)},c.prototype.encryptBlock=function(e){var t=this.encryptBlockRaw(e),n=r.allocUnsafe(16);return n.writeUInt32BE(t[0],0),n.writeUInt32BE(t[1],4),n.writeUInt32BE(t[2],8),n.writeUInt32BE(t[3],12),n},c.prototype.decryptBlock=function(e){var t=(e=i(e))[1];e[1]=e[3],e[3]=t;var n=s(e,this._invKeySchedule,u.INV_SUB_MIX,u.INV_SBOX,this._nRounds),o=r.allocUnsafe(16);return o.writeUInt32BE(n[0],0),o.writeUInt32BE(n[3],4),o.writeUInt32BE(n[2],8),o.writeUInt32BE(n[1],12),o},c.prototype.scrub=function(){o(this._keySchedule),o(this._invKeySchedule),o(this._key)},e.exports.AES=c},function(e,t,n){var r=n(8).Buffer,i=n(113);e.exports=function(e,t,n,o){if(r.isBuffer(e)||(e=r.from(e,"binary")),t&&(r.isBuffer(t)||(t=r.from(t,"binary")),8!==t.length))throw new RangeError("salt should be Buffer with 8 byte length");for(var s=n/8,a=r.alloc(s),u=r.alloc(o||0),c=r.alloc(0);s>0||o>0;){var f=new i;f.update(c),f.update(e),t&&f.update(t),c=f.digest();var l=0;if(s>0){var d=a.length-s;l=Math.min(s,c.length),c.copy(a,d,0,l),s-=l}if(l0){var h=u.length-o,p=Math.min(o,c.length-l);c.copy(u,h,l,l+p),o-=p}}return c.fill(0),{key:a,iv:u}}},function(e,t,n){"use strict";var r=n(29),i=n(47),o=i.getNAF,s=i.getJSF,a=i.assert;function u(e,t){this.type=e,this.p=new r(t.p,16),this.red=t.prime?r.red(t.prime):r.mont(this.p),this.zero=new r(0).toRed(this.red),this.one=new r(1).toRed(this.red),this.two=new r(2).toRed(this.red),this.n=t.n&&new r(t.n,16),this.g=t.g&&this.pointFromJSON(t.g,t.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n?this.n.bitLength():0;var n=this.n&&this.p.div(this.n);!n||n.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}function c(e,t){this.curve=e,this.type=t,this.precomputed=null}e.exports=u,u.prototype.point=function(){throw new Error("Not implemented")},u.prototype.validate=function(){throw new Error("Not implemented")},u.prototype._fixedNafMul=function(e,t){a(e.precomputed);var n=e._getDoubles(),r=o(t,1,this._bitLength),i=(1<=s;f--)u=(u<<1)+r[f];c.push(u)}for(var l=this.jpoint(null,null,null),d=this.jpoint(null,null,null),h=i;h>0;h--){for(s=0;s=0;c--){for(var f=0;c>=0&&0===s[c];c--)f++;if(c>=0&&f++,u=u.dblp(f),c<0)break;var l=s[c];a(0!==l),u="affine"===e.type?l>0?u.mixedAdd(i[l-1>>1]):u.mixedAdd(i[-l-1>>1].neg()):l>0?u.add(i[l-1>>1]):u.add(i[-l-1>>1].neg())}return"affine"===e.type?u.toP():u},u.prototype._wnafMulAdd=function(e,t,n,r,i){var a,u,c,f=this._wnafT1,l=this._wnafT2,d=this._wnafT3,h=0;for(a=0;a=1;a-=2){var v=a-1,g=a;if(1===f[v]&&1===f[g]){var m=[t[v],null,null,t[g]];0===t[v].y.cmp(t[g].y)?(m[1]=t[v].add(t[g]),m[2]=t[v].toJ().mixedAdd(t[g].neg())):0===t[v].y.cmp(t[g].y.redNeg())?(m[1]=t[v].toJ().mixedAdd(t[g]),m[2]=t[v].add(t[g].neg())):(m[1]=t[v].toJ().mixedAdd(t[g]),m[2]=t[v].toJ().mixedAdd(t[g].neg()));var b=[-3,-1,-5,-7,0,7,5,1,3],y=s(n[v],n[g]);for(h=Math.max(y[0].length,h),d[v]=new Array(h),d[g]=new Array(h),u=0;u=0;a--){for(var M=0;a>=0;){var A=!0;for(u=0;u=0&&M++,S=S.dblp(M),a<0)break;for(u=0;u0?c=l[u][I-1>>1]:I<0&&(c=l[u][-I-1>>1].neg()),S="affine"===c.type?S.mixedAdd(c):S.add(c))}}for(a=0;a=Math.ceil((e.bitLength()+1)/t.step)},c.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var n=[this],r=this,i=0;i))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)".replace(/NAME/g,r.nameRegexp);!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);const s={attributeNamePrefix:"@_",attrNodeName:!1,textNodeName:"#text",ignoreAttributes:!0,ignoreNameSpace:!1,allowBooleanAttributes:!1,parseNodeValue:!0,parseAttributeValue:!1,arrayMode:!1,trimValues:!0,cdataTagName:!1,cdataPositionChar:"\\c",tagValueProcessor:function(e,t){return e},attrValueProcessor:function(e,t){return e},stopNodes:[]};t.defaultOptions=s;const a=["attributeNamePrefix","attrNodeName","textNodeName","ignoreAttributes","ignoreNameSpace","allowBooleanAttributes","parseNodeValue","parseAttributeValue","arrayMode","trimValues","cdataTagName","cdataPositionChar","tagValueProcessor","attrValueProcessor","parseTrueNumberOnly","stopNodes"];function u(e,t,n){return t&&(n.trimValues&&(t=t.trim()),t=f(t=n.tagValueProcessor(t,e),n.parseNodeValue,n.parseTrueNumberOnly)),t}function c(e,t){if(t.ignoreNameSpace){const t=e.split(":"),n="/"===e.charAt(0)?"/":"";if("xmlns"===t[0])return"";2===t.length&&(e=n+t[1])}return e}function f(e,t,n){if(t&&"string"==typeof e){let t;return""===e.trim()||isNaN(e)?t="true"===e||"false"!==e&&e:(-1!==e.indexOf("0x")?t=Number.parseInt(e,16):-1!==e.indexOf(".")?(t=Number.parseFloat(e),e=e.replace(/\.?0+$/,"")):t=Number.parseInt(e,10),n&&(t=String(t)===e?t:e)),t}return r.isExist(e)?e:""}t.props=a;const l=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])(.*?)\\3)?","g");function d(e,t){if(!t.ignoreAttributes&&"string"==typeof e){e=e.replace(/\r?\n/g," ");const n=r.getAllMatches(e,l),i=n.length,o={};for(let e=0;e"===t)return{data:r,index:i};"\t"===t&&(t=" ")}r+=t}}function p(e,t,n,r){const i=e.indexOf(t,n);if(-1===i)throw new Error(r);return i+t.length-1}t.getTraversalObj=function(e,t){e=e.replace(/\r\n?/g,"\n"),t=i(t,s,a);const n=new o("!xml");let c=n,f="";for(let n=0;n",n,"Closing Tag is not closed.");let o=e.substring(n+2,i).trim();if(t.ignoreNameSpace){const e=o.indexOf(":");-1!==e&&(o=o.substr(e+1))}c&&(c.val?c.val=r.getValue(c.val)+""+u(o,f,t):c.val=u(o,f,t)),t.stopNodes.length&&t.stopNodes.includes(c.tagname)&&(c.child=[],null==c.attrsMap&&(c.attrsMap={}),c.val=e.substr(c.startIndex+1,n-c.startIndex-1)),c=c.parent,f="",n=i}else if("?"===e[n+1])n=p(e,"?>",n,"Pi Tag is not closed.");else if("!--"===e.substr(n+1,3))n=p(e,"--\x3e",n,"Comment is not closed.");else if("!D"===e.substr(n+1,2)){const t=p(e,">",n,"DOCTYPE is not closed.");n=e.substring(n,t).indexOf("[")>=0?e.indexOf("]>",n)+1:t}else if("!["===e.substr(n+1,2)){const i=p(e,"]]>",n,"CDATA is not closed.")-2,s=e.substring(n+9,i);if(f&&(c.val=r.getValue(c.val)+""+u(c.tagname,f,t),f=""),t.cdataTagName){const e=new o(t.cdataTagName,c,s);c.addChild(e),c.val=r.getValue(c.val)+t.cdataPositionChar,s&&(e.val=s)}else c.val=(c.val||"")+(s||"");n=i+2}else{const i=h(e,n+1);let s=i.data;const a=i.index,l=s.indexOf(" ");let p=s;if(-1!==l&&(p=s.substr(0,l).replace(/\s\s*$/,""),s=s.substr(l+1)),t.ignoreNameSpace){const e=p.indexOf(":");-1!==e&&(p=p.substr(e+1))}if(c&&f&&"!xml"!==c.tagname&&(c.val=r.getValue(c.val)+""+u(c.tagname,f,t)),s.length>0&&s.lastIndexOf("/")===s.length-1){"/"===p[p.length-1]?(p=p.substr(0,p.length-1),s=p):s=s.substr(0,s.length-1);const e=new o(p,c,"");p!==s&&(e.attrsMap=d(s,t)),c.addChild(e)}else{const e=new o(p,c);t.stopNodes.length&&t.stopNodes.includes(e.tagname)&&(e.startIndex=a),p!==s&&(e.attrsMap=d(s,t)),c.addChild(e),c=e}f="",n=a}else f+=e[n]}return n}},function(e,t,n){"use strict";n.d(t,"a",(function(){return i})),n.d(t,"b",(function(){return o})),n.d(t,"c",(function(){return s}));var r="undefined"!=typeof Symbol&&"function"==typeof Symbol.for,i=r?Symbol.for("INTERNAL_AWS_APPSYNC_PUBSUB_PROVIDER"):"@@INTERNAL_AWS_APPSYNC_PUBSUB_PROVIDER",o=r?Symbol.for("INTERNAL_AWS_APPSYNC_REALTIME_PUBSUB_PROVIDER"):"@@INTERNAL_AWS_APPSYNC_REALTIME_PUBSUB_PROVIDER",s="x-amz-user-agent"},function(e,t,n){"use strict";n.d(t,"a",(function(){return _}));var r=n(44),i=n(148),o=n(28),s=n(16),a=n(77);function u(e){return(u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var c=function(){return(c=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=r;if("+"!==s&&s!==a)return!1}return r===i.length})(r,e)&&n.push(t)}));var r=JSON.parse(t);"object"===h(r)&&(r[A]=e),n.forEach((function(e){e.forEach((function(e){return e.next(r)}))}))}catch(e){w.warn("Error handling message",e,t)}},t.prototype.subscribe=function(e,t){var n=this;void 0===t&&(t={});var i=[].concat(e);return w.debug("Subscribing to topic(s)",i.join(",")),new r.a((function(e){var r;i.forEach((function(t){var r=n._topicObservers.get(t);r||(r=new Set,n._topicObservers.set(t,r)),r.add(e)}));var o=t.clientId,s=void 0===o?n.clientId:o,a=n._clientIdObservers.get(s);return a||(a=new Set),a.add(e),n._clientIdObservers.set(s,a),m(n,void 0,void 0,(function(){var n,o,a,u;return b(this,(function(c){switch(c.label){case 0:return void 0!==(n=t.url)?[3,2]:[4,this.endpoint];case 1:return a=c.sent(),[3,3];case 2:a=n,c.label=3;case 3:o=a,c.label=4;case 4:return c.trys.push([4,6,,7]),[4,this.connect(s,{url:o})];case 5:return r=c.sent(),i.forEach((function(e){r.subscribe(e)})),[3,7];case 6:return u=c.sent(),e.error(u),[3,7];case 7:return[2]}}))})),function(){return w.debug("Unsubscribing from topic(s)",i.join(",")),r&&(n._clientIdObservers.get(s).delete(e),0===n._clientIdObservers.get(s).size&&(n.disconnect(s),n._clientIdObservers.delete(s)),i.forEach((function(t){var i=n._topicObservers.get(t)||new Set;i.delete(e),0===i.size&&(n._topicObservers.delete(t),r.isConnected()&&r.unsubscribe(t))}))),null}}))},t}(d),k=function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),O=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))},x=function(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},P=function(){for(var e=[],t=0;t-1}));if(r){var i=r.client,o=r.url;e[i]||(e[i]={url:o,topics:new Set}),e[i].topics.add(t)}return e}),{})),[4,Promise.all(a.map((function(e){var t=T(e,2),n=t[0],i=t[1],o=i.url,s=i.topics;return O(u,void 0,void 0,(function(){var e,t,i=this;return x(this,(function(a){switch(a.label){case 0:e=null,a.label=1;case 1:return a.trys.push([1,3,,4]),[4,this.connect(n,{clientId:n,url:o})];case 2:return e=a.sent(),[3,4];case 3:return t=a.sent(),r.error({message:"Failed to connect",error:t}),r.complete(),[2,void 0];case 4:return s.forEach((function(t){e.isConnected()&&(e.subscribe(t),i._topicClient.set(t,e))})),[2,e]}}))}))})))];case 1:return c.sent(),[2]}}))})),function(){N.debug("Unsubscribing from topic(s)",i.join(",")),i.forEach((function(e){var t=n._topicClient.get(e);t&&t.isConnected()&&(t.unsubscribe(e),n._topicClient.delete(e),Array.from(n._topicClient.values()).some((function(e){return e===t}))||n.disconnect(t.clientId)),n._topicObservers.delete(e)}))}}));return r.a.from(i).map((function(e){var t=n.getTopicForValue(e),r=n._topicAlias.get(t);return e.data=Object.entries(e.data).reduce((function(e,t){var n=T(t,2),i=n[0],o=n[1];return e[r||i]=o,e}),{}),e}))},t}(I),L=n(91),j=n(16),D=n(6),U=n(88),B=n(5),F=n(514),z=n(89),q=n(104),K=n(26),H=n(42),V=n(34),G=function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),W=function(){return(W=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},Z=new o.a("AWSAppSyncRealTimeProvider"),X="undefined"!=typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("amplify_default"):"@@amplify_default",Q=[400,401,403];!function(e){e.GQL_CONNECTION_INIT="connection_init",e.GQL_CONNECTION_ERROR="connection_error",e.GQL_CONNECTION_ACK="connection_ack",e.GQL_START="start",e.GQL_START_ACK="start_ack",e.GQL_DATA="data",e.GQL_CONNECTION_KEEP_ALIVE="ka",e.GQL_STOP="stop",e.GQL_COMPLETE="complete",e.GQL_ERROR="error"}(_||(_={})),function(e){e[e.PENDING=0]="PENDING",e[e.CONNECTED=1]="CONNECTED",e[e.FAILED=2]="FAILED"}(S||(S={})),function(e){e[e.CLOSED=0]="CLOSED",e[e.READY=1]="READY",e[e.CONNECTING=2]="CONNECTING"}(E||(E={}));var ee={accept:"application/json, text/javascript","content-encoding":"amz-1.0","content-type":"application/json; charset=UTF-8"},te=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.socketStatus=E.CLOSED,t.keepAliveTimeout=3e5,t.subscriptionObserverMap=new Map,t.promiseArray=[],t}return G(t,e),t.prototype.getProviderName=function(){return"AWSAppSyncRealTimeProvider"},t.prototype.newClient=function(){throw new Error("Not used here")},t.prototype.publish=function(e,t,n){return $(this,void 0,void 0,(function(){return Y(this,(function(e){throw new Error("Operation not supported")}))}))},t.prototype.subscribe=function(e,t){var n=this,i=t.appSyncGraphqlEndpoint;return new r.a((function(e){if(i){var r=Object(c.v4)();return n._startSubscriptionWithAWSAppSyncRealTime({options:t,observer:e,subscriptionId:r}),function(){return $(n,void 0,void 0,(function(){var e,t;return Y(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,3,4]),[4,this._waitForSubscriptionToBeConnected(r)];case 1:if(n.sent(),!(e=(this.subscriptionObserverMap.get(r)||{}).subscriptionState))return[2];if(e!==S.CONNECTED)throw new Error("Subscription never connected");return this._sendUnsubscriptionMessage(r),[3,4];case 2:return t=n.sent(),Z.debug("Error while unsubscribing "+t),[3,4];case 3:return this._removeSubscriptionObserver(r),[7];case 4:return[2]}}))}))}}e.error({errors:[W({},new L.a("Subscribe only available for AWS AppSync endpoint"))]}),e.complete()}))},Object.defineProperty(t.prototype,"isSSLEnabled",{get:function(){return!this.options.aws_appsync_dangerously_connect_to_http_endpoint_for_testing},enumerable:!0,configurable:!0}),t.prototype._startSubscriptionWithAWSAppSyncRealTime=function(e){var t=e.options,n=e.observer,r=e.subscriptionId;return $(this,void 0,void 0,(function(){var e,i,o,a,u,c,f,l,d,h,p,v,g,m,b,y,w,E,M,A,I,k,O,x,C,T,P=this;return Y(this,(function(N){switch(N.label){case 0:return e=t.appSyncGraphqlEndpoint,i=t.authenticationType,o=t.query,a=t.variables,u=t.apiKey,c=t.region,f=t.graphql_headers,l=void 0===f?function(){return{}}:f,d=t.additionalHeaders,h=void 0===d?{}:d,p=S.PENDING,v={query:o,variables:a},this.subscriptionObserverMap.set(r,{observer:n,query:o,variables:a,subscriptionState:p,startAckTimeoutId:null}),g=JSON.stringify(v),b=[{}],[4,this._awsRealTimeHeaderBasedAuth({apiKey:u,appSyncGraphqlEndpoint:e,authenticationType:i,payload:g,canonicalUri:"",region:c})];case 1:return y=[W.apply(void 0,b.concat([N.sent()]))],[4,l()];case 2:m=W.apply(void 0,[W.apply(void 0,[W.apply(void 0,y.concat([N.sent()])),h]),(T={},T[s.c]=B.a.userAgent,T)]),w={id:r,payload:{data:g,extensions:{authorization:W({},m)}},type:_.GQL_START},E=JSON.stringify(w),N.label=3;case 3:return N.trys.push([3,5,,6]),[4,this._initializeWebSocketConnection({apiKey:u,appSyncGraphqlEndpoint:e,authenticationType:i,region:c})];case 4:return N.sent(),[3,6];case 5:return M=N.sent(),Z.debug({err:M}),A=M.message,I=void 0===A?"":A,n.error({errors:[W({},new L.a("Connection failed: "+I))]}),n.complete(),"function"==typeof(k=(this.subscriptionObserverMap.get(r)||{}).subscriptionFailedCallback)&&k(),[2];case 6:return O=this.subscriptionObserverMap.get(r),x=O.subscriptionFailedCallback,C=O.subscriptionReadyCallback,this.subscriptionObserverMap.set(r,{observer:n,subscriptionState:p,variables:a,query:o,subscriptionReadyCallback:C,subscriptionFailedCallback:x,startAckTimeoutId:setTimeout((function(){P._timeoutStartSubscriptionAck.call(P,r)}),15e3)}),this.awsRealTimeSocket&&this.awsRealTimeSocket.send(E),[2]}}))}))},t.prototype._waitForSubscriptionToBeConnected=function(e){return $(this,void 0,void 0,(function(){var t=this;return Y(this,(function(n){return this.subscriptionObserverMap.get(e).subscriptionState===S.PENDING?[2,new Promise((function(n,r){var i=t.subscriptionObserverMap.get(e),o=i.observer,s=i.subscriptionState,a=i.variables,u=i.query;t.subscriptionObserverMap.set(e,{observer:o,subscriptionState:s,variables:a,query:u,subscriptionReadyCallback:n,subscriptionFailedCallback:r})}))]:[2]}))}))},t.prototype._sendUnsubscriptionMessage=function(e){try{if(this.awsRealTimeSocket&&this.awsRealTimeSocket.readyState===WebSocket.OPEN&&this.socketStatus===E.READY){var t={id:e,type:_.GQL_STOP},n=JSON.stringify(t);this.awsRealTimeSocket.send(n)}}catch(e){Z.debug({err:e})}},t.prototype._removeSubscriptionObserver=function(e){this.subscriptionObserverMap.delete(e),setTimeout(this._closeSocketIfRequired.bind(this),1e3)},t.prototype._closeSocketIfRequired=function(){if(!(this.subscriptionObserverMap.size>0))if(this.awsRealTimeSocket)if(this.awsRealTimeSocket.bufferedAmount>0)setTimeout(this._closeSocketIfRequired.bind(this),1e3);else{Z.debug("closing WebSocket..."),clearTimeout(this.keepAliveTimeoutId);var e=this.awsRealTimeSocket;e.onclose=void 0,e.onerror=void 0,e.close(1e3),this.awsRealTimeSocket=null,this.socketStatus=E.CLOSED}else this.socketStatus=E.CLOSED},t.prototype._handleIncomingSubscriptionMessage=function(e){Z.debug("subscription message from AWS AppSync RealTime: "+e.data);var t=JSON.parse(e.data),n=t.id,r=void 0===n?"":n,i=t.payload,o=t.type,s=this.subscriptionObserverMap.get(r)||{},a=s.observer,u=void 0===a?null:a,c=s.query,f=void 0===c?"":c,l=s.variables,d=void 0===l?{}:l,h=s.startAckTimeoutId,p=s.subscriptionReadyCallback,v=s.subscriptionFailedCallback;if(Z.debug({id:r,observer:u,query:f,variables:d}),o===_.GQL_DATA&&i&&i.data)u?u.next(i):Z.debug("observer not found for id: "+r);else if(o!==_.GQL_START_ACK){if(o===_.GQL_CONNECTION_KEEP_ALIVE)return clearTimeout(this.keepAliveTimeoutId),void(this.keepAliveTimeoutId=setTimeout(this._errorDisconnect.bind(this,V.a.TIMEOUT_DISCONNECT),this.keepAliveTimeout));if(o===_.GQL_ERROR){g=S.FAILED;this.subscriptionObserverMap.set(r,{observer:u,query:f,variables:d,startAckTimeoutId:h,subscriptionReadyCallback:p,subscriptionFailedCallback:v,subscriptionState:g}),u.error({errors:[W({},new L.a("Connection failed: "+JSON.stringify(i)))]}),clearTimeout(h),u.complete(),"function"==typeof v&&v()}}else{Z.debug("subscription ready for "+JSON.stringify({query:f,variables:d})),"function"==typeof p&&p(),clearTimeout(h),function(e,t,n){U.a.dispatch("api",{event:e,data:t,message:n},"PubSub",X)}(V.a.SUBSCRIPTION_ACK,{query:f,variables:d},"Connection established for subscription");var g=S.CONNECTED;this.subscriptionObserverMap.set(r,{observer:u,query:f,variables:d,startAckTimeoutId:null,subscriptionState:g,subscriptionReadyCallback:p,subscriptionFailedCallback:v})}},t.prototype._errorDisconnect=function(e){Z.debug("Disconnect error: "+e),this.subscriptionObserverMap.forEach((function(t){var n=t.observer;n&&!n.closed&&n.error({errors:[W({},new L.a(e))]})})),this.subscriptionObserverMap.clear(),this.awsRealTimeSocket&&this.awsRealTimeSocket.close(),this.socketStatus=E.CLOSED},t.prototype._timeoutStartSubscriptionAck=function(e){var t=this.subscriptionObserverMap.get(e)||{},n=t.observer,r=t.query,i=t.variables;n&&(this.subscriptionObserverMap.set(e,{observer:n,query:r,variables:i,subscriptionState:S.FAILED}),n&&!n.closed&&(n.error({errors:[W({},new L.a("Subscription timeout "+JSON.stringify({query:r,variables:i})))]}),n.complete()),Z.debug("timeoutStartSubscription",JSON.stringify({query:r,variables:i})))},t.prototype._initializeWebSocketConnection=function(e){var t=this,n=e.appSyncGraphqlEndpoint,r=e.authenticationType,i=e.apiKey,o=e.region;if(this.socketStatus!==E.READY)return new Promise((function(e,s){return $(t,void 0,void 0,(function(){var t,a,u,c,f,l,d,h,p,v;return Y(this,(function(g){switch(g.label){case 0:if(this.promiseArray.push({res:e,rej:s}),this.socketStatus!==E.CLOSED)return[3,5];g.label=1;case 1:return g.trys.push([1,4,,5]),this.socketStatus=E.CONNECTING,t=this.isSSLEnabled?"wss://":"ws://",a=n.replace("https://",t).replace("http://",t).replace("appsync-api","appsync-realtime-api").replace("gogi-beta","grt-beta"),u="{}",l=(f=JSON).stringify,[4,this._awsRealTimeHeaderBasedAuth({authenticationType:r,payload:u,canonicalUri:"/connect",apiKey:i,appSyncGraphqlEndpoint:n,region:o})];case 2:return c=l.apply(f,[g.sent()]),d=D.Buffer.from(c).toString("base64"),h=D.Buffer.from(u).toString("base64"),p=a+"?header="+d+"&payload="+h,[4,this._initializeRetryableHandshake({awsRealTimeUrl:p})];case 3:return g.sent(),this.promiseArray.forEach((function(e){var t=e.res;Z.debug("Notifying connection successful"),t()})),this.socketStatus=E.READY,this.promiseArray=[],[3,5];case 4:return v=g.sent(),this.promiseArray.forEach((function(e){return(0,e.rej)(v)})),this.promiseArray=[],this.awsRealTimeSocket&&this.awsRealTimeSocket.readyState===WebSocket.OPEN&&this.awsRealTimeSocket.close(3001),this.awsRealTimeSocket=null,this.socketStatus=E.CLOSED,[3,5];case 5:return[2]}}))}))}))},t.prototype._initializeRetryableHandshake=function(e){var t=e.awsRealTimeUrl;return $(this,void 0,void 0,(function(){return Y(this,(function(e){switch(e.label){case 0:return Z.debug("Initializaling retryable Handshake"),[4,Object(F.b)(this._initializeHandshake.bind(this),[{awsRealTimeUrl:t}],5e3)];case 1:return e.sent(),[2]}}))}))},t.prototype._initializeHandshake=function(e){var t=e.awsRealTimeUrl;return $(this,void 0,void 0,(function(){var e,n,r,i=this;return Y(this,(function(o){switch(o.label){case 0:Z.debug("Initializing handshake "+t),o.label=1;case 1:return o.trys.push([1,4,,5]),[4,new Promise((function(e,n){var r=new WebSocket(t,"graphql-ws");r.onerror=function(){Z.debug("WebSocket connection error")},r.onclose=function(){n(new Error("Connection handshake error"))},r.onopen=function(){return i.awsRealTimeSocket=r,e()}}))];case 2:return o.sent(),[4,new Promise((function(e,t){var n=!1;i.awsRealTimeSocket.onerror=function(e){Z.debug("WebSocket error "+JSON.stringify(e))},i.awsRealTimeSocket.onclose=function(e){Z.debug("WebSocket closed "+e.reason),t(new Error(JSON.stringify(e)))},i.awsRealTimeSocket.onmessage=function(r){Z.debug("subscription message from AWS AppSyncRealTime: "+r.data+" ");var o=JSON.parse(r.data),s=o.type,a=o.payload,u=(void 0===a?{}:a).connectionTimeoutMs,c=void 0===u?3e5:u;if(s===_.GQL_CONNECTION_ACK)return n=!0,i.keepAliveTimeout=c,i.awsRealTimeSocket.onmessage=i._handleIncomingSubscriptionMessage.bind(i),i.awsRealTimeSocket.onerror=function(e){Z.debug(e),i._errorDisconnect(V.a.CONNECTION_CLOSED)},i.awsRealTimeSocket.onclose=function(e){Z.debug("WebSocket closed "+e.reason),i._errorDisconnect(V.a.CONNECTION_CLOSED)},void e("Cool, connected to AWS AppSyncRealTime");if(s===_.GQL_CONNECTION_ERROR){var f=o.payload,l=(void 0===f?{}:f).errors,d=J(void 0===l?[]:l,1)[0],h=void 0===d?{}:d,p=h.errorType,v=void 0===p?"":p,g=h.errorCode;t({errorType:v,errorCode:void 0===g?0:g})}};var r={type:_.GQL_CONNECTION_INIT};i.awsRealTimeSocket.send(JSON.stringify(r)),setTimeout(function(){n||t(new Error("Connection timeout: ack from AWSRealTime was not received on 15000 ms"))}.bind(i),15e3)}))];case 3:return o.sent(),[3,5];case 4:throw e=o.sent(),n=e.errorType,r=e.errorCode,Q.includes(r)?new F.a(n):n?new Error(n):e;case 5:return[2]}}))}))},t.prototype._awsRealTimeHeaderBasedAuth=function(e){var t=e.authenticationType,n=e.payload,r=e.canonicalUri,i=e.appSyncGraphqlEndpoint,o=e.apiKey,s=e.region;return $(this,void 0,void 0,(function(){var e,a,u;return Y(this,(function(c){switch(c.label){case 0:return e={API_KEY:this._awsRealTimeApiKeyHeader.bind(this),AWS_IAM:this._awsRealTimeIAMHeader.bind(this),OPENID_CONNECT:this._awsRealTimeOPENIDHeader.bind(this),AMAZON_COGNITO_USER_POOLS:this._awsRealTimeCUPHeader.bind(this)},"function"!=typeof(a=e[t])?(Z.debug("Authentication type "+t+" not supported"),[2,""]):(u=j.parse(i).host,[4,a({payload:n,canonicalUri:r,appSyncGraphqlEndpoint:i,apiKey:o,region:s,host:u})]);case 1:return[2,c.sent()]}}))}))},t.prototype._awsRealTimeCUPHeader=function(e){var t=e.host;return $(this,void 0,void 0,(function(){return Y(this,(function(e){switch(e.label){case 0:return[4,H.a.currentSession()];case 1:return[2,{Authorization:e.sent().getAccessToken().getJwtToken(),host:t}]}}))}))},t.prototype._awsRealTimeOPENIDHeader=function(e){var t=e.host;return $(this,void 0,void 0,(function(){var e,n,r;return Y(this,(function(i){switch(i.label){case 0:return[4,K.a.getItem("federatedInfo")];case 1:return(n=i.sent())?(e=n.token,[3,4]):[3,2];case 2:return[4,H.a.currentAuthenticatedUser()];case 3:(r=i.sent())&&(e=r.token),i.label=4;case 4:if(!e)throw new Error("No federated jwt");return[2,{Authorization:e,host:t}]}}))}))},t.prototype._awsRealTimeApiKeyHeader=function(e){var t=e.apiKey,n=e.host;return $(this,void 0,void 0,(function(){var e,r;return Y(this,(function(i){return e=new Date,r=e.toISOString().replace(/[:\-]|\.\d{3}/g,""),[2,{host:n,"x-amz-date":r,"x-api-key":t}]}))}))},t.prototype._awsRealTimeIAMHeader=function(e){var t=e.payload,n=e.canonicalUri,r=e.appSyncGraphqlEndpoint,i=e.region;return $(this,void 0,void 0,(function(){var e,o,s;return Y(this,(function(a){switch(a.label){case 0:return e={region:i,service:"appsync"},[4,this._ensureCredentials()];case 1:if(!a.sent())throw new Error("No credentials");return[4,z.a.get().then((function(e){return{secret_key:e.secretAccessKey,access_key:e.accessKeyId,session_token:e.sessionToken}}))];case 2:return o=a.sent(),s={url:""+r+n,data:t,method:"POST",headers:W({},ee)},[2,q.a.sign(s,o,e).headers]}}))}))},t.prototype._ensureCredentials=function(){return z.a.get().then((function(e){if(!e)return!1;var t=z.a.shear(e);return Z.debug("set credentials for AWSAppSyncRealTimeProvider",t),!0})).catch((function(e){return Z.warn("ensure credentials error",e),!1}))},t}(d),ne=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))},re=function(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]>>8^o[255&(this.checksum^a)]}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return this},e.prototype.digest=function(){return(4294967295^this.checksum)>>>0},e}();t.Crc32=i;var o=Uint32Array.from([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117])},function(e,t,n){var r=n(431);e.exports=function(e,t){return r(e,t)}},function(e,t,n){var r=n(483),i=n(484),o=i;o.v1=r,o.v4=i,e.exports=o},function(e,t,n){"use strict";n.d(t,"a",(function(){return M}));var r=n(107),i=n(1),o=n(28),s=function(){function e(e){if(this.bytes=e,8!==e.byteLength)throw new Error("Int64 buffers must be exactly 8 bytes")}return e.fromNumber=function(t){if(t>0x8000000000000000||t<-0x8000000000000000)throw new Error(t+" is too large (or, if negative, too small) to represent as an Int64");for(var n=new Uint8Array(8),r=7,i=Math.abs(Math.round(t));r>-1&&i>0;r--,i/=256)n[r]=i;return t<0&&a(n),new e(n)},e.prototype.valueOf=function(){var e=this.bytes.slice(0),t=128&e[0];return t&&a(e),parseInt(Object(o.b)(e),16)*(t?-1:1)},e.prototype.toString=function(){return String(this.valueOf())},e}();function a(e){for(var t=0;t<8;t++)e[t]^=255;for(t=7;t>-1&&(e[t]++,0===e[t]);t--);}var u,c=function(){function e(e,t){this.toUtf8=e,this.fromUtf8=t}return e.prototype.format=function(e){var t,n,r,o,s=[];try{for(var a=Object(i.__values)(Object.keys(e)),u=a.next();!u.done;u=a.next()){var c=u.value,f=this.fromUtf8(c);s.push(Uint8Array.from([f.byteLength]),f,this.formatHeaderValue(e[c]))}}catch(e){t={error:e}}finally{try{u&&!u.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}var l=new Uint8Array(s.reduce((function(e,t){return e+t.byteLength}),0)),d=0;try{for(var h=Object(i.__values)(s),p=h.next();!p.done;p=h.next()){var v=p.value;l.set(v,d),d+=v.byteLength}}catch(e){r={error:e}}finally{try{p&&!p.done&&(o=h.return)&&o.call(h)}finally{if(r)throw r.error}}return l},e.prototype.formatHeaderValue=function(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":var t=new DataView(new ArrayBuffer(3));return t.setUint8(0,3),t.setInt16(1,e.value,!1),new Uint8Array(t.buffer);case"integer":var n=new DataView(new ArrayBuffer(5));return n.setUint8(0,4),n.setInt32(1,e.value,!1),new Uint8Array(n.buffer);case"long":var r=new Uint8Array(9);return r[0]=5,r.set(e.value.bytes,1),r;case"binary":var i=new DataView(new ArrayBuffer(3+e.value.byteLength));i.setUint8(0,6),i.setUint16(1,e.value.byteLength,!1);var a=new Uint8Array(i.buffer);return a.set(e.value,3),a;case"string":var u=this.fromUtf8(e.value),c=new DataView(new ArrayBuffer(3+u.byteLength));c.setUint8(0,7),c.setUint16(1,u.byteLength,!1);var f=new Uint8Array(c.buffer);return f.set(u,3),f;case"timestamp":var l=new Uint8Array(9);return l[0]=8,l.set(s.fromNumber(e.value.valueOf()).bytes,1),l;case"uuid":if(!y.test(e.value))throw new Error("Invalid UUID received: "+e.value);var d=new Uint8Array(17);return d[0]=9,d.set(Object(o.a)(e.value.replace(/\-/g,"")),1),d}},e.prototype.parse=function(e){for(var t={},n=0;n-1&&delete e.headers[a]}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return e}function E(e){return function(e){if("number"==typeof e)return new Date(1e3*e);if("string"==typeof e)return Number(e)?new Date(1e3*Number(e)):new Date(e);return e}(e).toISOString().replace(/\.\d{3}Z$/,"Z")}var M=function(){function e(e){var t=e.applyChecksum,n=e.credentials,r=e.region,i=e.service,o=e.sha256,s=e.uriEscapePath,a=void 0===s||s;this.service=i,this.sha256=o,this.uriEscapePath=a,this.applyChecksum="boolean"!=typeof t||t,this.regionProvider=k(r),this.credentialProvider=O(n)}return e.prototype.presign=function(e,t){return void 0===t&&(t={}),Object(r.__awaiter)(this,void 0,void 0,(function(){var n,i,o,s,a,u,c,f,l,d,h,v,m,b,_,E,M,k,O,x,C,T,P;return Object(r.__generator)(this,(function(N){switch(N.label){case 0:return n=t.signingDate,i=void 0===n?new Date:n,o=t.expiresIn,s=void 0===o?3600:o,a=t.unsignableHeaders,u=t.signableHeaders,c=t.signingRegion,f=t.signingService,[4,this.credentialProvider()];case 1:return l=N.sent(),null==c?[3,2]:(h=c,[3,4]);case 2:return[4,this.regionProvider()];case 3:h=N.sent(),N.label=4;case 4:return d=h,v=A(i),m=v.longDate,b=v.shortDate,s>604800?[2,Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future")]:(_=p(b,d,null!=f?f:this.service),E=function(e){var t,n,i="function"==typeof e.clone?e.clone():w(e),o=i.headers,s=i.query,a=void 0===s?{}:s;try{for(var u=Object(r.__values)(Object.keys(o)),c=u.next();!c.done;c=u.next()){var f=c.value;"x-amz-"===f.toLowerCase().substr(0,6)&&(a[f]=o[f],delete o[f])}}catch(e){t={error:e}}finally{try{c&&!c.done&&(n=u.return)&&n.call(u)}finally{if(t)throw t.error}}return Object(r.__assign)(Object(r.__assign)({},e),{headers:o,query:a})}(S(e)),l.sessionToken&&(E.query["X-Amz-Security-Token"]=l.sessionToken),E.query["X-Amz-Algorithm"]="AWS4-HMAC-SHA256",E.query["X-Amz-Credential"]=l.accessKeyId+"/"+_,E.query["X-Amz-Date"]=m,E.query["X-Amz-Expires"]=s.toString(10),M=g(E,a,u),E.query["X-Amz-SignedHeaders"]=I(M),k=E.query,O="X-Amz-Signature",x=this.getSignature,C=[m,_,this.getSigningKey(l,d,b,f)],T=this.createCanonicalRequest,P=[E,M],[4,y(e,this.sha256)]);case 5:return[4,x.apply(this,C.concat([T.apply(this,P.concat([N.sent()]))]))];case 6:return k[O]=N.sent(),[2,E]}}))}))},e.prototype.sign=function(e,t){return Object(r.__awaiter)(this,void 0,void 0,(function(){return Object(r.__generator)(this,(function(n){return"string"==typeof e?[2,this.signString(e,t)]:e.headers&&e.payload?[2,this.signEvent(e,t)]:[2,this.signRequest(e,t)]}))}))},e.prototype.signEvent=function(e,t){var n=e.headers,i=e.payload,o=t.signingDate,s=void 0===o?new Date:o,a=t.priorSignature,u=t.signingRegion,c=t.signingService;return Object(r.__awaiter)(this,void 0,void 0,(function(){var e,t,o,f,d,h,g,m,b,w,_;return Object(r.__generator)(this,(function(r){switch(r.label){case 0:return null==u?[3,1]:(t=u,[3,3]);case 1:return[4,this.regionProvider()];case 2:t=r.sent(),r.label=3;case 3:return e=t,o=A(s),f=o.shortDate,d=o.longDate,h=p(f,e,null!=c?c:this.service),[4,y({headers:{},body:i},this.sha256)];case 4:return g=r.sent(),(m=new this.sha256).update(n),w=v.b,[4,m.digest()];case 5:return b=w.apply(void 0,[r.sent()]),_=[l,d,h,a,b,g].join("\n"),[2,this.signString(_,{signingDate:s,signingRegion:e,signingService:c})]}}))}))},e.prototype.signString=function(e,t){var n=void 0===t?{}:t,i=n.signingDate,o=void 0===i?new Date:i,s=n.signingRegion,a=n.signingService;return Object(r.__awaiter)(this,void 0,void 0,(function(){var t,n,i,u,c,f,l,d;return Object(r.__generator)(this,(function(r){switch(r.label){case 0:return[4,this.credentialProvider()];case 1:return t=r.sent(),null==s?[3,2]:(i=s,[3,4]);case 2:return[4,this.regionProvider()];case 3:i=r.sent(),r.label=4;case 4:return n=i,u=A(o).shortDate,l=(f=this.sha256).bind,[4,this.getSigningKey(t,n,u,a)];case 5:return(c=new(l.apply(f,[void 0,r.sent()]))).update(e),d=v.b,[4,c.digest()];case 6:return[2,d.apply(void 0,[r.sent()])]}}))}))},e.prototype.signRequest=function(e,t){var n=void 0===t?{}:t,o=n.signingDate,s=void 0===o?new Date:o,u=n.signableHeaders,c=n.unsignableHeaders,f=n.signingRegion,l=n.signingService;return Object(r.__awaiter)(this,void 0,void 0,(function(){var t,n,o,d,h,v,m,b,w,_,E;return Object(r.__generator)(this,(function(M){switch(M.label){case 0:return[4,this.credentialProvider()];case 1:return t=M.sent(),null==f?[3,2]:(o=f,[3,4]);case 2:return[4,this.regionProvider()];case 3:o=M.sent(),M.label=4;case 4:return n=o,d=S(e),h=A(s),v=h.longDate,m=h.shortDate,b=p(m,n,null!=l?l:this.service),d.headers[i]=v,t.sessionToken&&(d.headers[a]=t.sessionToken),[4,y(d,this.sha256)];case 5:return w=M.sent(),!function(e,t){var n,i;e=e.toLowerCase();try{for(var o=Object(r.__values)(Object.keys(t)),s=o.next();!s.done;s=o.next()){if(e===s.value.toLowerCase())return!0}}catch(e){n={error:e}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return!1}("x-amz-content-sha256",d.headers)&&this.applyChecksum&&(d.headers["x-amz-content-sha256"]=w),_=g(d,c,u),[4,this.getSignature(v,b,this.getSigningKey(t,n,m,l),this.createCanonicalRequest(d,_,w))];case 6:return E=M.sent(),d.headers.authorization="AWS4-HMAC-SHA256 Credential="+t.accessKeyId+"/"+b+", SignedHeaders="+I(_)+", Signature="+E,[2,d]}}))}))},e.prototype.createCanonicalRequest=function(e,t,n){var i=Object.keys(t).sort();return e.method+"\n"+this.getCanonicalPath(e)+"\n"+function(e){var t,n,i=e.query,o=void 0===i?{}:i,a=[],u={},c=function(e){if(e.toLowerCase()===s)return"continue";a.push(e);var t=o[e];"string"==typeof t?u[e]=Object(m.a)(e)+"="+Object(m.a)(t):Array.isArray(t)&&(u[e]=t.slice(0).sort().reduce((function(t,n){return t.concat([Object(m.a)(e)+"="+Object(m.a)(n)])}),[]).join("&"))};try{for(var f=Object(r.__values)(Object.keys(o).sort()),l=f.next();!l.done;l=f.next()){c(l.value)}}catch(e){t={error:e}}finally{try{l&&!l.done&&(n=f.return)&&n.call(f)}finally{if(t)throw t.error}}return a.map((function(e){return u[e]})).filter((function(e){return e})).join("&")}(e)+"\n"+i.map((function(e){return e+":"+t[e]})).join("\n")+"\n\n"+i.join(";")+"\n"+n},e.prototype.createStringToSign=function(e,t,n){return Object(r.__awaiter)(this,void 0,void 0,(function(){var i,o;return Object(r.__generator)(this,(function(r){switch(r.label){case 0:return(i=new this.sha256).update(n),[4,i.digest()];case 1:return o=r.sent(),[2,"AWS4-HMAC-SHA256\n"+e+"\n"+t+"\n"+Object(v.b)(o)]}}))}))},e.prototype.getCanonicalPath=function(e){var t=e.path;return this.uriEscapePath?"/"+encodeURIComponent(t.replace(/^\//,"")).replace(/%2F/g,"/"):t},e.prototype.getSignature=function(e,t,n,i){return Object(r.__awaiter)(this,void 0,void 0,(function(){var o,s,a,u,c;return Object(r.__generator)(this,(function(r){switch(r.label){case 0:return[4,this.createStringToSign(e,t,i)];case 1:return o=r.sent(),u=(a=this.sha256).bind,[4,n];case 2:return(s=new(u.apply(a,[void 0,r.sent()]))).update(o),c=v.b,[4,s.digest()];case 3:return[2,c.apply(void 0,[r.sent()])]}}))}))},e.prototype.getSigningKey=function(e,t,n,i){return function(e,t,n,i,o){var s=n+":"+i+":"+o+":"+t.accessKeyId+":"+t.sessionToken;if(s in d)return d[s];for(h.push(s);h.length>50;)delete d[h.shift()];return d[s]=new Promise((function(a,u){var c,f,l=Promise.resolve("AWS4"+t.secretAccessKey),h=function(t){(l=l.then((function(n){return r=t,(i=new e(n)).update(r),i.digest();var r,i}))).catch((function(){}))};try{for(var p=Object(r.__values)([n,i,o,"aws4_request"]),v=p.next();!v.done;v=p.next()){h(v.value)}}catch(e){c={error:e}}finally{try{v&&!v.done&&(f=p.return)&&f.call(p)}finally{if(c)throw c.error}}l.then(a,(function(e){delete d[s],u(e)}))}))}(this.sha256,e,n,t,i||this.service)},e}(),A=function(e){var t=E(e).replace(/[\-:]/g,"");return{longDate:t,shortDate:t.substr(0,8)}},I=function(e){return Object.keys(e).sort().join(";")},k=function(e){if("string"==typeof e){var t=Promise.resolve(e);return function(){return t}}return e},O=function(e){if("object"==typeof e){var t=Promise.resolve(e);return function(){return t}}return e}},function(e,t,n){"use strict";n.d(t,"a",(function(){return i}));var r=n(1),i=function(e){return Object(r.__assign)(Object(r.__assign)({},e),{eventStreamMarshaller:e.eventStreamSerdeProvider(e)})}},function(e,t,n){"use strict";var r=n(7),i=n(162),o=n(8).Buffer,s=new Array(16);function a(){i.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}function u(e,t){return e<>>32-t}function c(e,t,n,r,i,o,s){return u(e+(t&n|~t&r)+i+o|0,s)+t|0}function f(e,t,n,r,i,o,s){return u(e+(t&r|n&~r)+i+o|0,s)+t|0}function l(e,t,n,r,i,o,s){return u(e+(t^n^r)+i+o|0,s)+t|0}function d(e,t,n,r,i,o,s){return u(e+(n^(t|~r))+i+o|0,s)+t|0}r(a,i),a.prototype._update=function(){for(var e=s,t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);var n=this._a,r=this._b,i=this._c,o=this._d;n=c(n,r,i,o,e[0],3614090360,7),o=c(o,n,r,i,e[1],3905402710,12),i=c(i,o,n,r,e[2],606105819,17),r=c(r,i,o,n,e[3],3250441966,22),n=c(n,r,i,o,e[4],4118548399,7),o=c(o,n,r,i,e[5],1200080426,12),i=c(i,o,n,r,e[6],2821735955,17),r=c(r,i,o,n,e[7],4249261313,22),n=c(n,r,i,o,e[8],1770035416,7),o=c(o,n,r,i,e[9],2336552879,12),i=c(i,o,n,r,e[10],4294925233,17),r=c(r,i,o,n,e[11],2304563134,22),n=c(n,r,i,o,e[12],1804603682,7),o=c(o,n,r,i,e[13],4254626195,12),i=c(i,o,n,r,e[14],2792965006,17),n=f(n,r=c(r,i,o,n,e[15],1236535329,22),i,o,e[1],4129170786,5),o=f(o,n,r,i,e[6],3225465664,9),i=f(i,o,n,r,e[11],643717713,14),r=f(r,i,o,n,e[0],3921069994,20),n=f(n,r,i,o,e[5],3593408605,5),o=f(o,n,r,i,e[10],38016083,9),i=f(i,o,n,r,e[15],3634488961,14),r=f(r,i,o,n,e[4],3889429448,20),n=f(n,r,i,o,e[9],568446438,5),o=f(o,n,r,i,e[14],3275163606,9),i=f(i,o,n,r,e[3],4107603335,14),r=f(r,i,o,n,e[8],1163531501,20),n=f(n,r,i,o,e[13],2850285829,5),o=f(o,n,r,i,e[2],4243563512,9),i=f(i,o,n,r,e[7],1735328473,14),n=l(n,r=f(r,i,o,n,e[12],2368359562,20),i,o,e[5],4294588738,4),o=l(o,n,r,i,e[8],2272392833,11),i=l(i,o,n,r,e[11],1839030562,16),r=l(r,i,o,n,e[14],4259657740,23),n=l(n,r,i,o,e[1],2763975236,4),o=l(o,n,r,i,e[4],1272893353,11),i=l(i,o,n,r,e[7],4139469664,16),r=l(r,i,o,n,e[10],3200236656,23),n=l(n,r,i,o,e[13],681279174,4),o=l(o,n,r,i,e[0],3936430074,11),i=l(i,o,n,r,e[3],3572445317,16),r=l(r,i,o,n,e[6],76029189,23),n=l(n,r,i,o,e[9],3654602809,4),o=l(o,n,r,i,e[12],3873151461,11),i=l(i,o,n,r,e[15],530742520,16),n=d(n,r=l(r,i,o,n,e[2],3299628645,23),i,o,e[0],4096336452,6),o=d(o,n,r,i,e[7],1126891415,10),i=d(i,o,n,r,e[14],2878612391,15),r=d(r,i,o,n,e[5],4237533241,21),n=d(n,r,i,o,e[12],1700485571,6),o=d(o,n,r,i,e[3],2399980690,10),i=d(i,o,n,r,e[10],4293915773,15),r=d(r,i,o,n,e[1],2240044497,21),n=d(n,r,i,o,e[8],1873313359,6),o=d(o,n,r,i,e[15],4264355552,10),i=d(i,o,n,r,e[6],2734768916,15),r=d(r,i,o,n,e[13],1309151649,21),n=d(n,r,i,o,e[4],4149444226,6),o=d(o,n,r,i,e[11],3174756917,10),i=d(i,o,n,r,e[2],718787259,15),r=d(r,i,o,n,e[9],3951481745,21),this._a=this._a+n|0,this._b=this._b+r|0,this._c=this._c+i|0,this._d=this._d+o|0},a.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=o.allocUnsafe(16);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e},e.exports=a},function(e,t,n){(function(t){function n(e){try{if(!t.localStorage)return!1}catch(e){return!1}var n=t.localStorage[e];return null!=n&&"true"===String(n).toLowerCase()}e.exports=function(e,t){if(n("noDeprecation"))return e;var r=!1;return function(){if(!r){if(n("throwDeprecation"))throw new Error(t);n("traceDeprecation")?console.trace(t):console.warn(t),r=!0}return e.apply(this,arguments)}}}).call(this,n(31))},function(e,t,n){"use strict";var r=n(67).codes.ERR_STREAM_PREMATURE_CLOSE;function i(){}e.exports=function e(t,n,o){if("function"==typeof n)return e(t,null,n);n||(n={}),o=function(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=new Array(n),i=0;i>>32-t}function v(e,t,n,r,i,o,s,a){return p(e+(t^n^r)+o+s|0,a)+i|0}function g(e,t,n,r,i,o,s,a){return p(e+(t&n|~t&r)+o+s|0,a)+i|0}function m(e,t,n,r,i,o,s,a){return p(e+((t|~n)^r)+o+s|0,a)+i|0}function b(e,t,n,r,i,o,s,a){return p(e+(t&r|n&~r)+o+s|0,a)+i|0}function y(e,t,n,r,i,o,s,a){return p(e+(t^(n|~r))+o+s|0,a)+i|0}i(h,o),h.prototype._update=function(){for(var e=s,t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);for(var n=0|this._a,r=0|this._b,i=0|this._c,o=0|this._d,h=0|this._e,w=0|this._a,_=0|this._b,S=0|this._c,E=0|this._d,M=0|this._e,A=0;A<80;A+=1){var I,k;A<16?(I=v(n,r,i,o,h,e[a[A]],l[0],c[A]),k=y(w,_,S,E,M,e[u[A]],d[0],f[A])):A<32?(I=g(n,r,i,o,h,e[a[A]],l[1],c[A]),k=b(w,_,S,E,M,e[u[A]],d[1],f[A])):A<48?(I=m(n,r,i,o,h,e[a[A]],l[2],c[A]),k=m(w,_,S,E,M,e[u[A]],d[2],f[A])):A<64?(I=b(n,r,i,o,h,e[a[A]],l[3],c[A]),k=g(w,_,S,E,M,e[u[A]],d[3],f[A])):(I=y(n,r,i,o,h,e[a[A]],l[4],c[A]),k=v(w,_,S,E,M,e[u[A]],d[4],f[A])),n=h,h=o,o=p(i,10),i=r,r=I,w=M,M=E,E=p(S,10),S=_,_=k}var O=this._b+i+E|0;this._b=this._c+o+M|0,this._c=this._d+h+w|0,this._d=this._e+n+_|0,this._e=this._a+r+S|0,this._a=O},h.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=r.alloc?r.alloc(20):new r(20);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e.writeInt32LE(this._e,16),e},e.exports=h},function(e,t,n){(t=e.exports=function(e){e=e.toLowerCase();var n=t[e];if(!n)throw new Error(e+" is not supported (we accept pull requests)");return new n}).sha=n(281),t.sha1=n(282),t.sha224=n(283),t.sha256=n(169),t.sha384=n(284),t.sha512=n(170)},function(e,t,n){(t=e.exports=n(171)).Stream=t,t.Readable=t,t.Writable=n(120),t.Duplex=n(60),t.Transform=n(174),t.PassThrough=n(291)},function(e,t,n){var r=n(6),i=r.Buffer;function o(e,t){for(var n in e)t[n]=e[n]}function s(e,t,n){return i(e,t,n)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?e.exports=r:(o(r,t),t.Buffer=s),o(i,s),s.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,n)},s.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=i(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}},function(e,t,n){"use strict";(function(t,r,i){var o=n(92);function s(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,n){var r=e.entry;e.entry=null;for(;r;){var i=r.callback;t.pendingcb--,i(n),r=r.next}t.corkedRequestsFree?t.corkedRequestsFree.next=e:t.corkedRequestsFree=e}(t,e)}}e.exports=b;var a,u=!t.browser&&["v0.10","v0.9."].indexOf(t.version.slice(0,5))>-1?r:o.nextTick;b.WritableState=m;var c=Object.create(n(80));c.inherits=n(7);var f={deprecate:n(114)},l=n(172),d=n(119).Buffer,h=i.Uint8Array||function(){};var p,v=n(173);function g(){}function m(e,t){a=a||n(60),e=e||{};var r=t instanceof a;this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var i=e.highWaterMark,c=e.writableHighWaterMark,f=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:r&&(c||0===c)?c:f,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var l=!1===e.decodeStrings;this.decodeStrings=!l,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var n=e._writableState,r=n.sync,i=n.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(n),t)!function(e,t,n,r,i){--t.pendingcb,n?(o.nextTick(i,r),o.nextTick(M,e,t),e._writableState.errorEmitted=!0,e.emit("error",r)):(i(r),e._writableState.errorEmitted=!0,e.emit("error",r),M(e,t))}(e,n,r,t,i);else{var s=S(n);s||n.corked||n.bufferProcessing||!n.bufferedRequest||_(e,n),r?u(w,e,n,s,i):w(e,n,s,i)}}(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new s(this)}function b(e){if(a=a||n(60),!(p.call(b,this)||this instanceof a))return new b(e);this._writableState=new m(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),l.call(this)}function y(e,t,n,r,i,o,s){t.writelen=r,t.writecb=s,t.writing=!0,t.sync=!0,n?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function w(e,t,n,r){n||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,r(),M(e,t)}function _(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,i=new Array(r),o=t.corkedRequestsFree;o.entry=n;for(var a=0,u=!0;n;)i[a]=n,n.isBuf||(u=!1),n=n.next,a+=1;i.allBuffers=u,y(e,t,!0,t.length,i,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new s(t),t.bufferedRequestCount=0}else{for(;n;){var c=n.chunk,f=n.encoding,l=n.callback;if(y(e,t,!1,t.objectMode?1:c.length,c,f,l),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function S(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function E(e,t){e._final((function(n){t.pendingcb--,n&&e.emit("error",n),t.prefinished=!0,e.emit("prefinish"),M(e,t)}))}function M(e,t){var n=S(t);return n&&(!function(e,t){t.prefinished||t.finalCalled||("function"==typeof e._final?(t.pendingcb++,t.finalCalled=!0,o.nextTick(E,e,t)):(t.prefinished=!0,e.emit("prefinish")))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"))),n}c.inherits(b,l),m.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(m.prototype,"buffer",{get:f.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(p=Function.prototype[Symbol.hasInstance],Object.defineProperty(b,Symbol.hasInstance,{value:function(e){return!!p.call(this,e)||this===b&&(e&&e._writableState instanceof m)}})):p=function(e){return e instanceof this},b.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},b.prototype.write=function(e,t,n){var r,i=this._writableState,s=!1,a=!i.objectMode&&(r=e,d.isBuffer(r)||r instanceof h);return a&&!d.isBuffer(e)&&(e=function(e){return d.from(e)}(e)),"function"==typeof t&&(n=t,t=null),a?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof n&&(n=g),i.ended?function(e,t){var n=new Error("write after end");e.emit("error",n),o.nextTick(t,n)}(this,n):(a||function(e,t,n,r){var i=!0,s=!1;return null===n?s=new TypeError("May not write null values to stream"):"string"==typeof n||void 0===n||t.objectMode||(s=new TypeError("Invalid non-string/buffer chunk")),s&&(e.emit("error",s),o.nextTick(r,s),i=!1),i}(this,i,e,n))&&(i.pendingcb++,s=function(e,t,n,r,i,o){if(!n){var s=function(e,t,n){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=d.from(t,n));return t}(t,r,i);r!==s&&(n=!0,i="buffer",r=s)}var a=t.objectMode?1:r.length;t.length+=a;var u=t.length-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(b.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),b.prototype._write=function(e,t,n){n(new Error("_write() is not implemented"))},b.prototype._writev=null,b.prototype.end=function(e,t,n){var r=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||r.finished||function(e,t,n){t.ending=!0,M(e,t),n&&(t.finished?o.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,r,n)},Object.defineProperty(b.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),b.prototype.destroy=v.destroy,b.prototype._undestroy=v.undestroy,b.prototype._destroy=function(e,t){this.end(),t(e)}}).call(this,n(20),n(289).setImmediate,n(31))},function(e,t,n){"use strict";var r=n(46);function i(e){this.options=e,this.type=this.options.type,this.blockSize=8,this._init(),this.buffer=new Array(this.blockSize),this.bufferOff=0}e.exports=i,i.prototype._init=function(){},i.prototype.update=function(e){return 0===e.length?[]:"decrypt"===this.type?this._updateDecrypt(e):this._updateEncrypt(e)},i.prototype._buffer=function(e,t){for(var n=Math.min(this.buffer.length-this.bufferOff,e.length-t),r=0;r0;r--)t+=this._buffer(e,t),n+=this._flushBuffer(i,n);return t+=this._buffer(e,t),i},i.prototype.final=function(e){var t,n;return e&&(t=this.update(e)),n="encrypt"===this.type?this._finalEncrypt():this._finalDecrypt(),t?t.concat(n):n},i.prototype._pad=function(e,t){if(0===t)return!1;for(;t=0||!t.umod(e.prime1)||!t.umod(e.prime2));return t}function s(e,n){var i=function(e){var t=o(e);return{blinder:t.toRed(r.mont(e.modulus)).redPow(new r(e.publicExponent)).fromRed(),unblinder:t.invm(e.modulus)}}(n),s=n.modulus.byteLength(),a=new r(e).mul(i.blinder).umod(n.modulus),u=a.toRed(r.mont(n.prime1)),c=a.toRed(r.mont(n.prime2)),f=n.coefficient,l=n.prime1,d=n.prime2,h=u.redPow(n.exponent1).fromRed(),p=c.redPow(n.exponent2).fromRed(),v=h.isub(p).imul(f).umod(l).imul(d);return p.iadd(v).imul(i.unblinder).umod(n.modulus).toArrayLike(t,"be",s)}s.getr=o,e.exports=s}).call(this,n(6).Buffer)},function(e,t,n){"use strict";var r=t;r.version=n(331).version,r.utils=n(47),r.rand=n(124),r.curve=n(199),r.curves=n(128),r.ec=n(342),r.eddsa=n(346)},function(e,t,n){"use strict";var r,i=t,o=n(129),s=n(199),a=n(47).assert;function u(e){"short"===e.type?this.curve=new s.short(e):"edwards"===e.type?this.curve=new s.edwards(e):this.curve=new s.mont(e),this.g=this.curve.g,this.n=this.curve.n,this.hash=e.hash,a(this.g.validate(),"Invalid curve"),a(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}function c(e,t){Object.defineProperty(i,e,{configurable:!0,enumerable:!0,get:function(){var n=new u(t);return Object.defineProperty(i,e,{configurable:!0,enumerable:!0,value:n}),n}})}i.PresetCurve=u,c("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:o.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),c("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:o.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),c("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:o.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),c("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:o.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),c("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:o.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),c("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:o.sha256,gRed:!1,g:["9"]}),c("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:o.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});try{r=n(341)}catch(e){r=void 0}c("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:o.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",r]})},function(e,t,n){var r=t;r.utils=n(51),r.common=n(82),r.sha=n(335),r.ripemd=n(339),r.hmac=n(340),r.sha1=r.sha.sha1,r.sha256=r.sha.sha256,r.sha224=r.sha.sha224,r.sha384=r.sha.sha384,r.sha512=r.sha.sha512,r.ripemd160=r.ripemd.ripemd160},function(e,t,n){"use strict";(function(t){var r,i=n(6),o=i.Buffer,s={};for(r in i)i.hasOwnProperty(r)&&"SlowBuffer"!==r&&"Buffer"!==r&&(s[r]=i[r]);var a=s.Buffer={};for(r in o)o.hasOwnProperty(r)&&"allocUnsafe"!==r&&"allocUnsafeSlow"!==r&&(a[r]=o[r]);if(s.Buffer.prototype=o.prototype,a.from&&a.from!==Uint8Array.from||(a.from=function(e,t,n){if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type '+typeof e);if(e&&void 0===e.length)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);return o(e,t,n)}),a.alloc||(a.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError('The "size" argument must be of type number. Received type '+typeof e);if(e<0||e>=2*(1<<30))throw new RangeError('The value "'+e+'" is invalid for option "size"');var r=o(e);return t&&0!==t.length?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r}),!s.kStringMaxLength)try{s.kStringMaxLength=t.binding("buffer").kStringMaxLength}catch(e){}s.constants||(s.constants={MAX_LENGTH:s.kMaxLength},s.kStringMaxLength&&(s.constants.MAX_STRING_LENGTH=s.kStringMaxLength)),e.exports=s}).call(this,n(20))},function(e,t,n){"use strict";const r=n(132).Reporter,i=n(83).EncoderBuffer,o=n(83).DecoderBuffer,s=n(46),a=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],u=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(a);function c(e,t,n){const r={};this._baseState=r,r.name=n,r.enc=e,r.parent=t||null,r.children=null,r.tag=null,r.args=null,r.reverseArgs=null,r.choice=null,r.optional=!1,r.any=!1,r.obj=!1,r.use=null,r.useDecoder=null,r.key=null,r.default=null,r.explicit=null,r.implicit=null,r.contains=null,r.parent||(r.children=[],this._wrap())}e.exports=c;const f=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];c.prototype.clone=function(){const e=this._baseState,t={};f.forEach((function(n){t[n]=e[n]}));const n=new this.constructor(t.parent);return n._baseState=t,n},c.prototype._wrap=function(){const e=this._baseState;u.forEach((function(t){this[t]=function(){const n=new this.constructor(this);return e.children.push(n),n[t].apply(n,arguments)}}),this)},c.prototype._init=function(e){const t=this._baseState;s(null===t.parent),e.call(this),t.children=t.children.filter((function(e){return e._baseState.parent===this}),this),s.equal(t.children.length,1,"Root node can have only one child")},c.prototype._useArgs=function(e){const t=this._baseState,n=e.filter((function(e){return e instanceof this.constructor}),this);e=e.filter((function(e){return!(e instanceof this.constructor)}),this),0!==n.length&&(s(null===t.children),t.children=n,n.forEach((function(e){e._baseState.parent=this}),this)),0!==e.length&&(s(null===t.args),t.args=e,t.reverseArgs=e.map((function(e){if("object"!=typeof e||e.constructor!==Object)return e;const t={};return Object.keys(e).forEach((function(n){n==(0|n)&&(n|=0);const r=e[n];t[r]=n})),t})))},["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"].forEach((function(e){c.prototype[e]=function(){const t=this._baseState;throw new Error(e+" not implemented for encoding: "+t.enc)}})),a.forEach((function(e){c.prototype[e]=function(){const t=this._baseState,n=Array.prototype.slice.call(arguments);return s(null===t.tag),t.tag=e,this._useArgs(n),this}})),c.prototype.use=function(e){s(e);const t=this._baseState;return s(null===t.use),t.use=e,this},c.prototype.optional=function(){return this._baseState.optional=!0,this},c.prototype.def=function(e){const t=this._baseState;return s(null===t.default),t.default=e,t.optional=!0,this},c.prototype.explicit=function(e){const t=this._baseState;return s(null===t.explicit&&null===t.implicit),t.explicit=e,this},c.prototype.implicit=function(e){const t=this._baseState;return s(null===t.explicit&&null===t.implicit),t.implicit=e,this},c.prototype.obj=function(){const e=this._baseState,t=Array.prototype.slice.call(arguments);return e.obj=!0,0!==t.length&&this._useArgs(t),this},c.prototype.key=function(e){const t=this._baseState;return s(null===t.key),t.key=e,this},c.prototype.any=function(){return this._baseState.any=!0,this},c.prototype.choice=function(e){const t=this._baseState;return s(null===t.choice),t.choice=e,this._useArgs(Object.keys(e).map((function(t){return e[t]}))),this},c.prototype.contains=function(e){const t=this._baseState;return s(null===t.use),t.contains=e,this},c.prototype._decode=function(e,t){const n=this._baseState;if(null===n.parent)return e.wrapResult(n.children[0]._decode(e,t));let r,i=n.default,s=!0,a=null;if(null!==n.key&&(a=e.enterKey(n.key)),n.optional){let r=null;if(null!==n.explicit?r=n.explicit:null!==n.implicit?r=n.implicit:null!==n.tag&&(r=n.tag),null!==r||n.any){if(s=this._peekTag(e,r,n.any),e.isError(s))return s}else{const r=e.save();try{null===n.choice?this._decodeGeneric(n.tag,e,t):this._decodeChoice(e,t),s=!0}catch(e){s=!1}e.restore(r)}}if(n.obj&&s&&(r=e.enterObject()),s){if(null!==n.explicit){const t=this._decodeTag(e,n.explicit);if(e.isError(t))return t;e=t}const r=e.offset;if(null===n.use&&null===n.choice){let t;n.any&&(t=e.save());const r=this._decodeTag(e,null!==n.implicit?n.implicit:n.tag,n.any);if(e.isError(r))return r;n.any?i=e.raw(t):e=r}if(t&&t.track&&null!==n.tag&&t.track(e.path(),r,e.length,"tagged"),t&&t.track&&null!==n.tag&&t.track(e.path(),e.offset,e.length,"content"),n.any||(i=null===n.choice?this._decodeGeneric(n.tag,e,t):this._decodeChoice(e,t)),e.isError(i))return i;if(n.any||null!==n.choice||null===n.children||n.children.forEach((function(n){n._decode(e,t)})),n.contains&&("octstr"===n.tag||"bitstr"===n.tag)){const r=new o(i);i=this._getUse(n.contains,e._reporterState.obj)._decode(r,t)}}return n.obj&&s&&(i=e.leaveObject(r)),null===n.key||null===i&&!0!==s?null!==a&&e.exitKey(a):e.leaveKey(a,n.key,i),i},c.prototype._decodeGeneric=function(e,t,n){const r=this._baseState;return"seq"===e||"set"===e?null:"seqof"===e||"setof"===e?this._decodeList(t,e,r.args[0],n):/str$/.test(e)?this._decodeStr(t,e,n):"objid"===e&&r.args?this._decodeObjid(t,r.args[0],r.args[1],n):"objid"===e?this._decodeObjid(t,null,null,n):"gentime"===e||"utctime"===e?this._decodeTime(t,e,n):"null_"===e?this._decodeNull(t,n):"bool"===e?this._decodeBool(t,n):"objDesc"===e?this._decodeStr(t,e,n):"int"===e||"enum"===e?this._decodeInt(t,r.args&&r.args[0],n):null!==r.use?this._getUse(r.use,t._reporterState.obj)._decode(t,n):t.error("unknown tag: "+e)},c.prototype._getUse=function(e,t){const n=this._baseState;return n.useDecoder=this._use(e,t),s(null===n.useDecoder._baseState.parent),n.useDecoder=n.useDecoder._baseState.children[0],n.implicit!==n.useDecoder._baseState.implicit&&(n.useDecoder=n.useDecoder.clone(),n.useDecoder._baseState.implicit=n.implicit),n.useDecoder},c.prototype._decodeChoice=function(e,t){const n=this._baseState;let r=null,i=!1;return Object.keys(n.choice).some((function(o){const s=e.save(),a=n.choice[o];try{const n=a._decode(e,t);if(e.isError(n))return!1;r={type:o,value:n},i=!0}catch(t){return e.restore(s),!1}return!0}),this),i?r:e.error("Choice not matched")},c.prototype._createEncoderBuffer=function(e){return new i(e,this.reporter)},c.prototype._encode=function(e,t,n){const r=this._baseState;if(null!==r.default&&r.default===e)return;const i=this._encodeValue(e,t,n);return void 0===i||this._skipDefault(i,t,n)?void 0:i},c.prototype._encodeValue=function(e,t,n){const i=this._baseState;if(null===i.parent)return i.children[0]._encode(e,t||new r);let o=null;if(this.reporter=t,i.optional&&void 0===e){if(null===i.default)return;e=i.default}let s=null,a=!1;if(i.any)o=this._createEncoderBuffer(e);else if(i.choice)o=this._encodeChoice(e,t);else if(i.contains)s=this._getUse(i.contains,n)._encode(e,t),a=!0;else if(i.children)s=i.children.map((function(n){if("null_"===n._baseState.tag)return n._encode(null,t,e);if(null===n._baseState.key)return t.error("Child should have a key");const r=t.enterKey(n._baseState.key);if("object"!=typeof e)return t.error("Child expected, but input is not object");const i=n._encode(e[n._baseState.key],t,e);return t.leaveKey(r),i}),this).filter((function(e){return e})),s=this._createEncoderBuffer(s);else if("seqof"===i.tag||"setof"===i.tag){if(!i.args||1!==i.args.length)return t.error("Too many args for : "+i.tag);if(!Array.isArray(e))return t.error("seqof/setof, but data is not Array");const n=this.clone();n._baseState.implicit=null,s=this._createEncoderBuffer(e.map((function(n){const r=this._baseState;return this._getUse(r.args[0],e)._encode(n,t)}),n))}else null!==i.use?o=this._getUse(i.use,n)._encode(e,t):(s=this._encodePrimitive(i.tag,e),a=!0);if(!i.any&&null===i.choice){const e=null!==i.implicit?i.implicit:i.tag,n=null===i.implicit?"universal":"context";null===e?null===i.use&&t.error("Tag could be omitted only for .use()"):null===i.use&&(o=this._encodeComposite(e,a,n,s))}return null!==i.explicit&&(o=this._encodeComposite(i.explicit,!1,"context",o)),o},c.prototype._encodeChoice=function(e,t){const n=this._baseState,r=n.choice[e.type];return r||s(!1,e.type+" not found in "+JSON.stringify(Object.keys(n.choice))),r._encode(e.value,t)},c.prototype._encodePrimitive=function(e,t){const n=this._baseState;if(/str$/.test(e))return this._encodeStr(t,e);if("objid"===e&&n.args)return this._encodeObjid(t,n.reverseArgs[0],n.args[1]);if("objid"===e)return this._encodeObjid(t,null,null);if("gentime"===e||"utctime"===e)return this._encodeTime(t,e);if("null_"===e)return this._encodeNull();if("int"===e||"enum"===e)return this._encodeInt(t,n.args&&n.reverseArgs[0]);if("bool"===e)return this._encodeBool(t);if("objDesc"===e)return this._encodeStr(t,e);throw new Error("Unsupported tag: "+e)},c.prototype._isNumstr=function(e){return/^[0-9 ]*$/.test(e)},c.prototype._isPrintstr=function(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(e)}},function(e,t,n){"use strict";const r=n(7);function i(e){this._reporterState={obj:null,path:[],options:e||{},errors:[]}}function o(e,t){this.path=e,this.rethrow(t)}t.Reporter=i,i.prototype.isError=function(e){return e instanceof o},i.prototype.save=function(){const e=this._reporterState;return{obj:e.obj,pathLen:e.path.length}},i.prototype.restore=function(e){const t=this._reporterState;t.obj=e.obj,t.path=t.path.slice(0,e.pathLen)},i.prototype.enterKey=function(e){return this._reporterState.path.push(e)},i.prototype.exitKey=function(e){const t=this._reporterState;t.path=t.path.slice(0,e-1)},i.prototype.leaveKey=function(e,t,n){const r=this._reporterState;this.exitKey(e),null!==r.obj&&(r.obj[t]=n)},i.prototype.path=function(){return this._reporterState.path.join("/")},i.prototype.enterObject=function(){const e=this._reporterState,t=e.obj;return e.obj={},t},i.prototype.leaveObject=function(e){const t=this._reporterState,n=t.obj;return t.obj=e,n},i.prototype.error=function(e){let t;const n=this._reporterState,r=e instanceof o;if(t=r?e:new o(n.path.map((function(e){return"["+JSON.stringify(e)+"]"})).join(""),e.message||e,e.stack),!n.options.partial)throw t;return r||n.errors.push(t),t},i.prototype.wrapResult=function(e){const t=this._reporterState;return t.options.partial?{result:this.isError(e)?null:e,errors:t.errors}:e},r(o,Error),o.prototype.rethrow=function(e){if(this.message=e+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,o),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}},function(e,t,n){"use strict";function r(e){const t={};return Object.keys(e).forEach((function(n){(0|n)==n&&(n|=0);const r=e[n];t[r]=n})),t}t.tagClass={0:"universal",1:"application",2:"context",3:"private"},t.tagClassByName=r(t.tagClass),t.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},t.tagByName=r(t.tag)},function(e,t,n){"use strict";n.r(t),n.d(t,"locateWindow",(function(){return i}));var r={};function i(){return"undefined"!=typeof window?window:"undefined"!=typeof self?self:r}},function(e,t,n){var r=n(84),i=n(85);e.exports=function(e){return"symbol"==typeof e||i(e)&&"[object Symbol]"==r(e)}},function(e,t,n){var r=n(395),i=n(411),o=n(413),s=n(414),a=n(415);function u(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]/g,">").replace(/"/g,""")+'"')}}catch(t){e={error:t}}finally{try{s&&!s.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}return r+(n?">"+this.children.map((function(e){return e.toString()})).join("")+"":"/>")},e}();var ti=function(){function e(e){this.value=e}return e.prototype.toString=function(){return(""+this.value).replace(/&/g,"&").replace(//g,">")},e}(),ni=n(253),ri=function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c;return d(this,(function(l){switch(l.label){case 0:return r=[f({},e)],c={},[4,Ai(e.body,t)];case 1:switch(n=f.apply(void 0,r.concat([(c.body=l.sent(),c)])),o="UnknownError",o=Ii(e,n.body),o){case"NoSuchUpload":case"com.amazonaws.s3#NoSuchUpload":return[3,2]}return[3,4];case 2:return s=[{}],[4,pi(n,t)];case 3:return i=f.apply(void 0,[f.apply(void 0,s.concat([l.sent()])),{name:o,$metadata:Si(e)}]),[3,5];case 4:a=n.body,o=a.code||a.Code||o,i=f(f({},a),{name:""+o,message:a.message||a.Message||o,$fault:"client",$metadata:Si(e)}),l.label=5;case 5:return u=i.message||i.Message||o,i.message=u,delete i.Message,[2,Promise.reject(Object.assign(new Error(u),i))]}}))}))},ii=function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u;return d(this,(function(c){switch(c.label){case 0:return r=[f({},e)],u={},[4,Ai(e.body,t)];case 1:return n=f.apply(void 0,r.concat([(u.body=c.sent(),u)])),o="UnknownError",o=Ii(e,n.body),s=n.body,o=s.code||s.Code||o,i=f(f({},s),{name:""+o,message:s.message||s.Message||o,$fault:"client",$metadata:Si(e)}),a=i.message||i.Message||o,i.message=a,delete i.Message,[2,Promise.reject(Object.assign(new Error(a),i))]}}))}))},oi=function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u;return d(this,(function(c){switch(c.label){case 0:return r=[f({},e)],u={},[4,Ai(e.body,t)];case 1:return n=f.apply(void 0,r.concat([(u.body=c.sent(),u)])),o="UnknownError",o=Ii(e,n.body),s=n.body,o=s.code||s.Code||o,i=f(f({},s),{name:""+o,message:s.message||s.Message||o,$fault:"client",$metadata:Si(e)}),a=i.message||i.Message||o,i.message=a,delete i.Message,[2,Promise.reject(Object.assign(new Error(a),i))]}}))}))},si=function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u;return d(this,(function(c){switch(c.label){case 0:return r=[f({},e)],u={},[4,Ai(e.body,t)];case 1:return n=f.apply(void 0,r.concat([(u.body=c.sent(),u)])),o="UnknownError",o=Ii(e,n.body),s=n.body,o=s.code||s.Code||o,i=f(f({},s),{name:""+o,message:s.message||s.Message||o,$fault:"client",$metadata:Si(e)}),a=i.message||i.Message||o,i.message=a,delete i.Message,[2,Promise.reject(Object.assign(new Error(a),i))]}}))}))},ai=function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c;return d(this,(function(l){switch(l.label){case 0:return r=[f({},e)],c={},[4,Ai(e.body,t)];case 1:switch(n=f.apply(void 0,r.concat([(c.body=l.sent(),c)])),o="UnknownError",o=Ii(e,n.body),o){case"NoSuchKey":case"com.amazonaws.s3#NoSuchKey":return[3,2]}return[3,4];case 2:return s=[{}],[4,hi(n,t)];case 3:return i=f.apply(void 0,[f.apply(void 0,s.concat([l.sent()])),{name:o,$metadata:Si(e)}]),[3,5];case 4:a=n.body,o=a.code||a.Code||o,i=f(f({},a),{name:""+o,message:a.message||a.Message||o,$fault:"client",$metadata:Si(e)}),l.label=5;case 5:return u=i.message||i.Message||o,i.message=u,delete i.Message,[2,Promise.reject(Object.assign(new Error(u),i))]}}))}))},ui=function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c;return d(this,(function(l){switch(l.label){case 0:return r=[f({},e)],c={},[4,Ai(e.body,t)];case 1:switch(n=f.apply(void 0,r.concat([(c.body=l.sent(),c)])),o="UnknownError",o=Ii(e,n.body),o){case"NoSuchBucket":case"com.amazonaws.s3#NoSuchBucket":return[3,2]}return[3,4];case 2:return s=[{}],[4,di(n,t)];case 3:return i=f.apply(void 0,[f.apply(void 0,s.concat([l.sent()])),{name:o,$metadata:Si(e)}]),[3,5];case 4:a=n.body,o=a.code||a.Code||o,i=f(f({},a),{name:""+o,message:a.message||a.Message||o,$fault:"client",$metadata:Si(e)}),l.label=5;case 5:return u=i.message||i.Message||o,i.message=u,delete i.Message,[2,Promise.reject(Object.assign(new Error(u),i))]}}))}))},ci=function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u;return d(this,(function(c){switch(c.label){case 0:return r=[f({},e)],u={},[4,Ai(e.body,t)];case 1:return n=f.apply(void 0,r.concat([(u.body=c.sent(),u)])),o="UnknownError",o=Ii(e,n.body),s=n.body,o=s.code||s.Code||o,i=f(f({},s),{name:""+o,message:s.message||s.Message||o,$fault:"client",$metadata:Si(e)}),a=i.message||i.Message||o,i.message=a,delete i.Message,[2,Promise.reject(Object.assign(new Error(a),i))]}}))}))},fi=function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u;return d(this,(function(c){switch(c.label){case 0:return r=[f({},e)],u={},[4,Ai(e.body,t)];case 1:return n=f.apply(void 0,r.concat([(u.body=c.sent(),u)])),o="UnknownError",o=Ii(e,n.body),s=n.body,o=s.code||s.Code||o,i=f(f({},s),{name:""+o,message:s.message||s.Message||o,$fault:"client",$metadata:Si(e)}),a=i.message||i.Message||o,i.message=a,delete i.Message,[2,Promise.reject(Object.assign(new Error(a),i))]}}))}))},li=function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u;return d(this,(function(c){switch(c.label){case 0:return r=[f({},e)],u={},[4,Ai(e.body,t)];case 1:return n=f.apply(void 0,r.concat([(u.body=c.sent(),u)])),o="UnknownError",o=Ii(e,n.body),s=n.body,o=s.code||s.Code||o,i=f(f({},s),{name:""+o,message:s.message||s.Message||o,$fault:"client",$metadata:Si(e)}),a=i.message||i.Message||o,i.message=a,delete i.Message,[2,Promise.reject(Object.assign(new Error(a),i))]}}))}))},di=function(e,t){return l(void 0,void 0,void 0,(function(){var t;return d(this,(function(n){return t={name:"NoSuchBucket",$fault:"client",$metadata:Si(e)},e.body,[2,t]}))}))},hi=function(e,t){return l(void 0,void 0,void 0,(function(){var t;return d(this,(function(n){return t={name:"NoSuchKey",$fault:"client",$metadata:Si(e)},e.body,[2,t]}))}))},pi=function(e,t){return l(void 0,void 0,void 0,(function(){var t;return d(this,(function(n){return t={name:"NoSuchUpload",$fault:"client",$metadata:Si(e)},e.body,[2,t]}))}))},vi=function(e,t){var n=new ei("CompletedMultipartUpload");void 0!==e.Parts&&gi(e.Parts,t).map((function(e){e=e.withName("Part"),n.addChildNode(e)}));return n},gi=function(e,t){return e.map((function(e){return function(e,t){var n=new ei("CompletedPart");if(void 0!==e.ETag){var r=new ei("ETag").addChildNode(new ti(e.ETag)).withName("ETag");n.addChildNode(r)}if(void 0!==e.PartNumber){r=new ei("PartNumber").addChildNode(new ti(String(e.PartNumber))).withName("PartNumber");n.addChildNode(r)}return n}(e).withName("member")}))},mi=function(e,t){return(e||[]).map((function(e){return function(e,t){var n={Prefix:void 0};return void 0!==e.Prefix&&(n.Prefix=e.Prefix),n}(e)}))},bi=function(e,t){var n={ID:void 0,DisplayName:void 0};return void 0!==e.ID&&(n.ID=e.ID),void 0!==e.DisplayName&&(n.DisplayName=e.DisplayName),n},yi=function(e,t){return(e||[]).map((function(e){return function(e,t){var n={Size:void 0,ETag:void 0,Owner:void 0,StorageClass:void 0,Key:void 0,LastModified:void 0};return void 0!==e.Size&&(n.Size=parseInt(e.Size)),void 0!==e.ETag&&(n.ETag=e.ETag),void 0!==e.Owner&&(n.Owner=wi(e.Owner,t)),void 0!==e.StorageClass&&(n.StorageClass=e.StorageClass),void 0!==e.Key&&(n.Key=e.Key),void 0!==e.LastModified&&(n.LastModified=new Date(e.LastModified)),n}(e,t)}))},wi=function(e,t){var n={DisplayName:void 0,ID:void 0};return void 0!==e.DisplayName&&(n.DisplayName=e.DisplayName),void 0!==e.ID&&(n.ID=e.ID),n},_i=function(e,t){return(e||[]).map((function(e){return function(e,t){var n={Size:void 0,LastModified:void 0,PartNumber:void 0,ETag:void 0};return void 0!==e.Size&&(n.Size=parseInt(e.Size)),void 0!==e.LastModified&&(n.LastModified=new Date(e.LastModified)),void 0!==e.PartNumber&&(n.PartNumber=parseInt(e.PartNumber)),void 0!==e.ETag&&(n.ETag=e.ETag),n}(e)}))},Si=function(e){return{httpStatusCode:e.statusCode,httpHeaders:e.headers,requestId:e.headers["x-amzn-requestid"]}},Ei=function(e,t){return void 0===e&&(e=new Uint8Array),e instanceof Uint8Array?Promise.resolve(e):t.streamCollector(e)||Promise.resolve(new Uint8Array)},Mi=function(e){return!(void 0===e||""===e||Object.getOwnPropertyNames(e).includes("length")&&0==e.length||Object.getOwnPropertyNames(e).includes("size")&&0==e.size)},Ai=function(e,t){return function(e,t){return Ei(e,t).then((function(e){return t.utf8Encoder(e)}))}(e,t).then((function(e){if(e.length){var t=Object(ni.parse)(e,{attributeNamePrefix:"",ignoreAttributes:!1,parseNodeValue:!1,tagValueProcessor:function(e,t){return e.replace(/&/g,"&").replace(/'/g,"'").replace(/"/g,'"').replace(/>/g,">").replace(/</g,"<")}}),n=Object.keys(t)[0],r=t[n];return r["#text"]&&(r[n]=r["#text"],delete r["#text"]),Object(Zr.h)(r)}return{}}))},Ii=function(e,t){return void 0!==t.Code?t.Code:404==e.statusCode?"NotFound":""},ki=function(e){return"string"==typeof e&&0===e.indexOf("arn:")&&e.split(":").length>=6},Oi=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,xi=/(\d+\.){3}\d+/,Ci=/\.\./,Ti=/\./,Pi=/^(.+\.)?s3[.-]([a-z0-9-]+)\./,Ni=/^s3(-external-1)?\.amazonaws\.com$/,Ri=function(e){return ji(e)?e.replace(/fips-|-fips/,""):e},Li=function(e){var t=e.match(Pi);return[t[2],e.replace(new RegExp("^"+t[0]),"")]},ji=function(e){return e.startsWith("fips-")||e.endsWith("-fips")},Di=function(e,t){return e===t||Ri(e)===t||e===Ri(t)},Ui=function(e,t){if(void 0===t&&(t={tlsCompatible:!0}),e.length>=64||!/^[a-z0-9][a-z0-9.-]+[a-z0-9]$/.test(e)||/(\d+\.){3}\d+/.test(e)||/[.-]{2}/.test(e)||(null==t?void 0:t.tlsCompatible)&&Ti.test(e))throw new Error("Invalid DNS label "+e)},Bi=function(e){var t=e.baseHostname;return Pi.test(t)?function(e){return"string"==typeof e.bucketName}(e)?zi(e):Fi(e):{bucketEndpoint:!1,hostname:t}},Fi=function(e){var t,n=Object(Qr.__read)((t=e.baseHostname,Ni.test(t)?[t.replace(".amazonaws.com",""),"amazonaws.com"]:Li(t)),2),r=n[0],i=n[1],o=e.pathStyleEndpoint,s=e.dualstackEndpoint,a=void 0!==s&&s,u=e.accelerateEndpoint,c=void 0!==u&&u,f=e.tlsCompatible,l=void 0===f||f,d=e.useArnRegion,h=e.bucketName,p=e.clientPartition,v=void 0===p?"aws":p,g=e.clientSigningRegion,m=void 0===g?r:g;!function(e){if(e.pathStyleEndpoint)throw new Error("Path-style S3 endpoint is not supported when bucket is an ARN");if(e.accelerateEndpoint)throw new Error("Accelerate endpoint is not supported when bucket is an ARN");if(!e.tlsCompatible)throw new Error("HTTPS is required when bucket is an ARN")}({pathStyleEndpoint:o,accelerateEndpoint:c,tlsCompatible:l});var b=h.service,y=h.partition,w=h.accountId,_=h.region,S=h.resource;!function(e){if("s3"!==e&&"s3-outposts"!==e)throw new Error("Expect 's3' or 's3-outposts' in ARN service component")}(b),function(e,t){if(e!==t.clientPartition)throw new Error('Partition in ARN is incompatible, got "'+e+'" but expected "'+t.clientPartition+'"')}(y,{clientPartition:v}),function(e){if(!/[0-9]{12}/.exec(e))throw new Error("Access point ARN accountID does not match regex '[0-9]{12}'")}(w),function(e,t){if(""===e)throw new Error("ARN region is empty");if(!t.useArnRegion&&!Di(e,t.clientRegion)&&!Di(e,t.clientSigningRegion))throw new Error("Region in ARN is incompatible, got "+e+" but expected "+t.clientRegion);if(t.useArnRegion&&ji(e))throw new Error("Endpoint does not support FIPS region")}(_,{useArnRegion:d,clientRegion:r,clientSigningRegion:m});var E=function(e){var t=e.includes(":")?":":"/",n=Object(Qr.__read)(e.split(t)),r=n[0],i=n.slice(1);if("accesspoint"===r){if(1!==i.length||""===i[0])throw new Error("Access Point ARN should have one resource accesspoint"+t+"{accesspointname}");return{accesspointName:i[0]}}if("outpost"===r){if(!i[0]||"accesspoint"!==i[1]||!i[2]||3!==i.length)throw new Error("Outpost ARN should have resource outpost"+t+"{outpostId}"+t+"accesspoint"+t+"{accesspointName}");var o=Object(Qr.__read)(i,3),s=o[0];o[1];return{outpostId:s,accesspointName:o[2]}}throw new Error("ARN resource should begin with 'accesspoint"+t+"' or 'outpost"+t+"'")}(S),M=E.accesspointName,A=E.outpostId;Ui(M+"-"+w,{tlsCompatible:l});var I=d?_:r,k=d?_:m;return A?(function(e){if("s3-outposts"!==e)throw new Error("Expect 's3-posts' in Outpost ARN service component")}(b),Ui(A,{tlsCompatible:l}),function(e){if(e)throw new Error("Dualstack endpoint is not supported with Outpost")}(a),function(e){if(ji(null!=e?e:""))throw new Error("FIPS region is not supported with Outpost, got "+e)}(I),{bucketEndpoint:!0,hostname:M+"-"+w+"."+A+".s3-outposts."+I+"."+i,signingRegion:k,signingService:"s3-outposts"}):(function(e){if("s3"!==e)throw new Error("Expect 's3' in Accesspoint ARN service component")}(b),{bucketEndpoint:!0,hostname:M+"-"+w+".s3-accesspoint"+(a?".dualstack":"")+"."+I+"."+i,signingRegion:k})},zi=function(e){var t,n=e.accelerateEndpoint,r=void 0!==n&&n,i=e.baseHostname,o=e.bucketName,s=e.dualstackEndpoint,a=void 0!==s&&s,u=e.pathStyleEndpoint,c=void 0!==u&&u,f=e.tlsCompatible,l=void 0===f||f,d=Object(Qr.__read)((t=i,Ni.test(t)?["us-east-1","amazonaws.com"]:Li(t)),2),h=d[0],p=d[1];return c||!function(e){return Oi.test(e)&&!xi.test(e)&&!Ci.test(e)}(o)||l&&Ti.test(o)?{bucketEndpoint:!1,hostname:a?"s3.dualstack."+h+"."+p:i}:(r?i="s3-accelerate"+(a?".dualstack":"")+"."+p:a&&(i="s3.dualstack."+h+"."+p),{bucketEndpoint:!0,hostname:o+"."+i})},qi=function(e){return function(t,n){return function(r){return Object(Qr.__awaiter)(void 0,void 0,void 0,(function(){var i,o,s,a,u,c,f,l,d,h,p,v,g,m,b,y,w;return Object(Qr.__generator)(this,(function(_){switch(_.label){case 0:return i=r.input.Bucket,o=e.bucketEndpoint,s=r.request,Xr.a.isInstance(s)?e.bucketEndpoint?(s.hostname=i,[3,6]):[3,1]:[3,7];case 1:return ki(i)?(a=function(e){var t=e.split(":");if(t.length<6||"arn"!==t[0])throw new Error("Malformed ARN");var n=Object(Qr.__read)(t);return{partition:n[1],service:n[2],region:n[3],accountId:n[4],resource:n.slice(5).join(":")}}(i),c=Ri,[4,e.region()]):[3,5];case 2:return u=c.apply(void 0,[_.sent()]),[4,e.regionInfoProvider(u)];case 3:return f=_.sent()||{},l=f.partition,d=f.signingRegion,h=void 0===d?u:d,[4,e.useArnRegion()];case 4:return p=_.sent(),v=Bi({bucketName:a,baseHostname:s.hostname,accelerateEndpoint:e.useAccelerateEndpoint,dualstackEndpoint:e.useDualstackEndpoint,pathStyleEndpoint:e.forcePathStyle,tlsCompatible:"https:"===s.protocol,useArnRegion:p,clientPartition:l,clientSigningRegion:h}),y=v.hostname,w=v.bucketEndpoint,g=v.signingRegion,m=v.signingService,g&&g!==h&&(n.signing_region=g),m&&"s3"!==m&&(n.signing_service=m),s.hostname=y,o=w,[3,6];case 5:b=Bi({bucketName:i,baseHostname:s.hostname,accelerateEndpoint:e.useAccelerateEndpoint,dualstackEndpoint:e.useDualstackEndpoint,pathStyleEndpoint:e.forcePathStyle,tlsCompatible:"https:"===s.protocol}),y=b.hostname,w=b.bucketEndpoint,s.hostname=y,o=w,_.label=6;case 6:o&&(s.path=s.path.replace(/^(\/)?[^\/]+/,""),""===s.path&&(s.path="/")),_.label=7;case 7:return[2,t(Object(Qr.__assign)(Object(Qr.__assign)({},r),{request:s}))]}}))}))}}},Ki={tags:["BUCKET_ENDPOINT"],name:"bucketEndpointMiddleware",relation:"before",toMiddleware:"hostHeaderMiddleware"},Hi=function(e){return{applyToStack:function(t){t.addRelativeTo(qi(e),Ki)}}};var Vi=n(10);var Gi={name:"ssecMiddleware",step:"initialize",tags:["SSE"]},Wi=function(e){return{applyToStack:function(t){t.add(function(e){var t=this;return function(n){return function(r){return Object(Qr.__awaiter)(t,void 0,void 0,(function(){var t,i,o,s,a,u,c,f,l,d,h,p,v,g,m,b,y;return Object(Qr.__generator)(this,(function(w){switch(w.label){case 0:t=Object(Qr.__assign)({},r.input),i=[{target:"SSECustomerKey",hash:"SSECustomerKeyMD5"},{target:"CopySourceSSECustomerKey",hash:"CopySourceSSECustomerKeyMD5"}],w.label=1;case 1:w.trys.push([1,6,7,8]),o=Object(Qr.__values)(i),s=o.next(),w.label=2;case 2:return s.done?[3,5]:(a=s.value,(u=t[a.target])?(c=ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):"string"==typeof u?e.utf8Decoder(u):new Uint8Array(u),f=e.base64Encoder(c),(l=new e.md5).update(c),d=[Object(Qr.__assign)({},t)],(y={})[a.target]=f,h=a.hash,v=(p=e).base64Encoder,[4,l.digest()]):[3,4]);case 3:t=Qr.__assign.apply(void 0,d.concat([(y[h]=v.apply(p,[w.sent()]),y)])),w.label=4;case 4:return s=o.next(),[3,2];case 5:return[3,8];case 6:return g=w.sent(),m={error:g},[3,8];case 7:try{s&&!s.done&&(b=o.return)&&b.call(o)}finally{if(m)throw m.error}return[7];case 8:return[2,n(Object(Qr.__assign)(Object(Qr.__assign)({},r),{input:t}))]}}))}))}}}(e),Gi)}}},$i=function(e){function t(t){var n=e.call(this)||this;return n.input=t,n}return c(t,e),t.prototype.resolveMiddleware=function(e,t,n){this.middlewareStack.use(Object(Vi.a)(t,this.serialize,this.deserialize)),this.middlewareStack.use(Wi(t)),this.middlewareStack.use(Hi(t));var r=e.concat(this.middlewareStack),i=t.logger,o={logger:i,clientName:"S3Client",commandName:"GetObjectCommand",inputFilterSensitiveLog:Xt.filterSensitiveLog,outputFilterSensitiveLog:Zt.filterSensitiveLog};"function"==typeof i.info&&i.info({clientName:"S3Client",commandName:"GetObjectCommand"});var s=t.requestHandler;return r.resolve((function(e){return s.handle(e.request,n||{})}),o)},t.prototype.serialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,l;return d(this,(function(d){switch(d.label){case 0:if(n=f(f(f(f(f(f(f(f(f(f({"Content-Type":""},Mi(e.SSECustomerKey)&&{"x-amz-server-side-encryption-customer-key":e.SSECustomerKey}),Mi(e.SSECustomerAlgorithm)&&{"x-amz-server-side-encryption-customer-algorithm":e.SSECustomerAlgorithm}),Mi(e.SSECustomerKeyMD5)&&{"x-amz-server-side-encryption-customer-key-MD5":e.SSECustomerKeyMD5}),Mi(e.RequestPayer)&&{"x-amz-request-payer":e.RequestPayer}),Mi(e.ExpectedBucketOwner)&&{"x-amz-expected-bucket-owner":e.ExpectedBucketOwner}),Mi(e.IfUnmodifiedSince)&&{"If-Unmodified-Since":Object(Zr.e)(e.IfUnmodifiedSince).toString()}),Mi(e.IfModifiedSince)&&{"If-Modified-Since":Object(Zr.e)(e.IfModifiedSince).toString()}),Mi(e.IfNoneMatch)&&{"If-None-Match":e.IfNoneMatch}),Mi(e.IfMatch)&&{"If-Match":e.IfMatch}),Mi(e.Range)&&{Range:e.Range}),r="/{Bucket}/{Key+}",void 0===e.Bucket)throw new Error("No value provided for input HTTP label: Bucket.");if((i=e.Bucket).length<=0)throw new Error("Empty value provided for input HTTP label: Bucket.");if(r=r.replace("{Bucket}",Object(Zr.f)(i)),void 0===e.Key)throw new Error("No value provided for input HTTP label: Key.");if((i=e.Key).length<=0)throw new Error("Empty value provided for input HTTP label: Key.");return r=r.replace("{Key+}",i.split("/").map((function(e){return Object(Zr.f)(e)})).join("/")),o=f(f(f(f(f(f(f(f({"x-id":"GetObject"},void 0!==e.ResponseContentEncoding&&{"response-content-encoding":e.ResponseContentEncoding}),void 0!==e.ResponseCacheControl&&{"response-cache-control":e.ResponseCacheControl}),void 0!==e.ResponseContentLanguage&&{"response-content-language":e.ResponseContentLanguage}),void 0!==e.ResponseContentDisposition&&{"response-content-disposition":e.ResponseContentDisposition}),void 0!==e.PartNumber&&{partNumber:e.PartNumber.toString()}),void 0!==e.VersionId&&{versionId:e.VersionId}),void 0!==e.ResponseExpires&&{"response-expires":(e.ResponseExpires.toISOString().split(".")[0]+"Z").toString()}),void 0!==e.ResponseContentType&&{"response-content-type":e.ResponseContentType}),[4,t.endpoint()];case 1:return s=d.sent(),a=s.hostname,u=s.protocol,c=void 0===u?"https":u,l=s.port,[2,new Xr.a({protocol:c,hostname:a,port:l,method:"GET",headers:n,path:r,query:o,body:void 0})]}}))}))}(e,t)},t.prototype.deserialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n,r;return d(this,(function(i){return 200!==e.statusCode&&e.statusCode>=300?[2,ai(e,t)]:(n={$metadata:Si(e),AcceptRanges:void 0,Body:void 0,CacheControl:void 0,ContentDisposition:void 0,ContentEncoding:void 0,ContentLanguage:void 0,ContentLength:void 0,ContentRange:void 0,ContentType:void 0,DeleteMarker:void 0,ETag:void 0,Expiration:void 0,Expires:void 0,LastModified:void 0,Metadata:void 0,MissingMeta:void 0,ObjectLockLegalHoldStatus:void 0,ObjectLockMode:void 0,ObjectLockRetainUntilDate:void 0,PartsCount:void 0,ReplicationStatus:void 0,RequestCharged:void 0,Restore:void 0,SSECustomerAlgorithm:void 0,SSECustomerKeyMD5:void 0,SSEKMSKeyId:void 0,ServerSideEncryption:void 0,StorageClass:void 0,TagCount:void 0,VersionId:void 0,WebsiteRedirectLocation:void 0},void 0!==e.headers["x-amz-object-lock-mode"]&&(n.ObjectLockMode=e.headers["x-amz-object-lock-mode"]),void 0!==e.headers["content-language"]&&(n.ContentLanguage=e.headers["content-language"]),void 0!==e.headers["content-disposition"]&&(n.ContentDisposition=e.headers["content-disposition"]),void 0!==e.headers["cache-control"]&&(n.CacheControl=e.headers["cache-control"]),void 0!==e.headers["content-type"]&&(n.ContentType=e.headers["content-type"]),void 0!==e.headers["content-range"]&&(n.ContentRange=e.headers["content-range"]),void 0!==e.headers["x-amz-server-side-encryption-aws-kms-key-id"]&&(n.SSEKMSKeyId=e.headers["x-amz-server-side-encryption-aws-kms-key-id"]),void 0!==e.headers["content-length"]&&(n.ContentLength=parseInt(e.headers["content-length"],10)),void 0!==e.headers["x-amz-object-lock-retain-until-date"]&&(n.ObjectLockRetainUntilDate=new Date(e.headers["x-amz-object-lock-retain-until-date"])),void 0!==e.headers["x-amz-object-lock-legal-hold"]&&(n.ObjectLockLegalHoldStatus=e.headers["x-amz-object-lock-legal-hold"]),void 0!==e.headers["x-amz-delete-marker"]&&(n.DeleteMarker="true"===e.headers["x-amz-delete-marker"]),void 0!==e.headers["x-amz-storage-class"]&&(n.StorageClass=e.headers["x-amz-storage-class"]),void 0!==e.headers["content-encoding"]&&(n.ContentEncoding=e.headers["content-encoding"]),void 0!==e.headers["x-amz-restore"]&&(n.Restore=e.headers["x-amz-restore"]),void 0!==e.headers["x-amz-website-redirect-location"]&&(n.WebsiteRedirectLocation=e.headers["x-amz-website-redirect-location"]),void 0!==e.headers["x-amz-server-side-encryption"]&&(n.ServerSideEncryption=e.headers["x-amz-server-side-encryption"]),void 0!==e.headers["x-amz-mp-parts-count"]&&(n.PartsCount=parseInt(e.headers["x-amz-mp-parts-count"],10)),void 0!==e.headers["x-amz-server-side-encryption-customer-algorithm"]&&(n.SSECustomerAlgorithm=e.headers["x-amz-server-side-encryption-customer-algorithm"]),void 0!==e.headers["accept-ranges"]&&(n.AcceptRanges=e.headers["accept-ranges"]),void 0!==e.headers["x-amz-version-id"]&&(n.VersionId=e.headers["x-amz-version-id"]),void 0!==e.headers.expires&&(n.Expires=new Date(e.headers.expires)),void 0!==e.headers["x-amz-expiration"]&&(n.Expiration=e.headers["x-amz-expiration"]),void 0!==e.headers["x-amz-missing-meta"]&&(n.MissingMeta=parseInt(e.headers["x-amz-missing-meta"],10)),void 0!==e.headers["x-amz-replication-status"]&&(n.ReplicationStatus=e.headers["x-amz-replication-status"]),void 0!==e.headers["x-amz-tagging-count"]&&(n.TagCount=parseInt(e.headers["x-amz-tagging-count"],10)),void 0!==e.headers["x-amz-server-side-encryption-customer-key-md5"]&&(n.SSECustomerKeyMD5=e.headers["x-amz-server-side-encryption-customer-key-md5"]),void 0!==e.headers["last-modified"]&&(n.LastModified=new Date(e.headers["last-modified"])),void 0!==e.headers.etag&&(n.ETag=e.headers.etag),void 0!==e.headers["x-amz-request-charged"]&&(n.RequestCharged=e.headers["x-amz-request-charged"]),Object.keys(e.headers).forEach((function(t){void 0===n.Metadata&&(n.Metadata={}),t.startsWith("x-amz-meta-")&&(n.Metadata[t.substring(11)]=e.headers[t])})),r=e.body,n.Body=r,[2,Promise.resolve(n)])}))}))}(e,t)},t}(Zr.b),Yi=function(e){function t(t){var n=e.call(this)||this;return n.input=t,n}return c(t,e),t.prototype.resolveMiddleware=function(e,t,n){this.middlewareStack.use(Object(Vi.a)(t,this.serialize,this.deserialize)),this.middlewareStack.use(Hi(t));var r=e.concat(this.middlewareStack),i=t.logger,o={logger:i,clientName:"S3Client",commandName:"DeleteObjectCommand",inputFilterSensitiveLog:Z.filterSensitiveLog,outputFilterSensitiveLog:J.filterSensitiveLog};"function"==typeof i.info&&i.info({clientName:"S3Client",commandName:"DeleteObjectCommand"});var s=t.requestHandler;return r.resolve((function(e){return s.handle(e.request,n||{})}),o)},t.prototype.serialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,l;return d(this,(function(d){switch(d.label){case 0:if(n=f(f(f(f({"Content-Type":""},Mi(e.MFA)&&{"x-amz-mfa":e.MFA}),Mi(e.ExpectedBucketOwner)&&{"x-amz-expected-bucket-owner":e.ExpectedBucketOwner}),Mi(e.BypassGovernanceRetention)&&{"x-amz-bypass-governance-retention":e.BypassGovernanceRetention.toString()}),Mi(e.RequestPayer)&&{"x-amz-request-payer":e.RequestPayer}),r="/{Bucket}/{Key+}",void 0===e.Bucket)throw new Error("No value provided for input HTTP label: Bucket.");if((i=e.Bucket).length<=0)throw new Error("Empty value provided for input HTTP label: Bucket.");if(r=r.replace("{Bucket}",Object(Zr.f)(i)),void 0===e.Key)throw new Error("No value provided for input HTTP label: Key.");if((i=e.Key).length<=0)throw new Error("Empty value provided for input HTTP label: Key.");return r=r.replace("{Key+}",i.split("/").map((function(e){return Object(Zr.f)(e)})).join("/")),o=f({"x-id":"DeleteObject"},void 0!==e.VersionId&&{versionId:e.VersionId}),[4,t.endpoint()];case 1:return s=d.sent(),a=s.hostname,u=s.protocol,c=void 0===u?"https":u,l=s.port,[2,new Xr.a({protocol:c,hostname:a,port:l,method:"DELETE",headers:n,path:r,query:o,body:void 0})]}}))}))}(e,t)},t.prototype.deserialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n;return d(this,(function(r){switch(r.label){case 0:return 204!==e.statusCode&&e.statusCode>=300?[2,si(e,t)]:(n={$metadata:Si(e),DeleteMarker:void 0,RequestCharged:void 0,VersionId:void 0},void 0!==e.headers["x-amz-delete-marker"]&&(n.DeleteMarker="true"===e.headers["x-amz-delete-marker"]),void 0!==e.headers["x-amz-request-charged"]&&(n.RequestCharged=e.headers["x-amz-request-charged"]),void 0!==e.headers["x-amz-version-id"]&&(n.VersionId=e.headers["x-amz-version-id"]),[4,Ei(e.body,t)]);case 1:return r.sent(),[2,Promise.resolve(n)]}}))}))}(e,t)},t}(Zr.b),Ji=function(e){function t(t){var n=e.call(this)||this;return n.input=t,n}return c(t,e),t.prototype.resolveMiddleware=function(e,t,n){this.middlewareStack.use(Object(Vi.a)(t,this.serialize,this.deserialize)),this.middlewareStack.use(Hi(t));var r=e.concat(this.middlewareStack),i=t.logger,o={logger:i,clientName:"S3Client",commandName:"ListObjectsCommand",inputFilterSensitiveLog:Fn.filterSensitiveLog,outputFilterSensitiveLog:Bn.filterSensitiveLog};"function"==typeof i.info&&i.info({clientName:"S3Client",commandName:"ListObjectsCommand"});var s=t.requestHandler;return r.resolve((function(e){return s.handle(e.request,n||{})}),o)},t.prototype.serialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,l;return d(this,(function(d){switch(d.label){case 0:if(n=f(f({"Content-Type":""},Mi(e.ExpectedBucketOwner)&&{"x-amz-expected-bucket-owner":e.ExpectedBucketOwner}),Mi(e.RequestPayer)&&{"x-amz-request-payer":e.RequestPayer}),r="/{Bucket}",void 0===e.Bucket)throw new Error("No value provided for input HTTP label: Bucket.");if((i=e.Bucket).length<=0)throw new Error("Empty value provided for input HTTP label: Bucket.");return r=r.replace("{Bucket}",Object(Zr.f)(i)),o=f(f(f(f(f({},void 0!==e.MaxKeys&&{"max-keys":e.MaxKeys.toString()}),void 0!==e.Marker&&{marker:e.Marker}),void 0!==e.Prefix&&{prefix:e.Prefix}),void 0!==e.Delimiter&&{delimiter:e.Delimiter}),void 0!==e.EncodingType&&{"encoding-type":e.EncodingType}),[4,t.endpoint()];case 1:return s=d.sent(),a=s.hostname,u=s.protocol,c=void 0===u?"https":u,l=s.port,[2,new Xr.a({protocol:c,hostname:a,port:l,method:"GET",headers:n,path:r,query:o,body:void 0})]}}))}))}(e,t)},t.prototype.deserialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n,r;return d(this,(function(i){switch(i.label){case 0:return 200!==e.statusCode&&e.statusCode>=300?[2,ui(e,t)]:(n={$metadata:Si(e),CommonPrefixes:void 0,Contents:void 0,Delimiter:void 0,EncodingType:void 0,IsTruncated:void 0,Marker:void 0,MaxKeys:void 0,Name:void 0,NextMarker:void 0,Prefix:void 0},[4,Ai(e.body,t)]);case 1:return""===(r=i.sent()).CommonPrefixes&&(n.CommonPrefixes=[]),void 0!==r.CommonPrefixes&&(n.CommonPrefixes=mi(Object(Zr.g)(r.CommonPrefixes),t)),""===r.Contents&&(n.Contents=[]),void 0!==r.Contents&&(n.Contents=yi(Object(Zr.g)(r.Contents),t)),void 0!==r.Delimiter&&(n.Delimiter=r.Delimiter),void 0!==r.EncodingType&&(n.EncodingType=r.EncodingType),void 0!==r.IsTruncated&&(n.IsTruncated="true"==r.IsTruncated),void 0!==r.Marker&&(n.Marker=r.Marker),void 0!==r.MaxKeys&&(n.MaxKeys=parseInt(r.MaxKeys)),void 0!==r.Name&&(n.Name=r.Name),void 0!==r.NextMarker&&(n.NextMarker=r.NextMarker),void 0!==r.Prefix&&(n.Prefix=r.Prefix),[2,Promise.resolve(n)]}}))}))}(e,t)},t}(Zr.b),Zi=n(153),Xi=n(38),Qi=n(110),eo=n(18);function to(e,t,n){return void 0===n&&(n=1048576),new Promise((function(r,i){var o=new FileReader;o.addEventListener("error",i),o.addEventListener("abort",i);var s=e.size,a=0;function u(){a>=s?r():o.readAsArrayBuffer(e.slice(a,Math.min(s,a+n)))}o.addEventListener("load",(function(e){var n=e.target.result;t(new Uint8Array(n)),a+=n.byteLength,u()})),u()}))}var no=n(24),ro=n(15),io=[1732584193,4023233417,2562383102,271733878],oo=function(){function e(){this.state=Uint32Array.from(io),this.buffer=new DataView(new ArrayBuffer(64)),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}return e.prototype.update=function(e){if(!function(e){if("string"==typeof e)return 0===e.length;return 0===e.byteLength}(e)){if(this.finished)throw new Error("Attempted to update an already finished hash.");var t=function(e){if("string"==typeof e)return Object(ro.a)(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT);return new Uint8Array(e)}(e),n=0,r=t.byteLength;for(this.bytesHashed+=r;r>0;)this.buffer.setUint8(this.bufferLength++,t[n++]),r--,64===this.bufferLength&&(this.hashBuffer(),this.bufferLength=0)}},e.prototype.digest=function(){return Object(Qr.__awaiter)(this,void 0,void 0,(function(){var e,t,n,r,i,o,s;return Object(Qr.__generator)(this,(function(a){if(!this.finished){if(t=(e=this).buffer,n=e.bufferLength,r=e.bytesHashed,i=8*r,t.setUint8(this.bufferLength++,128),n%64>=56){for(s=this.bufferLength;s<64;s++)t.setUint8(s,0);this.hashBuffer(),this.bufferLength=0}for(s=this.bufferLength;s<56;s++)t.setUint8(s,0);t.setUint32(56,i>>>0,!0),t.setUint32(60,Math.floor(i/4294967296),!0),this.hashBuffer(),this.finished=!0}for(o=new DataView(new ArrayBuffer(16)),s=0;s<4;s++)o.setUint32(4*s,this.state[s],!0);return[2,new Uint8Array(o.buffer,o.byteOffset,o.byteLength)]}))}))},e.prototype.hashBuffer=function(){var e=this.buffer,t=this.state,n=t[0],r=t[1],i=t[2],o=t[3];n=ao(n,r,i,o,e.getUint32(0,!0),7,3614090360),o=ao(o,n,r,i,e.getUint32(4,!0),12,3905402710),i=ao(i,o,n,r,e.getUint32(8,!0),17,606105819),r=ao(r,i,o,n,e.getUint32(12,!0),22,3250441966),n=ao(n,r,i,o,e.getUint32(16,!0),7,4118548399),o=ao(o,n,r,i,e.getUint32(20,!0),12,1200080426),i=ao(i,o,n,r,e.getUint32(24,!0),17,2821735955),r=ao(r,i,o,n,e.getUint32(28,!0),22,4249261313),n=ao(n,r,i,o,e.getUint32(32,!0),7,1770035416),o=ao(o,n,r,i,e.getUint32(36,!0),12,2336552879),i=ao(i,o,n,r,e.getUint32(40,!0),17,4294925233),r=ao(r,i,o,n,e.getUint32(44,!0),22,2304563134),n=ao(n,r,i,o,e.getUint32(48,!0),7,1804603682),o=ao(o,n,r,i,e.getUint32(52,!0),12,4254626195),i=ao(i,o,n,r,e.getUint32(56,!0),17,2792965006),n=uo(n,r=ao(r,i,o,n,e.getUint32(60,!0),22,1236535329),i,o,e.getUint32(4,!0),5,4129170786),o=uo(o,n,r,i,e.getUint32(24,!0),9,3225465664),i=uo(i,o,n,r,e.getUint32(44,!0),14,643717713),r=uo(r,i,o,n,e.getUint32(0,!0),20,3921069994),n=uo(n,r,i,o,e.getUint32(20,!0),5,3593408605),o=uo(o,n,r,i,e.getUint32(40,!0),9,38016083),i=uo(i,o,n,r,e.getUint32(60,!0),14,3634488961),r=uo(r,i,o,n,e.getUint32(16,!0),20,3889429448),n=uo(n,r,i,o,e.getUint32(36,!0),5,568446438),o=uo(o,n,r,i,e.getUint32(56,!0),9,3275163606),i=uo(i,o,n,r,e.getUint32(12,!0),14,4107603335),r=uo(r,i,o,n,e.getUint32(32,!0),20,1163531501),n=uo(n,r,i,o,e.getUint32(52,!0),5,2850285829),o=uo(o,n,r,i,e.getUint32(8,!0),9,4243563512),i=uo(i,o,n,r,e.getUint32(28,!0),14,1735328473),n=co(n,r=uo(r,i,o,n,e.getUint32(48,!0),20,2368359562),i,o,e.getUint32(20,!0),4,4294588738),o=co(o,n,r,i,e.getUint32(32,!0),11,2272392833),i=co(i,o,n,r,e.getUint32(44,!0),16,1839030562),r=co(r,i,o,n,e.getUint32(56,!0),23,4259657740),n=co(n,r,i,o,e.getUint32(4,!0),4,2763975236),o=co(o,n,r,i,e.getUint32(16,!0),11,1272893353),i=co(i,o,n,r,e.getUint32(28,!0),16,4139469664),r=co(r,i,o,n,e.getUint32(40,!0),23,3200236656),n=co(n,r,i,o,e.getUint32(52,!0),4,681279174),o=co(o,n,r,i,e.getUint32(0,!0),11,3936430074),i=co(i,o,n,r,e.getUint32(12,!0),16,3572445317),r=co(r,i,o,n,e.getUint32(24,!0),23,76029189),n=co(n,r,i,o,e.getUint32(36,!0),4,3654602809),o=co(o,n,r,i,e.getUint32(48,!0),11,3873151461),i=co(i,o,n,r,e.getUint32(60,!0),16,530742520),n=fo(n,r=co(r,i,o,n,e.getUint32(8,!0),23,3299628645),i,o,e.getUint32(0,!0),6,4096336452),o=fo(o,n,r,i,e.getUint32(28,!0),10,1126891415),i=fo(i,o,n,r,e.getUint32(56,!0),15,2878612391),r=fo(r,i,o,n,e.getUint32(20,!0),21,4237533241),n=fo(n,r,i,o,e.getUint32(48,!0),6,1700485571),o=fo(o,n,r,i,e.getUint32(12,!0),10,2399980690),i=fo(i,o,n,r,e.getUint32(40,!0),15,4293915773),r=fo(r,i,o,n,e.getUint32(4,!0),21,2240044497),n=fo(n,r,i,o,e.getUint32(32,!0),6,1873313359),o=fo(o,n,r,i,e.getUint32(60,!0),10,4264355552),i=fo(i,o,n,r,e.getUint32(24,!0),15,2734768916),r=fo(r,i,o,n,e.getUint32(52,!0),21,1309151649),n=fo(n,r,i,o,e.getUint32(16,!0),6,4149444226),o=fo(o,n,r,i,e.getUint32(44,!0),10,3174756917),i=fo(i,o,n,r,e.getUint32(8,!0),15,718787259),r=fo(r,i,o,n,e.getUint32(36,!0),21,3951481745),t[0]=n+t[0]&4294967295,t[1]=r+t[1]&4294967295,t[2]=i+t[2]&4294967295,t[3]=o+t[3]&4294967295},e}();function so(e,t,n,r,i,o){return((t=(t+e&4294967295)+(r+o&4294967295)&4294967295)<>>32-i)+n&4294967295}function ao(e,t,n,r,i,o,s){return so(t&n|~t&r,e,t,i,o,s)}function uo(e,t,n,r,i,o,s){return so(t&r|n&~r,e,t,i,o,s)}function co(e,t,n,r,i,o,s){return so(t^n^r,e,t,i,o,s)}function fo(e,t,n,r,i,o,s){return so(n^(t|~r),e,t,i,o,s)}var lo=n(11),ho=n(39),po=n(17),vo=n(40),go=n(41),mo=new Set(["ap-east-1","ap-northeast-1","ap-northeast-2","ap-south-1","ap-southeast-1","ap-southeast-2","ca-central-1","eu-central-1","eu-north-1","eu-west-1","eu-west-2","eu-west-3","me-south-1","sa-east-1","us-east-1","us-east-2","us-west-1","us-west-2"]),bo=new Set(["cn-north-1","cn-northwest-1"]),yo=new Set(["us-iso-east-1"]),wo=new Set(["us-isob-east-1"]),_o=new Set(["us-gov-east-1","us-gov-west-1"]),So=f(f({},{apiVersion:"2006-03-01",disableHostPrefix:!1,logger:{},regionInfoProvider:function(e,t){var n=void 0;switch(e){case"ap-east-1":n={hostname:"s3.ap-east-1.amazonaws.com",partition:"aws"};break;case"ap-northeast-1":n={hostname:"s3.ap-northeast-1.amazonaws.com",partition:"aws"};break;case"ap-northeast-2":n={hostname:"s3.ap-northeast-2.amazonaws.com",partition:"aws"};break;case"ap-south-1":n={hostname:"s3.ap-south-1.amazonaws.com",partition:"aws"};break;case"ap-southeast-1":n={hostname:"s3.ap-southeast-1.amazonaws.com",partition:"aws"};break;case"ap-southeast-2":n={hostname:"s3.ap-southeast-2.amazonaws.com",partition:"aws"};break;case"ca-central-1":n={hostname:"s3.ca-central-1.amazonaws.com",partition:"aws"};break;case"cn-north-1":n={hostname:"s3.cn-north-1.amazonaws.com.cn",partition:"aws-cn"};break;case"cn-northwest-1":n={hostname:"s3.cn-northwest-1.amazonaws.com.cn",partition:"aws-cn"};break;case"eu-central-1":n={hostname:"s3.eu-central-1.amazonaws.com",partition:"aws"};break;case"eu-north-1":n={hostname:"s3.eu-north-1.amazonaws.com",partition:"aws"};break;case"eu-west-1":n={hostname:"s3.eu-west-1.amazonaws.com",partition:"aws"};break;case"eu-west-2":n={hostname:"s3.eu-west-2.amazonaws.com",partition:"aws"};break;case"eu-west-3":n={hostname:"s3.eu-west-3.amazonaws.com",partition:"aws"};break;case"fips-us-gov-west-1":n={hostname:"s3-fips-us-gov-west-1.amazonaws.com",partition:"aws-us-gov",signingRegion:"us-gov-west-1"};break;case"me-south-1":n={hostname:"s3.me-south-1.amazonaws.com",partition:"aws"};break;case"s3-external-1":n={hostname:"s3-external-1.amazonaws.com",partition:"aws",signingRegion:"us-east-1"};break;case"sa-east-1":n={hostname:"s3.sa-east-1.amazonaws.com",partition:"aws"};break;case"us-east-1":n={hostname:"s3.amazonaws.com",partition:"aws"};break;case"us-east-2":n={hostname:"s3.us-east-2.amazonaws.com",partition:"aws"};break;case"us-gov-east-1":n={hostname:"s3.us-gov-east-1.amazonaws.com",partition:"aws-us-gov"};break;case"us-gov-west-1":n={hostname:"s3.us-gov-west-1.amazonaws.com",partition:"aws-us-gov"};break;case"us-iso-east-1":n={hostname:"s3.us-iso-east-1.c2s.ic.gov",partition:"aws-iso"};break;case"us-isob-east-1":n={hostname:"s3.us-isob-east-1.sc2s.sgov.gov",partition:"aws-iso-b"};break;case"us-west-1":n={hostname:"s3.us-west-1.amazonaws.com",partition:"aws"};break;case"us-west-2":n={hostname:"s3.us-west-2.amazonaws.com",partition:"aws"};break;default:mo.has(e)&&(n={hostname:"s3.{region}.amazonaws.com".replace("{region}",e),partition:"aws"}),bo.has(e)&&(n={hostname:"s3.{region}.amazonaws.com.cn".replace("{region}",e),partition:"aws-cn"}),yo.has(e)&&(n={hostname:"s3.{region}.c2s.ic.gov".replace("{region}",e),partition:"aws-iso"}),wo.has(e)&&(n={hostname:"s3.{region}.sc2s.sgov.gov".replace("{region}",e),partition:"aws-iso-b"}),_o.has(e)&&(n={hostname:"s3.{region}.amazonaws.com".replace("{region}",e),partition:"aws-us-gov"}),void 0===n&&(n={hostname:"s3.{region}.amazonaws.com".replace("{region}",e),partition:"aws"})}return Promise.resolve(n)},signingEscapePath:!1,signingName:"s3",useArnRegion:!1}),{runtime:"browser",base64Decoder:po.a,base64Encoder:po.b,bodyLengthChecker:vo.a,credentialDefaultProvider:Object(no.a)("Credential is missing"),defaultUserAgent:Object(go.a)(Zi.name,Zi.version),eventStreamSerdeProvider:Qi.a,maxAttempts:lo.a,md5:oo,region:Object(no.a)("Region is missing"),requestHandler:new eo.a,sha256:Xi.Sha256,streamCollector:eo.b,streamHasher:function(e,t){return Object(Qr.__awaiter)(this,void 0,void 0,(function(){var n;return Object(Qr.__generator)(this,(function(r){switch(r.label){case 0:return n=new e,[4,to(t,(function(e){n.update(e)}))];case 1:return r.sent(),[2,n.digest()]}}))}))},urlParser:ho.a,utf8Decoder:ro.a,utf8Encoder:ro.b}),Eo=n(22),Mo=n(112),Ao=n(37);var Io={step:"build",tags:["SET_EXPECT_HEADER","EXPECT_HEADER"],name:"addExpectContinueMiddleware"},ko=function(e){return{applyToStack:function(t){t.add(function(e){var t=this;return function(n){return function(r){return Object(Qr.__awaiter)(t,void 0,void 0,(function(){var t;return Object(Qr.__generator)(this,(function(i){return t=r.request,Xr.a.isInstance(t)&&t.body&&"node"===e.runtime&&(t.headers=Object(Qr.__assign)(Object(Qr.__assign)({},t.headers),{Expect:"100-continue"})),[2,n(Object(Qr.__assign)(Object(Qr.__assign)({},r),{request:t}))]}))}))}}}(e),Io)}}},Oo=n(21),xo=n(43);var Co={step:"initialize",tags:["VALIDATE_BUCKET_NAME"],name:"validateBucketNameMiddleware"},To=function(e){return{applyToStack:function(e){e.add(function(){var e=this;return function(t){return function(n){return Object(Qr.__awaiter)(e,void 0,void 0,(function(){var e,r;return Object(Qr.__generator)(this,(function(i){if("string"==typeof(e=n.input.Bucket)&&!ki(e)&&e.indexOf("/")>=0)throw(r=new Error("Bucket name shouldn't contain '/', received '"+e+"'")).name="InvalidBucketName",r;return[2,t(Object(Qr.__assign)({},n))]}))}))}}}(),Co)}}},Po={step:"build",tags:["USE_REGIONAL_ENDPOINT","S3"],name:"useRegionalEndpointMiddleware"},No=function(e){return{applyToStack:function(t){t.add(function(e){return function(t){return function(n){return Object(Qr.__awaiter)(void 0,void 0,void 0,(function(){var r,i;return Object(Qr.__generator)(this,(function(o){switch(o.label){case 0:return r=n.request,!Xr.a.isInstance(r)||e.isCustomEndpoint?[2,t(Object(Qr.__assign)({},n))]:"s3.amazonaws.com"!==r.hostname?[3,1]:(r.hostname="s3.us-east-1.amazonaws.com",[3,3]);case 1:return i="aws-global",[4,e.region()];case 2:i===o.sent()&&(r.hostname="s3.amazonaws.com"),o.label=3;case 3:return[2,t(Object(Qr.__assign)({},n))]}}))}))}}}(e),Po)}}},Ro=n(25),Lo=n(23),jo=function(e){function t(t){var n,r,i,o,s,a,u,c,l,d,h,p=this,v=f(f({},So),t),g=Object(Eo.b)(v),m=Object(Eo.a)(g),b=Object(Ro.b)(m),y=Object(lo.c)(b),w=Object(Lo.b)(y),_=(r=(n=w).bucketEndpoint,i=void 0!==r&&r,o=n.forcePathStyle,s=void 0!==o&&o,a=n.useAccelerateEndpoint,u=void 0!==a&&a,c=n.useDualstackEndpoint,l=void 0!==c&&c,d=n.useArnRegion,h=void 0!==d&&d,Object(Qr.__assign)(Object(Qr.__assign)({},n),{bucketEndpoint:i,forcePathStyle:s,useAccelerateEndpoint:u,useDualstackEndpoint:l,useArnRegion:"function"==typeof h?h:function(){return Promise.resolve(h)}})),S=Object(Oo.b)(_),E=Object(Mo.a)(S);return(p=e.call(this,E)||this).config=E,p.middlewareStack.use(Object(Ro.a)(p.config)),p.middlewareStack.use(Object(lo.b)(p.config)),p.middlewareStack.use(Object(Lo.a)(p.config)),p.middlewareStack.use(Object(Ao.a)(p.config)),p.middlewareStack.use(To(p.config)),p.middlewareStack.use(No(p.config)),p.middlewareStack.use(ko(p.config)),p.middlewareStack.use(Object(Oo.a)(p.config)),p.middlewareStack.use(Object(xo.a)(p.config)),p}return c(t,e),t.prototype.destroy=function(){e.prototype.destroy.call(this)},t}(Zr.a),Do=n(74);function Uo(e){var t=e.port,n=e.query,r=e.protocol,i=e.path,o=e.hostname;r&&":"!==r.substr(-1)&&(r+=":"),t&&(o+=":"+t),i&&"/"!==i.charAt(0)&&(i="/"+i);var s=n?Object(Do.a)(n):"";return s&&"?"!==s[0]&&(s="?"+s),r+"//"+o+i+s}function Bo(e,t){return Object(Qr.__awaiter)(this,void 0,void 0,(function(){var n,r,i=this;return Object(Qr.__generator)(this,(function(o){switch(o.label){case 0:return n=function(e){return function(e){return Object(Qr.__awaiter)(i,void 0,void 0,(function(){return Object(Qr.__generator)(this,(function(t){return[2,{output:{request:e.request},response:void 0}]}))}))}},(r=e.middlewareStack.clone()).add(n,{step:"build",priority:"low"}),[4,t.resolveMiddleware(r,e.config,void 0)(t).then((function(e){return e.output.request}))];case 1:return[2,o.sent()]}}))}))}var Fo=n(111),zo=function(){function e(e){var t=Object(Qr.__assign)({service:e.signingName||e.service||"s3",uriEscapePath:e.uriEscapePath||!1},e);this.signer=new Fo.a(t)}return e.prototype.presign=function(e,t){void 0===t&&(t={});var n=t.unsignableHeaders,r=void 0===n?new Set:n,i=Object(Qr.__rest)(t,["unsignableHeaders"]);return Object(Qr.__awaiter)(this,void 0,void 0,(function(){return Object(Qr.__generator)(this,(function(t){return r.add("content-type"),e.headers["X-Amz-Content-Sha256"]="UNSIGNED-PAYLOAD",[2,this.signer.presign(e,Object(Qr.__assign)({expiresIn:900,unsignableHeaders:r},i))]}))}))},e}(),qo=n(64),Ko=n.n(qo),Ho=new r.a("axios-http-handler"),Vo=function(){function e(e,t){void 0===e&&(e={}),this.httpOptions=e,this.emitter=t}return e.prototype.destroy=function(){},e.prototype.handle=function(e,t){var n=this.httpOptions.requestTimeout,r=this.emitter,i=e.path;if(e.query){var o=Object(Do.a)(e.query);o&&(i+="?"+o)}var s=e.port,a=e.protocol+"//"+e.hostname+(s?":"+s:"")+i,u={};u.url=a,u.method=e.method,u.headers=e.headers,delete u.headers.host,e.body?u.data=e.body:u.headers["Content-Type"]&&(u.data=null),r&&(u.onUploadProgress=function(e){r.emit("sendProgress",e),Ho.debug(e)}),u.responseType="blob";var c=[Ko.a.request(u).then((function(e){return{response:new Xr.b({headers:e.headers,statusCode:e.status,body:e.data})}})).catch((function(e){throw Ho.error(e),e})),Go(n)];return Promise.race(c)},e}();function Go(e){return void 0===e&&(e=0),new Promise((function(t,n){e&&setTimeout((function(){var t=new Error("Request did not complete within "+e+" ms");t.name="TimeoutError",n(t)}),e)}))}var Wo,$o,Yo,Jo,Zo,Xo,Qo,es,ts,ns,rs,is,os,ss,as,us,cs,fs,ls,ds,hs=function(e){function t(t){var n=e.call(this)||this;return n.input=t,n}return c(t,e),t.prototype.resolveMiddleware=function(e,t,n){this.middlewareStack.use(Object(Vi.a)(t,this.serialize,this.deserialize)),this.middlewareStack.use(Wi(t)),this.middlewareStack.use(Hi(t));var r=e.concat(this.middlewareStack),i=t.logger,o={logger:i,clientName:"S3Client",commandName:"PutObjectCommand",inputFilterSensitiveLog:_r.filterSensitiveLog,outputFilterSensitiveLog:wr.filterSensitiveLog};"function"==typeof i.info&&i.info({clientName:"S3Client",commandName:"PutObjectCommand"});var s=t.requestHandler;return r.resolve((function(e){return s.handle(e.request,n||{})}),o)},t.prototype.serialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,l,h,p;return d(this,(function(d){switch(d.label){case 0:if(n=f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f({"Content-Type":"application/octet-stream"},Mi(e.GrantFullControl)&&{"x-amz-grant-full-control":e.GrantFullControl}),Mi(e.ContentEncoding)&&{"Content-Encoding":e.ContentEncoding}),Mi(e.RequestPayer)&&{"x-amz-request-payer":e.RequestPayer}),Mi(e.GrantReadACP)&&{"x-amz-grant-read-acp":e.GrantReadACP}),Mi(e.SSECustomerKeyMD5)&&{"x-amz-server-side-encryption-customer-key-MD5":e.SSECustomerKeyMD5}),Mi(e.CacheControl)&&{"Cache-Control":e.CacheControl}),Mi(e.WebsiteRedirectLocation)&&{"x-amz-website-redirect-location":e.WebsiteRedirectLocation}),Mi(e.ObjectLockLegalHoldStatus)&&{"x-amz-object-lock-legal-hold":e.ObjectLockLegalHoldStatus}),Mi(e.GrantWriteACP)&&{"x-amz-grant-write-acp":e.GrantWriteACP}),Mi(e.ContentLength)&&{"Content-Length":e.ContentLength.toString()}),Mi(e.ObjectLockRetainUntilDate)&&{"x-amz-object-lock-retain-until-date":(e.ObjectLockRetainUntilDate.toISOString().split(".")[0]+"Z").toString()}),Mi(e.SSECustomerAlgorithm)&&{"x-amz-server-side-encryption-customer-algorithm":e.SSECustomerAlgorithm}),Mi(e.ContentDisposition)&&{"Content-Disposition":e.ContentDisposition}),Mi(e.SSECustomerKey)&&{"x-amz-server-side-encryption-customer-key":e.SSECustomerKey}),Mi(e.SSEKMSEncryptionContext)&&{"x-amz-server-side-encryption-context":e.SSEKMSEncryptionContext}),Mi(e.Tagging)&&{"x-amz-tagging":e.Tagging}),Mi(e.Expires)&&{Expires:Object(Zr.e)(e.Expires).toString()}),Mi(e.StorageClass)&&{"x-amz-storage-class":e.StorageClass}),Mi(e.ExpectedBucketOwner)&&{"x-amz-expected-bucket-owner":e.ExpectedBucketOwner}),Mi(e.ContentMD5)&&{"Content-MD5":e.ContentMD5}),Mi(e.ServerSideEncryption)&&{"x-amz-server-side-encryption":e.ServerSideEncryption}),Mi(e.ObjectLockMode)&&{"x-amz-object-lock-mode":e.ObjectLockMode}),Mi(e.SSEKMSKeyId)&&{"x-amz-server-side-encryption-aws-kms-key-id":e.SSEKMSKeyId}),Mi(e.ContentLanguage)&&{"Content-Language":e.ContentLanguage}),Mi(e.GrantRead)&&{"x-amz-grant-read":e.GrantRead}),Mi(e.ACL)&&{"x-amz-acl":e.ACL}),Mi(e.ContentType)&&{"Content-Type":e.ContentType}),void 0!==e.Metadata&&Object.keys(e.Metadata).reduce((function(t,n){return t["x-amz-meta-"+n]=e.Metadata[n],t}),{})),r="/{Bucket}/{Key+}",void 0===e.Bucket)throw new Error("No value provided for input HTTP label: Bucket.");if((i=e.Bucket).length<=0)throw new Error("Empty value provided for input HTTP label: Bucket.");if(r=r.replace("{Bucket}",Object(Zr.f)(i)),void 0===e.Key)throw new Error("No value provided for input HTTP label: Key.");if((i=e.Key).length<=0)throw new Error("Empty value provided for input HTTP label: Key.");return r=r.replace("{Key+}",i.split("/").map((function(e){return Object(Zr.f)(e)})).join("/")),o={"x-id":"PutObject"},void 0!==e.Body&&(a=e.Body,s=a),[4,t.endpoint()];case 1:return u=d.sent(),c=u.hostname,l=u.protocol,h=void 0===l?"https":l,p=u.port,[2,new Xr.a({protocol:h,hostname:c,port:p,method:"PUT",headers:n,path:r,query:o,body:s})]}}))}))}(e,t)},t.prototype.deserialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n;return d(this,(function(r){switch(r.label){case 0:return 200!==e.statusCode&&e.statusCode>=300?[2,fi(e,t)]:(n={$metadata:Si(e),ETag:void 0,Expiration:void 0,RequestCharged:void 0,SSECustomerAlgorithm:void 0,SSECustomerKeyMD5:void 0,SSEKMSEncryptionContext:void 0,SSEKMSKeyId:void 0,ServerSideEncryption:void 0,VersionId:void 0},void 0!==e.headers["x-amz-server-side-encryption-context"]&&(n.SSEKMSEncryptionContext=e.headers["x-amz-server-side-encryption-context"]),void 0!==e.headers["x-amz-expiration"]&&(n.Expiration=e.headers["x-amz-expiration"]),void 0!==e.headers["x-amz-server-side-encryption-customer-key-md5"]&&(n.SSECustomerKeyMD5=e.headers["x-amz-server-side-encryption-customer-key-md5"]),void 0!==e.headers.etag&&(n.ETag=e.headers.etag),void 0!==e.headers["x-amz-server-side-encryption-customer-algorithm"]&&(n.SSECustomerAlgorithm=e.headers["x-amz-server-side-encryption-customer-algorithm"]),void 0!==e.headers["x-amz-version-id"]&&(n.VersionId=e.headers["x-amz-version-id"]),void 0!==e.headers["x-amz-request-charged"]&&(n.RequestCharged=e.headers["x-amz-request-charged"]),void 0!==e.headers["x-amz-server-side-encryption-aws-kms-key-id"]&&(n.SSEKMSKeyId=e.headers["x-amz-server-side-encryption-aws-kms-key-id"]),void 0!==e.headers["x-amz-server-side-encryption"]&&(n.ServerSideEncryption=e.headers["x-amz-server-side-encryption"]),[4,Ei(e.body,t)]);case 1:return r.sent(),[2,Promise.resolve(n)]}}))}))}(e,t)},t}(Zr.b),ps=function(e){function t(t){var n=e.call(this)||this;return n.input=t,n}return c(t,e),t.prototype.resolveMiddleware=function(e,t,n){this.middlewareStack.use(Object(Vi.a)(t,this.serialize,this.deserialize)),this.middlewareStack.use(Wi(t)),this.middlewareStack.use(Hi(t));var r=e.concat(this.middlewareStack),i=t.logger,o={logger:i,clientName:"S3Client",commandName:"CreateMultipartUploadCommand",inputFilterSensitiveLog:D.filterSensitiveLog,outputFilterSensitiveLog:j.filterSensitiveLog};"function"==typeof i.info&&i.info({clientName:"S3Client",commandName:"CreateMultipartUploadCommand"});var s=t.requestHandler;return r.resolve((function(e){return s.handle(e.request,n||{})}),o)},t.prototype.serialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,l;return d(this,(function(d){switch(d.label){case 0:if(n=f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f({"Content-Type":""},Mi(e.GrantFullControl)&&{"x-amz-grant-full-control":e.GrantFullControl}),Mi(e.SSECustomerKeyMD5)&&{"x-amz-server-side-encryption-customer-key-MD5":e.SSECustomerKeyMD5}),Mi(e.SSECustomerAlgorithm)&&{"x-amz-server-side-encryption-customer-algorithm":e.SSECustomerAlgorithm}),Mi(e.SSEKMSKeyId)&&{"x-amz-server-side-encryption-aws-kms-key-id":e.SSEKMSKeyId}),Mi(e.ObjectLockLegalHoldStatus)&&{"x-amz-object-lock-legal-hold":e.ObjectLockLegalHoldStatus}),Mi(e.RequestPayer)&&{"x-amz-request-payer":e.RequestPayer}),Mi(e.GrantRead)&&{"x-amz-grant-read":e.GrantRead}),Mi(e.GrantWriteACP)&&{"x-amz-grant-write-acp":e.GrantWriteACP}),Mi(e.WebsiteRedirectLocation)&&{"x-amz-website-redirect-location":e.WebsiteRedirectLocation}),Mi(e.ContentType)&&{"Content-Type":e.ContentType}),Mi(e.ContentLanguage)&&{"Content-Language":e.ContentLanguage}),Mi(e.CacheControl)&&{"Cache-Control":e.CacheControl}),Mi(e.GrantReadACP)&&{"x-amz-grant-read-acp":e.GrantReadACP}),Mi(e.Tagging)&&{"x-amz-tagging":e.Tagging}),Mi(e.SSEKMSEncryptionContext)&&{"x-amz-server-side-encryption-context":e.SSEKMSEncryptionContext}),Mi(e.ACL)&&{"x-amz-acl":e.ACL}),Mi(e.SSECustomerKey)&&{"x-amz-server-side-encryption-customer-key":e.SSECustomerKey}),Mi(e.ExpectedBucketOwner)&&{"x-amz-expected-bucket-owner":e.ExpectedBucketOwner}),Mi(e.Expires)&&{Expires:Object(Zr.e)(e.Expires).toString()}),Mi(e.ObjectLockRetainUntilDate)&&{"x-amz-object-lock-retain-until-date":(e.ObjectLockRetainUntilDate.toISOString().split(".")[0]+"Z").toString()}),Mi(e.ServerSideEncryption)&&{"x-amz-server-side-encryption":e.ServerSideEncryption}),Mi(e.ContentDisposition)&&{"Content-Disposition":e.ContentDisposition}),Mi(e.ObjectLockMode)&&{"x-amz-object-lock-mode":e.ObjectLockMode}),Mi(e.StorageClass)&&{"x-amz-storage-class":e.StorageClass}),Mi(e.ContentEncoding)&&{"Content-Encoding":e.ContentEncoding}),void 0!==e.Metadata&&Object.keys(e.Metadata).reduce((function(t,n){return t["x-amz-meta-"+n]=e.Metadata[n],t}),{})),r="/{Bucket}/{Key+}",void 0===e.Bucket)throw new Error("No value provided for input HTTP label: Bucket.");if((i=e.Bucket).length<=0)throw new Error("Empty value provided for input HTTP label: Bucket.");if(r=r.replace("{Bucket}",Object(Zr.f)(i)),void 0===e.Key)throw new Error("No value provided for input HTTP label: Key.");if((i=e.Key).length<=0)throw new Error("Empty value provided for input HTTP label: Key.");return r=r.replace("{Key+}",i.split("/").map((function(e){return Object(Zr.f)(e)})).join("/")),o={uploads:""},[4,t.endpoint()];case 1:return s=d.sent(),a=s.hostname,u=s.protocol,c=void 0===u?"https":u,l=s.port,[2,new Xr.a({protocol:c,hostname:a,port:l,method:"POST",headers:n,path:r,query:o,body:void 0})]}}))}))}(e,t)},t.prototype.deserialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n,r;return d(this,(function(i){switch(i.label){case 0:return 200!==e.statusCode&&e.statusCode>=300?[2,oi(e,t)]:(n={$metadata:Si(e),AbortDate:void 0,AbortRuleId:void 0,Bucket:void 0,Key:void 0,RequestCharged:void 0,SSECustomerAlgorithm:void 0,SSECustomerKeyMD5:void 0,SSEKMSEncryptionContext:void 0,SSEKMSKeyId:void 0,ServerSideEncryption:void 0,UploadId:void 0},void 0!==e.headers["x-amz-server-side-encryption-context"]&&(n.SSEKMSEncryptionContext=e.headers["x-amz-server-side-encryption-context"]),void 0!==e.headers["x-amz-server-side-encryption"]&&(n.ServerSideEncryption=e.headers["x-amz-server-side-encryption"]),void 0!==e.headers["x-amz-request-charged"]&&(n.RequestCharged=e.headers["x-amz-request-charged"]),void 0!==e.headers["x-amz-abort-date"]&&(n.AbortDate=new Date(e.headers["x-amz-abort-date"])),void 0!==e.headers["x-amz-server-side-encryption-customer-algorithm"]&&(n.SSECustomerAlgorithm=e.headers["x-amz-server-side-encryption-customer-algorithm"]),void 0!==e.headers["x-amz-server-side-encryption-aws-kms-key-id"]&&(n.SSEKMSKeyId=e.headers["x-amz-server-side-encryption-aws-kms-key-id"]),void 0!==e.headers["x-amz-abort-rule-id"]&&(n.AbortRuleId=e.headers["x-amz-abort-rule-id"]),void 0!==e.headers["x-amz-server-side-encryption-customer-key-md5"]&&(n.SSECustomerKeyMD5=e.headers["x-amz-server-side-encryption-customer-key-md5"]),[4,Ai(e.body,t)]);case 1:return void 0!==(r=i.sent()).Bucket&&(n.Bucket=r.Bucket),void 0!==r.Key&&(n.Key=r.Key),void 0!==r.UploadId&&(n.UploadId=r.UploadId),[2,Promise.resolve(n)]}}))}))}(e,t)},t}(Zr.b);!function(e){e.SELECT="SELECT"}(Wo||(Wo={})),($o||($o={})).filterSensitiveLog=function(e){return f(f({},e),e.OutputLocation&&{OutputLocation:Br.filterSensitiveLog(e.OutputLocation)})},(Yo||(Yo={})).filterSensitiveLog=function(e){return f(f({},e),e.RestoreRequest&&{RestoreRequest:$o.filterSensitiveLog(e.RestoreRequest)})},(Jo||(Jo={})).filterSensitiveLog=function(e){return f({},e)},(Zo||(Zo={})).filterSensitiveLog=function(e){return f({},e)},(Xo||(Xo={})).filterSensitiveLog=function(e){return f({},e)},(Qo||(Qo={})).filterSensitiveLog=function(e){return f({},e)},(es||(es={})).filterSensitiveLog=function(e){return f({},e)},(ts||(ts={})).filterSensitiveLog=function(e){return f({},e)},(ns||(ns={})).filterSensitiveLog=function(e){return f({},e)},function(e){e.visit=function(e,t){return void 0!==e.Cont?t.Cont(e.Cont):void 0!==e.Progress?t.Progress(e.Progress):void 0!==e.Stats?t.Stats(e.Stats):void 0!==e.End?t.End(e.End):void 0!==e.Records?t.Records(e.Records):t._(e.$unknown[0],e.$unknown[1])},e.filterSensitiveLog=function(e){var t;return void 0!==e.Cont?{Cont:Jo.filterSensitiveLog(e.Cont)}:void 0!==e.Progress?{Progress:Qo.filterSensitiveLog(e.Progress)}:void 0!==e.Stats?{Stats:ns.filterSensitiveLog(e.Stats)}:void 0!==e.End?{End:Zo.filterSensitiveLog(e.End)}:void 0!==e.Records?{Records:es.filterSensitiveLog(e.Records)}:void 0!==e.$unknown?((t={})[e.$unknown[0]]="UNKNOWN",t):void 0}}(rs||(rs={})),(is||(is={})).filterSensitiveLog=function(e){return f(f({},e),e.Payload&&{Payload:"STREAMING_CONTENT"})},(os||(os={})).filterSensitiveLog=function(e){return f({},e)},(ss||(ss={})).filterSensitiveLog=function(e){return f({},e)},(as||(as={})).filterSensitiveLog=function(e){return f(f({},e),e.SSECustomerKey&&{SSECustomerKey:Zr.d})},(us||(us={})).filterSensitiveLog=function(e){return f(f({},e),e.SSEKMSKeyId&&{SSEKMSKeyId:Zr.d})},(cs||(cs={})).filterSensitiveLog=function(e){return f(f({},e),e.SSECustomerKey&&{SSECustomerKey:Zr.d})},(fs||(fs={})).filterSensitiveLog=function(e){return f({},e)},(ls||(ls={})).filterSensitiveLog=function(e){return f(f({},e),e.SSEKMSKeyId&&{SSEKMSKeyId:Zr.d})},(ds||(ds={})).filterSensitiveLog=function(e){return f(f(f({},e),e.SSECustomerKey&&{SSECustomerKey:Zr.d}),e.CopySourceSSECustomerKey&&{CopySourceSSECustomerKey:Zr.d})};var vs=function(e){function t(t){var n=e.call(this)||this;return n.input=t,n}return c(t,e),t.prototype.resolveMiddleware=function(e,t,n){this.middlewareStack.use(Object(Vi.a)(t,this.serialize,this.deserialize)),this.middlewareStack.use(Wi(t)),this.middlewareStack.use(Hi(t));var r=e.concat(this.middlewareStack),i=t.logger,o={logger:i,clientName:"S3Client",commandName:"UploadPartCommand",inputFilterSensitiveLog:cs.filterSensitiveLog,outputFilterSensitiveLog:us.filterSensitiveLog};"function"==typeof i.info&&i.info({clientName:"S3Client",commandName:"UploadPartCommand"});var s=t.requestHandler;return r.resolve((function(e){return s.handle(e.request,n||{})}),o)},t.prototype.serialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,l,h,p;return d(this,(function(d){switch(d.label){case 0:if(n=f(f(f(f(f(f(f({"Content-Type":"application/octet-stream"},Mi(e.ExpectedBucketOwner)&&{"x-amz-expected-bucket-owner":e.ExpectedBucketOwner}),Mi(e.RequestPayer)&&{"x-amz-request-payer":e.RequestPayer}),Mi(e.ContentLength)&&{"Content-Length":e.ContentLength.toString()}),Mi(e.SSECustomerKey)&&{"x-amz-server-side-encryption-customer-key":e.SSECustomerKey}),Mi(e.SSECustomerAlgorithm)&&{"x-amz-server-side-encryption-customer-algorithm":e.SSECustomerAlgorithm}),Mi(e.SSECustomerKeyMD5)&&{"x-amz-server-side-encryption-customer-key-MD5":e.SSECustomerKeyMD5}),Mi(e.ContentMD5)&&{"Content-MD5":e.ContentMD5}),r="/{Bucket}/{Key+}",void 0===e.Bucket)throw new Error("No value provided for input HTTP label: Bucket.");if((i=e.Bucket).length<=0)throw new Error("Empty value provided for input HTTP label: Bucket.");if(r=r.replace("{Bucket}",Object(Zr.f)(i)),void 0===e.Key)throw new Error("No value provided for input HTTP label: Key.");if((i=e.Key).length<=0)throw new Error("Empty value provided for input HTTP label: Key.");return r=r.replace("{Key+}",i.split("/").map((function(e){return Object(Zr.f)(e)})).join("/")),o=f(f({"x-id":"UploadPart"},void 0!==e.PartNumber&&{partNumber:e.PartNumber.toString()}),void 0!==e.UploadId&&{uploadId:e.UploadId}),void 0!==e.Body&&(a=e.Body,s=a),[4,t.endpoint()];case 1:return u=d.sent(),c=u.hostname,l=u.protocol,h=void 0===l?"https":l,p=u.port,[2,new Xr.a({protocol:h,hostname:c,port:p,method:"PUT",headers:n,path:r,query:o,body:s})]}}))}))}(e,t)},t.prototype.deserialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n;return d(this,(function(r){switch(r.label){case 0:return 200!==e.statusCode&&e.statusCode>=300?[2,li(e,t)]:(n={$metadata:Si(e),ETag:void 0,RequestCharged:void 0,SSECustomerAlgorithm:void 0,SSECustomerKeyMD5:void 0,SSEKMSKeyId:void 0,ServerSideEncryption:void 0},void 0!==e.headers["x-amz-server-side-encryption-customer-key-md5"]&&(n.SSECustomerKeyMD5=e.headers["x-amz-server-side-encryption-customer-key-md5"]),void 0!==e.headers["x-amz-server-side-encryption"]&&(n.ServerSideEncryption=e.headers["x-amz-server-side-encryption"]),void 0!==e.headers["x-amz-server-side-encryption-aws-kms-key-id"]&&(n.SSEKMSKeyId=e.headers["x-amz-server-side-encryption-aws-kms-key-id"]),void 0!==e.headers["x-amz-server-side-encryption-customer-algorithm"]&&(n.SSECustomerAlgorithm=e.headers["x-amz-server-side-encryption-customer-algorithm"]),void 0!==e.headers["x-amz-request-charged"]&&(n.RequestCharged=e.headers["x-amz-request-charged"]),void 0!==e.headers.etag&&(n.ETag=e.headers.etag),[4,Ei(e.body,t)]);case 1:return r.sent(),[2,Promise.resolve(n)]}}))}))}(e,t)},t}(Zr.b),gs=function(e){function t(t){var n=e.call(this)||this;return n.input=t,n}return c(t,e),t.prototype.resolveMiddleware=function(e,t,n){this.middlewareStack.use(Object(Vi.a)(t,this.serialize,this.deserialize)),this.middlewareStack.use(Hi(t));var r=e.concat(this.middlewareStack),i=t.logger,o={logger:i,clientName:"S3Client",commandName:"CompleteMultipartUploadCommand",inputFilterSensitiveLog:I.filterSensitiveLog,outputFilterSensitiveLog:E.filterSensitiveLog};"function"==typeof i.info&&i.info({clientName:"S3Client",commandName:"CompleteMultipartUploadCommand"});var s=t.requestHandler;return r.resolve((function(e){return s.handle(e.request,n||{})}),o)},t.prototype.serialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,l,h,p;return d(this,(function(d){switch(d.label){case 0:if(n=f(f({"Content-Type":"application/xml"},Mi(e.ExpectedBucketOwner)&&{"x-amz-expected-bucket-owner":e.ExpectedBucketOwner}),Mi(e.RequestPayer)&&{"x-amz-request-payer":e.RequestPayer}),r="/{Bucket}/{Key+}",void 0===e.Key)throw new Error("No value provided for input HTTP label: Key.");if((i=e.Key).length<=0)throw new Error("Empty value provided for input HTTP label: Key.");if(r=r.replace("{Key+}",i.split("/").map((function(e){return Object(Zr.f)(e)})).join("/")),void 0===e.Bucket)throw new Error("No value provided for input HTTP label: Bucket.");if((i=e.Bucket).length<=0)throw new Error("Empty value provided for input HTTP label: Bucket.");return r=r.replace("{Bucket}",Object(Zr.f)(i)),o=f({},void 0!==e.UploadId&&{uploadId:e.UploadId}),void 0!==e.MultipartUpload&&(a=vi(e.MultipartUpload,t),s='',a.addAttribute("xmlns","http://s3.amazonaws.com/doc/2006-03-01/"),s+=a.toString()),[4,t.endpoint()];case 1:return u=d.sent(),c=u.hostname,l=u.protocol,h=void 0===l?"https":l,p=u.port,[2,new Xr.a({protocol:h,hostname:c,port:p,method:"POST",headers:n,path:r,query:o,body:s})]}}))}))}(e,t)},t.prototype.deserialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n,r;return d(this,(function(i){switch(i.label){case 0:return 200!==e.statusCode&&e.statusCode>=300?[2,ii(e,t)]:(n={$metadata:Si(e),Bucket:void 0,ETag:void 0,Expiration:void 0,Key:void 0,Location:void 0,RequestCharged:void 0,SSEKMSKeyId:void 0,ServerSideEncryption:void 0,VersionId:void 0},void 0!==e.headers["x-amz-expiration"]&&(n.Expiration=e.headers["x-amz-expiration"]),void 0!==e.headers["x-amz-server-side-encryption"]&&(n.ServerSideEncryption=e.headers["x-amz-server-side-encryption"]),void 0!==e.headers["x-amz-server-side-encryption-aws-kms-key-id"]&&(n.SSEKMSKeyId=e.headers["x-amz-server-side-encryption-aws-kms-key-id"]),void 0!==e.headers["x-amz-version-id"]&&(n.VersionId=e.headers["x-amz-version-id"]),void 0!==e.headers["x-amz-request-charged"]&&(n.RequestCharged=e.headers["x-amz-request-charged"]),[4,Ai(e.body,t)]);case 1:return void 0!==(r=i.sent()).Bucket&&(n.Bucket=r.Bucket),void 0!==r.ETag&&(n.ETag=r.ETag),void 0!==r.Key&&(n.Key=r.Key),void 0!==r.Location&&(n.Location=r.Location),[2,Promise.resolve(n)]}}))}))}(e,t)},t}(Zr.b),ms=function(e){function t(t){var n=e.call(this)||this;return n.input=t,n}return c(t,e),t.prototype.resolveMiddleware=function(e,t,n){this.middlewareStack.use(Object(Vi.a)(t,this.serialize,this.deserialize)),this.middlewareStack.use(Hi(t));var r=e.concat(this.middlewareStack),i=t.logger,o={logger:i,clientName:"S3Client",commandName:"AbortMultipartUploadCommand",inputFilterSensitiveLog:v.filterSensitiveLog,outputFilterSensitiveLog:p.filterSensitiveLog};"function"==typeof i.info&&i.info({clientName:"S3Client",commandName:"AbortMultipartUploadCommand"});var s=t.requestHandler;return r.resolve((function(e){return s.handle(e.request,n||{})}),o)},t.prototype.serialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,l;return d(this,(function(d){switch(d.label){case 0:if(n=f(f({"Content-Type":""},Mi(e.RequestPayer)&&{"x-amz-request-payer":e.RequestPayer}),Mi(e.ExpectedBucketOwner)&&{"x-amz-expected-bucket-owner":e.ExpectedBucketOwner}),r="/{Bucket}/{Key+}",void 0===e.Key)throw new Error("No value provided for input HTTP label: Key.");if((i=e.Key).length<=0)throw new Error("Empty value provided for input HTTP label: Key.");if(r=r.replace("{Key+}",i.split("/").map((function(e){return Object(Zr.f)(e)})).join("/")),void 0===e.Bucket)throw new Error("No value provided for input HTTP label: Bucket.");if((i=e.Bucket).length<=0)throw new Error("Empty value provided for input HTTP label: Bucket.");return r=r.replace("{Bucket}",Object(Zr.f)(i)),o=f({"x-id":"AbortMultipartUpload"},void 0!==e.UploadId&&{uploadId:e.UploadId}),[4,t.endpoint()];case 1:return s=d.sent(),a=s.hostname,u=s.protocol,c=void 0===u?"https":u,l=s.port,[2,new Xr.a({protocol:c,hostname:a,port:l,method:"DELETE",headers:n,path:r,query:o,body:void 0})]}}))}))}(e,t)},t.prototype.deserialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n;return d(this,(function(r){switch(r.label){case 0:return 204!==e.statusCode&&e.statusCode>=300?[2,ri(e,t)]:(n={$metadata:Si(e),RequestCharged:void 0},void 0!==e.headers["x-amz-request-charged"]&&(n.RequestCharged=e.headers["x-amz-request-charged"]),[4,Ei(e.body,t)]);case 1:return r.sent(),[2,Promise.resolve(n)]}}))}))}(e,t)},t}(Zr.b),bs=function(e){function t(t){var n=e.call(this)||this;return n.input=t,n}return c(t,e),t.prototype.resolveMiddleware=function(e,t,n){this.middlewareStack.use(Object(Vi.a)(t,this.serialize,this.deserialize)),this.middlewareStack.use(Hi(t));var r=e.concat(this.middlewareStack),i=t.logger,o={logger:i,clientName:"S3Client",commandName:"ListPartsCommand",inputFilterSensitiveLog:Yn.filterSensitiveLog,outputFilterSensitiveLog:$n.filterSensitiveLog};"function"==typeof i.info&&i.info({clientName:"S3Client",commandName:"ListPartsCommand"});var s=t.requestHandler;return r.resolve((function(e){return s.handle(e.request,n||{})}),o)},t.prototype.serialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,l;return d(this,(function(d){switch(d.label){case 0:if(n=f(f({"Content-Type":""},Mi(e.RequestPayer)&&{"x-amz-request-payer":e.RequestPayer}),Mi(e.ExpectedBucketOwner)&&{"x-amz-expected-bucket-owner":e.ExpectedBucketOwner}),r="/{Bucket}/{Key+}",void 0===e.Bucket)throw new Error("No value provided for input HTTP label: Bucket.");if((i=e.Bucket).length<=0)throw new Error("Empty value provided for input HTTP label: Bucket.");if(r=r.replace("{Bucket}",Object(Zr.f)(i)),void 0===e.Key)throw new Error("No value provided for input HTTP label: Key.");if((i=e.Key).length<=0)throw new Error("Empty value provided for input HTTP label: Key.");return r=r.replace("{Key+}",i.split("/").map((function(e){return Object(Zr.f)(e)})).join("/")),o=f(f(f({"x-id":"ListParts"},void 0!==e.UploadId&&{uploadId:e.UploadId}),void 0!==e.MaxParts&&{"max-parts":e.MaxParts.toString()}),void 0!==e.PartNumberMarker&&{"part-number-marker":e.PartNumberMarker.toString()}),[4,t.endpoint()];case 1:return s=d.sent(),a=s.hostname,u=s.protocol,c=void 0===u?"https":u,l=s.port,[2,new Xr.a({protocol:c,hostname:a,port:l,method:"GET",headers:n,path:r,query:o,body:void 0})]}}))}))}(e,t)},t.prototype.deserialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n,r;return d(this,(function(i){switch(i.label){case 0:return 200!==e.statusCode&&e.statusCode>=300?[2,ci(e,t)]:(n={$metadata:Si(e),AbortDate:void 0,AbortRuleId:void 0,Bucket:void 0,Initiator:void 0,IsTruncated:void 0,Key:void 0,MaxParts:void 0,NextPartNumberMarker:void 0,Owner:void 0,PartNumberMarker:void 0,Parts:void 0,RequestCharged:void 0,StorageClass:void 0,UploadId:void 0},void 0!==e.headers["x-amz-abort-rule-id"]&&(n.AbortRuleId=e.headers["x-amz-abort-rule-id"]),void 0!==e.headers["x-amz-request-charged"]&&(n.RequestCharged=e.headers["x-amz-request-charged"]),void 0!==e.headers["x-amz-abort-date"]&&(n.AbortDate=new Date(e.headers["x-amz-abort-date"])),[4,Ai(e.body,t)]);case 1:return void 0!==(r=i.sent()).Bucket&&(n.Bucket=r.Bucket),void 0!==r.Initiator&&(n.Initiator=bi(r.Initiator,t)),void 0!==r.IsTruncated&&(n.IsTruncated="true"==r.IsTruncated),void 0!==r.Key&&(n.Key=r.Key),void 0!==r.MaxParts&&(n.MaxParts=parseInt(r.MaxParts)),void 0!==r.NextPartNumberMarker&&(n.NextPartNumberMarker=parseInt(r.NextPartNumberMarker)),void 0!==r.Owner&&(n.Owner=wi(r.Owner,t)),void 0!==r.PartNumberMarker&&(n.PartNumberMarker=parseInt(r.PartNumberMarker)),""===r.Part&&(n.Parts=[]),void 0!==r.Part&&(n.Parts=_i(Object(Zr.g)(r.Part),t)),void 0!==r.StorageClass&&(n.StorageClass=r.StorageClass),void 0!==r.UploadId&&(n.UploadId=r.UploadId),[2,Promise.resolve(n)]}}))}))}(e,t)},t}(Zr.b),ys=n(49),ws=n(106),_s=n(16),Ss=function(e){var t,n=Object(_s.parse)(e),r=n.hostname,i=void 0===r?"localhost":r,o=n.pathname,s=void 0===o?"/":o,a=n.port,u=n.protocol,c=void 0===u?"https:":u,f=n.search;return f&&(t=Object(ws.a)(f)),{hostname:i,port:a?parseInt(a):void 0,protocol:c,path:s,query:t}};function Es(e){return(Es="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var Ms=function(){return(Ms=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},Os=new r.a("AWSS3ProviderManagedUpload"),xs=function(){function e(e,t,n){this.minPartSize=5242880,this.queueSize=4,this.body=null,this.params=null,this.opts=null,this.multiPartMap=[],this.cancel=!1,this.bytesUploaded=0,this.totalBytesToUpload=0,this.emitter=null,this.params=e,this.opts=t,this.emitter=n}return e.prototype.upload=function(){return As(this,void 0,void 0,(function(){var e,t,n,r,i,o;return Is(this,(function(s){switch(s.label){case 0:return e=this,[4,this.validateAndSanitizeBody(this.params.Body)];case 1:return e.body=s.sent(),this.totalBytesToUpload=this.byteLength(this.body),this.totalBytesToUpload<=this.minPartSize?(this.params.Body=this.body,t=new hs(this.params),[4,this._createNewS3Client(this.opts,this.emitter)]):[3,3];case 2:return[2,s.sent().send(t)];case 3:return[4,this.createMultiPartUpload()];case 4:n=s.sent(),r=Math.ceil(this.totalBytesToUpload/this.minPartSize),i=0,s.label=5;case 5:return i0)throw new Error("Multi Part upload clean up failed");return[2]}}))}))},e.prototype.setupEventListener=function(e){var t=this;e.emitter.on("sendProgress",(function(n){t.progressChanged(e.partNumber,n.loaded-e._lastUploadedBytes),e._lastUploadedBytes=n.loaded}))},e.prototype.progressChanged=function(e,t){this.bytesUploaded+=t,this.emitter.emit("sendProgress",{loaded:this.bytesUploaded,total:this.totalBytesToUpload,part:e,key:this.params.Key})},e.prototype.byteLength=function(e){if(null==e)return 0;if("number"==typeof e.byteLength)return e.byteLength;if("number"==typeof e.length)return e.length;if("number"==typeof e.size)return e.size;if("string"!=typeof e.path)throw new Error("Cannot determine length of "+e)},e.prototype.validateAndSanitizeBody=function(e){return As(this,void 0,void 0,(function(){return Is(this,(function(t){switch(t.label){case 0:return this.isGenericObject(e)?[2,JSON.stringify(e)]:[3,1];case 1:return this.isBlob(e)?a.a.isReactNative?[4,Object(eo.b)(e)]:[3,3]:[3,4];case 2:return[2,t.sent()];case 3:case 4:return[2,e]}}))}))},e.prototype.isBlob=function(e){return"undefined"!=typeof Blob&&e instanceof Blob},e.prototype.isGenericObject=function(e){if(null!==e&&"object"===Es(e))try{return!(this.byteLength(e)>=0)}catch(e){return!0}return!1},e.prototype._createNewS3Client=function(e,t){return As(this,void 0,void 0,(function(){var n,r,i,o,s;return Is(this,(function(u){switch(u.label){case 0:return[4,this._getCredentials()];case 1:return n=u.sent(),r=e.region,i=e.dangerouslyConnectToHttpEndpointForTesting,o={},i&&(o={endpoint:"http://localhost:20005",tls:!1,bucketEndpoint:!1,forcePathStyle:!0}),(s=new jo(Ms(Ms({region:r,credentials:n},o),{requestHandler:new Vo({},t),customUserAgent:Object(a.b)(),urlParser:Ss}))).middlewareStack.remove("contentLengthMiddleware"),[2,s]}}))}))},e.prototype._getCredentials=function(){return s.a.get().then((function(e){if(!e)return!1;var t=s.a.shear(e);return Os.debug("set credentials for storage",t),t})).catch((function(e){return Os.warn("ensure credentials error",e),!1}))},e}();function Cs(e){return(Cs="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var Ts=function(){return(Ts=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},qs=new r.a("StorageClass"),Ks=function(){function e(){this._config={},this._pluggables=[],qs.debug("Storage Options",this._config),this.get=this.get.bind(this),this.put=this.put.bind(this),this.remove=this.remove.bind(this),this.list=this.list.bind(this)}return e.prototype.getModuleName=function(){return"Storage"},e.prototype.addPluggable=function(e){if(e&&"Storage"===e.getCategory()){this._pluggables.push(e);return e.configure(this._config[e.getProviderName()])}},e.prototype.getPluggable=function(e){var t=this._pluggables.find((function(t){return t.getProviderName()===e}));return void 0===t?(qs.debug("No plugin found with providerName",e),null):t},e.prototype.removePluggable=function(e){this._pluggables=this._pluggables.filter((function(t){return t.getProviderName()!==e}))},e.prototype.configure=function(e){var t=this;if(qs.debug("configure Storage"),!e)return this._config;var n=i.a.parseMobilehubConfig(e),r=Object.keys(n.Storage),o=["bucket","region","level","track","customPrefix","serverSideEncryption","SSECustomerAlgorithm","SSECustomerKey","SSECustomerKeyMD5","SSEKMSKeyId"],s=function(e){return o.some((function(t){return t===e}))};return r&&r.find((function(e){return s(e)}))&&!n.Storage.AWSS3&&(n.Storage.AWSS3={}),Object.entries(n.Storage).map((function(e){var t=zs(e,2),r=t[0],i=t[1];r&&s(r)&&void 0!==i&&(n.Storage.AWSS3[r]=i,delete n.Storage[r])})),Object.keys(n.Storage).forEach((function(e){"string"!=typeof n.Storage[e]&&(t._config[e]=Us(Us({},t._config[e]),n.Storage[e]))})),this._pluggables.forEach((function(e){e.configure(t._config[e.getProviderName()])})),0===this._pluggables.length&&this.addPluggable(new Ds),this._config},e.prototype.get=function(e,t){return Bs(this,void 0,void 0,(function(){var n,r,i;return Fs(this,(function(o){return n=(t||{}).provider,r=void 0===n?"AWSS3":n,void 0===(i=this._pluggables.find((function(e){return e.getProviderName()===r})))&&(qs.debug("No plugin found with providerName",r),Promise.reject("No plugin found in Storage for the provider")),[2,i.get(e,t)]}))}))},e.prototype.put=function(e,t,n){return Bs(this,void 0,void 0,(function(){var r,i,o;return Fs(this,(function(s){return r=(n||{}).provider,i=void 0===r?"AWSS3":r,void 0===(o=this._pluggables.find((function(e){return e.getProviderName()===i})))&&(qs.debug("No plugin found with providerName",i),Promise.reject("No plugin found in Storage for the provider")),[2,o.put(e,t,n)]}))}))},e.prototype.remove=function(e,t){return Bs(this,void 0,void 0,(function(){var n,r,i;return Fs(this,(function(o){return n=(t||{}).provider,r=void 0===n?"AWSS3":n,void 0===(i=this._pluggables.find((function(e){return e.getProviderName()===r})))&&(qs.debug("No plugin found with providerName",r),Promise.reject("No plugin found in Storage for the provider")),[2,i.remove(e,t)]}))}))},e.prototype.list=function(e,t){return Bs(this,void 0,void 0,(function(){var n,r,i;return Fs(this,(function(o){return n=(t||{}).provider,r=void 0===n?"AWSS3":n,void 0===(i=this._pluggables.find((function(e){return e.getProviderName()===r})))&&(qs.debug("No plugin found with providerName",r),Promise.reject("No plugin found in Storage for the provider")),[2,i.list(e,t)]}))}))},e}(),Hs=n(19),Vs=function(){return(Vs=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&(r=this.getByLanguage(e,n.split("-")[0])),r||(void 0!==t?t:e))},e.prototype.getByLanguage=function(e,t,n){if(void 0===n&&(n=null),!t)return n;var r=this._dict[t];return r?r[e]:n},e.prototype.putVocabulariesForLanguage=function(e,t){var n=this._dict[e];n||(n=this._dict[e]={}),Object.assign(n,t)},e.prototype.putVocabularies=function(e){var t=this;Object.keys(e).map((function(n){t.putVocabulariesForLanguage(n,e[n])}))},e}(),s=n(19),a=new r.a("I18n"),u=null,c=null,f=function(){function e(){}return e.configure=function(t){return a.debug("configure I18n"),t?(u=Object.assign({},u,t.I18n||t),e.createInstance(),u):u},e.getModuleName=function(){return"I18n"},e.createInstance=function(){a.debug("create I18n instance"),c||(c=new o(u))},e.setLanguage=function(t){return e.checkConfig(),c.setLanguage(t)},e.get=function(t,n){return e.checkConfig()?c.get(t,n):void 0===n?t:n},e.putVocabulariesForLanguage=function(t,n){return e.checkConfig(),c.putVocabulariesForLanguage(t,n)},e.putVocabularies=function(t){return e.checkConfig(),c.putVocabularies(t)},e.checkConfig=function(){return c||(c=new o(u)),!0},e}();s.a.register(f)},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(44),i=n(33),o=n(19);function s(e){return(s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var a=function(){function e(){this._logger=new r.a("ServiceWorker")}return Object.defineProperty(e.prototype,"serviceWorker",{get:function(){return this._serviceWorker},enumerable:!0,configurable:!0}),e.prototype.register=function(e,t){var n=this;return void 0===e&&(e="/service-worker.js"),void 0===t&&(t="/"),this._logger.debug("registering "+e),this._logger.debug("registering service worker with scope "+t),new Promise((function(r,i){if(!navigator||!("serviceWorker"in navigator))return i(new Error("Service Worker not available"));navigator.serviceWorker.register(e,{scope:t}).then((function(e){return e.installing?n._serviceWorker=e.installing:e.waiting?n._serviceWorker=e.waiting:e.active&&(n._serviceWorker=e.active),n._registration=e,n._setupListeners(),n._logger.debug("Service Worker Registration Success: "+e),r(e)})).catch((function(e){return n._logger.debug("Service Worker Registration Failed "+e),i(e)}))}))},e.prototype.enablePush=function(e){var t=this;if(!this._registration)throw new Error("Service Worker not registered");return this._publicKey=e,new Promise((function(n,r){if(!Object(i.b)().isBrowser)return r(new Error("Service Worker not available"));t._registration.pushManager.getSubscription().then((function(r){if(!r)return t._logger.debug("User is NOT subscribed to push"),t._registration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t._urlB64ToUint8Array(e)}).then((function(e){t._subscription=e,t._logger.debug("User subscribed: "+JSON.stringify(e)),n(e)})).catch((function(e){t._logger.error(e)}));t._subscription=r,t._logger.debug("User is subscribed to push: "+JSON.stringify(r)),n(r)}))}))},e.prototype._urlB64ToUint8Array=function(e){for(var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),n=window.atob(t),r=new Uint8Array(n.length),i=0;i0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s}var g,m,b,y,w,_,S,E,M,A,I,k,O,x,C,T,P,N,R,L,j,D,U,B,F,z,q,K,H,V,G,W,$,Y,J,Z,X,Q,ee,te,ne,re,ie,oe,se,ae,ue,ce,fe,le,de,he,pe,ve,ge,me,be,ye,we,_e,Se,Ee,Me,Ae,Ie,ke,Oe,xe,Ce,Te,Pe,Ne,Re,Le,je,De,Ue,Be,Fe,ze,qe,Ke,He,Ve,Ge,We,$e,Ye,Je,Ze,Xe,Qe,et,tt,nt,rt,it,ot,st,at,ut,ct,ft,lt,dt,ht,pt,vt,gt,mt,bt,yt,wt,_t,St,Et,Mt,At,It,kt,Ot,xt,Ct,Tt,Pt,Nt,Rt,Lt,jt,Dt,Ut;Object.create;(g||(g={})).filterSensitiveLog=function(e){return d({},e)},(m||(m={})).filterSensitiveLog=function(e){return d({},e)},(b||(b={})).filterSensitiveLog=function(e){return d({},e)},(y||(y={})).filterSensitiveLog=function(e){return d({},e)},(w||(w={})).filterSensitiveLog=function(e){return d({},e)},(_||(_={})).filterSensitiveLog=function(e){return d({},e)},(S||(S={})).filterSensitiveLog=function(e){return d({},e)},(E||(E={})).filterSensitiveLog=function(e){return d({},e)},(M||(M={})).filterSensitiveLog=function(e){return d({},e)},(A||(A={})).filterSensitiveLog=function(e){return d({},e)},(I||(I={})).filterSensitiveLog=function(e){return d({},e)},(k||(k={})).filterSensitiveLog=function(e){return d({},e)},(O||(O={})).filterSensitiveLog=function(e){return d({},e)},(x||(x={})).filterSensitiveLog=function(e){return d({},e)},(C||(C={})).filterSensitiveLog=function(e){return d({},e)},(T||(T={})).filterSensitiveLog=function(e){return d({},e)},(P||(P={})).filterSensitiveLog=function(e){return d({},e)},(N||(N={})).filterSensitiveLog=function(e){return d({},e)},(R||(R={})).filterSensitiveLog=function(e){return d({},e)},(L||(L={})).filterSensitiveLog=function(e){return d({},e)},(j||(j={})).filterSensitiveLog=function(e){return d({},e)},(D||(D={})).filterSensitiveLog=function(e){return d({},e)},(U||(U={})).filterSensitiveLog=function(e){return d({},e)},(B||(B={})).filterSensitiveLog=function(e){return d({},e)},(F||(F={})).filterSensitiveLog=function(e){return d({},e)},(z||(z={})).filterSensitiveLog=function(e){return d({},e)},(q||(q={})).filterSensitiveLog=function(e){return d({},e)},(K||(K={})).filterSensitiveLog=function(e){return d({},e)},(H||(H={})).filterSensitiveLog=function(e){return d({},e)},(V||(V={})).filterSensitiveLog=function(e){return d({},e)},(G||(G={})).filterSensitiveLog=function(e){return d({},e)},(W||(W={})).filterSensitiveLog=function(e){return d({},e)},($||($={})).filterSensitiveLog=function(e){return d({},e)},(Y||(Y={})).filterSensitiveLog=function(e){return d({},e)},(J||(J={})).filterSensitiveLog=function(e){return d({},e)},(Z||(Z={})).filterSensitiveLog=function(e){return d({},e)},(X||(X={})).filterSensitiveLog=function(e){return d({},e)},(Q||(Q={})).filterSensitiveLog=function(e){return d({},e)},(ee||(ee={})).filterSensitiveLog=function(e){return d({},e)},(te||(te={})).filterSensitiveLog=function(e){return d({},e)},(ne||(ne={})).filterSensitiveLog=function(e){return d({},e)},(re||(re={})).filterSensitiveLog=function(e){return d({},e)},(ie||(ie={})).filterSensitiveLog=function(e){return d({},e)},(oe||(oe={})).filterSensitiveLog=function(e){return d({},e)},(se||(se={})).filterSensitiveLog=function(e){return d({},e)},(ae||(ae={})).filterSensitiveLog=function(e){return d({},e)},(ue||(ue={})).filterSensitiveLog=function(e){return d({},e)},(ce||(ce={})).filterSensitiveLog=function(e){return d({},e)},(fe||(fe={})).filterSensitiveLog=function(e){return d({},e)},(le||(le={})).filterSensitiveLog=function(e){return d({},e)},(de||(de={})).filterSensitiveLog=function(e){return d({},e)},(he||(he={})).filterSensitiveLog=function(e){return d({},e)},(pe||(pe={})).filterSensitiveLog=function(e){return d({},e)},(ve||(ve={})).filterSensitiveLog=function(e){return d({},e)},(ge||(ge={})).filterSensitiveLog=function(e){return d({},e)},(me||(me={})).filterSensitiveLog=function(e){return d({},e)},(be||(be={})).filterSensitiveLog=function(e){return d({},e)},(ye||(ye={})).filterSensitiveLog=function(e){return d({},e)},(we||(we={})).filterSensitiveLog=function(e){return d({},e)},(_e||(_e={})).filterSensitiveLog=function(e){return d({},e)},(Se||(Se={})).filterSensitiveLog=function(e){return d({},e)},(Ee||(Ee={})).filterSensitiveLog=function(e){return d({},e)},(Me||(Me={})).filterSensitiveLog=function(e){return d({},e)},(Ae||(Ae={})).filterSensitiveLog=function(e){return d({},e)},(Ie||(Ie={})).filterSensitiveLog=function(e){return d({},e)},(ke||(ke={})).filterSensitiveLog=function(e){return d({},e)},(Oe||(Oe={})).filterSensitiveLog=function(e){return d({},e)},(xe||(xe={})).filterSensitiveLog=function(e){return d({},e)},(Ce||(Ce={})).filterSensitiveLog=function(e){return d({},e)},(Te||(Te={})).filterSensitiveLog=function(e){return d({},e)},(Pe||(Pe={})).filterSensitiveLog=function(e){return d({},e)},(Ne||(Ne={})).filterSensitiveLog=function(e){return d({},e)},(Re||(Re={})).filterSensitiveLog=function(e){return d({},e)},(Le||(Le={})).filterSensitiveLog=function(e){return d({},e)},(je||(je={})).filterSensitiveLog=function(e){return d({},e)},(De||(De={})).filterSensitiveLog=function(e){return d({},e)},(Ue||(Ue={})).filterSensitiveLog=function(e){return d({},e)},(Be||(Be={})).filterSensitiveLog=function(e){return d({},e)},(Fe||(Fe={})).filterSensitiveLog=function(e){return d({},e)},(ze||(ze={})).filterSensitiveLog=function(e){return d({},e)},(qe||(qe={})).filterSensitiveLog=function(e){return d({},e)},(Ke||(Ke={})).filterSensitiveLog=function(e){return d({},e)},(He||(He={})).filterSensitiveLog=function(e){return d({},e)},(Ve||(Ve={})).filterSensitiveLog=function(e){return d({},e)},(Ge||(Ge={})).filterSensitiveLog=function(e){return d({},e)},(We||(We={})).filterSensitiveLog=function(e){return d({},e)},($e||($e={})).filterSensitiveLog=function(e){return d({},e)},(Ye||(Ye={})).filterSensitiveLog=function(e){return d({},e)},(Je||(Je={})).filterSensitiveLog=function(e){return d({},e)},(Ze||(Ze={})).filterSensitiveLog=function(e){return d({},e)},(Xe||(Xe={})).filterSensitiveLog=function(e){return d({},e)},(Qe||(Qe={})).filterSensitiveLog=function(e){return d({},e)},(et||(et={})).filterSensitiveLog=function(e){return d({},e)},(tt||(tt={})).filterSensitiveLog=function(e){return d({},e)},(nt||(nt={})).filterSensitiveLog=function(e){return d({},e)},(rt||(rt={})).filterSensitiveLog=function(e){return d({},e)},(it||(it={})).filterSensitiveLog=function(e){return d({},e)},(ot||(ot={})).filterSensitiveLog=function(e){return d({},e)},(st||(st={})).filterSensitiveLog=function(e){return d({},e)},(at||(at={})).filterSensitiveLog=function(e){return d({},e)},(ut||(ut={})).filterSensitiveLog=function(e){return d({},e)},(ct||(ct={})).filterSensitiveLog=function(e){return d({},e)},(ft||(ft={})).filterSensitiveLog=function(e){return d({},e)},(lt||(lt={})).filterSensitiveLog=function(e){return d({},e)},(dt||(dt={})).filterSensitiveLog=function(e){return d({},e)},(ht||(ht={})).filterSensitiveLog=function(e){return d({},e)},(pt||(pt={})).filterSensitiveLog=function(e){return d({},e)},(vt||(vt={})).filterSensitiveLog=function(e){return d({},e)},(gt||(gt={})).filterSensitiveLog=function(e){return d({},e)},(mt||(mt={})).filterSensitiveLog=function(e){return d({},e)},(bt||(bt={})).filterSensitiveLog=function(e){return d({},e)},(yt||(yt={})).filterSensitiveLog=function(e){return d({},e)},(wt||(wt={})).filterSensitiveLog=function(e){return d({},e)},(_t||(_t={})).filterSensitiveLog=function(e){return d({},e)},(St||(St={})).filterSensitiveLog=function(e){return d({},e)},(Et||(Et={})).filterSensitiveLog=function(e){return d({},e)},(Mt||(Mt={})).filterSensitiveLog=function(e){return d({},e)},(At||(At={})).filterSensitiveLog=function(e){return d({},e)},(It||(It={})).filterSensitiveLog=function(e){return d({},e)},(kt||(kt={})).filterSensitiveLog=function(e){return d({},e)},(Ot||(Ot={})).filterSensitiveLog=function(e){return d({},e)},(xt||(xt={})).filterSensitiveLog=function(e){return d({},e)},(Ct||(Ct={})).filterSensitiveLog=function(e){return d({},e)},(Tt||(Tt={})).filterSensitiveLog=function(e){return d({},e)},(Pt||(Pt={})).filterSensitiveLog=function(e){return d({},e)},(Nt||(Nt={})).filterSensitiveLog=function(e){return d({},e)},(Rt||(Rt={})).filterSensitiveLog=function(e){return d({},e)},(Lt||(Lt={})).filterSensitiveLog=function(e){return d({},e)},(jt||(jt={})).filterSensitiveLog=function(e){return d({},e)},(Dt||(Dt={})).filterSensitiveLog=function(e){return d({},e)},(Ut||(Ut={})).filterSensitiveLog=function(e){return d({},e)};var Bt=n(2),Ft=n(0),zt=function(e,t){return h(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,f,l,h,v,g,m;return p(this,(function(p){switch(p.label){case 0:return r=[d({},e)],m={},[4,mn(e.body,t)];case 1:switch(n=d.apply(void 0,r.concat([(m.body=p.sent(),m)])),o="UnknownError",o=bn(e,n.body),o){case"BadRequestException":case"com.amazonaws.pinpoint#BadRequestException":return[3,2];case"ForbiddenException":case"com.amazonaws.pinpoint#ForbiddenException":return[3,4];case"InternalServerErrorException":case"com.amazonaws.pinpoint#InternalServerErrorException":return[3,6];case"MethodNotAllowedException":case"com.amazonaws.pinpoint#MethodNotAllowedException":return[3,8];case"NotFoundException":case"com.amazonaws.pinpoint#NotFoundException":return[3,10];case"PayloadTooLargeException":case"com.amazonaws.pinpoint#PayloadTooLargeException":return[3,12];case"TooManyRequestsException":case"com.amazonaws.pinpoint#TooManyRequestsException":return[3,14]}return[3,16];case 2:return s=[{}],[4,Kt(n,t)];case 3:return i=d.apply(void 0,[d.apply(void 0,s.concat([p.sent()])),{name:o,$metadata:vn(e)}]),[3,17];case 4:return a=[{}],[4,Ht(n,t)];case 5:return i=d.apply(void 0,[d.apply(void 0,a.concat([p.sent()])),{name:o,$metadata:vn(e)}]),[3,17];case 6:return u=[{}],[4,Vt(n,t)];case 7:return i=d.apply(void 0,[d.apply(void 0,u.concat([p.sent()])),{name:o,$metadata:vn(e)}]),[3,17];case 8:return c=[{}],[4,Gt(n,t)];case 9:return i=d.apply(void 0,[d.apply(void 0,c.concat([p.sent()])),{name:o,$metadata:vn(e)}]),[3,17];case 10:return f=[{}],[4,Wt(n,t)];case 11:return i=d.apply(void 0,[d.apply(void 0,f.concat([p.sent()])),{name:o,$metadata:vn(e)}]),[3,17];case 12:return l=[{}],[4,$t(n,t)];case 13:return i=d.apply(void 0,[d.apply(void 0,l.concat([p.sent()])),{name:o,$metadata:vn(e)}]),[3,17];case 14:return h=[{}],[4,Yt(n,t)];case 15:return i=d.apply(void 0,[d.apply(void 0,h.concat([p.sent()])),{name:o,$metadata:vn(e)}]),[3,17];case 16:v=n.body,o=v.code||v.Code||o,i=d(d({},v),{name:""+o,message:v.message||v.Message||o,$fault:"client",$metadata:vn(e)}),p.label=17;case 17:return g=i.message||i.Message||o,i.message=g,delete i.Message,[2,Promise.reject(Object.assign(new Error(g),i))]}}))}))},qt=function(e,t){return h(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,f,l,h,v,g,m;return p(this,(function(p){switch(p.label){case 0:return r=[d({},e)],m={},[4,mn(e.body,t)];case 1:switch(n=d.apply(void 0,r.concat([(m.body=p.sent(),m)])),o="UnknownError",o=bn(e,n.body),o){case"BadRequestException":case"com.amazonaws.pinpoint#BadRequestException":return[3,2];case"ForbiddenException":case"com.amazonaws.pinpoint#ForbiddenException":return[3,4];case"InternalServerErrorException":case"com.amazonaws.pinpoint#InternalServerErrorException":return[3,6];case"MethodNotAllowedException":case"com.amazonaws.pinpoint#MethodNotAllowedException":return[3,8];case"NotFoundException":case"com.amazonaws.pinpoint#NotFoundException":return[3,10];case"PayloadTooLargeException":case"com.amazonaws.pinpoint#PayloadTooLargeException":return[3,12];case"TooManyRequestsException":case"com.amazonaws.pinpoint#TooManyRequestsException":return[3,14]}return[3,16];case 2:return s=[{}],[4,Kt(n,t)];case 3:return i=d.apply(void 0,[d.apply(void 0,s.concat([p.sent()])),{name:o,$metadata:vn(e)}]),[3,17];case 4:return a=[{}],[4,Ht(n,t)];case 5:return i=d.apply(void 0,[d.apply(void 0,a.concat([p.sent()])),{name:o,$metadata:vn(e)}]),[3,17];case 6:return u=[{}],[4,Vt(n,t)];case 7:return i=d.apply(void 0,[d.apply(void 0,u.concat([p.sent()])),{name:o,$metadata:vn(e)}]),[3,17];case 8:return c=[{}],[4,Gt(n,t)];case 9:return i=d.apply(void 0,[d.apply(void 0,c.concat([p.sent()])),{name:o,$metadata:vn(e)}]),[3,17];case 10:return f=[{}],[4,Wt(n,t)];case 11:return i=d.apply(void 0,[d.apply(void 0,f.concat([p.sent()])),{name:o,$metadata:vn(e)}]),[3,17];case 12:return l=[{}],[4,$t(n,t)];case 13:return i=d.apply(void 0,[d.apply(void 0,l.concat([p.sent()])),{name:o,$metadata:vn(e)}]),[3,17];case 14:return h=[{}],[4,Yt(n,t)];case 15:return i=d.apply(void 0,[d.apply(void 0,h.concat([p.sent()])),{name:o,$metadata:vn(e)}]),[3,17];case 16:v=n.body,o=v.code||v.Code||o,i=d(d({},v),{name:""+o,message:v.message||v.Message||o,$fault:"client",$metadata:vn(e)}),p.label=17;case 17:return g=i.message||i.Message||o,i.message=g,delete i.Message,[2,Promise.reject(Object.assign(new Error(g),i))]}}))}))},Kt=function(e,t){return h(void 0,void 0,void 0,(function(){var t,n;return p(this,(function(r){return t={name:"BadRequestException",$fault:"client",$metadata:vn(e),Message:void 0,RequestID:void 0},void 0!==(n=e.body).Message&&null!==n.Message&&(t.Message=n.Message),void 0!==n.RequestID&&null!==n.RequestID&&(t.RequestID=n.RequestID),[2,t]}))}))},Ht=function(e,t){return h(void 0,void 0,void 0,(function(){var t,n;return p(this,(function(r){return t={name:"ForbiddenException",$fault:"client",$metadata:vn(e),Message:void 0,RequestID:void 0},void 0!==(n=e.body).Message&&null!==n.Message&&(t.Message=n.Message),void 0!==n.RequestID&&null!==n.RequestID&&(t.RequestID=n.RequestID),[2,t]}))}))},Vt=function(e,t){return h(void 0,void 0,void 0,(function(){var t,n;return p(this,(function(r){return t={name:"InternalServerErrorException",$fault:"server",$metadata:vn(e),Message:void 0,RequestID:void 0},void 0!==(n=e.body).Message&&null!==n.Message&&(t.Message=n.Message),void 0!==n.RequestID&&null!==n.RequestID&&(t.RequestID=n.RequestID),[2,t]}))}))},Gt=function(e,t){return h(void 0,void 0,void 0,(function(){var t,n;return p(this,(function(r){return t={name:"MethodNotAllowedException",$fault:"client",$metadata:vn(e),Message:void 0,RequestID:void 0},void 0!==(n=e.body).Message&&null!==n.Message&&(t.Message=n.Message),void 0!==n.RequestID&&null!==n.RequestID&&(t.RequestID=n.RequestID),[2,t]}))}))},Wt=function(e,t){return h(void 0,void 0,void 0,(function(){var t,n;return p(this,(function(r){return t={name:"NotFoundException",$fault:"client",$metadata:vn(e),Message:void 0,RequestID:void 0},void 0!==(n=e.body).Message&&null!==n.Message&&(t.Message=n.Message),void 0!==n.RequestID&&null!==n.RequestID&&(t.RequestID=n.RequestID),[2,t]}))}))},$t=function(e,t){return h(void 0,void 0,void 0,(function(){var t,n;return p(this,(function(r){return t={name:"PayloadTooLargeException",$fault:"client",$metadata:vn(e),Message:void 0,RequestID:void 0},void 0!==(n=e.body).Message&&null!==n.Message&&(t.Message=n.Message),void 0!==n.RequestID&&null!==n.RequestID&&(t.RequestID=n.RequestID),[2,t]}))}))},Yt=function(e,t){return h(void 0,void 0,void 0,(function(){var t,n;return p(this,(function(r){return t={name:"TooManyRequestsException",$fault:"client",$metadata:vn(e),Message:void 0,RequestID:void 0},void 0!==(n=e.body).Message&&null!==n.Message&&(t.Message=n.Message),void 0!==n.RequestID&&null!==n.RequestID&&(t.RequestID=n.RequestID),[2,t]}))}))},Jt=function(e,t){return d(d(d(d(d(d(d(d({},void 0!==e.AppVersion&&{AppVersion:e.AppVersion}),void 0!==e.Locale&&{Locale:e.Locale}),void 0!==e.Make&&{Make:e.Make}),void 0!==e.Model&&{Model:e.Model}),void 0!==e.ModelVersion&&{ModelVersion:e.ModelVersion}),void 0!==e.Platform&&{Platform:e.Platform}),void 0!==e.PlatformVersion&&{PlatformVersion:e.PlatformVersion}),void 0!==e.Timezone&&{Timezone:e.Timezone})},Zt=function(e,t){return d(d(d(d(d(d({},void 0!==e.City&&{City:e.City}),void 0!==e.Country&&{Country:e.Country}),void 0!==e.Latitude&&{Latitude:e.Latitude}),void 0!==e.Longitude&&{Longitude:e.Longitude}),void 0!==e.PostalCode&&{PostalCode:e.PostalCode}),void 0!==e.Region&&{Region:e.Region})},Xt=function(e,t){return d(d(d(d(d(d(d(d(d(d(d({},void 0!==e.Address&&{Address:e.Address}),void 0!==e.Attributes&&{Attributes:an(e.Attributes,t)}),void 0!==e.ChannelType&&{ChannelType:e.ChannelType}),void 0!==e.Demographic&&{Demographic:Jt(e.Demographic,t)}),void 0!==e.EffectiveDate&&{EffectiveDate:e.EffectiveDate}),void 0!==e.EndpointStatus&&{EndpointStatus:e.EndpointStatus}),void 0!==e.Location&&{Location:Zt(e.Location,t)}),void 0!==e.Metrics&&{Metrics:nn(e.Metrics,t)}),void 0!==e.OptOut&&{OptOut:e.OptOut}),void 0!==e.RequestId&&{RequestId:e.RequestId}),void 0!==e.User&&{User:Qt(e.User,t)})},Qt=function(e,t){return d(d({},void 0!==e.UserAttributes&&{UserAttributes:an(e.UserAttributes,t)}),void 0!==e.UserId&&{UserId:e.UserId})},en=function(e,t){return d({},void 0!==e.BatchItem&&{BatchItem:sn(e.BatchItem,t)})},tn=function(e,t){return e.map((function(e){return e}))},nn=function(e,t){return Object.entries(e).reduce((function(e,t){var n,r=v(t,2),i=r[0],o=r[1];return d(d({},e),((n={})[i]=o,n))}),{})},rn=function(e,t){return Object.entries(e).reduce((function(e,t){var n,r=v(t,2),i=r[0],o=r[1];return d(d({},e),((n={})[i]=o,n))}),{})},on=function(e,t){return Object.entries(e).reduce((function(e,n){var r,i=v(n,2),o=i[0],s=i[1];return d(d({},e),((r={})[o]=function(e,t){return d(d(d(d(d(d(d(d(d(d({},void 0!==e.AppPackageName&&{AppPackageName:e.AppPackageName}),void 0!==e.AppTitle&&{AppTitle:e.AppTitle}),void 0!==e.AppVersionCode&&{AppVersionCode:e.AppVersionCode}),void 0!==e.Attributes&&{Attributes:rn(e.Attributes,t)}),void 0!==e.ClientSdkVersion&&{ClientSdkVersion:e.ClientSdkVersion}),void 0!==e.EventType&&{EventType:e.EventType}),void 0!==e.Metrics&&{Metrics:nn(e.Metrics,t)}),void 0!==e.SdkName&&{SdkName:e.SdkName}),void 0!==e.Session&&{Session:cn(e.Session,t)}),void 0!==e.Timestamp&&{Timestamp:e.Timestamp})}(s,t),r))}),{})},sn=function(e,t){return Object.entries(e).reduce((function(e,n){var r,i=v(n,2),o=i[0],s=i[1];return d(d({},e),((r={})[o]=function(e,t){return d(d({},void 0!==e.Endpoint&&{Endpoint:un(e.Endpoint,t)}),void 0!==e.Events&&{Events:on(e.Events,t)})}(s,t),r))}),{})},an=function(e,t){return Object.entries(e).reduce((function(e,n){var r,i=v(n,2),o=i[0],s=i[1];return d(d({},e),((r={})[o]=tn(s,t),r))}),{})},un=function(e,t){return d(d(d(d(d(d(d(d(d(d(d({},void 0!==e.Address&&{Address:e.Address}),void 0!==e.Attributes&&{Attributes:an(e.Attributes,t)}),void 0!==e.ChannelType&&{ChannelType:e.ChannelType}),void 0!==e.Demographic&&{Demographic:Jt(e.Demographic,t)}),void 0!==e.EffectiveDate&&{EffectiveDate:e.EffectiveDate}),void 0!==e.EndpointStatus&&{EndpointStatus:e.EndpointStatus}),void 0!==e.Location&&{Location:Zt(e.Location,t)}),void 0!==e.Metrics&&{Metrics:nn(e.Metrics,t)}),void 0!==e.OptOut&&{OptOut:e.OptOut}),void 0!==e.RequestId&&{RequestId:e.RequestId}),void 0!==e.User&&{User:Qt(e.User,t)})},cn=function(e,t){return d(d(d(d({},void 0!==e.Duration&&{Duration:e.Duration}),void 0!==e.Id&&{Id:e.Id}),void 0!==e.StartTimestamp&&{StartTimestamp:e.StartTimestamp}),void 0!==e.StopTimestamp&&{StopTimestamp:e.StopTimestamp})},fn=function(e,t){return{Message:void 0!==e.Message&&null!==e.Message?e.Message:void 0,StatusCode:void 0!==e.StatusCode&&null!==e.StatusCode?e.StatusCode:void 0}},ln=function(e,t){return{Results:void 0!==e.Results&&null!==e.Results?hn(e.Results,t):void 0}},dn=function(e,t){return Object.entries(e).reduce((function(e,t){var n,r=v(t,2),i=r[0],o=r[1];return d(d({},e),((n={})[i]=function(e,t){return{Message:void 0!==e.Message&&null!==e.Message?e.Message:void 0,StatusCode:void 0!==e.StatusCode&&null!==e.StatusCode?e.StatusCode:void 0}}(o),n))}),{})},hn=function(e,t){return Object.entries(e).reduce((function(e,n){var r,i=v(n,2),o=i[0],s=i[1];return d(d({},e),((r={})[o]=function(e,t){return{EndpointItemResponse:void 0!==e.EndpointItemResponse&&null!==e.EndpointItemResponse?fn(e.EndpointItemResponse):void 0,EventsItemResponse:void 0!==e.EventsItemResponse&&null!==e.EventsItemResponse?dn(e.EventsItemResponse,t):void 0}}(s,t),r))}),{})},pn=function(e,t){return{Message:void 0!==e.Message&&null!==e.Message?e.Message:void 0,RequestID:void 0!==e.RequestID&&null!==e.RequestID?e.RequestID:void 0}},vn=function(e){return{httpStatusCode:e.statusCode,httpHeaders:e.headers,requestId:e.headers["x-amzn-requestid"]}},gn=function(e,t){return void 0===e&&(e=new Uint8Array),e instanceof Uint8Array?Promise.resolve(e):t.streamCollector(e)||Promise.resolve(new Uint8Array)},mn=function(e,t){return function(e,t){return gn(e,t).then((function(e){return t.utf8Encoder(e)}))}(e,t).then((function(e){return e.length?JSON.parse(e):{}}))},bn=function(e,t){var n,r,i=function(e){var t=e;return t.indexOf(":")>=0&&(t=t.split(":")[0]),t.indexOf("#")>=0&&(t=t.split("#")[1]),t},o=(n=e.headers,r="x-amzn-errortype",Object.keys(n).find((function(e){return e.toLowerCase()===r.toLowerCase()})));return void 0!==o?i(e.headers[o]):void 0!==t.code?i(t.code):void 0!==t.__type?i(t.__type):""},yn=n(10),wn=function(e){function t(t){var n=e.call(this)||this;return n.input=t,n}return l(t,e),t.prototype.resolveMiddleware=function(e,t,n){this.middlewareStack.use(Object(yn.a)(t,this.serialize,this.deserialize));var r=e.concat(this.middlewareStack),i=t.logger,o={logger:i,clientName:"PinpointClient",commandName:"PutEventsCommand",inputFilterSensitiveLog:Ie.filterSensitiveLog,outputFilterSensitiveLog:ke.filterSensitiveLog};"function"==typeof i.info&&i.info({clientName:"PinpointClient",commandName:"PutEventsCommand"});var s=t.requestHandler;return r.resolve((function(e){return s.handle(e.request,n||{})}),o)},t.prototype.serialize=function(e,t){return function(e,t){return h(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,f;return p(this,(function(l){switch(l.label){case 0:if(n={"Content-Type":"application/json"},r="/v1/apps/{ApplicationId}/events",void 0===e.ApplicationId)throw new Error("No value provided for input HTTP label: ApplicationId.");if((i=e.ApplicationId).length<=0)throw new Error("Empty value provided for input HTTP label: ApplicationId.");return r=r.replace("{ApplicationId}",Object(Ft.f)(i)),void 0!==e.EventsRequest&&(o=en(e.EventsRequest,t)),void 0===o&&(o={}),o=JSON.stringify(o),[4,t.endpoint()];case 1:return s=l.sent(),a=s.hostname,u=s.protocol,c=void 0===u?"https":u,f=s.port,[2,new Bt.a({protocol:c,hostname:a,port:f,method:"POST",headers:n,path:r,body:o})]}}))}))}(e,t)},t.prototype.deserialize=function(e,t){return function(e,t){return h(void 0,void 0,void 0,(function(){var n,r;return p(this,(function(i){switch(i.label){case 0:return 202!==e.statusCode&&e.statusCode>=300?[2,zt(e,t)]:(n={$metadata:vn(e),EventsResponse:void 0},[4,mn(e.body,t)]);case 1:return r=i.sent(),n.EventsResponse=ln(r,t),[2,Promise.resolve(n)]}}))}))}(e,t)},t}(Ft.b),_n=function(e){function t(t){var n=e.call(this)||this;return n.input=t,n}return l(t,e),t.prototype.resolveMiddleware=function(e,t,n){this.middlewareStack.use(Object(yn.a)(t,this.serialize,this.deserialize));var r=e.concat(this.middlewareStack),i=t.logger,o={logger:i,clientName:"PinpointClient",commandName:"UpdateEndpointCommand",inputFilterSensitiveLog:ct.filterSensitiveLog,outputFilterSensitiveLog:ft.filterSensitiveLog};"function"==typeof i.info&&i.info({clientName:"PinpointClient",commandName:"UpdateEndpointCommand"});var s=t.requestHandler;return r.resolve((function(e){return s.handle(e.request,n||{})}),o)},t.prototype.serialize=function(e,t){return function(e,t){return h(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,f;return p(this,(function(l){switch(l.label){case 0:if(n={"Content-Type":"application/json"},r="/v1/apps/{ApplicationId}/endpoints/{EndpointId}",void 0===e.ApplicationId)throw new Error("No value provided for input HTTP label: ApplicationId.");if((i=e.ApplicationId).length<=0)throw new Error("Empty value provided for input HTTP label: ApplicationId.");if(r=r.replace("{ApplicationId}",Object(Ft.f)(i)),void 0===e.EndpointId)throw new Error("No value provided for input HTTP label: EndpointId.");if((i=e.EndpointId).length<=0)throw new Error("Empty value provided for input HTTP label: EndpointId.");return r=r.replace("{EndpointId}",Object(Ft.f)(i)),void 0!==e.EndpointRequest&&(o=Xt(e.EndpointRequest,t)),void 0===o&&(o={}),o=JSON.stringify(o),[4,t.endpoint()];case 1:return s=l.sent(),a=s.hostname,u=s.protocol,c=void 0===u?"https":u,f=s.port,[2,new Bt.a({protocol:c,hostname:a,port:f,method:"PUT",headers:n,path:r,body:o})]}}))}))}(e,t)},t.prototype.deserialize=function(e,t){return function(e,t){return h(void 0,void 0,void 0,(function(){var n,r;return p(this,(function(i){switch(i.label){case 0:return 202!==e.statusCode&&e.statusCode>=300?[2,qt(e,t)]:(n={$metadata:vn(e),MessageBody:void 0},[4,mn(e.body,t)]);case 1:return r=i.sent(),n.MessageBody=pn(r,t),[2,Promise.resolve(n)]}}))}))}(e,t)},t}(Ft.b),Sn=n(149),En=n(38),Mn=n(18),An=n(24),In=n(11),kn=n(39),On=n(17),xn=n(40),Cn=n(41),Tn=n(15),Pn=new Set(["ap-east-1","ap-northeast-1","ap-northeast-2","ap-south-1","ap-southeast-1","ap-southeast-2","ca-central-1","eu-central-1","eu-north-1","eu-west-1","eu-west-2","eu-west-3","me-south-1","sa-east-1","us-east-1","us-east-2","us-west-1","us-west-2"]),Nn=new Set(["cn-north-1","cn-northwest-1"]),Rn=new Set(["us-iso-east-1"]),Ln=new Set(["us-isob-east-1"]),jn=new Set(["us-gov-east-1","us-gov-west-1"]),Dn=d(d({},{apiVersion:"2016-12-01",disableHostPrefix:!1,logger:{},regionInfoProvider:function(e,t){var n=void 0;switch(e){case"ap-south-1":n={hostname:"pinpoint.ap-south-1.amazonaws.com",partition:"aws",signingService:"mobiletargeting"};break;case"ap-southeast-2":n={hostname:"pinpoint.ap-southeast-2.amazonaws.com",partition:"aws",signingService:"mobiletargeting"};break;case"eu-central-1":n={hostname:"pinpoint.eu-central-1.amazonaws.com",partition:"aws",signingService:"mobiletargeting"};break;case"eu-west-1":n={hostname:"pinpoint.eu-west-1.amazonaws.com",partition:"aws",signingService:"mobiletargeting"};break;case"us-east-1":n={hostname:"pinpoint.us-east-1.amazonaws.com",partition:"aws",signingService:"mobiletargeting"};break;case"us-west-2":n={hostname:"pinpoint.us-west-2.amazonaws.com",partition:"aws",signingService:"mobiletargeting"};break;default:Pn.has(e)&&(n={hostname:"pinpoint.{region}.amazonaws.com".replace("{region}",e),partition:"aws",signingService:"mobiletargeting"}),Nn.has(e)&&(n={hostname:"pinpoint.{region}.amazonaws.com.cn".replace("{region}",e),partition:"aws-cn"}),Rn.has(e)&&(n={hostname:"pinpoint.{region}.c2s.ic.gov".replace("{region}",e),partition:"aws-iso"}),Ln.has(e)&&(n={hostname:"pinpoint.{region}.sc2s.sgov.gov".replace("{region}",e),partition:"aws-iso-b"}),jn.has(e)&&(n={hostname:"pinpoint.{region}.amazonaws.com".replace("{region}",e),partition:"aws-us-gov"}),void 0===n&&(n={hostname:"pinpoint.{region}.amazonaws.com".replace("{region}",e),partition:"aws",signingService:"mobiletargeting"})}return Promise.resolve(n)},signingName:"mobiletargeting"}),{runtime:"browser",base64Decoder:On.a,base64Encoder:On.b,bodyLengthChecker:xn.a,credentialDefaultProvider:Object(An.a)("Credential is missing"),defaultUserAgent:Object(Cn.a)(Sn.name,Sn.version),maxAttempts:In.a,region:Object(An.a)("Region is missing"),requestHandler:new Mn.a,sha256:En.Sha256,streamCollector:Mn.b,urlParser:kn.a,utf8Decoder:Tn.a,utf8Encoder:Tn.b}),Un=n(22),Bn=n(37),Fn=n(21),zn=n(43),qn=n(25),Kn=n(23),Hn=function(e){function t(t){var n=this,r=d(d({},Dn),t),i=Object(Un.b)(r),o=Object(Un.a)(i),s=Object(qn.b)(o),a=Object(In.c)(s),u=Object(Kn.b)(a),c=Object(Fn.b)(u);return(n=e.call(this,c)||this).config=c,n.middlewareStack.use(Object(qn.a)(n.config)),n.middlewareStack.use(Object(In.b)(n.config)),n.middlewareStack.use(Object(Kn.a)(n.config)),n.middlewareStack.use(Object(Bn.a)(n.config)),n.middlewareStack.use(Object(Fn.a)(n.config)),n.middlewareStack.use(Object(zn.a)(n.config)),n}return l(t,e),t.prototype.destroy=function(){e.prototype.destroy.call(this)},t}(Ft.a),Vn=n(26),Gn=n(27),Wn=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))},$n=function(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},Jn=function(){for(var e=[],t=0;tthis._config.bufferSize)return Zn.debug("Exceeded analytics events buffer size"),e.handlers.reject(new Error("Exceeded the size of analytics events buffer"));var n=((t={})[e.params.event.eventId]=e,t);this._buffer.push(n)},e.prototype.pause=function(){this._pause=!0},e.prototype.resume=function(){this._pause=!1},e.prototype.updateClient=function(e){this._client=e},e.prototype.flush=function(){this._flush=!0},e.prototype._startLoop=function(){this._interval&&clearInterval(this._interval);var e=this._config.flushInterval;this._interval=setInterval(this._sendBatch,e)},e.prototype._sendBatch=function(){var e=this._buffer.length;if(this._flush&&!e&&clearInterval(this._interval),!this._pause&&e){var t=this._config.flushSize,n=Math.min(t,e),r=this._buffer.splice(0,n);this._putEvents(r)}},e.prototype._putEvents=function(e){return Wn(this,void 0,void 0,(function(){var t,n,r,i,o;return $n(this,(function(s){switch(s.label){case 0:t=this._bufferToMap(e),n=this._generateBatchEventParams(t),s.label=1;case 1:return s.trys.push([1,3,,4]),r=new wn(n),[4,this._client.send(r)];case 2:return i=s.sent(),this._processPutEventsSuccessResponse(i,t),[3,4];case 3:return o=s.sent(),[2,this._handlePutEventsFailure(o,t)];case 4:return[2]}}))}))},e.prototype._generateBatchEventParams=function(e){var t={ApplicationId:"",EventsRequest:{BatchItem:{}}};return Object.values(e).forEach((function(e){var n=e.params,r=n.event,i=n.timestamp,o=n.config,s=r.name,a=r.attributes,u=r.metrics,c=r.eventId,f=r.session,l=o.appId,d=o.endpointId,h=t.EventsRequest.BatchItem;t.ApplicationId=t.ApplicationId||l,h[d]||(h[d]={Endpoint:{},Events:{}}),h[d].Events[c]={EventType:s,Timestamp:new Date(i).toISOString(),Attributes:a,Metrics:u,Session:f}})),t},e.prototype._handlePutEventsFailure=function(e,t){Zn.debug("_putEvents Failed: ",e);var n=e.$metadata&&e.$metadata.httpStatusCode;if(Xn.includes(n)){var r=Object.values(t);this._retry(r)}else;},e.prototype._processPutEventsSuccessResponse=function(e,t){var n=e.EventsResponse.Results,r=[];Object.entries(n).forEach((function(e){var n=Yn(e,2),i=n[0],o=n[1].EventsItemResponse;Object.entries(o).forEach((function(e){var n,o,s=Yn(e,2),a=s[0],u=s[1],c=u.StatusCode,f=u.Message,l=t[a],d={EventsResponse:{Results:(n={},n[i]={EventsItemResponse:(o={},o[a]={StatusCode:c,Message:f},o)},n)}};if(Qn.includes(c))l.handlers.resolve(d);else{if(!Xn.includes(c)){var h=l.params.event.name;return Zn.error("event "+a+" : "+h+" failed with error: "+f),l.handlers.reject(d)}r.push(l)}}))})),r.length&&this._retry(r)},e.prototype._retry=function(e){var t,n=[];e.forEach((function(e){var t,r=e.params,i=r.event,o=i.eventId,s=i.name;if(r.resendLimit-- >0)return Zn.debug("resending event "+o+" : "+s+" with "+r.resendLimit+" retry attempts remaining"),void n.push((t={},t[o]=e,t));Zn.debug("no retry attempts remaining for event "+o+" : "+s)})),(t=this._buffer).unshift.apply(t,Jn(n))},e.prototype._bufferToMap=function(e){return e.reduce((function(e,t){var n=Yn(Object.entries(t),1),r=Yn(n[0],2),i=r[0],o=r[1];return e[i]=o,e}),{})},e}();function tr(e){return(tr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var nr=function(){return(nr=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0?(ur.debug("resending event "+e.eventName+" with "+e.resendLimit+" retry times left"),this._pinpointPutEvents(e,t)):ur.debug("retry times used up for event "+e.eventName)},e.prototype._updateEndpoint=function(e){return rr(this,void 0,void 0,(function(){var t,n,r,i,o,s,u,c,f,l,d,h;return ir(this,(function(p){switch(p.label){case 0:t=e.params,n=e.handlers,r=t.config,i=t.event,o=r.appId,s=r.endpointId,u=this._endpointRequest(r,a.a.transferKeyToLowerCase(i,[],["attributes","userAttributes","Attributes","UserAttributes"])),c={ApplicationId:o,EndpointId:s,EndpointRequest:u},p.label=1;case 1:return p.trys.push([1,3,,4]),f=new _n(c),[4,this.pinpointClient.send(f)];case 2:return l=p.sent(),ur.debug("updateEndpoint success",l),this._endpointGenerating=!1,this._resumeBuffer(),n.resolve(l),[2];case 3:return d=p.sent(),h={err:d,update_params:c,endpointObject:e},[2,this._handleEndpointUpdateFailure(h)];case 4:return[2]}}))}))},e.prototype._handleEndpointUpdateFailure=function(e){return rr(this,void 0,void 0,(function(){var t,n,r;return ir(this,(function(i){switch(t=e.err,n=e.endpointObject,r=t.$metadata&&t.$metadata.httpStatusCode,ur.debug("updateEndpoint error",t),r){case 403:return[2,this._handleEndpointUpdateForbidden(e)];default:if(cr.includes(r))return!0,[2,this._retryEndpointUpdate(n,!0)];ur.error("updateEndpoint failed",t),n.handlers.reject(t)}return[2]}))}))},e.prototype._handleEndpointUpdateForbidden=function(e){var t=e.err,n=e.endpointObject,r=t.code,i=t.retryable;if("ExpiredTokenException"!==r&&!i)return n.handlers.reject(t);this._retryEndpointUpdate(n)},e.prototype._retryEndpointUpdate=function(e,t){void 0===t&&(t=!1),ur.debug("_retryEndpointUpdate",e);var n=e.params,r=n.config.resendLimit;if(n.resendLimit="number"==typeof n.resendLimit?n.resendLimit:r,n.resendLimit-- >0)return ur.debug("resending endpoint update "+n.event.eventId+" with "+n.resendLimit+" retry attempts remaining"),void(this._endpointBuffer.length?this._endpointBuffer.unshift(e):this._updateEndpoint(e));ur.warn("resending endpoint update "+n.event.eventId+" failed after "+n.config.resendLimit+" attempts"),this._endpointGenerating&&ur.error("Initial endpoint update failed. ")},e.prototype._initClients=function(e){return rr(this,void 0,void 0,(function(){var t,n;return ir(this,(function(r){return ur.debug("init clients"),this.pinpointClient&&this._config.credentials&&this._config.credentials.sessionToken===e.sessionToken&&this._config.credentials.identityId===e.identityId?(ur.debug("no change for aws credentials, directly return from init"),[2]):(t=this._config.credentials?this._config.credentials.identityId:null,this._config.credentials=e,n=this._config.region,ur.debug("init clients with credentials",e),this.pinpointClient=new Hn({region:n,credentials:e,customUserAgent:Object(u.b)()}),this.pinpointClient.middlewareStack.addRelativeTo((function(e){return function(t){return delete t.request.headers["amz-sdk-invocation-id"],delete t.request.headers["amz-sdk-request"],e(t)}}),{step:"finalizeRequest",relation:"after",toMiddleware:"retryMiddleware"}),this._bufferExists()&&t===e.identityId?this._updateBufferClient():this._initBuffer(),this._customizePinpointClientReq(),[2])}))}))},e.prototype._bufferExists=function(){return this._buffer&&this._buffer instanceof er},e.prototype._initBuffer=function(){this._bufferExists()&&this._flushBuffer(),this._buffer=new er(this.pinpointClient,this._config),this._endpointGenerating&&this._buffer.pause()},e.prototype._updateBufferClient=function(){this._bufferExists()&&this._buffer.updateClient(this.pinpointClient)},e.prototype._flushBuffer=function(){this._bufferExists()&&(this._buffer.flush(),this._buffer=null)},e.prototype._resumeBuffer=function(){this._bufferExists()&&this._buffer.resume()},e.prototype._customizePinpointClientReq=function(){},e.prototype._getEndpointId=function(e){return rr(this,void 0,void 0,(function(){var t;return ir(this,(function(n){switch(n.label){case 0:return[4,Vn.a.getItem(e)];case 1:return t=n.sent(),ur.debug("endpointId from cache",t,"type",tr(t)),t||(t=Object(Gn.v1)(),Vn.a.setItem(e,t)),[2,t]}}))}))},e.prototype._endpointRequest=function(e,t){var n=e.credentials,r=this._clientInfo||{},i=e.clientContext||{},o=e.endpoint||{},s={appVersion:r.appVersion,make:r.make,model:r.model,modelVersion:r.version,platform:r.platform},u=(i.clientId,i.appTitle,i.appVersionName,i.appVersionCode,i.appPackageName,or(i,["clientId","appTitle","appVersionName","appVersionCode","appPackageName"])),c=t.address?"android"===r.platform?"GCM":"APNS":void 0,f=nr(nr(nr({channelType:c,requestId:Object(Gn.v1)(),effectiveDate:(new Date).toISOString()},o),t),{attributes:nr(nr({},o.attributes),t.attributes),demographic:nr(nr(nr(nr({},s),u),o.demographic),t.demographic),location:nr(nr({},o.location),t.location),metrics:nr(nr({},o.metrics),t.metrics),user:{userId:t.userId||o.userId||n.identityId,userAttributes:nr(nr({},o.userAttributes),t.userAttributes)}}),l=(f.userId,f.userAttributes,f.name,f.session,f.eventId,f.immediate,or(f,["userId","userAttributes","name","session","eventId","immediate"]));return a.a.transferKeyToUpperCase(l,[],["metrics","userAttributes","attributes"])},e.prototype._eventError=function(e){ur.error("record event failed.",e),ur.warn('Please ensure you have updated your Pinpoint IAM Policy with the Action: "mobiletargeting:PutEvents" in order to record events')},e.prototype._getCredentials=function(){return rr(this,void 0,void 0,(function(){var e,t;return ir(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,c.a.get()];case 1:return(e=n.sent())?(ur.debug("set credentials for analytics",e),[2,c.a.shear(e)]):[2,null];case 2:return t=n.sent(),ur.debug("ensure credentials error",t),[2,null];case 3:return[2]}}))}))},e.category="Analytics",e.providerName="AWSPinpoint",e}()},function(e,t,n){"use strict";n.d(t,"a",(function(){return Ht}));var r=n(44),i=n(50),o=n(89),s=function(e,t){return(s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(e,t)};function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}s(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var u=function(){return(u=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=300?[2,Fe(e,t)]:[4,dt(e.body,t)];case 1:return n=o.sent(),{},r=st(n,t),i=u({$metadata:ct(e)},r),[2,Promise.resolve(i)]}}))}))}(e,t)},t}(pt.b),gt=n(150),mt=n(38),bt=n(110),yt=n(18),wt=n(24),_t=n(11),St=n(39),Et=n(17),Mt=n(40),At=n(41),It=n(15),kt=new Set(["ap-east-1","ap-northeast-1","ap-northeast-2","ap-south-1","ap-southeast-1","ap-southeast-2","ca-central-1","eu-central-1","eu-north-1","eu-west-1","eu-west-2","eu-west-3","me-south-1","sa-east-1","us-east-1","us-east-2","us-west-1","us-west-2"]),Ot=new Set(["cn-north-1","cn-northwest-1"]),xt=new Set(["us-iso-east-1"]),Ct=new Set(["us-isob-east-1"]),Tt=new Set(["us-gov-east-1","us-gov-west-1"]),Pt=u(u({},{apiVersion:"2013-12-02",disableHostPrefix:!1,logger:{},regionInfoProvider:function(e,t){var n=void 0;switch(e){case"ap-east-1":n={hostname:"kinesis.ap-east-1.amazonaws.com",partition:"aws"};break;case"ap-northeast-1":n={hostname:"kinesis.ap-northeast-1.amazonaws.com",partition:"aws"};break;case"ap-northeast-2":n={hostname:"kinesis.ap-northeast-2.amazonaws.com",partition:"aws"};break;case"ap-south-1":n={hostname:"kinesis.ap-south-1.amazonaws.com",partition:"aws"};break;case"ap-southeast-1":n={hostname:"kinesis.ap-southeast-1.amazonaws.com",partition:"aws"};break;case"ap-southeast-2":n={hostname:"kinesis.ap-southeast-2.amazonaws.com",partition:"aws"};break;case"ca-central-1":n={hostname:"kinesis.ca-central-1.amazonaws.com",partition:"aws"};break;case"cn-north-1":n={hostname:"kinesis.cn-north-1.amazonaws.com.cn",partition:"aws-cn"};break;case"cn-northwest-1":n={hostname:"kinesis.cn-northwest-1.amazonaws.com.cn",partition:"aws-cn"};break;case"eu-central-1":n={hostname:"kinesis.eu-central-1.amazonaws.com",partition:"aws"};break;case"eu-north-1":n={hostname:"kinesis.eu-north-1.amazonaws.com",partition:"aws"};break;case"eu-west-1":n={hostname:"kinesis.eu-west-1.amazonaws.com",partition:"aws"};break;case"eu-west-2":n={hostname:"kinesis.eu-west-2.amazonaws.com",partition:"aws"};break;case"eu-west-3":n={hostname:"kinesis.eu-west-3.amazonaws.com",partition:"aws"};break;case"me-south-1":n={hostname:"kinesis.me-south-1.amazonaws.com",partition:"aws"};break;case"sa-east-1":n={hostname:"kinesis.sa-east-1.amazonaws.com",partition:"aws"};break;case"us-east-1":n={hostname:"kinesis.us-east-1.amazonaws.com",partition:"aws"};break;case"us-east-2":n={hostname:"kinesis.us-east-2.amazonaws.com",partition:"aws"};break;case"us-gov-east-1":n={hostname:"kinesis.us-gov-east-1.amazonaws.com",partition:"aws-us-gov"};break;case"us-gov-west-1":n={hostname:"kinesis.us-gov-west-1.amazonaws.com",partition:"aws-us-gov"};break;case"us-iso-east-1":n={hostname:"kinesis.us-iso-east-1.c2s.ic.gov",partition:"aws-iso"};break;case"us-isob-east-1":n={hostname:"kinesis.us-isob-east-1.sc2s.sgov.gov",partition:"aws-iso-b"};break;case"us-west-1":n={hostname:"kinesis.us-west-1.amazonaws.com",partition:"aws"};break;case"us-west-2":n={hostname:"kinesis.us-west-2.amazonaws.com",partition:"aws"};break;default:kt.has(e)&&(n={hostname:"kinesis.{region}.amazonaws.com".replace("{region}",e),partition:"aws"}),Ot.has(e)&&(n={hostname:"kinesis.{region}.amazonaws.com.cn".replace("{region}",e),partition:"aws-cn"}),xt.has(e)&&(n={hostname:"kinesis.{region}.c2s.ic.gov".replace("{region}",e),partition:"aws-iso"}),Ct.has(e)&&(n={hostname:"kinesis.{region}.sc2s.sgov.gov".replace("{region}",e),partition:"aws-iso-b"}),Tt.has(e)&&(n={hostname:"kinesis.{region}.amazonaws.com".replace("{region}",e),partition:"aws-us-gov"}),void 0===n&&(n={hostname:"kinesis.{region}.amazonaws.com".replace("{region}",e),partition:"aws"})}return Promise.resolve(n)},signingName:"kinesis"}),{runtime:"browser",base64Decoder:Et.a,base64Encoder:Et.b,bodyLengthChecker:Mt.a,credentialDefaultProvider:Object(wt.a)("Credential is missing"),defaultUserAgent:Object(At.a)(gt.name,gt.version),eventStreamSerdeProvider:bt.a,maxAttempts:_t.a,region:Object(wt.a)("Region is missing"),requestHandler:new yt.a,sha256:mt.Sha256,streamCollector:yt.b,urlParser:St.a,utf8Decoder:It.a,utf8Encoder:It.b}),Nt=n(22),Rt=n(112),Lt=n(37),jt=n(21),Dt=n(43),Ut=n(25),Bt=n(23),Ft=function(e){function t(t){var n=this,r=u(u({},Pt),t),i=Object(Nt.b)(r),o=Object(Nt.a)(i),s=Object(Ut.b)(o),a=Object(_t.c)(s),c=Object(Bt.b)(a),f=Object(jt.b)(c),l=Object(Rt.a)(f);return(n=e.call(this,l)||this).config=l,n.middlewareStack.use(Object(Ut.a)(n.config)),n.middlewareStack.use(Object(_t.b)(n.config)),n.middlewareStack.use(Object(Bt.a)(n.config)),n.middlewareStack.use(Object(Lt.a)(n.config)),n.middlewareStack.use(Object(jt.a)(n.config)),n.middlewareStack.use(Object(Dt.a)(n.config)),n}return a(t,e),t.prototype.destroy=function(){e.prototype.destroy.call(this)},t}(pt.a),zt=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))},qt=function(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=0&&this.changeListeners.splice(t,1)},e}(),a=n(33),u=Object(a.b)().isBrowser,c=function(){function e(e){void 0===e&&(e={}),this.cookies=new s,this.store=u?window.localStorage:Object.create(null),this.cookies=e.req?new s(e.req.headers.cookie):new s,Object.assign(this.store,this.cookies.getAll())}return Object.defineProperty(e.prototype,"length",{get:function(){return Object.entries(this.store).length},enumerable:!0,configurable:!0}),e.prototype.clear=function(){var e=this;Array.from(new Array(this.length)).map((function(t,n){return e.key(n)})).forEach((function(t){return e.removeItem(t)}))},e.prototype.getItem=function(e){return this.getLocalItem(e)},e.prototype.getLocalItem=function(e){return Object.prototype.hasOwnProperty.call(this.store,e)?this.store[e]:null},e.prototype.getUniversalItem=function(e){return this.cookies.get(e)},e.prototype.key=function(e){return Object.keys(this.store)[e]},e.prototype.removeItem=function(e){this.removeLocalItem(e),this.removeUniversalItem(e)},e.prototype.removeLocalItem=function(e){delete this.store[e]},e.prototype.removeUniversalItem=function(e){this.cookies.remove(e,{path:"/"})},e.prototype.setItem=function(e,t){switch(this.setLocalItem(e,t),e.split(".").pop()){case"LastAuthUser":case"accessToken":case"idToken":this.setUniversalItem(e,t)}},e.prototype.setLocalItem=function(e,t){this.store[e]=t},e.prototype.setUniversalItem=function(e,t){this.cookies.set(e,t,{path:"/",sameSite:!0,secure:"localhost"!==window.location.hostname})},e}()},function(e){e.exports=JSON.parse('{"name":"@aws-sdk/client-cognito-identity","description":"AWS SDK for JavaScript Cognito Identity Client for Node.js, Browser and React Native","version":"1.0.0-rc.4","scripts":{"clean":"npm run remove-definitions && npm run remove-dist","build-documentation":"npm run clean && typedoc ./","prepublishOnly":"yarn build","pretest":"yarn build:cjs","remove-definitions":"rimraf ./types","remove-dist":"rimraf ./dist","remove-documentation":"rimraf ./docs","test:unit":"mocha **/cjs/**/*.spec.js","test:e2e":"mocha **/cjs/**/*.ispec.js && karma start karma.conf.js","test":"yarn test:unit","build:cjs":"tsc -p tsconfig.json","build:es":"tsc -p tsconfig.es.json","build":"yarn build:cjs && yarn build:es"},"main":"./dist/cjs/index.js","types":"./types/index.d.ts","module":"./dist/es/index.js","browser":{"./runtimeConfig":"./runtimeConfig.browser"},"react-native":{"./runtimeConfig":"./runtimeConfig.native"},"sideEffects":false,"dependencies":{"@aws-crypto/sha256-browser":"^1.0.0","@aws-crypto/sha256-js":"^1.0.0","@aws-sdk/config-resolver":"1.0.0-rc.3","@aws-sdk/credential-provider-node":"1.0.0-rc.3","@aws-sdk/fetch-http-handler":"1.0.0-rc.3","@aws-sdk/hash-node":"1.0.0-rc.3","@aws-sdk/invalid-dependency":"1.0.0-rc.3","@aws-sdk/middleware-content-length":"1.0.0-rc.3","@aws-sdk/middleware-host-header":"1.0.0-rc.3","@aws-sdk/middleware-logger":"1.0.0-rc.4","@aws-sdk/middleware-retry":"1.0.0-rc.4","@aws-sdk/middleware-serde":"1.0.0-rc.3","@aws-sdk/middleware-signing":"1.0.0-rc.3","@aws-sdk/middleware-stack":"1.0.0-rc.4","@aws-sdk/middleware-user-agent":"1.0.0-rc.3","@aws-sdk/node-config-provider":"1.0.0-rc.3","@aws-sdk/node-http-handler":"1.0.0-rc.3","@aws-sdk/protocol-http":"1.0.0-rc.3","@aws-sdk/smithy-client":"1.0.0-rc.4","@aws-sdk/types":"1.0.0-rc.3","@aws-sdk/url-parser-browser":"1.0.0-rc.3","@aws-sdk/url-parser-node":"1.0.0-rc.3","@aws-sdk/util-base64-browser":"1.0.0-rc.3","@aws-sdk/util-base64-node":"1.0.0-rc.3","@aws-sdk/util-body-length-browser":"1.0.0-rc.3","@aws-sdk/util-body-length-node":"1.0.0-rc.3","@aws-sdk/util-user-agent-browser":"1.0.0-rc.3","@aws-sdk/util-user-agent-node":"1.0.0-rc.3","@aws-sdk/util-utf8-browser":"1.0.0-rc.3","@aws-sdk/util-utf8-node":"1.0.0-rc.3","tslib":"^2.0.0"},"devDependencies":{"@aws-sdk/client-documentation-generator":"1.0.0-rc.3","@aws-sdk/client-iam":"1.0.0-rc.4","@types/chai":"^4.2.11","@types/mocha":"^7.0.2","@types/node":"^12.7.5","jest":"^26.1.0","rimraf":"^3.0.0","typedoc":"^0.17.8","typescript":"~4.0.2"},"engines":{"node":">=10.0.0"},"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","homepage":"https://github.com/aws/aws-sdk-js-v3/tree/master/clients/client-cognito-identity","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"clients/client-cognito-identity"}}')},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n(1).__exportStar(n(385),t)},function(e){e.exports=JSON.parse('{"name":"@aws-sdk/client-pinpoint","description":"AWS SDK for JavaScript Pinpoint Client for Node.js, Browser and React Native","version":"1.0.0-rc.4","scripts":{"clean":"npm run remove-definitions && npm run remove-dist","build-documentation":"npm run clean && typedoc ./","prepublishOnly":"yarn build","pretest":"yarn build:cjs","remove-definitions":"rimraf ./types","remove-dist":"rimraf ./dist","remove-documentation":"rimraf ./docs","test":"exit 0","build:cjs":"tsc -p tsconfig.json","build:es":"tsc -p tsconfig.es.json","build":"yarn build:cjs && yarn build:es"},"main":"./dist/cjs/index.js","types":"./types/index.d.ts","module":"./dist/es/index.js","browser":{"./runtimeConfig":"./runtimeConfig.browser"},"react-native":{"./runtimeConfig":"./runtimeConfig.native"},"sideEffects":false,"dependencies":{"@aws-crypto/sha256-browser":"^1.0.0","@aws-crypto/sha256-js":"^1.0.0","@aws-sdk/config-resolver":"1.0.0-rc.3","@aws-sdk/credential-provider-node":"1.0.0-rc.3","@aws-sdk/fetch-http-handler":"1.0.0-rc.3","@aws-sdk/hash-node":"1.0.0-rc.3","@aws-sdk/invalid-dependency":"1.0.0-rc.3","@aws-sdk/middleware-content-length":"1.0.0-rc.3","@aws-sdk/middleware-host-header":"1.0.0-rc.3","@aws-sdk/middleware-logger":"1.0.0-rc.4","@aws-sdk/middleware-retry":"1.0.0-rc.4","@aws-sdk/middleware-serde":"1.0.0-rc.3","@aws-sdk/middleware-signing":"1.0.0-rc.3","@aws-sdk/middleware-stack":"1.0.0-rc.4","@aws-sdk/middleware-user-agent":"1.0.0-rc.3","@aws-sdk/node-config-provider":"1.0.0-rc.3","@aws-sdk/node-http-handler":"1.0.0-rc.3","@aws-sdk/protocol-http":"1.0.0-rc.3","@aws-sdk/smithy-client":"1.0.0-rc.4","@aws-sdk/types":"1.0.0-rc.3","@aws-sdk/url-parser-browser":"1.0.0-rc.3","@aws-sdk/url-parser-node":"1.0.0-rc.3","@aws-sdk/util-base64-browser":"1.0.0-rc.3","@aws-sdk/util-base64-node":"1.0.0-rc.3","@aws-sdk/util-body-length-browser":"1.0.0-rc.3","@aws-sdk/util-body-length-node":"1.0.0-rc.3","@aws-sdk/util-user-agent-browser":"1.0.0-rc.3","@aws-sdk/util-user-agent-node":"1.0.0-rc.3","@aws-sdk/util-utf8-browser":"1.0.0-rc.3","@aws-sdk/util-utf8-node":"1.0.0-rc.3","tslib":"^2.0.0"},"devDependencies":{"@aws-sdk/client-documentation-generator":"1.0.0-rc.3","@types/node":"^12.7.5","jest":"^26.1.0","rimraf":"^3.0.0","typedoc":"^0.17.8","typescript":"~4.0.2"},"engines":{"node":">=10.0.0"},"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","homepage":"https://github.com/aws/aws-sdk-js-v3/tree/master/clients/client-pinpoint","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"clients/client-pinpoint"}}')},function(e){e.exports=JSON.parse('{"name":"@aws-sdk/client-kinesis","description":"AWS SDK for JavaScript Kinesis Client for Node.js, Browser and React Native","version":"1.0.0-rc.4","scripts":{"clean":"npm run remove-definitions && npm run remove-dist","build-documentation":"npm run clean && typedoc ./","prepublishOnly":"yarn build","pretest":"yarn build:cjs","remove-definitions":"rimraf ./types","remove-dist":"rimraf ./dist","remove-documentation":"rimraf ./docs","test":"exit 0","build:cjs":"tsc -p tsconfig.json","build:es":"tsc -p tsconfig.es.json","build":"yarn build:cjs && yarn build:es"},"main":"./dist/cjs/index.js","types":"./types/index.d.ts","module":"./dist/es/index.js","browser":{"./runtimeConfig":"./runtimeConfig.browser"},"react-native":{"./runtimeConfig":"./runtimeConfig.native"},"sideEffects":false,"dependencies":{"@aws-crypto/sha256-browser":"^1.0.0","@aws-crypto/sha256-js":"^1.0.0","@aws-sdk/config-resolver":"1.0.0-rc.3","@aws-sdk/credential-provider-node":"1.0.0-rc.3","@aws-sdk/eventstream-serde-browser":"1.0.0-rc.3","@aws-sdk/eventstream-serde-config-resolver":"1.0.0-rc.3","@aws-sdk/eventstream-serde-node":"1.0.0-rc.3","@aws-sdk/fetch-http-handler":"1.0.0-rc.3","@aws-sdk/hash-node":"1.0.0-rc.3","@aws-sdk/invalid-dependency":"1.0.0-rc.3","@aws-sdk/middleware-content-length":"1.0.0-rc.3","@aws-sdk/middleware-host-header":"1.0.0-rc.3","@aws-sdk/middleware-logger":"1.0.0-rc.4","@aws-sdk/middleware-retry":"1.0.0-rc.4","@aws-sdk/middleware-serde":"1.0.0-rc.3","@aws-sdk/middleware-signing":"1.0.0-rc.3","@aws-sdk/middleware-stack":"1.0.0-rc.4","@aws-sdk/middleware-user-agent":"1.0.0-rc.3","@aws-sdk/node-config-provider":"1.0.0-rc.3","@aws-sdk/node-http-handler":"1.0.0-rc.3","@aws-sdk/protocol-http":"1.0.0-rc.3","@aws-sdk/smithy-client":"1.0.0-rc.4","@aws-sdk/types":"1.0.0-rc.3","@aws-sdk/url-parser-browser":"1.0.0-rc.3","@aws-sdk/url-parser-node":"1.0.0-rc.3","@aws-sdk/util-base64-browser":"1.0.0-rc.3","@aws-sdk/util-base64-node":"1.0.0-rc.3","@aws-sdk/util-body-length-browser":"1.0.0-rc.3","@aws-sdk/util-body-length-node":"1.0.0-rc.3","@aws-sdk/util-user-agent-browser":"1.0.0-rc.3","@aws-sdk/util-user-agent-node":"1.0.0-rc.3","@aws-sdk/util-utf8-browser":"1.0.0-rc.3","@aws-sdk/util-utf8-node":"1.0.0-rc.3","tslib":"^2.0.0"},"devDependencies":{"@aws-sdk/client-documentation-generator":"1.0.0-rc.3","@types/node":"^12.7.5","jest":"^26.1.0","rimraf":"^3.0.0","typedoc":"^0.17.8","typescript":"~4.0.2"},"engines":{"node":">=10.0.0"},"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","homepage":"https://github.com/aws/aws-sdk-js-v3/tree/master/clients/client-kinesis","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"clients/client-kinesis"}}')},function(e){e.exports=JSON.parse('{"name":"@aws-sdk/client-firehose","description":"AWS SDK for JavaScript Firehose Client for Node.js, Browser and React Native","version":"1.0.0-rc.4","scripts":{"clean":"npm run remove-definitions && npm run remove-dist","build-documentation":"npm run clean && typedoc ./","prepublishOnly":"yarn build","pretest":"yarn build:cjs","remove-definitions":"rimraf ./types","remove-dist":"rimraf ./dist","remove-documentation":"rimraf ./docs","test":"exit 0","build:cjs":"tsc -p tsconfig.json","build:es":"tsc -p tsconfig.es.json","build":"yarn build:cjs && yarn build:es"},"main":"./dist/cjs/index.js","types":"./types/index.d.ts","module":"./dist/es/index.js","browser":{"./runtimeConfig":"./runtimeConfig.browser"},"react-native":{"./runtimeConfig":"./runtimeConfig.native"},"sideEffects":false,"dependencies":{"@aws-crypto/sha256-browser":"^1.0.0","@aws-crypto/sha256-js":"^1.0.0","@aws-sdk/config-resolver":"1.0.0-rc.3","@aws-sdk/credential-provider-node":"1.0.0-rc.3","@aws-sdk/fetch-http-handler":"1.0.0-rc.3","@aws-sdk/hash-node":"1.0.0-rc.3","@aws-sdk/invalid-dependency":"1.0.0-rc.3","@aws-sdk/middleware-content-length":"1.0.0-rc.3","@aws-sdk/middleware-host-header":"1.0.0-rc.3","@aws-sdk/middleware-logger":"1.0.0-rc.4","@aws-sdk/middleware-retry":"1.0.0-rc.4","@aws-sdk/middleware-serde":"1.0.0-rc.3","@aws-sdk/middleware-signing":"1.0.0-rc.3","@aws-sdk/middleware-stack":"1.0.0-rc.4","@aws-sdk/middleware-user-agent":"1.0.0-rc.3","@aws-sdk/node-config-provider":"1.0.0-rc.3","@aws-sdk/node-http-handler":"1.0.0-rc.3","@aws-sdk/protocol-http":"1.0.0-rc.3","@aws-sdk/smithy-client":"1.0.0-rc.4","@aws-sdk/types":"1.0.0-rc.3","@aws-sdk/url-parser-browser":"1.0.0-rc.3","@aws-sdk/url-parser-node":"1.0.0-rc.3","@aws-sdk/util-base64-browser":"1.0.0-rc.3","@aws-sdk/util-base64-node":"1.0.0-rc.3","@aws-sdk/util-body-length-browser":"1.0.0-rc.3","@aws-sdk/util-body-length-node":"1.0.0-rc.3","@aws-sdk/util-user-agent-browser":"1.0.0-rc.3","@aws-sdk/util-user-agent-node":"1.0.0-rc.3","@aws-sdk/util-utf8-browser":"1.0.0-rc.3","@aws-sdk/util-utf8-node":"1.0.0-rc.3","tslib":"^2.0.0"},"devDependencies":{"@aws-sdk/client-documentation-generator":"1.0.0-rc.3","@types/node":"^12.7.5","jest":"^26.1.0","rimraf":"^3.0.0","typedoc":"^0.17.8","typescript":"~4.0.2"},"engines":{"node":">=10.0.0"},"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","homepage":"https://github.com/aws/aws-sdk-js-v3/tree/master/clients/client-firehose","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"clients/client-firehose"}}')},function(e){e.exports=JSON.parse('{"name":"@aws-sdk/client-personalize-events","description":"AWS SDK for JavaScript Personalize Events Client for Node.js, Browser and React Native","version":"1.0.0-rc.4","scripts":{"clean":"npm run remove-definitions && npm run remove-dist","build-documentation":"npm run clean && typedoc ./","prepublishOnly":"yarn build","pretest":"yarn build:cjs","remove-definitions":"rimraf ./types","remove-dist":"rimraf ./dist","remove-documentation":"rimraf ./docs","test":"exit 0","build:cjs":"tsc -p tsconfig.json","build:es":"tsc -p tsconfig.es.json","build":"yarn build:cjs && yarn build:es"},"main":"./dist/cjs/index.js","types":"./types/index.d.ts","module":"./dist/es/index.js","browser":{"./runtimeConfig":"./runtimeConfig.browser"},"react-native":{"./runtimeConfig":"./runtimeConfig.native"},"sideEffects":false,"dependencies":{"@aws-crypto/sha256-browser":"^1.0.0","@aws-crypto/sha256-js":"^1.0.0","@aws-sdk/config-resolver":"1.0.0-rc.3","@aws-sdk/credential-provider-node":"1.0.0-rc.3","@aws-sdk/fetch-http-handler":"1.0.0-rc.3","@aws-sdk/hash-node":"1.0.0-rc.3","@aws-sdk/invalid-dependency":"1.0.0-rc.3","@aws-sdk/middleware-content-length":"1.0.0-rc.3","@aws-sdk/middleware-host-header":"1.0.0-rc.3","@aws-sdk/middleware-logger":"1.0.0-rc.4","@aws-sdk/middleware-retry":"1.0.0-rc.4","@aws-sdk/middleware-serde":"1.0.0-rc.3","@aws-sdk/middleware-signing":"1.0.0-rc.3","@aws-sdk/middleware-stack":"1.0.0-rc.4","@aws-sdk/middleware-user-agent":"1.0.0-rc.3","@aws-sdk/node-config-provider":"1.0.0-rc.3","@aws-sdk/node-http-handler":"1.0.0-rc.3","@aws-sdk/protocol-http":"1.0.0-rc.3","@aws-sdk/smithy-client":"1.0.0-rc.4","@aws-sdk/types":"1.0.0-rc.3","@aws-sdk/url-parser-browser":"1.0.0-rc.3","@aws-sdk/url-parser-node":"1.0.0-rc.3","@aws-sdk/util-base64-browser":"1.0.0-rc.3","@aws-sdk/util-base64-node":"1.0.0-rc.3","@aws-sdk/util-body-length-browser":"1.0.0-rc.3","@aws-sdk/util-body-length-node":"1.0.0-rc.3","@aws-sdk/util-user-agent-browser":"1.0.0-rc.3","@aws-sdk/util-user-agent-node":"1.0.0-rc.3","@aws-sdk/util-utf8-browser":"1.0.0-rc.3","@aws-sdk/util-utf8-node":"1.0.0-rc.3","tslib":"^2.0.0"},"devDependencies":{"@aws-sdk/client-documentation-generator":"1.0.0-rc.3","@types/node":"^12.7.5","jest":"^26.1.0","rimraf":"^3.0.0","typedoc":"^0.17.8","typescript":"~4.0.2"},"engines":{"node":">=10.0.0"},"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","homepage":"https://github.com/aws/aws-sdk-js-v3/tree/master/clients/client-personalize-events","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"clients/client-personalize-events"}}')},function(e){e.exports=JSON.parse('{"name":"@aws-sdk/client-s3","description":"AWS SDK for JavaScript S3 Client for Node.js, Browser and React Native","version":"1.0.0-rc.4","scripts":{"clean":"npm run remove-definitions && npm run remove-dist","build-documentation":"npm run clean && typedoc ./","prepublishOnly":"yarn build","pretest":"yarn build:cjs","remove-definitions":"rimraf ./types","remove-dist":"rimraf ./dist","remove-documentation":"rimraf ./docs","test:unit":"mocha **/cjs/**/*.spec.js","test:e2e":"mocha **/cjs/**/*.ispec.js && karma start karma.conf.js","test":"yarn test:unit","build:cjs":"tsc -p tsconfig.json","build:es":"tsc -p tsconfig.es.json","build":"yarn build:cjs && yarn build:es"},"main":"./dist/cjs/index.js","types":"./types/index.d.ts","module":"./dist/es/index.js","browser":{"./runtimeConfig":"./runtimeConfig.browser"},"react-native":{"./runtimeConfig":"./runtimeConfig.native"},"sideEffects":false,"dependencies":{"@aws-crypto/sha256-browser":"^1.0.0","@aws-crypto/sha256-js":"^1.0.0","@aws-sdk/config-resolver":"1.0.0-rc.3","@aws-sdk/credential-provider-node":"1.0.0-rc.3","@aws-sdk/eventstream-serde-browser":"1.0.0-rc.3","@aws-sdk/eventstream-serde-config-resolver":"1.0.0-rc.3","@aws-sdk/eventstream-serde-node":"1.0.0-rc.3","@aws-sdk/fetch-http-handler":"1.0.0-rc.3","@aws-sdk/hash-blob-browser":"1.0.0-rc.3","@aws-sdk/hash-node":"1.0.0-rc.3","@aws-sdk/hash-stream-node":"1.0.0-rc.3","@aws-sdk/invalid-dependency":"1.0.0-rc.3","@aws-sdk/md5-js":"1.0.0-rc.3","@aws-sdk/middleware-apply-body-checksum":"1.0.0-rc.3","@aws-sdk/middleware-bucket-endpoint":"1.0.0-rc.4","@aws-sdk/middleware-content-length":"1.0.0-rc.3","@aws-sdk/middleware-expect-continue":"1.0.0-rc.3","@aws-sdk/middleware-host-header":"1.0.0-rc.3","@aws-sdk/middleware-location-constraint":"1.0.0-rc.3","@aws-sdk/middleware-logger":"1.0.0-rc.4","@aws-sdk/middleware-retry":"1.0.0-rc.4","@aws-sdk/middleware-sdk-s3":"1.0.0-rc.3","@aws-sdk/middleware-serde":"1.0.0-rc.3","@aws-sdk/middleware-signing":"1.0.0-rc.3","@aws-sdk/middleware-ssec":"1.0.0-rc.3","@aws-sdk/middleware-stack":"1.0.0-rc.4","@aws-sdk/middleware-user-agent":"1.0.0-rc.3","@aws-sdk/node-config-provider":"1.0.0-rc.3","@aws-sdk/node-http-handler":"1.0.0-rc.3","@aws-sdk/protocol-http":"1.0.0-rc.3","@aws-sdk/smithy-client":"1.0.0-rc.4","@aws-sdk/types":"1.0.0-rc.3","@aws-sdk/url-parser-browser":"1.0.0-rc.3","@aws-sdk/url-parser-node":"1.0.0-rc.3","@aws-sdk/util-base64-browser":"1.0.0-rc.3","@aws-sdk/util-base64-node":"1.0.0-rc.3","@aws-sdk/util-body-length-browser":"1.0.0-rc.3","@aws-sdk/util-body-length-node":"1.0.0-rc.3","@aws-sdk/util-user-agent-browser":"1.0.0-rc.3","@aws-sdk/util-user-agent-node":"1.0.0-rc.3","@aws-sdk/util-utf8-browser":"1.0.0-rc.3","@aws-sdk/util-utf8-node":"1.0.0-rc.3","@aws-sdk/xml-builder":"1.0.0-rc.3","fast-xml-parser":"^3.16.0","tslib":"^2.0.0"},"devDependencies":{"@aws-sdk/client-documentation-generator":"1.0.0-rc.3","@types/chai":"^4.2.11","@types/mocha":"^7.0.2","@types/node":"^12.7.5","jest":"^26.1.0","rimraf":"^3.0.0","typedoc":"^0.17.8","typescript":"~4.0.2"},"engines":{"node":">=10.0.0"},"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","homepage":"https://github.com/aws/aws-sdk-js-v3/tree/master/clients/client-s3","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"clients/client-s3"}}')},function(e,t,n){"use strict";(function(e){n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return S}));var r,i,o=n(58),s=n(52),a=n(42),u=n(26),c=n(44),f=n(88),l=n(34),d=n(14),h=n(13),p=n(9),v=n(3),g=function(){return(g=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},w=function(){for(var e=[],t=0;t0){var s=r.map((function(e){return e.message}));return _.warn("Skipping incoming subscription. Messages: "+s.join("\n")),void S.drainBuffer()}var a=p.a.getPredicates(S.syncPredicates.get(t),!1),u=n[o];S.passesPredicateValidation(u,a)&&S.pushToBuffer(i,t,u),S.drainBuffer()},error:function(e){var t=e.error,r=y((void 0===t?{errors:[]}:t).errors,1)[0],i=(void 0===r?{}:r).message,o=void 0===i?"":i;_.warn("subscriptionError",o),"function"==typeof w&&w(),o.includes('"errorType":"Unauthorized"')||n.error(o)}})),l.push(m(S,void 0,void 0,(function(){var e,t=this;return b(this,(function(n){switch(n.label){case 0:return[4,new Promise((function(n){w=n,e=t.hubQueryCompletionListener.bind(t,n),f.a.listen("api",e)}))];case 1:return n.sent(),f.a.remove("api",e),[2]}}))}))),[2]}))}))})),[2]}))}))}))})),Promise.all(l).then((function(){return n.next(r.CONNECTED)})),[2]}}))})),function(){d.forEach((function(e){return e.unsubscribe()}))}})),new d.a((function(e){return t.dataObserver=e,t.drainBuffer(),function(){t.dataObserver=null}}))]},t.prototype.passesPredicateValidation=function(e,t){if(!t)return!0;var n=t.predicates,r=t.type;return Object(v.y)(e,r,n)},t.prototype.pushToBuffer=function(e,t,n){this.buffer.push([e,t,n])},t.prototype.drainBuffer=function(){var e=this;this.dataObserver&&(this.buffer.forEach((function(t){return e.dataObserver.next(t)})),this.buffer=[])},t}()}).call(this,n(6).Buffer)},function(e){e.exports=JSON.parse('{"name":"@aws-sdk/client-lex-runtime-service","description":"AWS SDK for JavaScript Lex Runtime Service Client for Node.js, Browser and React Native","version":"1.0.0-rc.4","scripts":{"clean":"npm run remove-definitions && npm run remove-dist","build-documentation":"npm run clean && typedoc ./","prepublishOnly":"yarn build","pretest":"yarn build:cjs","remove-definitions":"rimraf ./types","remove-dist":"rimraf ./dist","remove-documentation":"rimraf ./docs","test:unit":"mocha **/cjs/**/*.spec.js","test":"yarn test:unit","build:cjs":"tsc -p tsconfig.json","build:es":"tsc -p tsconfig.es.json","build":"yarn build:cjs && yarn build:es"},"main":"./dist/cjs/index.js","types":"./types/index.d.ts","module":"./dist/es/index.js","browser":{"./runtimeConfig":"./runtimeConfig.browser"},"react-native":{"./runtimeConfig":"./runtimeConfig.native"},"sideEffects":false,"dependencies":{"@aws-crypto/sha256-browser":"^1.0.0","@aws-crypto/sha256-js":"^1.0.0","@aws-sdk/config-resolver":"1.0.0-rc.3","@aws-sdk/credential-provider-node":"1.0.0-rc.3","@aws-sdk/fetch-http-handler":"1.0.0-rc.3","@aws-sdk/hash-node":"1.0.0-rc.3","@aws-sdk/invalid-dependency":"1.0.0-rc.3","@aws-sdk/middleware-content-length":"1.0.0-rc.3","@aws-sdk/middleware-host-header":"1.0.0-rc.3","@aws-sdk/middleware-logger":"1.0.0-rc.4","@aws-sdk/middleware-retry":"1.0.0-rc.4","@aws-sdk/middleware-serde":"1.0.0-rc.3","@aws-sdk/middleware-signing":"1.0.0-rc.3","@aws-sdk/middleware-stack":"1.0.0-rc.4","@aws-sdk/middleware-user-agent":"1.0.0-rc.3","@aws-sdk/node-config-provider":"1.0.0-rc.3","@aws-sdk/node-http-handler":"1.0.0-rc.3","@aws-sdk/protocol-http":"1.0.0-rc.3","@aws-sdk/smithy-client":"1.0.0-rc.4","@aws-sdk/types":"1.0.0-rc.3","@aws-sdk/url-parser-browser":"1.0.0-rc.3","@aws-sdk/url-parser-node":"1.0.0-rc.3","@aws-sdk/util-base64-browser":"1.0.0-rc.3","@aws-sdk/util-base64-node":"1.0.0-rc.3","@aws-sdk/util-body-length-browser":"1.0.0-rc.3","@aws-sdk/util-body-length-node":"1.0.0-rc.3","@aws-sdk/util-user-agent-browser":"1.0.0-rc.3","@aws-sdk/util-user-agent-node":"1.0.0-rc.3","@aws-sdk/util-utf8-browser":"1.0.0-rc.3","@aws-sdk/util-utf8-node":"1.0.0-rc.3","tslib":"^2.0.0"},"devDependencies":{"@aws-sdk/client-documentation-generator":"1.0.0-rc.3","@types/chai":"^4.2.11","@types/mocha":"^7.0.2","@types/node":"^12.7.5","jest":"^26.1.0","rimraf":"^3.0.0","typedoc":"^0.17.8","typescript":"~4.0.2"},"engines":{"node":">=10.0.0"},"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","homepage":"https://github.com/aws/aws-sdk-js-v3/tree/master/clients/client-lex-runtime-service","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"clients/client-lex-runtime-service"}}')},,function(e,t,n){"use strict";n.r(t);var r=n(19),i=n(143);n.d(t,"Amplify",(function(){return r.a}));var o=n(63),s=n(26),a=n(491);n.d(t,"Analytics",(function(){return a.a}));var u=n(144);n.d(t,"AWSPinpointProvider",(function(){return u.a}));var c=n(145);n.d(t,"AWSKinesisProvider",(function(){return c.a}));var f=n(492);n.d(t,"AWSKinesisFirehoseProvider",(function(){return f.a}));var l=n(490);n.d(t,"AmazonPersonalizeProvider",(function(){return l.a})),n.d(t,"Auth",(function(){return o.a}));var d=n(140);n.d(t,"Storage",(function(){return d.a})),n.d(t,"StorageClass",(function(){return d.b}));var h=n(62);n.d(t,"API",(function(){return h.a})),n.d(t,"APIClass",(function(){return h.b}));var p=n(248);n.d(t,"graphqlOperation",(function(){return p.b}));var v=n(258);n.d(t,"DataStore",(function(){return v.a}));var g=n(9);n.d(t,"Predicates",(function(){return g.b}));var m=n(4);n.d(t,"SortDirection",(function(){return m.e})),n.d(t,"syncExpression",(function(){return m.n}));var b=n(105);n.d(t,"PubSub",(function(){return b.a})),n.d(t,"Cache",(function(){return s.a}));var y=n(489);n.d(t,"Interactions",(function(){return y.a}));var w=n(246);for(var _ in w)["default","Analytics","AWSPinpointProvider","AWSKinesisProvider","AWSKinesisFirehoseProvider","AmazonPersonalizeProvider","Auth","Storage","StorageClass","API","APIClass","graphqlOperation","DataStore","Predicates","SortDirection","syncExpression","PubSub","Cache","Interactions","XR","Predictions","Logger","Hub","JS","ClientDevice","Signer","I18n","ServiceWorker","withSSRContext","Amplify"].indexOf(_)<0&&function(e){n.d(t,e,(function(){return w[e]}))}(_);var S=n(493);n.d(t,"XR",(function(){return S.a}));var E=n(488);n.d(t,"Predictions",(function(){return E.a}));var M=n(44);n.d(t,"Logger",(function(){return M.a}));var A=n(88);n.d(t,"Hub",(function(){return A.a}));var I=n(33);n.d(t,"JS",(function(){return I.a}));var k=n(141);n.d(t,"ClientDevice",(function(){return k.a}));var O=n(104);n.d(t,"Signer",(function(){return O.a}));var x=n(142);n.d(t,"I18n",(function(){return x.a})),n.d(t,"ServiceWorker",(function(){return i.a}));var C=n(247);n.d(t,"withSSRContext",(function(){return C.a})),r.a.Auth=o.a,r.a.Cache=s.a,r.a.ServiceWorker=i.a,t.default=r.a},,,function(e,t){var n={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},function(e,t,n){var r;e.exports=(r=n(32),function(){if("function"==typeof ArrayBuffer){var e=r.lib.WordArray,t=e.init;(e.init=function(e){if(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),(e instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array)&&(e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),e instanceof Uint8Array){for(var n=e.byteLength,r=[],i=0;i>>2]|=e[i]<<24-i%4*8;t.call(this,r,n)}else t.apply(this,arguments)}).prototype=e}}(),r.lib.WordArray)},function(e,t,n){"use strict";var r=n(8).Buffer,i=n(273).Transform;function o(e){i.call(this),this._block=r.allocUnsafe(e),this._blockSize=e,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}n(7)(o,i),o.prototype._transform=function(e,t,n){var r=null;try{this.update(e,t)}catch(e){r=e}n(r)},o.prototype._flush=function(e){var t=null;try{this.push(this.digest())}catch(e){t=e}e(t)},o.prototype.update=function(e,t){if(function(e,t){if(!r.isBuffer(e)&&"string"!=typeof e)throw new TypeError(t+" must be a string or a buffer")}(e,"Data"),this._finalized)throw new Error("Digest already called");r.isBuffer(e)||(e=r.from(e,t));for(var n=this._block,i=0;this._blockOffset+e.length-i>=this._blockSize;){for(var o=this._blockOffset;o0;++s)this._length[s]+=a,(a=this._length[s]/4294967296|0)>0&&(this._length[s]-=4294967296*a);return this},o.prototype._update=function(){throw new Error("_update is not implemented")},o.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();void 0!==e&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var n=0;n<4;++n)this._length[n]=0;return t},o.prototype._digest=function(){throw new Error("_digest is not implemented")},e.exports=o},function(e,t,n){"use strict";(function(t,r){var i;e.exports=A,A.ReadableState=M;n(49).EventEmitter;var o=function(e,t){return e.listeners(t).length},s=n(164),a=n(6).Buffer,u=t.Uint8Array||function(){};var c,f=n(274);c=f&&f.debuglog?f.debuglog("stream"):function(){};var l,d,h,p=n(275),v=n(165),g=n(166).getHighWaterMark,m=n(67).codes,b=m.ERR_INVALID_ARG_TYPE,y=m.ERR_STREAM_PUSH_AFTER_EOF,w=m.ERR_METHOD_NOT_IMPLEMENTED,_=m.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;n(7)(A,s);var S=v.errorOrDestroy,E=["error","close","destroy","pause","resume"];function M(e,t,r){i=i||n(68),e=e||{},"boolean"!=typeof r&&(r=t instanceof i),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=g(this,e,"readableHighWaterMark",r),this.buffer=new p,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==e.emitClose,this.autoDestroy=!!e.autoDestroy,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(l||(l=n(59).StringDecoder),this.decoder=new l(e.encoding),this.encoding=e.encoding)}function A(e){if(i=i||n(68),!(this instanceof A))return new A(e);var t=this instanceof i;this._readableState=new M(e,this,t),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),s.call(this)}function I(e,t,n,r,i){c("readableAddChunk",t);var o,s=e._readableState;if(null===t)s.reading=!1,function(e,t){if(c("onEofChunk"),t.ended)return;if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?x(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,C(e)))}(e,s);else if(i||(o=function(e,t){var n;r=t,a.isBuffer(r)||r instanceof u||"string"==typeof t||void 0===t||e.objectMode||(n=new b("chunk",["string","Buffer","Uint8Array"],t));var r;return n}(s,t)),o)S(e,o);else if(s.objectMode||t&&t.length>0)if("string"==typeof t||s.objectMode||Object.getPrototypeOf(t)===a.prototype||(t=function(e){return a.from(e)}(t)),r)s.endEmitted?S(e,new _):k(e,s,t,!0);else if(s.ended)S(e,new y);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!n?(t=s.decoder.write(t),s.objectMode||0!==t.length?k(e,s,t,!1):T(e,s)):k(e,s,t,!1)}else r||(s.reading=!1,T(e,s));return!s.ended&&(s.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=1073741824?e=1073741824:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function x(e){var t=e._readableState;c("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(c("emitReadable",t.flowing),t.emittedReadable=!0,r.nextTick(C,e))}function C(e){var t=e._readableState;c("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,j(e)}function T(e,t){t.readingMore||(t.readingMore=!0,r.nextTick(P,e,t))}function P(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function R(e){c("readable nexttick read 0"),e.read(0)}function L(e,t){c("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),j(e),t.flowing&&!t.reading&&e.read(0)}function j(e){var t=e._readableState;for(c("flow",t.flowing);t.flowing&&null!==e.read(););}function D(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function U(e){var t=e._readableState;c("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,r.nextTick(B,t,e))}function B(e,t){if(c("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}function F(e,t){for(var n=0,r=e.length;n=t.highWaterMark:t.length>0)||t.ended))return c("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?U(this):x(this),null;if(0===(e=O(e,t))&&t.ended)return 0===t.length&&U(this),null;var r,i=t.needReadable;return c("need readable",i),(0===t.length||t.length-e0?D(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&U(this)),null!==r&&this.emit("data",r),r},A.prototype._read=function(e){S(this,new w("_read()"))},A.prototype.pipe=function(e,t){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e)}i.pipesCount+=1,c("pipe count=%d opts=%j",i.pipesCount,t);var s=(!t||!1!==t.end)&&e!==r.stdout&&e!==r.stderr?u:g;function a(t,r){c("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,c("cleanup"),e.removeListener("close",p),e.removeListener("finish",v),e.removeListener("drain",f),e.removeListener("error",h),e.removeListener("unpipe",a),n.removeListener("end",u),n.removeListener("end",g),n.removeListener("data",d),l=!0,!i.awaitDrain||e._writableState&&!e._writableState.needDrain||f())}function u(){c("onend"),e.end()}i.endEmitted?r.nextTick(s):n.once("end",s),e.on("unpipe",a);var f=function(e){return function(){var t=e._readableState;c("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&o(e,"data")&&(t.flowing=!0,j(e))}}(n);e.on("drain",f);var l=!1;function d(t){c("ondata");var r=e.write(t);c("dest.write",r),!1===r&&((1===i.pipesCount&&i.pipes===e||i.pipesCount>1&&-1!==F(i.pipes,e))&&!l&&(c("false write response, pause",i.awaitDrain),i.awaitDrain++),n.pause())}function h(t){c("onerror",t),g(),e.removeListener("error",h),0===o(e,"error")&&S(e,t)}function p(){e.removeListener("finish",v),g()}function v(){c("onfinish"),e.removeListener("close",p),g()}function g(){c("unpipe"),n.unpipe(e)}return n.on("data",d),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",h),e.once("close",p),e.once("finish",v),e.emit("pipe",n),i.flowing||(c("pipe resume"),n.resume()),e},A.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n)),this;if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o0,!1!==i.flowing&&this.resume()):"readable"===e&&(i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,c("on readable",i.length,i.reading),i.length?x(this):i.reading||r.nextTick(R,this))),n},A.prototype.addListener=A.prototype.on,A.prototype.removeListener=function(e,t){var n=s.prototype.removeListener.call(this,e,t);return"readable"===e&&r.nextTick(N,this),n},A.prototype.removeAllListeners=function(e){var t=s.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||r.nextTick(N,this),t},A.prototype.resume=function(){var e=this._readableState;return e.flowing||(c("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,r.nextTick(L,e,t))}(this,e)),e.paused=!1,this},A.prototype.pause=function(){return c("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(c("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},A.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on("end",(function(){if(c("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(i){(c("wrapped data"),n.decoder&&(i=n.decoder.write(i)),n.objectMode&&null==i)||(n.objectMode||i&&i.length)&&(t.push(i)||(r=!0,e.pause()))})),e)void 0===this[i]&&"function"==typeof e[i]&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var o=0;o-1))throw new _(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(A.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(A.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),A.prototype._write=function(e,t,n){n(new v("_write()"))},A.prototype._writev=null,A.prototype.end=function(e,t,n){var i=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),i.corked&&(i.corked=1,this.uncork()),i.ending||function(e,t,n){t.ending=!0,T(e,t),n&&(t.finished?r.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,i,n),this},Object.defineProperty(A.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(A.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),A.prototype.destroy=l.destroy,A.prototype._undestroy=l.undestroy,A.prototype._destroy=function(e,t){t(e)}}).call(this,n(31),n(20))},function(e,t,n){"use strict";e.exports=f;var r=n(67).codes,i=r.ERR_METHOD_NOT_IMPLEMENTED,o=r.ERR_MULTIPLE_CALLBACK,s=r.ERR_TRANSFORM_ALREADY_TRANSFORMING,a=r.ERR_TRANSFORM_WITH_LENGTH_0,u=n(68);function c(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(null===r)return this.emit("error",new o);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var i=this._readableState;i.reading=!1,(i.needReadable||i.length>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function d(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function h(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}r(u,i),u.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},u.prototype._update=function(e){for(var t,n=this._w,r=0|this._a,i=0|this._b,o=0|this._c,a=0|this._d,u=0|this._e,p=0|this._f,v=0|this._g,g=0|this._h,m=0;m<16;++m)n[m]=e.readInt32BE(4*m);for(;m<64;++m)n[m]=0|(((t=n[m-2])>>>17|t<<15)^(t>>>19|t<<13)^t>>>10)+n[m-7]+h(n[m-15])+n[m-16];for(var b=0;b<64;++b){var y=g+d(u)+c(u,p,v)+s[b]+n[b]|0,w=l(r)+f(r,i,o)|0;g=v,v=p,p=u,u=a+y|0,a=o,o=i,i=r,r=y+w|0}this._a=r+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=a+this._d|0,this._e=u+this._e|0,this._f=p+this._f|0,this._g=v+this._g|0,this._h=g+this._h|0},u.prototype._hash=function(){var e=o.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e},e.exports=u},function(e,t,n){var r=n(7),i=n(69),o=n(8).Buffer,s=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],a=new Array(160);function u(){this.init(),this._w=a,i.call(this,128,112)}function c(e,t,n){return n^e&(t^n)}function f(e,t,n){return e&t|n&(e|t)}function l(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function d(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function h(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function p(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function v(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function g(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function m(e,t){return e>>>0>>0?1:0}r(u,i),u.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},u.prototype._update=function(e){for(var t=this._w,n=0|this._ah,r=0|this._bh,i=0|this._ch,o=0|this._dh,a=0|this._eh,u=0|this._fh,b=0|this._gh,y=0|this._hh,w=0|this._al,_=0|this._bl,S=0|this._cl,E=0|this._dl,M=0|this._el,A=0|this._fl,I=0|this._gl,k=0|this._hl,O=0;O<32;O+=2)t[O]=e.readInt32BE(4*O),t[O+1]=e.readInt32BE(4*O+4);for(;O<160;O+=2){var x=t[O-30],C=t[O-30+1],T=h(x,C),P=p(C,x),N=v(x=t[O-4],C=t[O-4+1]),R=g(C,x),L=t[O-14],j=t[O-14+1],D=t[O-32],U=t[O-32+1],B=P+j|0,F=T+L+m(B,P)|0;F=(F=F+N+m(B=B+R|0,R)|0)+D+m(B=B+U|0,U)|0,t[O]=F,t[O+1]=B}for(var z=0;z<160;z+=2){F=t[z],B=t[z+1];var q=f(n,r,i),K=f(w,_,S),H=l(n,w),V=l(w,n),G=d(a,M),W=d(M,a),$=s[z],Y=s[z+1],J=c(a,u,b),Z=c(M,A,I),X=k+W|0,Q=y+G+m(X,k)|0;Q=(Q=(Q=Q+J+m(X=X+Z|0,Z)|0)+$+m(X=X+Y|0,Y)|0)+F+m(X=X+B|0,B)|0;var ee=V+K|0,te=H+q+m(ee,V)|0;y=b,k=I,b=u,I=A,u=a,A=M,a=o+Q+m(M=E+X|0,E)|0,o=i,E=S,i=r,S=_,r=n,_=w,n=Q+te+m(w=X+ee|0,X)|0}this._al=this._al+w|0,this._bl=this._bl+_|0,this._cl=this._cl+S|0,this._dl=this._dl+E|0,this._el=this._el+M|0,this._fl=this._fl+A|0,this._gl=this._gl+I|0,this._hl=this._hl+k|0,this._ah=this._ah+n+m(this._al,w)|0,this._bh=this._bh+r+m(this._bl,_)|0,this._ch=this._ch+i+m(this._cl,S)|0,this._dh=this._dh+o+m(this._dl,E)|0,this._eh=this._eh+a+m(this._el,M)|0,this._fh=this._fh+u+m(this._fl,A)|0,this._gh=this._gh+b+m(this._gl,I)|0,this._hh=this._hh+y+m(this._hl,k)|0},u.prototype._hash=function(){var e=o.allocUnsafe(64);function t(t,n,r){e.writeInt32BE(t,r),e.writeInt32BE(n,r+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e},e.exports=u},function(e,t,n){"use strict";(function(t,r){var i=n(92);e.exports=y;var o,s=n(160);y.ReadableState=b;n(49).EventEmitter;var a=function(e,t){return e.listeners(t).length},u=n(172),c=n(119).Buffer,f=t.Uint8Array||function(){};var l=Object.create(n(80));l.inherits=n(7);var d=n(286),h=void 0;h=d&&d.debuglog?d.debuglog("stream"):function(){};var p,v=n(287),g=n(173);l.inherits(y,u);var m=["error","close","destroy","pause","resume"];function b(e,t){e=e||{};var r=t instanceof(o=o||n(60));this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var i=e.highWaterMark,s=e.readableHighWaterMark,a=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:r&&(s||0===s)?s:a,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new v,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(p||(p=n(59).StringDecoder),this.decoder=new p(e.encoding),this.encoding=e.encoding)}function y(e){if(o=o||n(60),!(this instanceof y))return new y(e);this._readableState=new b(e,this),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),u.call(this)}function w(e,t,n,r,i){var o,s=e._readableState;null===t?(s.reading=!1,function(e,t){if(t.ended)return;if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,E(e)}(e,s)):(i||(o=function(e,t){var n;r=t,c.isBuffer(r)||r instanceof f||"string"==typeof t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk"));var r;return n}(s,t)),o?e.emit("error",o):s.objectMode||t&&t.length>0?("string"==typeof t||s.objectMode||Object.getPrototypeOf(t)===c.prototype||(t=function(e){return c.from(e)}(t)),r?s.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):_(e,s,t,!0):s.ended?e.emit("error",new Error("stream.push() after EOF")):(s.reading=!1,s.decoder&&!n?(t=s.decoder.write(t),s.objectMode||0!==t.length?_(e,s,t,!1):A(e,s)):_(e,s,t,!1))):r||(s.reading=!1));return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=8388608?e=8388608:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function E(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(h("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?i.nextTick(M,e):M(e))}function M(e){h("emit readable"),e.emit("readable"),x(e)}function A(e,t){t.readingMore||(t.readingMore=!0,i.nextTick(I,e,t))}function I(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=function(e,t,n){var r;eo.length?o.length:e;if(s===o.length?i+=o:i+=o.slice(0,e),0===(e-=s)){s===o.length?(++r,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(s));break}++r}return t.length-=r,i}(e,t):function(e,t){var n=c.allocUnsafe(e),r=t.head,i=1;r.data.copy(n),e-=r.data.length;for(;r=r.next;){var o=r.data,s=e>o.length?o.length:e;if(o.copy(n,n.length-e,0,s),0===(e-=s)){s===o.length?(++i,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(s));break}++i}return t.length-=i,n}(e,t);return r}(e,t.buffer,t.decoder),n);var n}function T(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,i.nextTick(P,t,e))}function P(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function N(e,t){for(var n=0,r=e.length;n=t.highWaterMark||t.ended))return h("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?T(this):E(this),null;if(0===(e=S(e,t))&&t.ended)return 0===t.length&&T(this),null;var r,i=t.needReadable;return h("need readable",i),(0===t.length||t.length-e0?C(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&T(this)),null!==r&&this.emit("data",r),r},y.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},y.prototype.pipe=function(e,t){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,h("pipe count=%d opts=%j",o.pipesCount,t);var u=(!t||!1!==t.end)&&e!==r.stdout&&e!==r.stderr?f:y;function c(t,r){h("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,h("cleanup"),e.removeListener("close",m),e.removeListener("finish",b),e.removeListener("drain",l),e.removeListener("error",g),e.removeListener("unpipe",c),n.removeListener("end",f),n.removeListener("end",y),n.removeListener("data",v),d=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||l())}function f(){h("onend"),e.end()}o.endEmitted?i.nextTick(u):n.once("end",u),e.on("unpipe",c);var l=function(e){return function(){var t=e._readableState;h("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&a(e,"data")&&(t.flowing=!0,x(e))}}(n);e.on("drain",l);var d=!1;var p=!1;function v(t){h("ondata"),p=!1,!1!==e.write(t)||p||((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==N(o.pipes,e))&&!d&&(h("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,p=!0),n.pause())}function g(t){h("onerror",t),y(),e.removeListener("error",g),0===a(e,"error")&&e.emit("error",t)}function m(){e.removeListener("finish",b),y()}function b(){h("onfinish"),e.removeListener("close",m),y()}function y(){h("unpipe"),n.unpipe(e)}return n.on("data",v),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?s(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",g),e.once("close",m),e.once("finish",b),e.emit("pipe",n),o.flowing||(h("pipe resume"),n.resume()),e},y.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n)),this;if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;on)?t=("rmd160"===e?new u:c(e)).update(t).digest():t.lengthn||t!=t)throw new TypeError("Bad key length")}},function(e,t,n){(function(t){var n;if(t.browser)n="utf-8";else if(t.version){n=parseInt(t.version.split(".")[0].slice(1),10)>=6?"utf-8":"binary"}else n="utf-8";e.exports=n}).call(this,n(20))},function(e,t,n){var r=n(176),i=n(116),o=n(117),s=n(8).Buffer,a=n(179),u=n(180),c=n(182),f=s.alloc(128),l={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,rmd160:20,ripemd160:20};function d(e,t,n){var a=function(e){function t(t){return o(e).update(t).digest()}return"rmd160"===e||"ripemd160"===e?function(e){return(new i).update(e).digest()}:"md5"===e?r:t}(e),u="sha512"===e||"sha384"===e?128:64;t.length>u?t=a(t):t.length>>0},t.writeUInt32BE=function(e,t,n){e[0+n]=t>>>24,e[1+n]=t>>>16&255,e[2+n]=t>>>8&255,e[3+n]=255&t},t.ip=function(e,t,n,r){for(var i=0,o=0,s=6;s>=0;s-=2){for(var a=0;a<=24;a+=8)i<<=1,i|=t>>>a+s&1;for(a=0;a<=24;a+=8)i<<=1,i|=e>>>a+s&1}for(s=6;s>=0;s-=2){for(a=1;a<=25;a+=8)o<<=1,o|=t>>>a+s&1;for(a=1;a<=25;a+=8)o<<=1,o|=e>>>a+s&1}n[r+0]=i>>>0,n[r+1]=o>>>0},t.rip=function(e,t,n,r){for(var i=0,o=0,s=0;s<4;s++)for(var a=24;a>=0;a-=8)i<<=1,i|=t>>>a+s&1,i<<=1,i|=e>>>a+s&1;for(s=4;s<8;s++)for(a=24;a>=0;a-=8)o<<=1,o|=t>>>a+s&1,o<<=1,o|=e>>>a+s&1;n[r+0]=i>>>0,n[r+1]=o>>>0},t.pc1=function(e,t,n,r){for(var i=0,o=0,s=7;s>=5;s--){for(var a=0;a<=24;a+=8)i<<=1,i|=t>>a+s&1;for(a=0;a<=24;a+=8)i<<=1,i|=e>>a+s&1}for(a=0;a<=24;a+=8)i<<=1,i|=t>>a+s&1;for(s=1;s<=3;s++){for(a=0;a<=24;a+=8)o<<=1,o|=t>>a+s&1;for(a=0;a<=24;a+=8)o<<=1,o|=e>>a+s&1}for(a=0;a<=24;a+=8)o<<=1,o|=e>>a+s&1;n[r+0]=i>>>0,n[r+1]=o>>>0},t.r28shl=function(e,t){return e<>>28-t};var r=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];t.pc2=function(e,t,n,i){for(var o=0,s=0,a=r.length>>>1,u=0;u>>r[u]&1;for(u=a;u>>r[u]&1;n[i+0]=o>>>0,n[i+1]=s>>>0},t.expand=function(e,t,n){var r=0,i=0;r=(1&e)<<5|e>>>27;for(var o=23;o>=15;o-=4)r<<=6,r|=e>>>o&63;for(o=11;o>=3;o-=4)i|=e>>>o&63,i<<=6;i|=(31&e)<<1|e>>>31,t[n+0]=r>>>0,t[n+1]=i>>>0};var i=[14,0,4,15,13,7,1,4,2,14,15,2,11,13,8,1,3,10,10,6,6,12,12,11,5,9,9,5,0,3,7,8,4,15,1,12,14,8,8,2,13,4,6,9,2,1,11,7,15,5,12,11,9,3,7,14,3,10,10,0,5,6,0,13,15,3,1,13,8,4,14,7,6,15,11,2,3,8,4,14,9,12,7,0,2,1,13,10,12,6,0,9,5,11,10,5,0,13,14,8,7,10,11,1,10,3,4,15,13,4,1,2,5,11,8,6,12,7,6,12,9,0,3,5,2,14,15,9,10,13,0,7,9,0,14,9,6,3,3,4,15,6,5,10,1,2,13,8,12,5,7,14,11,12,4,11,2,15,8,1,13,1,6,10,4,13,9,0,8,6,15,9,3,8,0,7,11,4,1,15,2,14,12,3,5,11,10,5,14,2,7,12,7,13,13,8,14,11,3,5,0,6,6,15,9,0,10,3,1,4,2,7,8,2,5,12,11,1,12,10,4,14,15,9,10,3,6,15,9,0,0,6,12,10,11,1,7,13,13,8,15,9,1,4,3,5,14,11,5,12,2,7,8,2,4,14,2,14,12,11,4,2,1,12,7,4,10,7,11,13,6,1,8,5,5,0,3,15,15,10,13,3,0,9,14,8,9,6,4,11,2,8,1,12,11,7,10,1,13,14,7,2,8,13,15,6,9,15,12,0,5,9,6,10,3,4,0,5,14,3,12,10,1,15,10,4,15,2,9,7,2,12,6,9,8,5,0,6,13,1,3,13,4,14,14,0,7,11,5,3,11,8,9,4,14,3,15,2,5,12,2,9,8,5,12,15,3,10,7,11,0,14,4,1,10,7,1,6,13,0,11,8,6,13,4,13,11,0,2,11,14,7,15,4,0,9,8,1,13,10,3,14,12,3,9,5,7,12,5,2,10,15,6,8,1,6,1,6,4,11,11,13,13,8,12,1,3,4,7,10,14,7,10,9,15,5,6,0,8,15,0,14,5,2,9,3,2,12,13,1,2,15,8,13,4,8,6,10,15,3,11,7,1,4,10,12,9,5,3,6,14,11,5,0,0,14,12,9,7,2,7,2,11,1,4,14,1,7,9,4,12,10,14,8,2,13,0,15,6,12,10,9,13,0,15,3,3,5,5,6,8,11];t.substitute=function(e,t){for(var n=0,r=0;r<4;r++){n<<=4,n|=i[64*r+(e>>>18-6*r&63)]}for(r=0;r<4;r++){n<<=4,n|=i[256+64*r+(t>>>18-6*r&63)]}return n>>>0};var o=[16,25,12,11,3,20,4,15,31,17,9,6,27,14,1,22,30,24,8,18,0,5,29,23,13,19,2,26,10,21,28,7];t.permute=function(e){for(var t=0,n=0;n>>o[n]&1;return t>>>0},t.padSplit=function(e,t,n){for(var r=e.toString(2);r.length>>1];n=o.r28shl(n,a),i=o.r28shl(i,a),o.pc2(n,i,e.keys,s)}},u.prototype._update=function(e,t,n,r){var i=this._desState,s=o.readUInt32BE(e,t),a=o.readUInt32BE(e,t+4);o.ip(s,a,i.tmp,0),s=i.tmp[0],a=i.tmp[1],"encrypt"===this.type?this._encrypt(i,s,a,i.tmp,0):this._decrypt(i,s,a,i.tmp,0),s=i.tmp[0],a=i.tmp[1],o.writeUInt32BE(n,s,r),o.writeUInt32BE(n,a,r+4)},u.prototype._pad=function(e,t){for(var n=e.length-t,r=t;r>>0,s=d}o.rip(a,s,r,i)},u.prototype._decrypt=function(e,t,n,r,i){for(var s=n,a=t,u=e.keys.length-2;u>=0;u-=2){var c=e.keys[u],f=e.keys[u+1];o.expand(s,e.tmp,0),c^=e.tmp[0],f^=e.tmp[1];var l=o.substitute(c,f),d=s;s=(a^o.permute(l))>>>0,a=d}o.rip(s,a,r,i)}},function(e,t,n){var r=n(81),i=n(8).Buffer,o=n(186);function s(e){var t=e._cipher.encryptBlockRaw(e._prev);return o(e._prev),t}t.encrypt=function(e,t){var n=Math.ceil(t.length/16),o=e._cache.length;e._cache=i.concat([e._cache,i.allocUnsafe(16*n)]);for(var a=0;ae;)n.ishrn(1);if(n.isEven()&&n.iadd(a),n.testn(1)||n.iadd(u),t.cmp(u)){if(!t.cmp(c))for(;n.mod(f).cmp(l);)n.iadd(h)}else for(;n.mod(o).cmp(d);)n.iadd(h);if(g(p=n.shrn(1))&&g(n)&&m(p)&&m(n)&&s.test(p)&&s.test(n))return n}}},function(e,t,n){var r=n(29),i=n(124);function o(e){this.rand=e||new i.Rand}e.exports=o,o.create=function(e){return new o(e)},o.prototype._randbelow=function(e){var t=e.bitLength(),n=Math.ceil(t/8);do{var i=new r(this.rand.generate(n))}while(i.cmp(e)>=0);return i},o.prototype._randrange=function(e,t){var n=t.sub(e);return e.add(this._randbelow(n))},o.prototype.test=function(e,t,n){var i=e.bitLength(),o=r.mont(e),s=new r(1).toRed(o);t||(t=Math.max(1,i/48|0));for(var a=e.subn(1),u=0;!a.testn(u);u++);for(var c=e.shrn(u),f=a.toRed(o);t>0;t--){var l=this._randrange(new r(2),a);n&&n(l);var d=l.toRed(o).redPow(c);if(0!==d.cmp(s)&&0!==d.cmp(f)){for(var h=1;h0;t--){var f=this._randrange(new r(2),s),l=e.gcd(f);if(0!==l.cmpn(1))return l;var d=f.toRed(i).redPow(u);if(0!==d.cmp(o)&&0!==d.cmp(c)){for(var h=1;h0)if("string"==typeof t||s.objectMode||Object.getPrototypeOf(t)===a.prototype||(t=function(e){return a.from(e)}(t)),r)s.endEmitted?S(e,new _):k(e,s,t,!0);else if(s.ended)S(e,new y);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!n?(t=s.decoder.write(t),s.objectMode||0!==t.length?k(e,s,t,!1):T(e,s)):k(e,s,t,!1)}else r||(s.reading=!1,T(e,s));return!s.ended&&(s.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=1073741824?e=1073741824:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function x(e){var t=e._readableState;c("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(c("emitReadable",t.flowing),t.emittedReadable=!0,r.nextTick(C,e))}function C(e){var t=e._readableState;c("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,j(e)}function T(e,t){t.readingMore||(t.readingMore=!0,r.nextTick(P,e,t))}function P(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function R(e){c("readable nexttick read 0"),e.read(0)}function L(e,t){c("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),j(e),t.flowing&&!t.reading&&e.read(0)}function j(e){var t=e._readableState;for(c("flow",t.flowing);t.flowing&&null!==e.read(););}function D(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function U(e){var t=e._readableState;c("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,r.nextTick(B,t,e))}function B(e,t){if(c("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}function F(e,t){for(var n=0,r=e.length;n=t.highWaterMark:t.length>0)||t.ended))return c("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?U(this):x(this),null;if(0===(e=O(e,t))&&t.ended)return 0===t.length&&U(this),null;var r,i=t.needReadable;return c("need readable",i),(0===t.length||t.length-e0?D(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&U(this)),null!==r&&this.emit("data",r),r},A.prototype._read=function(e){S(this,new w("_read()"))},A.prototype.pipe=function(e,t){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e)}i.pipesCount+=1,c("pipe count=%d opts=%j",i.pipesCount,t);var s=(!t||!1!==t.end)&&e!==r.stdout&&e!==r.stderr?u:g;function a(t,r){c("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,c("cleanup"),e.removeListener("close",p),e.removeListener("finish",v),e.removeListener("drain",f),e.removeListener("error",h),e.removeListener("unpipe",a),n.removeListener("end",u),n.removeListener("end",g),n.removeListener("data",d),l=!0,!i.awaitDrain||e._writableState&&!e._writableState.needDrain||f())}function u(){c("onend"),e.end()}i.endEmitted?r.nextTick(s):n.once("end",s),e.on("unpipe",a);var f=function(e){return function(){var t=e._readableState;c("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&o(e,"data")&&(t.flowing=!0,j(e))}}(n);e.on("drain",f);var l=!1;function d(t){c("ondata");var r=e.write(t);c("dest.write",r),!1===r&&((1===i.pipesCount&&i.pipes===e||i.pipesCount>1&&-1!==F(i.pipes,e))&&!l&&(c("false write response, pause",i.awaitDrain),i.awaitDrain++),n.pause())}function h(t){c("onerror",t),g(),e.removeListener("error",h),0===o(e,"error")&&S(e,t)}function p(){e.removeListener("finish",v),g()}function v(){c("onfinish"),e.removeListener("close",p),g()}function g(){c("unpipe"),n.unpipe(e)}return n.on("data",d),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",h),e.once("close",p),e.once("finish",v),e.emit("pipe",n),i.flowing||(c("pipe resume"),n.resume()),e},A.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n)),this;if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o0,!1!==i.flowing&&this.resume()):"readable"===e&&(i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,c("on readable",i.length,i.reading),i.length?x(this):i.reading||r.nextTick(R,this))),n},A.prototype.addListener=A.prototype.on,A.prototype.removeListener=function(e,t){var n=s.prototype.removeListener.call(this,e,t);return"readable"===e&&r.nextTick(N,this),n},A.prototype.removeAllListeners=function(e){var t=s.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||r.nextTick(N,this),t},A.prototype.resume=function(){var e=this._readableState;return e.flowing||(c("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,r.nextTick(L,e,t))}(this,e)),e.paused=!1,this},A.prototype.pause=function(){return c("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(c("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},A.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on("end",(function(){if(c("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(i){(c("wrapped data"),n.decoder&&(i=n.decoder.write(i)),n.objectMode&&null==i)||(n.objectMode||i&&i.length)&&(t.push(i)||(r=!0,e.pause()))})),e)void 0===this[i]&&"function"==typeof e[i]&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var o=0;o-1))throw new _(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(A.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(A.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),A.prototype._write=function(e,t,n){n(new v("_write()"))},A.prototype._writev=null,A.prototype.end=function(e,t,n){var i=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),i.corked&&(i.corked=1,this.uncork()),i.ending||function(e,t,n){t.ending=!0,T(e,t),n&&(t.finished?r.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,i,n),this},Object.defineProperty(A.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(A.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),A.prototype.destroy=l.destroy,A.prototype._undestroy=l.undestroy,A.prototype._destroy=function(e,t){t(e)}}).call(this,n(31),n(20))},function(e,t,n){"use strict";e.exports=f;var r=n(70).codes,i=r.ERR_METHOD_NOT_IMPLEMENTED,o=r.ERR_MULTIPLE_CALLBACK,s=r.ERR_TRANSFORM_ALREADY_TRANSFORMING,a=r.ERR_TRANSFORM_WITH_LENGTH_0,u=n(71);function c(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(null===r)return this.emit("error",new o);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var i=this._readableState;i.reading=!1,(i.needReadable||i.length>8,s=255&i;o?n.push(o,s):n.push(s)}return n},r.zero2=i,r.toHex=o,r.encode=function(e,t){return"hex"===t?o(e):e}},function(e,t,n){"use strict";var r=t;r.base=n(95),r.short=n(332),r.mont=n(333),r.edwards=n(334)},function(e,t,n){"use strict";var r=n(51).rotr32;function i(e,t,n){return e&t^~e&n}function o(e,t,n){return e&t^e&n^t&n}function s(e,t,n){return e^t^n}t.ft_1=function(e,t,n,r){return 0===e?i(t,n,r):1===e||3===e?s(t,n,r):2===e?o(t,n,r):void 0},t.ch32=i,t.maj32=o,t.p32=s,t.s0_256=function(e){return r(e,2)^r(e,13)^r(e,22)},t.s1_256=function(e){return r(e,6)^r(e,11)^r(e,25)},t.g0_256=function(e){return r(e,7)^r(e,18)^e>>>3},t.g1_256=function(e){return r(e,17)^r(e,19)^e>>>10}},function(e,t,n){"use strict";var r=n(51),i=n(82),o=n(200),s=n(46),a=r.sum32,u=r.sum32_4,c=r.sum32_5,f=o.ch32,l=o.maj32,d=o.s0_256,h=o.s1_256,p=o.g0_256,v=o.g1_256,g=i.BlockHash,m=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function b(){if(!(this instanceof b))return new b;g.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=m,this.W=new Array(64)}r.inherits(b,g),e.exports=b,b.blockSize=512,b.outSize=256,b.hmacStrength=192,b.padLength=64,b.prototype._update=function(e,t){for(var n=this.W,r=0;r<16;r++)n[r]=e[t+r];for(;r=49&&c<=54?c-49+10:c>=17&&c<=22?c-17+10:c,s|=u}return r(!(240&s),"Invalid character in "+e),i}function u(e,t,n,i){for(var o=0,s=0,a=Math.min(e.length,n),u=t;u=49?c-49+10:c>=17?c-17+10:c,r(c>=0&&s0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,n){if("number"==typeof e)return this._initNumber(e,t,n);if("object"==typeof e)return this._initArray(e,t,n);"hex"===t&&(t=16),r(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&i++,16===t?this._parseHex(e,i):this._parseBase(e,t,i),"-"===e[0]&&(this.negative=1),this._strip(),"le"===n&&this._initArray(this.toArray(),t,n)},o.prototype._initNumber=function(e,t,n){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(r(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),t,n)},o.prototype._initArray=function(e,t,n){if(r("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)s=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=s<>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);else if("le"===n)for(i=0,o=0;i>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);return this._strip()},o.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var n=0;n=t;n-=6)i=a(e,n,n+6),this.words[r]|=i<>>26-o&4194303,(o+=24)>=26&&(o-=26,r++);n+6!==t&&(i=a(e,t,n+6),this.words[r]|=i<>>26-o&4194303),this._strip()},o.prototype._parseBase=function(e,t,n){this.words=[0],this.length=1;for(var r=0,i=1;i<=67108863;i*=t)r++;r--,i=i/t|0;for(var o=e.length-n,s=o%r,a=Math.min(o,o-s)+n,c=0,f=n;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{o.prototype[Symbol.for("nodejs.util.inspect.custom")]=f}catch(e){o.prototype.inspect=f}else o.prototype.inspect=f;function f(){return(this.red?""}var l=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],d=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];o.prototype.toString=function(e,t){var n;if(t=0|t||1,16===(e=e||10)||"hex"===e){n="";for(var i=0,o=0,s=0;s>>24-i&16777215)||s!==this.length-1?l[6-u.length]+u+n:u+n,(i+=2)>=26&&(i-=26,s--)}for(0!==o&&(n=o.toString(16)+n);n.length%t!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(e===(0|e)&&e>=2&&e<=36){var c=d[e],f=h[e];n="";var p=this.clone();for(p.negative=0;!p.isZero();){var v=p.modrn(f).toString(e);n=(p=p.idivn(f)).isZero()?v+n:l[c-v.length]+v+n}for(this.isZero()&&(n="0"+n);n.length%t!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16,2)},s&&(o.prototype.toBuffer=function(e,t){return this.toArrayLike(s,e,t)}),o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)};function p(e,t,n){n.negative=t.negative^e.negative;var r=e.length+t.length|0;n.length=r,r=r-1|0;var i=0|e.words[0],o=0|t.words[0],s=i*o,a=67108863&s,u=s/67108864|0;n.words[0]=a;for(var c=1;c>>26,l=67108863&u,d=Math.min(c,t.length-1),h=Math.max(0,c-e.length+1);h<=d;h++){var p=c-h|0;f+=(s=(i=0|e.words[p])*(o=0|t.words[h])+l)/67108864|0,l=67108863&s}n.words[c]=0|l,u=0|f}return 0!==u?n.words[c]=0|u:n.length--,n._strip()}o.prototype.toArrayLike=function(e,t,n){this._strip();var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0");var s=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,o);return this["_toArrayLike"+("le"===t?"LE":"BE")](s,i),s},o.prototype._toArrayLikeLE=function(e,t){for(var n=0,r=0,i=0,o=0;i>8&255),n>16&255),6===o?(n>24&255),r=0,o=0):(r=s>>>24,o+=2)}if(n=0&&(e[n--]=s>>8&255),n>=0&&(e[n--]=s>>16&255),6===o?(n>=0&&(e[n--]=s>>24&255),r=0,o=0):(r=s>>>24,o+=2)}if(n>=0)for(e[n--]=r;n>=0;)e[n--]=0},Math.clz32?o.prototype._countBits=function(e){return 32-Math.clz32(e)}:o.prototype._countBits=function(e){var t=e,n=0;return t>=4096&&(n+=13,t>>>=13),t>=64&&(n+=7,t>>>=7),t>=8&&(n+=4,t>>>=4),t>=2&&(n+=2,t>>>=2),n+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,n=0;return 0==(8191&t)&&(n+=13,t>>>=13),0==(127&t)&&(n+=7,t>>>=7),0==(15&t)&&(n+=4,t>>>=4),0==(3&t)&&(n+=2,t>>>=2),0==(1&t)&&n++,n},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var n=0;ne.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,n;this.length>e.length?(t=this,n=e):(t=e,n=this);for(var r=0;re.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){r("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),n=e%26;this._expand(t),n>0&&t--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this._strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){r("number"==typeof e&&e>=0);var n=e/26|0,i=e%26;return this._expand(n+1),this.words[n]=t?this.words[n]|1<e.length?(n=this,r=e):(n=e,r=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=n.length,0!==i)this.words[this.length]=i,this.length++;else if(n!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var n,r,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(n=this,r=e):(n=e,r=this);for(var o=0,s=0;s>26,this.words[s]=67108863&t;for(;0!==o&&s>26,this.words[s]=67108863&t;if(0===o&&s>>13,h=0|s[1],p=8191&h,v=h>>>13,g=0|s[2],m=8191&g,b=g>>>13,y=0|s[3],w=8191&y,_=y>>>13,S=0|s[4],E=8191&S,M=S>>>13,A=0|s[5],I=8191&A,k=A>>>13,O=0|s[6],x=8191&O,C=O>>>13,T=0|s[7],P=8191&T,N=T>>>13,R=0|s[8],L=8191&R,j=R>>>13,D=0|s[9],U=8191&D,B=D>>>13,F=0|a[0],z=8191&F,q=F>>>13,K=0|a[1],H=8191&K,V=K>>>13,G=0|a[2],W=8191&G,$=G>>>13,Y=0|a[3],J=8191&Y,Z=Y>>>13,X=0|a[4],Q=8191&X,ee=X>>>13,te=0|a[5],ne=8191&te,re=te>>>13,ie=0|a[6],oe=8191&ie,se=ie>>>13,ae=0|a[7],ue=8191&ae,ce=ae>>>13,fe=0|a[8],le=8191&fe,de=fe>>>13,he=0|a[9],pe=8191&he,ve=he>>>13;n.negative=e.negative^t.negative,n.length=19;var ge=(c+(r=Math.imul(l,z))|0)+((8191&(i=(i=Math.imul(l,q))+Math.imul(d,z)|0))<<13)|0;c=((o=Math.imul(d,q))+(i>>>13)|0)+(ge>>>26)|0,ge&=67108863,r=Math.imul(p,z),i=(i=Math.imul(p,q))+Math.imul(v,z)|0,o=Math.imul(v,q);var me=(c+(r=r+Math.imul(l,H)|0)|0)+((8191&(i=(i=i+Math.imul(l,V)|0)+Math.imul(d,H)|0))<<13)|0;c=((o=o+Math.imul(d,V)|0)+(i>>>13)|0)+(me>>>26)|0,me&=67108863,r=Math.imul(m,z),i=(i=Math.imul(m,q))+Math.imul(b,z)|0,o=Math.imul(b,q),r=r+Math.imul(p,H)|0,i=(i=i+Math.imul(p,V)|0)+Math.imul(v,H)|0,o=o+Math.imul(v,V)|0;var be=(c+(r=r+Math.imul(l,W)|0)|0)+((8191&(i=(i=i+Math.imul(l,$)|0)+Math.imul(d,W)|0))<<13)|0;c=((o=o+Math.imul(d,$)|0)+(i>>>13)|0)+(be>>>26)|0,be&=67108863,r=Math.imul(w,z),i=(i=Math.imul(w,q))+Math.imul(_,z)|0,o=Math.imul(_,q),r=r+Math.imul(m,H)|0,i=(i=i+Math.imul(m,V)|0)+Math.imul(b,H)|0,o=o+Math.imul(b,V)|0,r=r+Math.imul(p,W)|0,i=(i=i+Math.imul(p,$)|0)+Math.imul(v,W)|0,o=o+Math.imul(v,$)|0;var ye=(c+(r=r+Math.imul(l,J)|0)|0)+((8191&(i=(i=i+Math.imul(l,Z)|0)+Math.imul(d,J)|0))<<13)|0;c=((o=o+Math.imul(d,Z)|0)+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,r=Math.imul(E,z),i=(i=Math.imul(E,q))+Math.imul(M,z)|0,o=Math.imul(M,q),r=r+Math.imul(w,H)|0,i=(i=i+Math.imul(w,V)|0)+Math.imul(_,H)|0,o=o+Math.imul(_,V)|0,r=r+Math.imul(m,W)|0,i=(i=i+Math.imul(m,$)|0)+Math.imul(b,W)|0,o=o+Math.imul(b,$)|0,r=r+Math.imul(p,J)|0,i=(i=i+Math.imul(p,Z)|0)+Math.imul(v,J)|0,o=o+Math.imul(v,Z)|0;var we=(c+(r=r+Math.imul(l,Q)|0)|0)+((8191&(i=(i=i+Math.imul(l,ee)|0)+Math.imul(d,Q)|0))<<13)|0;c=((o=o+Math.imul(d,ee)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,r=Math.imul(I,z),i=(i=Math.imul(I,q))+Math.imul(k,z)|0,o=Math.imul(k,q),r=r+Math.imul(E,H)|0,i=(i=i+Math.imul(E,V)|0)+Math.imul(M,H)|0,o=o+Math.imul(M,V)|0,r=r+Math.imul(w,W)|0,i=(i=i+Math.imul(w,$)|0)+Math.imul(_,W)|0,o=o+Math.imul(_,$)|0,r=r+Math.imul(m,J)|0,i=(i=i+Math.imul(m,Z)|0)+Math.imul(b,J)|0,o=o+Math.imul(b,Z)|0,r=r+Math.imul(p,Q)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,ee)|0;var _e=(c+(r=r+Math.imul(l,ne)|0)|0)+((8191&(i=(i=i+Math.imul(l,re)|0)+Math.imul(d,ne)|0))<<13)|0;c=((o=o+Math.imul(d,re)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,r=Math.imul(x,z),i=(i=Math.imul(x,q))+Math.imul(C,z)|0,o=Math.imul(C,q),r=r+Math.imul(I,H)|0,i=(i=i+Math.imul(I,V)|0)+Math.imul(k,H)|0,o=o+Math.imul(k,V)|0,r=r+Math.imul(E,W)|0,i=(i=i+Math.imul(E,$)|0)+Math.imul(M,W)|0,o=o+Math.imul(M,$)|0,r=r+Math.imul(w,J)|0,i=(i=i+Math.imul(w,Z)|0)+Math.imul(_,J)|0,o=o+Math.imul(_,Z)|0,r=r+Math.imul(m,Q)|0,i=(i=i+Math.imul(m,ee)|0)+Math.imul(b,Q)|0,o=o+Math.imul(b,ee)|0,r=r+Math.imul(p,ne)|0,i=(i=i+Math.imul(p,re)|0)+Math.imul(v,ne)|0,o=o+Math.imul(v,re)|0;var Se=(c+(r=r+Math.imul(l,oe)|0)|0)+((8191&(i=(i=i+Math.imul(l,se)|0)+Math.imul(d,oe)|0))<<13)|0;c=((o=o+Math.imul(d,se)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,r=Math.imul(P,z),i=(i=Math.imul(P,q))+Math.imul(N,z)|0,o=Math.imul(N,q),r=r+Math.imul(x,H)|0,i=(i=i+Math.imul(x,V)|0)+Math.imul(C,H)|0,o=o+Math.imul(C,V)|0,r=r+Math.imul(I,W)|0,i=(i=i+Math.imul(I,$)|0)+Math.imul(k,W)|0,o=o+Math.imul(k,$)|0,r=r+Math.imul(E,J)|0,i=(i=i+Math.imul(E,Z)|0)+Math.imul(M,J)|0,o=o+Math.imul(M,Z)|0,r=r+Math.imul(w,Q)|0,i=(i=i+Math.imul(w,ee)|0)+Math.imul(_,Q)|0,o=o+Math.imul(_,ee)|0,r=r+Math.imul(m,ne)|0,i=(i=i+Math.imul(m,re)|0)+Math.imul(b,ne)|0,o=o+Math.imul(b,re)|0,r=r+Math.imul(p,oe)|0,i=(i=i+Math.imul(p,se)|0)+Math.imul(v,oe)|0,o=o+Math.imul(v,se)|0;var Ee=(c+(r=r+Math.imul(l,ue)|0)|0)+((8191&(i=(i=i+Math.imul(l,ce)|0)+Math.imul(d,ue)|0))<<13)|0;c=((o=o+Math.imul(d,ce)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,r=Math.imul(L,z),i=(i=Math.imul(L,q))+Math.imul(j,z)|0,o=Math.imul(j,q),r=r+Math.imul(P,H)|0,i=(i=i+Math.imul(P,V)|0)+Math.imul(N,H)|0,o=o+Math.imul(N,V)|0,r=r+Math.imul(x,W)|0,i=(i=i+Math.imul(x,$)|0)+Math.imul(C,W)|0,o=o+Math.imul(C,$)|0,r=r+Math.imul(I,J)|0,i=(i=i+Math.imul(I,Z)|0)+Math.imul(k,J)|0,o=o+Math.imul(k,Z)|0,r=r+Math.imul(E,Q)|0,i=(i=i+Math.imul(E,ee)|0)+Math.imul(M,Q)|0,o=o+Math.imul(M,ee)|0,r=r+Math.imul(w,ne)|0,i=(i=i+Math.imul(w,re)|0)+Math.imul(_,ne)|0,o=o+Math.imul(_,re)|0,r=r+Math.imul(m,oe)|0,i=(i=i+Math.imul(m,se)|0)+Math.imul(b,oe)|0,o=o+Math.imul(b,se)|0,r=r+Math.imul(p,ue)|0,i=(i=i+Math.imul(p,ce)|0)+Math.imul(v,ue)|0,o=o+Math.imul(v,ce)|0;var Me=(c+(r=r+Math.imul(l,le)|0)|0)+((8191&(i=(i=i+Math.imul(l,de)|0)+Math.imul(d,le)|0))<<13)|0;c=((o=o+Math.imul(d,de)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,r=Math.imul(U,z),i=(i=Math.imul(U,q))+Math.imul(B,z)|0,o=Math.imul(B,q),r=r+Math.imul(L,H)|0,i=(i=i+Math.imul(L,V)|0)+Math.imul(j,H)|0,o=o+Math.imul(j,V)|0,r=r+Math.imul(P,W)|0,i=(i=i+Math.imul(P,$)|0)+Math.imul(N,W)|0,o=o+Math.imul(N,$)|0,r=r+Math.imul(x,J)|0,i=(i=i+Math.imul(x,Z)|0)+Math.imul(C,J)|0,o=o+Math.imul(C,Z)|0,r=r+Math.imul(I,Q)|0,i=(i=i+Math.imul(I,ee)|0)+Math.imul(k,Q)|0,o=o+Math.imul(k,ee)|0,r=r+Math.imul(E,ne)|0,i=(i=i+Math.imul(E,re)|0)+Math.imul(M,ne)|0,o=o+Math.imul(M,re)|0,r=r+Math.imul(w,oe)|0,i=(i=i+Math.imul(w,se)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,se)|0,r=r+Math.imul(m,ue)|0,i=(i=i+Math.imul(m,ce)|0)+Math.imul(b,ue)|0,o=o+Math.imul(b,ce)|0,r=r+Math.imul(p,le)|0,i=(i=i+Math.imul(p,de)|0)+Math.imul(v,le)|0,o=o+Math.imul(v,de)|0;var Ae=(c+(r=r+Math.imul(l,pe)|0)|0)+((8191&(i=(i=i+Math.imul(l,ve)|0)+Math.imul(d,pe)|0))<<13)|0;c=((o=o+Math.imul(d,ve)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,r=Math.imul(U,H),i=(i=Math.imul(U,V))+Math.imul(B,H)|0,o=Math.imul(B,V),r=r+Math.imul(L,W)|0,i=(i=i+Math.imul(L,$)|0)+Math.imul(j,W)|0,o=o+Math.imul(j,$)|0,r=r+Math.imul(P,J)|0,i=(i=i+Math.imul(P,Z)|0)+Math.imul(N,J)|0,o=o+Math.imul(N,Z)|0,r=r+Math.imul(x,Q)|0,i=(i=i+Math.imul(x,ee)|0)+Math.imul(C,Q)|0,o=o+Math.imul(C,ee)|0,r=r+Math.imul(I,ne)|0,i=(i=i+Math.imul(I,re)|0)+Math.imul(k,ne)|0,o=o+Math.imul(k,re)|0,r=r+Math.imul(E,oe)|0,i=(i=i+Math.imul(E,se)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,se)|0,r=r+Math.imul(w,ue)|0,i=(i=i+Math.imul(w,ce)|0)+Math.imul(_,ue)|0,o=o+Math.imul(_,ce)|0,r=r+Math.imul(m,le)|0,i=(i=i+Math.imul(m,de)|0)+Math.imul(b,le)|0,o=o+Math.imul(b,de)|0;var Ie=(c+(r=r+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,ve)|0)+Math.imul(v,pe)|0))<<13)|0;c=((o=o+Math.imul(v,ve)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,r=Math.imul(U,W),i=(i=Math.imul(U,$))+Math.imul(B,W)|0,o=Math.imul(B,$),r=r+Math.imul(L,J)|0,i=(i=i+Math.imul(L,Z)|0)+Math.imul(j,J)|0,o=o+Math.imul(j,Z)|0,r=r+Math.imul(P,Q)|0,i=(i=i+Math.imul(P,ee)|0)+Math.imul(N,Q)|0,o=o+Math.imul(N,ee)|0,r=r+Math.imul(x,ne)|0,i=(i=i+Math.imul(x,re)|0)+Math.imul(C,ne)|0,o=o+Math.imul(C,re)|0,r=r+Math.imul(I,oe)|0,i=(i=i+Math.imul(I,se)|0)+Math.imul(k,oe)|0,o=o+Math.imul(k,se)|0,r=r+Math.imul(E,ue)|0,i=(i=i+Math.imul(E,ce)|0)+Math.imul(M,ue)|0,o=o+Math.imul(M,ce)|0,r=r+Math.imul(w,le)|0,i=(i=i+Math.imul(w,de)|0)+Math.imul(_,le)|0,o=o+Math.imul(_,de)|0;var ke=(c+(r=r+Math.imul(m,pe)|0)|0)+((8191&(i=(i=i+Math.imul(m,ve)|0)+Math.imul(b,pe)|0))<<13)|0;c=((o=o+Math.imul(b,ve)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,r=Math.imul(U,J),i=(i=Math.imul(U,Z))+Math.imul(B,J)|0,o=Math.imul(B,Z),r=r+Math.imul(L,Q)|0,i=(i=i+Math.imul(L,ee)|0)+Math.imul(j,Q)|0,o=o+Math.imul(j,ee)|0,r=r+Math.imul(P,ne)|0,i=(i=i+Math.imul(P,re)|0)+Math.imul(N,ne)|0,o=o+Math.imul(N,re)|0,r=r+Math.imul(x,oe)|0,i=(i=i+Math.imul(x,se)|0)+Math.imul(C,oe)|0,o=o+Math.imul(C,se)|0,r=r+Math.imul(I,ue)|0,i=(i=i+Math.imul(I,ce)|0)+Math.imul(k,ue)|0,o=o+Math.imul(k,ce)|0,r=r+Math.imul(E,le)|0,i=(i=i+Math.imul(E,de)|0)+Math.imul(M,le)|0,o=o+Math.imul(M,de)|0;var Oe=(c+(r=r+Math.imul(w,pe)|0)|0)+((8191&(i=(i=i+Math.imul(w,ve)|0)+Math.imul(_,pe)|0))<<13)|0;c=((o=o+Math.imul(_,ve)|0)+(i>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,r=Math.imul(U,Q),i=(i=Math.imul(U,ee))+Math.imul(B,Q)|0,o=Math.imul(B,ee),r=r+Math.imul(L,ne)|0,i=(i=i+Math.imul(L,re)|0)+Math.imul(j,ne)|0,o=o+Math.imul(j,re)|0,r=r+Math.imul(P,oe)|0,i=(i=i+Math.imul(P,se)|0)+Math.imul(N,oe)|0,o=o+Math.imul(N,se)|0,r=r+Math.imul(x,ue)|0,i=(i=i+Math.imul(x,ce)|0)+Math.imul(C,ue)|0,o=o+Math.imul(C,ce)|0,r=r+Math.imul(I,le)|0,i=(i=i+Math.imul(I,de)|0)+Math.imul(k,le)|0,o=o+Math.imul(k,de)|0;var xe=(c+(r=r+Math.imul(E,pe)|0)|0)+((8191&(i=(i=i+Math.imul(E,ve)|0)+Math.imul(M,pe)|0))<<13)|0;c=((o=o+Math.imul(M,ve)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,r=Math.imul(U,ne),i=(i=Math.imul(U,re))+Math.imul(B,ne)|0,o=Math.imul(B,re),r=r+Math.imul(L,oe)|0,i=(i=i+Math.imul(L,se)|0)+Math.imul(j,oe)|0,o=o+Math.imul(j,se)|0,r=r+Math.imul(P,ue)|0,i=(i=i+Math.imul(P,ce)|0)+Math.imul(N,ue)|0,o=o+Math.imul(N,ce)|0,r=r+Math.imul(x,le)|0,i=(i=i+Math.imul(x,de)|0)+Math.imul(C,le)|0,o=o+Math.imul(C,de)|0;var Ce=(c+(r=r+Math.imul(I,pe)|0)|0)+((8191&(i=(i=i+Math.imul(I,ve)|0)+Math.imul(k,pe)|0))<<13)|0;c=((o=o+Math.imul(k,ve)|0)+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,r=Math.imul(U,oe),i=(i=Math.imul(U,se))+Math.imul(B,oe)|0,o=Math.imul(B,se),r=r+Math.imul(L,ue)|0,i=(i=i+Math.imul(L,ce)|0)+Math.imul(j,ue)|0,o=o+Math.imul(j,ce)|0,r=r+Math.imul(P,le)|0,i=(i=i+Math.imul(P,de)|0)+Math.imul(N,le)|0,o=o+Math.imul(N,de)|0;var Te=(c+(r=r+Math.imul(x,pe)|0)|0)+((8191&(i=(i=i+Math.imul(x,ve)|0)+Math.imul(C,pe)|0))<<13)|0;c=((o=o+Math.imul(C,ve)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,r=Math.imul(U,ue),i=(i=Math.imul(U,ce))+Math.imul(B,ue)|0,o=Math.imul(B,ce),r=r+Math.imul(L,le)|0,i=(i=i+Math.imul(L,de)|0)+Math.imul(j,le)|0,o=o+Math.imul(j,de)|0;var Pe=(c+(r=r+Math.imul(P,pe)|0)|0)+((8191&(i=(i=i+Math.imul(P,ve)|0)+Math.imul(N,pe)|0))<<13)|0;c=((o=o+Math.imul(N,ve)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,r=Math.imul(U,le),i=(i=Math.imul(U,de))+Math.imul(B,le)|0,o=Math.imul(B,de);var Ne=(c+(r=r+Math.imul(L,pe)|0)|0)+((8191&(i=(i=i+Math.imul(L,ve)|0)+Math.imul(j,pe)|0))<<13)|0;c=((o=o+Math.imul(j,ve)|0)+(i>>>13)|0)+(Ne>>>26)|0,Ne&=67108863;var Re=(c+(r=Math.imul(U,pe))|0)+((8191&(i=(i=Math.imul(U,ve))+Math.imul(B,pe)|0))<<13)|0;return c=((o=Math.imul(B,ve))+(i>>>13)|0)+(Re>>>26)|0,Re&=67108863,u[0]=ge,u[1]=me,u[2]=be,u[3]=ye,u[4]=we,u[5]=_e,u[6]=Se,u[7]=Ee,u[8]=Me,u[9]=Ae,u[10]=Ie,u[11]=ke,u[12]=Oe,u[13]=xe,u[14]=Ce,u[15]=Te,u[16]=Pe,u[17]=Ne,u[18]=Re,0!==c&&(u[19]=c,n.length++),n};function g(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var r=0,i=0,o=0;o>>26)|0)>>>26,s&=67108863}n.words[o]=a,r=s,s=i}return 0!==r?n.words[o]=r:n.length--,n._strip()}function m(e,t,n){return g(e,t,n)}function b(e,t){this.x=e,this.y=t}Math.imul||(v=p),o.prototype.mulTo=function(e,t){var n=this.length+e.length;return 10===this.length&&10===e.length?v(this,e,t):n<63?p(this,e,t):n<1024?g(this,e,t):m(this,e,t)},b.prototype.makeRBT=function(e){for(var t=new Array(e),n=o.prototype._countBits(e)-1,r=0;r>=1;return r},b.prototype.permute=function(e,t,n,r,i,o){for(var s=0;s>>=1)i++;return 1<>>=13,n[2*s+1]=8191&o,o>>>=13;for(s=2*t;s>=26,n+=o/67108864|0,n+=s>>>26,this.words[i]=67108863&s}return 0!==n&&(this.words[i]=n,this.length++),t?this.ineg():this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),n=0;n>>i&1}return t}(e);if(0===t.length)return new o(1);for(var n=this,r=0;r=0);var t,n=e%26,i=(e-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var s=0;for(t=0;t>>26-n}s&&(this.words[t]=s,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t=0),i=t?(t-t%26)/26:0;var o=e%26,s=Math.min((e-o)/26,this.length),a=67108863^67108863>>>o<s)for(this.length-=s,c=0;c=0&&(0!==f||c>=i);c--){var l=0|this.words[c];this.words[c]=f<<26-o|l>>>o,f=l&a}return u&&0!==f&&(u.words[u.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},o.prototype.ishrn=function(e,t,n){return r(0===this.negative),this.iushrn(e,t,n)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){r("number"==typeof e&&e>=0);var t=e%26,n=(e-t)/26,i=1<=0);var t=e%26,n=(e-t)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==t&&n++,this.length=Math.min(n,this.length),0!==t){var i=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(r("number"==typeof e),r(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(u/67108864|0),this.words[i+n]=67108863&o}for(;i>26,this.words[i+n]=67108863&o;if(0===a)return this._strip();for(r(-1===a),a=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this._strip()},o.prototype._wordDiv=function(e,t){var n=(this.length,e.length),r=this.clone(),i=e,s=0|i.words[i.length-1];0!==(n=26-this._countBits(s))&&(i=i.ushln(n),r.iushln(n),s=0|i.words[i.length-1]);var a,u=r.length-i.length;if("mod"!==t){(a=new o(null)).length=u+1,a.words=new Array(a.length);for(var c=0;c=0;l--){var d=67108864*(0|r.words[i.length+l])+(0|r.words[i.length+l-1]);for(d=Math.min(d/s|0,67108863),r._ishlnsubmul(i,d,l);0!==r.negative;)d--,r.negative=0,r._ishlnsubmul(i,1,l),r.isZero()||(r.negative^=1);a&&(a.words[l]=d)}return a&&a._strip(),r._strip(),"div"!==t&&0!==n&&r.iushrn(n),{div:a||null,mod:r}},o.prototype.divmod=function(e,t,n){return r(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(i=a.div.neg()),"div"!==t&&(s=a.mod.neg(),n&&0!==s.negative&&s.iadd(e)),{div:i,mod:s}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(i=a.div.neg()),{div:i,mod:a.mod}):0!=(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(s=a.mod.neg(),n&&0!==s.negative&&s.isub(e)),{div:a.div,mod:s}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modrn(e.words[0]))}:this._wordDiv(e,t);var i,s,a},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var n=0!==t.div.negative?t.mod.isub(e):t.mod,r=e.ushrn(1),i=e.andln(1),o=n.cmp(r);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modrn=function(e){var t=e<0;t&&(e=-e),r(e<=67108863);for(var n=(1<<26)%e,i=0,o=this.length-1;o>=0;o--)i=(n*i+(0|this.words[o]))%e;return t?-i:i},o.prototype.modn=function(e){return this.modrn(e)},o.prototype.idivn=function(e){var t=e<0;t&&(e=-e),r(e<=67108863);for(var n=0,i=this.length-1;i>=0;i--){var o=(0|this.words[i])+67108864*n;this.words[i]=o/e|0,n=o%e}return this._strip(),t?this.ineg():this},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){r(0===e.negative),r(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),s=new o(0),a=new o(0),u=new o(1),c=0;t.isEven()&&n.isEven();)t.iushrn(1),n.iushrn(1),++c;for(var f=n.clone(),l=t.clone();!t.isZero();){for(var d=0,h=1;0==(t.words[0]&h)&&d<26;++d,h<<=1);if(d>0)for(t.iushrn(d);d-- >0;)(i.isOdd()||s.isOdd())&&(i.iadd(f),s.isub(l)),i.iushrn(1),s.iushrn(1);for(var p=0,v=1;0==(n.words[0]&v)&&p<26;++p,v<<=1);if(p>0)for(n.iushrn(p);p-- >0;)(a.isOdd()||u.isOdd())&&(a.iadd(f),u.isub(l)),a.iushrn(1),u.iushrn(1);t.cmp(n)>=0?(t.isub(n),i.isub(a),s.isub(u)):(n.isub(t),a.isub(i),u.isub(s))}return{a:a,b:u,gcd:n.iushln(c)}},o.prototype._invmp=function(e){r(0===e.negative),r(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,s=new o(1),a=new o(0),u=n.clone();t.cmpn(1)>0&&n.cmpn(1)>0;){for(var c=0,f=1;0==(t.words[0]&f)&&c<26;++c,f<<=1);if(c>0)for(t.iushrn(c);c-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);for(var l=0,d=1;0==(n.words[0]&d)&&l<26;++l,d<<=1);if(l>0)for(n.iushrn(l);l-- >0;)a.isOdd()&&a.iadd(u),a.iushrn(1);t.cmp(n)>=0?(t.isub(n),s.isub(a)):(n.isub(t),a.isub(s))}return(i=0===t.cmpn(1)?s:a).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),n=e.clone();t.negative=0,n.negative=0;for(var r=0;t.isEven()&&n.isEven();r++)t.iushrn(1),n.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;n.isEven();)n.iushrn(1);var i=t.cmp(n);if(i<0){var o=t;t=n,n=o}else if(0===i||0===n.cmpn(1))break;t.isub(n)}return n.iushln(r)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){r("number"==typeof e);var t=e%26,n=(e-t)/26,i=1<>>26,a&=67108863,this.words[s]=a}return 0!==o&&(this.words[s]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,n=e<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this._strip(),this.length>1)t=1;else{n&&(e=-e),r(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:ie.length)return 1;if(this.length=0;n--){var r=0|this.words[n],i=0|e.words[n];if(r!==i){ri&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new A(e)},o.prototype.toRed=function(e){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return r(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return r(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var y={k256:null,p224:null,p192:null,p25519:null};function w(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function _(){w.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function S(){w.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function E(){w.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function M(){w.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function A(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else r(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function I(e){A.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}w.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},w.prototype.ireduce=function(e){var t,n=e;do{this.split(n,this.tmp),t=(n=(n=this.imulK(n)).iadd(this.tmp)).bitLength()}while(t>this.n);var r=t0?n.isub(this.p):void 0!==n.strip?n.strip():n._strip(),n},w.prototype.split=function(e,t){e.iushrn(this.n,0,t)},w.prototype.imulK=function(e){return e.imul(this.k)},i(_,w),_.prototype.split=function(e,t){for(var n=Math.min(e.length,9),r=0;r>>22,i=o}i>>>=22,e.words[r-10]=i,0===i&&e.length>10?e.length-=10:e.length-=9},_.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,n=0;n>>=26,e.words[n]=i,t=r}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(y[e])return y[e];var t;if("k256"===e)t=new _;else if("p224"===e)t=new S;else if("p192"===e)t=new E;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new M}return y[e]=t,t},A.prototype._verify1=function(e){r(0===e.negative,"red works only with positives"),r(e.red,"red works only with red numbers")},A.prototype._verify2=function(e,t){r(0==(e.negative|t.negative),"red works only with positives"),r(e.red&&e.red===t.red,"red works only with red numbers")},A.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(c(e,e.umod(this.m)._forceRed(this)),e)},A.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},A.prototype.add=function(e,t){this._verify2(e,t);var n=e.add(t);return n.cmp(this.m)>=0&&n.isub(this.m),n._forceRed(this)},A.prototype.iadd=function(e,t){this._verify2(e,t);var n=e.iadd(t);return n.cmp(this.m)>=0&&n.isub(this.m),n},A.prototype.sub=function(e,t){this._verify2(e,t);var n=e.sub(t);return n.cmpn(0)<0&&n.iadd(this.m),n._forceRed(this)},A.prototype.isub=function(e,t){this._verify2(e,t);var n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n},A.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},A.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},A.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},A.prototype.isqr=function(e){return this.imul(e,e.clone())},A.prototype.sqr=function(e){return this.mul(e,e)},A.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(r(t%2==1),3===t){var n=this.m.add(new o(1)).iushrn(2);return this.pow(e,n)}for(var i=this.m.subn(1),s=0;!i.isZero()&&0===i.andln(1);)s++,i.iushrn(1);r(!i.isZero());var a=new o(1).toRed(this),u=a.redNeg(),c=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new o(2*f*f).toRed(this);0!==this.pow(f,c).cmp(u);)f.redIAdd(u);for(var l=this.pow(f,i),d=this.pow(e,i.addn(1).iushrn(1)),h=this.pow(e,i),p=s;0!==h.cmp(a);){for(var v=h,g=0;0!==v.cmp(a);g++)v=v.redSqr();r(g=0;r--){for(var c=t.words[r],f=u-1;f>=0;f--){var l=c>>f&1;i!==n[0]&&(i=this.sqr(i)),0!==l||0!==s?(s<<=1,s|=l,(4===++a||0===r&&0===f)&&(i=this.mul(i,n[s]),a=0,s=0)):a=0}u=26}return i},A.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},A.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new I(e)},i(I,A),I.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},I.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},I.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var n=e.imul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=n.isub(r).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},I.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var n=e.mul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=n.isub(r).iushrn(this.shift),s=i;return i.cmp(this.m)>=0?s=i.isub(this.m):i.cmpn(0)<0&&(s=i.iadd(this.m)),s._forceRed(this)},I.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(e,this)}).call(this,n(57)(e))},function(e,t,n){"use strict";const r=t;r.bignum=n(29),r.define=n(351).define,r.base=n(354),r.constants=n(355),r.decoders=n(207),r.encoders=n(205)},function(e,t,n){"use strict";const r=t;r.der=n(206),r.pem=n(352)},function(e,t,n){"use strict";const r=n(7),i=n(130).Buffer,o=n(131),s=n(133);function a(e){this.enc="der",this.name=e.name,this.entity=e,this.tree=new u,this.tree._init(e.body)}function u(e){o.call(this,"der",e)}function c(e){return e<10?"0"+e:e}e.exports=a,a.prototype.encode=function(e,t){return this.tree._encode(e,t).join()},r(u,o),u.prototype._encodeComposite=function(e,t,n,r){const o=function(e,t,n,r){let i;"seqof"===e?e="seq":"setof"===e&&(e="set");if(s.tagByName.hasOwnProperty(e))i=s.tagByName[e];else{if("number"!=typeof e||(0|e)!==e)return r.error("Unknown tag: "+e);i=e}if(i>=31)return r.error("Multi-octet tag encoding unsupported");t||(i|=32);return i|=s.tagClassByName[n||"universal"]<<6,i}(e,t,n,this.reporter);if(r.length<128){const e=i.alloc(2);return e[0]=o,e[1]=r.length,this._createEncoderBuffer([e,r])}let a=1;for(let e=r.length;e>=256;e>>=8)a++;const u=i.alloc(2+a);u[0]=o,u[1]=128|a;for(let e=1+a,t=r.length;t>0;e--,t>>=8)u[e]=255&t;return this._createEncoderBuffer([u,r])},u.prototype._encodeStr=function(e,t){if("bitstr"===t)return this._createEncoderBuffer([0|e.unused,e.data]);if("bmpstr"===t){const t=i.alloc(2*e.length);for(let n=0;n=40)return this.reporter.error("Second objid identifier OOB");e.splice(0,2,40*e[0]+e[1])}let r=0;for(let t=0;t=128;n>>=7)r++}const o=i.alloc(r);let s=o.length-1;for(let t=e.length-1;t>=0;t--){let n=e[t];for(o[s--]=127&n;(n>>=7)>0;)o[s--]=128|127&n}return this._createEncoderBuffer(o)},u.prototype._encodeTime=function(e,t){let n;const r=new Date(e);return"gentime"===t?n=[c(r.getUTCFullYear()),c(r.getUTCMonth()+1),c(r.getUTCDate()),c(r.getUTCHours()),c(r.getUTCMinutes()),c(r.getUTCSeconds()),"Z"].join(""):"utctime"===t?n=[c(r.getUTCFullYear()%100),c(r.getUTCMonth()+1),c(r.getUTCDate()),c(r.getUTCHours()),c(r.getUTCMinutes()),c(r.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+t+" time is not supported yet"),this._encodeStr(n,"octstr")},u.prototype._encodeNull=function(){return this._createEncoderBuffer("")},u.prototype._encodeInt=function(e,t){if("string"==typeof e){if(!t)return this.reporter.error("String int or enum given, but no values map");if(!t.hasOwnProperty(e))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(e));e=t[e]}if("number"!=typeof e&&!i.isBuffer(e)){const t=e.toArray();!e.sign&&128&t[0]&&t.unshift(0),e=i.from(t)}if(i.isBuffer(e)){let t=e.length;0===e.length&&t++;const n=i.alloc(t);return e.copy(n),0===e.length&&(n[0]=0),this._createEncoderBuffer(n)}if(e<128)return this._createEncoderBuffer(e);if(e<256)return this._createEncoderBuffer([0,e]);let n=1;for(let t=e;t>=256;t>>=8)n++;const r=new Array(n);for(let t=r.length-1;t>=0;t--)r[t]=255&e,e>>=8;return 128&r[0]&&r.unshift(0),this._createEncoderBuffer(i.from(r))},u.prototype._encodeBool=function(e){return this._createEncoderBuffer(e?255:0)},u.prototype._use=function(e,t){return"function"==typeof e&&(e=e(t)),e._getEncoder("der").tree},u.prototype._skipDefault=function(e,t,n){const r=this._baseState;let i;if(null===r.default)return!1;const o=e.join();if(void 0===r.defaultBuffer&&(r.defaultBuffer=this._encodeValue(r.default,t,n).join()),o.length!==r.defaultBuffer.length)return!1;for(i=0;i>6],i=0==(32&n);if(31==(31&n)){let r=n;for(n=0;128==(128&r);){if(r=e.readUInt8(t),e.isError(r))return r;n<<=7,n|=127&r}}else n&=31;return{cls:r,primitive:i,tag:n,tagStr:a.tag[n]}}function l(e,t,n){let r=e.readUInt8(n);if(e.isError(r))return r;if(!t&&128===r)return null;if(0==(128&r))return r;const i=127&r;if(i>4)return e.error("length octect is too long");r=0;for(let t=0;t>>((3&t)<<3)&255;return i}}},function(e,t){for(var n=[],r=0;r<256;++r)n[r]=(r+256).toString(16).substr(1);e.exports=function(e,t){var r=t||0,i=n;return[i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]],"-",i[e[r++]],i[e[r++]],"-",i[e[r++]],i[e[r++]],"-",i[e[r++]],i[e[r++]],"-",i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]]].join("")}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Sha256=void 0;var r=n(217),i=n(218),o=n(249),s=n(134),a=function(){function e(e){e?(this.operation=function(e){return new Promise((function(t,n){var r=s.locateWindow().msCrypto.subtle.importKey("raw",u(e),i.SHA_256_HMAC_ALGO,!1,["sign"]);r.oncomplete=function(){r.result&&t(r.result),n("ImportKey completed without importing key.")},r.onerror=function(){n("ImportKey failed to import key.")}}))}(e).then((function(e){return s.locateWindow().msCrypto.subtle.sign(i.SHA_256_HMAC_ALGO,e)})),this.operation.catch((function(){}))):this.operation=Promise.resolve(s.locateWindow().msCrypto.subtle.digest("SHA-256"))}return e.prototype.update=function(e){var t=this;r.isEmptyData(e)||(this.operation=this.operation.then((function(n){return n.onerror=function(){t.operation=Promise.reject(new Error("Error encountered updating hash"))},n.process(u(e)),n})),this.operation.catch((function(){})))},e.prototype.digest=function(){return this.operation.then((function(e){return new Promise((function(t,n){e.onerror=function(){n("Error encountered finalizing hash")},e.oncomplete=function(){e.result&&t(new Uint8Array(e.result)),n("Error encountered finalizing hash")},e.finish()}))}))},e}();function u(e){return"string"==typeof e?o.fromUtf8(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}t.Sha256=a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEmptyData=void 0,t.isEmptyData=function(e){return"string"==typeof e?0===e.length:0===e.byteLength}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EMPTY_DATA_SHA_256=t.SHA_256_HMAC_ALGO=t.SHA_256_HASH=void 0,t.SHA_256_HASH={name:"SHA-256"},t.SHA_256_HMAC_ALGO={name:"HMAC",hash:t.SHA_256_HASH},t.EMPTY_DATA_SHA_256=new Uint8Array([227,176,196,66,152,252,28,20,154,251,244,200,153,111,185,36,39,174,65,228,100,155,147,76,164,149,153,27,120,82,184,85])},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Sha256=void 0;var r=n(249),i=n(217),o=n(218),s=n(134),a=function(){function e(e){this.toHash=new Uint8Array(0),void 0!==e&&(this.key=new Promise((function(t,n){s.locateWindow().crypto.subtle.importKey("raw",u(e),o.SHA_256_HMAC_ALGO,!1,["sign"]).then(t,n)})),this.key.catch((function(){})))}return e.prototype.update=function(e){if(!i.isEmptyData(e)){var t=u(e),n=new Uint8Array(this.toHash.byteLength+t.byteLength);n.set(this.toHash,0),n.set(t,this.toHash.byteLength),this.toHash=n}},e.prototype.digest=function(){var e=this;return this.key?this.key.then((function(t){return s.locateWindow().crypto.subtle.sign(o.SHA_256_HMAC_ALGO,t,e.toHash).then((function(e){return new Uint8Array(e)}))})):i.isEmptyData(this.toHash)?Promise.resolve(o.EMPTY_DATA_SHA_256):Promise.resolve().then((function(){return s.locateWindow().crypto.subtle.digest(o.SHA_256_HASH,e.toHash)})).then((function(e){return Promise.resolve(new Uint8Array(e))}))},e}();function u(e){return"string"==typeof e?r.fromUtf8(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}t.Sha256=a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MAX_HASHABLE_LENGTH=t.INIT=t.KEY=t.DIGEST_LENGTH=t.BLOCK_SIZE=void 0,t.BLOCK_SIZE=64,t.DIGEST_LENGTH=32,t.KEY=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),t.INIT=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],t.MAX_HASHABLE_LENGTH=Math.pow(2,53)-1},function(e,t,n){"use strict";n.d(t,"a",(function(){return o}));var r=new(n(44).a)("Parser"),i=function(e){var t,n={};if(e.aws_mobile_analytics_app_id){var i={AWSPinpoint:{appId:e.aws_mobile_analytics_app_id,region:e.aws_mobile_analytics_app_region}};n.Analytics=i}return(e.aws_cognito_identity_pool_id||e.aws_user_pools_id)&&(n.Auth={userPoolId:e.aws_user_pools_id,userPoolWebClientId:e.aws_user_pools_web_client_id,region:e.aws_cognito_region,identityPoolId:e.aws_cognito_identity_pool_id,identityPoolRegion:e.aws_cognito_region,mandatorySignIn:"enable"===e.aws_mandatory_sign_in}),t=e.aws_user_files_s3_bucket?{AWSS3:{bucket:e.aws_user_files_s3_bucket,region:e.aws_user_files_s3_bucket_region,dangerouslyConnectToHttpEndpointForTesting:e.aws_user_files_s3_dangerously_connect_to_http_endpoint_for_testing}}:e?e.Storage||e:{},n.Analytics=Object.assign({},n.Analytics,e.Analytics),n.Auth=Object.assign({},n.Auth,e.Auth),n.Storage=Object.assign({},t),r.debug("parse config",e,"to amplifyconfig",n),n},o=function(){function e(){}return e.parseMobilehubConfig=i,e}()},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BLOCK_SIZE=64,t.DIGEST_LENGTH=32,t.KEY=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),t.INIT=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],t.MAX_HASHABLE_LENGTH=Math.pow(2,53)-1},function(e,t,n){(function(t){var n="object"==typeof t&&t&&t.Object===Object&&t;e.exports=n}).call(this,n(31))},function(e,t,n){var r=n(84),i=n(225);e.exports=function(e){if(!i(e))return!1;var t=r(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t}},function(e,t){e.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},function(e,t){var n=Function.prototype.toString;e.exports=function(e){if(null!=e){try{return n.call(e)}catch(e){}try{return e+""}catch(e){}}return""}},function(e,t){e.exports=function(e,t){return e===t||e!=e&&t!=t}},function(e,t,n){var r=n(229),i=n(420),o=Object.prototype.hasOwnProperty;e.exports=function(e){if(!r(e))return i(e);var t=[];for(var n in Object(e))o.call(e,n)&&"constructor"!=n&&t.push(n);return t}},function(e,t){var n=Object.prototype;e.exports=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||n)}},function(e,t,n){var r=n(422),i=n(137),o=n(423),s=n(424),a=n(425),u=n(84),c=n(226),f=c(r),l=c(i),d=c(o),h=c(s),p=c(a),v=u;(r&&"[object DataView]"!=v(new r(new ArrayBuffer(1)))||i&&"[object Map]"!=v(new i)||o&&"[object Promise]"!=v(o.resolve())||s&&"[object Set]"!=v(new s)||a&&"[object WeakMap]"!=v(new a))&&(v=function(e){var t=u(e),n="[object Object]"==t?e.constructor:void 0,r=n?c(n):"";if(r)switch(r){case f:return"[object DataView]";case l:return"[object Map]";case d:return"[object Promise]";case h:return"[object Set]";case p:return"[object WeakMap]"}return t}),e.exports=v},function(e,t,n){var r=n(426),i=n(85),o=Object.prototype,s=o.hasOwnProperty,a=o.propertyIsEnumerable,u=r(function(){return arguments}())?r:function(e){return i(e)&&s.call(e,"callee")&&!a.call(e,"callee")};e.exports=u},function(e,t,n){var r=n(224),i=n(233);e.exports=function(e){return null!=e&&i(e.length)&&!r(e)}},function(e,t){e.exports=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991}},function(e,t,n){var r=n(439),i=n(442),o=n(443);e.exports=function(e,t,n,s,a,u){var c=1&n,f=e.length,l=t.length;if(f!=l&&!(c&&l>f))return!1;var d=u.get(e),h=u.get(t);if(d&&h)return d==t&&h==e;var p=-1,v=!0,g=2&n?new r:void 0;for(u.set(e,t),u.set(t,e);++p=200&&e<300}};u.headers={common:{Accept:"application/json, text/plain, */*"}},r.forEach(["delete","get","head"],(function(e){u.headers[e]={}})),r.forEach(["post","put","patch"],(function(e){u.headers[e]=r.merge(o)})),e.exports=u}).call(this,n(20))},function(e,t,n){"use strict";var r=n(45),i=n(471),o=n(473),s=n(236),a=n(474),u=n(477),c=n(478),f=n(240);e.exports=function(e){return new Promise((function(t,n){var l=e.data,d=e.headers;r.isFormData(l)&&delete d["Content-Type"];var h=new XMLHttpRequest;if(e.auth){var p=e.auth.username||"",v=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";d.Authorization="Basic "+btoa(p+":"+v)}var g=a(e.baseURL,e.url);if(h.open(e.method.toUpperCase(),s(g,e.params,e.paramsSerializer),!0),h.timeout=e.timeout,h.onreadystatechange=function(){if(h&&4===h.readyState&&(0!==h.status||h.responseURL&&0===h.responseURL.indexOf("file:"))){var r="getAllResponseHeaders"in h?u(h.getAllResponseHeaders()):null,o={data:e.responseType&&"text"!==e.responseType?h.response:h.responseText,status:h.status,statusText:h.statusText,headers:r,config:e,request:h};i(t,n,o),h=null}},h.onabort=function(){h&&(n(f("Request aborted",e,"ECONNABORTED",h)),h=null)},h.onerror=function(){n(f("Network Error",e,null,h)),h=null},h.ontimeout=function(){var t="timeout of "+e.timeout+"ms exceeded";e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),n(f(t,e,"ECONNABORTED",h)),h=null},r.isStandardBrowserEnv()){var m=(e.withCredentials||c(g))&&e.xsrfCookieName?o.read(e.xsrfCookieName):void 0;m&&(d[e.xsrfHeaderName]=m)}if("setRequestHeader"in h&&r.forEach(d,(function(e,t){void 0===l&&"content-type"===t.toLowerCase()?delete d[t]:h.setRequestHeader(t,e)})),r.isUndefined(e.withCredentials)||(h.withCredentials=!!e.withCredentials),e.responseType)try{h.responseType=e.responseType}catch(t){if("json"!==e.responseType)throw t}"function"==typeof e.onDownloadProgress&&h.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&h.upload&&h.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then((function(e){h&&(h.abort(),n(e),h=null)})),l||(l=null),h.send(l)}))}},function(e,t,n){"use strict";var r=n(472);e.exports=function(e,t,n,i,o){var s=new Error(e);return r(s,t,n,i,o)}},function(e,t,n){"use strict";var r=n(45);e.exports=function(e,t){t=t||{};var n={},i=["url","method","data"],o=["headers","auth","proxy","params"],s=["baseURL","transformRequest","transformResponse","paramsSerializer","timeout","timeoutMessage","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","decompress","maxContentLength","maxBodyLength","maxRedirects","transport","httpAgent","httpsAgent","cancelToken","socketPath","responseEncoding"],a=["validateStatus"];function u(e,t){return r.isPlainObject(e)&&r.isPlainObject(t)?r.merge(e,t):r.isPlainObject(t)?r.merge({},t):r.isArray(t)?t.slice():t}function c(i){r.isUndefined(t[i])?r.isUndefined(e[i])||(n[i]=u(void 0,e[i])):n[i]=u(e[i],t[i])}r.forEach(i,(function(e){r.isUndefined(t[e])||(n[e]=u(void 0,t[e]))})),r.forEach(o,c),r.forEach(s,(function(i){r.isUndefined(t[i])?r.isUndefined(e[i])||(n[i]=u(void 0,e[i])):n[i]=u(void 0,t[i])})),r.forEach(a,(function(r){r in t?n[r]=u(e[r],t[r]):r in e&&(n[r]=u(void 0,e[r]))}));var f=i.concat(o).concat(s).concat(a),l=Object.keys(e).concat(Object.keys(t)).filter((function(e){return-1===f.indexOf(e)}));return r.forEach(l,c),n}},function(e,t,n){"use strict";function r(e){this.message=e}r.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},r.prototype.__CANCEL__=!0,e.exports=r},function(e,t){var n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(n){var r=new Uint8Array(16);e.exports=function(){return n(r),r}}else{var i=new Array(16);e.exports=function(){for(var e,t=0;t<16;t++)0==(3&t)&&(e=4294967296*Math.random()),i[t]=e>>>((3&t)<<3)&255;return i}}},function(e,t){for(var n=[],r=0;r<256;++r)n[r]=(r+256).toString(16).substr(1);e.exports=function(e,t){var r=t||0,i=n;return[i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]],"-",i[e[r++]],i[e[r++]],"-",i[e[r++]],i[e[r++]],"-",i[e[r++]],i[e[r++]],"-",i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]]].join("")}},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));var r=function(){function e(){}return e.createPredicateBuilder=function(t){var n=t.name,r=new Set(Object.keys(t.fields)),i=new Proxy({},{get:function(t,i,o){var s=i;if(!r.has(s))throw new Error("Invalid field for model. field: "+s+", model: "+n);return function(t){return e.sortPredicateGroupsMap.get(o).push({field:s,sortDirection:t}),o}}});return e.sortPredicateGroupsMap.set(i,[]),i},e.isValidPredicate=function(t){return e.sortPredicateGroupsMap.has(t)},e.getPredicates=function(t,n){if(void 0===n&&(n=!0),n&&!e.isValidPredicate(t))throw new Error("The predicate is not valid");return e.sortPredicateGroupsMap.get(t)},e.createFromExisting=function(t,n){if(n&&t)return n(e.createPredicateBuilder(t))},e.sortPredicateGroupsMap=new WeakMap,e}()},function(e,t,n){(function(e){var n,r,i,o;function s(e){return(s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}o=function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==s(e)&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=0)}([function(e,t,n){"use strict";function r(e){for(var n in e)t.hasOwnProperty(n)||(t[n]=e[n])}Object.defineProperty(t,"__esModule",{value:!0}),r(n(1)),r(n(2)),r(n(3)),r(n(4)),r(n(5)),r(n(6)),r(n(7)),r(n(8)),r(n(9)),r(n(10)),r(n(11)),r(n(12)),r(n(13))},function(e,t,n){e.exports={a:"Anchor__a___1_Iz8"}},function(e,t,n){e.exports={button:"Button__button___vS7Mv",signInButton:"Button__signInButton___3bUH-",googleSignInButton:"Button__googleSignInButton___1YiCu",signInButtonIcon:"Button__signInButtonIcon___ihN75",auth0SignInButton:"Button__auth0SignInButton___znnCj",facebookSignInButton:"Button__facebookSignInButton___34Txh",amazonSignInButton:"Button__amazonSignInButton___2EMtl",oAuthSignInButton:"Button__oAuthSignInButton___3UGOl",signInButtonContent:"Button__signInButtonContent___xqTXJ"}},function(e,t,n){e.exports={formContainer:"Form__formContainer___1GA3x",formSection:"Form__formSection___1PPvW",formField:"Form__formField___38Ikl",formRow:"Form__formRow___2mwRs"}},function(e,t,n){e.exports={hint:"Hint__hint___2XngB"}},function(e,t,n){e.exports={input:"Input__input___3e_bf",inputLabel:"Input__inputLabel___3VF0S",label:"Input__label___23sO8",radio:"Input__radio___2hllK"}},function(e,t,n){e.exports={navBar:"Nav__navBar___xtCFA",navRight:"Nav__navRight___1QG2J",nav:"Nav__nav___2Dx2Y",navItem:"Nav__navItem___1LtFQ"}},function(e,t,n){e.exports={photoPickerButton:"PhotoPicker__photoPickerButton___2XdVn",photoPlaceholder:"PhotoPicker__photoPlaceholder___2JXO4",photoPlaceholderIcon:"PhotoPicker__photoPlaceholderIcon___3Et71"}},function(e,t,n){e.exports={container:"Section__container___3YYTG",actionRow:"Section__actionRow___2LWSU",sectionHeader:"Section__sectionHeader___2djyg",sectionHeaderHint:"Section__sectionHeaderHint___3Wxdc",sectionBody:"Section__sectionBody___ihqqd",sectionHeaderContent:"Section__sectionHeaderContent___1UCqa",sectionFooter:"Section__sectionFooter___1T54C",sectionFooterPrimaryContent:"Section__sectionFooterPrimaryContent___2r9ZX",sectionFooterSecondaryContent:"Section__sectionFooterSecondaryContent___Nj41Q"}},function(e,t,n){e.exports={selectInput:"SelectInput__selectInput___3efO4"}},function(e,t,n){e.exports={strike:"Strike__strike___1XV1b",strikeContent:"Strike__strikeContent___10gLb"}},function(e,t,n){e.exports={toast:"Toast__toast___XXr3v",toastClose:"Toast__toastClose___18lU4"}},function(e,t,n){e.exports={totpQrcode:"Totp__totpQrcode___1crLx"}},function(e,t,n){e.exports={sumerianSceneContainer:"XR__sumerianSceneContainer___3nVMt",sumerianScene:"XR__sumerianScene___2Tt7-",loadingOverlay:"XR__loadingOverlay___IbqcI",loadingContainer:"XR__loadingContainer___2Itxb",loadingLogo:"XR__loadingLogo___Ub7xQ",loadingSceneName:"XR__loadingSceneName___3__ne",loadingBar:"XR__loadingBar___2vcke",loadingBarFill:"XR__loadingBarFill___3M-D9",sceneErrorText:"XR__sceneErrorText___2y0tp",sceneBar:"XR__sceneBar___2ShrP",sceneName:"XR__sceneName___1ApHr",sceneActions:"XR__sceneActions___7plGs",actionButton:"XR__actionButton___2poIM",tooltip:"XR__tooltip___UYyhn",actionIcon:"XR__actionIcon___2qnd2",autoShowTooltip:"XR__autoShowTooltip___V1QH7"}}])},"object"==s(t)&&"object"==s(e)?e.exports=o():(r=[],void 0===(i="function"==typeof(n=o)?n.apply(t,r):n)||(e.exports=i))}).call(this,n(57)(e))},function(e,t,n){"use strict";n.d(t,"a",(function(){return d}));var r=n(52),i=n(63),o=n(89),s=n(19),a=n(146),u=n(258),c=function(){return(c=Object.assign||function(e){for(var t,n=1,r=arguments.length;n2&&void 0!==arguments[2]?arguments[2]:i,r=void 0,u=Array.isArray(e),c=[e],f=-1,l=[],d=void 0,h=void 0,p=void 0,v=[],g=[],m=e;do{var b=++f===c.length,y=b&&0!==l.length;if(b){if(h=0===g.length?void 0:v[v.length-1],d=p,p=g.pop(),y){if(u)d=d.slice();else{var w={};for(var _ in d)d.hasOwnProperty(_)&&(w[_]=d[_]);d=w}for(var S=0,E=0;E0||m(0,"line in locationOffset is 1-indexed and must be positive"),this.locationOffset.column>0||m(0,"column in locationOffset is 1-indexed and must be positive")};function _(e,t,n){return new r.a("Syntax Error: ".concat(n),void 0,e,[t])}function S(e){for(var t=e.split(/\r\n|[\n\r]/g),n=null,r=1;r0&&M(t[0]);)t.shift();for(;t.length>0&&M(t[t.length-1]);)t.pop();return t.join("\n")}function E(e){for(var t=0;t",EOF:"",BANG:"!",DOLLAR:"$",AMP:"&",PAREN_L:"(",PAREN_R:")",SPREAD:"...",COLON:":",EQUALS:"=",AT:"@",BRACKET_L:"[",BRACKET_R:"]",BRACE_L:"{",PIPE:"|",BRACE_R:"}",NAME:"Name",INT:"Int",FLOAT:"Float",STRING:"String",BLOCK_STRING:"BlockString",COMMENT:"Comment"});function x(e){var t=e.value;return t?"".concat(e.kind,' "').concat(t,'"'):e.kind}var C=String.prototype.charCodeAt,T=String.prototype.slice;function P(e,t,n,r,i,o,s){this.kind=e,this.start=t,this.end=n,this.line=r,this.column=i,this.value=s,this.prev=o,this.next=null}function N(e){return isNaN(e)?O.EOF:e<127?JSON.stringify(String.fromCharCode(e)):'"\\u'.concat(("00"+e.toString(16).toUpperCase()).slice(-4),'"')}function R(e,t){var n=e.source,r=n.body,i=r.length,o=function(e,t,n){var r=e.length,i=t;for(;i=i)return new P(O.EOF,i,i,s,a,t);var u=C.call(r,o);switch(u){case 33:return new P(O.BANG,o,o+1,s,a,t);case 35:return function(e,t,n,r,i){var o,s=e.body,a=t;do{o=C.call(s,++a)}while(null!==o&&(o>31||9===o));return new P(O.COMMENT,t,a,n,r,i,T.call(s,t+1,a))}(n,o,s,a,t);case 36:return new P(O.DOLLAR,o,o+1,s,a,t);case 38:return new P(O.AMP,o,o+1,s,a,t);case 40:return new P(O.PAREN_L,o,o+1,s,a,t);case 41:return new P(O.PAREN_R,o,o+1,s,a,t);case 46:if(46===C.call(r,o+1)&&46===C.call(r,o+2))return new P(O.SPREAD,o,o+3,s,a,t);break;case 58:return new P(O.COLON,o,o+1,s,a,t);case 61:return new P(O.EQUALS,o,o+1,s,a,t);case 64:return new P(O.AT,o,o+1,s,a,t);case 91:return new P(O.BRACKET_L,o,o+1,s,a,t);case 93:return new P(O.BRACKET_R,o,o+1,s,a,t);case 123:return new P(O.BRACE_L,o,o+1,s,a,t);case 124:return new P(O.PIPE,o,o+1,s,a,t);case 125:return new P(O.BRACE_R,o,o+1,s,a,t);case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:case 95:case 97:case 98:case 99:case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:case 108:case 109:case 110:case 111:case 112:case 113:case 114:case 115:case 116:case 117:case 118:case 119:case 120:case 121:case 122:return function(e,t,n,r,i){var o=e.body,s=o.length,a=t+1,u=0;for(;a!==s&&null!==(u=C.call(o,a))&&(95===u||u>=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122);)++a;return new P(O.NAME,t,a,n,r,i,T.call(o,t,a))}(n,o,s,a,t);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return function(e,t,n,r,i,o){var s=e.body,a=n,u=t,c=!1;45===a&&(a=C.call(s,++u));if(48===a){if((a=C.call(s,++u))>=48&&a<=57)throw _(e,u,"Invalid number, unexpected digit after 0: ".concat(N(a),"."))}else u=L(e,u,a),a=C.call(s,u);46===a&&(c=!0,a=C.call(s,++u),u=L(e,u,a),a=C.call(s,u));69!==a&&101!==a||(c=!0,43!==(a=C.call(s,++u))&&45!==a||(a=C.call(s,++u)),u=L(e,u,a));return new P(c?O.FLOAT:O.INT,t,u,r,i,o,T.call(s,t,u))}(n,o,u,s,a,t);case 34:return 34===C.call(r,o+1)&&34===C.call(r,o+2)?function(e,t,n,r,i){var o=e.body,s=t+3,a=s,u=0,c="";for(;s=48&&o<=57){do{o=C.call(r,++i)}while(o>=48&&o<=57);return i}throw _(e,i,"Invalid number, expected digit but got: ".concat(N(o),"."))}function j(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:-1}P.prototype.toJSON=P.prototype.inspect=function(){return{kind:this.kind,value:this.value,line:this.line,column:this.column}};var D=Object.freeze({NAME:"Name",DOCUMENT:"Document",OPERATION_DEFINITION:"OperationDefinition",VARIABLE_DEFINITION:"VariableDefinition",SELECTION_SET:"SelectionSet",FIELD:"Field",ARGUMENT:"Argument",FRAGMENT_SPREAD:"FragmentSpread",INLINE_FRAGMENT:"InlineFragment",FRAGMENT_DEFINITION:"FragmentDefinition",VARIABLE:"Variable",INT:"IntValue",FLOAT:"FloatValue",STRING:"StringValue",BOOLEAN:"BooleanValue",NULL:"NullValue",ENUM:"EnumValue",LIST:"ListValue",OBJECT:"ObjectValue",OBJECT_FIELD:"ObjectField",DIRECTIVE:"Directive",NAMED_TYPE:"NamedType",LIST_TYPE:"ListType",NON_NULL_TYPE:"NonNullType",SCHEMA_DEFINITION:"SchemaDefinition",OPERATION_TYPE_DEFINITION:"OperationTypeDefinition",SCALAR_TYPE_DEFINITION:"ScalarTypeDefinition",OBJECT_TYPE_DEFINITION:"ObjectTypeDefinition",FIELD_DEFINITION:"FieldDefinition",INPUT_VALUE_DEFINITION:"InputValueDefinition",INTERFACE_TYPE_DEFINITION:"InterfaceTypeDefinition",UNION_TYPE_DEFINITION:"UnionTypeDefinition",ENUM_TYPE_DEFINITION:"EnumTypeDefinition",ENUM_VALUE_DEFINITION:"EnumValueDefinition",INPUT_OBJECT_TYPE_DEFINITION:"InputObjectTypeDefinition",DIRECTIVE_DEFINITION:"DirectiveDefinition",SCHEMA_EXTENSION:"SchemaExtension",SCALAR_TYPE_EXTENSION:"ScalarTypeExtension",OBJECT_TYPE_EXTENSION:"ObjectTypeExtension",INTERFACE_TYPE_EXTENSION:"InterfaceTypeExtension",UNION_TYPE_EXTENSION:"UnionTypeExtension",ENUM_TYPE_EXTENSION:"EnumTypeExtension",INPUT_OBJECT_TYPE_EXTENSION:"InputObjectTypeExtension"}),U=Object.freeze({QUERY:"QUERY",MUTATION:"MUTATION",SUBSCRIPTION:"SUBSCRIPTION",FIELD:"FIELD",FRAGMENT_DEFINITION:"FRAGMENT_DEFINITION",FRAGMENT_SPREAD:"FRAGMENT_SPREAD",INLINE_FRAGMENT:"INLINE_FRAGMENT",VARIABLE_DEFINITION:"VARIABLE_DEFINITION",SCHEMA:"SCHEMA",SCALAR:"SCALAR",OBJECT:"OBJECT",FIELD_DEFINITION:"FIELD_DEFINITION",ARGUMENT_DEFINITION:"ARGUMENT_DEFINITION",INTERFACE:"INTERFACE",UNION:"UNION",ENUM:"ENUM",ENUM_VALUE:"ENUM_VALUE",INPUT_OBJECT:"INPUT_OBJECT",INPUT_FIELD_DEFINITION:"INPUT_FIELD_DEFINITION"});function B(e,t){var n="string"==typeof e?new w(e):e;if(!(n instanceof w))throw new TypeError("Must provide Source. Received: ".concat(g(n)));return function(e){var t=e.token;return{kind:D.DOCUMENT,definitions:Te(e,O.SOF,z,O.EOF),loc:Ee(e,t)}}(A(n,t||{}))}function F(e){var t=ke(e,O.NAME);return{kind:D.NAME,value:t.value,loc:Ee(e,t)}}function z(e){if(Ae(e,O.NAME))switch(e.token.value){case"query":case"mutation":case"subscription":case"fragment":return q(e);case"schema":case"scalar":case"type":case"interface":case"union":case"enum":case"input":case"directive":return ce(e);case"extend":return function(e){var t=e.lookahead();if(t.kind===O.NAME)switch(t.value){case"schema":return function(e){var t=e.token;Oe(e,"extend"),Oe(e,"schema");var n=oe(e,!0),r=Ae(e,O.BRACE_L)?Te(e,O.BRACE_L,de,O.BRACE_R):[];if(0===n.length&&0===r.length)throw xe(e);return{kind:D.SCHEMA_EXTENSION,directives:n,operationTypes:r,loc:Ee(e,t)}}(e);case"scalar":return function(e){var t=e.token;Oe(e,"extend"),Oe(e,"scalar");var n=F(e),r=oe(e,!0);if(0===r.length)throw xe(e);return{kind:D.SCALAR_TYPE_EXTENSION,name:n,directives:r,loc:Ee(e,t)}}(e);case"type":return function(e){var t=e.token;Oe(e,"extend"),Oe(e,"type");var n=F(e),r=he(e),i=oe(e,!0),o=pe(e);if(0===r.length&&0===i.length&&0===o.length)throw xe(e);return{kind:D.OBJECT_TYPE_EXTENSION,name:n,interfaces:r,directives:i,fields:o,loc:Ee(e,t)}}(e);case"interface":return function(e){var t=e.token;Oe(e,"extend"),Oe(e,"interface");var n=F(e),r=oe(e,!0),i=pe(e);if(0===r.length&&0===i.length)throw xe(e);return{kind:D.INTERFACE_TYPE_EXTENSION,name:n,directives:r,fields:i,loc:Ee(e,t)}}(e);case"union":return function(e){var t=e.token;Oe(e,"extend"),Oe(e,"union");var n=F(e),r=oe(e,!0),i=be(e);if(0===r.length&&0===i.length)throw xe(e);return{kind:D.UNION_TYPE_EXTENSION,name:n,directives:r,types:i,loc:Ee(e,t)}}(e);case"enum":return function(e){var t=e.token;Oe(e,"extend"),Oe(e,"enum");var n=F(e),r=oe(e,!0),i=ye(e);if(0===r.length&&0===i.length)throw xe(e);return{kind:D.ENUM_TYPE_EXTENSION,name:n,directives:r,values:i,loc:Ee(e,t)}}(e);case"input":return function(e){var t=e.token;Oe(e,"extend"),Oe(e,"input");var n=F(e),r=oe(e,!0),i=_e(e);if(0===r.length&&0===i.length)throw xe(e);return{kind:D.INPUT_OBJECT_TYPE_EXTENSION,name:n,directives:r,fields:i,loc:Ee(e,t)}}(e)}throw xe(e,t)}(e)}else{if(Ae(e,O.BRACE_L))return q(e);if(fe(e))return ce(e)}throw xe(e)}function q(e){if(Ae(e,O.NAME))switch(e.token.value){case"query":case"mutation":case"subscription":return K(e);case"fragment":return function(e){var t=e.token;if(Oe(e,"fragment"),e.options.experimentalFragmentVariables)return{kind:D.FRAGMENT_DEFINITION,name:Q(e),variableDefinitions:V(e),typeCondition:(Oe(e,"on"),ue(e)),directives:oe(e,!1),selectionSet:$(e),loc:Ee(e,t)};return{kind:D.FRAGMENT_DEFINITION,name:Q(e),typeCondition:(Oe(e,"on"),ue(e)),directives:oe(e,!1),selectionSet:$(e),loc:Ee(e,t)}}(e)}else if(Ae(e,O.BRACE_L))return K(e);throw xe(e)}function K(e){var t=e.token;if(Ae(e,O.BRACE_L))return{kind:D.OPERATION_DEFINITION,operation:"query",name:void 0,variableDefinitions:[],directives:[],selectionSet:$(e),loc:Ee(e,t)};var n,r=H(e);return Ae(e,O.NAME)&&(n=F(e)),{kind:D.OPERATION_DEFINITION,operation:r,name:n,variableDefinitions:V(e),directives:oe(e,!1),selectionSet:$(e),loc:Ee(e,t)}}function H(e){var t=ke(e,O.NAME);switch(t.value){case"query":return"query";case"mutation":return"mutation";case"subscription":return"subscription"}throw xe(e,t)}function V(e){return Ae(e,O.PAREN_L)?Te(e,O.PAREN_L,G,O.PAREN_R):[]}function G(e){var t=e.token;return e.options.experimentalVariableDefinitionDirectives?{kind:D.VARIABLE_DEFINITION,variable:W(e),type:(ke(e,O.COLON),ae(e)),defaultValue:Ie(e,O.EQUALS)?ee(e,!0):void 0,directives:oe(e,!0),loc:Ee(e,t)}:{kind:D.VARIABLE_DEFINITION,variable:W(e),type:(ke(e,O.COLON),ae(e)),defaultValue:Ie(e,O.EQUALS)?ee(e,!0):void 0,loc:Ee(e,t)}}function W(e){var t=e.token;return ke(e,O.DOLLAR),{kind:D.VARIABLE,name:F(e),loc:Ee(e,t)}}function $(e){var t=e.token;return{kind:D.SELECTION_SET,selections:Te(e,O.BRACE_L,Y,O.BRACE_R),loc:Ee(e,t)}}function Y(e){return Ae(e,O.SPREAD)?function(e){var t,n=e.token;if(ke(e,O.SPREAD),Ae(e,O.NAME)&&"on"!==e.token.value)return{kind:D.FRAGMENT_SPREAD,name:Q(e),directives:oe(e,!1),loc:Ee(e,n)};"on"===e.token.value&&(e.advance(),t=ue(e));return{kind:D.INLINE_FRAGMENT,typeCondition:t,directives:oe(e,!1),selectionSet:$(e),loc:Ee(e,n)}}(e):function(e){var t,n,r=e.token,i=F(e);Ie(e,O.COLON)?(t=i,n=F(e)):n=i;return{kind:D.FIELD,alias:t,name:n,arguments:J(e,!1),directives:oe(e,!1),selectionSet:Ae(e,O.BRACE_L)?$(e):void 0,loc:Ee(e,r)}}(e)}function J(e,t){var n=t?X:Z;return Ae(e,O.PAREN_L)?Te(e,O.PAREN_L,n,O.PAREN_R):[]}function Z(e){var t=e.token;return{kind:D.ARGUMENT,name:F(e),value:(ke(e,O.COLON),ee(e,!1)),loc:Ee(e,t)}}function X(e){var t=e.token;return{kind:D.ARGUMENT,name:F(e),value:(ke(e,O.COLON),ne(e)),loc:Ee(e,t)}}function Q(e){if("on"===e.token.value)throw xe(e);return F(e)}function ee(e,t){var n=e.token;switch(n.kind){case O.BRACKET_L:return function(e,t){var n=e.token,r=t?ne:re;return{kind:D.LIST,values:Ce(e,O.BRACKET_L,r,O.BRACKET_R),loc:Ee(e,n)}}(e,t);case O.BRACE_L:return function(e,t){var n=e.token;ke(e,O.BRACE_L);var r=[];for(;!Ie(e,O.BRACE_R);)r.push(ie(e,t));return{kind:D.OBJECT,fields:r,loc:Ee(e,n)}}(e,t);case O.INT:return e.advance(),{kind:D.INT,value:n.value,loc:Ee(e,n)};case O.FLOAT:return e.advance(),{kind:D.FLOAT,value:n.value,loc:Ee(e,n)};case O.STRING:case O.BLOCK_STRING:return te(e);case O.NAME:return"true"===n.value||"false"===n.value?(e.advance(),{kind:D.BOOLEAN,value:"true"===n.value,loc:Ee(e,n)}):"null"===n.value?(e.advance(),{kind:D.NULL,loc:Ee(e,n)}):(e.advance(),{kind:D.ENUM,value:n.value,loc:Ee(e,n)});case O.DOLLAR:if(!t)return W(e)}throw xe(e)}function te(e){var t=e.token;return e.advance(),{kind:D.STRING,value:t.value,block:t.kind===O.BLOCK_STRING,loc:Ee(e,t)}}function ne(e){return ee(e,!0)}function re(e){return ee(e,!1)}function ie(e,t){var n=e.token;return{kind:D.OBJECT_FIELD,name:F(e),value:(ke(e,O.COLON),ee(e,t)),loc:Ee(e,n)}}function oe(e,t){for(var n=[];Ae(e,O.AT);)n.push(se(e,t));return n}function se(e,t){var n=e.token;return ke(e,O.AT),{kind:D.DIRECTIVE,name:F(e),arguments:J(e,t),loc:Ee(e,n)}}function ae(e){var t,n=e.token;return Ie(e,O.BRACKET_L)?(t=ae(e),ke(e,O.BRACKET_R),t={kind:D.LIST_TYPE,type:t,loc:Ee(e,n)}):t=ue(e),Ie(e,O.BANG)?{kind:D.NON_NULL_TYPE,type:t,loc:Ee(e,n)}:t}function ue(e){var t=e.token;return{kind:D.NAMED_TYPE,name:F(e),loc:Ee(e,t)}}function ce(e){var t=fe(e)?e.lookahead():e.token;if(t.kind===O.NAME)switch(t.value){case"schema":return function(e){var t=e.token;Oe(e,"schema");var n=oe(e,!0),r=Te(e,O.BRACE_L,de,O.BRACE_R);return{kind:D.SCHEMA_DEFINITION,directives:n,operationTypes:r,loc:Ee(e,t)}}(e);case"scalar":return function(e){var t=e.token,n=le(e);Oe(e,"scalar");var r=F(e),i=oe(e,!0);return{kind:D.SCALAR_TYPE_DEFINITION,description:n,name:r,directives:i,loc:Ee(e,t)}}(e);case"type":return function(e){var t=e.token,n=le(e);Oe(e,"type");var r=F(e),i=he(e),o=oe(e,!0),s=pe(e);return{kind:D.OBJECT_TYPE_DEFINITION,description:n,name:r,interfaces:i,directives:o,fields:s,loc:Ee(e,t)}}(e);case"interface":return function(e){var t=e.token,n=le(e);Oe(e,"interface");var r=F(e),i=oe(e,!0),o=pe(e);return{kind:D.INTERFACE_TYPE_DEFINITION,description:n,name:r,directives:i,fields:o,loc:Ee(e,t)}}(e);case"union":return function(e){var t=e.token,n=le(e);Oe(e,"union");var r=F(e),i=oe(e,!0),o=be(e);return{kind:D.UNION_TYPE_DEFINITION,description:n,name:r,directives:i,types:o,loc:Ee(e,t)}}(e);case"enum":return function(e){var t=e.token,n=le(e);Oe(e,"enum");var r=F(e),i=oe(e,!0),o=ye(e);return{kind:D.ENUM_TYPE_DEFINITION,description:n,name:r,directives:i,values:o,loc:Ee(e,t)}}(e);case"input":return function(e){var t=e.token,n=le(e);Oe(e,"input");var r=F(e),i=oe(e,!0),o=_e(e);return{kind:D.INPUT_OBJECT_TYPE_DEFINITION,description:n,name:r,directives:i,fields:o,loc:Ee(e,t)}}(e);case"directive":return function(e){var t=e.token,n=le(e);Oe(e,"directive"),ke(e,O.AT);var r=F(e),i=ge(e);Oe(e,"on");var o=function(e){Ie(e,O.PIPE);var t=[];do{t.push(Se(e))}while(Ie(e,O.PIPE));return t}(e);return{kind:D.DIRECTIVE_DEFINITION,description:n,name:r,arguments:i,locations:o,loc:Ee(e,t)}}(e)}throw xe(e,t)}function fe(e){return Ae(e,O.STRING)||Ae(e,O.BLOCK_STRING)}function le(e){if(fe(e))return te(e)}function de(e){var t=e.token,n=H(e);ke(e,O.COLON);var r=ue(e);return{kind:D.OPERATION_TYPE_DEFINITION,operation:n,type:r,loc:Ee(e,t)}}function he(e){var t=[];if("implements"===e.token.value){e.advance(),Ie(e,O.AMP);do{t.push(ue(e))}while(Ie(e,O.AMP)||e.options.allowLegacySDLImplementsInterfaces&&Ae(e,O.NAME))}return t}function pe(e){return e.options.allowLegacySDLEmptyFields&&Ae(e,O.BRACE_L)&&e.lookahead().kind===O.BRACE_R?(e.advance(),e.advance(),[]):Ae(e,O.BRACE_L)?Te(e,O.BRACE_L,ve,O.BRACE_R):[]}function ve(e){var t=e.token,n=le(e),r=F(e),i=ge(e);ke(e,O.COLON);var o=ae(e),s=oe(e,!0);return{kind:D.FIELD_DEFINITION,description:n,name:r,arguments:i,type:o,directives:s,loc:Ee(e,t)}}function ge(e){return Ae(e,O.PAREN_L)?Te(e,O.PAREN_L,me,O.PAREN_R):[]}function me(e){var t=e.token,n=le(e),r=F(e);ke(e,O.COLON);var i,o=ae(e);Ie(e,O.EQUALS)&&(i=ne(e));var s=oe(e,!0);return{kind:D.INPUT_VALUE_DEFINITION,description:n,name:r,type:o,defaultValue:i,directives:s,loc:Ee(e,t)}}function be(e){var t=[];if(Ie(e,O.EQUALS)){Ie(e,O.PIPE);do{t.push(ue(e))}while(Ie(e,O.PIPE))}return t}function ye(e){return Ae(e,O.BRACE_L)?Te(e,O.BRACE_L,we,O.BRACE_R):[]}function we(e){var t=e.token,n=le(e),r=F(e),i=oe(e,!0);return{kind:D.ENUM_VALUE_DEFINITION,description:n,name:r,directives:i,loc:Ee(e,t)}}function _e(e){return Ae(e,O.BRACE_L)?Te(e,O.BRACE_L,me,O.BRACE_R):[]}function Se(e){var t=e.token,n=F(e);if(U.hasOwnProperty(n.value))return n;throw xe(e,t)}function Ee(e,t){if(!e.options.noLocation)return new Me(t,e.lastToken,e.source)}function Me(e,t,n){this.start=e.start,this.end=t.end,this.startToken=e,this.endToken=t,this.source=n}function Ae(e,t){return e.token.kind===t}function Ie(e,t){var n=e.token.kind===t;return n&&e.advance(),n}function ke(e,t){var n=e.token;if(n.kind===t)return e.advance(),n;throw _(e.source,n.start,"Expected ".concat(t,", found ").concat(x(n)))}function Oe(e,t){var n=e.token;if(n.kind===O.NAME&&n.value===t)return e.advance(),n;throw _(e.source,n.start,'Expected "'.concat(t,'", found ').concat(x(n)))}function xe(e,t){var n=t||e.token;return _(e.source,n.start,"Unexpected ".concat(x(n)))}function Ce(e,t,n,r){ke(e,t);for(var i=[];!Ie(e,r);)i.push(n(e));return i}function Te(e,t,n,r){ke(e,t);for(var i=[n(e)];!Ie(e,r);)i.push(n(e));return i}Me.prototype.toJSON=Me.prototype.inspect=function(){return{start:this.start,end:this.end}};var Pe=n(44),Ne=n(89),Re=n(5),Le=n(103),je=n(19),De=n(34),Ue=n(42),Be=n(26),Fe=n(254),ze=function(){return(ze=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},Ge=new Pe.a("GraphQLAPI"),We=function(e,t){return void 0===t&&(t={}),{query:e,variables:t}},$e=function(){function e(e){this._api=null,this.Auth=Ue.a,this.Cache=Be.a,this.Credentials=Ne.a,this._options=e,Ge.debug("API Options",this._options)}return e.prototype.getModuleName=function(){return"GraphQLAPI"},e.prototype.configure=function(e){var t=e||{},n=t.API,r=void 0===n?{}:n,i=He(t,["API"]),o=ze(ze({},i),r);return Ge.debug("configure GraphQL API",{opt:o}),o.aws_project_region&&(o=Object.assign({},o,{region:o.aws_project_region,header:{}})),void 0!==o.graphql_headers&&"function"!=typeof o.graphql_headers&&(Ge.warn("graphql_headers should be a function"),o.graphql_headers=void 0),this._options=Object.assign({},this._options,o),this.createInstance(),this._options},e.prototype.createInstance=function(){return Ge.debug("create Rest instance"),this._options?(this._api=new Fe.a(this._options),this._api.Credentials=this.Credentials,!0):Promise.reject("API not configured")},e.prototype._headerBasedAuth=function(e){return qe(this,void 0,void 0,(function(){var t,n,r,i,o,s,a,u;return Ke(this,(function(c){switch(c.label){case 0:switch(t=this._options,n=t.aws_appsync_authenticationType,r=t.aws_appsync_apiKey,i={},e||n||"AWS_IAM"){case"API_KEY":return[3,1];case"AWS_IAM":return[3,2];case"OPENID_CONNECT":return[3,4];case"AMAZON_COGNITO_USER_POOLS":return[3,9]}return[3,11];case 1:if(!r)throw new Error("No api-key configured");return i={Authorization:null,"X-Api-Key":r},[3,12];case 2:return[4,this._ensureCredentials()];case 3:if(!c.sent())throw new Error("No credentials");return[3,12];case 4:return o=void 0,[4,Be.a.getItem("federatedInfo")];case 5:return(s=c.sent())?(o=s.token,[3,8]):[3,6];case 6:return[4,Ue.a.currentAuthenticatedUser()];case 7:(a=c.sent())&&(o=a.token),c.label=8;case 8:if(!o)throw new Error("No federated jwt");return i={Authorization:o},[3,12];case 9:return[4,this.Auth.currentSession()];case 10:return u=c.sent(),i={Authorization:u.getAccessToken().getJwtToken()},[3,12];case 11:return i={Authorization:null},[3,12];case 12:return[2,i]}}))}))},e.prototype.getGraphqlOperationType=function(e){var t=B(e);return Ve(t.definitions,1)[0].operation},e.prototype.graphql=function(e,t){var n=e.query,r=e.variables,i=void 0===r?{}:r,o=e.authMode,s=B("string"==typeof n?n:u(n)),a=Ve(s.definitions.filter((function(e){return"OperationDefinition"===e.kind})),1)[0],c=(void 0===a?{}:a).operation;switch(c){case"query":case"mutation":var f=this._api.getCancellableToken(),l={cancellableToken:f},d=this._graphql({query:s,variables:i,authMode:o},t,l);return this._api.updateRequestToBeCancellable(d,f),d;case"subscription":return this._graphqlSubscribe({query:s,variables:i,authMode:o},t)}throw new Error("invalid operation type: "+c)},e.prototype._graphql=function(e,t,n){var i=e.query,o=e.variables,s=e.authMode;return void 0===t&&(t={}),void 0===n&&(n={}),qe(this,void 0,void 0,(function(){var e,a,c,f,l,d,h,p,v,g,m,b,y,w,_,S,E,M,A,I,k;return Ke(this,(function(O){switch(O.label){case 0:return this._api?[3,2]:[4,this.createInstance()];case 1:O.sent(),O.label=2;case 2:return e=this._options,a=e.aws_appsync_region,c=e.aws_appsync_graphqlEndpoint,f=e.graphql_headers,l=void 0===f?function(){return{}}:f,d=e.graphql_endpoint,h=e.graphql_endpoint_iam_region,v=[{}],(g=!d)?[4,this._headerBasedAuth(s)]:[3,4];case 3:g=O.sent(),O.label=4;case 4:return m=[ze.apply(void 0,v.concat([g]))],(b=d)?h?[4,this._headerBasedAuth(s)]:[3,6]:[3,8];case 5:return y=O.sent(),[3,7];case 6:y={Authorization:null},O.label=7;case 7:b=y,O.label=8;case 8:return w=[ze.apply(void 0,m.concat([b]))],[4,l({query:i,variables:o})];case 9:if(p=ze.apply(void 0,[ze.apply(void 0,[ze.apply(void 0,w.concat([O.sent()])),t]),!d&&(k={},k["x-amz-user-agent"]=Re.a.userAgent,k)]),_={query:u(i),variables:o},S=Object.assign({headers:p,body:_,signerServiceInfo:{service:d?"execute-api":"appsync",region:d?h:a}},n),!(E=d||c))throw{data:{},errors:[new r.a("No graphql endpoint provided.")]};O.label=10;case 10:return O.trys.push([10,12,,13]),[4,this._api.post(E,S)];case 11:return M=O.sent(),[3,13];case 12:if(A=O.sent(),this._api.isCancel(A))throw A;return M={data:{},errors:[new r.a(A.message)]},[3,13];case 13:if((I=M.errors)&&I.length)throw M;return[2,M]}}))}))},e.prototype.isCancel=function(e){return this._api.isCancel(e)},e.prototype.cancel=function(e,t){return this._api.cancel(e,t)},e.prototype._graphqlSubscribe=function(e,t){var n=e.query,r=e.variables,i=e.authMode;void 0===t&&(t={});var o=this._options,s=o.aws_appsync_region,a=o.aws_appsync_graphqlEndpoint,c=o.aws_appsync_authenticationType,f=o.aws_appsync_apiKey,l=o.graphql_headers,d=void 0===l?function(){return{}}:l,h=i||c||"AWS_IAM";if(De.b&&"function"==typeof De.b.subscribe)return De.b.subscribe("",{provider:Le.b,appSyncGraphqlEndpoint:a,authenticationType:h,apiKey:f,query:u(n),region:s,variables:r,graphql_headers:d,additionalHeaders:t});throw Ge.debug("No pubsub module applied for subscription"),new Error("No pubsub module applied for subscription")},e.prototype._ensureCredentials=function(){var e=this;return this.Credentials.get().then((function(t){if(!t)return!1;var n=e.Credentials.shear(t);return Ge.debug("set credentials for api",n),!0})).catch((function(e){return Ge.warn("ensure credentials error",e),!1}))},e}(),Ye=new $e(null);je.a.register(Ye)},function(e,t,n){"use strict";n.r(t),n.d(t,"fromUtf8",(function(){return r})),n.d(t,"toUtf8",(function(){return i}));var r=function(e){return"function"==typeof TextEncoder?function(e){return(new TextEncoder).encode(e)}(e):function(e){for(var t=[],n=0,r=e.length;n>6|192,63&i|128);else if(n+1>18|240,o>>12&63|128,o>>6&63|128,63&o|128)}else t.push(i>>12|224,i>>6&63|128,63&i|128)}return Uint8Array.from(t)}(e)},i=function(e){return"function"==typeof TextDecoder?function(e){return new TextDecoder("utf-8").decode(e)}(e):function(e){for(var t="",n=0,r=e.length;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0){var s=n.substring(0,i),a=n.substring(i+r.length);n=s+t[o]+a}return n},S=[0,6,77,81,73,115,100,112,3],E=[0,4,77,81,84,84,4],M=function(e,t){for(var n in this.type=e,t)t.hasOwnProperty(n)&&(this[n]=t[n])};function A(e,t){var n,r=t,f=e[t],d=f>>4,p=f&=15;t+=1;var v=0,g=1;do{if(t==e.length)return[null,r];v+=(127&(n=e[t++]))*g,g*=128}while(0!=(128&n));var m=t+v;if(m>e.length)return[null,r];var b=new M(d);switch(d){case i:1&e[t++]&&(b.sessionPresent=!0),b.returnCode=e[t++];break;case o:var y=p>>1&3,w=O(e,t),_=T(e,t+=2,w);t+=w,y>0&&(b.messageIdentifier=O(e,t),t+=2);var S=new L(e.subarray(t,m));1==(1&p)&&(S.retained=!0),8==(8&p)&&(S.duplicate=!0),S.qos=y,S.destinationName=_,b.payloadMessage=S;break;case s:case a:case u:case c:case h:b.messageIdentifier=O(e,t);break;case l:b.messageIdentifier=O(e,t),t+=2,b.returnCode=e.subarray(t,m)}return[b,m]}function I(e,t,n){return t[n++]=e>>8,t[n++]=e%256,n}function k(e,t,n,r){return C(e,n,r=I(t,n,r)),r+t}function O(e,t){return 256*e[t]+e[t+1]}function x(e){for(var t=0,n=0;n2047?(55296<=r&&r<=56319&&(n++,t++),t+=3):r>127?t+=2:t++}return t}function C(e,t,n){for(var r=n,i=0;i>6&31|192,t[r++]=63&o|128):o<=65535?(t[r++]=o>>12&15|224,t[r++]=o>>6&63|128,t[r++]=63&o|128):(t[r++]=o>>18&7|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=63&o|128)}return t}function T(e,t,n){for(var r,i="",o=t;o65535&&(r-=65536,i+=String.fromCharCode(55296+(r>>10)),r=56320+(1023&r)),i+=String.fromCharCode(r)}return i}M.prototype.encode=function(){var e,t=(15&this.type)<<4,n=0,i=[],s=0;switch(void 0!==this.messageIdentifier&&(n+=2),this.type){case r:switch(this.mqttVersion){case 3:n+=S.length+3;break;case 4:n+=E.length+3}n+=x(this.clientId)+2,void 0!==this.willMessage&&(n+=x(this.willMessage.destinationName)+2,(e=this.willMessage.payloadBytes)instanceof Uint8Array||(e=new Uint8Array(c)),n+=e.byteLength+2),void 0!==this.userName&&(n+=x(this.userName)+2),void 0!==this.password&&(n+=x(this.password)+2);break;case f:t|=2;for(var a=0;a>=7)>0&&(r|=128),t[n++]=r}while(e>0&&n<4);return t}(n),h=l.length+1,p=new ArrayBuffer(n+h),v=new Uint8Array(p);if(v[0]=t,v.set(l,1),this.type==o)h=k(this.payloadMessage.destinationName,s,v,h);else if(this.type==r){switch(this.mqttVersion){case 3:v.set(S,h),h+=S.length;break;case 4:v.set(E,h),h+=E.length}var g=0;this.cleanSession&&(g=2),void 0!==this.willMessage&&(g|=4,g|=this.willMessage.qos<<3,this.willMessage.retained&&(g|=32)),void 0!==this.userName&&(g|=128),void 0!==this.password&&(g|=64),v[h++]=g,h=I(this.keepAliveInterval,v,h)}switch(void 0!==this.messageIdentifier&&(h=I(this.messageIdentifier,v,h)),this.type){case r:h=k(this.clientId,x(this.clientId),v,h),void 0!==this.willMessage&&(h=k(this.willMessage.destinationName,x(this.willMessage.destinationName),v,h),h=I(e.byteLength,v,h),v.set(e,h),h+=e.byteLength),void 0!==this.userName&&(h=k(this.userName,x(this.userName),v,h)),void 0!==this.password&&(h=k(this.password,x(this.password),v,h));break;case o:v.set(c,h);break;case f:for(a=0;a0&&(this.timeout=setTimeout(r(this),this._keepAliveInterval))},this.cancel=function(){clearTimeout(this.timeout)}},N=function(e,t,n,r){t||(t=30),this.timeout=setTimeout(function(e,t,n){return function(){return e.apply(t,n)}}(n,e,r),1e3*t),this.cancel=function(){clearTimeout(this.timeout)}},R=function(t,r,i,o,s){if(!("WebSocket"in e)||null===e.WebSocket)throw new Error(_(y.UNSUPPORTED,["WebSocket"]));if(!("ArrayBuffer"in e)||null===e.ArrayBuffer)throw new Error(_(y.UNSUPPORTED,["ArrayBuffer"]));for(var a in this._trace("Paho.Client",t,r,i,o,s),this.host=r,this.port=i,this.path=o,this.uri=t,this.clientId=s,this._wsuri=null,this._localKey=r+":"+i+("/mqtt"!=o?":"+o:"")+":"+s+":",this._msg_queue=[],this._buffered_msg_queue=[],this._sentMessages={},this._receivedMessages={},this._notify_msg_sent={},this._message_identifier=1,this._sequence=0,n)0!==a.indexOf("Sent:"+this._localKey)&&0!==a.indexOf("Received:"+this._localKey)||this.restore(a)};R.prototype.host=null,R.prototype.port=null,R.prototype.path=null,R.prototype.uri=null,R.prototype.clientId=null,R.prototype.socket=null,R.prototype.connected=!1,R.prototype.maxMessageIdentifier=65536,R.prototype.connectOptions=null,R.prototype.hostIndex=null,R.prototype.onConnected=null,R.prototype.onConnectionLost=null,R.prototype.onMessageDelivered=null,R.prototype.onMessageArrived=null,R.prototype.traceFunction=null,R.prototype._msg_queue=null,R.prototype._buffered_msg_queue=null,R.prototype._connectTimeout=null,R.prototype.sendPinger=null,R.prototype.receivePinger=null,R.prototype._reconnectInterval=1,R.prototype._reconnecting=!1,R.prototype._reconnectTimeout=null,R.prototype.disconnectedPublishing=!1,R.prototype.disconnectedBufferSize=5e3,R.prototype.receiveBuffer=null,R.prototype._traceBuffer=null,R.prototype._MAX_TRACE_ENTRIES=100,R.prototype.connect=function(e){var t=this._traceMask(e,"password");if(this._trace("Client.connect",t,this.socket,this.connected),this.connected)throw new Error(_(y.INVALID_STATE,["already connected"]));if(this.socket)throw new Error(_(y.INVALID_STATE,["already connected"]));this._reconnecting&&(this._reconnectTimeout.cancel(),this._reconnectTimeout=null,this._reconnecting=!1),this.connectOptions=e,this._reconnectInterval=1,this._reconnecting=!1,e.uris?(this.hostIndex=0,this._doConnect(e.uris[0])):this._doConnect(this.uri)},R.prototype.subscribe=function(e,t){if(this._trace("Client.subscribe",e,t),!this.connected)throw new Error(_(y.INVALID_STATE,["not connected"]));var n=new M(f);n.topics=e.constructor===Array?e:[e],void 0===t.qos&&(t.qos=0),n.requestedQos=[];for(var r=0;r0?this._requires_ack(t):this.onMessageDelivered&&(this._notify_msg_sent[t]=this.onMessageDelivered(t.payloadMessage)),this._schedule_message(t);else{if(!this._reconnecting||!this.disconnectedPublishing)throw new Error(_(y.INVALID_STATE,["not connected"]));if(Object.keys(this._sentMessages).length+this._buffered_msg_queue.length>this.disconnectedBufferSize)throw new Error(_(y.BUFFER_FULL,[this.disconnectedBufferSize]));e.qos>0?this._requires_ack(t):(t.sequence=++this._sequence,this._buffered_msg_queue.unshift(t))}},R.prototype.disconnect=function(){if(this._trace("Client.disconnect"),this._reconnecting&&(this._reconnectTimeout.cancel(),this._reconnectTimeout=null,this._reconnecting=!1),!this.socket)throw new Error(_(y.INVALID_STATE,["not connecting or connected"]));var e=new M(g);this._notify_msg_sent[e]=b(this._disconnected,this),this._schedule_message(e)},R.prototype.getTraceLog=function(){if(null!==this._traceBuffer){for(var e in this._trace("Client.getTraceLog",new Date),this._trace("Client.getTraceLog in flight messages",this._sentMessages.length),this._sentMessages)this._trace("_sentMessages ",e,this._sentMessages[e]);for(var e in this._receivedMessages)this._trace("_receivedMessages ",e,this._receivedMessages[e]);return this._traceBuffer}},R.prototype.startTrace=function(){null===this._traceBuffer&&(this._traceBuffer=[]),this._trace("Client.startTrace",new Date,"@VERSION@-@BUILDLEVEL@")},R.prototype.stopTrace=function(){delete this._traceBuffer},R.prototype._doConnect=function(e){if(this.connectOptions.useSSL){var t=e.split(":");t[0]="wss",e=t.join(":")}this._wsuri=e,this.connected=!1,this.connectOptions.mqttVersion<4?this.socket=new WebSocket(e,["mqttv3.1"]):this.socket=new WebSocket(e,["mqtt"]),this.socket.binaryType="arraybuffer",this.socket.onopen=b(this._on_socket_open,this),this.socket.onmessage=b(this._on_socket_message,this),this.socket.onerror=b(this._on_socket_error,this),this.socket.onclose=b(this._on_socket_close,this),this.sendPinger=new P(this,this.connectOptions.keepAliveInterval),this.receivePinger=new P(this,this.connectOptions.keepAliveInterval),this._connectTimeout&&(this._connectTimeout.cancel(),this._connectTimeout=null),this._connectTimeout=new N(this,this.connectOptions.timeout,this._disconnected,[y.CONNECT_TIMEOUT.code,_(y.CONNECT_TIMEOUT)])},R.prototype._schedule_message=function(e){this._msg_queue.unshift(e),this.connected&&this._process_queue()},R.prototype.store=function(e,t){var r={type:t.type,messageIdentifier:t.messageIdentifier,version:1};switch(t.type){case o:t.pubRecReceived&&(r.pubRecReceived=!0),r.payloadMessage={};for(var i="",s=t.payloadMessage.payloadBytes,a=0;a=2;){var f=parseInt(s.substring(0,2),16);s=s.substring(2,s.length),u[c++]=f}var l=new L(u);l.qos=r.payloadMessage.qos,l.destinationName=r.payloadMessage.destinationName,r.payloadMessage.duplicate&&(l.duplicate=!0),r.payloadMessage.retained&&(l.retained=!0),i.payloadMessage=l;break;default:throw Error(_(y.INVALID_STORED_DATA,[e,t]))}0===e.indexOf("Sent:"+this._localKey)?(i.payloadMessage.duplicate=!0,this._sentMessages[i.messageIdentifier]=i):0===e.indexOf("Received:"+this._localKey)&&(this._receivedMessages[i.messageIdentifier]=i)},R.prototype._process_queue=function(){for(var e=null;e=this._msg_queue.pop();)this._socket_send(e),this._notify_msg_sent[e]&&(this._notify_msg_sent[e](),delete this._notify_msg_sent[e])},R.prototype._requires_ack=function(e){var t=Object.keys(this._sentMessages).length;if(t>this.maxMessageIdentifier)throw Error("Too many messages:"+t);for(;void 0!==this._sentMessages[this._message_identifier];)this._message_identifier++;e.messageIdentifier=this._message_identifier,this._sentMessages[e.messageIdentifier]=e,e.type===o&&this.store("Sent:",e),this._message_identifier===this.maxMessageIdentifier&&(this._message_identifier=1)},R.prototype._on_socket_open=function(){var e=new M(r,this.connectOptions);e.clientId=this.clientId,this._socket_send(e)},R.prototype._on_socket_message=function(e){this._trace("Client._on_socket_message",e.data);for(var t=this._deframeMessages(e.data),n=0;n0)for(var m=null;m=this._buffered_msg_queue.pop();)d.push(m),this.onMessageDelivered&&(this._notify_msg_sent[m]=this.onMessageDelivered(m.payloadMessage));d=d.sort((function(e,t){return e.sequence-t.sequence}));for(var b=0,S=d.length;b65535)throw new Error(_(y.INVALID_ARGUMENT,[r,"clientId"]));var f=new R(i,e,t,n,r);Object.defineProperties(this,{host:{get:function(){return e},set:function(){throw new Error(_(y.UNSUPPORTED_OPERATION))}},port:{get:function(){return t},set:function(){throw new Error(_(y.UNSUPPORTED_OPERATION))}},path:{get:function(){return n},set:function(){throw new Error(_(y.UNSUPPORTED_OPERATION))}},uri:{get:function(){return i},set:function(){throw new Error(_(y.UNSUPPORTED_OPERATION))}},clientId:{get:function(){return f.clientId},set:function(){throw new Error(_(y.UNSUPPORTED_OPERATION))}},onConnected:{get:function(){return f.onConnected},set:function(e){if("function"!=typeof e)throw new Error(_(y.INVALID_TYPE,[typeof e,"onConnected"]));f.onConnected=e}},disconnectedPublishing:{get:function(){return f.disconnectedPublishing},set:function(e){f.disconnectedPublishing=e}},disconnectedBufferSize:{get:function(){return f.disconnectedBufferSize},set:function(e){f.disconnectedBufferSize=e}},onConnectionLost:{get:function(){return f.onConnectionLost},set:function(e){if("function"!=typeof e)throw new Error(_(y.INVALID_TYPE,[typeof e,"onConnectionLost"]));f.onConnectionLost=e}},onMessageDelivered:{get:function(){return f.onMessageDelivered},set:function(e){if("function"!=typeof e)throw new Error(_(y.INVALID_TYPE,[typeof e,"onMessageDelivered"]));f.onMessageDelivered=e}},onMessageArrived:{get:function(){return f.onMessageArrived},set:function(e){if("function"!=typeof e)throw new Error(_(y.INVALID_TYPE,[typeof e,"onMessageArrived"]));f.onMessageArrived=e}},trace:{get:function(){return f.traceFunction},set:function(e){if("function"!=typeof e)throw new Error(_(y.INVALID_TYPE,[typeof e,"onTrace"]));f.traceFunction=e}}}),this.connect=function(e){if(m(e=e||{},{timeout:"number",userName:"string",password:"string",willMessage:"object",keepAliveInterval:"number",cleanSession:"boolean",useSSL:"boolean",invocationContext:"object",onSuccess:"function",onFailure:"function",hosts:"object",ports:"object",reconnect:"boolean",mqttVersion:"number",mqttVersionExplicit:"boolean",uris:"object"}),void 0===e.keepAliveInterval&&(e.keepAliveInterval=60),e.mqttVersion>4||e.mqttVersion<3)throw new Error(_(y.INVALID_ARGUMENT,[e.mqttVersion,"connectOptions.mqttVersion"]));if(void 0===e.mqttVersion?(e.mqttVersionExplicit=!1,e.mqttVersion=4):e.mqttVersionExplicit=!0,void 0!==e.password&&void 0===e.userName)throw new Error(_(y.INVALID_ARGUMENT,[e.password,"connectOptions.password"]));if(e.willMessage){if(!(e.willMessage instanceof L))throw new Error(_(y.INVALID_TYPE,[e.willMessage,"connectOptions.willMessage"]));if(e.willMessage.stringPayload=null,void 0===e.willMessage.destinationName)throw new Error(_(y.INVALID_TYPE,[typeof e.willMessage.destinationName,"connectOptions.willMessage.destinationName"]))}if(void 0===e.cleanSession&&(e.cleanSession=!0),e.hosts){if(!(e.hosts instanceof Array))throw new Error(_(y.INVALID_ARGUMENT,[e.hosts,"connectOptions.hosts"]));if(e.hosts.length<1)throw new Error(_(y.INVALID_ARGUMENT,[e.hosts,"connectOptions.hosts"]));for(var t=!1,r=0;r=3&&(i.qos=n),arguments.length>=4&&(i.retained=r),f.send(i)},this.publish=function(e,t,n,r){var i;if(0===arguments.length)throw new Error("Invalid argument.length");if(1==arguments.length){if(!(e instanceof L)&&"string"!=typeof e)throw new Error("Invalid argument:"+typeof e);if(void 0===(i=e).destinationName)throw new Error(_(y.INVALID_ARGUMENT,[i.destinationName,"Message.destinationName"]));f.send(i)}else(i=new L(t)).destinationName=e,arguments.length>=3&&(i.qos=n),arguments.length>=4&&(i.retained=r),f.send(i)},this.disconnect=function(){f.disconnect()},this.getTraceLog=function(){return f.getTraceLog()},this.startTrace=function(){f.startTrace()},this.stopTrace=function(){f.stopTrace()},this.isConnected=function(){return f.connected}},Message:L}}(void 0!==t?t:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},e.exports=n()}).call(this,n(31))},function(e,t,n){"use strict";var r,i,o=n(486);function s(e,t,n){if(e._observer)a(e._observer,t,n);else if(e._observers){var r=[];e._observers.forEach((function(e){r.push(e)})),r.forEach((function(e){a(e,t,n)}))}}function a(e,t,n){if(!e.closed)switch(t){case"next":return e.next(n);case"error":return e.error(n);case"complete":return e.complete(n)}}function u(e){return e._observer||e._observers&&e._observers.size>0}function c(e){var t=this;this._observer=null,this._observers=null,this._observable=new o((function(n){return function(e,t){!u(e)&&t&&t.start&&t.start()}(t,e),function(e,t){e._observers?e._observers.add(t):e._observer?(e._observers=new Set,e._observers.add(e._observer),e._observers.add(t),e._observer=null):e._observer=t}(t,n),function(){!function(e,t){e._observers?e._observers.delete(t):e._observer===t&&(e._observer=null)}(t,n),function(e,t){!u(e)&&t&&t.pause&&t.pause()}(t,e)}}))}r=c.prototype,i={get observable(){return this._observable},get observed(){return u(this)},next:function(e){s(this,"next",e)},error:function(e){s(this,"error",e)},complete:function(e){s(this,"complete",e)}},Object.keys(i).forEach((function(e){var t=Object.getOwnPropertyDescriptor(i,e);t.enumerable=!1,Object.defineProperty(r,e,t)})),e.exports=c},function(e,t,n){"use strict";n.d(t,"a",(function(){return Nt}));var r=n(44),i=n(33),o=n(88),s=n(19);function a(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;r3?t.i-4:t.i:Array.isArray(e)?1:g(e)?2:m(e)?3:0}function d(e,t){return 2===l(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function h(e,t){return 2===l(e)?e.get(t):e[t]}function p(e,t,n){var r=l(e);2===r?e.set(t,n):3===r?(e.delete(t),e.add(n)):e[t]=n}function v(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}function g(e){return G&&e instanceof Map}function m(e){return W&&e instanceof Set}function b(e){return e.o||e.t}function y(e){if(Array.isArray(e))return Array.prototype.slice.call(e);var t=Q(e);delete t[Z];for(var n=X(t),r=0;r1&&(e.set=e.add=e.clear=e.delete=_),Object.freeze(e),t&&f(e,(function(e,t){return w(t,!0)}),!0)),e}function _(){a(2)}function S(e){return null==e||"object"!=typeof e||Object.isFrozen(e)}function E(e){var t=ee[e];return t||a(18,e),t}function M(e,t){ee[e]||(ee[e]=t)}function A(){return H}function I(e,t){t&&(E("Patches"),e.u=[],e.s=[],e.v=t)}function k(e){O(e),e.p.forEach(C),e.p=null}function O(e){e===H&&(H=e.l)}function x(e){return H={p:[],l:H,h:e,m:!0,_:0}}function C(e){var t=e[Z];0===t.i||1===t.i?t.j():t.g=!0}function T(e,t){t._=t.p.length;var n=t.p[0],r=void 0!==e&&e!==n;return t.h.O||E("ES5").S(t,e,r),r?(n[Z].P&&(k(t),a(4)),c(e)&&(e=P(t,e),t.l||R(t,e)),t.u&&E("Patches").M(n[Z],e,t.u,t.s)):e=P(t,n,[]),k(t),t.u&&t.v(t.u,t.s),e!==Y?e:void 0}function P(e,t,n){if(S(t))return t;var r=t[Z];if(!r)return f(t,(function(i,o){return N(e,r,t,i,o,n)}),!0),t;if(r.A!==e)return t;if(!r.P)return R(e,r.t,!0),r.t;if(!r.I){r.I=!0,r.A._--;var i=4===r.i||5===r.i?r.o=y(r.k):r.o;f(3===r.i?new Set(i):i,(function(t,o){return N(e,r,i,t,o,n)})),R(e,i,!1),n&&e.u&&E("Patches").R(r,n,e.u,e.s)}return r.o}function N(e,t,n,r,i,o){if(u(i)){var s=P(e,i,o&&t&&3!==t.i&&!d(t.D,r)?o.concat(r):void 0);if(p(n,r,s),!u(s))return;e.m=!1}if(c(i)&&!S(i)){if(!e.h.N&&e._<1)return;P(e,i),t&&t.A.l||R(e,i)}}function R(e,t,n){void 0===n&&(n=!1),e.h.N&&e.m&&w(t,n)}function L(e,t){var n=e[Z];return(n?b(n):e)[t]}function j(e,t){if(t in e)for(var n=Object.getPrototypeOf(e);n;){var r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=Object.getPrototypeOf(n)}}function D(e){e.P||(e.P=!0,e.l&&D(e.l))}function U(e){e.o||(e.o=y(e.t))}function B(e,t,n){var r=g(t)?E("MapSet").T(t,n):m(t)?E("MapSet").F(t,n):e.O?function(e,t){var n=Array.isArray(e),r={i:n?1:0,A:t?t.A:A(),P:!1,I:!1,D:{},l:t,t:e,k:null,o:null,j:null,C:!1},i=r,o=te;n&&(i=[r],o=ne);var s=Proxy.revocable(i,o),a=s.revoke,u=s.proxy;return r.k=u,r.j=a,u}(t,n):E("ES5").J(t,n);return(n?n.A:A()).p.push(r),r}function F(e){return u(e)||a(22,e),function e(t){if(!c(t))return t;var n,r=t[Z],i=l(t);if(r){if(!r.P&&(r.i<4||!E("ES5").K(r)))return r.t;r.I=!0,n=z(t,i),r.I=!1}else n=z(t,i);return f(n,(function(t,i){r&&h(r.t,t)===i||p(n,t,e(i))})),3===i?new Set(n):n}(e)}function z(e,t){switch(t){case 2:return new Map(e);case 3:return Array.from(e)}return y(e)}function q(){function e(t){if(!c(t))return t;if(Array.isArray(t))return t.map(e);if(g(t))return new Map(Array.from(t.entries()).map((function(t){return[t[0],e(t[1])]})));if(m(t))return new Set(Array.from(t).map(e));var n=Object.create(Object.getPrototypeOf(t));for(var r in t)n[r]=e(t[r]);return n}function t(t){return u(t)?e(t):t}var n="add";M("Patches",{$:function(t,r){return r.forEach((function(r){for(var i=r.path,o=r.op,s=t,u=0;u1?o-1:0),a=1;a1?n-1:0),o=1;o=0;n--){var r=t[n];if(0===r.path.length&&"replace"===r.op){e=r.value;break}}var i=E("Patches").$;return u(e)?i(e,t):this.produce(e,(function(e){return i(e,t.slice(n+1))}))},e}()),oe=(ie.produce,ie.produceWithPatches.bind(ie),ie.setAutoFreeze.bind(ie)),se=(ie.setUseProxies.bind(ie),ie.applyPatches.bind(ie),ie.createDraft.bind(ie),ie.finishDraft.bind(ie),n(109),n(14)),ae=n(9),ue=n(245),ce=function(){function e(){this._queue=[],this._pending=!1}return e.prototype.isLocked=function(){return this._pending},e.prototype.acquire=function(){var e=this,t=new Promise((function(t){return e._queue.push(t)}));return this._pending||this._dispatchNext(),t},e.prototype.runExclusive=function(e){return this.acquire().then((function(t){var n;try{n=e()}catch(e){throw t(),e}return Promise.resolve(n).then((function(e){return t(),e}),(function(e){throw t(),e}))}))},e.prototype._dispatchNext=function(){this._queue.length>0?(this._pending=!0,this._queue.shift()(this._dispatchNext.bind(this))):this._pending=!1},e}(),fe=n(257),le=n.n(fe),de=n(4),he=n(3),pe=function(){return Object(i.b)().isBrowser&&window.indexedDB||Object(i.c)()&&self.indexedDB?n(495).default:new(0,n(496).AsyncStorageAdapter)},ve=function(){return(ve=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},we=new r.a("DataStore"),_e=function(){function e(e,t,n,r,i,o){this.schema=e,this.namespaceResolver=t,this.getModelConstructorByModelName=n,this.modelInstanceCreator=r,this.adapter=i,this.sessionId=o,this.adapter=pe(),this.pushStream=new le.a}return e.getNamespace=function(){return{name:he.b,relationships:{},enums:{},models:{},nonModels:{}}},e.prototype.init=function(){return ge(this,void 0,void 0,(function(){var e,t;return me(this,(function(n){switch(n.label){case 0:return void 0===this.initialized?[3,2]:[4,this.initialized];case 1:return n.sent(),[2];case 2:return we.debug("Starting Storage"),this.initialized=new Promise((function(n,r){e=n,t=r})),this.adapter.setUp(this.schema,this.namespaceResolver,this.modelInstanceCreator,this.getModelConstructorByModelName,this.sessionId).then(e,t),[4,this.initialized];case 3:return n.sent(),[2]}}))}))},e.prototype.save=function(e,t,n,r){return ge(this,void 0,void 0,(function(){var i,o=this;return me(this,(function(s){switch(s.label){case 0:return[4,this.init()];case 1:return s.sent(),[4,this.adapter.save(e,t)];case 2:return(i=s.sent()).forEach((function(e){var i,s=ye(e,2),a=s[0],u=s[1];if(u===de.c.UPDATE&&r&&r.length){i={},r.map((function(e){return e.path&&e.path[0]})).forEach((function(e){i[e]=a[e]}));var c=a.id,f=a._version,l=a._lastChangedAt,d=a._deleted;i=ve(ve({},i),{id:c,_version:f,_lastChangedAt:l,_deleted:d})}var h=i||a,p=Object.getPrototypeOf(a).constructor;o.pushStream.next({model:p,opType:u,element:h,mutator:n,condition:ae.a.getPredicates(t,!1)})})),[2,i]}}))}))},e.prototype.delete=function(e,t,n){return ge(this,void 0,void 0,(function(){var r,i,o,s,a=this;return me(this,(function(u){switch(u.label){case 0:return[4,this.init()];case 1:return u.sent(),[4,this.adapter.delete(e,t)];case 2:return s=ye.apply(void 0,[u.sent(),2]),i=s[0],r=s[1],o=new Set(i.map((function(e){return e.id}))),Object(he.s)(e)||Array.isArray(r)||(r=[r]),r.forEach((function(r){var i,s=Object.getPrototypeOf(r).constructor;Object(he.s)(e)||(i=o.has(r.id)?ae.a.getPredicates(t,!1):void 0),a.pushStream.next({model:s,opType:de.c.DELETE,element:r,mutator:n,condition:i})})),[2,[i,r]]}}))}))},e.prototype.query=function(e,t,n){return ge(this,void 0,void 0,(function(){return me(this,(function(r){switch(r.label){case 0:return[4,this.init()];case 1:return r.sent(),[4,this.adapter.query(e,t,n)];case 2:return[2,r.sent()]}}))}))},e.prototype.queryOne=function(e,t){return void 0===t&&(t=de.d.FIRST),ge(this,void 0,void 0,(function(){return me(this,(function(n){switch(n.label){case 0:return[4,this.init()];case 1:return n.sent(),[4,this.adapter.queryOne(e,t)];case 2:return[2,n.sent()]}}))}))},e.prototype.observe=function(e,t,n){var r=!e,i=ae.a.getPredicates(t,!1)||{},o=i.predicates,s=i.type,a=!!o,u=this.pushStream.observable.filter((function(e){var t=e.mutator;return!n||t!==n})).map((function(e){e.mutator;return be(e,["mutator"])}));return r||(u=u.filter((function(t){var n=t.model,r=t.element;return e===n&&(!a||Object(he.y)(r,s,o))}))),u},e.prototype.clear=function(e){return void 0===e&&(e=!0),ge(this,void 0,void 0,(function(){return me(this,(function(t){switch(t.label){case 0:return this.initialized=void 0,[4,this.adapter.clear()];case 1:return t.sent(),e&&this.pushStream.complete(),[2]}}))}))},e.prototype.batchSave=function(e,t,n){return ge(this,void 0,void 0,(function(){var r,i=this;return me(this,(function(o){switch(o.label){case 0:return[4,this.init()];case 1:return o.sent(),[4,this.adapter.batchSave(e,t)];case 2:return(r=o.sent()).forEach((function(t){var r=ye(t,2),o=r[0],s=r[1];i.pushStream.next({model:e,opType:s,element:o,mutator:n,condition:void 0})})),[2,r]}}))}))},e}(),Se=function(){function e(e,t,n,r,i,o){this.mutex=new ce,this.storage=new _e(e,t,n,r,i,o)}return e.prototype.runExclusive=function(e){return this.mutex.runExclusive(e.bind(this,this.storage))},e.prototype.save=function(e,t,n,r){return ge(this,void 0,void 0,(function(){return me(this,(function(i){return[2,this.runExclusive((function(i){return i.save(e,t,n,r)}))]}))}))},e.prototype.delete=function(e,t,n){return ge(this,void 0,void 0,(function(){return me(this,(function(r){return[2,this.runExclusive((function(r){if(Object(he.s)(e)){var i=e;return r.delete(i,t,n)}var o=e;return r.delete(o,t,n)}))]}))}))},e.prototype.query=function(e,t,n){return ge(this,void 0,void 0,(function(){return me(this,(function(r){return[2,this.runExclusive((function(r){return r.query(e,t,n)}))]}))}))},e.prototype.queryOne=function(e,t){return void 0===t&&(t=de.d.FIRST),ge(this,void 0,void 0,(function(){return me(this,(function(n){return[2,this.runExclusive((function(n){return n.queryOne(e,t)}))]}))}))},e.getNamespace=function(){return _e.getNamespace()},e.prototype.observe=function(e,t,n){return this.storage.observe(e,t,n)},e.prototype.clear=function(){return ge(this,void 0,void 0,(function(){return me(this,(function(e){switch(e.label){case 0:return[4,this.storage.clear()];case 1:return e.sent(),[2]}}))}))},e.prototype.batchSave=function(e,t){return this.storage.batchSave(e,t)},e.prototype.init=function(){return ge(this,void 0,void 0,(function(){return me(this,(function(e){return[2,this.storage.init()]}))}))},e}(),Ee=n(34),Me=function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},Ae=(new(function(){function e(){}return e.prototype.networkMonitor=function(t){if(Object(i.b)().isNode)return se.a.from([{online:!0}]);var n=Object(i.c)()?self:window;return new se.a((function(t){t.next({online:n.navigator.onLine});var r=function(){return t.next({online:!0})},i=function(){return t.next({online:!1})};return n.addEventListener("online",r),n.addEventListener("offline",i),e._observers.push(t),function(){n.removeEventListener("online",r),n.removeEventListener("offline",i),e._observers=e._observers.filter((function(e){return e!==t}))}}))},e._observerOverride=function(t){var n,r,i=function(n){if(n.closed)return e._observers=e._observers.filter((function(e){return e!==n})),"continue";n.next(t)};try{for(var o=Me(e._observers),s=o.next();!s.done;s=o.next()){i(s.value)}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}},e._observers=[],e}())).networkMonitor(),Ie=function(){return(Ie=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},Te=function(){function e(e,t){this.outbox=e,this.ownSymbol=t}return e.prototype.merge=function(e,t){return Oe(this,void 0,void 0,(function(){var n,r,i,o,s;return xe(this,(function(a){switch(a.label){case 0:return[4,this.outbox.getForModel(e,t)];case 1:return r=a.sent(),i=t._deleted,0!==r.length?[3,5]:i?(n=de.c.DELETE,[4,e.delete(t,void 0,this.ownSymbol)]):[3,3];case 2:return a.sent(),[3,5];case 3:return[4,e.save(t,void 0,this.ownSymbol)];case 4:o=Ce.apply(void 0,[a.sent(),1]),s=Ce(o[0],2),n=s[1],a.label=5;case 5:return[2,n]}}))}))},e.prototype.mergePage=function(e,t,n){return Oe(this,void 0,void 0,(function(){return xe(this,(function(r){switch(r.label){case 0:return[4,e.batchSave(t,n,this.ownSymbol)];case 1:return[2,r.sent()]}}))}))},e}(),Pe=n(13),Ne=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))},Re=function(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},je=function(){function e(e,t,n,r){this.schema=e,this.namespaceResolver=t,this.MutationEvent=n,this.ownSymbol=r}return e.prototype.enqueue=function(e,t){return Ne(this,void 0,void 0,(function(){var n=this;return Re(this,(function(r){return e.runExclusive((function(e){return Ne(n,void 0,void 0,(function(){var n,r,i,o,s,a,u,c=this;return Re(this,(function(f){switch(f.label){case 0:return n=this.schema.namespaces[he.c].models.MutationEvent,r=ae.a.createFromExisting(n,(function(e){return e.modelId("eq",t.modelId).id("ne",c.inProgressMutationEventId)})),[4,e.query(this.MutationEvent,r)];case 1:return i=Le.apply(void 0,[f.sent(),1]),void 0!==(o=i[0])?[3,3]:[4,e.save(t,void 0,this.ownSymbol)];case 2:return f.sent(),[2];case 3:return s=t.operation,o.operation!==Pe.a.CREATE?[3,8]:s!==Pe.a.DELETE?[3,5]:[4,e.delete(this.MutationEvent,r)];case 4:return f.sent(),[3,7];case 5:return[4,e.save(this.MutationEvent.copyOf(o,(function(e){e.data=t.data})),void 0,this.ownSymbol)];case 6:f.sent(),f.label=7;case 7:return[3,12];case 8:return a=t.condition,u=JSON.parse(a),0!==Object.keys(u).length?[3,10]:[4,e.delete(this.MutationEvent,r)];case 9:f.sent(),f.label=10;case 10:return[4,e.save(t,void 0,this.ownSymbol)];case 11:f.sent(),f.label=12;case 12:return[2]}}))}))})),[2]}))}))},e.prototype.dequeue=function(e){return Ne(this,void 0,void 0,(function(){var t;return Re(this,(function(n){switch(n.label){case 0:return[4,this.peek(e)];case 1:return t=n.sent(),[4,e.delete(t)];case 2:return n.sent(),this.inProgressMutationEventId=void 0,[2,t]}}))}))},e.prototype.peek=function(e){return Ne(this,void 0,void 0,(function(){var t;return Re(this,(function(n){switch(n.label){case 0:return[4,e.queryOne(this.MutationEvent,de.d.FIRST)];case 1:return t=n.sent(),this.inProgressMutationEventId=t?t.id:void 0,[2,t]}}))}))},e.prototype.getForModel=function(e,t){return Ne(this,void 0,void 0,(function(){var n;return Re(this,(function(r){switch(r.label){case 0:return n=this.schema.namespaces[he.c].models.MutationEvent,[4,e.query(this.MutationEvent,ae.a.createFromExisting(n,(function(e){return e.modelId("eq",t.id)})))];case 1:return[2,r.sent()]}}))}))},e.prototype.getModelIds=function(e){return Ne(this,void 0,void 0,(function(){var t,n;return Re(this,(function(r){switch(r.label){case 0:return[4,e.query(this.MutationEvent)];case 1:return t=r.sent(),n=new Set,t.forEach((function(e){var t=e.modelId;return n.add(t)})),[2,n]}}))}))},e}(),De=n(52),Ue=n(514),Be=function(){return(Be=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},He=new r.a("DataStore"),Ve=function(){function e(e,t,n,r,i,o,s,a){this.schema=e,this.storage=t,this.userClasses=n,this.outbox=r,this.modelInstanceCreator=i,this.MutationEvent=o,this.conflictHandler=s,this.errorHandler=a,this.typeQuery=new WeakMap,this.processing=!1,this.generateQueries()}return e.prototype.generateQueries=function(){var e=this;Object.values(this.schema.namespaces).forEach((function(t){Object.values(t.models).filter((function(e){return e.syncable})).forEach((function(n){var r=Ke(Object(Pe.b)(t,n,"CREATE"),1)[0],i=Ke(Object(Pe.b)(t,n,"UPDATE"),1)[0],o=Ke(Object(Pe.b)(t,n,"DELETE"),1)[0];e.typeQuery.set(n,[r,i,o])}))}))},e.prototype.isReady=function(){return void 0!==this.observer},e.prototype.start=function(){var e=this;return new se.a((function(t){return e.observer=t,e.resume(),function(){e.pause()}}))},e.prototype.resume=function(){return Fe(this,void 0,void 0,(function(){var e,t,n,r,i,o,s,a,u,c,f,l,d,h,p;return ze(this,(function(v){switch(v.label){case 0:if(this.processing||!this.isReady())return[2];this.processing=!0,t=he.d,v.label=1;case 1:return(n=this.processing)?[4,this.outbox.peek(this.storage)]:[3,3];case 2:n=void 0!==(e=v.sent()),v.label=3;case 3:if(!n)return[3,12];r=e.model,i=e.operation,o=e.data,s=e.condition,a=this.userClasses[r],u=void 0,c=void 0,f=void 0,v.label=4;case 4:return v.trys.push([4,6,,7]),[4,this.jitteredRetry(t,r,i,o,s,a,this.MutationEvent,e)];case 5:return p=Ke.apply(void 0,[v.sent(),3]),u=p[0],c=p[1],f=p[2],[3,7];case 6:return"Offline"===(l=v.sent()).message||"RetryMutation"===l.message?[3,1]:[3,7];case 7:return void 0!==u?[3,9]:(He.debug("done retrying"),[4,this.outbox.dequeue(this.storage)]);case 8:return v.sent(),[3,1];case 9:return d=u.data[c],[4,this.outbox.dequeue(this.storage)];case 10:return v.sent(),[4,this.outbox.peek(this.storage)];case 11:return h=void 0!==v.sent(),this.observer.next({operation:i,modelDefinition:f,model:d,hasMore:h}),[3,1];case 12:return this.pause(),[2]}}))}))},e.prototype.jitteredRetry=function(e,t,n,r,i,o,s,a){return Fe(this,void 0,void 0,(function(){var u=this;return ze(this,(function(c){switch(c.label){case 0:return[4,Object(Ue.b)((function(t,n,r,i,o,s,a){return Fe(u,void 0,void 0,(function(){var u,c,f,l,d,h,p,v,g,m,b,y,w,_,S,E,M,A,I,k,O;return ze(this,(function(x){switch(x.label){case 0:u=Ke(this.createQueryVariables(e,t,n,r,i),5),c=u[0],f=u[1],l=u[2],d=u[3],h=u[4],p={query:c,variables:f},v=0,g=this.opTypeFromTransformerOperation(n),x.label=1;case 1:return x.trys.push([1,3,,13]),[4,De.a.graphql(p)];case 2:return[2,[x.sent(),d,h]];case 3:if(!((m=x.sent()).errors&&m.errors.length>0))return[3,12];if(b=Ke(m.errors,1),"Network Error"===(y=b[0]).message){if(!this.processing)throw new Ue.a("Offline");throw new Error("Network Error")}return"ConflictUnhandled"!==y.errorType?[3,11]:(v++,w=void 0,v>10?(w=de.a,[3,7]):[3,4]);case 4:return x.trys.push([4,6,,7]),[4,this.conflictHandler({modelConstructor:o,localModel:this.modelInstanceCreator(o,f.input),remoteModel:this.modelInstanceCreator(o,y.data),operation:g,attempts:v})];case 5:return w=x.sent(),[3,7];case 6:return _=x.sent(),He.warn("conflict trycatch",_),[3,13];case 7:return w!==de.a?[3,9]:(S=Ke(Object(Pe.b)(this.schema.namespaces[e],h,"GET"),1),E=Ke(S[0],3),M=E[1],A=E[2],[4,De.a.graphql({query:A,variables:{id:f.input.id}})]);case 8:return[2,[x.sent(),M,h]];case 9:return I=this.schema.namespaces[e],k=Object(Pe.d)(I.relationships,h,g,o,w,l,s,this.modelInstanceCreator,a.id),[4,this.storage.save(k)];case 10:throw x.sent(),new Ue.a("RetryMutation");case 11:try{this.errorHandler({localModel:this.modelInstanceCreator(o,f.input),message:y.message,operation:n,errorType:y.errorType,errorInfo:y.errorInfo,remoteModel:y.data?this.modelInstanceCreator(o,y.data):null})}catch(e){He.warn("failed to execute errorHandler",e)}finally{return[2,y.data?[{data:(O={},O[d]=y.data,O)},d,h]:[]]}x.label=12;case 12:return[3,13];case 13:if(p)return[3,1];x.label=14;case 14:return[2]}}))}))}),[t,n,r,i,o,s,a])];case 1:return[2,c.sent()]}}))}))},e.prototype.createQueryVariables=function(e,t,n,r,i){var o=this.schema.namespaces[e].models[t],s=this.typeQuery.get(o),a=Ke(s.find((function(e){return Ke(e,1)[0]===n})),3),u=a[1],c=a[2],f=JSON.parse(r),l=f._version,d=qe(f,["_version"]),h=n===Pe.a.DELETE?{id:d.id}:Object.values(o.fields).filter((function(e){var t=e.name,r=e.type,i=e.association;return Object(de.h)(r)?!(!Object(de.m)(i)||"BELONGS_TO"!==i.connectionType):n!==Pe.a.UPDATE||d.hasOwnProperty(t)})).map((function(e){var t=e.name,n=e.type,r=e.association,i=t,o=d[t];return Object(de.h)(n)&&Object(de.m)(r)&&(i=r.targetName,o=d[i]),[i,o]})).reduce((function(e,t){var n=Ke(t,2),r=n[0],i=n[1];return e[r]=i,e}),{}),p=Be(Be({},h),{_version:l}),v=JSON.parse(i);return[c,Be({input:p},n===Pe.a.CREATE?{}:{condition:Object.keys(v).length>0?v:null}),v,u,o]},e.prototype.opTypeFromTransformerOperation=function(e){switch(e){case Pe.a.CREATE:return de.c.INSERT;case Pe.a.DELETE:return de.c.DELETE;case Pe.a.UPDATE:return de.c.UPDATE;case Pe.a.GET:break;default:Object(he.f)(e)}},e.prototype.pause=function(){this.processing=!1},e}(),Ge=n(154),We=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))},$e=function(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},Je=function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},Ze=new r.a("DataStore"),Xe=function(){function e(e,t,n,r){void 0===t&&(t=1e4),void 0===n&&(n=1e3),this.schema=e,this.maxRecordsToSync=t,this.syncPageSize=n,this.syncPredicates=r,this.typeQuery=new WeakMap,this.generateQueries()}return e.prototype.generateQueries=function(){var e=this;Object.values(this.schema.namespaces).forEach((function(t){Object.values(t.models).filter((function(e){return e.syncable})).forEach((function(n){var r=Ye(Object(Pe.b)(t,n,"LIST"),1),i=Ye(r[0]).slice(1);e.typeQuery.set(n,i)}))}))},e.prototype.graphqlFilterFromPredicate=function(e){if(!this.syncPredicates)return null;var t=ae.a.getPredicates(this.syncPredicates.get(e),!1);return t?Object(Pe.h)(t):null},e.prototype.retrievePage=function(e,t,n,r,i){return void 0===r&&(r=null),We(this,void 0,void 0,(function(){var o,s,a,u,c,f,l,d,h;return $e(this,(function(p){switch(p.label){case 0:return o=Ye(this.typeQuery.get(e),2),s=o[0],a=o[1],u={limit:r,nextToken:n,lastSync:t,filter:i},[4,this.jitteredRetry(a,u,s)];case 1:return c=p.sent().data,f=c[s],l=f.items,d=f.nextToken,h=f.startedAt,[2,{nextToken:d,startedAt:h,items:l}]}}))}))},e.prototype.jitteredRetry=function(e,t,n){return We(this,void 0,void 0,(function(){var r=this;return $e(this,(function(i){switch(i.label){case 0:return[4,Object(Ue.b)((function(e,t){return We(r,void 0,void 0,(function(){var r,i;return $e(this,(function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,De.a.graphql({query:e,variables:t})];case 1:return[2,o.sent()];case 2:if(r=o.sent(),r.errors.some((function(e){return"Unauthorized"===e.errorType})))return(i=r).data[n].items=i.data[n].items.filter((function(e){return null!==e})),Ze.warn("queryError","User is unauthorized, some items could not be returned."),[2,i];throw r;case 3:return[2]}}))}))}),[e,t])];case 1:return[2,i.sent()]}}))}))},e.prototype.start=function(e){var t=this,n=!0,r=void 0!==this.maxRecordsToSync?this.maxRecordsToSync:1e4,i=void 0!==this.syncPageSize?this.syncPageSize:1e3,o=new Map;return new se.a((function(s){var a=Object.values(t.schema.namespaces).reduce((function(t,n){var r,i;try{for(var o=Je(Array.from(n.modelTopologicalOrdering.keys())),s=o.next();!s.done;s=o.next()){var a=s.value,u=e.get(n.models[a]);t.set(n.models[a],u)}}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(r)throw r.error}}return t}),new Map),u=Array.from(a.entries()).filter((function(e){return Ye(e,1)[0].syncable})).map((function(e){var a=Ye(e,2),u=a[0],c=Ye(a[1],2),f=c[0],l=c[1];return We(t,void 0,void 0,(function(){var e,t,a,c,d,h,p,v,g,m=this;return $e(this,(function(b){switch(b.label){case 0:return e=!1,t=null,a=null,c=null,d=0,h=this.graphqlFilterFromPredicate(u),p=this.schema.namespaces[f].modelTopologicalOrdering.get(u.name),v=p.map((function(e){return o.get(f+"_"+e)})),g=new Promise((function(o){return We(m,void 0,void 0,(function(){var p,g;return $e(this,(function(m){switch(m.label){case 0:return[4,Promise.all(v)];case 1:m.sent(),m.label=2;case 2:return n?(p=Math.min(r-d,i),[4,this.retrievePage(u,l,t,p,h)]):[2];case 3:g=m.sent(),c=g.items,t=g.nextToken,a=g.startedAt,d+=c.length,e=null===t||d>=r,s.next({namespace:f,modelDefinition:u,items:c,done:e,startedAt:a,isFullSync:!l}),m.label=4;case 4:if(!e)return[3,2];m.label=5;case 5:return o(),[2]}}))}))})),o.set(f+"_"+u.name,g),[4,g];case 1:return b.sent(),[2]}}))}))}));return Promise.all(u).then((function(){s.complete()})),function(){n=!1}}))},e}(),Qe=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))},et=function(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},nt=function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},rt=function(){for(var e=[],t=0;t0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s};oe(!0),q();var ht,pt,vt,gt,mt,bt=new r.a("DataStore"),yt=(Object(he.v)(Date.now()),i.a.browserOrNode().isNode),wt=new WeakMap,_t=new WeakMap,St=function(e){var t=wt.get(e);return ht.namespaces[t].models[e.name]},Et=function(e){return Object(he.s)(e)&&wt.has(e)},Mt=function(e){return wt.get(e)},At=new WeakSet;function It(e,t){return At.add(t),new e(t)}var kt;function Ot(e){return"string"==typeof e}function xt(e){var t=e.localModel,n=e.modelConstructor,r=e.remoteModel._version;return It(n,ut(ut({},t),{_version:r}))}function Ct(e){bt.warn(e)}function Tt(e,t){var n;switch(e){case he.a:n=pt[t];break;case he.d:n=vt[t];break;case he.c:n=gt[t];break;case he.b:n=mt[t];break;default:Object(he.f)(e)}if(Et(n))return n;var r="Model name is not valid for namespace. modelName: "+t+", namespace: "+e;throw bt.error(r),new Error(r)}function Pt(e,t){return ct(this,void 0,void 0,(function(){var n,r,i=this;return ft(this,(function(o){switch(o.label){case 0:return n=pt.Setting,r=ht.namespaces[he.a].models.Setting,[4,e.runExclusive((function(e){return ct(i,void 0,void 0,(function(){var i,o;return ft(this,(function(s){switch(s.label){case 0:return[4,e.query(n,ae.a.createFromExisting(r,(function(e){return e.key("eq","schemaVersion")})),{page:0,limit:1})];case 1:return i=dt.apply(void 0,[s.sent(),1]),void 0===(o=i[0])||void 0===o.value?[3,4]:JSON.parse(o.value)===t?[3,3]:[4,e.clear(!1)];case 2:s.sent(),s.label=3;case 3:return[3,6];case 4:return[4,e.save(It(n,{key:"schemaVersion",value:JSON.stringify(t)}))];case 5:s.sent(),s.label=6;case 6:return[2]}}))}))}))];case 1:return o.sent(),[2]}}))}))}var Nt=new(function(){function e(){var e=this;this.amplifyConfig={},this.syncPredicates=new WeakMap,this.start=function(){return ct(e,void 0,void 0,(function(){var e,t,n,r=this;return ft(this,(function(i){switch(i.label){case 0:return void 0!==this.initialized?[3,1]:(bt.debug("Starting DataStore"),this.initialized=new Promise((function(e,t){r.initResolve=e,r.initReject=t})),[3,3]);case 1:return[4,this.initialized];case 2:return i.sent(),[2];case 3:return this.storage=new Se(ht,Mt,Tt,It,void 0,this.sessionId),[4,this.storage.init()];case 4:return i.sent(),[4,Pt(this.storage,ht.version)];case 5:return i.sent(),(e=this.amplifyConfig.aws_appsync_graphqlEndpoint)?(bt.debug("GraphQL endpoint available",e),t=this,[4,this.processSyncExpressions()]):[3,7];case 6:return t.syncPredicates=i.sent(),this.sync=new at(ht,Mt,gt,vt,this.storage,It,this.maxRecordsToSync,this.syncPageSize,this.conflictHandler,this.errorHandler,this.syncPredicates,this.amplifyConfig),n=1e3*this.fullSyncInterval*60,kt=this.sync.start({fullSyncInterval:n}).subscribe({next:function(e){var t=e.type,n=e.data;t===(yt?re.SYNC_ENGINE_SYNC_QUERIES_READY:re.SYNC_ENGINE_STORAGE_SUBSCRIBED)&&r.initResolve(),o.a.dispatch("datastore",{event:t,data:n})},error:function(e){bt.warn("Sync error",e),r.initReject()}}),[3,8];case 7:bt.warn("Data won't be synchronized. No GraphQL endpoint configured. Did you forget `Amplify.configure(awsconfig)`?",{config:this.amplifyConfig}),this.initResolve(),i.label=8;case 8:return[4,this.initialized];case 9:return i.sent(),[2]}}))}))},this.query=function(t,n,r){return ct(e,void 0,void 0,(function(){var e,i,o,s,a;return ft(this,(function(u){switch(u.label){case 0:return[4,this.start()];case 1:if(u.sent(),!Et(t))throw e="Constructor is not for a valid model",bt.error(e,{modelConstructor:t}),new Error(e);return"string"==typeof n&&void 0!==r&&bt.warn("Pagination is ignored when querying by id"),i=St(t),o=Ot(n)?ae.a.createForId(i,n):Object(ae.c)(n)?void 0:ae.a.createFromExisting(i,n),s=this.processPagination(i,r),bt.debug("params ready",{modelConstructor:t,predicate:ae.a.getPredicates(o,!1),pagination:ut(ut({},s),{sort:ue.a.getPredicates(s.sort,!1)})}),[4,this.storage.query(t,o,s)];case 2:return a=u.sent(),[2,Ot(n)?a[0]:a]}}))}))},this.save=function(t,n){return ct(e,void 0,void 0,(function(){var e,r,i,o,s,a,u=this;return ft(this,(function(c){switch(c.label){case 0:return[4,this.start()];case 1:if(c.sent(),e=_t.get(t),r=t?t.constructor:void 0,!Et(r))throw i="Object is not an instance of a valid model",bt.error(i,{model:t}),new Error(i);return o=St(r),s=ae.a.createFromExisting(o,n),[4,this.storage.runExclusive((function(n){return ct(u,void 0,void 0,(function(){return ft(this,(function(i){switch(i.label){case 0:return[4,n.save(t,s,void 0,e)];case 1:return i.sent(),[2,n.query(r,ae.a.createForId(o,t.id))]}}))}))}))];case 2:return a=dt.apply(void 0,[c.sent(),1]),[2,a[0]]}}))}))},this.setConflictHandler=function(t){var n=t.DataStore;return n?n.conflictHandler:e.conflictHandler===xt&&t.conflictHandler?t.conflictHandler:e.conflictHandler||xt},this.setErrorHandler=function(t){var n=t.DataStore;return n?n.errorHandler:e.errorHandler===Ct&&t.errorHandler?t.errorHandler:e.errorHandler||Ct},this.delete=function(t,n){return ct(e,void 0,void 0,(function(){var e,r,i,o,s,a,u,c,f;return ft(this,(function(l){switch(l.label){case 0:return[4,this.start()];case 1:if(l.sent(),!t)throw u="Model or Model Constructor required",bt.error(u,{modelOrConstructor:t}),new Error(u);if(!Et(t))return[3,3];if(o=t,!n)throw u="Id to delete or criteria required. Do you want to delete all? Pass Predicates.ALL",bt.error(u,{idOrCriteria:n}),new Error(u);if("string"==typeof n)e=ae.a.createForId(St(o),n);else if(!(e=ae.a.createFromExisting(St(o),n))||!ae.a.isValidPredicate(e))throw u="Criteria required. Do you want to delete all? Pass Predicates.ALL",bt.error(u,{condition:e}),new Error(u);return[4,this.storage.delete(o,e)];case 2:return r=dt.apply(void 0,[l.sent(),1]),[2,r[0]];case 3:if(i=t,o=Object.getPrototypeOf(i||{}).constructor,!Et(o))throw u="Object is not an instance of a valid model",bt.error(u,{model:i}),new Error(u);if(s=St(o),a=ae.a.createForId(s,i.id),n){if("function"!=typeof n)throw u="Invalid criteria",bt.error(u,{idOrCriteria:n}),new Error(u);e=n(a)}else e=a;return[4,this.storage.delete(i,e)];case 4:return c=dt.apply(void 0,[l.sent(),1]),f=dt(c[0],1),[2,f[0]]}}))}))},this.observe=function(t,n){var r,i=t&&Et(t)?t:void 0;if(t&&void 0===i){var o=t,s=o&&Object.getPrototypeOf(o).constructor;if(Et(s))return n&&bt.warn("idOrCriteria is ignored when using a model instance",{model:o,idOrCriteria:n}),e.observe(s,o.id);var a="The model is not an instance of a PersistentModelConstructor";throw bt.error(a,{model:o}),new Error(a)}if(void 0!==n&&void 0===i){a="Cannot provide criteria without a modelConstructor";throw bt.error(a,n),new Error(a)}if(i&&!Et(i)){a="Constructor is not for a valid model";throw bt.error(a,{modelConstructor:i}),new Error(a)}return r="string"==typeof n?ae.a.createForId(St(i),n):i&&ae.a.createFromExisting(St(i),n),new se.a((function(t){var n;return ct(e,void 0,void 0,(function(){return ft(this,(function(e){switch(e.label){case 0:return[4,this.start()];case 1:return e.sent(),n=this.storage.observe(i,r).filter((function(e){var t=e.model;return Mt(t)===he.d})).subscribe(t),[2]}}))})),function(){n&&n.unsubscribe()}}))},this.configure=function(t){void 0===t&&(t={});var n=t.DataStore,r=(t.conflictHandler,t.errorHandler,t.maxRecordsToSync),i=t.syncPageSize,o=t.fullSyncInterval,s=t.syncExpressions,a=lt(t,["DataStore","conflictHandler","errorHandler","maxRecordsToSync","syncPageSize","fullSyncInterval","syncExpressions"]);e.amplifyConfig=ut(ut({},a),e.amplifyConfig),e.conflictHandler=e.setConflictHandler(t),e.errorHandler=e.setErrorHandler(t),e.syncExpressions=n&&n.syncExpressions||e.syncExpressions||s,e.maxRecordsToSync=n&&n.maxRecordsToSync||e.maxRecordsToSync||r,e.syncPageSize=n&&n.syncPageSize||e.syncPageSize||i,e.fullSyncInterval=n&&n.fullSyncInterval||e.fullSyncInterval||o||1440,e.sessionId=e.retrieveSessionId()},this.clear=function(){return ct(this,void 0,void 0,(function(){return ft(this,(function(e){switch(e.label){case 0:return void 0===this.storage?[2]:(kt&&!kt.closed&&kt.unsubscribe(),[4,this.storage.clear()]);case 1:return e.sent(),this.sync&&this.sync.unsubscribeConnectivity(),this.initialized=void 0,this.storage=void 0,this.sync=void 0,this.syncPredicates=new WeakMap,[2]}}))}))},this.stop=function(){return ct(this,void 0,void 0,(function(){return ft(this,(function(e){switch(e.label){case 0:return void 0===this.initialized?[3,2]:[4,this.start()];case 1:e.sent(),e.label=2;case 2:return kt&&!kt.closed&&kt.unsubscribe(),this.sync&&this.sync.unsubscribeConnectivity(),this.initialized=void 0,this.sync=void 0,[2]}}))}))}}return e.prototype.getModuleName=function(){return"DataStore"},e.prototype.processPagination=function(e,t){var n,r=t||{},i=r.limit,o=r.page,s=r.sort;if(void 0!==o&&void 0===i)throw new Error("Limit is required when requesting a page");if(void 0!==o){if("number"!=typeof o)throw new Error("Page should be a number");if(o<0)throw new Error("Page can't be negative")}if(void 0!==i){if("number"!=typeof i)throw new Error("Limit should be a number");if(i<0)throw new Error("Limit can't be negative")}return s&&(n=ue.a.createFromExisting(e,t.sort)),{limit:i,page:o,sort:n}},e.prototype.processSyncExpressions=function(){return ct(this,void 0,void 0,(function(){var e,t=this;return ft(this,(function(n){switch(n.label){case 0:return this.syncExpressions&&this.syncExpressions.length?[4,Promise.all(this.syncExpressions.map((function(e){return ct(t,void 0,void 0,(function(){var t,n,r,i,o,s;return ft(this,(function(a){switch(a.label){case 0:return[4,e];case 1:return t=a.sent(),n=t.modelConstructor,r=t.conditionProducer,i=St(n),[4,this.unwrapPromise(r)];case 2:return o=a.sent(),Object(ae.c)(o)?[2,[i,null]]:(s=this.createFromCondition(i,o),[2,[i,s]])}}))}))})))]:[2,new WeakMap];case 1:return e=n.sent(),[2,this.weakMapFromEntries(e)]}}))}))},e.prototype.createFromCondition=function(e,t){try{return ae.a.createFromExisting(e,t)}catch(e){throw bt.error("Error creating Sync Predicate"),e}},e.prototype.unwrapPromise=function(e){return ct(this,void 0,void 0,(function(){var t;return ft(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,e()];case 1:return[2,n.sent()];case 2:if((t=n.sent())instanceof TypeError)return[2,e];throw t;case 3:return[2]}}))}))},e.prototype.weakMapFromEntries=function(e){return e.reduce((function(e,t){var n=dt(t,2),r=n[0],i=n[1];if(e.has(r)){var o=r.name;return bt.warn("You can only utilize one Sync Expression per model.\n Subsequent sync expressions for the "+o+" model will be ignored."),e}return i&&e.set(r,i),e}),new WeakMap)},e.prototype.retrieveSessionId=function(){try{var e=sessionStorage.getItem("datastoreSessionId");if(e){var t=this.amplifyConfig.aws_appsync_graphqlEndpoint.split("/")[2];return e+"-"+dt(t.split("."),1)[0]}}catch(e){return}},e}());s.a.register(Nt)},,,,,,,,,,,function(e,t,n){"use strict";t.byteLength=function(e){var t=c(e),n=t[0],r=t[1];return 3*(n+r)/4-r},t.toByteArray=function(e){var t,n,r=c(e),s=r[0],a=r[1],u=new o(function(e,t,n){return 3*(t+n)/4-n}(0,s,a)),f=0,l=a>0?s-4:s;for(n=0;n>16&255,u[f++]=t>>8&255,u[f++]=255&t;2===a&&(t=i[e.charCodeAt(n)]<<2|i[e.charCodeAt(n+1)]>>4,u[f++]=255&t);1===a&&(t=i[e.charCodeAt(n)]<<10|i[e.charCodeAt(n+1)]<<4|i[e.charCodeAt(n+2)]>>2,u[f++]=t>>8&255,u[f++]=255&t);return u},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,o=[],s=0,a=n-i;sa?a:s+16383));1===i?(t=e[n-1],o.push(r[t>>2]+r[t<<4&63]+"==")):2===i&&(t=(e[n-2]<<8)+e[n-1],o.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"="));return o.join("")};for(var r=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,u=s.length;a0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function f(e,t,n){for(var i,o,s=[],a=t;a>18&63]+r[o>>12&63]+r[o>>6&63]+r[63&o]);return s.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},function(e,t){ +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +t.read=function(e,t,n,r,i){var o,s,a=8*i-r-1,u=(1<>1,f=-7,l=n?i-1:0,d=n?-1:1,h=e[t+l];for(l+=d,o=h&(1<<-f)-1,h>>=-f,f+=a;f>0;o=256*o+e[t+l],l+=d,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=r;f>0;s=256*s+e[t+l],l+=d,f-=8);if(0===o)o=1-c;else{if(o===u)return s?NaN:1/0*(h?-1:1);s+=Math.pow(2,r),o-=c}return(h?-1:1)*s*Math.pow(2,o-r)},t.write=function(e,t,n,r,i,o){var s,a,u,c=8*o-i-1,f=(1<>1,d=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,h=r?0:o-1,p=r?1:-1,v=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=f):(s=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-s))<1&&(s--,u*=2),(t+=s+l>=1?d/u:d*Math.pow(2,1-l))*u>=2&&(s++,u/=2),s+l>=f?(a=0,s=f):s+l>=1?(a=(t*u-1)*Math.pow(2,i),s+=l):(a=t*Math.pow(2,l-1)*Math.pow(2,i),s=0));i>=8;e[n+h]=255&a,h+=p,a/=256,i-=8);for(s=s<0;e[n+h]=255&s,h+=p,s/=256,c-=8);e[n+h-p]|=128*v}},function(e,t,n){var r,i,o,s;e.exports=(r=n(32),o=(i=r).lib.Base,s=i.enc.Utf8,void(i.algo.HMAC=o.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=s.parse(t));var n=e.blockSize,r=4*n;t.sigBytes>r&&(t=e.finalize(t)),t.clamp();for(var i=this._oKey=t.clone(),o=this._iKey=t.clone(),a=i.words,u=o.words,c=0;c0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n}},{key:"concat",value:function(e){if(0===this.length)return s.alloc(0);for(var t,n,r,i=s.allocUnsafe(e>>>0),o=this.head,a=0;o;)t=o.data,n=i,r=a,s.prototype.copy.call(t,n,r),a+=o.data.length,o=o.next;return i}},{key:"consume",value:function(e,t){var n;return ei.length?i.length:e;if(o===i.length?r+=i:r+=i.slice(0,e),0==(e-=o)){o===i.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(o));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=s.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,o=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,o),0==(e-=o)){o===i.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=i.slice(o));break}++r}return this.length-=r,t}},{key:u,value:function(e,t){return a(this,function(e){for(var t=1;t0,(function(e){r||(r=e),e&&s.forEach(c),o||(s.forEach(c),i(r))}))}));return t.reduce(f)}},function(e,t,n){var r=n(7),i=n(69),o=n(8).Buffer,s=[1518500249,1859775393,-1894007588,-899497514],a=new Array(80);function u(){this.init(),this._w=a,i.call(this,64,56)}function c(e){return e<<30|e>>>2}function f(e,t,n,r){return 0===e?t&n|~t&r:2===e?t&n|t&r|n&r:t^n^r}r(u,i),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,n=this._w,r=0|this._a,i=0|this._b,o=0|this._c,a=0|this._d,u=0|this._e,l=0;l<16;++l)n[l]=e.readInt32BE(4*l);for(;l<80;++l)n[l]=n[l-3]^n[l-8]^n[l-14]^n[l-16];for(var d=0;d<80;++d){var h=~~(d/20),p=0|((t=r)<<5|t>>>27)+f(h,i,o,a)+u+n[d]+s[h];u=a,a=o,o=c(i),i=r,r=p}this._a=r+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=a+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},e.exports=u},function(e,t,n){var r=n(7),i=n(69),o=n(8).Buffer,s=[1518500249,1859775393,-1894007588,-899497514],a=new Array(80);function u(){this.init(),this._w=a,i.call(this,64,56)}function c(e){return e<<5|e>>>27}function f(e){return e<<30|e>>>2}function l(e,t,n,r){return 0===e?t&n|~t&r:2===e?t&n|t&r|n&r:t^n^r}r(u,i),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,n=this._w,r=0|this._a,i=0|this._b,o=0|this._c,a=0|this._d,u=0|this._e,d=0;d<16;++d)n[d]=e.readInt32BE(4*d);for(;d<80;++d)n[d]=(t=n[d-3]^n[d-8]^n[d-14]^n[d-16])<<1|t>>>31;for(var h=0;h<80;++h){var p=~~(h/20),v=c(r)+l(p,i,o,a)+u+n[h]+s[p]|0;u=a,a=o,o=f(i),i=r,r=v}this._a=r+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=a+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},e.exports=u},function(e,t,n){var r=n(7),i=n(169),o=n(69),s=n(8).Buffer,a=new Array(64);function u(){this.init(),this._w=a,o.call(this,64,56)}r(u,i),u.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},u.prototype._hash=function(){var e=s.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e},e.exports=u},function(e,t,n){var r=n(7),i=n(170),o=n(69),s=n(8).Buffer,a=new Array(160);function u(){this.init(),this._w=a,o.call(this,128,112)}r(u,i),u.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},u.prototype._hash=function(){var e=s.allocUnsafe(48);function t(t,n,r){e.writeInt32BE(t,r),e.writeInt32BE(n,r+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e},e.exports=u},function(e,t,n){e.exports=i;var r=n(49).EventEmitter;function i(){r.call(this)}n(7)(i,r),i.Readable=n(118),i.Writable=n(292),i.Duplex=n(293),i.Transform=n(294),i.PassThrough=n(295),i.Stream=i,i.prototype.pipe=function(e,t){var n=this;function i(t){e.writable&&!1===e.write(t)&&n.pause&&n.pause()}function o(){n.readable&&n.resume&&n.resume()}n.on("data",i),e.on("drain",o),e._isStdio||t&&!1===t.end||(n.on("end",a),n.on("close",u));var s=!1;function a(){s||(s=!0,e.end())}function u(){s||(s=!0,"function"==typeof e.destroy&&e.destroy())}function c(e){if(f(),0===r.listenerCount(this,"error"))throw e}function f(){n.removeListener("data",i),e.removeListener("drain",o),n.removeListener("end",a),n.removeListener("close",u),n.removeListener("error",c),e.removeListener("error",c),n.removeListener("end",f),n.removeListener("close",f),e.removeListener("close",f)}return n.on("error",c),e.on("error",c),n.on("end",f),n.on("close",f),e.on("close",f),e.emit("pipe",n),e}},function(e,t){},function(e,t,n){"use strict";var r=n(119).Buffer,i=n(288);e.exports=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},e.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},e.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n},e.prototype.concat=function(e){if(0===this.length)return r.alloc(0);if(1===this.length)return this.head.data;for(var t,n,i,o=r.allocUnsafe(e>>>0),s=this.head,a=0;s;)t=s.data,n=o,i=a,t.copy(n,i),a+=s.data.length,s=s.next;return o},e}(),i&&i.inspect&&i.inspect.custom&&(e.exports.prototype[i.inspect.custom]=function(){var e=i.inspect({length:this.length});return this.constructor.name+" "+e})},function(e,t){},function(e,t,n){(function(e){var r=void 0!==e&&e||"undefined"!=typeof self&&self||window,i=Function.prototype.apply;function o(e,t){this._id=e,this._clearFn=t}t.setTimeout=function(){return new o(i.call(setTimeout,r,arguments),clearTimeout)},t.setInterval=function(){return new o(i.call(setInterval,r,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e&&e.close()},o.prototype.unref=o.prototype.ref=function(){},o.prototype.close=function(){this._clearFn.call(r,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},n(290),t.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==e&&e.setImmediate||this&&this.setImmediate,t.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==e&&e.clearImmediate||this&&this.clearImmediate}).call(this,n(31))},function(e,t,n){(function(e,t){!function(e,n){"use strict";if(!e.setImmediate){var r,i,o,s,a,u=1,c={},f=!1,l=e.document,d=Object.getPrototypeOf&&Object.getPrototypeOf(e);d=d&&d.setTimeout?d:e,"[object process]"==={}.toString.call(e.process)?r=function(e){t.nextTick((function(){p(e)}))}:!function(){if(e.postMessage&&!e.importScripts){var t=!0,n=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=n,t}}()?e.MessageChannel?((o=new MessageChannel).port1.onmessage=function(e){p(e.data)},r=function(e){o.port2.postMessage(e)}):l&&"onreadystatechange"in l.createElement("script")?(i=l.documentElement,r=function(e){var t=l.createElement("script");t.onreadystatechange=function(){p(e),t.onreadystatechange=null,i.removeChild(t),t=null},i.appendChild(t)}):r=function(e){setTimeout(p,0,e)}:(s="setImmediate$"+Math.random()+"$",a=function(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(s)&&p(+t.data.slice(s.length))},e.addEventListener?e.addEventListener("message",a,!1):e.attachEvent("onmessage",a),r=function(t){e.postMessage(s+t,"*")}),d.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),n=0;n64?t=e(t):t.length<64&&(t=i.concat([t,s],64));for(var n=this._ipad=i.allocUnsafe(64),r=this._opad=i.allocUnsafe(64),a=0;a<64;a++)n[a]=54^t[a],r[a]=92^t[a];this._hash=[n]}r(a,o),a.prototype._update=function(e){this._hash.push(e)},a.prototype._final=function(){var e=this._alg(i.concat(this._hash));return this._alg(i.concat([this._opad,e]))},e.exports=a},function(e,t,n){e.exports=n(177)},function(e,t,n){(function(t,r){var i,o=n(8).Buffer,s=n(179),a=n(180),u=n(181),c=n(182),f=t.crypto&&t.crypto.subtle,l={sha:"SHA-1","sha-1":"SHA-1",sha1:"SHA-1",sha256:"SHA-256","sha-256":"SHA-256",sha384:"SHA-384","sha-384":"SHA-384","sha-512":"SHA-512",sha512:"SHA-512"},d=[];function h(e,t,n,r,i){return f.importKey("raw",e,{name:"PBKDF2"},!1,["deriveBits"]).then((function(e){return f.deriveBits({name:"PBKDF2",salt:t,iterations:n,hash:{name:i}},e,r<<3)})).then((function(e){return o.from(e)}))}e.exports=function(e,n,p,v,g,m){"function"==typeof g&&(m=g,g=void 0);var b=l[(g=g||"sha1").toLowerCase()];if(!b||"function"!=typeof t.Promise)return r.nextTick((function(){var t;try{t=u(e,n,p,v,g)}catch(e){return m(e)}m(null,t)}));if(s(p,v),e=c(e,a,"Password"),n=c(n,a,"Salt"),"function"!=typeof m)throw new Error("No callback provided to pbkdf2");!function(e,t){e.then((function(e){r.nextTick((function(){t(null,e)}))}),(function(e){r.nextTick((function(){t(e)}))}))}(function(e){if(t.process&&!t.process.browser)return Promise.resolve(!1);if(!f||!f.importKey||!f.deriveBits)return Promise.resolve(!1);if(void 0!==d[e])return d[e];var n=h(i=i||o.alloc(8),i,10,128,e).then((function(){return!0})).catch((function(){return!1}));return d[e]=n,n}(b).then((function(t){return t?h(e,n,p,v,b):u(e,n,p,v,g)})),m)}}).call(this,n(31),n(20))},function(e,t,n){var r=n(300),i=n(122),o=n(123),s=n(313),a=n(94);function u(e,t,n){if(e=e.toLowerCase(),o[e])return i.createCipheriv(e,t,n);if(s[e])return new r({key:t,iv:n,mode:e});throw new TypeError("invalid suite type")}function c(e,t,n){if(e=e.toLowerCase(),o[e])return i.createDecipheriv(e,t,n);if(s[e])return new r({key:t,iv:n,mode:e,decrypt:!0});throw new TypeError("invalid suite type")}t.createCipher=t.Cipher=function(e,t){var n,r;if(e=e.toLowerCase(),o[e])n=o[e].key,r=o[e].iv;else{if(!s[e])throw new TypeError("invalid suite type");n=8*s[e].key,r=s[e].iv}var i=a(t,!1,n,r);return u(e,i.key,i.iv)},t.createCipheriv=t.Cipheriv=u,t.createDecipher=t.Decipher=function(e,t){var n,r;if(e=e.toLowerCase(),o[e])n=o[e].key,r=o[e].iv;else{if(!s[e])throw new TypeError("invalid suite type");n=8*s[e].key,r=s[e].iv}var i=a(t,!1,n,r);return c(e,i.key,i.iv)},t.createDecipheriv=t.Decipheriv=c,t.listCiphers=t.getCiphers=function(){return Object.keys(s).concat(i.getCiphers())}},function(e,t,n){var r=n(56),i=n(301),o=n(7),s=n(8).Buffer,a={"des-ede3-cbc":i.CBC.instantiate(i.EDE),"des-ede3":i.EDE,"des-ede-cbc":i.CBC.instantiate(i.EDE),"des-ede":i.EDE,"des-cbc":i.CBC.instantiate(i.DES),"des-ecb":i.DES};function u(e){r.call(this);var t,n=e.mode.toLowerCase(),i=a[n];t=e.decrypt?"decrypt":"encrypt";var o=e.key;s.isBuffer(o)||(o=s.from(o)),"des-ede"!==n&&"des-ede-cbc"!==n||(o=s.concat([o,o.slice(0,8)]));var u=e.iv;s.isBuffer(u)||(u=s.from(u)),this._des=i.create({key:o,iv:u,type:t})}a.des=a["des-cbc"],a.des3=a["des-ede3-cbc"],e.exports=u,o(u,r),u.prototype._update=function(e){return s.from(this._des.update(e))},u.prototype._final=function(){return s.from(this._des.final())}},function(e,t,n){"use strict";t.utils=n(183),t.Cipher=n(121),t.DES=n(184),t.CBC=n(302),t.EDE=n(303)},function(e,t,n){"use strict";var r=n(46),i=n(7),o={};function s(e){r.equal(e.length,8,"Invalid IV length"),this.iv=new Array(8);for(var t=0;t15){var e=this.cache.slice(0,16);return this.cache=this.cache.slice(16),e}return null},d.prototype.flush=function(){for(var e=16-this.cache.length,t=o.allocUnsafe(e),n=-1;++n>s%8,e._prev=o(e._prev,n?r:i);return a}function o(e,t){var n=e.length,i=-1,o=r.allocUnsafe(e.length);for(e=r.concat([e,r.from([t])]);++i>7;return o}t.encrypt=function(e,t,n){for(var o=t.length,s=r.allocUnsafe(o),a=-1;++a>>0,0),t.writeUInt32BE(e[1]>>>0,4),t.writeUInt32BE(e[2]>>>0,8),t.writeUInt32BE(e[3]>>>0,12),t}function s(e){this.h=e,this.state=r.alloc(16,0),this.cache=r.allocUnsafe(0)}s.prototype.ghash=function(e){for(var t=-1;++t0;t--)r[t]=r[t]>>>1|(1&r[t-1])<<31;r[0]=r[0]>>>1,n&&(r[0]=r[0]^225<<24)}this.state=o(i)},s.prototype.update=function(e){var t;for(this.cache=r.concat([this.cache,e]);this.cache.length>=16;)t=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(t)},s.prototype.final=function(e,t){return this.cache.length&&this.ghash(r.concat([this.cache,i],16)),this.ghash(o([0,e,0,t])),this.state},e.exports=s},function(e,t,n){var r=n(188),i=n(8).Buffer,o=n(123),s=n(189),a=n(56),u=n(93),c=n(94);function f(e,t,n){a.call(this),this._cache=new l,this._last=void 0,this._cipher=new u.AES(t),this._prev=i.from(n),this._mode=e,this._autopadding=!0}function l(){this.cache=i.allocUnsafe(0)}function d(e,t,n){var a=o[e.toLowerCase()];if(!a)throw new TypeError("invalid suite type");if("string"==typeof n&&(n=i.from(n)),"GCM"!==a.mode&&n.length!==a.iv)throw new TypeError("invalid iv length "+n.length);if("string"==typeof t&&(t=i.from(t)),t.length!==a.key/8)throw new TypeError("invalid key length "+t.length);return"stream"===a.type?new s(a.module,t,n,!0):"auth"===a.type?new r(a.module,t,n,!0):new f(a.module,t,n)}n(7)(f,a),f.prototype._update=function(e){var t,n;this._cache.add(e);for(var r=[];t=this._cache.get(this._autopadding);)n=this._mode.decrypt(this,t),r.push(n);return i.concat(r)},f.prototype._final=function(){var e=this._cache.flush();if(this._autopadding)return function(e){var t=e[15];if(t<1||t>16)throw new Error("unable to decrypt data");var n=-1;for(;++n16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t}else if(this.cache.length>=16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t;return null},l.prototype.flush=function(){if(this.cache.length)return this.cache},t.createDecipher=function(e,t){var n=o[e.toLowerCase()];if(!n)throw new TypeError("invalid suite type");var r=c(t,!1,n.key,n.iv);return d(e,r.key,r.iv)},t.createDecipheriv=d},function(e,t){t["des-ecb"]={key:8,iv:0},t["des-cbc"]=t.des={key:8,iv:8},t["des-ede3-cbc"]=t.des3={key:24,iv:8},t["des-ede3"]={key:24,iv:0},t["des-ede-cbc"]={key:16,iv:8},t["des-ede"]={key:16,iv:0}},function(e,t,n){(function(e){var r=n(190),i=n(317),o=n(318);var s={binary:!0,hex:!0,base64:!0};t.DiffieHellmanGroup=t.createDiffieHellmanGroup=t.getDiffieHellman=function(t){var n=new e(i[t].prime,"hex"),r=new e(i[t].gen,"hex");return new o(n,r)},t.createDiffieHellman=t.DiffieHellman=function t(n,i,a,u){return e.isBuffer(i)||void 0===s[i]?t(n,"binary",i,a):(i=i||"binary",u=u||"binary",a=a||new e([2]),e.isBuffer(a)||(a=new e(a,u)),"number"==typeof n?new o(r(n,a),a,!0):(e.isBuffer(n)||(n=new e(n,i)),new o(n,a,!0)))}}).call(this,n(6).Buffer)},function(e,t){},function(e,t){},function(e){e.exports=JSON.parse('{"modp1":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},"modp2":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},"modp5":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},"modp14":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},"modp15":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},"modp16":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},"modp17":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},"modp18":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}')},function(e,t,n){(function(t){var r=n(29),i=new(n(191)),o=new r(24),s=new r(11),a=new r(10),u=new r(3),c=new r(7),f=n(190),l=n(66);function d(e,n){return n=n||"utf8",t.isBuffer(e)||(e=new t(e,n)),this._pub=new r(e),this}function h(e,n){return n=n||"utf8",t.isBuffer(e)||(e=new t(e,n)),this._priv=new r(e),this}e.exports=v;var p={};function v(e,t,n){this.setGenerator(t),this.__prime=new r(e),this._prime=r.mont(this.__prime),this._primeLen=e.length,this._pub=void 0,this._priv=void 0,this._primeCode=void 0,n?(this.setPublicKey=d,this.setPrivateKey=h):this._primeCode=8}function g(e,n){var r=new t(e.toArray());return n?r.toString(n):r}Object.defineProperty(v.prototype,"verifyError",{enumerable:!0,get:function(){return"number"!=typeof this._primeCode&&(this._primeCode=function(e,t){var n=t.toString("hex"),r=[n,e.toString(16)].join("_");if(r in p)return p[r];var l,d=0;if(e.isEven()||!f.simpleSieve||!f.fermatTest(e)||!i.test(e))return d+=1,d+="02"===n||"05"===n?8:4,p[r]=d,d;switch(i.test(e.shrn(1))||(d+=2),n){case"02":e.mod(o).cmp(s)&&(d+=8);break;case"05":(l=e.mod(a)).cmp(u)&&l.cmp(c)&&(d+=8);break;default:d+=4}return p[r]=d,d}(this.__prime,this.__gen)),this._primeCode}}),v.prototype.generateKeys=function(){return this._priv||(this._priv=new r(l(this._primeLen))),this._pub=this._gen.toRed(this._prime).redPow(this._priv).fromRed(),this.getPublicKey()},v.prototype.computeSecret=function(e){var n=(e=(e=new r(e)).toRed(this._prime)).redPow(this._priv).fromRed(),i=new t(n.toArray()),o=this.getPrime();if(i.length0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n}},{key:"concat",value:function(e){if(0===this.length)return s.alloc(0);for(var t,n,r,i=s.allocUnsafe(e>>>0),o=this.head,a=0;o;)t=o.data,n=i,r=a,s.prototype.copy.call(t,n,r),a+=o.data.length,o=o.next;return i}},{key:"consume",value:function(e,t){var n;return ei.length?i.length:e;if(o===i.length?r+=i:r+=i.slice(0,e),0==(e-=o)){o===i.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(o));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=s.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,o=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,o),0==(e-=o)){o===i.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=i.slice(o));break}++r}return this.length-=r,t}},{key:u,value:function(e,t){return a(this,function(e){for(var t=1;t0,(function(e){r||(r=e),e&&s.forEach(c),o||(s.forEach(c),i(r))}))}));return t.reduce(f)}},function(e,t,n){var r=n(8).Buffer,i=n(175),o=n(126),s=n(127).ec,a=n(203),u=n(96),c=n(209);function f(e,t,n,o){if((e=r.from(e.toArray())).length0&&n.ishrn(r),n}function d(e,t,n){var o,s;do{for(o=r.alloc(0);8*o.length=49&&c<=54?c-49+10:c>=17&&c<=22?c-17+10:c,s|=u}return r(!(240&s),"Invalid character in "+e),i}function u(e,t,n,i){for(var o=0,s=0,a=Math.min(e.length,n),u=t;u=49?c-49+10:c>=17?c-17+10:c,r(c>=0&&s0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,n){if("number"==typeof e)return this._initNumber(e,t,n);if("object"==typeof e)return this._initArray(e,t,n);"hex"===t&&(t=16),r(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&i++,16===t?this._parseHex(e,i):this._parseBase(e,t,i),"-"===e[0]&&(this.negative=1),this._strip(),"le"===n&&this._initArray(this.toArray(),t,n)},o.prototype._initNumber=function(e,t,n){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(r(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),t,n)},o.prototype._initArray=function(e,t,n){if(r("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)s=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=s<>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);else if("le"===n)for(i=0,o=0;i>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);return this._strip()},o.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var n=0;n=t;n-=6)i=a(e,n,n+6),this.words[r]|=i<>>26-o&4194303,(o+=24)>=26&&(o-=26,r++);n+6!==t&&(i=a(e,t,n+6),this.words[r]|=i<>>26-o&4194303),this._strip()},o.prototype._parseBase=function(e,t,n){this.words=[0],this.length=1;for(var r=0,i=1;i<=67108863;i*=t)r++;r--,i=i/t|0;for(var o=e.length-n,s=o%r,a=Math.min(o,o-s)+n,c=0,f=n;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{o.prototype[Symbol.for("nodejs.util.inspect.custom")]=f}catch(e){o.prototype.inspect=f}else o.prototype.inspect=f;function f(){return(this.red?""}var l=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],d=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];o.prototype.toString=function(e,t){var n;if(t=0|t||1,16===(e=e||10)||"hex"===e){n="";for(var i=0,o=0,s=0;s>>24-i&16777215)||s!==this.length-1?l[6-u.length]+u+n:u+n,(i+=2)>=26&&(i-=26,s--)}for(0!==o&&(n=o.toString(16)+n);n.length%t!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(e===(0|e)&&e>=2&&e<=36){var c=d[e],f=h[e];n="";var p=this.clone();for(p.negative=0;!p.isZero();){var v=p.modrn(f).toString(e);n=(p=p.idivn(f)).isZero()?v+n:l[c-v.length]+v+n}for(this.isZero()&&(n="0"+n);n.length%t!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16,2)},s&&(o.prototype.toBuffer=function(e,t){return this.toArrayLike(s,e,t)}),o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)};function p(e,t,n){n.negative=t.negative^e.negative;var r=e.length+t.length|0;n.length=r,r=r-1|0;var i=0|e.words[0],o=0|t.words[0],s=i*o,a=67108863&s,u=s/67108864|0;n.words[0]=a;for(var c=1;c>>26,l=67108863&u,d=Math.min(c,t.length-1),h=Math.max(0,c-e.length+1);h<=d;h++){var p=c-h|0;f+=(s=(i=0|e.words[p])*(o=0|t.words[h])+l)/67108864|0,l=67108863&s}n.words[c]=0|l,u=0|f}return 0!==u?n.words[c]=0|u:n.length--,n._strip()}o.prototype.toArrayLike=function(e,t,n){this._strip();var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0");var s=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,o);return this["_toArrayLike"+("le"===t?"LE":"BE")](s,i),s},o.prototype._toArrayLikeLE=function(e,t){for(var n=0,r=0,i=0,o=0;i>8&255),n>16&255),6===o?(n>24&255),r=0,o=0):(r=s>>>24,o+=2)}if(n=0&&(e[n--]=s>>8&255),n>=0&&(e[n--]=s>>16&255),6===o?(n>=0&&(e[n--]=s>>24&255),r=0,o=0):(r=s>>>24,o+=2)}if(n>=0)for(e[n--]=r;n>=0;)e[n--]=0},Math.clz32?o.prototype._countBits=function(e){return 32-Math.clz32(e)}:o.prototype._countBits=function(e){var t=e,n=0;return t>=4096&&(n+=13,t>>>=13),t>=64&&(n+=7,t>>>=7),t>=8&&(n+=4,t>>>=4),t>=2&&(n+=2,t>>>=2),n+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,n=0;return 0==(8191&t)&&(n+=13,t>>>=13),0==(127&t)&&(n+=7,t>>>=7),0==(15&t)&&(n+=4,t>>>=4),0==(3&t)&&(n+=2,t>>>=2),0==(1&t)&&n++,n},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var n=0;ne.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,n;this.length>e.length?(t=this,n=e):(t=e,n=this);for(var r=0;re.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){r("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),n=e%26;this._expand(t),n>0&&t--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this._strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){r("number"==typeof e&&e>=0);var n=e/26|0,i=e%26;return this._expand(n+1),this.words[n]=t?this.words[n]|1<e.length?(n=this,r=e):(n=e,r=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=n.length,0!==i)this.words[this.length]=i,this.length++;else if(n!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var n,r,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(n=this,r=e):(n=e,r=this);for(var o=0,s=0;s>26,this.words[s]=67108863&t;for(;0!==o&&s>26,this.words[s]=67108863&t;if(0===o&&s>>13,h=0|s[1],p=8191&h,v=h>>>13,g=0|s[2],m=8191&g,b=g>>>13,y=0|s[3],w=8191&y,_=y>>>13,S=0|s[4],E=8191&S,M=S>>>13,A=0|s[5],I=8191&A,k=A>>>13,O=0|s[6],x=8191&O,C=O>>>13,T=0|s[7],P=8191&T,N=T>>>13,R=0|s[8],L=8191&R,j=R>>>13,D=0|s[9],U=8191&D,B=D>>>13,F=0|a[0],z=8191&F,q=F>>>13,K=0|a[1],H=8191&K,V=K>>>13,G=0|a[2],W=8191&G,$=G>>>13,Y=0|a[3],J=8191&Y,Z=Y>>>13,X=0|a[4],Q=8191&X,ee=X>>>13,te=0|a[5],ne=8191&te,re=te>>>13,ie=0|a[6],oe=8191&ie,se=ie>>>13,ae=0|a[7],ue=8191&ae,ce=ae>>>13,fe=0|a[8],le=8191&fe,de=fe>>>13,he=0|a[9],pe=8191&he,ve=he>>>13;n.negative=e.negative^t.negative,n.length=19;var ge=(c+(r=Math.imul(l,z))|0)+((8191&(i=(i=Math.imul(l,q))+Math.imul(d,z)|0))<<13)|0;c=((o=Math.imul(d,q))+(i>>>13)|0)+(ge>>>26)|0,ge&=67108863,r=Math.imul(p,z),i=(i=Math.imul(p,q))+Math.imul(v,z)|0,o=Math.imul(v,q);var me=(c+(r=r+Math.imul(l,H)|0)|0)+((8191&(i=(i=i+Math.imul(l,V)|0)+Math.imul(d,H)|0))<<13)|0;c=((o=o+Math.imul(d,V)|0)+(i>>>13)|0)+(me>>>26)|0,me&=67108863,r=Math.imul(m,z),i=(i=Math.imul(m,q))+Math.imul(b,z)|0,o=Math.imul(b,q),r=r+Math.imul(p,H)|0,i=(i=i+Math.imul(p,V)|0)+Math.imul(v,H)|0,o=o+Math.imul(v,V)|0;var be=(c+(r=r+Math.imul(l,W)|0)|0)+((8191&(i=(i=i+Math.imul(l,$)|0)+Math.imul(d,W)|0))<<13)|0;c=((o=o+Math.imul(d,$)|0)+(i>>>13)|0)+(be>>>26)|0,be&=67108863,r=Math.imul(w,z),i=(i=Math.imul(w,q))+Math.imul(_,z)|0,o=Math.imul(_,q),r=r+Math.imul(m,H)|0,i=(i=i+Math.imul(m,V)|0)+Math.imul(b,H)|0,o=o+Math.imul(b,V)|0,r=r+Math.imul(p,W)|0,i=(i=i+Math.imul(p,$)|0)+Math.imul(v,W)|0,o=o+Math.imul(v,$)|0;var ye=(c+(r=r+Math.imul(l,J)|0)|0)+((8191&(i=(i=i+Math.imul(l,Z)|0)+Math.imul(d,J)|0))<<13)|0;c=((o=o+Math.imul(d,Z)|0)+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,r=Math.imul(E,z),i=(i=Math.imul(E,q))+Math.imul(M,z)|0,o=Math.imul(M,q),r=r+Math.imul(w,H)|0,i=(i=i+Math.imul(w,V)|0)+Math.imul(_,H)|0,o=o+Math.imul(_,V)|0,r=r+Math.imul(m,W)|0,i=(i=i+Math.imul(m,$)|0)+Math.imul(b,W)|0,o=o+Math.imul(b,$)|0,r=r+Math.imul(p,J)|0,i=(i=i+Math.imul(p,Z)|0)+Math.imul(v,J)|0,o=o+Math.imul(v,Z)|0;var we=(c+(r=r+Math.imul(l,Q)|0)|0)+((8191&(i=(i=i+Math.imul(l,ee)|0)+Math.imul(d,Q)|0))<<13)|0;c=((o=o+Math.imul(d,ee)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,r=Math.imul(I,z),i=(i=Math.imul(I,q))+Math.imul(k,z)|0,o=Math.imul(k,q),r=r+Math.imul(E,H)|0,i=(i=i+Math.imul(E,V)|0)+Math.imul(M,H)|0,o=o+Math.imul(M,V)|0,r=r+Math.imul(w,W)|0,i=(i=i+Math.imul(w,$)|0)+Math.imul(_,W)|0,o=o+Math.imul(_,$)|0,r=r+Math.imul(m,J)|0,i=(i=i+Math.imul(m,Z)|0)+Math.imul(b,J)|0,o=o+Math.imul(b,Z)|0,r=r+Math.imul(p,Q)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,ee)|0;var _e=(c+(r=r+Math.imul(l,ne)|0)|0)+((8191&(i=(i=i+Math.imul(l,re)|0)+Math.imul(d,ne)|0))<<13)|0;c=((o=o+Math.imul(d,re)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,r=Math.imul(x,z),i=(i=Math.imul(x,q))+Math.imul(C,z)|0,o=Math.imul(C,q),r=r+Math.imul(I,H)|0,i=(i=i+Math.imul(I,V)|0)+Math.imul(k,H)|0,o=o+Math.imul(k,V)|0,r=r+Math.imul(E,W)|0,i=(i=i+Math.imul(E,$)|0)+Math.imul(M,W)|0,o=o+Math.imul(M,$)|0,r=r+Math.imul(w,J)|0,i=(i=i+Math.imul(w,Z)|0)+Math.imul(_,J)|0,o=o+Math.imul(_,Z)|0,r=r+Math.imul(m,Q)|0,i=(i=i+Math.imul(m,ee)|0)+Math.imul(b,Q)|0,o=o+Math.imul(b,ee)|0,r=r+Math.imul(p,ne)|0,i=(i=i+Math.imul(p,re)|0)+Math.imul(v,ne)|0,o=o+Math.imul(v,re)|0;var Se=(c+(r=r+Math.imul(l,oe)|0)|0)+((8191&(i=(i=i+Math.imul(l,se)|0)+Math.imul(d,oe)|0))<<13)|0;c=((o=o+Math.imul(d,se)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,r=Math.imul(P,z),i=(i=Math.imul(P,q))+Math.imul(N,z)|0,o=Math.imul(N,q),r=r+Math.imul(x,H)|0,i=(i=i+Math.imul(x,V)|0)+Math.imul(C,H)|0,o=o+Math.imul(C,V)|0,r=r+Math.imul(I,W)|0,i=(i=i+Math.imul(I,$)|0)+Math.imul(k,W)|0,o=o+Math.imul(k,$)|0,r=r+Math.imul(E,J)|0,i=(i=i+Math.imul(E,Z)|0)+Math.imul(M,J)|0,o=o+Math.imul(M,Z)|0,r=r+Math.imul(w,Q)|0,i=(i=i+Math.imul(w,ee)|0)+Math.imul(_,Q)|0,o=o+Math.imul(_,ee)|0,r=r+Math.imul(m,ne)|0,i=(i=i+Math.imul(m,re)|0)+Math.imul(b,ne)|0,o=o+Math.imul(b,re)|0,r=r+Math.imul(p,oe)|0,i=(i=i+Math.imul(p,se)|0)+Math.imul(v,oe)|0,o=o+Math.imul(v,se)|0;var Ee=(c+(r=r+Math.imul(l,ue)|0)|0)+((8191&(i=(i=i+Math.imul(l,ce)|0)+Math.imul(d,ue)|0))<<13)|0;c=((o=o+Math.imul(d,ce)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,r=Math.imul(L,z),i=(i=Math.imul(L,q))+Math.imul(j,z)|0,o=Math.imul(j,q),r=r+Math.imul(P,H)|0,i=(i=i+Math.imul(P,V)|0)+Math.imul(N,H)|0,o=o+Math.imul(N,V)|0,r=r+Math.imul(x,W)|0,i=(i=i+Math.imul(x,$)|0)+Math.imul(C,W)|0,o=o+Math.imul(C,$)|0,r=r+Math.imul(I,J)|0,i=(i=i+Math.imul(I,Z)|0)+Math.imul(k,J)|0,o=o+Math.imul(k,Z)|0,r=r+Math.imul(E,Q)|0,i=(i=i+Math.imul(E,ee)|0)+Math.imul(M,Q)|0,o=o+Math.imul(M,ee)|0,r=r+Math.imul(w,ne)|0,i=(i=i+Math.imul(w,re)|0)+Math.imul(_,ne)|0,o=o+Math.imul(_,re)|0,r=r+Math.imul(m,oe)|0,i=(i=i+Math.imul(m,se)|0)+Math.imul(b,oe)|0,o=o+Math.imul(b,se)|0,r=r+Math.imul(p,ue)|0,i=(i=i+Math.imul(p,ce)|0)+Math.imul(v,ue)|0,o=o+Math.imul(v,ce)|0;var Me=(c+(r=r+Math.imul(l,le)|0)|0)+((8191&(i=(i=i+Math.imul(l,de)|0)+Math.imul(d,le)|0))<<13)|0;c=((o=o+Math.imul(d,de)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,r=Math.imul(U,z),i=(i=Math.imul(U,q))+Math.imul(B,z)|0,o=Math.imul(B,q),r=r+Math.imul(L,H)|0,i=(i=i+Math.imul(L,V)|0)+Math.imul(j,H)|0,o=o+Math.imul(j,V)|0,r=r+Math.imul(P,W)|0,i=(i=i+Math.imul(P,$)|0)+Math.imul(N,W)|0,o=o+Math.imul(N,$)|0,r=r+Math.imul(x,J)|0,i=(i=i+Math.imul(x,Z)|0)+Math.imul(C,J)|0,o=o+Math.imul(C,Z)|0,r=r+Math.imul(I,Q)|0,i=(i=i+Math.imul(I,ee)|0)+Math.imul(k,Q)|0,o=o+Math.imul(k,ee)|0,r=r+Math.imul(E,ne)|0,i=(i=i+Math.imul(E,re)|0)+Math.imul(M,ne)|0,o=o+Math.imul(M,re)|0,r=r+Math.imul(w,oe)|0,i=(i=i+Math.imul(w,se)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,se)|0,r=r+Math.imul(m,ue)|0,i=(i=i+Math.imul(m,ce)|0)+Math.imul(b,ue)|0,o=o+Math.imul(b,ce)|0,r=r+Math.imul(p,le)|0,i=(i=i+Math.imul(p,de)|0)+Math.imul(v,le)|0,o=o+Math.imul(v,de)|0;var Ae=(c+(r=r+Math.imul(l,pe)|0)|0)+((8191&(i=(i=i+Math.imul(l,ve)|0)+Math.imul(d,pe)|0))<<13)|0;c=((o=o+Math.imul(d,ve)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,r=Math.imul(U,H),i=(i=Math.imul(U,V))+Math.imul(B,H)|0,o=Math.imul(B,V),r=r+Math.imul(L,W)|0,i=(i=i+Math.imul(L,$)|0)+Math.imul(j,W)|0,o=o+Math.imul(j,$)|0,r=r+Math.imul(P,J)|0,i=(i=i+Math.imul(P,Z)|0)+Math.imul(N,J)|0,o=o+Math.imul(N,Z)|0,r=r+Math.imul(x,Q)|0,i=(i=i+Math.imul(x,ee)|0)+Math.imul(C,Q)|0,o=o+Math.imul(C,ee)|0,r=r+Math.imul(I,ne)|0,i=(i=i+Math.imul(I,re)|0)+Math.imul(k,ne)|0,o=o+Math.imul(k,re)|0,r=r+Math.imul(E,oe)|0,i=(i=i+Math.imul(E,se)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,se)|0,r=r+Math.imul(w,ue)|0,i=(i=i+Math.imul(w,ce)|0)+Math.imul(_,ue)|0,o=o+Math.imul(_,ce)|0,r=r+Math.imul(m,le)|0,i=(i=i+Math.imul(m,de)|0)+Math.imul(b,le)|0,o=o+Math.imul(b,de)|0;var Ie=(c+(r=r+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,ve)|0)+Math.imul(v,pe)|0))<<13)|0;c=((o=o+Math.imul(v,ve)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,r=Math.imul(U,W),i=(i=Math.imul(U,$))+Math.imul(B,W)|0,o=Math.imul(B,$),r=r+Math.imul(L,J)|0,i=(i=i+Math.imul(L,Z)|0)+Math.imul(j,J)|0,o=o+Math.imul(j,Z)|0,r=r+Math.imul(P,Q)|0,i=(i=i+Math.imul(P,ee)|0)+Math.imul(N,Q)|0,o=o+Math.imul(N,ee)|0,r=r+Math.imul(x,ne)|0,i=(i=i+Math.imul(x,re)|0)+Math.imul(C,ne)|0,o=o+Math.imul(C,re)|0,r=r+Math.imul(I,oe)|0,i=(i=i+Math.imul(I,se)|0)+Math.imul(k,oe)|0,o=o+Math.imul(k,se)|0,r=r+Math.imul(E,ue)|0,i=(i=i+Math.imul(E,ce)|0)+Math.imul(M,ue)|0,o=o+Math.imul(M,ce)|0,r=r+Math.imul(w,le)|0,i=(i=i+Math.imul(w,de)|0)+Math.imul(_,le)|0,o=o+Math.imul(_,de)|0;var ke=(c+(r=r+Math.imul(m,pe)|0)|0)+((8191&(i=(i=i+Math.imul(m,ve)|0)+Math.imul(b,pe)|0))<<13)|0;c=((o=o+Math.imul(b,ve)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,r=Math.imul(U,J),i=(i=Math.imul(U,Z))+Math.imul(B,J)|0,o=Math.imul(B,Z),r=r+Math.imul(L,Q)|0,i=(i=i+Math.imul(L,ee)|0)+Math.imul(j,Q)|0,o=o+Math.imul(j,ee)|0,r=r+Math.imul(P,ne)|0,i=(i=i+Math.imul(P,re)|0)+Math.imul(N,ne)|0,o=o+Math.imul(N,re)|0,r=r+Math.imul(x,oe)|0,i=(i=i+Math.imul(x,se)|0)+Math.imul(C,oe)|0,o=o+Math.imul(C,se)|0,r=r+Math.imul(I,ue)|0,i=(i=i+Math.imul(I,ce)|0)+Math.imul(k,ue)|0,o=o+Math.imul(k,ce)|0,r=r+Math.imul(E,le)|0,i=(i=i+Math.imul(E,de)|0)+Math.imul(M,le)|0,o=o+Math.imul(M,de)|0;var Oe=(c+(r=r+Math.imul(w,pe)|0)|0)+((8191&(i=(i=i+Math.imul(w,ve)|0)+Math.imul(_,pe)|0))<<13)|0;c=((o=o+Math.imul(_,ve)|0)+(i>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,r=Math.imul(U,Q),i=(i=Math.imul(U,ee))+Math.imul(B,Q)|0,o=Math.imul(B,ee),r=r+Math.imul(L,ne)|0,i=(i=i+Math.imul(L,re)|0)+Math.imul(j,ne)|0,o=o+Math.imul(j,re)|0,r=r+Math.imul(P,oe)|0,i=(i=i+Math.imul(P,se)|0)+Math.imul(N,oe)|0,o=o+Math.imul(N,se)|0,r=r+Math.imul(x,ue)|0,i=(i=i+Math.imul(x,ce)|0)+Math.imul(C,ue)|0,o=o+Math.imul(C,ce)|0,r=r+Math.imul(I,le)|0,i=(i=i+Math.imul(I,de)|0)+Math.imul(k,le)|0,o=o+Math.imul(k,de)|0;var xe=(c+(r=r+Math.imul(E,pe)|0)|0)+((8191&(i=(i=i+Math.imul(E,ve)|0)+Math.imul(M,pe)|0))<<13)|0;c=((o=o+Math.imul(M,ve)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,r=Math.imul(U,ne),i=(i=Math.imul(U,re))+Math.imul(B,ne)|0,o=Math.imul(B,re),r=r+Math.imul(L,oe)|0,i=(i=i+Math.imul(L,se)|0)+Math.imul(j,oe)|0,o=o+Math.imul(j,se)|0,r=r+Math.imul(P,ue)|0,i=(i=i+Math.imul(P,ce)|0)+Math.imul(N,ue)|0,o=o+Math.imul(N,ce)|0,r=r+Math.imul(x,le)|0,i=(i=i+Math.imul(x,de)|0)+Math.imul(C,le)|0,o=o+Math.imul(C,de)|0;var Ce=(c+(r=r+Math.imul(I,pe)|0)|0)+((8191&(i=(i=i+Math.imul(I,ve)|0)+Math.imul(k,pe)|0))<<13)|0;c=((o=o+Math.imul(k,ve)|0)+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,r=Math.imul(U,oe),i=(i=Math.imul(U,se))+Math.imul(B,oe)|0,o=Math.imul(B,se),r=r+Math.imul(L,ue)|0,i=(i=i+Math.imul(L,ce)|0)+Math.imul(j,ue)|0,o=o+Math.imul(j,ce)|0,r=r+Math.imul(P,le)|0,i=(i=i+Math.imul(P,de)|0)+Math.imul(N,le)|0,o=o+Math.imul(N,de)|0;var Te=(c+(r=r+Math.imul(x,pe)|0)|0)+((8191&(i=(i=i+Math.imul(x,ve)|0)+Math.imul(C,pe)|0))<<13)|0;c=((o=o+Math.imul(C,ve)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,r=Math.imul(U,ue),i=(i=Math.imul(U,ce))+Math.imul(B,ue)|0,o=Math.imul(B,ce),r=r+Math.imul(L,le)|0,i=(i=i+Math.imul(L,de)|0)+Math.imul(j,le)|0,o=o+Math.imul(j,de)|0;var Pe=(c+(r=r+Math.imul(P,pe)|0)|0)+((8191&(i=(i=i+Math.imul(P,ve)|0)+Math.imul(N,pe)|0))<<13)|0;c=((o=o+Math.imul(N,ve)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,r=Math.imul(U,le),i=(i=Math.imul(U,de))+Math.imul(B,le)|0,o=Math.imul(B,de);var Ne=(c+(r=r+Math.imul(L,pe)|0)|0)+((8191&(i=(i=i+Math.imul(L,ve)|0)+Math.imul(j,pe)|0))<<13)|0;c=((o=o+Math.imul(j,ve)|0)+(i>>>13)|0)+(Ne>>>26)|0,Ne&=67108863;var Re=(c+(r=Math.imul(U,pe))|0)+((8191&(i=(i=Math.imul(U,ve))+Math.imul(B,pe)|0))<<13)|0;return c=((o=Math.imul(B,ve))+(i>>>13)|0)+(Re>>>26)|0,Re&=67108863,u[0]=ge,u[1]=me,u[2]=be,u[3]=ye,u[4]=we,u[5]=_e,u[6]=Se,u[7]=Ee,u[8]=Me,u[9]=Ae,u[10]=Ie,u[11]=ke,u[12]=Oe,u[13]=xe,u[14]=Ce,u[15]=Te,u[16]=Pe,u[17]=Ne,u[18]=Re,0!==c&&(u[19]=c,n.length++),n};function g(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var r=0,i=0,o=0;o>>26)|0)>>>26,s&=67108863}n.words[o]=a,r=s,s=i}return 0!==r?n.words[o]=r:n.length--,n._strip()}function m(e,t,n){return g(e,t,n)}function b(e,t){this.x=e,this.y=t}Math.imul||(v=p),o.prototype.mulTo=function(e,t){var n=this.length+e.length;return 10===this.length&&10===e.length?v(this,e,t):n<63?p(this,e,t):n<1024?g(this,e,t):m(this,e,t)},b.prototype.makeRBT=function(e){for(var t=new Array(e),n=o.prototype._countBits(e)-1,r=0;r>=1;return r},b.prototype.permute=function(e,t,n,r,i,o){for(var s=0;s>>=1)i++;return 1<>>=13,n[2*s+1]=8191&o,o>>>=13;for(s=2*t;s>=26,n+=o/67108864|0,n+=s>>>26,this.words[i]=67108863&s}return 0!==n&&(this.words[i]=n,this.length++),t?this.ineg():this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),n=0;n>>i&1}return t}(e);if(0===t.length)return new o(1);for(var n=this,r=0;r=0);var t,n=e%26,i=(e-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var s=0;for(t=0;t>>26-n}s&&(this.words[t]=s,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t=0),i=t?(t-t%26)/26:0;var o=e%26,s=Math.min((e-o)/26,this.length),a=67108863^67108863>>>o<s)for(this.length-=s,c=0;c=0&&(0!==f||c>=i);c--){var l=0|this.words[c];this.words[c]=f<<26-o|l>>>o,f=l&a}return u&&0!==f&&(u.words[u.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},o.prototype.ishrn=function(e,t,n){return r(0===this.negative),this.iushrn(e,t,n)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){r("number"==typeof e&&e>=0);var t=e%26,n=(e-t)/26,i=1<=0);var t=e%26,n=(e-t)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==t&&n++,this.length=Math.min(n,this.length),0!==t){var i=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(r("number"==typeof e),r(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(u/67108864|0),this.words[i+n]=67108863&o}for(;i>26,this.words[i+n]=67108863&o;if(0===a)return this._strip();for(r(-1===a),a=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this._strip()},o.prototype._wordDiv=function(e,t){var n=(this.length,e.length),r=this.clone(),i=e,s=0|i.words[i.length-1];0!==(n=26-this._countBits(s))&&(i=i.ushln(n),r.iushln(n),s=0|i.words[i.length-1]);var a,u=r.length-i.length;if("mod"!==t){(a=new o(null)).length=u+1,a.words=new Array(a.length);for(var c=0;c=0;l--){var d=67108864*(0|r.words[i.length+l])+(0|r.words[i.length+l-1]);for(d=Math.min(d/s|0,67108863),r._ishlnsubmul(i,d,l);0!==r.negative;)d--,r.negative=0,r._ishlnsubmul(i,1,l),r.isZero()||(r.negative^=1);a&&(a.words[l]=d)}return a&&a._strip(),r._strip(),"div"!==t&&0!==n&&r.iushrn(n),{div:a||null,mod:r}},o.prototype.divmod=function(e,t,n){return r(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(i=a.div.neg()),"div"!==t&&(s=a.mod.neg(),n&&0!==s.negative&&s.iadd(e)),{div:i,mod:s}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(i=a.div.neg()),{div:i,mod:a.mod}):0!=(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(s=a.mod.neg(),n&&0!==s.negative&&s.isub(e)),{div:a.div,mod:s}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modrn(e.words[0]))}:this._wordDiv(e,t);var i,s,a},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var n=0!==t.div.negative?t.mod.isub(e):t.mod,r=e.ushrn(1),i=e.andln(1),o=n.cmp(r);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modrn=function(e){var t=e<0;t&&(e=-e),r(e<=67108863);for(var n=(1<<26)%e,i=0,o=this.length-1;o>=0;o--)i=(n*i+(0|this.words[o]))%e;return t?-i:i},o.prototype.modn=function(e){return this.modrn(e)},o.prototype.idivn=function(e){var t=e<0;t&&(e=-e),r(e<=67108863);for(var n=0,i=this.length-1;i>=0;i--){var o=(0|this.words[i])+67108864*n;this.words[i]=o/e|0,n=o%e}return this._strip(),t?this.ineg():this},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){r(0===e.negative),r(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),s=new o(0),a=new o(0),u=new o(1),c=0;t.isEven()&&n.isEven();)t.iushrn(1),n.iushrn(1),++c;for(var f=n.clone(),l=t.clone();!t.isZero();){for(var d=0,h=1;0==(t.words[0]&h)&&d<26;++d,h<<=1);if(d>0)for(t.iushrn(d);d-- >0;)(i.isOdd()||s.isOdd())&&(i.iadd(f),s.isub(l)),i.iushrn(1),s.iushrn(1);for(var p=0,v=1;0==(n.words[0]&v)&&p<26;++p,v<<=1);if(p>0)for(n.iushrn(p);p-- >0;)(a.isOdd()||u.isOdd())&&(a.iadd(f),u.isub(l)),a.iushrn(1),u.iushrn(1);t.cmp(n)>=0?(t.isub(n),i.isub(a),s.isub(u)):(n.isub(t),a.isub(i),u.isub(s))}return{a:a,b:u,gcd:n.iushln(c)}},o.prototype._invmp=function(e){r(0===e.negative),r(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,s=new o(1),a=new o(0),u=n.clone();t.cmpn(1)>0&&n.cmpn(1)>0;){for(var c=0,f=1;0==(t.words[0]&f)&&c<26;++c,f<<=1);if(c>0)for(t.iushrn(c);c-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);for(var l=0,d=1;0==(n.words[0]&d)&&l<26;++l,d<<=1);if(l>0)for(n.iushrn(l);l-- >0;)a.isOdd()&&a.iadd(u),a.iushrn(1);t.cmp(n)>=0?(t.isub(n),s.isub(a)):(n.isub(t),a.isub(s))}return(i=0===t.cmpn(1)?s:a).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),n=e.clone();t.negative=0,n.negative=0;for(var r=0;t.isEven()&&n.isEven();r++)t.iushrn(1),n.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;n.isEven();)n.iushrn(1);var i=t.cmp(n);if(i<0){var o=t;t=n,n=o}else if(0===i||0===n.cmpn(1))break;t.isub(n)}return n.iushln(r)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){r("number"==typeof e);var t=e%26,n=(e-t)/26,i=1<>>26,a&=67108863,this.words[s]=a}return 0!==o&&(this.words[s]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,n=e<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this._strip(),this.length>1)t=1;else{n&&(e=-e),r(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:ie.length)return 1;if(this.length=0;n--){var r=0|this.words[n],i=0|e.words[n];if(r!==i){ri&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new A(e)},o.prototype.toRed=function(e){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return r(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return r(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var y={k256:null,p224:null,p192:null,p25519:null};function w(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function _(){w.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function S(){w.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function E(){w.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function M(){w.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function A(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else r(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function I(e){A.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}w.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},w.prototype.ireduce=function(e){var t,n=e;do{this.split(n,this.tmp),t=(n=(n=this.imulK(n)).iadd(this.tmp)).bitLength()}while(t>this.n);var r=t0?n.isub(this.p):void 0!==n.strip?n.strip():n._strip(),n},w.prototype.split=function(e,t){e.iushrn(this.n,0,t)},w.prototype.imulK=function(e){return e.imul(this.k)},i(_,w),_.prototype.split=function(e,t){for(var n=Math.min(e.length,9),r=0;r>>22,i=o}i>>>=22,e.words[r-10]=i,0===i&&e.length>10?e.length-=10:e.length-=9},_.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,n=0;n>>=26,e.words[n]=i,t=r}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(y[e])return y[e];var t;if("k256"===e)t=new _;else if("p224"===e)t=new S;else if("p192"===e)t=new E;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new M}return y[e]=t,t},A.prototype._verify1=function(e){r(0===e.negative,"red works only with positives"),r(e.red,"red works only with red numbers")},A.prototype._verify2=function(e,t){r(0==(e.negative|t.negative),"red works only with positives"),r(e.red&&e.red===t.red,"red works only with red numbers")},A.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(c(e,e.umod(this.m)._forceRed(this)),e)},A.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},A.prototype.add=function(e,t){this._verify2(e,t);var n=e.add(t);return n.cmp(this.m)>=0&&n.isub(this.m),n._forceRed(this)},A.prototype.iadd=function(e,t){this._verify2(e,t);var n=e.iadd(t);return n.cmp(this.m)>=0&&n.isub(this.m),n},A.prototype.sub=function(e,t){this._verify2(e,t);var n=e.sub(t);return n.cmpn(0)<0&&n.iadd(this.m),n._forceRed(this)},A.prototype.isub=function(e,t){this._verify2(e,t);var n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n},A.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},A.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},A.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},A.prototype.isqr=function(e){return this.imul(e,e.clone())},A.prototype.sqr=function(e){return this.mul(e,e)},A.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(r(t%2==1),3===t){var n=this.m.add(new o(1)).iushrn(2);return this.pow(e,n)}for(var i=this.m.subn(1),s=0;!i.isZero()&&0===i.andln(1);)s++,i.iushrn(1);r(!i.isZero());var a=new o(1).toRed(this),u=a.redNeg(),c=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new o(2*f*f).toRed(this);0!==this.pow(f,c).cmp(u);)f.redIAdd(u);for(var l=this.pow(f,i),d=this.pow(e,i.addn(1).iushrn(1)),h=this.pow(e,i),p=s;0!==h.cmp(a);){for(var v=h,g=0;0!==v.cmp(a);g++)v=v.redSqr();r(g=0;r--){for(var c=t.words[r],f=u-1;f>=0;f--){var l=c>>f&1;i!==n[0]&&(i=this.sqr(i)),0!==l||0!==s?(s<<=1,s|=l,(4===++a||0===r&&0===f)&&(i=this.mul(i,n[s]),a=0,s=0)):a=0}u=26}return i},A.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},A.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new I(e)},i(I,A),I.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},I.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},I.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var n=e.imul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=n.isub(r).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},I.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var n=e.mul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=n.isub(r).iushrn(this.shift),s=i;return i.cmp(this.m)>=0?s=i.isub(this.m):i.cmpn(0)<0&&(s=i.iadd(this.m)),s._forceRed(this)},I.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(e,this)}).call(this,n(57)(e))},function(e,t){},function(e){e.exports=JSON.parse('{"name":"elliptic","version":"6.5.4","description":"EC cryptography","main":"lib/elliptic.js","files":["lib"],"scripts":{"lint":"eslint lib test","lint:fix":"npm run lint -- --fix","unit":"istanbul test _mocha --reporter=spec test/index.js","test":"npm run lint && npm run unit","version":"grunt dist && git add dist/"},"repository":{"type":"git","url":"git@github.com:indutny/elliptic"},"keywords":["EC","Elliptic","curve","Cryptography"],"author":"Fedor Indutny ","license":"MIT","bugs":{"url":"https://github.com/indutny/elliptic/issues"},"homepage":"https://github.com/indutny/elliptic","devDependencies":{"brfs":"^2.0.2","coveralls":"^3.1.0","eslint":"^7.6.0","grunt":"^1.2.1","grunt-browserify":"^5.3.0","grunt-cli":"^1.3.2","grunt-contrib-connect":"^3.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^5.0.0","grunt-mocha-istanbul":"^5.0.2","grunt-saucelabs":"^9.0.1","istanbul":"^0.4.5","mocha":"^8.0.1"},"dependencies":{"bn.js":"^4.11.9","brorand":"^1.1.0","hash.js":"^1.0.0","hmac-drbg":"^1.0.1","inherits":"^2.0.4","minimalistic-assert":"^1.0.1","minimalistic-crypto-utils":"^1.0.1"}}')},function(e,t,n){"use strict";var r=n(47),i=n(29),o=n(7),s=n(95),a=r.assert;function u(e){s.call(this,"short",e),this.a=new i(e.a,16).toRed(this.red),this.b=new i(e.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(e),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}function c(e,t,n,r){s.BasePoint.call(this,e,"affine"),null===t&&null===n?(this.x=null,this.y=null,this.inf=!0):(this.x=new i(t,16),this.y=new i(n,16),r&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}function f(e,t,n,r){s.BasePoint.call(this,e,"jacobian"),null===t&&null===n&&null===r?(this.x=this.curve.one,this.y=this.curve.one,this.z=new i(0)):(this.x=new i(t,16),this.y=new i(n,16),this.z=new i(r,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}o(u,s),e.exports=u,u.prototype._getEndomorphism=function(e){if(this.zeroA&&this.g&&this.n&&1===this.p.modn(3)){var t,n;if(e.beta)t=new i(e.beta,16).toRed(this.red);else{var r=this._getEndoRoots(this.p);t=(t=r[0].cmp(r[1])<0?r[0]:r[1]).toRed(this.red)}if(e.lambda)n=new i(e.lambda,16);else{var o=this._getEndoRoots(this.n);0===this.g.mul(o[0]).x.cmp(this.g.x.redMul(t))?n=o[0]:(n=o[1],a(0===this.g.mul(n).x.cmp(this.g.x.redMul(t))))}return{beta:t,lambda:n,basis:e.basis?e.basis.map((function(e){return{a:new i(e.a,16),b:new i(e.b,16)}})):this._getEndoBasis(n)}}},u.prototype._getEndoRoots=function(e){var t=e===this.p?this.red:i.mont(e),n=new i(2).toRed(t).redInvm(),r=n.redNeg(),o=new i(3).toRed(t).redNeg().redSqrt().redMul(n);return[r.redAdd(o).fromRed(),r.redSub(o).fromRed()]},u.prototype._getEndoBasis=function(e){for(var t,n,r,o,s,a,u,c,f,l=this.n.ushrn(Math.floor(this.n.bitLength()/2)),d=e,h=this.n.clone(),p=new i(1),v=new i(0),g=new i(0),m=new i(1),b=0;0!==d.cmpn(0);){var y=h.div(d);c=h.sub(y.mul(d)),f=g.sub(y.mul(p));var w=m.sub(y.mul(v));if(!r&&c.cmp(l)<0)t=u.neg(),n=p,r=c.neg(),o=f;else if(r&&2==++b)break;u=c,h=d,d=c,g=p,p=f,m=v,v=w}s=c.neg(),a=f;var _=r.sqr().add(o.sqr());return s.sqr().add(a.sqr()).cmp(_)>=0&&(s=t,a=n),r.negative&&(r=r.neg(),o=o.neg()),s.negative&&(s=s.neg(),a=a.neg()),[{a:r,b:o},{a:s,b:a}]},u.prototype._endoSplit=function(e){var t=this.endo.basis,n=t[0],r=t[1],i=r.b.mul(e).divRound(this.n),o=n.b.neg().mul(e).divRound(this.n),s=i.mul(n.a),a=o.mul(r.a),u=i.mul(n.b),c=o.mul(r.b);return{k1:e.sub(s).sub(a),k2:u.add(c).neg()}},u.prototype.pointFromX=function(e,t){(e=new i(e,16)).red||(e=e.toRed(this.red));var n=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),r=n.redSqrt();if(0!==r.redSqr().redSub(n).cmp(this.zero))throw new Error("invalid point");var o=r.fromRed().isOdd();return(t&&!o||!t&&o)&&(r=r.redNeg()),this.point(e,r)},u.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,n=e.y,r=this.a.redMul(t),i=t.redSqr().redMul(t).redIAdd(r).redIAdd(this.b);return 0===n.redSqr().redISub(i).cmpn(0)},u.prototype._endoWnafMulAdd=function(e,t,n){for(var r=this._endoWnafT1,i=this._endoWnafT2,o=0;o":""},c.prototype.isInfinity=function(){return this.inf},c.prototype.add=function(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return this.curve.point(null,null);if(0===this.x.cmp(e.x))return this.curve.point(null,null);var t=this.y.redSub(e.y);0!==t.cmpn(0)&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var n=t.redSqr().redISub(this.x).redISub(e.x),r=t.redMul(this.x.redSub(n)).redISub(this.y);return this.curve.point(n,r)},c.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(0===e.cmpn(0))return this.curve.point(null,null);var t=this.curve.a,n=this.x.redSqr(),r=e.redInvm(),i=n.redAdd(n).redIAdd(n).redIAdd(t).redMul(r),o=i.redSqr().redISub(this.x.redAdd(this.x)),s=i.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,s)},c.prototype.getX=function(){return this.x.fromRed()},c.prototype.getY=function(){return this.y.fromRed()},c.prototype.mul=function(e){return e=new i(e,16),this.isInfinity()?this:this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve.endo?this.curve._endoWnafMulAdd([this],[e]):this.curve._wnafMul(this,e)},c.prototype.mulAdd=function(e,t,n){var r=[this,t],i=[e,n];return this.curve.endo?this.curve._endoWnafMulAdd(r,i):this.curve._wnafMulAdd(1,r,i,2)},c.prototype.jmulAdd=function(e,t,n){var r=[this,t],i=[e,n];return this.curve.endo?this.curve._endoWnafMulAdd(r,i,!0):this.curve._wnafMulAdd(1,r,i,2,!0)},c.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||0===this.x.cmp(e.x)&&0===this.y.cmp(e.y))},c.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var n=this.precomputed,r=function(e){return e.neg()};t.precomputed={naf:n.naf&&{wnd:n.naf.wnd,points:n.naf.points.map(r)},doubles:n.doubles&&{step:n.doubles.step,points:n.doubles.points.map(r)}}}return t},c.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},o(f,s.BasePoint),u.prototype.jpoint=function(e,t,n){return new f(this,e,t,n)},f.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),n=this.x.redMul(t),r=this.y.redMul(t).redMul(e);return this.curve.point(n,r)},f.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},f.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),n=this.z.redSqr(),r=this.x.redMul(t),i=e.x.redMul(n),o=this.y.redMul(t.redMul(e.z)),s=e.y.redMul(n.redMul(this.z)),a=r.redSub(i),u=o.redSub(s);if(0===a.cmpn(0))return 0!==u.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var c=a.redSqr(),f=c.redMul(a),l=r.redMul(c),d=u.redSqr().redIAdd(f).redISub(l).redISub(l),h=u.redMul(l.redISub(d)).redISub(o.redMul(f)),p=this.z.redMul(e.z).redMul(a);return this.curve.jpoint(d,h,p)},f.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),n=this.x,r=e.x.redMul(t),i=this.y,o=e.y.redMul(t).redMul(this.z),s=n.redSub(r),a=i.redSub(o);if(0===s.cmpn(0))return 0!==a.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var u=s.redSqr(),c=u.redMul(s),f=n.redMul(u),l=a.redSqr().redIAdd(c).redISub(f).redISub(f),d=a.redMul(f.redISub(l)).redISub(i.redMul(c)),h=this.z.redMul(s);return this.curve.jpoint(l,d,h)},f.prototype.dblp=function(e){if(0===e)return this;if(this.isInfinity())return this;if(!e)return this.dbl();var t;if(this.curve.zeroA||this.curve.threeA){var n=this;for(t=0;t=0)return!1;if(n.redIAdd(i),0===this.x.cmp(n))return!0}},f.prototype.inspect=function(){return this.isInfinity()?"":""},f.prototype.isInfinity=function(){return 0===this.z.cmpn(0)}},function(e,t,n){"use strict";var r=n(29),i=n(7),o=n(95),s=n(47);function a(e){o.call(this,"mont",e),this.a=new r(e.a,16).toRed(this.red),this.b=new r(e.b,16).toRed(this.red),this.i4=new r(4).toRed(this.red).redInvm(),this.two=new r(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}function u(e,t,n){o.BasePoint.call(this,e,"projective"),null===t&&null===n?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new r(t,16),this.z=new r(n,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}i(a,o),e.exports=a,a.prototype.validate=function(e){var t=e.normalize().x,n=t.redSqr(),r=n.redMul(t).redAdd(n.redMul(this.a)).redAdd(t);return 0===r.redSqrt().redSqr().cmp(r)},i(u,o.BasePoint),a.prototype.decodePoint=function(e,t){return this.point(s.toArray(e,t),1)},a.prototype.point=function(e,t){return new u(this,e,t)},a.prototype.pointFromJSON=function(e){return u.fromJSON(this,e)},u.prototype.precompute=function(){},u.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},u.fromJSON=function(e,t){return new u(e,t[0],t[1]||e.one)},u.prototype.inspect=function(){return this.isInfinity()?"":""},u.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},u.prototype.dbl=function(){var e=this.x.redAdd(this.z).redSqr(),t=this.x.redSub(this.z).redSqr(),n=e.redSub(t),r=e.redMul(t),i=n.redMul(t.redAdd(this.curve.a24.redMul(n)));return this.curve.point(r,i)},u.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},u.prototype.diffAdd=function(e,t){var n=this.x.redAdd(this.z),r=this.x.redSub(this.z),i=e.x.redAdd(e.z),o=e.x.redSub(e.z).redMul(n),s=i.redMul(r),a=t.z.redMul(o.redAdd(s).redSqr()),u=t.x.redMul(o.redISub(s).redSqr());return this.curve.point(a,u)},u.prototype.mul=function(e){for(var t=e.clone(),n=this,r=this.curve.point(null,null),i=[];0!==t.cmpn(0);t.iushrn(1))i.push(t.andln(1));for(var o=i.length-1;o>=0;o--)0===i[o]?(n=n.diffAdd(r,this),r=r.dbl()):(r=n.diffAdd(r,this),n=n.dbl());return r},u.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},u.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},u.prototype.eq=function(e){return 0===this.getX().cmp(e.getX())},u.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},u.prototype.getX=function(){return this.normalize(),this.x.fromRed()}},function(e,t,n){"use strict";var r=n(47),i=n(29),o=n(7),s=n(95),a=r.assert;function u(e){this.twisted=1!=(0|e.a),this.mOneA=this.twisted&&-1==(0|e.a),this.extended=this.mOneA,s.call(this,"edwards",e),this.a=new i(e.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new i(e.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new i(e.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),a(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|e.c)}function c(e,t,n,r,o){s.BasePoint.call(this,e,"projective"),null===t&&null===n&&null===r?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new i(t,16),this.y=new i(n,16),this.z=r?new i(r,16):this.curve.one,this.t=o&&new i(o,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}o(u,s),e.exports=u,u.prototype._mulA=function(e){return this.mOneA?e.redNeg():this.a.redMul(e)},u.prototype._mulC=function(e){return this.oneC?e:this.c.redMul(e)},u.prototype.jpoint=function(e,t,n,r){return this.point(e,t,n,r)},u.prototype.pointFromX=function(e,t){(e=new i(e,16)).red||(e=e.toRed(this.red));var n=e.redSqr(),r=this.c2.redSub(this.a.redMul(n)),o=this.one.redSub(this.c2.redMul(this.d).redMul(n)),s=r.redMul(o.redInvm()),a=s.redSqrt();if(0!==a.redSqr().redSub(s).cmp(this.zero))throw new Error("invalid point");var u=a.fromRed().isOdd();return(t&&!u||!t&&u)&&(a=a.redNeg()),this.point(e,a)},u.prototype.pointFromY=function(e,t){(e=new i(e,16)).red||(e=e.toRed(this.red));var n=e.redSqr(),r=n.redSub(this.c2),o=n.redMul(this.d).redMul(this.c2).redSub(this.a),s=r.redMul(o.redInvm());if(0===s.cmp(this.zero)){if(t)throw new Error("invalid point");return this.point(this.zero,e)}var a=s.redSqrt();if(0!==a.redSqr().redSub(s).cmp(this.zero))throw new Error("invalid point");return a.fromRed().isOdd()!==t&&(a=a.redNeg()),this.point(a,e)},u.prototype.validate=function(e){if(e.isInfinity())return!0;e.normalize();var t=e.x.redSqr(),n=e.y.redSqr(),r=t.redMul(this.a).redAdd(n),i=this.c2.redMul(this.one.redAdd(this.d.redMul(t).redMul(n)));return 0===r.cmp(i)},o(c,s.BasePoint),u.prototype.pointFromJSON=function(e){return c.fromJSON(this,e)},u.prototype.point=function(e,t,n,r){return new c(this,e,t,n,r)},c.fromJSON=function(e,t){return new c(e,t[0],t[1],t[2])},c.prototype.inspect=function(){return this.isInfinity()?"":""},c.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},c.prototype._extDbl=function(){var e=this.x.redSqr(),t=this.y.redSqr(),n=this.z.redSqr();n=n.redIAdd(n);var r=this.curve._mulA(e),i=this.x.redAdd(this.y).redSqr().redISub(e).redISub(t),o=r.redAdd(t),s=o.redSub(n),a=r.redSub(t),u=i.redMul(s),c=o.redMul(a),f=i.redMul(a),l=s.redMul(o);return this.curve.point(u,c,l,f)},c.prototype._projDbl=function(){var e,t,n,r,i,o,s=this.x.redAdd(this.y).redSqr(),a=this.x.redSqr(),u=this.y.redSqr();if(this.curve.twisted){var c=(r=this.curve._mulA(a)).redAdd(u);this.zOne?(e=s.redSub(a).redSub(u).redMul(c.redSub(this.curve.two)),t=c.redMul(r.redSub(u)),n=c.redSqr().redSub(c).redSub(c)):(i=this.z.redSqr(),o=c.redSub(i).redISub(i),e=s.redSub(a).redISub(u).redMul(o),t=c.redMul(r.redSub(u)),n=c.redMul(o))}else r=a.redAdd(u),i=this.curve._mulC(this.z).redSqr(),o=r.redSub(i).redSub(i),e=this.curve._mulC(s.redISub(r)).redMul(o),t=this.curve._mulC(r).redMul(a.redISub(u)),n=r.redMul(o);return this.curve.point(e,t,n)},c.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},c.prototype._extAdd=function(e){var t=this.y.redSub(this.x).redMul(e.y.redSub(e.x)),n=this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)),r=this.t.redMul(this.curve.dd).redMul(e.t),i=this.z.redMul(e.z.redAdd(e.z)),o=n.redSub(t),s=i.redSub(r),a=i.redAdd(r),u=n.redAdd(t),c=o.redMul(s),f=a.redMul(u),l=o.redMul(u),d=s.redMul(a);return this.curve.point(c,f,d,l)},c.prototype._projAdd=function(e){var t,n,r=this.z.redMul(e.z),i=r.redSqr(),o=this.x.redMul(e.x),s=this.y.redMul(e.y),a=this.curve.d.redMul(o).redMul(s),u=i.redSub(a),c=i.redAdd(a),f=this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(o).redISub(s),l=r.redMul(u).redMul(f);return this.curve.twisted?(t=r.redMul(c).redMul(s.redSub(this.curve._mulA(o))),n=u.redMul(c)):(t=r.redMul(c).redMul(s.redSub(o)),n=this.curve._mulC(u).redMul(c)),this.curve.point(l,t,n)},c.prototype.add=function(e){return this.isInfinity()?e:e.isInfinity()?this:this.curve.extended?this._extAdd(e):this._projAdd(e)},c.prototype.mul=function(e){return this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve._wnafMul(this,e)},c.prototype.mulAdd=function(e,t,n){return this.curve._wnafMulAdd(1,[this,t],[e,n],2,!1)},c.prototype.jmulAdd=function(e,t,n){return this.curve._wnafMulAdd(1,[this,t],[e,n],2,!0)},c.prototype.normalize=function(){if(this.zOne)return this;var e=this.z.redInvm();return this.x=this.x.redMul(e),this.y=this.y.redMul(e),this.t&&(this.t=this.t.redMul(e)),this.z=this.curve.one,this.zOne=!0,this},c.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},c.prototype.getX=function(){return this.normalize(),this.x.fromRed()},c.prototype.getY=function(){return this.normalize(),this.y.fromRed()},c.prototype.eq=function(e){return this===e||0===this.getX().cmp(e.getX())&&0===this.getY().cmp(e.getY())},c.prototype.eqXToP=function(e){var t=e.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(t))return!0;for(var n=e.clone(),r=this.curve.redN.redMul(this.z);;){if(n.iadd(this.curve.n),n.cmp(this.curve.p)>=0)return!1;if(t.redIAdd(r),0===this.x.cmp(t))return!0}},c.prototype.toP=c.prototype.normalize,c.prototype.mixedAdd=c.prototype.add},function(e,t,n){"use strict";t.sha1=n(336),t.sha224=n(337),t.sha256=n(201),t.sha384=n(338),t.sha512=n(202)},function(e,t,n){"use strict";var r=n(51),i=n(82),o=n(200),s=r.rotl32,a=r.sum32,u=r.sum32_5,c=o.ft_1,f=i.BlockHash,l=[1518500249,1859775393,2400959708,3395469782];function d(){if(!(this instanceof d))return new d;f.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}r.inherits(d,f),e.exports=d,d.blockSize=512,d.outSize=160,d.hmacStrength=80,d.padLength=64,d.prototype._update=function(e,t){for(var n=this.W,r=0;r<16;r++)n[r]=e[t+r];for(;rthis.blockSize&&(e=(new this.Hash).update(e).digest()),i(e.length<=this.blockSize);for(var t=e.length;t0))return s.iaddn(1),this.keyFromPrivate(s)}},l.prototype._truncateToN=function(e,t){var n=8*e.byteLength()-this.n.bitLength();return n>0&&(e=e.ushrn(n)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},l.prototype.sign=function(e,t,n,o){"object"==typeof n&&(o=n,n=null),o||(o={}),t=this.keyFromPrivate(t,n),e=this._truncateToN(new r(e,16));for(var s=this.n.byteLength(),a=t.getPrivate().toArray("be",s),u=e.toArray("be",s),c=new i({hash:this.hash,entropy:a,nonce:u,pers:o.pers,persEnc:o.persEnc||"utf8"}),l=this.n.sub(new r(1)),d=0;;d++){var h=o.k?o.k(d):new r(c.generate(this.n.byteLength()));if(!((h=this._truncateToN(h,!0)).cmpn(1)<=0||h.cmp(l)>=0)){var p=this.g.mul(h);if(!p.isInfinity()){var v=p.getX(),g=v.umod(this.n);if(0!==g.cmpn(0)){var m=h.invm(this.n).mul(g.mul(t.getPrivate()).iadd(e));if(0!==(m=m.umod(this.n)).cmpn(0)){var b=(p.getY().isOdd()?1:0)|(0!==v.cmp(g)?2:0);return o.canonical&&m.cmp(this.nh)>0&&(m=this.n.sub(m),b^=1),new f({r:g,s:m,recoveryParam:b})}}}}}},l.prototype.verify=function(e,t,n,i){e=this._truncateToN(new r(e,16)),n=this.keyFromPublic(n,i);var o=(t=new f(t,"hex")).r,s=t.s;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;if(s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var a,u=s.invm(this.n),c=u.mul(e).umod(this.n),l=u.mul(o).umod(this.n);return this.curve._maxwellTrick?!(a=this.g.jmulAdd(c,n.getPublic(),l)).isInfinity()&&a.eqXToP(o):!(a=this.g.mulAdd(c,n.getPublic(),l)).isInfinity()&&0===a.getX().umod(this.n).cmp(o)},l.prototype.recoverPubKey=function(e,t,n,i){u((3&n)===n,"The recovery param is more than two bits"),t=new f(t,i);var o=this.n,s=new r(e),a=t.r,c=t.s,l=1&n,d=n>>1;if(a.cmp(this.curve.p.umod(this.curve.n))>=0&&d)throw new Error("Unable to find sencond key candinate");a=d?this.curve.pointFromX(a.add(this.curve.n),l):this.curve.pointFromX(a,l);var h=t.r.invm(o),p=o.sub(s).mul(h).umod(o),v=c.mul(h).umod(o);return this.g.mulAdd(p,a,v)},l.prototype.getKeyRecoveryParam=function(e,t,n,r){if(null!==(t=new f(t,r)).recoveryParam)return t.recoveryParam;for(var i=0;i<4;i++){var o;try{o=this.recoverPubKey(e,t,i)}catch(e){continue}if(o.eq(n))return i}throw new Error("Unable to find valid recovery factor")}},function(e,t,n){"use strict";var r=n(129),i=n(198),o=n(46);function s(e){if(!(this instanceof s))return new s(e);this.hash=e.hash,this.predResist=!!e.predResist,this.outLen=this.hash.outSize,this.minEntropy=e.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var t=i.toArray(e.entropy,e.entropyEnc||"hex"),n=i.toArray(e.nonce,e.nonceEnc||"hex"),r=i.toArray(e.pers,e.persEnc||"hex");o(t.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(t,n,r)}e.exports=s,s.prototype._init=function(e,t,n){var r=e.concat(t).concat(n);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(n||[])),this._reseed=1},s.prototype.generate=function(e,t,n,r){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof t&&(r=n,n=t,t=null),n&&(n=i.toArray(n,r||"hex"),this._update(n));for(var o=[];o.length"}},function(e,t,n){"use strict";var r=n(29),i=n(47),o=i.assert;function s(e,t){if(e instanceof s)return e;this._importDER(e,t)||(o(e.r&&e.s,"Signature without r or s"),this.r=new r(e.r,16),this.s=new r(e.s,16),void 0===e.recoveryParam?this.recoveryParam=null:this.recoveryParam=e.recoveryParam)}function a(){this.place=0}function u(e,t){var n=e[t.place++];if(!(128&n))return n;var r=15&n;if(0===r||r>4)return!1;for(var i=0,o=0,s=t.place;o>>=0;return!(i<=127)&&(t.place=s,i)}function c(e){for(var t=0,n=e.length-1;!e[t]&&!(128&e[t+1])&&t>>3);for(e.push(128|n);--n;)e.push(t>>>(n<<3)&255);e.push(t)}}e.exports=s,s.prototype._importDER=function(e,t){e=i.toArray(e,t);var n=new a;if(48!==e[n.place++])return!1;var o=u(e,n);if(!1===o)return!1;if(o+n.place!==e.length)return!1;if(2!==e[n.place++])return!1;var s=u(e,n);if(!1===s)return!1;var c=e.slice(n.place,s+n.place);if(n.place+=s,2!==e[n.place++])return!1;var f=u(e,n);if(!1===f)return!1;if(e.length!==f+n.place)return!1;var l=e.slice(n.place,f+n.place);if(0===c[0]){if(!(128&c[1]))return!1;c=c.slice(1)}if(0===l[0]){if(!(128&l[1]))return!1;l=l.slice(1)}return this.r=new r(c),this.s=new r(l),this.recoveryParam=null,!0},s.prototype.toDER=function(e){var t=this.r.toArray(),n=this.s.toArray();for(128&t[0]&&(t=[0].concat(t)),128&n[0]&&(n=[0].concat(n)),t=c(t),n=c(n);!(n[0]||128&n[1]);)n=n.slice(1);var r=[2];f(r,t.length),(r=r.concat(t)).push(2),f(r,n.length);var o=r.concat(n),s=[48];return f(s,o.length),s=s.concat(o),i.encode(s,e)}},function(e,t,n){"use strict";var r=n(129),i=n(128),o=n(47),s=o.assert,a=o.parseBytes,u=n(347),c=n(348);function f(e){if(s("ed25519"===e,"only tested with ed25519 so far"),!(this instanceof f))return new f(e);e=i[e].curve,this.curve=e,this.g=e.g,this.g.precompute(e.n.bitLength()+1),this.pointClass=e.point().constructor,this.encodingLength=Math.ceil(e.n.bitLength()/8),this.hash=r.sha512}e.exports=f,f.prototype.sign=function(e,t){e=a(e);var n=this.keyFromSecret(t),r=this.hashInt(n.messagePrefix(),e),i=this.g.mul(r),o=this.encodePoint(i),s=this.hashInt(o,n.pubBytes(),e).mul(n.priv()),u=r.add(s).umod(this.curve.n);return this.makeSignature({R:i,S:u,Rencoded:o})},f.prototype.verify=function(e,t,n){e=a(e),t=this.makeSignature(t);var r=this.keyFromPublic(n),i=this.hashInt(t.Rencoded(),r.pubBytes(),e),o=this.g.mul(t.S());return t.R().add(r.pub().mul(i)).eq(o)},f.prototype.hashInt=function(){for(var e=this.hash(),t=0;t=t)throw new Error("invalid sig")}e.exports=function(e,t,n,c,f){var l=s(n);if("ec"===l.type){if("ecdsa"!==c&&"ecdsa/rsa"!==c)throw new Error("wrong public key type");return function(e,t,n){var r=a[n.data.algorithm.curve.join(".")];if(!r)throw new Error("unknown curve "+n.data.algorithm.curve.join("."));var i=new o(r),s=n.data.subjectPrivateKey.data;return i.verify(t,e,s)}(e,t,l)}if("dsa"===l.type){if("dsa"!==c)throw new Error("wrong public key type");return function(e,t,n){var r=n.data.p,o=n.data.q,a=n.data.g,c=n.data.pub_key,f=s.signature.decode(e,"der"),l=f.s,d=f.r;u(l,o),u(d,o);var h=i.mont(r),p=l.invm(o);return 0===a.toRed(h).redPow(new i(t).mul(p).mod(o)).fromRed().mul(c.toRed(h).redPow(d.mul(p).mod(o)).fromRed()).mod(r).mod(o).cmp(d)}(e,t,l)}if("rsa"!==c&&"ecdsa/rsa"!==c)throw new Error("wrong public key type");t=r.concat([f,t]);for(var d=l.modulus.byteLength(),h=[1],p=0;t.length+h.length+2n-d-2)throw new Error("message too long");var h=l.alloc(n-r-d-2),p=n-f-1,v=i(f),g=a(l.concat([c,h,l.alloc(1,1),t],p),s(v,p)),m=a(v,s(g,f));return new u(l.concat([l.alloc(1),m,g],n))}(p,t);else if(1===d)h=function(e,t,n){var r,o=t.length,s=e.modulus.byteLength();if(o>s-11)throw new Error("message too long");r=n?l.alloc(s-o-3,255):function(e){var t,n=l.allocUnsafe(e),r=0,o=i(2*e),s=0;for(;r=0)throw new Error("data too long for modulus")}return n?f(h,p):c(h,p)}},function(e,t,n){var r=n(96),i=n(210),o=n(211),s=n(29),a=n(126),u=n(79),c=n(212),f=n(8).Buffer;e.exports=function(e,t,n){var l;l=e.padding?e.padding:n?1:4;var d,h=r(e),p=h.modulus.byteLength();if(t.length>p||new s(t).cmp(h.modulus)>=0)throw new Error("decryption error");d=n?c(new s(t),h):a(t,h);var v=f.alloc(p-d.length);if(d=f.concat([v,d],p),4===l)return function(e,t){var n=e.modulus.byteLength(),r=u("sha1").update(f.alloc(0)).digest(),s=r.length;if(0!==t[0])throw new Error("decryption error");var a=t.slice(1,s+1),c=t.slice(s+1),l=o(a,i(c,s)),d=o(c,i(l,n-s-1));if(function(e,t){e=f.from(e),t=f.from(t);var n=0,r=e.length;e.length!==t.length&&(n++,r=Math.min(e.length,t.length));var i=-1;for(;++i=t.length){o++;break}var s=t.slice(2,i-1);("0002"!==r.toString("hex")&&!n||"0001"!==r.toString("hex")&&n)&&o++;s.length<8&&o++;if(o)throw new Error("decryption error");return t.slice(i)}(0,d,n);if(3===l)return d;throw new Error("unknown padding")}},function(e,t,n){"use strict";(function(e,r){function i(){throw new Error("secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11")}var o=n(8),s=n(66),a=o.Buffer,u=o.kMaxLength,c=e.crypto||e.msCrypto,f=Math.pow(2,32)-1;function l(e,t){if("number"!=typeof e||e!=e)throw new TypeError("offset must be a number");if(e>f||e<0)throw new TypeError("offset must be a uint32");if(e>u||e>t)throw new RangeError("offset out of range")}function d(e,t,n){if("number"!=typeof e||e!=e)throw new TypeError("size must be a number");if(e>f||e<0)throw new TypeError("size must be a uint32");if(e+t>n||e>u)throw new RangeError("buffer too small")}function h(e,t,n,i){if(r.browser){var o=e.buffer,a=new Uint8Array(o,t,n);return c.getRandomValues(a),i?void r.nextTick((function(){i(null,e)})):e}if(!i)return s(n).copy(e,t),e;s(n,(function(n,r){if(n)return i(n);r.copy(e,t),i(null,e)}))}c&&c.getRandomValues||!r.browser?(t.randomFill=function(t,n,r,i){if(!(a.isBuffer(t)||t instanceof e.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');if("function"==typeof n)i=n,n=0,r=t.length;else if("function"==typeof r)i=r,r=t.length-n;else if("function"!=typeof i)throw new TypeError('"cb" argument must be a function');return l(n,t.length),d(r,n,t.length),h(t,n,r,i)},t.randomFillSync=function(t,n,r){void 0===n&&(n=0);if(!(a.isBuffer(t)||t instanceof e.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');l(n,t.length),void 0===r&&(r=t.length-n);return d(r,n,t.length),h(t,n,r)}):(t.randomFill=i,t.randomFillSync=i)}).call(this,n(31),n(20))},function(e,t,n){e.exports=self.fetch||(self.fetch=n(213).default||n(213))},function(e,t,n){(function(e,r){var i;/*! https://mths.be/punycode v1.4.1 by @mathias */!function(o){t&&t.nodeType,e&&e.nodeType;var s="object"==typeof r&&r;s.global!==s&&s.window!==s&&s.self;var a,u=2147483647,c=/^xn--/,f=/[^\x20-\x7E]/,l=/[\x2E\u3002\uFF0E\uFF61]/g,d={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},h=Math.floor,p=String.fromCharCode;function v(e){throw new RangeError(d[e])}function g(e,t){for(var n=e.length,r=[];n--;)r[n]=t(e[n]);return r}function m(e,t){var n=e.split("@"),r="";return n.length>1&&(r=n[0]+"@",e=n[1]),r+g((e=e.replace(l,".")).split("."),t).join(".")}function b(e){for(var t,n,r=[],i=0,o=e.length;i=55296&&t<=56319&&i65535&&(t+=p((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=p(e)})).join("")}function w(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function _(e,t,n){var r=0;for(e=n?h(e/700):e>>1,e+=h(e/t);e>455;r+=36)e=h(e/35);return h(r+36*e/(e+38))}function S(e){var t,n,r,i,o,s,a,c,f,l,d,p=[],g=e.length,m=0,b=128,w=72;for((n=e.lastIndexOf("-"))<0&&(n=0),r=0;r=128&&v("not-basic"),p.push(e.charCodeAt(r));for(i=n>0?n+1:0;i=g&&v("invalid-input"),((c=(d=e.charCodeAt(i++))-48<10?d-22:d-65<26?d-65:d-97<26?d-97:36)>=36||c>h((u-m)/s))&&v("overflow"),m+=c*s,!(c<(f=a<=w?1:a>=w+26?26:a-w));a+=36)s>h(u/(l=36-f))&&v("overflow"),s*=l;w=_(m-o,t=p.length+1,0==o),h(m/t)>u-b&&v("overflow"),b+=h(m/t),m%=t,p.splice(m++,0,b)}return y(p)}function E(e){var t,n,r,i,o,s,a,c,f,l,d,g,m,y,S,E=[];for(g=(e=b(e)).length,t=128,n=0,o=72,s=0;s=t&&dh((u-n)/(m=r+1))&&v("overflow"),n+=(a-t)*m,t=a,s=0;su&&v("overflow"),d==t){for(c=n,f=36;!(c<(l=f<=o?1:f>=o+26?26:f-o));f+=36)S=c-l,y=36-l,E.push(p(w(l+S%y,0))),c=h(S/y);E.push(p(w(c,0))),o=_(n,m,r==i),n=0,++r}++n,++t}return E.join("")}a={version:"1.4.1",ucs2:{decode:b,encode:y},decode:S,encode:E,toASCII:function(e){return m(e,(function(e){return f.test(e)?"xn--"+E(e):e}))},toUnicode:function(e){return m(e,(function(e){return c.test(e)?S(e.slice(4).toLowerCase()):e}))}},void 0===(i=function(){return a}.call(t,n,t,e))||(e.exports=i)}()}).call(this,n(57)(e),n(31))},function(e,t,n){"use strict";e.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},function(e,t,n){"use strict";t.decode=t.parse=n(369),t.encode=t.stringify=n(370)},function(e,t,n){"use strict";function r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.exports=function(e,t,n,o){t=t||"&",n=n||"=";var s={};if("string"!=typeof e||0===e.length)return s;var a=/\+/g;e=e.split(t);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var c=e.length;u>0&&c>u&&(c=u);for(var f=0;f=0?(l=v.substr(0,g),d=v.substr(g+1)):(l=v,d=""),h=decodeURIComponent(l),p=decodeURIComponent(d),r(s,h)?i(s[h])?s[h].push(p):s[h]=[s[h],p]:s[h]=p}return s};var i=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},function(e,t,n){"use strict";var r=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};e.exports=function(e,t,n,a){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?o(s(e),(function(s){var a=encodeURIComponent(r(s))+n;return i(e[s])?o(e[s],(function(e){return a+encodeURIComponent(r(e))})).join(t):a+encodeURIComponent(r(e[s]))})).join(t):a?encodeURIComponent(r(a))+n+encodeURIComponent(r(e)):""};var i=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function o(e,t){if(e.map)return e.map(t);for(var n=[],r=0;ra)&&void 0===e.nsecs&&(v=0),v>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");a=p,u=v,i=d;var m=(1e4*(268435455&(p+=122192928e5))+v)%4294967296;f[c++]=m>>>24&255,f[c++]=m>>>16&255,f[c++]=m>>>8&255,f[c++]=255&m;var b=p/4294967296*1e4&268435455;f[c++]=b>>>8&255,f[c++]=255&b,f[c++]=b>>>24&15|16,f[c++]=b>>>16&255,f[c++]=d>>>8|128,f[c++]=255&d;for(var y=0;y<6;++y)f[c+y]=l[y];return t||s(f)}},function(e,t,n){var r=n(214),i=n(215);e.exports=function(e,t,n){var o=t&&n||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var s=(e=e||{}).random||(e.rng||r)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t)for(var a=0;a<16;++a)t[o+a]=s[a];return t||i(s)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Sha256=void 0;var r=n(216),i=n(219),o=n(374),s=n(377),a=n(379),u=n(134),c=function(){function e(e){s.supportsWebCrypto(u.locateWindow())?this.hash=new i.Sha256(e):a.isMsWindow(u.locateWindow())?this.hash=new r.Sha256(e):this.hash=new o.Sha256(e)}return e.prototype.update=function(e,t){this.hash.update(e,t)},e.prototype.digest=function(){return this.hash.digest()},e}();t.Sha256=c},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n(1).__exportStar(n(375),t)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Sha256=void 0;var r=n(1),i=n(220),o=n(376),s=n(497),a=function(){function e(e){if(this.hash=new o.RawSha256,e){this.outer=new o.RawSha256;var t=function(e){var t=u(e);if(t.byteLength>i.BLOCK_SIZE){var n=new o.RawSha256;n.update(t),t=n.digest()}var r=new Uint8Array(i.BLOCK_SIZE);return r.set(t),r}(e),n=new Uint8Array(i.BLOCK_SIZE);n.set(t);for(var r=0;rr.MAX_HASHABLE_LENGTH)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[t++],n--,this.bufferLength===r.BLOCK_SIZE&&(this.hashBuffer(),this.bufferLength=0)},e.prototype.digest=function(){if(!this.finished){var e=8*this.bytesHashed,t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),n=this.bufferLength;if(t.setUint8(this.bufferLength++,128),n%r.BLOCK_SIZE>=r.BLOCK_SIZE-8){for(var i=this.bufferLength;i>>24&255,o[4*i+1]=this.state[i]>>>16&255,o[4*i+2]=this.state[i]>>>8&255,o[4*i+3]=this.state[i]>>>0&255;return o},e.prototype.hashBuffer=function(){for(var e=this.buffer,t=this.state,n=t[0],i=t[1],o=t[2],s=t[3],a=t[4],u=t[5],c=t[6],f=t[7],l=0;l>>17|d<<15)^(d>>>19|d<<13)^d>>>10,p=((d=this.temp[l-15])>>>7|d<<25)^(d>>>18|d<<14)^d>>>3;this.temp[l]=(h+this.temp[l-7]|0)+(p+this.temp[l-16]|0)}var v=(((a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7))+(a&u^~a&c)|0)+(f+(r.KEY[l]+this.temp[l]|0)|0)|0,g=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&i^n&o^i&o)|0;f=c,c=u,u=a,a=s+v|0,s=o,o=i,i=n,n=v+g|0}t[0]+=n,t[1]+=i,t[2]+=o,t[3]+=s,t[4]+=a,t[5]+=u,t[6]+=c,t[7]+=f},e}();t.RawSha256=i},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n(1).__exportStar(n(378),t)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.supportsZeroByteGCM=t.supportsSubtleCrypto=t.supportsSecureRandom=t.supportsWebCrypto=void 0;var r=n(1),i=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function o(e){return"object"==typeof e&&"object"==typeof e.crypto&&"function"==typeof e.crypto.getRandomValues}function s(e){return e&&i.every((function(t){return"function"==typeof e[t]}))}t.supportsWebCrypto=function(e){return!(!o(e)||"object"!=typeof e.crypto.subtle)&&s(e.crypto.subtle)},t.supportsSecureRandom=o,t.supportsSubtleCrypto=s,t.supportsZeroByteGCM=function(e){return r.__awaiter(this,void 0,void 0,(function(){var t;return r.__generator(this,(function(n){switch(n.label){case 0:if(!s(e))return[2,!1];n.label=1;case 1:return n.trys.push([1,4,,5]),[4,e.generateKey({name:"AES-GCM",length:128},!1,["encrypt"])];case 2:return t=n.sent(),[4,e.encrypt({name:"AES-GCM",iv:new Uint8Array(Array(12)),additionalData:new Uint8Array(Array(16)),tagLength:128},t,new Uint8Array(0))];case 3:return[2,16===n.sent().byteLength];case 4:return n.sent(),[2,!1];case 5:return[2]}}))}))}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(1);r.__exportStar(n(380),t),r.__exportStar(n(381),t),r.__exportStar(n(382),t),r.__exportStar(n(383),t),r.__exportStar(n(384),t)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMsWindow=void 0;var r=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];t.isMsWindow=function(e){if(function(e){return"MSInputMethodContext"in e&&"msCrypto"in e}(e)&&void 0!==e.msCrypto.subtle){var t=e.msCrypto,n=t.getRandomValues,i=t.subtle;return r.map((function(e){return i[e]})).concat(n).every((function(e){return"function"==typeof e}))}return!1}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),i=n(222),o=n(386),s=n(494),a=function(){function e(e){if(this.hash=new o.RawSha256,e){this.outer=new o.RawSha256;var t=function(e){var t=u(e);if(t.byteLength>i.BLOCK_SIZE){var n=new o.RawSha256;n.update(t),t=n.digest()}var r=new Uint8Array(i.BLOCK_SIZE);return r.set(t),r}(e),n=new Uint8Array(i.BLOCK_SIZE);n.set(t);for(var r=0;rr.MAX_HASHABLE_LENGTH)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[t++],n--,this.bufferLength===r.BLOCK_SIZE&&(this.hashBuffer(),this.bufferLength=0)},e.prototype.digest=function(){if(!this.finished){var e=8*this.bytesHashed,t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),n=this.bufferLength;if(t.setUint8(this.bufferLength++,128),n%r.BLOCK_SIZE>=r.BLOCK_SIZE-8){for(var i=this.bufferLength;i>>24&255,o[4*i+1]=this.state[i]>>>16&255,o[4*i+2]=this.state[i]>>>8&255,o[4*i+3]=this.state[i]>>>0&255;return o},e.prototype.hashBuffer=function(){for(var e=this.buffer,t=this.state,n=t[0],i=t[1],o=t[2],s=t[3],a=t[4],u=t[5],c=t[6],f=t[7],l=0;l>>17|d<<15)^(d>>>19|d<<13)^d>>>10,p=((d=this.temp[l-15])>>>7|d<<25)^(d>>>18|d<<14)^d>>>3;this.temp[l]=(h+this.temp[l-7]|0)+(p+this.temp[l-16]|0)}var v=(((a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7))+(a&u^~a&c)|0)+(f+(r.KEY[l]+this.temp[l]|0)|0)|0,g=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&i^n&o^i&o)|0;f=c,c=u,u=a,a=s+v|0,s=o,o=i,i=n,n=v+g|0}t[0]+=n,t[1]+=i,t[2]+=o,t[3]+=s,t[4]+=a,t[5]+=u,t[6]+=c,t[7]+=f},e}();t.RawSha256=i},function(e,t,n){var r=n(388),i=n(419);e.exports=function(e,t){for(var n=0,o=(t=r(t,e)).length;null!=e&&n-1}},function(e,t,n){var r=n(100);e.exports=function(e,t){var n=this.__data__,i=r(n,e);return i<0?(++this.size,n.push([e,t])):n[i][1]=t,this}},function(e,t,n){var r=n(101);e.exports=function(e){var t=r(this,e).delete(e);return this.size-=t?1:0,t}},function(e,t){e.exports=function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}},function(e,t,n){var r=n(101);e.exports=function(e){return r(this,e).get(e)}},function(e,t,n){var r=n(101);e.exports=function(e){return r(this,e).has(e)}},function(e,t,n){var r=n(101);e.exports=function(e,t){var n=r(this,e),i=n.size;return n.set(e,t),this.size+=n.size==i?0:1,this}},function(e,t,n){var r=n(417);e.exports=function(e){return null==e?"":r(e)}},function(e,t,n){var r=n(97),i=n(418),o=n(61),s=n(135),a=r?r.prototype:void 0,u=a?a.toString:void 0;e.exports=function e(t){if("string"==typeof t)return t;if(o(t))return i(t,e)+"";if(s(t))return u?u.call(t):"";var n=t+"";return"0"==n&&1/t==-1/0?"-0":n}},function(e,t){e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length,i=Array(r);++n-1&&e%1==0&&e1){o[u]=[];for(let n in e.child[u])e.child[u].hasOwnProperty(n)&&o[u].push(i(e.child[u][n],t,u))}else{const s=i(e.child[u][0],t,u),a=!0===t.arrayMode&&"object"==typeof s||r.isTagNameInArrayMode(u,t.arrayMode,n);o[u]=a?[s]:s}}return o};t.convertToJson=i},function(e,t,n){"use strict";e.exports=function(e,t,n){this.tagname=e,this.parent=t,this.child={},this.attrsMap={},this.val=n,this.addChild=function(e){Array.isArray(this.child[e.tagname])?this.child[e.tagname].push(e):this.child[e.tagname]=[e]}}},function(e,t,n){"use strict";const r=n(54),i={allowBooleanAttributes:!1},o=["allowBooleanAttributes"];function s(e,t){for(var n=t;t5&&"xml"===r)return d("InvalidXml","XML declaration allowed only at the start of the document.",p(e,t));if("?"==e[t]&&">"==e[t+1]){t++;break}}return t}function a(e,t){if(e.length>t+5&&"-"===e[t+1]&&"-"===e[t+2]){for(t+=3;t"===e[t+2]){t+=2;break}}else if(e.length>t+8&&"D"===e[t+1]&&"O"===e[t+2]&&"C"===e[t+3]&&"T"===e[t+4]&&"Y"===e[t+5]&&"P"===e[t+6]&&"E"===e[t+7]){let n=1;for(t+=8;t"===e[t]&&(n--,0===n))break}else if(e.length>t+9&&"["===e[t+1]&&"C"===e[t+2]&&"D"===e[t+3]&&"A"===e[t+4]&&"T"===e[t+5]&&"A"===e[t+6]&&"["===e[t+7])for(t+=8;t"===e[t+2]){t+=2;break}return t}t.validate=function(e,t){t=r.buildOptions(t,i,o);const n=[];let c=!1,h=!1;"\ufeff"===e[0]&&(e=e.substr(1));for(let i=0;i"!==e[i]&&" "!==e[i]&&"\t"!==e[i]&&"\n"!==e[i]&&"\r"!==e[i];i++)g+=e[i];if(g=g.trim(),"/"===g[g.length-1]&&(g=g.substring(0,g.length-1),i--),v=g,!r.isName(v)){let t;return t=0===g.trim().length?"There is an unnecessary space between tag name and backward slash '0)return d("InvalidTag","Closing tag '"+g+"' can't have attributes or invalid starting.",p(e,i));{const t=n.pop();if(g!==t)return d("InvalidTag","Closing tag '"+t+"' is expected inplace of '"+g+"'.",p(e,i));0==n.length&&(h=!0)}}else{const r=f(b,t);if(!0!==r)return d(r.err.code,r.err.msg,p(e,i-b.length+r.err.line));if(!0===h)return d("InvalidXml","Multiple possible root nodes found.",p(e,i));n.push(g),c=!0}for(i++;i0)||d("InvalidXml","Invalid '"+JSON.stringify(n,null,4).replace(/\r?\n/g,"")+"' found.",1):d("InvalidXml","Start tag expected.",1)};function u(e,t){let n="",r="",i=!1;for(;t"===e[t]&&""===r){i=!0;break}n+=e[t]}return""===r&&{value:n,index:t,tagClosed:i}}const c=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function f(e,t){const n=r.getAllMatches(e,c),i={};for(let r=0;r1){for(var u in i+='"'+a+'" : [ ',e.child[a])i+=s(e.child[a][u],t)+" , ";i=i.substr(0,i.length-1)+" ] "}else i+='"'+a+'" : '+s(e.child[a][0],t)+" ,"}return r.merge(i,e.attrsMap),r.isEmptyObject(i)?r.isExist(e.val)?e.val:"":(r.isExist(e.val)&&("string"!=typeof e.val||""!==e.val&&e.val!==t.cdataPositionChar)&&(i+='"'+t.textNodeName+'" : '+(!0!==(c=e.val)&&!1!==c&&isNaN(c)?'"'+c+'"':c)),","===i[i.length-1]&&(i=i.substr(0,i.length-2)),i+"}");var c};t.convertToJsonString=function(e,t){return(t=i(t,o.defaultOptions,o.props)).indentBy=t.indentBy||"",s(e,t,0)}},function(e,t,n){"use strict";const r=n(54).buildOptions,i={attributeNamePrefix:"@_",attrNodeName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataTagName:!1,cdataPositionChar:"\\c",format:!1,indentBy:" ",supressEmptyNode:!1,tagValueProcessor:function(e){return e},attrValueProcessor:function(e){return e}},o=["attributeNamePrefix","attrNodeName","textNodeName","ignoreAttributes","cdataTagName","cdataPositionChar","format","indentBy","supressEmptyNode","tagValueProcessor","attrValueProcessor"];function s(e){this.options=r(e,i,o),this.options.ignoreAttributes||this.options.attrNodeName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=p),this.options.cdataTagName?this.isCDATA=v:this.isCDATA=function(){return!1},this.replaceCDATAstr=a,this.replaceCDATAarr=u,this.options.format?(this.indentate=h,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine=""),this.options.supressEmptyNode?(this.buildTextNode=d,this.buildObjNode=f):(this.buildTextNode=l,this.buildObjNode=c),this.buildTextValNode=l,this.buildObjectNode=c}function a(e,t){return e=this.options.tagValueProcessor(""+e),""===this.options.cdataPositionChar||""===e?e+"");return e+this.newLine}function c(e,t,n,r){return n&&!e.includes("<")?this.indentate(r)+"<"+t+n+">"+e+""+this.options.tagValueProcessor(e)+"=0)return;s[t]="set-cookie"===t?(s[t]?s[t]:[]).concat([n]):s[t]?s[t]+", "+n:n}})),s):s}},function(e,t,n){"use strict";var r=n(45);e.exports=r.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");function i(e){var r=e;return t&&(n.setAttribute("href",r),r=n.href),n.setAttribute("href",r),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:"/"===n.pathname.charAt(0)?n.pathname:"/"+n.pathname}}return e=i(window.location.href),function(t){var n=r.isString(t)?i(t):t;return n.protocol===e.protocol&&n.host===e.host}}():function(){return!0}},function(e,t,n){"use strict";var r=n(242);function i(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var n=this;e((function(e){n.reason||(n.reason=new r(e),t(n.reason))}))}i.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},i.source=function(){var e;return{token:new i((function(t){e=t})),cancel:e}},e.exports=i},function(e,t,n){"use strict";e.exports=function(e){return function(t){return e.apply(null,t)}}},function(e,t,n){"use strict";e.exports=function(e){return"object"==typeof e&&!0===e.isAxiosError}},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){for(var n=0;n1,i=!1,o=arguments[1],s=o;return new n((function(n){return t.subscribe({next:function(t){var o=!i;if(i=!0,!o||r)try{s=e(s,t)}catch(e){return n.error(e)}else s=t},error:function(e){n.error(e)},complete:function(){if(!i&&!r)return n.error(new TypeError("Cannot reduce an empty sequence"));n.next(s),n.complete()}})}))}},{key:"concat",value:function(){for(var e=this,t=arguments.length,n=new Array(t),r=0;r=0&&i.splice(e,1),s()}});i.push(o)},error:function(e){r.error(e)},complete:function(){s()}});function s(){o.closed&&0===i.length&&r.complete()}return function(){i.forEach((function(e){return e.unsubscribe()})),o.unsubscribe()}}))}},{key:f,value:function(){return this}}],[{key:"from",value:function(t){var n="function"==typeof this?this:e;if(null==t)throw new TypeError(t+" is not an object");var r=d(t,f);if(r){var i=r.call(t);if(Object(i)!==i)throw new TypeError(i+" is not an object");return p(i)&&i.constructor===n?i:new n((function(e){return i.subscribe(e)}))}if(a("iterator")&&(r=d(t,c)))return new n((function(e){g((function(){if(!e.closed){var n=!0,i=!1,o=void 0;try{for(var s,a=r.call(t)[Symbol.iterator]();!(n=(s=a.next()).done);n=!0){var u=s.value;if(e.next(u),e.closed)return}}catch(e){i=!0,o=e}finally{try{n||null==a.return||a.return()}finally{if(i)throw o}}e.complete()}}))}));if(Array.isArray(t))return new n((function(e){g((function(){if(!e.closed){for(var n=0;na)&&void 0===e.nsecs&&(v=0),v>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");a=p,u=v,i=d;var m=(1e4*(268435455&(p+=122192928e5))+v)%4294967296;f[c++]=m>>>24&255,f[c++]=m>>>16&255,f[c++]=m>>>8&255,f[c++]=255&m;var b=p/4294967296*1e4&268435455;f[c++]=b>>>8&255,f[c++]=255&b,f[c++]=b>>>24&15|16,f[c++]=b>>>16&255,f[c++]=d>>>8|128,f[c++]=255&d;for(var y=0;y<6;++y)f[c+y]=l[y];return t||s(f)}},function(e,t,n){var r=n(243),i=n(244);e.exports=function(e,t,n){var o=t&&n||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var s=(e=e||{}).random||(e.rng||r)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t)for(var a=0;a<16;++a)t[o+a]=s[a];return t||i(s)}},function(e,t){},function(e,t,n){e.exports=n(487).Observable},function(e,t,n){"use strict";(function(e){!function(e,t){function n(e){return"function"==typeof Symbol&&Boolean(Symbol[e])}function r(e){return n(e)?Symbol[e]:"@@"+e}function i(e){setTimeout((function(){throw e}))}function o(e,t){var n=e[t];if(null!=n){if("function"!=typeof n)throw new TypeError(n+" is not a function");return n}}function s(e){var t=e.constructor;return void 0!==t&&null===(t=t[r("species")])&&(t=void 0),void 0!==t?t:d}function a(e,t){Object.keys(t).forEach((function(n){var r=Object.getOwnPropertyDescriptor(t,n);r.enumerable=!1,Object.defineProperty(e,n,r)}))}function u(e){var t=e._cleanup;if(t){e._cleanup=void 0;try{t()}catch(e){i(e)}}}function c(e){return void 0===e._observer}function f(e,t){if(Object(e)!==e)throw new TypeError("Observer must be an object");this._cleanup=void 0,this._observer=e;try{var n=o(e,"start");n&&n.call(e,this)}catch(e){i(e)}if(!c(this)){e=new l(this);try{var r=t.call(void 0,e);if(null!=r){if("function"==typeof r.unsubscribe)s=r,r=function(){s.unsubscribe()};else if("function"!=typeof r)throw new TypeError(r+" is not a function");this._cleanup=r}}catch(t){return void e.error(t)}var s;c(this)&&u(this)}}function l(e){this._subscription=e}function d(e){if(!(this instanceof d))throw new TypeError("Observable cannot be called as a function");if("function"!=typeof e)throw new TypeError("Observable initializer must be a function");this._subscriber=e}"function"!=typeof Symbol||Symbol.observable||(Symbol.observable=Symbol("observable")),a(f.prototype={},{get closed(){return c(this)},unsubscribe:function(){var e;c(e=this)||(e._observer=void 0,u(e))}}),a(l.prototype={},{get closed(){return c(this._subscription)},next:function(e){var t=this._subscription;if(!c(t)){var n=t._observer;try{var r=o(n,"next");r&&r.call(n,e)}catch(e){i(e)}}},error:function(e){var t=this._subscription;if(c(t))i(e);else{var n=t._observer;t._observer=void 0;try{var r=o(n,"error");if(!r)throw e;r.call(n,e)}catch(e){i(e)}u(t)}},complete:function(){var e=this._subscription;if(!c(e)){var t=e._observer;e._observer=void 0;try{var n=o(t,"complete");n&&n.call(t)}catch(e){i(e)}u(e)}}}),a(d.prototype,{subscribe:function(e){for(var t=[],n=1;n1,i=!1,o=arguments[1],a=o;return new n((function(n){return t.subscribe({next:function(t){if(!n.closed){var o=!i;if(i=!0,!o||r)try{a=e(a,t)}catch(e){return n.error(e)}else a=t}},error:function(e){n.error(e)},complete:function(){if(!i&&!r)return n.error(new TypeError("Cannot reduce an empty sequence"));n.next(a),n.complete()}})}))}}),Object.defineProperty(d.prototype,r("observable"),{value:function(){return this},writable:!0,configurable:!0}),a(d,{from:function(e){var t="function"==typeof this?this:d;if(null==e)throw new TypeError(e+" is not an object");var i=o(e,r("observable"));if(i){var s=i.call(e);if(Object(s)!==s)throw new TypeError(s+" is not an object");return s.constructor===t?s:new t((function(e){return s.subscribe(e)}))}if(n("iterator")&&(i=o(e,r("iterator"))))return new t((function(t){for(var n,r=i.call(e)[Symbol.iterator]();!(n=r.next()).done;){var o=n.value;if(t.next(o),t.closed)return}t.complete()}));if(Array.isArray(e))return new t((function(t){for(var n=0;n0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},a=function(){for(var e=[],t=0;t",e),null):t},e.prototype.removePluggable=function(e){this._convertPluggables=this._convertPluggables.filter((function(t){return t.getProviderName()!==e})),this._identifyPluggables=this._identifyPluggables.filter((function(t){return t.getProviderName()!==e})),this._interpretPluggables=this._interpretPluggables.filter((function(t){return t.getProviderName()!==e}))},e.prototype.configure=function(e){var t=this,n=e?e.predictions||e:{};n=o(o({},n),e),this._options=Object.assign({},this._options,n),u.debug("configure Predictions",this._options),this.getAllProviders().forEach((function(e){return t.configurePluggable(e)}))},e.prototype.interpret=function(e,t){return this.getPluggableToExecute(this._interpretPluggables,t).interpret(e)},e.prototype.convert=function(e,t){return this.getPluggableToExecute(this._convertPluggables,t).convert(e)},e.prototype.identify=function(e,t){return this.getPluggableToExecute(this._identifyPluggables,t).identify(e)},e.prototype.getPluggableToExecute=function(e,t){if(t&&t.providerName)return a(e).find((function(e){return e.getProviderName()===t.providerName}));if(1===e.length)return e[0];throw new Error("More than one or no providers are configured, Either specify a provider name or configure exactly one provider")},e.prototype.getAllProviders=function(){return a(this._convertPluggables,this._identifyPluggables,this._interpretPluggables)},e.prototype.configurePluggable=function(e){var t=Object.assign({},this._options.predictions,this._options[e.getCategory().toLowerCase()]);e.configure(t)},e.prototype.implementsConvertPluggable=function(e){return e&&"function"==typeof e.convert},e.prototype.implementsIdentifyPluggable=function(e){return e&&"function"==typeof e.identify},e.prototype.implementsInterpretPluggable=function(e){return e&&"function"==typeof e.interpret},e}())({});i.a.register(c)},function(e,t,n){"use strict";n.d(t,"a",(function(){return ft}));var r=n(44),i=n(19),o=function(){return(o=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s}Object.create;var p,v,g,m,b,y,w,_,S,E,M,A,I,k,O,x,C,T,P,N,R,L,j,D,U,B,F,z,q,K,H,V,G,W,$,Y=n(155),J=n(38),Z=n(18),X=n(24),Q=n(11),ee=n(39),te=n(17),ne=n(40),re=n(41),ie=n(15),oe=new Set(["ap-east-1","ap-northeast-1","ap-northeast-2","ap-south-1","ap-southeast-1","ap-southeast-2","ca-central-1","eu-central-1","eu-north-1","eu-west-1","eu-west-2","eu-west-3","me-south-1","sa-east-1","us-east-1","us-east-2","us-west-1","us-west-2"]),se=new Set(["cn-north-1","cn-northwest-1"]),ae=new Set(["us-iso-east-1"]),ue=new Set(["us-isob-east-1"]),ce=new Set(["us-gov-east-1","us-gov-west-1"]),fe=f(f({},{apiVersion:"2016-11-28",disableHostPrefix:!1,logger:{},regionInfoProvider:function(e,t){var n=void 0;switch(e){case"eu-west-1":n={hostname:"runtime.lex.eu-west-1.amazonaws.com",partition:"aws",signingService:"lex"};break;case"us-east-1":n={hostname:"runtime.lex.us-east-1.amazonaws.com",partition:"aws",signingService:"lex"};break;case"us-west-2":n={hostname:"runtime.lex.us-west-2.amazonaws.com",partition:"aws",signingService:"lex"};break;default:oe.has(e)&&(n={hostname:"runtime.lex.{region}.amazonaws.com".replace("{region}",e),partition:"aws",signingService:"lex"}),se.has(e)&&(n={hostname:"runtime.lex.{region}.amazonaws.com.cn".replace("{region}",e),partition:"aws-cn"}),ae.has(e)&&(n={hostname:"runtime.lex.{region}.c2s.ic.gov".replace("{region}",e),partition:"aws-iso"}),ue.has(e)&&(n={hostname:"runtime.lex.{region}.sc2s.sgov.gov".replace("{region}",e),partition:"aws-iso-b"}),ce.has(e)&&(n={hostname:"runtime.lex.{region}.amazonaws.com".replace("{region}",e),partition:"aws-us-gov"}),void 0===n&&(n={hostname:"runtime.lex.{region}.amazonaws.com".replace("{region}",e),partition:"aws",signingService:"lex"})}return Promise.resolve(n)},signingName:"lex"}),{runtime:"browser",base64Decoder:te.a,base64Encoder:te.b,bodyLengthChecker:ne.a,credentialDefaultProvider:Object(X.a)("Credential is missing"),defaultUserAgent:Object(re.a)(Y.name,Y.version),maxAttempts:Q.a,region:Object(X.a)("Region is missing"),requestHandler:new Z.a,sha256:J.Sha256,streamCollector:Z.b,urlParser:ee.a,utf8Decoder:ie.a,utf8Encoder:ie.b}),le=n(22),de=n(37),he=n(21),pe=n(43),ve=n(25),ge=n(23),me=n(0),be=function(e){function t(t){var n=this,r=f(f({},fe),t),i=Object(le.b)(r),o=Object(le.a)(i),s=Object(ve.b)(o),a=Object(Q.c)(s),u=Object(ge.b)(a),c=Object(he.b)(u);return(n=e.call(this,c)||this).config=c,n.middlewareStack.use(Object(ve.a)(n.config)),n.middlewareStack.use(Object(Q.b)(n.config)),n.middlewareStack.use(Object(ge.a)(n.config)),n.middlewareStack.use(Object(de.a)(n.config)),n.middlewareStack.use(Object(he.a)(n.config)),n.middlewareStack.use(Object(pe.a)(n.config)),n}return c(t,e),t.prototype.destroy=function(){e.prototype.destroy.call(this)},t}(me.a);(p||(p={})).filterSensitiveLog=function(e){return f({},e)},(v||(v={})).filterSensitiveLog=function(e){return f({},e)},(g||(g={})).filterSensitiveLog=function(e){return f({},e)},(m||(m={})).filterSensitiveLog=function(e){return f({},e)},(b||(b={})).filterSensitiveLog=function(e){return f({},e)},(y||(y={})).filterSensitiveLog=function(e){return f({},e)},(w||(w={})).filterSensitiveLog=function(e){return f({},e)},(_||(_={})).filterSensitiveLog=function(e){return f({},e)},function(e){e.FAILED="Failed",e.FULFILLED="Fulfilled",e.READY_FOR_FULFILLMENT="ReadyForFulfillment"}(S||(S={})),function(e){e.COMPOSITE="Composite",e.CUSTOM_PAYLOAD="CustomPayload",e.PLAIN_TEXT="PlainText",e.SSML="SSML"}(E||(E={})),function(e){e.CLOSE="Close",e.CONFIRM_INTENT="ConfirmIntent",e.DELEGATE="Delegate",e.ELICIT_INTENT="ElicitIntent",e.ELICIT_SLOT="ElicitSlot"}(M||(M={})),(A||(A={})).filterSensitiveLog=function(e){return f(f(f({},e),e.slots&&{slots:me.d}),e.message&&{message:me.d})},function(e){e.CONFIRMED="Confirmed",e.DENIED="Denied",e.NONE="None"}(I||(I={})),(k||(k={})).filterSensitiveLog=function(e){return f(f({},e),e.slots&&{slots:me.d})},(O||(O={})).filterSensitiveLog=function(e){return f(f(f(f({},e),e.dialogAction&&{dialogAction:A.filterSensitiveLog(e.dialogAction)}),e.recentIntentSummaryView&&{recentIntentSummaryView:e.recentIntentSummaryView.map((function(e){return k.filterSensitiveLog(e)}))}),e.sessionAttributes&&{sessionAttributes:me.d})},(x||(x={})).filterSensitiveLog=function(e){return f({},e)},(C||(C={})).filterSensitiveLog=function(e){return f({},e)},(T||(T={})).filterSensitiveLog=function(e){return f({},e)},(P||(P={})).filterSensitiveLog=function(e){return f({},e)},(N||(N={})).filterSensitiveLog=function(e){return f(f(f({},e),e.requestAttributes&&{requestAttributes:me.d}),e.sessionAttributes&&{sessionAttributes:me.d})},function(e){e.CONFIRM_INTENT="ConfirmIntent",e.ELICIT_INTENT="ElicitIntent",e.ELICIT_SLOT="ElicitSlot",e.FAILED="Failed",e.FULFILLED="Fulfilled",e.READY_FOR_FULFILLMENT="ReadyForFulfillment"}(R||(R={})),(L||(L={})).filterSensitiveLog=function(e){return f(f({},e),e.message&&{message:me.d})},(j||(j={})).filterSensitiveLog=function(e){return f({},e)},(D||(D={})).filterSensitiveLog=function(e){return f({},e)},(U||(U={})).filterSensitiveLog=function(e){return f(f(f(f({},e),e.requestAttributes&&{requestAttributes:me.d}),e.inputText&&{inputText:me.d}),e.sessionAttributes&&{sessionAttributes:me.d})},(B||(B={})).filterSensitiveLog=function(e){return f({},e)},(F||(F={})).filterSensitiveLog=function(e){return f(f({},e),e.slots&&{slots:me.d})},function(e){e.GENERIC="application/vnd.amazonaws.card.generic"}(z||(z={})),(q||(q={})).filterSensitiveLog=function(e){return f({},e)},(K||(K={})).filterSensitiveLog=function(e){return f({},e)},(H||(H={})).filterSensitiveLog=function(e){return f({},e)},(V||(V={})).filterSensitiveLog=function(e){return f({},e)},(G||(G={})).filterSensitiveLog=function(e){return f(f(f(f(f({},e),e.alternativeIntents&&{alternativeIntents:e.alternativeIntents.map((function(e){return F.filterSensitiveLog(e)}))}),e.message&&{message:me.d}),e.sessionAttributes&&{sessionAttributes:me.d}),e.slots&&{slots:me.d})},(W||(W={})).filterSensitiveLog=function(e){return f(f(f(f({},e),e.dialogAction&&{dialogAction:A.filterSensitiveLog(e.dialogAction)}),e.recentIntentSummaryView&&{recentIntentSummaryView:e.recentIntentSummaryView.map((function(e){return k.filterSensitiveLog(e)}))}),e.sessionAttributes&&{sessionAttributes:me.d})},($||($={})).filterSensitiveLog=function(e){return f(f({},e),e.message&&{message:me.d})};var ye,we=n(2),_e=function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,l,h,p,v,g,m,b,y,w,_;return d(this,(function(d){switch(d.label){case 0:return r=[f({},e)],_={},[4,Ge(e.body,t)];case 1:switch(n=f.apply(void 0,r.concat([(_.body=d.sent(),_)])),o="UnknownError",o=We(e,n.body),o){case"BadGatewayException":case"com.amazonaws.lexruntimeservice#BadGatewayException":return[3,2];case"BadRequestException":case"com.amazonaws.lexruntimeservice#BadRequestException":return[3,4];case"ConflictException":case"com.amazonaws.lexruntimeservice#ConflictException":return[3,6];case"DependencyFailedException":case"com.amazonaws.lexruntimeservice#DependencyFailedException":return[3,8];case"InternalFailureException":case"com.amazonaws.lexruntimeservice#InternalFailureException":return[3,10];case"LimitExceededException":case"com.amazonaws.lexruntimeservice#LimitExceededException":return[3,12];case"LoopDetectedException":case"com.amazonaws.lexruntimeservice#LoopDetectedException":return[3,14];case"NotAcceptableException":case"com.amazonaws.lexruntimeservice#NotAcceptableException":return[3,16];case"NotFoundException":case"com.amazonaws.lexruntimeservice#NotFoundException":return[3,18];case"RequestTimeoutException":case"com.amazonaws.lexruntimeservice#RequestTimeoutException":return[3,20];case"UnsupportedMediaTypeException":case"com.amazonaws.lexruntimeservice#UnsupportedMediaTypeException":return[3,22]}return[3,24];case 2:return s=[{}],[4,Ee(n,t)];case 3:return i=f.apply(void 0,[f.apply(void 0,s.concat([d.sent()])),{name:o,$metadata:Ke(e)}]),[3,25];case 4:return a=[{}],[4,Me(n,t)];case 5:return i=f.apply(void 0,[f.apply(void 0,a.concat([d.sent()])),{name:o,$metadata:Ke(e)}]),[3,25];case 6:return u=[{}],[4,Ae(n,t)];case 7:return i=f.apply(void 0,[f.apply(void 0,u.concat([d.sent()])),{name:o,$metadata:Ke(e)}]),[3,25];case 8:return c=[{}],[4,Ie(n,t)];case 9:return i=f.apply(void 0,[f.apply(void 0,c.concat([d.sent()])),{name:o,$metadata:Ke(e)}]),[3,25];case 10:return l=[{}],[4,ke(n,t)];case 11:return i=f.apply(void 0,[f.apply(void 0,l.concat([d.sent()])),{name:o,$metadata:Ke(e)}]),[3,25];case 12:return h=[{}],[4,Oe(n,t)];case 13:return i=f.apply(void 0,[f.apply(void 0,h.concat([d.sent()])),{name:o,$metadata:Ke(e)}]),[3,25];case 14:return p=[{}],[4,xe(n,t)];case 15:return i=f.apply(void 0,[f.apply(void 0,p.concat([d.sent()])),{name:o,$metadata:Ke(e)}]),[3,25];case 16:return v=[{}],[4,Ce(n,t)];case 17:return i=f.apply(void 0,[f.apply(void 0,v.concat([d.sent()])),{name:o,$metadata:Ke(e)}]),[3,25];case 18:return g=[{}],[4,Te(n,t)];case 19:return i=f.apply(void 0,[f.apply(void 0,g.concat([d.sent()])),{name:o,$metadata:Ke(e)}]),[3,25];case 20:return m=[{}],[4,Pe(n,t)];case 21:return i=f.apply(void 0,[f.apply(void 0,m.concat([d.sent()])),{name:o,$metadata:Ke(e)}]),[3,25];case 22:return b=[{}],[4,Ne(n,t)];case 23:return i=f.apply(void 0,[f.apply(void 0,b.concat([d.sent()])),{name:o,$metadata:Ke(e)}]),[3,25];case 24:y=n.body,o=y.code||y.Code||o,i=f(f({},y),{name:""+o,message:y.message||y.Message||o,$fault:"client",$metadata:Ke(e)}),d.label=25;case 25:return w=i.message||i.Message||o,i.message=w,delete i.Message,[2,Promise.reject(Object.assign(new Error(w),i))]}}))}))},Se=function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,l,h,p,v,g,m,b;return d(this,(function(d){switch(d.label){case 0:return r=[f({},e)],b={},[4,Ge(e.body,t)];case 1:switch(n=f.apply(void 0,r.concat([(b.body=d.sent(),b)])),o="UnknownError",o=We(e,n.body),o){case"BadGatewayException":case"com.amazonaws.lexruntimeservice#BadGatewayException":return[3,2];case"BadRequestException":case"com.amazonaws.lexruntimeservice#BadRequestException":return[3,4];case"ConflictException":case"com.amazonaws.lexruntimeservice#ConflictException":return[3,6];case"DependencyFailedException":case"com.amazonaws.lexruntimeservice#DependencyFailedException":return[3,8];case"InternalFailureException":case"com.amazonaws.lexruntimeservice#InternalFailureException":return[3,10];case"LimitExceededException":case"com.amazonaws.lexruntimeservice#LimitExceededException":return[3,12];case"LoopDetectedException":case"com.amazonaws.lexruntimeservice#LoopDetectedException":return[3,14];case"NotFoundException":case"com.amazonaws.lexruntimeservice#NotFoundException":return[3,16]}return[3,18];case 2:return s=[{}],[4,Ee(n,t)];case 3:return i=f.apply(void 0,[f.apply(void 0,s.concat([d.sent()])),{name:o,$metadata:Ke(e)}]),[3,19];case 4:return a=[{}],[4,Me(n,t)];case 5:return i=f.apply(void 0,[f.apply(void 0,a.concat([d.sent()])),{name:o,$metadata:Ke(e)}]),[3,19];case 6:return u=[{}],[4,Ae(n,t)];case 7:return i=f.apply(void 0,[f.apply(void 0,u.concat([d.sent()])),{name:o,$metadata:Ke(e)}]),[3,19];case 8:return c=[{}],[4,Ie(n,t)];case 9:return i=f.apply(void 0,[f.apply(void 0,c.concat([d.sent()])),{name:o,$metadata:Ke(e)}]),[3,19];case 10:return l=[{}],[4,ke(n,t)];case 11:return i=f.apply(void 0,[f.apply(void 0,l.concat([d.sent()])),{name:o,$metadata:Ke(e)}]),[3,19];case 12:return h=[{}],[4,Oe(n,t)];case 13:return i=f.apply(void 0,[f.apply(void 0,h.concat([d.sent()])),{name:o,$metadata:Ke(e)}]),[3,19];case 14:return p=[{}],[4,xe(n,t)];case 15:return i=f.apply(void 0,[f.apply(void 0,p.concat([d.sent()])),{name:o,$metadata:Ke(e)}]),[3,19];case 16:return v=[{}],[4,Te(n,t)];case 17:return i=f.apply(void 0,[f.apply(void 0,v.concat([d.sent()])),{name:o,$metadata:Ke(e)}]),[3,19];case 18:g=n.body,o=g.code||g.Code||o,i=f(f({},g),{name:""+o,message:g.message||g.Message||o,$fault:"client",$metadata:Ke(e)}),d.label=19;case 19:return m=i.message||i.Message||o,i.message=m,delete i.Message,[2,Promise.reject(Object.assign(new Error(m),i))]}}))}))},Ee=function(e,t){return l(void 0,void 0,void 0,(function(){var t,n;return d(this,(function(r){return t={name:"BadGatewayException",$fault:"server",$metadata:Ke(e),Message:void 0},void 0!==(n=e.body).Message&&null!==n.Message&&(t.Message=n.Message),[2,t]}))}))},Me=function(e,t){return l(void 0,void 0,void 0,(function(){var t,n;return d(this,(function(r){return t={name:"BadRequestException",$fault:"client",$metadata:Ke(e),message:void 0},void 0!==(n=e.body).message&&null!==n.message&&(t.message=n.message),[2,t]}))}))},Ae=function(e,t){return l(void 0,void 0,void 0,(function(){var t,n;return d(this,(function(r){return t={name:"ConflictException",$fault:"client",$metadata:Ke(e),message:void 0},void 0!==(n=e.body).message&&null!==n.message&&(t.message=n.message),[2,t]}))}))},Ie=function(e,t){return l(void 0,void 0,void 0,(function(){var t,n;return d(this,(function(r){return t={name:"DependencyFailedException",$fault:"client",$metadata:Ke(e),Message:void 0},void 0!==(n=e.body).Message&&null!==n.Message&&(t.Message=n.Message),[2,t]}))}))},ke=function(e,t){return l(void 0,void 0,void 0,(function(){var t,n;return d(this,(function(r){return t={name:"InternalFailureException",$fault:"server",$metadata:Ke(e),message:void 0},void 0!==(n=e.body).message&&null!==n.message&&(t.message=n.message),[2,t]}))}))},Oe=function(e,t){return l(void 0,void 0,void 0,(function(){var t,n;return d(this,(function(r){return t={name:"LimitExceededException",$fault:"client",$metadata:Ke(e),message:void 0,retryAfterSeconds:void 0},void 0!==e.headers["retry-after"]&&(t.retryAfterSeconds=e.headers["retry-after"]),void 0!==(n=e.body).message&&null!==n.message&&(t.message=n.message),[2,t]}))}))},xe=function(e,t){return l(void 0,void 0,void 0,(function(){var t,n;return d(this,(function(r){return t={name:"LoopDetectedException",$fault:"server",$metadata:Ke(e),Message:void 0},void 0!==(n=e.body).Message&&null!==n.Message&&(t.Message=n.Message),[2,t]}))}))},Ce=function(e,t){return l(void 0,void 0,void 0,(function(){var t,n;return d(this,(function(r){return t={name:"NotAcceptableException",$fault:"client",$metadata:Ke(e),message:void 0},void 0!==(n=e.body).message&&null!==n.message&&(t.message=n.message),[2,t]}))}))},Te=function(e,t){return l(void 0,void 0,void 0,(function(){var t,n;return d(this,(function(r){return t={name:"NotFoundException",$fault:"client",$metadata:Ke(e),message:void 0},void 0!==(n=e.body).message&&null!==n.message&&(t.message=n.message),[2,t]}))}))},Pe=function(e,t){return l(void 0,void 0,void 0,(function(){var t,n;return d(this,(function(r){return t={name:"RequestTimeoutException",$fault:"client",$metadata:Ke(e),message:void 0},void 0!==(n=e.body).message&&null!==n.message&&(t.message=n.message),[2,t]}))}))},Ne=function(e,t){return l(void 0,void 0,void 0,(function(){var t,n;return d(this,(function(r){return t={name:"UnsupportedMediaTypeException",$fault:"client",$metadata:Ke(e),message:void 0},void 0!==(n=e.body).message&&null!==n.message&&(t.message=n.message),[2,t]}))}))},Re=function(e,t){return Object.entries(e).reduce((function(e,t){var n,r=h(t,2),i=r[0],o=r[1];return f(f({},e),((n={})[i]=o,n))}),{})},Le=function(e,t){return(e||[]).map((function(e){return function(e,t){return{attachmentLinkUrl:void 0!==e.attachmentLinkUrl&&null!==e.attachmentLinkUrl?e.attachmentLinkUrl:void 0,buttons:void 0!==e.buttons&&null!==e.buttons?Ue(e.buttons,t):void 0,imageUrl:void 0!==e.imageUrl&&null!==e.imageUrl?e.imageUrl:void 0,subTitle:void 0!==e.subTitle&&null!==e.subTitle?e.subTitle:void 0,title:void 0!==e.title&&null!==e.title?e.title:void 0}}(e,t)}))},je=function(e,t){return{score:void 0!==e.score&&null!==e.score?e.score:void 0}},De=function(e,t){return(e||[]).map((function(e){return Be(e,t)}))},Ue=function(e,t){return(e||[]).map((function(e){return function(e,t){return{text:void 0!==e.text&&null!==e.text?e.text:void 0,value:void 0!==e.value&&null!==e.value?e.value:void 0}}(e)}))},Be=function(e,t){return{intentName:void 0!==e.intentName&&null!==e.intentName?e.intentName:void 0,nluIntentConfidence:void 0!==e.nluIntentConfidence&&null!==e.nluIntentConfidence?je(e.nluIntentConfidence,t):void 0,slots:void 0!==e.slots&&null!==e.slots?qe(e.slots,t):void 0}},Fe=function(e,t){return{contentType:void 0!==e.contentType&&null!==e.contentType?e.contentType:void 0,genericAttachments:void 0!==e.genericAttachments&&null!==e.genericAttachments?Le(e.genericAttachments,t):void 0,version:void 0!==e.version&&null!==e.version?e.version:void 0}},ze=function(e,t){return{sentimentLabel:void 0!==e.sentimentLabel&&null!==e.sentimentLabel?e.sentimentLabel:void 0,sentimentScore:void 0!==e.sentimentScore&&null!==e.sentimentScore?e.sentimentScore:void 0}},qe=function(e,t){return Object.entries(e).reduce((function(e,t){var n,r=h(t,2),i=r[0],o=r[1];return f(f({},e),((n={})[i]=o,n))}),{})},Ke=function(e){return{httpStatusCode:e.statusCode,httpHeaders:e.headers,requestId:e.headers["x-amzn-requestid"]}},He=function(e,t){return function(e,t){return void 0===e&&(e=new Uint8Array),e instanceof Uint8Array?Promise.resolve(e):t.streamCollector(e)||Promise.resolve(new Uint8Array)}(e,t).then((function(e){return t.utf8Encoder(e)}))},Ve=function(e){return!(void 0===e||""===e||Object.getOwnPropertyNames(e).includes("length")&&0==e.length||Object.getOwnPropertyNames(e).includes("size")&&0==e.size)},Ge=function(e,t){return He(e,t).then((function(e){return e.length?JSON.parse(e):{}}))},We=function(e,t){var n,r,i=function(e){var t=e;return t.indexOf(":")>=0&&(t=t.split(":")[0]),t.indexOf("#")>=0&&(t=t.split("#")[1]),t},o=(n=e.headers,r="x-amzn-errortype",Object.keys(n).find((function(e){return e.toLowerCase()===r.toLowerCase()})));return void 0!==o?i(e.headers[o]):void 0!==t.code?i(t.code):void 0!==t.__type?i(t.__type):""},$e=n(10),Ye=function(e){function t(t){var n=e.call(this)||this;return n.input=t,n}return c(t,e),t.prototype.resolveMiddleware=function(e,t,n){this.middlewareStack.use(Object($e.a)(t,this.serialize,this.deserialize));var r=e.concat(this.middlewareStack),i=t.logger,o={logger:i,clientName:"LexRuntimeServiceClient",commandName:"PostTextCommand",inputFilterSensitiveLog:U.filterSensitiveLog,outputFilterSensitiveLog:G.filterSensitiveLog};"function"==typeof i.info&&i.info({clientName:"LexRuntimeServiceClient",commandName:"PostTextCommand"});var s=t.requestHandler;return r.resolve((function(e){return s.handle(e.request,n||{})}),o)},t.prototype.serialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,l;return d(this,(function(d){switch(d.label){case 0:if(n={"Content-Type":"application/json"},r="/bot/{botName}/alias/{botAlias}/user/{userId}/text",void 0===e.userId)throw new Error("No value provided for input HTTP label: userId.");if((i=e.userId).length<=0)throw new Error("Empty value provided for input HTTP label: userId.");if(r=r.replace("{userId}",Object(me.f)(i)),void 0===e.botAlias)throw new Error("No value provided for input HTTP label: botAlias.");if((i=e.botAlias).length<=0)throw new Error("Empty value provided for input HTTP label: botAlias.");if(r=r.replace("{botAlias}",Object(me.f)(i)),void 0===e.botName)throw new Error("No value provided for input HTTP label: botName.");if((i=e.botName).length<=0)throw new Error("Empty value provided for input HTTP label: botName.");return r=r.replace("{botName}",Object(me.f)(i)),o=JSON.stringify(f(f(f({},void 0!==e.inputText&&{inputText:e.inputText}),void 0!==e.requestAttributes&&{requestAttributes:Re(e.requestAttributes,t)}),void 0!==e.sessionAttributes&&{sessionAttributes:Re(e.sessionAttributes,t)})),[4,t.endpoint()];case 1:return s=d.sent(),a=s.hostname,u=s.protocol,c=void 0===u?"https":u,l=s.port,[2,new we.a({protocol:c,hostname:a,port:l,method:"POST",headers:n,path:r,body:o})]}}))}))}(e,t)},t.prototype.deserialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n,r;return d(this,(function(i){switch(i.label){case 0:return 200!==e.statusCode&&e.statusCode>=300?[2,Se(e,t)]:(n={$metadata:Ke(e),alternativeIntents:void 0,botVersion:void 0,dialogState:void 0,intentName:void 0,message:void 0,messageFormat:void 0,nluIntentConfidence:void 0,responseCard:void 0,sentimentResponse:void 0,sessionAttributes:void 0,sessionId:void 0,slotToElicit:void 0,slots:void 0},[4,Ge(e.body,t)]);case 1:return void 0!==(r=i.sent()).alternativeIntents&&null!==r.alternativeIntents&&(n.alternativeIntents=De(r.alternativeIntents,t)),void 0!==r.botVersion&&null!==r.botVersion&&(n.botVersion=r.botVersion),void 0!==r.dialogState&&null!==r.dialogState&&(n.dialogState=r.dialogState),void 0!==r.intentName&&null!==r.intentName&&(n.intentName=r.intentName),void 0!==r.message&&null!==r.message&&(n.message=r.message),void 0!==r.messageFormat&&null!==r.messageFormat&&(n.messageFormat=r.messageFormat),void 0!==r.nluIntentConfidence&&null!==r.nluIntentConfidence&&(n.nluIntentConfidence=je(r.nluIntentConfidence,t)),void 0!==r.responseCard&&null!==r.responseCard&&(n.responseCard=Fe(r.responseCard,t)),void 0!==r.sentimentResponse&&null!==r.sentimentResponse&&(n.sentimentResponse=ze(r.sentimentResponse,t)),void 0!==r.sessionAttributes&&null!==r.sessionAttributes&&(n.sessionAttributes=qe(r.sessionAttributes,t)),void 0!==r.sessionId&&null!==r.sessionId&&(n.sessionId=r.sessionId),void 0!==r.slotToElicit&&null!==r.slotToElicit&&(n.slotToElicit=r.slotToElicit),void 0!==r.slots&&null!==r.slots&&(n.slots=qe(r.slots,t)),[2,Promise.resolve(n)]}}))}))}(e,t)},t}(me.b),Je=function(e){function t(t){var n=e.call(this)||this;return n.input=t,n}return c(t,e),t.prototype.resolveMiddleware=function(e,t,n){this.middlewareStack.use(Object($e.a)(t,this.serialize,this.deserialize));var r=e.concat(this.middlewareStack),i=t.logger,o={logger:i,clientName:"LexRuntimeServiceClient",commandName:"PostContentCommand",inputFilterSensitiveLog:N.filterSensitiveLog,outputFilterSensitiveLog:L.filterSensitiveLog};"function"==typeof i.info&&i.info({clientName:"LexRuntimeServiceClient",commandName:"PostContentCommand"});var s=t.requestHandler;return r.resolve((function(e){return s.handle(e.request,n||{})}),o)},t.prototype.serialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,l;return d(this,(function(d){switch(d.label){case 0:if(n=f(f(f(f({"Content-Type":"application/octet-stream","x-amz-content-sha256":"UNSIGNED-PAYLOAD"},Ve(e.requestAttributes)&&{"x-amz-lex-request-attributes":me.c.fromObject(e.requestAttributes)}),Ve(e.sessionAttributes)&&{"x-amz-lex-session-attributes":me.c.fromObject(e.sessionAttributes)}),Ve(e.contentType)&&{"Content-Type":e.contentType}),Ve(e.accept)&&{Accept:e.accept}),r="/bot/{botName}/alias/{botAlias}/user/{userId}/content",void 0===e.botAlias)throw new Error("No value provided for input HTTP label: botAlias.");if((i=e.botAlias).length<=0)throw new Error("Empty value provided for input HTTP label: botAlias.");if(r=r.replace("{botAlias}",Object(me.f)(i)),void 0===e.botName)throw new Error("No value provided for input HTTP label: botName.");if((i=e.botName).length<=0)throw new Error("Empty value provided for input HTTP label: botName.");if(r=r.replace("{botName}",Object(me.f)(i)),void 0===e.userId)throw new Error("No value provided for input HTTP label: userId.");if((i=e.userId).length<=0)throw new Error("Empty value provided for input HTTP label: userId.");return r=r.replace("{userId}",Object(me.f)(i)),void 0!==e.inputStream&&(o=e.inputStream),[4,t.endpoint()];case 1:return s=d.sent(),a=s.hostname,u=s.protocol,c=void 0===u?"https":u,l=s.port,[2,new we.a({protocol:c,hostname:a,port:l,method:"POST",headers:n,path:r,body:o})]}}))}))}(e,t)},t.prototype.deserialize=function(e,t){return function(e,t){return l(void 0,void 0,void 0,(function(){var n,r;return d(this,(function(i){return 200!==e.statusCode&&e.statusCode>=300?[2,_e(e,t)]:(n={$metadata:Ke(e),alternativeIntents:void 0,audioStream:void 0,botVersion:void 0,contentType:void 0,dialogState:void 0,inputTranscript:void 0,intentName:void 0,message:void 0,messageFormat:void 0,nluIntentConfidence:void 0,sentimentResponse:void 0,sessionAttributes:void 0,sessionId:void 0,slotToElicit:void 0,slots:void 0},void 0!==e.headers["x-amz-lex-alternative-intents"]&&(n.alternativeIntents=new me.c(e.headers["x-amz-lex-alternative-intents"])),void 0!==e.headers["x-amz-lex-message-format"]&&(n.messageFormat=e.headers["x-amz-lex-message-format"]),void 0!==e.headers["content-type"]&&(n.contentType=e.headers["content-type"]),void 0!==e.headers["x-amz-lex-message"]&&(n.message=e.headers["x-amz-lex-message"]),void 0!==e.headers["x-amz-lex-bot-version"]&&(n.botVersion=e.headers["x-amz-lex-bot-version"]),void 0!==e.headers["x-amz-lex-sentiment"]&&(n.sentimentResponse=e.headers["x-amz-lex-sentiment"]),void 0!==e.headers["x-amz-lex-slots"]&&(n.slots=new me.c(e.headers["x-amz-lex-slots"])),void 0!==e.headers["x-amz-lex-input-transcript"]&&(n.inputTranscript=e.headers["x-amz-lex-input-transcript"]),void 0!==e.headers["x-amz-lex-slot-to-elicit"]&&(n.slotToElicit=e.headers["x-amz-lex-slot-to-elicit"]),void 0!==e.headers["x-amz-lex-session-attributes"]&&(n.sessionAttributes=new me.c(e.headers["x-amz-lex-session-attributes"])),void 0!==e.headers["x-amz-lex-session-id"]&&(n.sessionId=e.headers["x-amz-lex-session-id"]),void 0!==e.headers["x-amz-lex-dialog-state"]&&(n.dialogState=e.headers["x-amz-lex-dialog-state"]),void 0!==e.headers["x-amz-lex-intent-name"]&&(n.intentName=e.headers["x-amz-lex-intent-name"]),void 0!==e.headers["x-amz-lex-nlu-intent-confidence"]&&(n.nluIntentConfidence=new me.c(e.headers["x-amz-lex-nlu-intent-confidence"])),r=e.body,n.audioStream=r,[2,Promise.resolve(n)])}))}))}(e,t)},t}(me.b),Ze=n(89),Xe=n(50),Qe=function(e){if(e instanceof Blob||e instanceof ReadableStream)return new Response(e).arrayBuffer().then((function(e){return new Uint8Array(e)}));throw new Error("Readable is not supported.")},et=(ye=function(e,t){return(ye=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}ye(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),tt=function(){return(tt=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=0&&(t=t.split(":")[0]),t.indexOf("#")>=0&&(t=t.split("#")[1]),t},o=(n=e.headers,r="x-amzn-errortype",Object.keys(n).find((function(e){return e.toLowerCase()===r.toLowerCase()})));return void 0!==o?i(e.headers[o]):void 0!==t.code?i(t.code):void 0!==t.__type?i(t.__type):""},N=n(10),R=function(e){function t(t){var n=e.call(this)||this;return n.input=t,n}return u(t,e),t.prototype.resolveMiddleware=function(e,t,n){this.middlewareStack.use(Object(N.a)(t,this.serialize,this.deserialize));var r=e.concat(this.middlewareStack),i=t.logger,o={logger:i,clientName:"PersonalizeEventsClient",commandName:"PutEventsCommand",inputFilterSensitiveLog:p.filterSensitiveLog,outputFilterSensitiveLog:function(e){return e}};"function"==typeof i.info&&i.info({clientName:"PersonalizeEventsClient",commandName:"PutEventsCommand"});var s=t.requestHandler;return r.resolve((function(e){return s.handle(e.request,n||{})}),o)},t.prototype.serialize=function(e,t){return function(e,t){return f(void 0,void 0,void 0,(function(){var n,r,i,o,s,a,u,f;return l(this,(function(l){switch(l.label){case 0:return n={"Content-Type":"application/json"},r="/events",i=JSON.stringify(c(c(c(c({},void 0!==e.eventList&&{eventList:k(e.eventList,t)}),void 0!==e.sessionId&&{sessionId:e.sessionId}),void 0!==e.trackingId&&{trackingId:e.trackingId}),void 0!==e.userId&&{userId:e.userId})),[4,t.endpoint()];case 1:return o=l.sent(),s=o.hostname,a=o.protocol,u=void 0===a?"https":a,f=o.port,[2,new E.a({protocol:u,hostname:s,port:f,method:"POST",headers:n,path:r,body:i})]}}))}))}(e,t)},t.prototype.deserialize=function(e,t){return function(e,t){return f(void 0,void 0,void 0,(function(){var n;return l(this,(function(r){switch(r.label){case 0:return 200!==e.statusCode&&e.statusCode>=300?[2,A(e,t)]:(n={$metadata:x(e)},[4,C(e.body,t)]);case 1:return r.sent(),[2,Promise.resolve(n)]}}))}))}(e,t)},t}(M.b),L=n(152),j=n(38),D=n(18),U=n(24),B=n(11),F=n(39),z=n(17),q=n(40),K=n(41),H=n(15),V="personalize-events.{region}.amazonaws.com",G=new Set(["ap-east-1","ap-northeast-1","ap-northeast-2","ap-south-1","ap-southeast-1","ap-southeast-2","ca-central-1","eu-central-1","eu-north-1","eu-west-1","eu-west-2","eu-west-3","me-south-1","sa-east-1","us-east-1","us-east-2","us-west-1","us-west-2"]),W=new Set(["cn-north-1","cn-northwest-1"]),$=new Set(["us-iso-east-1"]),Y=new Set(["us-isob-east-1"]),J=new Set(["us-gov-east-1","us-gov-west-1"]),Z=c(c({},{apiVersion:"2018-03-22",disableHostPrefix:!1,logger:{},regionInfoProvider:function(e,t){var n=void 0;return G.has(e)&&(n={hostname:V.replace("{region}",e),partition:"aws"}),W.has(e)&&(n={hostname:"personalize-events.{region}.amazonaws.com.cn".replace("{region}",e),partition:"aws-cn"}),$.has(e)&&(n={hostname:"personalize-events.{region}.c2s.ic.gov".replace("{region}",e),partition:"aws-iso"}),Y.has(e)&&(n={hostname:"personalize-events.{region}.sc2s.sgov.gov".replace("{region}",e),partition:"aws-iso-b"}),J.has(e)&&(n={hostname:"personalize-events.{region}.amazonaws.com".replace("{region}",e),partition:"aws-us-gov"}),void 0===n&&(n={hostname:V.replace("{region}",e),partition:"aws"}),Promise.resolve(n)},signingName:"personalize"}),{runtime:"browser",base64Decoder:z.a,base64Encoder:z.b,bodyLengthChecker:q.a,credentialDefaultProvider:Object(U.a)("Credential is missing"),defaultUserAgent:Object(K.a)(L.name,L.version),maxAttempts:B.a,region:Object(U.a)("Region is missing"),requestHandler:new D.a,sha256:j.Sha256,streamCollector:D.b,urlParser:F.a,utf8Decoder:H.a,utf8Encoder:H.b}),X=n(22),Q=n(37),ee=n(21),te=n(43),ne=n(25),re=n(23),ie=function(e){function t(t){var n=this,r=c(c({},Z),t),i=Object(X.b)(r),o=Object(X.a)(i),s=Object(ne.b)(o),a=Object(B.c)(s),u=Object(re.b)(a),f=Object(ee.b)(u);return(n=e.call(this,f)||this).config=f,n.middlewareStack.use(Object(ne.a)(n.config)),n.middlewareStack.use(Object(B.b)(n.config)),n.middlewareStack.use(Object(re.a)(n.config)),n.middlewareStack.use(Object(Q.a)(n.config)),n.middlewareStack.use(Object(ee.a)(n.config)),n.middlewareStack.use(Object(te.a)(n.config)),n}return u(t,e),t.prototype.destroy=function(){e.prototype.destroy.call(this)},t}(M.a),oe=n(36),se=n.n(oe),ae=n(108),ue=n.n(ae),ce=n(27),fe=n(26),le=(new r.a("AmazonPersonalizeProvider"),function(){function e(e){void 0===e&&(e=""),this._isBrowser=i.a.browserOrNode().isBrowser,this._timerKey=Object(ce.v1)().substr(0,15),this._refreshTimer()}return e.prototype._refreshTimer=function(){this._timer&&clearInterval(this._timer);var e=this;this._timer=setInterval((function(){e._timerKey=Object(ce.v1)().substr(0,15)}),3e4)},e.prototype.storeValue=function(e,t){var n=new Date,r=new Date;r.setTime(n.getTime()+6048e5),fe.a.setItem(this._getCachePrefix(e),t,{expires:r.getTime()})},e.prototype.retrieveValue=function(e){return fe.a.getItem(this._getCachePrefix(e))},e.prototype._getCachePrefix=function(e){return this._isBrowser?e+"."+window.location.host:"peronslize"},e.prototype.getTimerKey=function(){return this._timerKey},e.prototype.updateSessionInfo=function(e,t){var n=t.userId,r=t.sessionId;if(this._isRequireNewSession(e,n,r)){var i=Object(ce.v1)();this.storeValue("_awsct_uid",e),this.storeValue("_awsct_sid",i),t.sessionId=i}else this._isRequireUpdateSessionInfo(e,n,r)&&this.storeValue("_awsct_uid",e);t.userId=e},e.prototype._isRequireUpdateSessionInfo=function(e,t,n){return!se()(n)&&se()(t)&&!se()(e)},e.prototype.retrieveSessionInfo=function(e){var t={};return t.trackingId=e,t.sessionId=this.retrieveValue("_awsct_sid"),t.userId=this.retrieveValue("_awsct_uid"),se()(t.sessionId)&&(t.sessionId=Object(ce.v1)(),this.storeValue("_awsct_sid",t.sessionId)),this.storeValue("_awsct",e),t},e.prototype._isRequireNewSession=function(e,t,n){var r=se()(n),i=se()(e)&&!se()(t),o=!se()(e)&&!se()(t)&&!ue()(e,t);return r||i||o},e}());!function(e){e.PLAY="play",e.PAUSE="pause",e.ENDED="Ended"}(w||(w={})),function(e){e.IFRAME="IFRAME",e.VIDEO="VIDEO",e.AUDIO="AUDIO"}(_||(_={})),function(e){e.PLAY="Play",e.ENDED="Ended",e.PAUSE="Pause",e.TIME_WATCHED="TimeWatched"}(S||(S={}));var de=function(){function e(e,t){var n;this.eventActionMapping=((n={})[S.ENDED]=this.endedEventAction.bind(this),n[S.PLAY]=this.playEventAction.bind(this),n[S.PAUSE]=this.pauseEventAction.bind(this),n);var r=e.eventData;this._params=e,this._mediaElement=document.getElementById(r.properties.domElementId),this._started=!1,this._provider=t,{IFRAME:this._iframeMediaTracker,VIDEO:this._html5MediaTracker,AUDIO:this._html5MediaTracker}[this._mediaElement.tagName].bind(this)(),this._initYoutubeFrame()}return e.prototype._initYoutubeFrame=function(){this._youTubeIframeLoader={src:"https://www.youtube.com/iframe_api",loading:!1,loaded:!1,listeners:[],load:function(e){var t=this;if(this.listeners.push(e),this.loaded)setTimeout((function(){t.done()}));else if(!this.loading){this.loading=!0,window.onYouTubeIframeAPIReady=function(){t.loaded=!0,t.done()};var n=document.createElement("script");n.type="text/javascript",n.src=this.src,document.body.appendChild(n)}},done:function(){for(delete window.onYouTubeIframeAPIReady;this.listeners.length;)this.listeners.pop()(window.YT)}}},e.prototype._iframeMediaTracker=function(){var e=this;setInterval((function(){e._started&&e.recordEvent(_.IFRAME,S.TIME_WATCHED)}),3e3),this._youTubeIframeLoader.load((function(t){e._iframePlayer=new t.Player(e._mediaElement.id,{events:{onStateChange:e._onPlayerStateChange.bind(e)}})}))},e.prototype._onPlayerStateChange=function(e){var t={0:S.ENDED,1:S.PLAY,2:S.PAUSE}[e.data];t&&this.eventActionMapping[t](_.IFRAME)},e.prototype._html5MediaTracker=function(){var e=this;setInterval((function(){e._started&&e.recordEvent(_.VIDEO,S.TIME_WATCHED)}),3e3),this._mediaElement.addEventListener(w.PLAY,(function(){e.eventActionMapping[S.PLAY](_.VIDEO)}),!1),this._mediaElement.addEventListener(w.PAUSE,(function(){e.eventActionMapping[S.PAUSE](_.VIDEO)}),!1),this._mediaElement.addEventListener(w.ENDED,(function(){e.eventActionMapping[S.ENDED](_.VIDEO)}),!1)},e.prototype.playEventAction=function(e){this._started=!0,this.recordEvent(e,S.PLAY)},e.prototype.pauseEventAction=function(e){this._started=!1,this.recordEvent(e,S.PAUSE)},e.prototype.endedEventAction=function(e){this._started=!1,this.recordEvent(e,S.ENDED)},e.prototype.recordEvent=function(e,t){var n=Object.assign({},this._params),r=n.eventData;r.eventType=t,e===_.VIDEO?(r.properties.timestamp=this._mediaElement.currentTime,r.properties.duration=this._mediaElement.duration):(r.properties.timestamp=this._financial(this._iframePlayer.getCurrentTime()),r.properties.duration=this._financial(this._iframePlayer.getDuration()));var i=parseFloat(r.properties.timestamp)/parseFloat(r.properties.duration);r.properties.eventValue=Number(i.toFixed(4)),delete r.properties.domElementId,this._provider.putToBuffer(n)},e.prototype._financial=function(e){return Number.parseFloat(e).toFixed(4)},e}(),he=n(252),pe=n.n(he),ve=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))},ge=function(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&this._config.flushSize<=10?this._config.flushSize:5,this._config.flushInterval=this._config.flushInterval||5e3,this._sessionManager=new le,se()(this._config.trackingId)||(this._sessionInfo=this._sessionManager.retrieveSessionInfo(this._config.trackingId)),this._isBrowser=i.a.browserOrNode().isBrowser,this._setupTimer()}return e.prototype._setupTimer=function(){this._timer&&clearInterval(this._timer);var e=this._config.flushInterval,t=this;this._timer=setInterval((function(){t._sendFromBuffer()}),e)},e.prototype.record=function(e){return ve(this,void 0,void 0,(function(){var t,n,r,i,o;return ge(this,(function(s){switch(s.label){case 0:return[4,this._getCredentials()];case 1:return(t=s.sent())?(Object.assign(e,{config:this._config,credentials:t,sentAt:new Date}),n=e.event,r=n.eventType,i=n.properties,"Identify"===r?(this._sessionManager.updateSessionInfo(i&&i.userId?i.userId:"",this._sessionInfo),[2]):(se()(e.event.userId)||this._sessionManager.updateSessionInfo(e.event.userId,this._sessionInfo),o=this.generateRequestParams(e,this._sessionInfo),"MediaAutoTrack"!==r?[3,7]:this._isBrowser?se()(pe()(o,"eventData.properties.domElementId",null))?[3,3]:[4,this.isElementFullyLoaded(this.loadElement,o.eventData.properties.domElementId,500,5)]:[3,5])):[2,Promise.resolve(!1)];case 2:return s.sent()?new de(o,this):me.debug("Cannot find the media element."),[3,4];case 3:me.debug("Missing domElementId field in 'properties' for MediaAutoTrack event type."),s.label=4;case 4:return[3,6];case 5:me.debug("MediaAutoTrack only for browser"),s.label=6;case 6:return[2];case 7:return[2,this.putToBuffer(o)]}}))}))},e.prototype.loadElement=function(e){return new Promise((function(t,n){return document.getElementById(e)&&document.getElementById(e).clientHeight?t(!0):n(!0)}))},e.prototype.isElementFullyLoaded=function(e,t,n,r){var i=this;return new Promise((function(o,s){return e(t).then(o).catch((function(a){return r-1>0?(u=n,new Promise((function(e){return setTimeout(e,u)}))).then(i.isElementFullyLoaded.bind(null,e,t,n,r-1)).then(o).catch(s):s(a);var u}))}))},e.prototype.getCategory=function(){return"Analytics"},e.prototype.getProviderName=function(){return"AmazonPersonalize"},e.prototype.configure=function(e){me.debug("configure Analytics",e);var t=e||{};return this._config=Object.assign({},this._config,t),se()(this._config.trackingId)||(this._sessionInfo=this._sessionManager.retrieveSessionInfo(this._config.trackingId)),this._setupTimer(),this._config},e.prototype.generateRequestParams=function(e,t){var n={},r=e.event,i=r.eventType,o=r.properties;return n.eventData={eventType:i,properties:o},n.sessionInfo=t,n.sentAt=e.sentAt,n.credentials=e.credentials,n.config=e.config,n},e.prototype._sendEvents=function(e){var t=e.length;if(0!==t){var n=e[0],r=n.config,i=n.credentials,o=n.sessionInfo;if(!this._init(r,i))return!1;if(t>0){for(var s=[],a=0;a0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},c=function(){for(var e=[],t=0;t0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=300?[2,st(e,t)]:[4,Et(e.body,t)];case 1:return n=o.sent(),{},r=gt(n,t),i=a({$metadata:wt(e)},r),[2,Promise.resolve(i)]}}))}))}(e,t)},t}(rt.b),It=n(151),kt=n(38),Ot=n(18),xt=n(24),Ct=n(11),Tt=n(39),Pt=n(17),Nt=n(40),Rt=n(41),Lt=n(15),jt=new Set(["ap-east-1","ap-northeast-1","ap-northeast-2","ap-south-1","ap-southeast-1","ap-southeast-2","ca-central-1","eu-central-1","eu-north-1","eu-west-1","eu-west-2","eu-west-3","me-south-1","sa-east-1","us-east-1","us-east-2","us-west-1","us-west-2"]),Dt=new Set(["cn-north-1","cn-northwest-1"]),Ut=new Set(["us-iso-east-1"]),Bt=new Set(["us-isob-east-1"]),Ft=new Set(["us-gov-east-1","us-gov-west-1"]),zt=a(a({},{apiVersion:"2015-08-04",disableHostPrefix:!1,logger:{},regionInfoProvider:function(e,t){var n=void 0;switch(e){case"ap-east-1":n={hostname:"firehose.ap-east-1.amazonaws.com",partition:"aws"};break;case"ap-northeast-1":n={hostname:"firehose.ap-northeast-1.amazonaws.com",partition:"aws"};break;case"ap-northeast-2":n={hostname:"firehose.ap-northeast-2.amazonaws.com",partition:"aws"};break;case"ap-south-1":n={hostname:"firehose.ap-south-1.amazonaws.com",partition:"aws"};break;case"ap-southeast-1":n={hostname:"firehose.ap-southeast-1.amazonaws.com",partition:"aws"};break;case"ap-southeast-2":n={hostname:"firehose.ap-southeast-2.amazonaws.com",partition:"aws"};break;case"ca-central-1":n={hostname:"firehose.ca-central-1.amazonaws.com",partition:"aws"};break;case"cn-north-1":n={hostname:"firehose.cn-north-1.amazonaws.com.cn",partition:"aws-cn"};break;case"cn-northwest-1":n={hostname:"firehose.cn-northwest-1.amazonaws.com.cn",partition:"aws-cn"};break;case"eu-central-1":n={hostname:"firehose.eu-central-1.amazonaws.com",partition:"aws"};break;case"eu-north-1":n={hostname:"firehose.eu-north-1.amazonaws.com",partition:"aws"};break;case"eu-west-1":n={hostname:"firehose.eu-west-1.amazonaws.com",partition:"aws"};break;case"eu-west-2":n={hostname:"firehose.eu-west-2.amazonaws.com",partition:"aws"};break;case"eu-west-3":n={hostname:"firehose.eu-west-3.amazonaws.com",partition:"aws"};break;case"me-south-1":n={hostname:"firehose.me-south-1.amazonaws.com",partition:"aws"};break;case"sa-east-1":n={hostname:"firehose.sa-east-1.amazonaws.com",partition:"aws"};break;case"us-east-1":n={hostname:"firehose.us-east-1.amazonaws.com",partition:"aws"};break;case"us-east-2":n={hostname:"firehose.us-east-2.amazonaws.com",partition:"aws"};break;case"us-gov-east-1":n={hostname:"firehose.us-gov-east-1.amazonaws.com",partition:"aws-us-gov"};break;case"us-gov-west-1":n={hostname:"firehose.us-gov-west-1.amazonaws.com",partition:"aws-us-gov"};break;case"us-west-1":n={hostname:"firehose.us-west-1.amazonaws.com",partition:"aws"};break;case"us-west-2":n={hostname:"firehose.us-west-2.amazonaws.com",partition:"aws"};break;default:jt.has(e)&&(n={hostname:"firehose.{region}.amazonaws.com".replace("{region}",e),partition:"aws"}),Dt.has(e)&&(n={hostname:"firehose.{region}.amazonaws.com.cn".replace("{region}",e),partition:"aws-cn"}),Ut.has(e)&&(n={hostname:"firehose.{region}.c2s.ic.gov".replace("{region}",e),partition:"aws-iso"}),Bt.has(e)&&(n={hostname:"firehose.{region}.sc2s.sgov.gov".replace("{region}",e),partition:"aws-iso-b"}),Ft.has(e)&&(n={hostname:"firehose.{region}.amazonaws.com".replace("{region}",e),partition:"aws-us-gov"}),void 0===n&&(n={hostname:"firehose.{region}.amazonaws.com".replace("{region}",e),partition:"aws"})}return Promise.resolve(n)},signingName:"firehose"}),{runtime:"browser",base64Decoder:Pt.a,base64Encoder:Pt.b,bodyLengthChecker:Nt.a,credentialDefaultProvider:Object(xt.a)("Credential is missing"),defaultUserAgent:Object(Rt.a)(It.name,It.version),maxAttempts:Ct.a,region:Object(xt.a)("Region is missing"),requestHandler:new Ot.a,sha256:kt.Sha256,streamCollector:Ot.b,urlParser:Tt.a,utf8Decoder:Lt.a,utf8Encoder:Lt.b}),qt=n(22),Kt=n(37),Ht=n(21),Vt=n(43),Gt=n(25),Wt=n(23),$t=function(e){function t(t){var n=this,r=a(a({},zt),t),i=Object(qt.b)(r),o=Object(qt.a)(i),s=Object(Gt.b)(o),u=Object(Ct.c)(s),c=Object(Wt.b)(u),f=Object(Ht.b)(c);return(n=e.call(this,f)||this).config=f,n.middlewareStack.use(Object(Gt.a)(n.config)),n.middlewareStack.use(Object(Ct.b)(n.config)),n.middlewareStack.use(Object(Wt.a)(n.config)),n.middlewareStack.use(Object(Kt.a)(n.config)),n.middlewareStack.use(Object(Ht.a)(n.config)),n.middlewareStack.use(Object(Vt.a)(n.config)),n}return s(t,e),t.prototype.destroy=function(){e.prototype.destroy.call(this)},t}(rt.a),Yt=(it=function(e,t){return(it=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}it(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Jt=new r.a("AWSKineisFirehoseProvider"),Zt=function(e){function t(t){return e.call(this,t)||this}return Yt(t,e),t.prototype.getProviderName=function(){return"AWSKinesisFirehose"},t.prototype._sendEvents=function(e){var t=this;if(0!==e.length){var n=e[0],r=n.config,i=n.credentials;if(!this._init(r,i))return!1;var o={};e.map((function(e){var t=e.event,n=t.streamName,r=t.data;void 0===o[n]&&(o[n]=[]);var i=r&&"string"!=typeof r?JSON.stringify(r):r,s={Data:Object(Lt.a)(i)};o[n].push(s)})),Object.keys(o).map((function(e){Jt.debug("putting records to kinesis",e,"with records",o[e]),t._kinesisFirehose.send(new At({Records:o[e],DeliveryStreamName:e})).then((function(t){return Jt.debug("Upload records to stream",e)})).catch((function(e){return Jt.debug("Failed to upload records to Kinesis",e)}))}))}},t.prototype._init=function(e,t){if(Jt.debug("init clients"),this._kinesisFirehose&&this._config.credentials&&this._config.credentials.sessionToken===t.sessionToken&&this._config.credentials.identityId===t.identityId)return Jt.debug("no change for analytics config, directly return from init"),!0;this._config.credentials=t;var n=e.region;return this._initFirehose(n,t)},t.prototype._initFirehose=function(e,t){return Jt.debug("initialize kinesis firehose with credentials",t),this._kinesisFirehose=new $t({apiVersion:"2015-08-04",region:e,credentials:t}),!0},t}(i.a)},function(e,t,n){"use strict";n.d(t,"a",(function(){return T}));var r,i=n(44),o=n(19),s=n(5),a=n(89),u=n(104),c=function(){return(c=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},A=new i.a("SumerianProvider"),I=function(e){function t(t){return void 0===t&&(t={}),e.call(this,t)||this}return w(t,e),t.prototype.getProviderName=function(){return"SumerianProvider"},t.prototype.loadScript=function(e){return S(this,void 0,void 0,(function(){return E(this,(function(t){return[2,new Promise((function(t,n){var r=document.createElement("script");r.src=e,r.addEventListener("load",(function(e){t()})),r.addEventListener("error",(function(t){n(new Error("Failed to load script: "+e))})),document.head.appendChild(r)}))]}))}))},t.prototype.loadScene=function(e,t,n){return S(this,void 0,void 0,(function(){var r,i,o,c,f,l,d,h,p,v,g,y,w,S,I,k,O,x,C,T,P,N,R,L,j,D,U;return E(this,(function(E){switch(E.label){case 0:if(!e)throw l="No scene name passed into loadScene",A.error(l),new b(l);if(!t)throw l="No dom element id passed into loadScene",A.error(l),new m(l);if(!(r=document.getElementById(t)))throw l="DOM element id, "+t+" not found",A.error(l),new m(l);if(!(i=this.getScene(e)).sceneConfig)throw l="No scene config configured for scene: "+e,A.error(l),new b(l);if(o=i.sceneConfig.url,c=i.sceneConfig.sceneId,i.sceneConfig.hasOwnProperty("region"))f=i.sceneConfig.region;else{if(!this.options.hasOwnProperty("region"))throw l="No region configured for scene: "+e,A.error(l),new b(l);f=this.options.region}d={region:f,customUserAgent:s.a.userAgent+"-SumerianScene"},h={headers:{"X-Amz-User-Agent":s.a.userAgent}},p=o,E.label=1;case 1:return E.trys.push([1,3,,4]),[4,a.a.get()];case 2:return v=E.sent(),d.credentials=v,g={secret_key:v.secretAccessKey,access_key:v.accessKeyId,session_token:v.sessionToken},y={region:f,service:"sumerian"},w=u.a.sign({method:"GET",url:o},g,y),h.headers=_(_({},h.headers),w.headers),p=w.url,[3,4];case 3:return E.sent(),A.debug("No credentials available, the request will be unsigned"),[3,4];case 4:return[4,fetch(p,h)];case 5:return[4,(S=E.sent()).json()];case 6:if(I=E.sent(),403===S.status)throw I.message?(A.error("Failure to authenticate user: "+I.message),new b("Failure to authenticate user: "+I.message)):(A.error("Failure to authenticate user"),new b("Failure to authenticate user"));return k=I.bundleData[c],[4,fetch(k.url,{headers:k.headers})];case 7:return[4,E.sent().json()];case 8:O=E.sent(),E.label=9;case 9:return E.trys.push([9,11,,12]),[4,this.loadScript(O[c].bootstrapperUrl)];case 10:return E.sent(),[3,12];case 11:throw x=E.sent(),A.error(x),new b(x);case 12:return C=n.progressCallback?n.progressCallback:void 0,T=i.publishParamOverrides?i.publishParamOverrides:void 0,P={element:r,sceneId:c,sceneBundle:O,apiResponse:I,progressCallback:C,publishParamOverrides:T,awsSDKConfigOverride:d},[4,window.SumerianBootstrapper.loadScene(P)];case 13:N=E.sent(),i.sceneController=N,i.isLoaded=!0;try{for(R=M(N.sceneLoadWarnings),L=R.next();!L.done;L=R.next())j=L.value,A.warn("loadScene warning: "+j)}catch(e){D={error:e}}finally{try{L&&!L.done&&(U=R.return)&&U.call(R)}finally{if(D)throw D.error}}return[2]}}))}))},t.prototype.isSceneLoaded=function(e){return this.getScene(e).isLoaded||!1},t.prototype.getScene=function(e){if(!this.options.scenes){var t="No scenes were defined in the configuration";throw A.error(t),new p(t)}if(!e){t="No scene name was passed";throw A.error(t),new v(t)}if(!this.options.scenes[e]){t="Scene '"+e+"' is not configured";throw A.error(t),new v(t)}return this.options.scenes[e]},t.prototype.getSceneController=function(e){if(!this.options.scenes){var t="No scenes were defined in the configuration";throw A.error(t),new p(t)}var n=this.options.scenes[e];if(!n){t="Scene '"+e+"' is not configured";throw A.error(t),new v(t)}var r=n.sceneController;if(!r){t="Scene controller for '"+e+"' has not been loaded";throw A.error(t),new g(t)}return r},t.prototype.isVRCapable=function(e){return this.getSceneController(e).vrCapable},t.prototype.isVRPresentationActive=function(e){return this.getSceneController(e).vrPresentationActive},t.prototype.start=function(e){this.getSceneController(e).start()},t.prototype.enterVR=function(e){this.getSceneController(e).enterVR()},t.prototype.exitVR=function(e){this.getSceneController(e).exitVR()},t.prototype.isMuted=function(e){return this.getSceneController(e).muted},t.prototype.setMuted=function(e,t){this.getSceneController(e).muted=t},t.prototype.onSceneEvent=function(e,t,n){this.getSceneController(e).on(t,n)},t.prototype.enableAudio=function(e){this.getSceneController(e).enableAudio()},t}(l),k=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))},O=function(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},C=new i.a("XR"),T=new(function(){function e(e){this._options=e,C.debug("XR Options",this._options),this._defaultProvider="SumerianProvider",this._pluggables={},this.addPluggable(new I)}return e.prototype.configure=function(e){var t=this,n=e?e.XR||e:{};return C.debug("configure XR",{opt:n}),this._options=Object.assign({},this._options,n),Object.entries(this._pluggables).map((function(e){var r=x(e,2),i=r[0],o=r[1];i!==t._defaultProvider||n[t._defaultProvider]?o.configure(t._options[i]):o.configure(t._options)})),this._options},e.prototype.addPluggable=function(e){return k(this,void 0,void 0,(function(){return O(this,(function(t){return e&&"XR"===e.getCategory()?(this._pluggables[e.getProviderName()]=e,[2,e.configure(this._options)]):[2]}))}))},e.prototype.loadScene=function(e,t,n,r){return void 0===n&&(n={}),void 0===r&&(r=this._defaultProvider),k(this,void 0,void 0,(function(){return O(this,(function(i){switch(i.label){case 0:if(!this._pluggables[r])throw new y("Provider '"+r+"' not configured");return[4,this._pluggables[r].loadScene(e,t,n)];case 1:return[2,i.sent()]}}))}))},e.prototype.isSceneLoaded=function(e,t){if(void 0===t&&(t=this._defaultProvider),!this._pluggables[t])throw new y("Provider '"+t+"' not configured");return this._pluggables[t].isSceneLoaded(e)},e.prototype.getSceneController=function(e,t){if(void 0===t&&(t=this._defaultProvider),!this._pluggables[t])throw new y("Provider '"+t+"' not configured");return this._pluggables[t].getSceneController(e)},e.prototype.isVRCapable=function(e,t){if(void 0===t&&(t=this._defaultProvider),!this._pluggables[t])throw new y("Provider '"+t+"' not configured");return this._pluggables[t].isVRCapable(e)},e.prototype.isVRPresentationActive=function(e,t){if(void 0===t&&(t=this._defaultProvider),!this._pluggables[t])throw new y("Provider '"+t+"' not configured");return this._pluggables[t].isVRPresentationActive(e)},e.prototype.start=function(e,t){if(void 0===t&&(t=this._defaultProvider),!this._pluggables[t])throw new y("Provider '"+t+"' not configured");return this._pluggables[t].start(e)},e.prototype.enterVR=function(e,t){if(void 0===t&&(t=this._defaultProvider),!this._pluggables[t])throw new y("Provider '"+t+"' not configured");return this._pluggables[t].enterVR(e)},e.prototype.exitVR=function(e,t){if(void 0===t&&(t=this._defaultProvider),!this._pluggables[t])throw new y("Provider '"+t+"' not configured");return this._pluggables[t].exitVR(e)},e.prototype.isMuted=function(e,t){if(void 0===t&&(t=this._defaultProvider),!this._pluggables[t])throw new y("Provider '"+t+"' not configured");return this._pluggables[t].isMuted(e)},e.prototype.setMuted=function(e,t,n){if(void 0===n&&(n=this._defaultProvider),!this._pluggables[n])throw new y("Provider '"+n+"' not configured");return this._pluggables[n].setMuted(e,t)},e.prototype.onSceneEvent=function(e,t,n,r){if(void 0===r&&(r=this._defaultProvider),!this._pluggables[r])throw new y("Provider '"+r+"' not configured");return this._pluggables[r].onSceneEvent(e,t,n)},e.prototype.enableAudio=function(e,t){if(void 0===t&&(t=this._defaultProvider),!this._pluggables[t])throw new y("Provider '"+t+"' not configured");return this._pluggables[t].enableAudio(e)},e}())(null);o.a.register(T)},function(e,t,n){"use strict";n.r(t),n.d(t,"fromUtf8",(function(){return r})),n.d(t,"toUtf8",(function(){return i}));var r=function(e){return"function"==typeof TextEncoder?function(e){return(new TextEncoder).encode(e)}(e):function(e){for(var t=[],n=0,r=e.length;n>6|192,63&i|128);else if(n+1>18|240,o>>12&63|128,o>>6&63|128,63&o|128)}else t.push(i>>12|224,i>>6&63|128,63&i|128)}return Uint8Array.from(t)}(e)},i=function(e){return"function"==typeof TextDecoder?function(e){return new TextDecoder("utf-8").decode(e)}(e):function(e){for(var t="",n=0,r=e.length;n(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function d(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(o||(o=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(v(this),t),p(s.get(this))}:function(...t){return p(e.apply(v(this),t))}:function(t,...n){const r=e.call(v(this),t,...n);return u.set(r,t.sort?t.sort():[t]),p(r)}}function h(e){return"function"==typeof e?d(e):(e instanceof IDBTransaction&&function(e){if(a.has(e))return;const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",o),e.removeEventListener("abort",o)},i=()=>{t(),r()},o=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",i),e.addEventListener("error",o),e.addEventListener("abort",o)});a.set(e,t)}(e),t=e,(i||(i=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])).some(e=>t instanceof e)?new Proxy(e,l):e);var t}function p(e){if(e instanceof IDBRequest)return function(e){const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("success",i),e.removeEventListener("error",o)},i=()=>{t(p(e.result)),r()},o=()=>{n(e.error),r()};e.addEventListener("success",i),e.addEventListener("error",o)});return t.then(t=>{t instanceof IDBCursor&&s.set(t,e)}).catch(()=>{}),f.set(t,e),t}(e);if(c.has(e))return c.get(e);const t=h(e);return t!==e&&(c.set(e,t),f.set(t,e)),t}const v=e=>f.get(e);function g(e,t,{blocked:n,upgrade:r,blocking:i,terminated:o}={}){const s=indexedDB.open(e,t),a=p(s);return r&&s.addEventListener("upgradeneeded",e=>{r(p(s.result),e.oldVersion,e.newVersion,p(s.transaction))}),n&&s.addEventListener("blocked",()=>n()),a.then(e=>{o&&e.addEventListener("close",()=>o()),i&&e.addEventListener("versionchange",()=>i())}).catch(()=>{}),a}function m(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",()=>t()),p(n).then(()=>{})}const b=["get","getKey","getAll","getAllKeys","count"],y=["put","add","delete","clear"],w=new Map;function _(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(w.get(t))return w.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=y.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!b.includes(n))return;const o=async function(e,...t){const o=this.transaction(e,i?"readwrite":"readonly");let s=o.store;r&&(s=s.index(t.shift()));const a=await s[n](...t);return i&&await o.done,a};return w.set(t,o),o}l=(e=>({...e,get:(t,n,r)=>_(t,n)||e.get(t,n,r),has:(t,n)=>!!_(t,n)||e.has(t,n)}))(l);var S=n(9),E=n(245),M=n(4),A=n(3);function I(e){return(I="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var k=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))},O=function(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},T=function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},P=function(){for(var e=[],t=0;t0?u+a:e.length;return e.slice(u,c)}return e},e.prototype.enginePagination=function(e,t){return k(this,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,f,l,d;return O(this,(function(h){switch(h.label){case 0:return t?(r=t.page,i=void 0===r?0:r,o=t.limit,s=void 0===o?0:o,a=Math.max(0,i*s)||0,[4,this.db.transaction(e).objectStore(e).openCursor()]):[3,7];case 1:return(u=h.sent())&&a>0?[4,u.advance(a)]:[3,3];case 2:h.sent(),h.label=3;case 3:c=[],f="number"==typeof s&&s>0,l=!0,d=s,h.label=4;case 4:return l&&u&&u.value?(c.push(u.value),[4,u.continue()]):[3,6];case 5:return u=h.sent(),f?(d--,l=d>0&&null!==u):l=null!==u,[3,4];case 6:return n=c,[3,9];case 7:return[4,this.db.getAll(e)];case 8:n=h.sent(),h.label=9;case 9:return[2,n]}}))}))},e.prototype.queryOne=function(e,t){return void 0===t&&(t=M.d.FIRST),k(this,void 0,void 0,(function(){var n,r,i;return O(this,(function(o){switch(o.label){case 0:return[4,this.checkPrivate()];case 1:return o.sent(),n=this.getStorenameForModel(e),[4,this.db.transaction([n],"readonly").objectStore(n).openCursor(void 0,t===M.d.FIRST?"next":"prev")];case 2:return r=o.sent(),[2,(i=r?r.value:void 0)&&this.modelInstanceCreator(e,i)]}}))}))},e.prototype.delete=function(e,t){return k(this,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,f,l,d,h,p,v,g;return O(this,(function(m){switch(m.label){case 0:return[4,this.checkPrivate()];case 1:return m.sent(),n=[],Object(A.s)(e)?(o=e,s=this.namespaceResolver(o),a=this.getStorenameForModel(o),[4,this.query(o,t)]):[3,9];case 2:return r=m.sent(),v=this.schema.namespaces[s].relationships[o.name].relationTypes,void 0===t?[3,5]:[4,this.deleteTraverse(v,r,o.name,s,n)];case 3:return m.sent(),[4,this.deleteItem(n)];case 4:return m.sent(),g=n.reduce((function(e,t){var n=t.items;return e.concat(n)}),[]),[2,[r,g]];case 5:return[4,this.deleteTraverse(v,r,o.name,s,n)];case 6:return m.sent(),[4,this.db.transaction([a],"readwrite").objectStore(a).clear()];case 7:return m.sent(),g=n.reduce((function(e,t){var n=t.items;return e.concat(n)}),[]),[2,[r,g]];case 8:return[3,17];case 9:return i=e,o=Object.getPrototypeOf(i).constructor,s=this.namespaceResolver(o),a=this.getStorenameForModel(o),t?(u=this.db.transaction([a],"readwrite"),c=u.objectStore(a),[4,this._get(c,i.id)]):[3,13];case 10:if(void 0===(f=m.sent()))return p="Model instance not found in storage",N.warn(p,{model:i}),[2,[[i],[]]];if(l=S.a.getPredicates(t),d=l.predicates,h=l.type,!Object(A.y)(f,h,d))throw p="Conditional update failed",N.error(p,{model:f,condition:d}),new Error(p);return[4,u.done];case 11:return m.sent(),v=this.schema.namespaces[s].relationships[o.name].relationTypes,[4,this.deleteTraverse(v,[i],o.name,s,n)];case 12:return m.sent(),[3,15];case 13:return v=this.schema.namespaces[s].relationships[o.name].relationTypes,[4,this.deleteTraverse(v,[i],o.name,s,n)];case 14:m.sent(),m.label=15;case 15:return[4,this.deleteItem(n)];case 16:return m.sent(),g=n.reduce((function(e,t){var n=t.items;return e.concat(n)}),[]),[2,[[i],g]];case 17:return[2]}}))}))},e.prototype.deleteItem=function(e){var t,n,r,i,o,s;return k(this,void 0,void 0,(function(){var a,u,c,f,l,d,h,p,v,g,m,b;return O(this,(function(y){switch(y.label){case 0:a=e.map((function(e){return e.storeName})),u=this.db.transaction(P(a),"readwrite"),y.label=1;case 1:y.trys.push([1,22,23,28]),t=x(e),y.label=2;case 2:return[4,t.next()];case 3:if((n=y.sent()).done)return[3,21];c=n.value,f=c.storeName,l=c.items,d=u.objectStore(f),y.label=4;case 4:y.trys.push([4,14,15,20]),h=x(l),y.label=5;case 5:return[4,h.next()];case 6:return(p=y.sent()).done?[3,13]:(v=p.value)?(g=void 0,"object"!==I(v)?[3,8]:[4,d.index("byId").getKey(v.id)]):[3,12];case 7:return g=y.sent(),[3,10];case 8:return[4,d.index("byId").getKey(v.toString())];case 9:g=y.sent(),y.label=10;case 10:return void 0===g?[3,12]:[4,d.delete(g)];case 11:y.sent(),y.label=12;case 12:return[3,5];case 13:return[3,20];case 14:return m=y.sent(),o={error:m},[3,20];case 15:return y.trys.push([15,,18,19]),p&&!p.done&&(s=h.return)?[4,s.call(h)]:[3,17];case 16:y.sent(),y.label=17;case 17:return[3,19];case 18:if(o)throw o.error;return[7];case 19:return[7];case 20:return[3,2];case 21:return[3,28];case 22:return b=y.sent(),r={error:b},[3,28];case 23:return y.trys.push([23,,26,27]),n&&!n.done&&(i=t.return)?[4,i.call(t)]:[3,25];case 24:y.sent(),y.label=25;case 25:return[3,27];case 26:if(r)throw r.error;return[7];case 27:return[7];case 28:return[2]}}))}))},e.prototype.deleteTraverse=function(e,t,n,r,i){var o,s,a,u,c,f,l,d,h,p,v,g;return k(this,void 0,void 0,(function(){var m,b,y,w,_,S,E,M,I,k,C,T=this;return O(this,(function(O){switch(O.label){case 0:O.trys.push([0,35,36,41]),o=x(e),O.label=1;case 1:return[4,o.next()];case 2:if((s=O.sent()).done)return[3,34];switch(m=s.value,b=m.relationType,m.fieldName,y=m.modelName,w=this.getStorename(r,y),_=Object(A.g)(this.schema.namespaces[r].relationships[y].relationTypes,n)||Object(A.h)(this.schema.namespaces[r].relationships[y].indexes,m.associatedWith),b){case"HAS_ONE":return[3,3];case"HAS_MANY":return[3,17];case"BELONGS_TO":return[3,31]}return[3,32];case 3:O.trys.push([3,10,11,16]),a=x(t),O.label=4;case 4:return[4,a.next()];case 5:return(u=O.sent()).done?[3,9]:(M=u.value,[4,this.db.transaction(w,"readwrite").objectStore(w).index(_).get(M.id)]);case 6:return S=O.sent(),[4,this.deleteTraverse(this.schema.namespaces[r].relationships[y].relationTypes,S?[S]:[],y,r,i)];case 7:O.sent(),O.label=8;case 8:return[3,4];case 9:return[3,16];case 10:return E=O.sent(),h={error:E},[3,16];case 11:return O.trys.push([11,,14,15]),u&&!u.done&&(p=a.return)?[4,p.call(a)]:[3,13];case 12:O.sent(),O.label=13;case 13:return[3,15];case 14:if(h)throw h.error;return[7];case 15:return[7];case 16:return[3,33];case 17:O.trys.push([17,24,25,30]),c=x(t),O.label=18;case 18:return[4,c.next()];case 19:return(f=O.sent()).done?[3,23]:(M=f.value,[4,this.db.transaction(w,"readwrite").objectStore(w).index(_).getAll(M.id)]);case 20:return I=O.sent(),[4,this.deleteTraverse(this.schema.namespaces[r].relationships[y].relationTypes,I,y,r,i)];case 21:O.sent(),O.label=22;case 22:return[3,18];case 23:return[3,30];case 24:return k=O.sent(),v={error:k},[3,30];case 25:return O.trys.push([25,,28,29]),f&&!f.done&&(g=c.return)?[4,g.call(c)]:[3,27];case 26:O.sent(),O.label=27;case 27:return[3,29];case 28:if(v)throw v.error;return[7];case 29:return[7];case 30:case 31:return[3,33];case 32:return Object(A.f)(b),[3,33];case 33:return[3,1];case 34:return[3,41];case 35:return C=O.sent(),l={error:C},[3,41];case 36:return O.trys.push([36,,39,40]),s&&!s.done&&(d=o.return)?[4,d.call(o)]:[3,38];case 37:O.sent(),O.label=38;case 38:return[3,40];case 39:if(l)throw l.error;return[7];case 40:return[7];case 41:return i.push({storeName:this.getStorename(r,n),items:t.map((function(e){return T.modelInstanceCreator(T.getModelConstructorByModelName(r,n),e)}))}),[2]}}))}))},e.prototype.clear=function(){return k(this,void 0,void 0,(function(){return O(this,(function(e){switch(e.label){case 0:return[4,this.checkPrivate()];case 1:return e.sent(),this.db.close(),[4,m(this.dbName)];case 2:return e.sent(),this.db=void 0,this.initPromise=void 0,[2]}}))}))},e.prototype.batchSave=function(e,t){return k(this,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,f,l,d,h;return O(this,(function(p){switch(p.label){case 0:return 0===t.length?[2,[]]:[4,this.checkPrivate()];case 1:p.sent(),n=[],r=this.getStorenameForModel(e),i=this.db.transaction(r,"readwrite"),o=i.store,s=function(t){var r,i,s,u,c;return O(this,(function(f){switch(f.label){case 0:return r=Object(A.x)(e.name,a.modelInstanceCreator(e,t),a.schema.namespaces[a.namespaceResolver(e)],a.modelInstanceCreator,a.getModelConstructorByModelName),i=t.id,s=t._deleted,[4,o.index("byId").getKey(i)];case 1:return u=f.sent(),s?[3,3]:(c=r.find((function(e){return e.instance.id===i})).instance,n.push([c,u?M.c.UPDATE:M.c.INSERT]),[4,o.put(c,u)]);case 2:return f.sent(),[3,5];case 3:return n.push([t,M.c.DELETE]),u?[4,o.delete(u)]:[3,5];case 4:f.sent(),f.label=5;case 5:return[2]}}))},a=this,p.label=2;case 2:p.trys.push([2,7,8,9]),u=C(t),c=u.next(),p.label=3;case 3:return c.done?[3,6]:(f=c.value,[5,s(f)]);case 4:p.sent(),p.label=5;case 5:return c=u.next(),[3,3];case 6:return[3,9];case 7:return l=p.sent(),d={error:l},[3,9];case 8:try{c&&!c.done&&(h=u.return)&&h.call(u)}finally{if(d)throw d.error}return[7];case 9:return[4,i.done];case 10:return p.sent(),[2,n]}}))}))},e}();t.default=new R},function(e,t,n){"use strict";n.r(t),n.d(t,"AsyncStorageAdapter",(function(){return I}));var r=n(44),i=n(4),o=n(3),s=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))},a=function(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},c=function(){var e=this;this.db=new Map,this.getAllKeys=function(){return s(e,void 0,void 0,(function(){return a(this,(function(e){return[2,Array.from(this.db.keys())]}))}))},this.multiGet=function(t){return s(e,void 0,void 0,(function(){var e=this;return a(this,(function(n){return[2,t.reduce((function(t,n){return t.push([n,e.db.get(n)]),t}),[])]}))}))},this.multiRemove=function(t,n){return s(e,void 0,void 0,(function(){var e=this;return a(this,(function(r){return t.forEach((function(t){return e.db.delete(t)})),n(),[2]}))}))},this.multiSet=function(t,n){return s(e,void 0,void 0,(function(){var e=this;return a(this,(function(r){return t.forEach((function(t){var n=u(t,2),r=n[0],i=n[1];e.setItem(r,i)})),n(),[2]}))}))},this.setItem=function(t,n){return s(e,void 0,void 0,(function(){return a(this,(function(e){return[2,this.db.set(t,n)]}))}))},this.removeItem=function(t){return s(e,void 0,void 0,(function(){return a(this,(function(e){return[2,this.db.delete(t)]}))}))},this.getItem=function(t){return s(e,void 0,void 0,(function(){return a(this,(function(e){return[2,this.db.get(t)]}))}))}};var f=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))},l=function(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},h=function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},p="@AmplifyDatastore",v=new Map,g=function(){function e(){this._collectionInMemoryIndex=new Map,this.storage=new c}return e.prototype.getCollectionIndex=function(e){return this._collectionInMemoryIndex.has(e)||this._collectionInMemoryIndex.set(e,new Map),this._collectionInMemoryIndex.get(e)},e.prototype.getMonotonicFactory=function(e){return v.has(e)||v.set(e,Object(o.v)()),v.get(e)},e.prototype.init=function(){return f(this,void 0,void 0,(function(){var e,t,n,r,i,o,s,a,u,c,f,v,g,m,b,y,w,_,S,E;return l(this,(function(l){switch(l.label){case 0:return this._collectionInMemoryIndex.clear(),[4,this.storage.getAllKeys()];case 1:e=l.sent(),t=[],l.label=2;case 2:l.trys.push([2,12,13,14]),n=d(e),r=n.next(),l.label=3;case 3:return r.done?[3,11]:(i=r.value,o=h(i.split("::"),5),s=o[0],a=o[1],u=o[2],c=o[3],f=o[4],s!==p?[3,10]:"Data"!==u?[3,9]:(v=void 0,void 0!==f?[3,7]:(g=c,m=this.getMonotonicFactory(a)(),b=this.getLegacyKeyForItem(a,g),y=this.getKeyForItem(a,g,m),[4,this.storage.getItem(b)])));case 4:return w=l.sent(),[4,this.storage.setItem(y,w)];case 5:return l.sent(),[4,this.storage.removeItem(b)];case 6:return l.sent(),v=m,[3,8];case 7:v=c,l.label=8;case 8:return this.getCollectionIndex(a).set(f,v),[3,10];case 9:"Collection"===u&&t.push(i),l.label=10;case 10:return r=n.next(),[3,3];case 11:return[3,14];case 12:return _=l.sent(),S={error:_},[3,14];case 13:try{r&&!r.done&&(E=n.return)&&E.call(n)}finally{if(S)throw S.error}return[7];case 14:return t.length>0?[4,this.storage.multiRemove(t)]:[3,16];case 15:l.sent(),l.label=16;case 16:return[2]}}))}))},e.prototype.save=function(e,t){return f(this,void 0,void 0,(function(){var n,r;return l(this,(function(i){switch(i.label){case 0:return n=this.getCollectionIndex(t).get(e.id)||this.getMonotonicFactory(t)(),r=this.getKeyForItem(t,e.id,n),this.getCollectionIndex(t).set(e.id,n),[4,this.storage.setItem(r,JSON.stringify(e))];case 1:return i.sent(),[2]}}))}))},e.prototype.batchSave=function(e,t){return f(this,void 0,void 0,(function(){var n,r,o,s,a,u,c,f,p,v,g,m,b,y,w,_,S,E,M,A,I,k=this;return l(this,(function(l){switch(l.label){case 0:if(0===t.length)return[2,[]];n=[],r=this.getCollectionIndex(e),o=new Set,s=new Set,a=[],u={};try{for(c=d(t),f=c.next();!f.done;f=c.next())p=f.value,v=p.id,g=p._deleted,m=r.get(v)||this.getMonotonicFactory(e)(),S=this.getKeyForItem(e,v,m),a.push(S),u[S]={ulid:m,model:p},g?o.add(S):s.add(S)}catch(e){E={error:e}}finally{try{f&&!f.done&&(M=c.return)&&M.call(c)}finally{if(E)throw E.error}}return[4,this.storage.multiGet(a)];case 1:return b=l.sent(),y=b.filter((function(e){return!!h(e,2)[1]})).reduce((function(e,t){var n=h(t,1)[0];return e.add(n)}),new Set),[4,new Promise((function(e,t){if(0!==o.size){var n=Array.from(o);n.forEach((function(e){return r.delete(u[e].model.id)})),k.storage.multiRemove(n,(function(n){n&&n.length>0?t(n):e()}))}else e()}))];case 2:return l.sent(),[4,new Promise((function(e,t){if(0!==s.size){var n=Array.from(s).map((function(e){return[e,JSON.stringify(u[e].model)]}));s.forEach((function(e){var t=u[e],n=t.model.id,i=t.ulid;r.set(n,i)})),k.storage.multiSet(n,(function(n){n&&n.length>0?t(n):e()}))}else e()}))];case 3:l.sent();try{for(w=d(a),_=w.next();!_.done;_=w.next())S=_.value,o.has(S)&&y.has(S)?n.push([u[S].model,i.c.DELETE]):s.has(S)&&n.push([u[S].model,y.has(S)?i.c.UPDATE:i.c.INSERT])}catch(e){A={error:e}}finally{try{_&&!_.done&&(I=w.return)&&I.call(w)}finally{if(A)throw A.error}}return[2,n]}}))}))},e.prototype.get=function(e,t){return f(this,void 0,void 0,(function(){var n,r,i;return l(this,(function(o){switch(o.label){case 0:return n=this.getCollectionIndex(t).get(e),r=this.getKeyForItem(t,e,n),[4,this.storage.getItem(r)];case 1:return i=o.sent(),[2,i&&JSON.parse(i)]}}))}))},e.prototype.getOne=function(e,t){return f(this,void 0,void 0,(function(){var n,r,o,s,a,u,c;return l(this,(function(f){switch(f.label){case 0:return n=this.getCollectionIndex(t),r=h(e===i.d.FIRST?function(){var e,t,r,i,o;try{for(var s=d(n),a=s.next();!a.done;a=s.next()){i=(r=h(a.value,2))[0],o=r[1];break}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}return[i,o]}():function(){var e,t,r,i,o;try{for(var s=d(n),a=s.next();!a.done;a=s.next())i=(r=h(a.value,2))[0],o=r[1]}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}return[i,o]}(),2),o=r[0],s=r[1],a=this.getKeyForItem(t,o,s),(c=a)?[4,this.storage.getItem(a)]:[3,2];case 1:c=f.sent(),f.label=2;case 2:return[2,(u=c)&&JSON.parse(u)||void 0]}}))}))},e.prototype.getAll=function(e,t){return f(this,void 0,void 0,(function(){var n,r,i,o,s,a,u,c,f,p,v,g,m,b,y,w,_,S;return l(this,(function(l){switch(l.label){case 0:n=this.getCollectionIndex(e),i=(r=t||{}).page,o=void 0===i?0:i,s=r.limit,a=void 0===s?0:s,u=Math.max(0,o*a)||0,c=a>0?u+a:void 0,f=[],p=0;try{for(v=d(n),g=v.next();!g.done&&(m=h(g.value,2),b=m[0],y=m[1],++p<=u||(f.push(this.getKeyForItem(e,b,y)),p!==c));g=v.next());}catch(e){_={error:e}}finally{try{g&&!g.done&&(S=v.return)&&S.call(v)}finally{if(_)throw _.error}}return[4,this.storage.multiGet(f)];case 1:return w=l.sent(),[2,w.filter((function(e){return h(e,2)[1]})).map((function(e){var t=h(e,2)[1];return JSON.parse(t)}))]}}))}))},e.prototype.delete=function(e,t){return f(this,void 0,void 0,(function(){var n,r;return l(this,(function(i){switch(i.label){case 0:return n=this.getCollectionIndex(t).get(e),r=this.getKeyForItem(t,e,n),this.getCollectionIndex(t).delete(e),[4,this.storage.removeItem(r)];case 1:return i.sent(),[2]}}))}))},e.prototype.clear=function(){return f(this,void 0,void 0,(function(){var e,t;return l(this,(function(n){switch(n.label){case 0:return[4,this.storage.getAllKeys()];case 1:return e=n.sent(),t=e.filter((function(e){return e.startsWith(p)})),[4,this.storage.multiRemove(t)];case 2:return n.sent(),this._collectionInMemoryIndex.clear(),[2]}}))}))},e.prototype.getKeyForItem=function(e,t,n){return this.getKeyPrefixForStoreItems(e)+"::"+n+"::"+t},e.prototype.getLegacyKeyForItem=function(e,t){return this.getKeyPrefixForStoreItems(e)+"::"+t},e.prototype.getKeyPrefixForStoreItems=function(e){return p+"::"+e+"::Data"},e}(),m=n(9),b=n(245);function y(e){return(y="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var w=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))},_=function(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},M=function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},A=new r.a("DataStore"),I=function(){function e(){}return e.prototype.getStorenameForModel=function(e){var t=this.namespaceResolver(e),n=e.name;return this.getStorename(t,n)},e.prototype.getStorename=function(e,t){return e+"_"+t},e.prototype.setUp=function(e,t,n,r){return w(this,void 0,void 0,(function(){var i,o=this;return _(this,(function(s){switch(s.label){case 0:return this.initPromise?[3,1]:(this.initPromise=new Promise((function(e,t){o.resolve=e,o.reject=t})),[3,3]);case 1:return[4,this.initPromise];case 2:return s.sent(),[2];case 3:this.schema=e,this.namespaceResolver=t,this.modelInstanceCreator=n,this.getModelConstructorByModelName=r,s.label=4;case 4:return s.trys.push([4,7,,8]),this.db?[3,6]:(this.db=new g,[4,this.db.init()]);case 5:s.sent(),this.resolve(),s.label=6;case 6:return[3,8];case 7:return i=s.sent(),this.reject(i),[3,8];case 8:return[2]}}))}))},e.prototype.save=function(e,t){var n,r;return w(this,void 0,void 0,(function(){var s,a,u,c,f,l,d,h,p,v,g,b,y,w,E,M,I,k,O,x,C,T=this;return _(this,(function(_){switch(_.label){case 0:return s=Object.getPrototypeOf(e).constructor,a=this.getStorenameForModel(s),u=Object(o.x)(s.name,e,this.schema.namespaces[this.namespaceResolver(s)],this.modelInstanceCreator,this.getModelConstructorByModelName),c=this.namespaceResolver(s),f=new Set,l=Object.values(u).map((function(e){var t=e.modelName,n=e.item,r=e.instance,i=T.getStorename(c,t);return f.add(i),{storeName:i,item:n,instance:r}})),[4,this.db.get(e.id,a)];case 1:if(d=_.sent(),t&&d&&(h=m.a.getPredicates(t),p=h.predicates,v=h.type,!Object(o.y)(d,v,p)))throw g="Conditional update failed",A.error(g,{model:d,condition:p}),new Error(g);b=[],_.label=2;case 2:_.trys.push([2,11,12,17]),y=S(l),_.label=3;case 3:return[4,y.next()];case 4:return(w=_.sent()).done?[3,10]:(E=w.value,M=E.storeName,I=E.item,k=E.instance,O=I.id,[4,this.db.get(O,M)]);case 5:return x=_.sent()?i.c.UPDATE:i.c.INSERT,O!==e.id?[3,7]:[4,this.db.save(I,M)];case 6:return _.sent(),b.push([k,x]),[3,9];case 7:return x!==i.c.INSERT?[3,9]:[4,this.db.save(I,M)];case 8:_.sent(),b.push([k,x]),_.label=9;case 9:return[3,3];case 10:return[3,17];case 11:return C=_.sent(),n={error:C},[3,17];case 12:return _.trys.push([12,,15,16]),w&&!w.done&&(r=y.return)?[4,r.call(y)]:[3,14];case 13:_.sent(),_.label=14;case 14:return[3,16];case 15:if(n)throw n.error;return[7];case 16:return[7];case 17:return[2,b]}}))}))},e.prototype.load=function(e,t,n){var r,i,s,a,u,c,f,l,d,h;return w(this,void 0,void 0,(function(){var p,v,g,m,b,y,w,E,M,A,I,k,O,x,C,T,P,N,R=this;return _(this,(function(_){switch(_.label){case 0:if(p=this.schema.namespaces[e],v=p.relationships[t].relationTypes,g=v.map((function(t){var n=t.modelName;return R.getStorename(e,n)})),m=this.getModelConstructorByModelName(e,t),0===g.length)return[2,n.map((function(e){return R.modelInstanceCreator(m,e)}))];_.label=1;case 1:_.trys.push([1,34,35,40]),b=S(v),_.label=2;case 2:return[4,b.next()];case 3:if((y=_.sent()).done)return[3,33];switch(w=y.value,E=w.fieldName,M=w.modelName,A=w.targetName,I=w.relationType,k=this.getStorename(e,M),O=this.getModelConstructorByModelName(e,M),I){case"HAS_ONE":return[3,4];case"BELONGS_TO":return[3,17];case"HAS_MANY":return[3,30]}return[3,31];case 4:_.trys.push([4,10,11,16]),r=S(n),_.label=5;case 5:return[4,r.next()];case 6:return(i=_.sent()).done?[3,9]:(C=i.value)[E]?[4,this.db.get(C[E],k)]:[3,8];case 7:T=_.sent(),C[E]=T&&this.modelInstanceCreator(O,T),_.label=8;case 8:return[3,5];case 9:return[3,16];case 10:return x=_.sent(),f={error:x},[3,16];case 11:return _.trys.push([11,,14,15]),i&&!i.done&&(l=r.return)?[4,l.call(r)]:[3,13];case 12:_.sent(),_.label=13;case 13:return[3,15];case 14:if(f)throw f.error;return[7];case 15:return[7];case 16:return[3,32];case 17:_.trys.push([17,23,24,29]),s=S(n),_.label=18;case 18:return[4,s.next()];case 19:return(a=_.sent()).done?[3,22]:(C=a.value)[A]?[4,this.db.get(C[A],k)]:[3,21];case 20:T=_.sent(),C[E]=T&&this.modelInstanceCreator(O,T),delete C[A],_.label=21;case 21:return[3,18];case 22:return[3,29];case 23:return P=_.sent(),d={error:P},[3,29];case 24:return _.trys.push([24,,27,28]),a&&!a.done&&(h=s.return)?[4,h.call(s)]:[3,26];case 25:_.sent(),_.label=26;case 26:return[3,28];case 27:if(d)throw d.error;return[7];case 28:return[7];case 29:case 30:return[3,32];case 31:return Object(o.f)(I),[3,32];case 32:return[3,2];case 33:return[3,40];case 34:return N=_.sent(),u={error:N},[3,40];case 35:return _.trys.push([35,,38,39]),y&&!y.done&&(c=b.return)?[4,c.call(b)]:[3,37];case 36:_.sent(),_.label=37;case 37:return[3,39];case 38:if(u)throw u.error;return[7];case 39:return[7];case 40:return[2,n.map((function(e){return R.modelInstanceCreator(m,e)}))]}}))}))},e.prototype.query=function(e,t,n){return w(this,void 0,void 0,(function(){var r,s,a,u,c,f,l,d,h,p,v,g,b,y;return _(this,(function(w){switch(w.label){case 0:return r=this.getStorenameForModel(e),s=this.namespaceResolver(e),a=n&&n.sort,t?(u=m.a.getPredicates(t))?(c=u.predicates,f=u.type,(l=1===c.length&&c.find((function(e){return Object(i.k)(e)&&"id"===e.field&&"eq"===e.operator})))?(d=l.operand,[4,this.db.get(d,r)]):[3,4]):[3,7]:[3,7];case 1:return(h=w.sent())?[4,this.load(s,e.name,[h])]:[3,3];case 2:return p=E.apply(void 0,[w.sent(),1]),[2,[p[0]]];case 3:return[2,[]];case 4:return[4,this.db.getAll(r)];case 5:return v=w.sent(),g=c?v.filter((function(e){return Object(o.y)(e,f,c)})):v,[4,this.load(s,e.name,this.inMemoryPagination(g,n))];case 6:return[2,w.sent()];case 7:return a?[4,this.db.getAll(r)]:[3,10];case 8:return b=w.sent(),[4,this.load(s,e.name,this.inMemoryPagination(b,n))];case 9:return[2,w.sent()];case 10:return[4,this.db.getAll(r,n)];case 11:return y=w.sent(),[4,this.load(s,e.name,y)];case 12:return[2,w.sent()]}}))}))},e.prototype.inMemoryPagination=function(e,t){if(t){if(t.sort){var n=b.a.getPredicates(t.sort);if(n.length){var r=Object(o.w)(n);e.sort(r)}}var i=t.page,s=void 0===i?0:i,a=t.limit,u=void 0===a?0:a,c=Math.max(0,s*u)||0,f=u>0?c+u:e.length;return e.slice(c,f)}return e},e.prototype.queryOne=function(e,t){return void 0===t&&(t=i.d.FIRST),w(this,void 0,void 0,(function(){var n,r;return _(this,(function(i){switch(i.label){case 0:return n=this.getStorenameForModel(e),[4,this.db.getOne(t,n)];case 1:return[2,(r=i.sent())&&this.modelInstanceCreator(e,r)]}}))}))},e.prototype.delete=function(e,t){return w(this,void 0,void 0,(function(){var n,r,i,s,a,u,c,f,l,d,h,p,v;return _(this,(function(g){switch(g.label){case 0:return n=[],Object(o.s)(e)?(s=e,a=this.namespaceResolver(s),[4,this.query(s,t)]):[3,8];case 1:return r=g.sent(),p=this.schema.namespaces[a].relationships[s.name].relationTypes,void 0===t?[3,4]:[4,this.deleteTraverse(p,r,s.name,a,n)];case 2:return g.sent(),[4,this.deleteItem(n)];case 3:return g.sent(),v=n.reduce((function(e,t){var n=t.items;return e.concat(n)}),[]),[2,[r,v]];case 4:return[4,this.deleteTraverse(p,r,s.name,a,n)];case 5:return g.sent(),[4,this.deleteItem(n)];case 6:return g.sent(),v=n.reduce((function(e,t){var n=t.items;return e.concat(n)}),[]),[2,[r,v]];case 7:return[3,15];case 8:return i=e,s=Object.getPrototypeOf(i).constructor,a=this.namespaceResolver(s),u=this.getStorenameForModel(s),t?[4,this.db.get(i.id,u)]:[3,11];case 9:if(void 0===(c=g.sent()))return h="Model instance not found in storage",A.warn(h,{model:i}),[2,[[i],[]]];if(f=m.a.getPredicates(t),l=f.predicates,d=f.type,!Object(o.y)(c,d,l))throw h="Conditional update failed",A.error(h,{model:c,condition:l}),new Error(h);return p=this.schema.namespaces[a].relationships[s.name].relationTypes,[4,this.deleteTraverse(p,[i],s.name,a,n)];case 10:return g.sent(),[3,13];case 11:return p=this.schema.namespaces[a].relationships[s.name].relationTypes,[4,this.deleteTraverse(p,[i],s.name,a,n)];case 12:g.sent(),g.label=13;case 13:return[4,this.deleteItem(n)];case 14:return g.sent(),v=n.reduce((function(e,t){var n=t.items;return e.concat(n)}),[]),[2,[[i],v]];case 15:return[2]}}))}))},e.prototype.deleteItem=function(e){var t,n,r,i,o,s;return w(this,void 0,void 0,(function(){var a,u,c,f,l,d,h,p,v;return _(this,(function(g){switch(g.label){case 0:g.trys.push([0,17,18,23]),t=S(e),g.label=1;case 1:return[4,t.next()];case 2:if((n=g.sent()).done)return[3,16];a=n.value,u=a.storeName,c=a.items,g.label=3;case 3:g.trys.push([3,9,10,15]),f=S(c),g.label=4;case 4:return[4,f.next()];case 5:return(l=g.sent()).done?[3,8]:(d=l.value)?"object"!==y(d)?[3,7]:(h=d.id,[4,this.db.delete(h,u)]):[3,7];case 6:g.sent(),g.label=7;case 7:return[3,4];case 8:return[3,15];case 9:return p=g.sent(),o={error:p},[3,15];case 10:return g.trys.push([10,,13,14]),l&&!l.done&&(s=f.return)?[4,s.call(f)]:[3,12];case 11:g.sent(),g.label=12;case 12:return[3,14];case 13:if(o)throw o.error;return[7];case 14:return[7];case 15:return[3,1];case 16:return[3,23];case 17:return v=g.sent(),r={error:v},[3,23];case 18:return g.trys.push([18,,21,22]),n&&!n.done&&(i=t.return)?[4,i.call(t)]:[3,20];case 19:g.sent(),g.label=20;case 20:return[3,22];case 21:if(r)throw r.error;return[7];case 22:return[7];case 23:return[2]}}))}))},e.prototype.deleteTraverse=function(e,t,n,r,i){var s,a,u,c,f,l,d,h,p,v,g,m;return w(this,void 0,void 0,(function(){var b,y,w,E,M,A,I,k,O,x,C,T,P=this;return _(this,(function(_){switch(_.label){case 0:_.trys.push([0,35,36,41]),s=S(e),_.label=1;case 1:return[4,s.next()];case 2:if((a=_.sent()).done)return[3,34];switch(b=a.value,y=b.relationType,w=b.modelName,E=this.getStorename(r,w),M=Object(o.g)(this.schema.namespaces[r].relationships[w].relationTypes,n)||Object(o.h)(this.schema.namespaces[r].relationships[w].indexes,b.associatedWith),y){case"HAS_ONE":return[3,3];case"HAS_MANY":return[3,17];case"BELONGS_TO":return[3,31]}return[3,32];case 3:_.trys.push([3,10,11,16]),u=S(t),_.label=4;case 4:return[4,u.next()];case 5:return(c=_.sent()).done?[3,9]:(k=c.value,[4,this.db.getAll(E)]);case 6:return O=_.sent(),A=O.filter((function(e){return e[M]===k.id})),[4,this.deleteTraverse(this.schema.namespaces[r].relationships[w].relationTypes,A,w,r,i)];case 7:_.sent(),_.label=8;case 8:return[3,4];case 9:return[3,16];case 10:return I=_.sent(),p={error:I},[3,16];case 11:return _.trys.push([11,,14,15]),c&&!c.done&&(v=u.return)?[4,v.call(u)]:[3,13];case 12:_.sent(),_.label=13;case 13:return[3,15];case 14:if(p)throw p.error;return[7];case 15:return[7];case 16:return[3,33];case 17:_.trys.push([17,24,25,30]),f=S(t),_.label=18;case 18:return[4,f.next()];case 19:return(l=_.sent()).done?[3,23]:(k=l.value,[4,this.db.getAll(E)]);case 20:return O=_.sent(),x=O.filter((function(e){return e[M]===k.id})),[4,this.deleteTraverse(this.schema.namespaces[r].relationships[w].relationTypes,x,w,r,i)];case 21:_.sent(),_.label=22;case 22:return[3,18];case 23:return[3,30];case 24:return C=_.sent(),g={error:C},[3,30];case 25:return _.trys.push([25,,28,29]),l&&!l.done&&(m=f.return)?[4,m.call(f)]:[3,27];case 26:_.sent(),_.label=27;case 27:return[3,29];case 28:if(g)throw g.error;return[7];case 29:return[7];case 30:case 31:return[3,33];case 32:return Object(o.f)(y),[3,33];case 33:return[3,1];case 34:return[3,41];case 35:return T=_.sent(),d={error:T},[3,41];case 36:return _.trys.push([36,,39,40]),a&&!a.done&&(h=s.return)?[4,h.call(s)]:[3,38];case 37:_.sent(),_.label=38;case 38:return[3,40];case 39:if(d)throw d.error;return[7];case 40:return[7];case 41:return i.push({storeName:this.getStorename(r,n),items:t.map((function(e){return P.modelInstanceCreator(P.getModelConstructorByModelName(r,n),e)}))}),[2]}}))}))},e.prototype.clear=function(){return w(this,void 0,void 0,(function(){return _(this,(function(e){switch(e.label){case 0:return[4,this.db.clear()];case 1:return e.sent(),this.db=void 0,this.initPromise=void 0,[2]}}))}))},e.prototype.batchSave=function(e,t){return w(this,void 0,void 0,(function(){var n,r,i,s,a,u,c,f,l,d,h;return _(this,(function(p){switch(p.label){case 0:n=e.name,r=this.namespaceResolver(e),i=this.getStorename(r,n),s=[],a=function(t){var n=t.id,r=Object(o.x)(e.name,u.modelInstanceCreator(e,t),u.schema.namespaces[u.namespaceResolver(e)],u.modelInstanceCreator,u.getModelConstructorByModelName).find((function(e){return e.instance.id===n})).instance;s.push(r)},u=this;try{for(c=M(t),f=c.next();!f.done;f=c.next())l=f.value,a(l)}catch(e){d={error:e}}finally{try{f&&!f.done&&(h=c.return)&&h.call(c)}finally{if(d)throw d.error}}return[4,this.db.batchSave(i,s)];case 1:return[2,p.sent()]}}))}))},e}();t.default=new I},function(e,t,n){"use strict";n.r(t),n.d(t,"fromUtf8",(function(){return r})),n.d(t,"toUtf8",(function(){return i}));var r=function(e){return"function"==typeof TextEncoder?function(e){return(new TextEncoder).encode(e)}(e):function(e){for(var t=[],n=0,r=e.length;n>6|192,63&i|128);else if(n+1>18|240,o>>12&63|128,o>>6&63|128,63&o|128)}else t.push(i>>12|224,i>>6&63|128,63&i|128)}return Uint8Array.from(t)}(e)},i=function(e){return"function"==typeof TextDecoder?function(e){return new TextDecoder("utf-8").decode(e)}(e):function(e){for(var t="",n=0,r=e.length;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s},c=function(){for(var e=[],t=0;te)&&n}}(n))}}])})); + +// version: 3.3.18 diff --git a/docs/javascript/extra.js b/docs/javascript/extra.js new file mode 100644 index 000000000..0ade322a6 --- /dev/null +++ b/docs/javascript/extra.js @@ -0,0 +1,71 @@ +const Amplify = window.aws_amplify.Amplify +const Analytics = Amplify.Analytics +const KinesisFirehoseProvider = window.aws_amplify.AWSKinesisFirehoseProvider + +const awsconfig = { + "aws_project_region": "eu-west-1", + "aws_cognito_identity_pool_id": "eu-west-1:3df3caec-4bb6-4891-b154-ee940c8264b8", + "aws_cognito_region": "eu-west-1", + "aws_kinesis_firehose_stream_name": "ClickStreamKinesisFirehose-OGX7PQdrynUo", +}; + +const RUNTIME = "python" + +const attachListeners = () => { + /* Register handler to log search on blur */ + document.addEventListener("DOMContentLoaded", function () { + recordPageView({ + prevLocation: document.referrer + }) + if (document.forms.search) { + let query = document.forms.search.query + query.addEventListener("blur", function () { + // If Search result is ever actionable + // we should populate `value` + if (this.value) { + let path = document.location.pathname; + console.info(`Search value: ${this.value}`) + recordPageView({ + searchPattern: this.value + }) + } + }) + } + }) + + // Register handler for page sections when browser history is changed + window.onpopstate = function (event) { + recordPageView({ + prevLocation: document.referrer + }) + }; +} + +const init = () => { + Analytics.addPluggable(new KinesisFirehoseProvider()) + Amplify.configure(awsconfig); + + Analytics.configure({ + AWSKinesisFirehose: { + region: awsconfig.aws_project_region + } + }) + + attachListeners() +} + +const recordPageView = ({prevLocation, searchPattern}) => { + Analytics.record({ + data: { + // Do not count page view for search + url: searchPattern ? null : window.location.href, + section: searchPattern ? null : location.pathname, + previous: prevLocation || null, + search: searchPattern || null, + language: RUNTIME + }, + streamName: awsconfig.aws_kinesis_firehose_stream_name + }, 'AWSKinesisFirehose') +} + +init() diff --git a/docs/media/aws-logo-light.svg b/docs/media/aws-logo-light.svg new file mode 100644 index 000000000..982571b86 --- /dev/null +++ b/docs/media/aws-logo-light.svg @@ -0,0 +1,38 @@ + + + + + + + + + + + + diff --git a/docs/media/metrics_terminology.png b/docs/media/metrics_terminology.png new file mode 100644 index 000000000..a20fafd6a Binary files /dev/null and b/docs/media/metrics_terminology.png differ diff --git a/docs/media/tracer_utility_showcase.png b/docs/media/tracer_utility_showcase.png new file mode 100644 index 000000000..55d7d5d0b Binary files /dev/null and b/docs/media/tracer_utility_showcase.png differ diff --git a/docs/media/utilities_data_classes.png b/docs/media/utilities_data_classes.png new file mode 100644 index 000000000..94ed83bde Binary files /dev/null and b/docs/media/utilities_data_classes.png differ diff --git a/docs/media/utilities_typing.png b/docs/media/utilities_typing.png new file mode 100644 index 000000000..0f293abb6 Binary files /dev/null and b/docs/media/utilities_typing.png differ diff --git a/docs/overrides/assets/images/powertools_docs_thumbnail.png b/docs/overrides/assets/images/powertools_docs_thumbnail.png new file mode 100644 index 000000000..e87b8f198 Binary files /dev/null and b/docs/overrides/assets/images/powertools_docs_thumbnail.png differ diff --git a/docs/references.md b/docs/references.md new file mode 100644 index 000000000..56026d152 --- /dev/null +++ b/docs/references.md @@ -0,0 +1,24 @@ +--- +title: AWS Lambda Powertools for .NET references +description: AWS Lambda Powertools for .NET references +--- + +## Environment variables + +!!! info + **Explicit parameters take precedence over environment variables.** + +| Environment variable | Description | Utility | Default | +| ------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------- | +| **POWERTOOLS_SERVICE_NAME** | Sets service name used for tracing namespace, metrics dimension and structured logging | All | `"service_undefined"` | +| **POWERTOOLS_METRICS_NAMESPACE** | Sets namespace used for metrics | [Metrics](./core/metrics) | `None` | +| **POWERTOOLS_TRACE_DISABLED** | Disables tracing | [Tracing](./core/tracing) | `false` | +| **POWERTOOLS_TRACER_CAPTURE_RESPONSE** | Captures Lambda or method return as metadata. | [Tracing](./core/tracing) | `true` | +| **POWERTOOLS_TRACER_CAPTURE_ERROR** | Captures Lambda or method exception as metadata. | [Tracing](./core/tracing) | `true` | +| **POWERTOOLS_LOGGER_LOG_EVENT** | Logs incoming event | [Logging](./core/logging) | `false` | +| **POWERTOOLS_LOGGER_SAMPLE_RATE** | Debug log sampling | [Logging](./core/logging) | `0` | +| **POWERTOOLS_LOG_DEDUPLICATION_DISABLED** | Disables log deduplication filter protection to use Pytest Live Log feature | [Logging](./core/logging) | `false` | + +## SAM template snippets + +TODO.... diff --git a/docs/stylesheets/extra.css b/docs/stylesheets/extra.css new file mode 100644 index 000000000..f24b32faa --- /dev/null +++ b/docs/stylesheets/extra.css @@ -0,0 +1,35 @@ +.md-grid { + max-width: 81vw +} + +.highlight .hll { + background-color: lavender + + [data-md-color-scheme="slate"] { + background-color: rgb(69, 48, 164) + } +} + +.md-typeset table:not([class]) { + font-size: 0.75rem +} + +.md-typeset a { + border-bottom: 0.1px dashed black +} + +.md-typeset table:not([class]) { + font-size: 0.75rem +} + +.md-nav__link--active { + font-weight: bold +} + +.md-typeset .admonition, .md-typeset details { + font-size: 0.70rem +} + +[data-md-color-scheme="slate"] { + --md-typeset-a-color: rgb(28, 152, 152) +} diff --git a/docs/tenets.md b/docs/tenets.md new file mode 100644 index 000000000..33c331a15 --- /dev/null +++ b/docs/tenets.md @@ -0,0 +1,13 @@ +--- +title: AWS Lambda Powertools for .NET (developer preview) +description: AWS Lambda Powertools for .NET (developer preview) +--- + +Core utilities such as Tracing, Logging, Metrics, and Event Handler will be available across all Lambda Powertools runtimes. Additional utilities are subjective to each language ecosystem and customer demand. + +* **AWS Lambda only**. We optimise for AWS Lambda function environments and supported runtimes only. Utilities might work with web frameworks and non-Lambda environments, though they are not officially supported. +* **Eases the adoption of best practices**. The main priority of the utilities is to facilitate best practices adoption, as defined in the AWS Well-Architected Serverless Lens; all other functionality is optional. +* **Keep it lean**. Additional dependencies are carefully considered for security and ease of maintenance, and prevent negatively impacting startup time. +* **We strive for backwards compatibility**. New features and changes should keep backwards compatibility. If a breaking change cannot be avoided, the deprecation and migration process should be clearly defined. +* **We work backwards from the community**. We aim to strike a balance of what would work best for 80% of customers. Emerging practices are considered and discussed via Requests for Comment (RFCs) +* **Idiomatic**. Utilities follow programming language idioms and language-specific best practices. diff --git a/examples/.gitignore b/examples/.gitignore new file mode 100644 index 000000000..cb4fe3d70 --- /dev/null +++ b/examples/.gitignore @@ -0,0 +1,454 @@ +# Created by https://www.toptal.com/developers/gitignore/api/dotnetcore,visualstudio,visualstudiocode,rider +# Edit at https://www.toptal.com/developers/gitignore?templates=dotnetcore,visualstudio,visualstudiocode,rider + +### DotnetCore ### +# .NET Core build folders +bin/ +obj/ + +# Common node modules locations +/node_modules +/wwwroot/node_modules + +### Rider ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*[.json, .xml, .info] + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# End of https://www.toptal.com/developers/gitignore/api/dotnetcore,visualstudio,visualstudiocode,rider +.DS_Store diff --git a/examples/Logging/.gitignore b/examples/Logging/.gitignore new file mode 100644 index 000000000..af2786a14 --- /dev/null +++ b/examples/Logging/.gitignore @@ -0,0 +1,638 @@ +samconfig.toml + +# Created by https://www.toptal.com/developers/gitignore/api/sam,linux,macos,windows,dotsettings,sublimetext,visualstudio,visualstudiocode,jetbrains +# Edit at https://www.toptal.com/developers/gitignore?templates=sam,linux,macos,windows,dotsettings,sublimetext,visualstudio,visualstudiocode,jetbrains + +### DotSettings ### +*.DotSettings + +### JetBrains ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### JetBrains Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### SAM ### +# Ignore build directories for the AWS Serverless Application Model (SAM) +# Info: https://aws.amazon.com/serverless/sam/ +# Docs: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-reference.html + +**/.aws-sam + +### SublimeText ### +# Cache files for Sublime Text +*.tmlanguage.cache +*.tmPreferences.cache +*.stTheme.cache + +# Workspace files are user-specific +*.sublime-workspace + +# Project files should be checked into the repository, unless a significant +# proportion of contributors will probably not be using Sublime Text +# *.sublime-project + +# SFTP configuration file +sftp-config.json +sftp-config-alt*.json + +# Package control specific files +Package Control.last-run +Package Control.ca-list +Package Control.ca-bundle +Package Control.system-ca-bundle +Package Control.cache/ +Package Control.ca-certs/ +Package Control.merged-ca-bundle +Package Control.user-ca-bundle +oscrypto-ca-bundle.crt +bh_unicode_properties.cache + +# Sublime-github package stores a github token in this file +# https://packagecontrol.io/packages/sublime-github +GitHub.sublime-settings + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +# Support for Project snippet scope + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +*.code-workspace + +# Local History for Visual Studio Code + +# Windows Installer files from build outputs + +# JetBrains Rider +*.sln.iml + +### VisualStudio Patch ### +# Additional files built by Visual Studio + +# End of https://www.toptal.com/developers/gitignore/api/sam,linux,macos,windows,dotsettings,sublimetext,visualstudio,visualstudiocode,jetbrains diff --git a/examples/Logging/PowertoolsLoggingExample.sln b/examples/Logging/PowertoolsLoggingExample.sln new file mode 100644 index 000000000..fa39af04d --- /dev/null +++ b/examples/Logging/PowertoolsLoggingExample.sln @@ -0,0 +1,28 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30114.105 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HelloWorld", "src\HelloWorld\HelloWorld.csproj", "{F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HelloWorld.Tests", "test\HelloWorld.Test\HelloWorld.Tests.csproj", "{9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}.Release|Any CPU.Build.0 = Release|Any CPU + {9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/examples/Logging/README.md b/examples/Logging/README.md new file mode 100644 index 000000000..de68ac4ca --- /dev/null +++ b/examples/Logging/README.md @@ -0,0 +1,120 @@ +# AWS Lambda Powertools for .NET Logging Example + +This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes the following files and folders. + +- src - Code for the application's Lambda function and Project Dockerfile. +- events - Invocation events that you can use to invoke the function. +- test - Unit tests for the application code. +- template.yaml - A template that defines the application's AWS resources. + +The application uses several AWS resources, including Lambda functions and an API Gateway API. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code. + +If you prefer to use an integrated development environment (IDE) to build and test your application, you can use the AWS Toolkit. +The AWS Toolkit is an open source plug-in for popular IDEs that uses the SAM CLI to build and deploy serverless applications on AWS. The AWS Toolkit also adds a simplified step-through debugging experience for Lambda function code. See the following links to get started. + +- [Visual Studio Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html) +- [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html) +- [Rider](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) + +## Deploy the sample application + +The Serverless Application Model Command Line Interface (SAM CLI) is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API. + +To use the SAM CLI, you need the following tools. + +- SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) +- Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community) + +You will need the following for local testing. +- .NET 6.0 - [Install .NET 6.0](https://www.microsoft.com/net/download) + +To build and deploy your application for the first time, run the following in your shell. Make sure the `template.yaml` file is in your current directory: + +```bash +sam build +sam deploy --guided +``` + +The first command will build a docker image from a Dockerfile and then copy the source of your application inside the Docker image. The second command will package and deploy your application to AWS, with a series of prompts: + +- **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name. +- **AWS Region**: The AWS region you want to deploy your app to. +- **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes. +- **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command. +- **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application. + +You can find your API Gateway Endpoint URL in the output values displayed after deployment. + +## Use the SAM CLI to build and test locally + +Build your application with the `sam build` command. + +```bash +Logging$ sam build +``` + +The SAM CLI builds a docker image from a Dockerfile and then installs dependencies defined in `src/HelloWorld.csproj` inside the docker image. The processed template file is saved in the `.aws-sam/build` folder. + +Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project. + +Run functions locally and invoke them with the `sam local invoke` command. + +```bash +Logging$ sam local invoke HelloWorldFunction --event events/event.json +``` + +The SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000. + +```bash +Logging$ sam local start-api +Logging$ curl http://localhost:3000/ +``` + +The SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The `Events` property on each function's definition includes the route and method for each path. + +```yaml + Events: + HelloWorld: + Type: Api + Properties: + Path: /hello + Method: get +``` + +## Add a resource to your application + +The application template uses AWS Serverless Application Model (AWS SAM) to define application resources. AWS SAM is an extension of AWS CloudFormation with a simpler syntax for configuring common serverless application resources such as functions, triggers, and APIs. For resources not included in [the SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), you can use standard [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) resource types. + +## Fetch, tail, and filter Lambda function logs + +To simplify troubleshooting, SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug. + +`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM. + +```bash +Logging$ sam logs -n HelloWorldFunction --stack-name Logging --tail +``` + +You can find more information and examples about filtering Lambda function logs in the [SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html). + +## Unit tests + +Tests are defined in the `test` folder in this project. + +```bash +Logging$ dotnet test test/HelloWorld.Test +``` + +## Cleanup + +To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following: + +```bash +aws cloudformation delete-stack --stack-name Logging +``` + +## Resources + +See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the SAM CLI, and serverless application concepts. + +Next, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples and learn how authors developed their applications: [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/) diff --git a/examples/Logging/events/event.json b/examples/Logging/events/event.json new file mode 100644 index 000000000..3822fadaa --- /dev/null +++ b/examples/Logging/events/event.json @@ -0,0 +1,63 @@ +{ + "body": "{\"message\": \"hello world\"}", + "resource": "/{proxy+}", + "path": "/path/to/resource", + "httpMethod": "POST", + "isBase64Encoded": false, + "queryStringParameters": { + "foo": "bar" + }, + "pathParameters": { + "proxy": "/path/to/resource" + }, + "stageVariables": { + "baz": "qux" + }, + "headers": { + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", + "Accept-Encoding": "gzip, deflate, sdch", + "Accept-Language": "en-US,en;q=0.8", + "Cache-Control": "max-age=0", + "CloudFront-Forwarded-Proto": "https", + "CloudFront-Is-Desktop-Viewer": "true", + "CloudFront-Is-Mobile-Viewer": "false", + "CloudFront-Is-SmartTV-Viewer": "false", + "CloudFront-Is-Tablet-Viewer": "false", + "CloudFront-Viewer-Country": "US", + "Host": "1234567890.execute-api.us-east-1.amazonaws.com", + "Upgrade-Insecure-Requests": "1", + "User-Agent": "Custom User Agent String", + "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", + "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", + "X-Forwarded-For": "127.0.0.1, 127.0.0.2", + "X-Forwarded-Port": "443", + "X-Forwarded-Proto": "https" + }, + "requestContext": { + "accountId": "123456789012", + "resourceId": "123456", + "stage": "prod", + "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", + "requestTime": "09/Apr/2015:12:34:56 +0000", + "requestTimeEpoch": 1428582896000, + "identity": { + "cognitoIdentityPoolId": null, + "accountId": null, + "cognitoIdentityId": null, + "caller": null, + "accessKey": null, + "sourceIp": "127.0.0.1", + "cognitoAuthenticationType": null, + "cognitoAuthenticationProvider": null, + "userArn": null, + "userAgent": "Custom User Agent String", + "user": null + }, + "path": "/prod/path/to/resource", + "resourcePath": "/{proxy+}", + "httpMethod": "POST", + "apiId": "1234567890", + "protocol": "HTTP/1.1" + } + } + \ No newline at end of file diff --git a/examples/Logging/omnisharp.json b/examples/Logging/omnisharp.json new file mode 100644 index 000000000..c42f8db91 --- /dev/null +++ b/examples/Logging/omnisharp.json @@ -0,0 +1,11 @@ +{ + "fileOptions": { + "excludeSearchPatterns": [ + "**/bin/**/*", + "**/obj/**/*" + ] + }, + "msbuild": { + "Platform": "rhel.7.2-x64" + } +} \ No newline at end of file diff --git a/examples/Logging/src/HelloWorld/Dockerfile b/examples/Logging/src/HelloWorld/Dockerfile new file mode 100644 index 000000000..fca242579 --- /dev/null +++ b/examples/Logging/src/HelloWorld/Dockerfile @@ -0,0 +1,26 @@ +ARG SAM_BUILD_MODE=Release +FROM public.ecr.aws/lambda/dotnet:6 AS base +FROM mcr.microsoft.com/dotnet/sdk:6.0-bullseye-slim as build + +ARG SAM_BUILD_MODE +ENV ENV_BUILD_MODE = ${SAM_BUILD_MODE} + +WORKDIR /src +COPY ["HelloWorld.csproj", "HelloWorld/"] +RUN dotnet restore "HelloWorld/HelloWorld.csproj" + +WORKDIR "/src/HelloWorld" +COPY . . + +RUN dotnet build "HelloWorld.csproj" --configuration ${SAM_BUILD_MODE} --output /app/build + +FROM build AS publish +RUN if [ "$ENV_BUILD_MODE" = "Debug" ]; \ +then dotnet publish "HelloWorld.csproj" --configuration "Debug" --runtime linux-x64 --self-contained false --output /app/publish; \ +else dotnet publish "HelloWorld.csproj" --configuration "Release" --runtime linux-x64 --self-contained false --output /app/publish -p:PublishReadyToRun=true; fi + + +FROM base AS final +WORKDIR /var/task +COPY --from=publish /app/publish . +CMD ["HelloWorld::HelloWorld.Function::FunctionHandler"] \ No newline at end of file diff --git a/examples/Logging/src/HelloWorld/Function.cs b/examples/Logging/src/HelloWorld/Function.cs new file mode 100644 index 000000000..ca519d1e2 --- /dev/null +++ b/examples/Logging/src/HelloWorld/Function.cs @@ -0,0 +1,184 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +using Amazon; +using Amazon.DynamoDBv2; +using Amazon.DynamoDBv2.DataModel; +using Amazon.Lambda.APIGatewayEvents; +using Amazon.Lambda.Core; +using Amazon.Lambda.Serialization.SystemTextJson; +using AWS.Lambda.Powertools.Logging; + +// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. +[assembly: LambdaSerializer(typeof(DefaultLambdaJsonSerializer))] + +namespace HelloWorld; + +public class Function +{ + private static HttpClient? _httpClient; + private static IDynamoDBContext? _dynamoDbContext; + + /// + /// Function constructor + /// + public Function() + { + _httpClient = new HttpClient(); + + var tableName = Environment.GetEnvironmentVariable("TABLE_NAME"); + + if (!string.IsNullOrEmpty(tableName)) + { + AWSConfigsDynamoDB.Context.TypeMappings[typeof(LookupRecord)] = + new Amazon.Util.TypeMapping(typeof(LookupRecord), tableName); + } + + var config = new DynamoDBContextConfig { Conversion = DynamoDBEntryConversion.V2 }; + _dynamoDbContext = new DynamoDBContext(new AmazonDynamoDBClient(), config); + } + + /// + /// Test constructor + /// + public Function(IDynamoDBContext dynamoDbContext, HttpClient httpClient) + { + _httpClient = httpClient; + _dynamoDbContext = dynamoDbContext; + } + + [Logging(LogEvent = true)] + public async Task FunctionHandler(APIGatewayProxyRequest apigwProxyEvent, + ILambdaContext context) + { + var requestContextRequestId = apigwProxyEvent.RequestContext.RequestId; + + var lookupId = new Dictionary() + { + { "LookupId", requestContextRequestId } + }; + + // Appended keys are added to all subsequent log entries in the current execution. + // Call this method as early as possible in the Lambda handler. + // Typically this is value would be passed into the function via the event. + // Set the ClearState = true to force the removal of keys across invocations, + Logger.AppendKeys(lookupId); + + Logger.LogInformation("Getting ip address from external service"); + + var location = await GetCallingIp(); + + var lookupRecord = new LookupRecord(lookupId: requestContextRequestId, + greeting: "Hello AWS Lambda Powertools for .NET", ipAddress: location); + + try + { + await SaveRecordInDynamo(lookupRecord); + + return new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(lookupRecord), + StatusCode = 200, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + catch (Exception e) + { + return new APIGatewayProxyResponse + { + Body = e.Message, + StatusCode = 500, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + } + + private static async Task GetCallingIp() + { + if (_httpClient == null) return "0.0.0.0"; + _httpClient.DefaultRequestHeaders.Accept.Clear(); + _httpClient.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); + + try + { + Logger.LogInformation("Calling Check IP API"); + + var response = await _httpClient.GetStringAsync("https://checkip.amazonaws.com/").ConfigureAwait(false); + var ip = response.Replace("\n", ""); + + Logger.LogInformation($"API response returned {ip}"); + + return ip; + } + catch (Exception ex) + { + Logger.LogError(ex); + throw; + } + } + + /// + /// Saves the lookup record in DynamoDB + /// + /// + /// A Task that can be used to poll or wait for results, or both. + private static async Task SaveRecordInDynamo(LookupRecord lookupRecord) + { + try + { + Logger.LogInformation($"Saving record with id {lookupRecord.LookupId}"); + await _dynamoDbContext?.SaveAsync(lookupRecord)!; + } + catch (AmazonDynamoDBException e) + { + Logger.LogCritical(e.Message); + throw; + } + } +} + +/// +/// Record to represent the data structure of Lookup +/// +[Serializable] +public class LookupRecord +{ + public LookupRecord() + { + } + + /// + /// Record to represent the data structure of Lookup + /// + /// Id of the lookup + /// Greeting phrase + /// IP address + public LookupRecord(string? lookupId, string? greeting, string? ipAddress) + { + LookupId = lookupId; + Greeting = greeting; + IpAddress = ipAddress; + } + + public string? LookupId { get; set; } + public string? Greeting { get; set; } + public string? IpAddress { get; set; } + +} \ No newline at end of file diff --git a/examples/Logging/src/HelloWorld/HelloWorld.csproj b/examples/Logging/src/HelloWorld/HelloWorld.csproj new file mode 100644 index 000000000..7702ddbff --- /dev/null +++ b/examples/Logging/src/HelloWorld/HelloWorld.csproj @@ -0,0 +1,14 @@ + + + net6.0 + true + enable + + + + + + + + + \ No newline at end of file diff --git a/examples/Logging/template-docker.yaml b/examples/Logging/template-docker.yaml new file mode 100644 index 000000000..57d06c766 --- /dev/null +++ b/examples/Logging/template-docker.yaml @@ -0,0 +1,100 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +AWSTemplateFormatVersion: "2010-09-09" +Transform: AWS::Serverless-2016-10-31 +Description: > + Example project for AWS Lambda Powertools Logging utility + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Timeout: 10 + Environment: + Variables: + POWERTOOLS_SERVICE_NAME: powertools-dotnet-logging-sample + POWERTOOLS_LOG_LEVEL: Debug + POWERTOOLS_LOGGER_CASE: SnakeCase # Allowed values are: CamelCase, PascalCase and SnakeCase + +Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + MemorySize: 256 + PackageType: Image + Role: !Sub ${HelloWorldFunctionRole.Arn} + Environment: + Variables: + TABLE_NAME: !Ref PowertoolsLoggingTable + Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get + Metadata: + DockerTag: dotnet6.0-v1 + DockerContext: ./src/HelloWorld + Dockerfile: Dockerfile + DockerBuildArgs: + SAM_BUILD_MODE: Release # Debug or Release + + + PowertoolsLoggingTable: + Type: AWS::Serverless::SimpleTable + Properties: + TableName: PowertoolsLogging + PrimaryKey: + Name: LookupId + Type: String + + HelloWorldFunctionRole: + Type: "AWS::IAM::Role" + Properties: + Path: !Join ["", ["/", !Ref "AWS::StackName", "/"]] + ManagedPolicyArns: + - "arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess" + - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - + Sid: "AllowLambdaServiceToAssumeRole" + Effect: "Allow" + Action: + - "sts:AssumeRole" + Principal: + Service: + - "lambda.amazonaws.com" + Policies: + - PolicyName: "AllowCRUDOperationsOnDynamoDB" + PolicyDocument: + Version: '2012-10-17' + Statement: + - + Effect: "Allow" + Action: + - 'dynamodb:GetItem' + - 'dynamodb:DeleteItem' + - 'dynamodb:DescribeTable' + - 'dynamodb:PutItem' + - 'dynamodb:Scan' + - 'dynamodb:Query' + - 'dynamodb:UpdateItem' + - 'dynamodb:BatchWriteItem' + - 'dynamodb:BatchGetItem' + Resource: + - !Sub ${PowertoolsLoggingTable.Arn} + +Outputs: + # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function + # Find out more about other implicit resources you can reference within SAM + # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api + HelloWorldApi: + Description: "API Gateway endpoint URL for Prod stage for Hello World function" + Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" + HelloWorldFunction: + Description: "Hello World Lambda Function ARN" + Value: !GetAtt HelloWorldFunction.Arn + HelloWorldFunctionIamRole: + Description: "Implicit IAM Role created for Hello World function" + Value: !GetAtt HelloWorldFunctionRole.Arn diff --git a/examples/Logging/template.yaml b/examples/Logging/template.yaml new file mode 100644 index 000000000..414521d60 --- /dev/null +++ b/examples/Logging/template.yaml @@ -0,0 +1,95 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +AWSTemplateFormatVersion: "2010-09-09" +Transform: AWS::Serverless-2016-10-31 +Description: > + Example project for AWS Lambda Powertools Logging utility + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Timeout: 10 + Environment: + Variables: + POWERTOOLS_SERVICE_NAME: powertools-dotnet-logging-sample + POWERTOOLS_LOG_LEVEL: Debug + POWERTOOLS_LOGGER_CASE: SnakeCase # Allowed values are: CamelCase, PascalCase and SnakeCase + +Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + Runtime: dotnet6 + CodeUri: ./src/HelloWorld/ + Handler: HelloWorld::HelloWorld.Function::FunctionHandler + MemorySize: 256 + Role: !Sub ${HelloWorldFunctionRole.Arn} + Environment: + Variables: + TABLE_NAME: !Ref PowertoolsLoggingTable + Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get + + PowertoolsLoggingTable: + Type: AWS::Serverless::SimpleTable + Properties: + TableName: PowertoolsLogging + PrimaryKey: + Name: LookupId + Type: String + + HelloWorldFunctionRole: + Type: "AWS::IAM::Role" + Properties: + Path: !Join ["", ["/", !Ref "AWS::StackName", "/"]] + ManagedPolicyArns: + - "arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess" + - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - + Sid: "AllowLambdaServiceToAssumeRole" + Effect: "Allow" + Action: + - "sts:AssumeRole" + Principal: + Service: + - "lambda.amazonaws.com" + Policies: + - PolicyName: "AllowCRUDOperationsOnDynamoDB" + PolicyDocument: + Version: '2012-10-17' + Statement: + - + Effect: "Allow" + Action: + - 'dynamodb:GetItem' + - 'dynamodb:DeleteItem' + - 'dynamodb:DescribeTable' + - 'dynamodb:PutItem' + - 'dynamodb:Scan' + - 'dynamodb:Query' + - 'dynamodb:UpdateItem' + - 'dynamodb:BatchWriteItem' + - 'dynamodb:BatchGetItem' + Resource: + - !Sub ${PowertoolsLoggingTable.Arn} + +Outputs: + # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function + # Find out more about other implicit resources you can reference within SAM + # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api + HelloWorldApi: + Description: "API Gateway endpoint URL for Prod stage for Hello World function" + Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" + HelloWorldFunction: + Description: "Hello World Lambda Function ARN" + Value: !GetAtt HelloWorldFunction.Arn + HelloWorldFunctionIamRole: + Description: "Implicit IAM Role created for Hello World function" + Value: !GetAtt HelloWorldFunctionRole.Arn diff --git a/examples/Logging/test/HelloWorld.Test/FunctionTest.cs b/examples/Logging/test/HelloWorld.Test/FunctionTest.cs new file mode 100644 index 000000000..df2d461f1 --- /dev/null +++ b/examples/Logging/test/HelloWorld.Test/FunctionTest.cs @@ -0,0 +1,108 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Amazon.DynamoDBv2.DataModel; +using Xunit; +using Amazon.Lambda.APIGatewayEvents; +using Amazon.Lambda.TestUtilities; +using Moq; +using Moq.Protected; +using Xunit.Abstractions; + +namespace HelloWorld.Tests +{ + public class FunctionTest + { + private readonly ITestOutputHelper _testOutputHelper; + + public FunctionTest(ITestOutputHelper testOutputHelper) + { + _testOutputHelper = testOutputHelper; + } + + [Fact] + public async Task TestHelloWorldFunctionHandler() + { + // Arrange + var requestId = Guid.NewGuid().ToString("D"); + var accountId = Guid.NewGuid().ToString("D"); + var location = "192.158. 1.38"; + + var dynamoDbContext = new Mock(); + var handlerMock = new Mock(); + handlerMock + .Protected() + .Setup>( + "SendAsync", + ItExpr.IsAny(), + ItExpr.IsAny() + ) + .ReturnsAsync(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK, + Content = new StringContent(location) + }) + .Verifiable(); + + var request = new APIGatewayProxyRequest + { + RequestContext = new APIGatewayProxyRequest.ProxyRequestContext + { + RequestId = requestId, + AccountId = accountId + } + }; + + var context = new TestLambdaContext + { + FunctionName = "PowertoolsLoggingSample-HelloWorldFunction-Gg8rhPwO7Wa1", + FunctionVersion = "1", + MemoryLimitInMB = 215, + AwsRequestId = Guid.NewGuid().ToString("D") + }; + + var body = new Dictionary + { + { "LookupId", requestId }, + { "Greeting", "Hello AWS Lambda Powertools for .NET" }, + { "IpAddress", location }, + }; + + var expectedResponse = new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(body), + StatusCode = 200, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + + var function = new Function(dynamoDbContext.Object, new HttpClient(handlerMock.Object)); + var response = await function.FunctionHandler(request, context); + + _testOutputHelper.WriteLine("Lambda Response: \n" + response.Body); + _testOutputHelper.WriteLine("Expected Response: \n" + expectedResponse.Body); + + Assert.Equal(expectedResponse.Body, response.Body); + Assert.Equal(expectedResponse.Headers, response.Headers); + Assert.Equal(expectedResponse.StatusCode, response.StatusCode); + } + } +} \ No newline at end of file diff --git a/examples/Logging/test/HelloWorld.Test/HelloWorld.Tests.csproj b/examples/Logging/test/HelloWorld.Test/HelloWorld.Tests.csproj new file mode 100644 index 000000000..be3f49fd8 --- /dev/null +++ b/examples/Logging/test/HelloWorld.Test/HelloWorld.Tests.csproj @@ -0,0 +1,18 @@ + + + net6.0 + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/examples/Metrics/.gitignore b/examples/Metrics/.gitignore new file mode 100644 index 000000000..af2786a14 --- /dev/null +++ b/examples/Metrics/.gitignore @@ -0,0 +1,638 @@ +samconfig.toml + +# Created by https://www.toptal.com/developers/gitignore/api/sam,linux,macos,windows,dotsettings,sublimetext,visualstudio,visualstudiocode,jetbrains +# Edit at https://www.toptal.com/developers/gitignore?templates=sam,linux,macos,windows,dotsettings,sublimetext,visualstudio,visualstudiocode,jetbrains + +### DotSettings ### +*.DotSettings + +### JetBrains ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### JetBrains Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### SAM ### +# Ignore build directories for the AWS Serverless Application Model (SAM) +# Info: https://aws.amazon.com/serverless/sam/ +# Docs: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-reference.html + +**/.aws-sam + +### SublimeText ### +# Cache files for Sublime Text +*.tmlanguage.cache +*.tmPreferences.cache +*.stTheme.cache + +# Workspace files are user-specific +*.sublime-workspace + +# Project files should be checked into the repository, unless a significant +# proportion of contributors will probably not be using Sublime Text +# *.sublime-project + +# SFTP configuration file +sftp-config.json +sftp-config-alt*.json + +# Package control specific files +Package Control.last-run +Package Control.ca-list +Package Control.ca-bundle +Package Control.system-ca-bundle +Package Control.cache/ +Package Control.ca-certs/ +Package Control.merged-ca-bundle +Package Control.user-ca-bundle +oscrypto-ca-bundle.crt +bh_unicode_properties.cache + +# Sublime-github package stores a github token in this file +# https://packagecontrol.io/packages/sublime-github +GitHub.sublime-settings + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +# Support for Project snippet scope + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +*.code-workspace + +# Local History for Visual Studio Code + +# Windows Installer files from build outputs + +# JetBrains Rider +*.sln.iml + +### VisualStudio Patch ### +# Additional files built by Visual Studio + +# End of https://www.toptal.com/developers/gitignore/api/sam,linux,macos,windows,dotsettings,sublimetext,visualstudio,visualstudiocode,jetbrains diff --git a/examples/Metrics/PowertoolsMetricsExample.sln b/examples/Metrics/PowertoolsMetricsExample.sln new file mode 100644 index 000000000..fa39af04d --- /dev/null +++ b/examples/Metrics/PowertoolsMetricsExample.sln @@ -0,0 +1,28 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30114.105 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HelloWorld", "src\HelloWorld\HelloWorld.csproj", "{F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HelloWorld.Tests", "test\HelloWorld.Test\HelloWorld.Tests.csproj", "{9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}.Release|Any CPU.Build.0 = Release|Any CPU + {9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/examples/Metrics/README.md b/examples/Metrics/README.md new file mode 100644 index 000000000..83f0c1b96 --- /dev/null +++ b/examples/Metrics/README.md @@ -0,0 +1,120 @@ +# AWS Lambda Powertools for .NET Metrics Example + +This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes the following files and folders. + +- src - Code for the application's Lambda function and Project Dockerfile. +- events - Invocation events that you can use to invoke the function. +- test - Unit tests for the application code. +- template.yaml - A template that defines the application's AWS resources. + +The application uses several AWS resources, including Lambda functions and an API Gateway API. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code. + +If you prefer to use an integrated development environment (IDE) to build and test your application, you can use the AWS Toolkit. +The AWS Toolkit is an open source plug-in for popular IDEs that uses the SAM CLI to build and deploy serverless applications on AWS. The AWS Toolkit also adds a simplified step-through debugging experience for Lambda function code. See the following links to get started. + +- [Visual Studio Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html) +- [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html) +- [Rider](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) + +## Deploy the sample application + +The Serverless Application Model Command Line Interface (SAM CLI) is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API. + +To use the SAM CLI, you need the following tools. + +- SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) +- Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community) + +You will need the following for local testing. +- .NET 6.0 - [Install .NET 6.0](https://www.microsoft.com/net/download) + +To build and deploy your application for the first time, run the following in your shell. Make sure the `template.yaml` file is in your current directory: + +```bash +sam build +sam deploy --guided +``` + +The first command will build a docker image from a Dockerfile and then copy the source of your application inside the Docker image. The second command will package and deploy your application to AWS, with a series of prompts: + +- **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name. +- **AWS Region**: The AWS region you want to deploy your app to. +- **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes. +- **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command. +- **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application. + +You can find your API Gateway Endpoint URL in the output values displayed after deployment. + +## Use the SAM CLI to build and test locally + +Build your application with the `sam build` command. + +```bash +Logging$ sam build +``` + +The SAM CLI builds a docker image from a Dockerfile and then installs dependencies defined in `src/HelloWorld.csproj` inside the docker image. The processed template file is saved in the `.aws-sam/build` folder. + +Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project. + +Run functions locally and invoke them with the `sam local invoke` command. + +```bash +Logging$ sam local invoke HelloWorldFunction --event events/event.json +``` + +The SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000. + +```bash +Logging$ sam local start-api +Logging$ curl http://localhost:3000/ +``` + +The SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The `Events` property on each function's definition includes the route and method for each path. + +```yaml + Events: + HelloWorld: + Type: Api + Properties: + Path: /hello + Method: get +``` + +## Add a resource to your application + +The application template uses AWS Serverless Application Model (AWS SAM) to define application resources. AWS SAM is an extension of AWS CloudFormation with a simpler syntax for configuring common serverless application resources such as functions, triggers, and APIs. For resources not included in [the SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), you can use standard [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) resource types. + +## Fetch, tail, and filter Lambda function logs + +To simplify troubleshooting, SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug. + +`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM. + +```bash +Logging$ sam logs -n HelloWorldFunction --stack-name Logging --tail +``` + +You can find more information and examples about filtering Lambda function logs in the [SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html). + +## Unit tests + +Tests are defined in the `test` folder in this project. + +```bash +Logging$ dotnet test test/HelloWorld.Test +``` + +## Cleanup + +To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following: + +```bash +aws cloudformation delete-stack --stack-name Logging +``` + +## Resources + +See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the SAM CLI, and serverless application concepts. + +Next, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples and learn how authors developed their applications: [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/) diff --git a/examples/Metrics/events/event.json b/examples/Metrics/events/event.json new file mode 100644 index 000000000..3822fadaa --- /dev/null +++ b/examples/Metrics/events/event.json @@ -0,0 +1,63 @@ +{ + "body": "{\"message\": \"hello world\"}", + "resource": "/{proxy+}", + "path": "/path/to/resource", + "httpMethod": "POST", + "isBase64Encoded": false, + "queryStringParameters": { + "foo": "bar" + }, + "pathParameters": { + "proxy": "/path/to/resource" + }, + "stageVariables": { + "baz": "qux" + }, + "headers": { + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", + "Accept-Encoding": "gzip, deflate, sdch", + "Accept-Language": "en-US,en;q=0.8", + "Cache-Control": "max-age=0", + "CloudFront-Forwarded-Proto": "https", + "CloudFront-Is-Desktop-Viewer": "true", + "CloudFront-Is-Mobile-Viewer": "false", + "CloudFront-Is-SmartTV-Viewer": "false", + "CloudFront-Is-Tablet-Viewer": "false", + "CloudFront-Viewer-Country": "US", + "Host": "1234567890.execute-api.us-east-1.amazonaws.com", + "Upgrade-Insecure-Requests": "1", + "User-Agent": "Custom User Agent String", + "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", + "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", + "X-Forwarded-For": "127.0.0.1, 127.0.0.2", + "X-Forwarded-Port": "443", + "X-Forwarded-Proto": "https" + }, + "requestContext": { + "accountId": "123456789012", + "resourceId": "123456", + "stage": "prod", + "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", + "requestTime": "09/Apr/2015:12:34:56 +0000", + "requestTimeEpoch": 1428582896000, + "identity": { + "cognitoIdentityPoolId": null, + "accountId": null, + "cognitoIdentityId": null, + "caller": null, + "accessKey": null, + "sourceIp": "127.0.0.1", + "cognitoAuthenticationType": null, + "cognitoAuthenticationProvider": null, + "userArn": null, + "userAgent": "Custom User Agent String", + "user": null + }, + "path": "/prod/path/to/resource", + "resourcePath": "/{proxy+}", + "httpMethod": "POST", + "apiId": "1234567890", + "protocol": "HTTP/1.1" + } + } + \ No newline at end of file diff --git a/examples/Metrics/omnisharp.json b/examples/Metrics/omnisharp.json new file mode 100644 index 000000000..c42f8db91 --- /dev/null +++ b/examples/Metrics/omnisharp.json @@ -0,0 +1,11 @@ +{ + "fileOptions": { + "excludeSearchPatterns": [ + "**/bin/**/*", + "**/obj/**/*" + ] + }, + "msbuild": { + "Platform": "rhel.7.2-x64" + } +} \ No newline at end of file diff --git a/examples/Metrics/src/HelloWorld/Dockerfile b/examples/Metrics/src/HelloWorld/Dockerfile new file mode 100644 index 000000000..fca242579 --- /dev/null +++ b/examples/Metrics/src/HelloWorld/Dockerfile @@ -0,0 +1,26 @@ +ARG SAM_BUILD_MODE=Release +FROM public.ecr.aws/lambda/dotnet:6 AS base +FROM mcr.microsoft.com/dotnet/sdk:6.0-bullseye-slim as build + +ARG SAM_BUILD_MODE +ENV ENV_BUILD_MODE = ${SAM_BUILD_MODE} + +WORKDIR /src +COPY ["HelloWorld.csproj", "HelloWorld/"] +RUN dotnet restore "HelloWorld/HelloWorld.csproj" + +WORKDIR "/src/HelloWorld" +COPY . . + +RUN dotnet build "HelloWorld.csproj" --configuration ${SAM_BUILD_MODE} --output /app/build + +FROM build AS publish +RUN if [ "$ENV_BUILD_MODE" = "Debug" ]; \ +then dotnet publish "HelloWorld.csproj" --configuration "Debug" --runtime linux-x64 --self-contained false --output /app/publish; \ +else dotnet publish "HelloWorld.csproj" --configuration "Release" --runtime linux-x64 --self-contained false --output /app/publish -p:PublishReadyToRun=true; fi + + +FROM base AS final +WORKDIR /var/task +COPY --from=publish /app/publish . +CMD ["HelloWorld::HelloWorld.Function::FunctionHandler"] \ No newline at end of file diff --git a/examples/Metrics/src/HelloWorld/Function.cs b/examples/Metrics/src/HelloWorld/Function.cs new file mode 100644 index 000000000..c3f48fe7a --- /dev/null +++ b/examples/Metrics/src/HelloWorld/Function.cs @@ -0,0 +1,213 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +using Amazon; +using Amazon.DynamoDBv2; +using Amazon.DynamoDBv2.DataModel; +using Amazon.Lambda.APIGatewayEvents; +using Amazon.Lambda.Core; +using Amazon.Lambda.Serialization.SystemTextJson; +using AWS.Lambda.Powertools.Logging; +using AWS.Lambda.Powertools.Metrics; + +// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. +[assembly: LambdaSerializer(typeof(DefaultLambdaJsonSerializer))] + +namespace HelloWorld; + +public class Function +{ + private static HttpClient? _httpClient; + private static IDynamoDBContext? _dynamoDbContext; + + /// + /// Function constructor + /// + public Function() + { + _httpClient = new HttpClient(); + + var tableName = Environment.GetEnvironmentVariable("TABLE_NAME"); + + if (!string.IsNullOrEmpty(tableName)) + { + AWSConfigsDynamoDB.Context.TypeMappings[typeof(LookupRecord)] = + new Amazon.Util.TypeMapping(typeof(LookupRecord), tableName); + } + + var config = new DynamoDBContextConfig { Conversion = DynamoDBEntryConversion.V2 }; + _dynamoDbContext = new DynamoDBContext(new AmazonDynamoDBClient(), config); + } + + /// + /// Test constructor + /// + public Function(IDynamoDBContext dynamoDbContext, HttpClient httpClient) + { + _httpClient = httpClient; + _dynamoDbContext = dynamoDbContext; + } + + /// + /// Lambda Handler + /// + /// API Gateway Proxy event + /// AWS Lambda context + /// API Gateway Proxy response + [Logging(LogEvent = true)] + [Metrics(CaptureColdStart = true)] + public async Task FunctionHandler(APIGatewayProxyRequest apigwProxyEvent, + ILambdaContext context) + { + var requestContextRequestId = apigwProxyEvent.RequestContext.RequestId; + + Logger.LogInformation("Getting ip address from external service"); + + // Add Metric to capture the amount of time + Metrics.PushSingleMetric( + metricName: "CallingIP", + value: 1, + unit: MetricUnit.Count, + service: "lambda-powertools-metrics-example", + defaultDimensions: new Dictionary + { + { "Metric Type", "Single" } + }); + + var watch = Stopwatch.StartNew(); + var location = await GetCallingIp(); + watch.Stop(); + + Metrics.AddMetric("ElapsedExecutionTime", watch.ElapsedMilliseconds, MetricUnit.Milliseconds); + Metrics.AddMetric("SuccessfulLocations", 1, MetricUnit.Count); + + var lookupRecord = new LookupRecord(lookupId: requestContextRequestId, + greeting: "Hello AWS Lambda Powertools for .NET", ipAddress: location); + + try + { + Metrics.PushSingleMetric( + metricName: "RecordsSaved", + value: 1, + unit: MetricUnit.Count, + service: "lambda-powertools-metrics-example", + defaultDimensions: new Dictionary + { + { "Metric Type", "Single" } + }); + + await SaveRecordInDynamo(lookupRecord); + + Metrics.AddMetric("SuccessfulWrites", 1, MetricUnit.Count); + + return new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(lookupRecord), + StatusCode = 200, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + catch (Exception e) + { + return new APIGatewayProxyResponse + { + Body = e.Message, + StatusCode = 500, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + } + + /// + /// Calls location api to return IP address + /// + /// IP address string + private static async Task GetCallingIp() + { + if (_httpClient == null) return "0.0.0.0"; + _httpClient.DefaultRequestHeaders.Accept.Clear(); + _httpClient.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); + + try + { + Logger.LogInformation("Calling Check IP API"); + + var response = await _httpClient.GetStringAsync("https://checkip.amazonaws.com/").ConfigureAwait(false); + var ip = response.Replace("\n", ""); + + Logger.LogInformation($"API response returned {ip}"); + + return ip; + } + catch (Exception ex) + { + Logger.LogError(ex); + throw; + } + } + + /// + /// Saves the lookup record in DynamoDB + /// + /// Instance of LookupRecord + /// A Task that can be used to poll or wait for results, or both. + private static async Task SaveRecordInDynamo(LookupRecord lookupRecord) + { + try + { + Logger.LogInformation($"Saving record with id {lookupRecord.LookupId}"); + await _dynamoDbContext?.SaveAsync(lookupRecord)!; + } + catch (AmazonDynamoDBException e) + { + Logger.LogCritical(e.Message); + throw; + } + } +} + +/// +/// LookupRecord class represents the data structure of location lookup +/// +[Serializable] +public class LookupRecord +{ + public LookupRecord() + { + } + + /// + /// Create new LookupRecord + /// + /// Id of the lookup + /// Greeting phrase + /// IP address + public LookupRecord(string? lookupId, string? greeting, string? ipAddress) + { + LookupId = lookupId; + Greeting = greeting; + IpAddress = ipAddress; + } + + public string? LookupId { get; set; } + public string? Greeting { get; set; } + public string? IpAddress { get; set; } +} \ No newline at end of file diff --git a/examples/Metrics/src/HelloWorld/HelloWorld.csproj b/examples/Metrics/src/HelloWorld/HelloWorld.csproj new file mode 100644 index 000000000..f8a5fc9d9 --- /dev/null +++ b/examples/Metrics/src/HelloWorld/HelloWorld.csproj @@ -0,0 +1,15 @@ + + + net6.0 + true + enable + + + + + + + + + + \ No newline at end of file diff --git a/examples/Metrics/template-docker.yaml b/examples/Metrics/template-docker.yaml new file mode 100644 index 000000000..f36100cd7 --- /dev/null +++ b/examples/Metrics/template-docker.yaml @@ -0,0 +1,101 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +AWSTemplateFormatVersion: "2010-09-09" +Transform: AWS::Serverless-2016-10-31 +Description: > + Example project for AWS Lambda Powertools Metrics utility + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Timeout: 10 + Environment: + Variables: + POWERTOOLS_SERVICE_NAME: powertools-dotnet-metrics-sample # This can also be set using the Metrics decorator on your handler [Metrics(Namespace = "aws-lambda-powertools"] + POWERTOOLS_LOG_LEVEL: Debug + POWERTOOLS_LOGGER_CASE: SnakeCase # Allowed values are: CamelCase, PascalCase and SnakeCase (default) + POWERTOOLS_METRICS_NAMESPACE: AWSLambdaPowertools # This can also be set using the Metrics decorator on your handler [Metrics(Namespace = "aws-lambda-powertools"] + +Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + MemorySize: 256 + PackageType: Image + Role: !Sub ${HelloWorldFunctionRole.Arn} + Environment: + Variables: + TABLE_NAME: !Ref PowertoolsMetricsTable + Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get + Metadata: + DockerTag: dotnet6.0-v1 + DockerContext: ./src/HelloWorld + Dockerfile: Dockerfile + DockerBuildArgs: + SAM_BUILD_MODE: Release # Debug or Release + + + PowertoolsMetricsTable: + Type: AWS::Serverless::SimpleTable + Properties: + TableName: PowertoolsMetrics + PrimaryKey: + Name: LookupId + Type: String + + HelloWorldFunctionRole: + Type: "AWS::IAM::Role" + Properties: + Path: !Join ["", ["/", !Ref "AWS::StackName", "/"]] + ManagedPolicyArns: + - "arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess" + - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - + Sid: "AllowLambdaServiceToAssumeRole" + Effect: "Allow" + Action: + - "sts:AssumeRole" + Principal: + Service: + - "lambda.amazonaws.com" + Policies: + - PolicyName: "AllowCRUDOperationsOnDynamoDB" + PolicyDocument: + Version: '2012-10-17' + Statement: + - + Effect: "Allow" + Action: + - 'dynamodb:GetItem' + - 'dynamodb:DeleteItem' + - 'dynamodb:DescribeTable' + - 'dynamodb:PutItem' + - 'dynamodb:Scan' + - 'dynamodb:Query' + - 'dynamodb:UpdateItem' + - 'dynamodb:BatchWriteItem' + - 'dynamodb:BatchGetItem' + Resource: + - !Sub ${PowertoolsMetricsTable.Arn} + +Outputs: + # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function + # Find out more about other implicit resources you can reference within SAM + # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api + HelloWorldApi: + Description: "API Gateway endpoint URL for Prod stage for Hello World function" + Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" + HelloWorldFunction: + Description: "Hello World Lambda Function ARN" + Value: !GetAtt HelloWorldFunction.Arn + HelloWorldFunctionIamRole: + Description: "Implicit IAM Role created for Hello World function" + Value: !GetAtt HelloWorldFunctionRole.Arn diff --git a/examples/Metrics/template.yaml b/examples/Metrics/template.yaml new file mode 100644 index 000000000..483f8a2cb --- /dev/null +++ b/examples/Metrics/template.yaml @@ -0,0 +1,96 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +AWSTemplateFormatVersion: "2010-09-09" +Transform: AWS::Serverless-2016-10-31 +Description: > + Example project for AWS Lambda Powertools Metrics utility + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Timeout: 10 + Environment: + Variables: + POWERTOOLS_SERVICE_NAME: powertools-dotnet-metrics-sample # This can also be set using the Metrics decorator on your handler [Metrics(Namespace = "aws-lambda-powertools"] + POWERTOOLS_LOG_LEVEL: Debug + POWERTOOLS_LOGGER_CASE: SnakeCase # Allowed values are: CamelCase, PascalCase and SnakeCase (default) + POWERTOOLS_METRICS_NAMESPACE: AWSLambdaPowertools # This can also be set using the Metrics decorator on your handler [Metrics(Namespace = "aws-lambda-powertools"] + +Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + Runtime: dotnet6 + CodeUri: ./src/HelloWorld/ + Handler: HelloWorld::HelloWorld.Function::FunctionHandler + MemorySize: 256 + Role: !Sub ${HelloWorldFunctionRole.Arn} + Environment: + Variables: + TABLE_NAME: !Ref PowertoolsMetricsTable + Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get + + PowertoolsMetricsTable: + Type: AWS::Serverless::SimpleTable + Properties: + TableName: PowertoolsMetrics + PrimaryKey: + Name: LookupId + Type: String + + HelloWorldFunctionRole: + Type: "AWS::IAM::Role" + Properties: + Path: !Join ["", ["/", !Ref "AWS::StackName", "/"]] + ManagedPolicyArns: + - "arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess" + - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - + Sid: "AllowLambdaServiceToAssumeRole" + Effect: "Allow" + Action: + - "sts:AssumeRole" + Principal: + Service: + - "lambda.amazonaws.com" + Policies: + - PolicyName: "AllowCRUDOperationsOnDynamoDB" + PolicyDocument: + Version: '2012-10-17' + Statement: + - + Effect: "Allow" + Action: + - 'dynamodb:GetItem' + - 'dynamodb:DeleteItem' + - 'dynamodb:DescribeTable' + - 'dynamodb:PutItem' + - 'dynamodb:Scan' + - 'dynamodb:Query' + - 'dynamodb:UpdateItem' + - 'dynamodb:BatchWriteItem' + - 'dynamodb:BatchGetItem' + Resource: + - !Sub ${PowertoolsMetricsTable.Arn} + +Outputs: + # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function + # Find out more about other implicit resources you can reference within SAM + # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api + HelloWorldApi: + Description: "API Gateway endpoint URL for Prod stage for Hello World function" + Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" + HelloWorldFunction: + Description: "Hello World Lambda Function ARN" + Value: !GetAtt HelloWorldFunction.Arn + HelloWorldFunctionIamRole: + Description: "Implicit IAM Role created for Hello World function" + Value: !GetAtt HelloWorldFunctionRole.Arn diff --git a/examples/Metrics/test/HelloWorld.Test/FunctionTest.cs b/examples/Metrics/test/HelloWorld.Test/FunctionTest.cs new file mode 100644 index 000000000..a99b46bc3 --- /dev/null +++ b/examples/Metrics/test/HelloWorld.Test/FunctionTest.cs @@ -0,0 +1,108 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Amazon.DynamoDBv2.DataModel; +using Xunit; +using Amazon.Lambda.APIGatewayEvents; +using Amazon.Lambda.TestUtilities; +using Moq; +using Moq.Protected; +using Xunit.Abstractions; + +namespace HelloWorld.Tests +{ + public class FunctionTest + { + private readonly ITestOutputHelper _testOutputHelper; + + public FunctionTest(ITestOutputHelper testOutputHelper) + { + _testOutputHelper = testOutputHelper; + } + + [Fact] + public async Task TestHelloWorldFunctionHandler() + { + var requestId = Guid.NewGuid().ToString("D"); + var accountId = Guid.NewGuid().ToString("D"); + var location = "192.158. 1.38"; + Environment.SetEnvironmentVariable("POWERTOOLS_METRICS_NAMESPACE","AWSLambdaPowertools"); + + var dynamoDbContext = new Mock(); + var handlerMock = new Mock(); + handlerMock + .Protected() + .Setup>( + "SendAsync", + ItExpr.IsAny(), + ItExpr.IsAny() + ) + .ReturnsAsync(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK, + Content = new StringContent(location) + }) + .Verifiable(); + + var request = new APIGatewayProxyRequest + { + RequestContext = new APIGatewayProxyRequest.ProxyRequestContext + { + RequestId = requestId, + AccountId = accountId + } + }; + + var context = new TestLambdaContext() + { + FunctionName = "PowertoolsLoggingSample-HelloWorldFunction-Gg8rhPwO7Wa1", + FunctionVersion = "1", + MemoryLimitInMB = 215, + AwsRequestId = Guid.NewGuid().ToString("D") + }; + + var body = new Dictionary + { + { "LookupId", requestId }, + { "Greeting", "Hello AWS Lambda Powertools for .NET" }, + { "IpAddress", location }, + }; + + var expectedResponse = new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(body), + StatusCode = 200, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + + var function = new Function(dynamoDbContext.Object, new HttpClient(handlerMock.Object)); + var response = await function.FunctionHandler(request, context); + + _testOutputHelper.WriteLine("Lambda Response: \n" + response.Body); + _testOutputHelper.WriteLine("Expected Response: \n" + expectedResponse.Body); + + Assert.Equal(expectedResponse.Body, response.Body); + Assert.Equal(expectedResponse.Headers, response.Headers); + Assert.Equal(expectedResponse.StatusCode, response.StatusCode); + } + } +} \ No newline at end of file diff --git a/examples/Metrics/test/HelloWorld.Test/HelloWorld.Tests.csproj b/examples/Metrics/test/HelloWorld.Test/HelloWorld.Tests.csproj new file mode 100644 index 000000000..be3f49fd8 --- /dev/null +++ b/examples/Metrics/test/HelloWorld.Test/HelloWorld.Tests.csproj @@ -0,0 +1,18 @@ + + + net6.0 + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/examples/Tracing/.gitignore b/examples/Tracing/.gitignore new file mode 100644 index 000000000..0b4d6c4c4 --- /dev/null +++ b/examples/Tracing/.gitignore @@ -0,0 +1,637 @@ +samconfig.toml +# Created by https://www.toptal.com/developers/gitignore/api/sam,linux,macos,windows,dotsettings,sublimetext,visualstudio,visualstudiocode,jetbrains +# Edit at https://www.toptal.com/developers/gitignore?templates=sam,linux,macos,windows,dotsettings,sublimetext,visualstudio,visualstudiocode,jetbrains + +### DotSettings ### +*.DotSettings + +### JetBrains ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### JetBrains Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### SAM ### +# Ignore build directories for the AWS Serverless Application Model (SAM) +# Info: https://aws.amazon.com/serverless/sam/ +# Docs: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-reference.html + +**/.aws-sam + +### SublimeText ### +# Cache files for Sublime Text +*.tmlanguage.cache +*.tmPreferences.cache +*.stTheme.cache + +# Workspace files are user-specific +*.sublime-workspace + +# Project files should be checked into the repository, unless a significant +# proportion of contributors will probably not be using Sublime Text +# *.sublime-project + +# SFTP configuration file +sftp-config.json +sftp-config-alt*.json + +# Package control specific files +Package Control.last-run +Package Control.ca-list +Package Control.ca-bundle +Package Control.system-ca-bundle +Package Control.cache/ +Package Control.ca-certs/ +Package Control.merged-ca-bundle +Package Control.user-ca-bundle +oscrypto-ca-bundle.crt +bh_unicode_properties.cache + +# Sublime-github package stores a github token in this file +# https://packagecontrol.io/packages/sublime-github +GitHub.sublime-settings + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +# Support for Project snippet scope + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +*.code-workspace + +# Local History for Visual Studio Code + +# Windows Installer files from build outputs + +# JetBrains Rider +*.sln.iml + +### VisualStudio Patch ### +# Additional files built by Visual Studio + +# End of https://www.toptal.com/developers/gitignore/api/sam,linux,macos,windows,dotsettings,sublimetext,visualstudio,visualstudiocode,jetbrains diff --git a/examples/Tracing/PowertoolsTracingExample.sln b/examples/Tracing/PowertoolsTracingExample.sln new file mode 100644 index 000000000..fa39af04d --- /dev/null +++ b/examples/Tracing/PowertoolsTracingExample.sln @@ -0,0 +1,28 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30114.105 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HelloWorld", "src\HelloWorld\HelloWorld.csproj", "{F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HelloWorld.Tests", "test\HelloWorld.Test\HelloWorld.Tests.csproj", "{9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F36CE828-C7B1-4BD1-AC4B-500C7ACD14E1}.Release|Any CPU.Build.0 = Release|Any CPU + {9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9B31B9EA-52BC-47B6-B78B-AC16502D8D4A}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/examples/Tracing/README.md b/examples/Tracing/README.md new file mode 100644 index 000000000..83f0c1b96 --- /dev/null +++ b/examples/Tracing/README.md @@ -0,0 +1,120 @@ +# AWS Lambda Powertools for .NET Metrics Example + +This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes the following files and folders. + +- src - Code for the application's Lambda function and Project Dockerfile. +- events - Invocation events that you can use to invoke the function. +- test - Unit tests for the application code. +- template.yaml - A template that defines the application's AWS resources. + +The application uses several AWS resources, including Lambda functions and an API Gateway API. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code. + +If you prefer to use an integrated development environment (IDE) to build and test your application, you can use the AWS Toolkit. +The AWS Toolkit is an open source plug-in for popular IDEs that uses the SAM CLI to build and deploy serverless applications on AWS. The AWS Toolkit also adds a simplified step-through debugging experience for Lambda function code. See the following links to get started. + +- [Visual Studio Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html) +- [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html) +- [Rider](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) + +## Deploy the sample application + +The Serverless Application Model Command Line Interface (SAM CLI) is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API. + +To use the SAM CLI, you need the following tools. + +- SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) +- Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community) + +You will need the following for local testing. +- .NET 6.0 - [Install .NET 6.0](https://www.microsoft.com/net/download) + +To build and deploy your application for the first time, run the following in your shell. Make sure the `template.yaml` file is in your current directory: + +```bash +sam build +sam deploy --guided +``` + +The first command will build a docker image from a Dockerfile and then copy the source of your application inside the Docker image. The second command will package and deploy your application to AWS, with a series of prompts: + +- **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name. +- **AWS Region**: The AWS region you want to deploy your app to. +- **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes. +- **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command. +- **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application. + +You can find your API Gateway Endpoint URL in the output values displayed after deployment. + +## Use the SAM CLI to build and test locally + +Build your application with the `sam build` command. + +```bash +Logging$ sam build +``` + +The SAM CLI builds a docker image from a Dockerfile and then installs dependencies defined in `src/HelloWorld.csproj` inside the docker image. The processed template file is saved in the `.aws-sam/build` folder. + +Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project. + +Run functions locally and invoke them with the `sam local invoke` command. + +```bash +Logging$ sam local invoke HelloWorldFunction --event events/event.json +``` + +The SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000. + +```bash +Logging$ sam local start-api +Logging$ curl http://localhost:3000/ +``` + +The SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The `Events` property on each function's definition includes the route and method for each path. + +```yaml + Events: + HelloWorld: + Type: Api + Properties: + Path: /hello + Method: get +``` + +## Add a resource to your application + +The application template uses AWS Serverless Application Model (AWS SAM) to define application resources. AWS SAM is an extension of AWS CloudFormation with a simpler syntax for configuring common serverless application resources such as functions, triggers, and APIs. For resources not included in [the SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), you can use standard [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) resource types. + +## Fetch, tail, and filter Lambda function logs + +To simplify troubleshooting, SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug. + +`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM. + +```bash +Logging$ sam logs -n HelloWorldFunction --stack-name Logging --tail +``` + +You can find more information and examples about filtering Lambda function logs in the [SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html). + +## Unit tests + +Tests are defined in the `test` folder in this project. + +```bash +Logging$ dotnet test test/HelloWorld.Test +``` + +## Cleanup + +To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following: + +```bash +aws cloudformation delete-stack --stack-name Logging +``` + +## Resources + +See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the SAM CLI, and serverless application concepts. + +Next, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples and learn how authors developed their applications: [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/) diff --git a/examples/Tracing/events/event.json b/examples/Tracing/events/event.json new file mode 100644 index 000000000..3822fadaa --- /dev/null +++ b/examples/Tracing/events/event.json @@ -0,0 +1,63 @@ +{ + "body": "{\"message\": \"hello world\"}", + "resource": "/{proxy+}", + "path": "/path/to/resource", + "httpMethod": "POST", + "isBase64Encoded": false, + "queryStringParameters": { + "foo": "bar" + }, + "pathParameters": { + "proxy": "/path/to/resource" + }, + "stageVariables": { + "baz": "qux" + }, + "headers": { + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", + "Accept-Encoding": "gzip, deflate, sdch", + "Accept-Language": "en-US,en;q=0.8", + "Cache-Control": "max-age=0", + "CloudFront-Forwarded-Proto": "https", + "CloudFront-Is-Desktop-Viewer": "true", + "CloudFront-Is-Mobile-Viewer": "false", + "CloudFront-Is-SmartTV-Viewer": "false", + "CloudFront-Is-Tablet-Viewer": "false", + "CloudFront-Viewer-Country": "US", + "Host": "1234567890.execute-api.us-east-1.amazonaws.com", + "Upgrade-Insecure-Requests": "1", + "User-Agent": "Custom User Agent String", + "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", + "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", + "X-Forwarded-For": "127.0.0.1, 127.0.0.2", + "X-Forwarded-Port": "443", + "X-Forwarded-Proto": "https" + }, + "requestContext": { + "accountId": "123456789012", + "resourceId": "123456", + "stage": "prod", + "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", + "requestTime": "09/Apr/2015:12:34:56 +0000", + "requestTimeEpoch": 1428582896000, + "identity": { + "cognitoIdentityPoolId": null, + "accountId": null, + "cognitoIdentityId": null, + "caller": null, + "accessKey": null, + "sourceIp": "127.0.0.1", + "cognitoAuthenticationType": null, + "cognitoAuthenticationProvider": null, + "userArn": null, + "userAgent": "Custom User Agent String", + "user": null + }, + "path": "/prod/path/to/resource", + "resourcePath": "/{proxy+}", + "httpMethod": "POST", + "apiId": "1234567890", + "protocol": "HTTP/1.1" + } + } + \ No newline at end of file diff --git a/examples/Tracing/omnisharp.json b/examples/Tracing/omnisharp.json new file mode 100644 index 000000000..c42f8db91 --- /dev/null +++ b/examples/Tracing/omnisharp.json @@ -0,0 +1,11 @@ +{ + "fileOptions": { + "excludeSearchPatterns": [ + "**/bin/**/*", + "**/obj/**/*" + ] + }, + "msbuild": { + "Platform": "rhel.7.2-x64" + } +} \ No newline at end of file diff --git a/examples/Tracing/src/HelloWorld/Dockerfile b/examples/Tracing/src/HelloWorld/Dockerfile new file mode 100644 index 000000000..fca242579 --- /dev/null +++ b/examples/Tracing/src/HelloWorld/Dockerfile @@ -0,0 +1,26 @@ +ARG SAM_BUILD_MODE=Release +FROM public.ecr.aws/lambda/dotnet:6 AS base +FROM mcr.microsoft.com/dotnet/sdk:6.0-bullseye-slim as build + +ARG SAM_BUILD_MODE +ENV ENV_BUILD_MODE = ${SAM_BUILD_MODE} + +WORKDIR /src +COPY ["HelloWorld.csproj", "HelloWorld/"] +RUN dotnet restore "HelloWorld/HelloWorld.csproj" + +WORKDIR "/src/HelloWorld" +COPY . . + +RUN dotnet build "HelloWorld.csproj" --configuration ${SAM_BUILD_MODE} --output /app/build + +FROM build AS publish +RUN if [ "$ENV_BUILD_MODE" = "Debug" ]; \ +then dotnet publish "HelloWorld.csproj" --configuration "Debug" --runtime linux-x64 --self-contained false --output /app/publish; \ +else dotnet publish "HelloWorld.csproj" --configuration "Release" --runtime linux-x64 --self-contained false --output /app/publish -p:PublishReadyToRun=true; fi + + +FROM base AS final +WORKDIR /var/task +COPY --from=publish /app/publish . +CMD ["HelloWorld::HelloWorld.Function::FunctionHandler"] \ No newline at end of file diff --git a/examples/Tracing/src/HelloWorld/Function.cs b/examples/Tracing/src/HelloWorld/Function.cs new file mode 100644 index 000000000..357c10bd2 --- /dev/null +++ b/examples/Tracing/src/HelloWorld/Function.cs @@ -0,0 +1,196 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +using Amazon; +using Amazon.DynamoDBv2; +using Amazon.DynamoDBv2.DataModel; +using Amazon.Lambda.APIGatewayEvents; +using Amazon.Lambda.Core; +using Amazon.Lambda.Serialization.SystemTextJson; +using Amazon.XRay.Recorder.Handlers.AwsSdk; +using AWS.Lambda.Powertools.Logging; +using AWS.Lambda.Powertools.Tracing; + +// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. +[assembly: LambdaSerializer(typeof(DefaultLambdaJsonSerializer))] + +namespace HelloWorld; + +public class Function +{ + private static HttpClient? _httpClient; + private static IDynamoDBContext? _dynamoDbContext; + + /// + /// Function constructor + /// + public Function() + { + AWSSDKHandler.RegisterXRayForAllServices(); + _httpClient = new HttpClient(); + + var tableName = Environment.GetEnvironmentVariable("TABLE_NAME"); + + if (!string.IsNullOrEmpty(tableName)) + { + AWSConfigsDynamoDB.Context.TypeMappings[typeof(LookupRecord)] = + new Amazon.Util.TypeMapping(typeof(LookupRecord), tableName); + } + + var config = new DynamoDBContextConfig { Conversion = DynamoDBEntryConversion.V2 }; + _dynamoDbContext = new DynamoDBContext(new AmazonDynamoDBClient(), config); + } + + /// + /// Test constructor + /// + public Function(IDynamoDBContext dynamoDbContext, HttpClient httpClient) + { + _httpClient = httpClient; + _dynamoDbContext = dynamoDbContext; + } + + /// + /// Lambda Handler + /// + /// API Gateway Proxy event + /// AWS Lambda context + /// API Gateway Proxy response + [Logging(LogEvent = true)] + [Tracing(CaptureMode = TracingCaptureMode.ResponseAndError)] + public async Task FunctionHandler(APIGatewayProxyRequest apigwProxyEvent, + ILambdaContext context) + { + var requestContextRequestId = apigwProxyEvent.RequestContext.RequestId; + + Logger.LogInformation("Getting ip address from external service"); + + var location = await GetCallingIp().ConfigureAwait(false); + + var lookupRecord = new LookupRecord(lookupId: requestContextRequestId, + greeting: "Hello AWS Lambda Powertools for .NET", ipAddress: location); + + // Trace Fluent API + Tracing.WithSubsegment("LoggingResponse", + subsegment => + { + subsegment.AddAnnotation("AccountId", apigwProxyEvent.RequestContext.AccountId); + subsegment.AddMetadata("LookupRecord", lookupRecord); + }); + + try + { + await SaveRecordInDynamo(lookupRecord); + + return new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(lookupRecord), + StatusCode = 200, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + catch (Exception e) + { + return new APIGatewayProxyResponse + { + Body = e.Message, + StatusCode = 500, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + } + + /// + /// Calls location api to return IP address + /// + /// IP address string + [Tracing(SegmentName = "Location service")] + private static async Task GetCallingIp() + { + if (_httpClient == null) return "0.0.0.0"; + _httpClient.DefaultRequestHeaders.Accept.Clear(); + _httpClient.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); + + try + { + Logger.LogInformation("Calling Check IP API"); + + var response = await _httpClient.GetStringAsync("https://checkip.amazonaws.com/").ConfigureAwait(false); + var ip = response.Replace("\n", ""); + + Logger.LogInformation($"API response returned {ip}"); + + return ip; + } + catch (Exception ex) + { + Logger.LogError(ex); + throw; + } + } + + /// + /// Saves the lookup record in DynamoDB + /// + /// Instance of LookupRecord + /// A Task that can be used to poll or wait for results, or both. + [Tracing(SegmentName = "DynamoDB")] + private static async Task SaveRecordInDynamo(LookupRecord lookupRecord) + { + try + { + Logger.LogInformation($"Saving record with id {lookupRecord.LookupId}"); + await _dynamoDbContext?.SaveAsync(lookupRecord)!; + } + catch (AmazonDynamoDBException e) + { + Logger.LogCritical(e.Message); + throw; + } + } +} + +/// +/// LookupRecord class represents the data structure of location lookup +/// +[Serializable] +public class LookupRecord +{ + public LookupRecord() + { + } + + /// + /// Create new LookupRecord + /// + /// Id of the lookup + /// Greeting phrase + /// IP address + public LookupRecord(string? lookupId, string? greeting, string? ipAddress) + { + LookupId = lookupId; + Greeting = greeting; + IpAddress = ipAddress; + } + + public string? LookupId { get; set; } + public string? Greeting { get; set; } + public string? IpAddress { get; set; } +} \ No newline at end of file diff --git a/examples/Tracing/src/HelloWorld/HelloWorld.csproj b/examples/Tracing/src/HelloWorld/HelloWorld.csproj new file mode 100644 index 000000000..06cb31509 --- /dev/null +++ b/examples/Tracing/src/HelloWorld/HelloWorld.csproj @@ -0,0 +1,16 @@ + + + net6.0 + true + enable + + + + + + + + + + + \ No newline at end of file diff --git a/examples/Tracing/template-docker.yaml b/examples/Tracing/template-docker.yaml new file mode 100644 index 000000000..38914c501 --- /dev/null +++ b/examples/Tracing/template-docker.yaml @@ -0,0 +1,100 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +AWSTemplateFormatVersion: "2010-09-09" +Transform: AWS::Serverless-2016-10-31 +Description: > + Example project for AWS Lambda Powertools tracing utility + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Timeout: 10 + Environment: + Variables: + POWERTOOLS_SERVICE_NAME: powertools-dotnet-tracing-sample + POWERTOOLS_LOG_LEVEL: Debug + POWERTOOLS_LOGGER_CASE: SnakeCase # Allowed values are: CamelCase, PascalCase and SnakeCase + +Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + MemorySize: 256 + PackageType: Image + Role: !Sub ${HelloWorldFunctionRole.Arn} + Environment: + Variables: + TABLE_NAME: !Ref PowertoolsTracingTable + Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get + Metadata: + DockerTag: dotnet6.0-v1 + DockerContext: ./src/HelloWorld + Dockerfile: Dockerfile + DockerBuildArgs: + SAM_BUILD_MODE: Release # Debug or Release + + + PowertoolsTracingTable: + Type: AWS::Serverless::SimpleTable + Properties: + TableName: PowertoolsLogging + PrimaryKey: + Name: LookupId + Type: String + + HelloWorldFunctionRole: + Type: "AWS::IAM::Role" + Properties: + Path: !Join ["", ["/", !Ref "AWS::StackName", "/"]] + ManagedPolicyArns: + - "arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess" + - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - + Sid: "AllowLambdaServiceToAssumeRole" + Effect: "Allow" + Action: + - "sts:AssumeRole" + Principal: + Service: + - "lambda.amazonaws.com" + Policies: + - PolicyName: "AllowCRUDOperationsOnDynamoDB" + PolicyDocument: + Version: '2012-10-17' + Statement: + - + Effect: "Allow" + Action: + - 'dynamodb:GetItem' + - 'dynamodb:DeleteItem' + - 'dynamodb:DescribeTable' + - 'dynamodb:PutItem' + - 'dynamodb:Scan' + - 'dynamodb:Query' + - 'dynamodb:UpdateItem' + - 'dynamodb:BatchWriteItem' + - 'dynamodb:BatchGetItem' + Resource: + - !Sub ${PowertoolsTracingTable.Arn} + +Outputs: + # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function + # Find out more about other implicit resources you can reference within SAM + # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api + HelloWorldApi: + Description: "API Gateway endpoint URL for Prod stage for Hello World function" + Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" + HelloWorldFunction: + Description: "Hello World Lambda Function ARN" + Value: !GetAtt HelloWorldFunction.Arn + HelloWorldFunctionIamRole: + Description: "Implicit IAM Role created for Hello World function" + Value: !GetAtt HelloWorldFunctionRole.Arn diff --git a/examples/Tracing/template.yaml b/examples/Tracing/template.yaml new file mode 100644 index 000000000..51181507e --- /dev/null +++ b/examples/Tracing/template.yaml @@ -0,0 +1,109 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +AWSTemplateFormatVersion: "2010-09-09" +Transform: AWS::Serverless-2016-10-31 +Description: > + Example project for AWS Lambda Powertools tracing utility + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Timeout: 10 + Tracing: Active + Environment: + Variables: + POWERTOOLS_SERVICE_NAME: powertools-dotnet-tracing-sample + POWERTOOLS_LOG_LEVEL: Debug + POWERTOOLS_LOGGER_CASE: SnakeCase # Allowed values are: CamelCase, PascalCase and SnakeCase (Default) + POWERTOOLS_TRACER_CAPTURE_RESPONSE: true + POWERTOOLS_TRACER_CAPTURE_ERROR: true # To disable tracing (CaptureMode = TracingCaptureMode.Disabled) + +Resources: + + HelloWorldApi: + Type: AWS::Serverless::Api + Properties: + StageName: Prod + EndpointConfiguration: REGIONAL + TracingEnabled: true + + HelloWorldFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + Runtime: dotnet6 + CodeUri: ./src/HelloWorld/ + Handler: HelloWorld::HelloWorld.Function::FunctionHandler + MemorySize: 256 + Role: !Sub ${HelloWorldFunctionRole.Arn} + Environment: + Variables: + TABLE_NAME: !Ref PowertoolsTracingTable + Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + RestApiId: !Ref HelloWorldApi + Path: /hello + Method: get + + + + PowertoolsTracingTable: + Type: AWS::Serverless::SimpleTable + Properties: + TableName: PowertoolsTracing + PrimaryKey: + Name: LookupId + Type: String + + HelloWorldFunctionRole: + Type: "AWS::IAM::Role" + Properties: + Path: !Join ["", ["/", !Ref "AWS::StackName", "/"]] + ManagedPolicyArns: + - "arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess" + - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - + Sid: "AllowLambdaServiceToAssumeRole" + Effect: "Allow" + Action: + - "sts:AssumeRole" + Principal: + Service: + - "lambda.amazonaws.com" + Policies: + - PolicyName: "AllowCRUDOperationsOnDynamoDB" + PolicyDocument: + Version: '2012-10-17' + Statement: + - + Effect: "Allow" + Action: + - 'dynamodb:GetItem' + - 'dynamodb:DeleteItem' + - 'dynamodb:DescribeTable' + - 'dynamodb:PutItem' + - 'dynamodb:Scan' + - 'dynamodb:Query' + - 'dynamodb:UpdateItem' + - 'dynamodb:BatchWriteItem' + - 'dynamodb:BatchGetItem' + Resource: + - !Sub ${PowertoolsTracingTable.Arn} + +Outputs: + # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function + # Find out more about other implicit resources you can reference within SAM + # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api + HelloWorldApi: + Description: "API Gateway endpoint URL for Prod stage for Hello World function" + Value: !Sub "https://${HelloWorldApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" + HelloWorldFunction: + Description: "Hello World Lambda Function ARN" + Value: !GetAtt HelloWorldFunction.Arn + HelloWorldFunctionIamRole: + Description: "Implicit IAM Role created for Hello World function" + Value: !GetAtt HelloWorldFunctionRole.Arn diff --git a/examples/Tracing/test/HelloWorld.Test/FunctionTest.cs b/examples/Tracing/test/HelloWorld.Test/FunctionTest.cs new file mode 100644 index 000000000..83ac37121 --- /dev/null +++ b/examples/Tracing/test/HelloWorld.Test/FunctionTest.cs @@ -0,0 +1,108 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Amazon.DynamoDBv2.DataModel; +using Xunit; +using Amazon.Lambda.APIGatewayEvents; +using Amazon.Lambda.TestUtilities; +using Moq; +using Moq.Protected; +using Xunit.Abstractions; + +namespace HelloWorld.Tests +{ + public class FunctionTest + { + private readonly ITestOutputHelper _testOutputHelper; + + public FunctionTest(ITestOutputHelper testOutputHelper) + { + _testOutputHelper = testOutputHelper; + } + + [Fact] + public async Task TestHelloWorldFunctionHandler() + { + var requestId = Guid.NewGuid().ToString("D"); + var accountId = Guid.NewGuid().ToString("D"); + var location = "192.158. 1.38"; + Environment.SetEnvironmentVariable("POWERTOOLS_SERVICE_NAME","powertools-dotnet-sample"); + + var dynamoDbContext = new Mock(); + var handlerMock = new Mock(); + handlerMock + .Protected() + .Setup>( + "SendAsync", + ItExpr.IsAny(), + ItExpr.IsAny() + ) + .ReturnsAsync(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK, + Content = new StringContent(location) + }) + .Verifiable(); + + var request = new APIGatewayProxyRequest + { + RequestContext = new APIGatewayProxyRequest.ProxyRequestContext + { + RequestId = requestId, + AccountId = accountId + } + }; + + var context = new TestLambdaContext() + { + FunctionName = "PowertoolsLoggingSample-HelloWorldFunction-Gg8rhPwO7Wa1", + FunctionVersion = "1", + MemoryLimitInMB = 215, + AwsRequestId = Guid.NewGuid().ToString("D") + }; + + var body = new Dictionary + { + { "LookupId", requestId }, + { "Greeting", "Hello AWS Lambda Powertools for .NET" }, + { "IpAddress", location }, + }; + + var expectedResponse = new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(body), + StatusCode = 200, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + + var function = new Function(dynamoDbContext.Object, new HttpClient(handlerMock.Object)); + var response = await function.FunctionHandler(request, context); + + _testOutputHelper.WriteLine("Lambda Response: \n" + response.Body); + _testOutputHelper.WriteLine("Expected Response: \n" + expectedResponse.Body); + + Assert.Equal(expectedResponse.Body, response.Body); + Assert.Equal(expectedResponse.Headers, response.Headers); + Assert.Equal(expectedResponse.StatusCode, response.StatusCode); + } + } +} \ No newline at end of file diff --git a/examples/Tracing/test/HelloWorld.Test/HelloWorld.Tests.csproj b/examples/Tracing/test/HelloWorld.Test/HelloWorld.Tests.csproj new file mode 100644 index 000000000..be3f49fd8 --- /dev/null +++ b/examples/Tracing/test/HelloWorld.Test/HelloWorld.Tests.csproj @@ -0,0 +1,18 @@ + + + net6.0 + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/global.json b/global.json new file mode 100644 index 000000000..572a2a6fa --- /dev/null +++ b/global.json @@ -0,0 +1,5 @@ +{ + "sdk": { + "version": "6.0.200" + } +} diff --git a/libraries/.gitignore b/libraries/.gitignore new file mode 100644 index 000000000..cb4fe3d70 --- /dev/null +++ b/libraries/.gitignore @@ -0,0 +1,454 @@ +# Created by https://www.toptal.com/developers/gitignore/api/dotnetcore,visualstudio,visualstudiocode,rider +# Edit at https://www.toptal.com/developers/gitignore?templates=dotnetcore,visualstudio,visualstudiocode,rider + +### DotnetCore ### +# .NET Core build folders +bin/ +obj/ + +# Common node modules locations +/node_modules +/wwwroot/node_modules + +### Rider ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*[.json, .xml, .info] + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# End of https://www.toptal.com/developers/gitignore/api/dotnetcore,visualstudio,visualstudiocode,rider +.DS_Store diff --git a/libraries/AWS.Lambda.Powertools.sln b/libraries/AWS.Lambda.Powertools.sln new file mode 100644 index 000000000..9c5da4355 --- /dev/null +++ b/libraries/AWS.Lambda.Powertools.sln @@ -0,0 +1,147 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.6.30114.105 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{73C9B1E5-3893-47E8-B373-17E5F5D7E6F5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AWS.Lambda.Powertools.Common", "src\AWS.Lambda.Powertools.Common\AWS.Lambda.Powertools.Common.csproj", "{ACED222F-BDEB-48B6-BA6E-A28659080766}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AWS.Lambda.Powertools.Logging", "src\AWS.Lambda.Powertools.Logging\AWS.Lambda.Powertools.Logging.csproj", "{7A6A2996-1F41-4C94-A0A2-3AE963247243}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AWS.Lambda.Powertools.Metrics", "src\AWS.Lambda.Powertools.Metrics\AWS.Lambda.Powertools.Metrics.csproj", "{3BA6251D-DE4E-4547-AAA9-25F4BA04C636}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AWS.Lambda.Powertools.Tracing", "src\AWS.Lambda.Powertools.Tracing\AWS.Lambda.Powertools.Tracing.csproj", "{1A3AC28C-3AEE-40FE-B229-9E38BB609547}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{1CFF5568-8486-475F-81F6-06105C437528}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AWS.Lambda.Powertools.Logging.Tests", "tests\AWS.Lambda.Powertools.Logging.Tests\AWS.Lambda.Powertools.Logging.Tests.csproj", "{B68A0D0A-4785-48CB-864F-29E3A8ACA526}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AWS.Lambda.Powertools.Metrics.Tests", "tests\AWS.Lambda.Powertools.Metrics.Tests\AWS.Lambda.Powertools.Metrics.Tests.csproj", "{A422C742-2CF9-409D-BDAE-15825AB62113}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AWS.Lambda.Powertools.Tracing.Tests", "tests\AWS.Lambda.Powertools.Tracing.Tests\AWS.Lambda.Powertools.Tracing.Tests.csproj", "{A040AED5-BBB8-4BFA-B2A5-BBD82817B8A5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AWS.Lambda.Powertools.Common.Tests", "tests\AWS.Lambda.Powertools.Common.Tests\AWS.Lambda.Powertools.Common.Tests.csproj", "{4EC48E6A-45B5-4E25-ABBD-C23FE2BD6E1E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {ACED222F-BDEB-48B6-BA6E-A28659080766}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ACED222F-BDEB-48B6-BA6E-A28659080766}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ACED222F-BDEB-48B6-BA6E-A28659080766}.Debug|x64.ActiveCfg = Debug|Any CPU + {ACED222F-BDEB-48B6-BA6E-A28659080766}.Debug|x64.Build.0 = Debug|Any CPU + {ACED222F-BDEB-48B6-BA6E-A28659080766}.Debug|x86.ActiveCfg = Debug|Any CPU + {ACED222F-BDEB-48B6-BA6E-A28659080766}.Debug|x86.Build.0 = Debug|Any CPU + {ACED222F-BDEB-48B6-BA6E-A28659080766}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ACED222F-BDEB-48B6-BA6E-A28659080766}.Release|Any CPU.Build.0 = Release|Any CPU + {ACED222F-BDEB-48B6-BA6E-A28659080766}.Release|x64.ActiveCfg = Release|Any CPU + {ACED222F-BDEB-48B6-BA6E-A28659080766}.Release|x64.Build.0 = Release|Any CPU + {ACED222F-BDEB-48B6-BA6E-A28659080766}.Release|x86.ActiveCfg = Release|Any CPU + {ACED222F-BDEB-48B6-BA6E-A28659080766}.Release|x86.Build.0 = Release|Any CPU + {7A6A2996-1F41-4C94-A0A2-3AE963247243}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7A6A2996-1F41-4C94-A0A2-3AE963247243}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7A6A2996-1F41-4C94-A0A2-3AE963247243}.Debug|x64.ActiveCfg = Debug|Any CPU + {7A6A2996-1F41-4C94-A0A2-3AE963247243}.Debug|x64.Build.0 = Debug|Any CPU + {7A6A2996-1F41-4C94-A0A2-3AE963247243}.Debug|x86.ActiveCfg = Debug|Any CPU + {7A6A2996-1F41-4C94-A0A2-3AE963247243}.Debug|x86.Build.0 = Debug|Any CPU + {7A6A2996-1F41-4C94-A0A2-3AE963247243}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7A6A2996-1F41-4C94-A0A2-3AE963247243}.Release|Any CPU.Build.0 = Release|Any CPU + {7A6A2996-1F41-4C94-A0A2-3AE963247243}.Release|x64.ActiveCfg = Release|Any CPU + {7A6A2996-1F41-4C94-A0A2-3AE963247243}.Release|x64.Build.0 = Release|Any CPU + {7A6A2996-1F41-4C94-A0A2-3AE963247243}.Release|x86.ActiveCfg = Release|Any CPU + {7A6A2996-1F41-4C94-A0A2-3AE963247243}.Release|x86.Build.0 = Release|Any CPU + {3BA6251D-DE4E-4547-AAA9-25F4BA04C636}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3BA6251D-DE4E-4547-AAA9-25F4BA04C636}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3BA6251D-DE4E-4547-AAA9-25F4BA04C636}.Debug|x64.ActiveCfg = Debug|Any CPU + {3BA6251D-DE4E-4547-AAA9-25F4BA04C636}.Debug|x64.Build.0 = Debug|Any CPU + {3BA6251D-DE4E-4547-AAA9-25F4BA04C636}.Debug|x86.ActiveCfg = Debug|Any CPU + {3BA6251D-DE4E-4547-AAA9-25F4BA04C636}.Debug|x86.Build.0 = Debug|Any CPU + {3BA6251D-DE4E-4547-AAA9-25F4BA04C636}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3BA6251D-DE4E-4547-AAA9-25F4BA04C636}.Release|Any CPU.Build.0 = Release|Any CPU + {3BA6251D-DE4E-4547-AAA9-25F4BA04C636}.Release|x64.ActiveCfg = Release|Any CPU + {3BA6251D-DE4E-4547-AAA9-25F4BA04C636}.Release|x64.Build.0 = Release|Any CPU + {3BA6251D-DE4E-4547-AAA9-25F4BA04C636}.Release|x86.ActiveCfg = Release|Any CPU + {3BA6251D-DE4E-4547-AAA9-25F4BA04C636}.Release|x86.Build.0 = Release|Any CPU + {1A3AC28C-3AEE-40FE-B229-9E38BB609547}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1A3AC28C-3AEE-40FE-B229-9E38BB609547}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1A3AC28C-3AEE-40FE-B229-9E38BB609547}.Debug|x64.ActiveCfg = Debug|Any CPU + {1A3AC28C-3AEE-40FE-B229-9E38BB609547}.Debug|x64.Build.0 = Debug|Any CPU + {1A3AC28C-3AEE-40FE-B229-9E38BB609547}.Debug|x86.ActiveCfg = Debug|Any CPU + {1A3AC28C-3AEE-40FE-B229-9E38BB609547}.Debug|x86.Build.0 = Debug|Any CPU + {1A3AC28C-3AEE-40FE-B229-9E38BB609547}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1A3AC28C-3AEE-40FE-B229-9E38BB609547}.Release|Any CPU.Build.0 = Release|Any CPU + {1A3AC28C-3AEE-40FE-B229-9E38BB609547}.Release|x64.ActiveCfg = Release|Any CPU + {1A3AC28C-3AEE-40FE-B229-9E38BB609547}.Release|x64.Build.0 = Release|Any CPU + {1A3AC28C-3AEE-40FE-B229-9E38BB609547}.Release|x86.ActiveCfg = Release|Any CPU + {1A3AC28C-3AEE-40FE-B229-9E38BB609547}.Release|x86.Build.0 = Release|Any CPU + {B68A0D0A-4785-48CB-864F-29E3A8ACA526}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B68A0D0A-4785-48CB-864F-29E3A8ACA526}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B68A0D0A-4785-48CB-864F-29E3A8ACA526}.Debug|x64.ActiveCfg = Debug|Any CPU + {B68A0D0A-4785-48CB-864F-29E3A8ACA526}.Debug|x64.Build.0 = Debug|Any CPU + {B68A0D0A-4785-48CB-864F-29E3A8ACA526}.Debug|x86.ActiveCfg = Debug|Any CPU + {B68A0D0A-4785-48CB-864F-29E3A8ACA526}.Debug|x86.Build.0 = Debug|Any CPU + {B68A0D0A-4785-48CB-864F-29E3A8ACA526}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B68A0D0A-4785-48CB-864F-29E3A8ACA526}.Release|Any CPU.Build.0 = Release|Any CPU + {B68A0D0A-4785-48CB-864F-29E3A8ACA526}.Release|x64.ActiveCfg = Release|Any CPU + {B68A0D0A-4785-48CB-864F-29E3A8ACA526}.Release|x64.Build.0 = Release|Any CPU + {B68A0D0A-4785-48CB-864F-29E3A8ACA526}.Release|x86.ActiveCfg = Release|Any CPU + {B68A0D0A-4785-48CB-864F-29E3A8ACA526}.Release|x86.Build.0 = Release|Any CPU + {A422C742-2CF9-409D-BDAE-15825AB62113}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A422C742-2CF9-409D-BDAE-15825AB62113}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A422C742-2CF9-409D-BDAE-15825AB62113}.Debug|x64.ActiveCfg = Debug|Any CPU + {A422C742-2CF9-409D-BDAE-15825AB62113}.Debug|x64.Build.0 = Debug|Any CPU + {A422C742-2CF9-409D-BDAE-15825AB62113}.Debug|x86.ActiveCfg = Debug|Any CPU + {A422C742-2CF9-409D-BDAE-15825AB62113}.Debug|x86.Build.0 = Debug|Any CPU + {A422C742-2CF9-409D-BDAE-15825AB62113}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A422C742-2CF9-409D-BDAE-15825AB62113}.Release|Any CPU.Build.0 = Release|Any CPU + {A422C742-2CF9-409D-BDAE-15825AB62113}.Release|x64.ActiveCfg = Release|Any CPU + {A422C742-2CF9-409D-BDAE-15825AB62113}.Release|x64.Build.0 = Release|Any CPU + {A422C742-2CF9-409D-BDAE-15825AB62113}.Release|x86.ActiveCfg = Release|Any CPU + {A422C742-2CF9-409D-BDAE-15825AB62113}.Release|x86.Build.0 = Release|Any CPU + {A040AED5-BBB8-4BFA-B2A5-BBD82817B8A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A040AED5-BBB8-4BFA-B2A5-BBD82817B8A5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A040AED5-BBB8-4BFA-B2A5-BBD82817B8A5}.Debug|x64.ActiveCfg = Debug|Any CPU + {A040AED5-BBB8-4BFA-B2A5-BBD82817B8A5}.Debug|x64.Build.0 = Debug|Any CPU + {A040AED5-BBB8-4BFA-B2A5-BBD82817B8A5}.Debug|x86.ActiveCfg = Debug|Any CPU + {A040AED5-BBB8-4BFA-B2A5-BBD82817B8A5}.Debug|x86.Build.0 = Debug|Any CPU + {A040AED5-BBB8-4BFA-B2A5-BBD82817B8A5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A040AED5-BBB8-4BFA-B2A5-BBD82817B8A5}.Release|Any CPU.Build.0 = Release|Any CPU + {A040AED5-BBB8-4BFA-B2A5-BBD82817B8A5}.Release|x64.ActiveCfg = Release|Any CPU + {A040AED5-BBB8-4BFA-B2A5-BBD82817B8A5}.Release|x64.Build.0 = Release|Any CPU + {A040AED5-BBB8-4BFA-B2A5-BBD82817B8A5}.Release|x86.ActiveCfg = Release|Any CPU + {A040AED5-BBB8-4BFA-B2A5-BBD82817B8A5}.Release|x86.Build.0 = Release|Any CPU + {4EC48E6A-45B5-4E25-ABBD-C23FE2BD6E1E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4EC48E6A-45B5-4E25-ABBD-C23FE2BD6E1E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4EC48E6A-45B5-4E25-ABBD-C23FE2BD6E1E}.Debug|x64.ActiveCfg = Debug|Any CPU + {4EC48E6A-45B5-4E25-ABBD-C23FE2BD6E1E}.Debug|x64.Build.0 = Debug|Any CPU + {4EC48E6A-45B5-4E25-ABBD-C23FE2BD6E1E}.Debug|x86.ActiveCfg = Debug|Any CPU + {4EC48E6A-45B5-4E25-ABBD-C23FE2BD6E1E}.Debug|x86.Build.0 = Debug|Any CPU + {4EC48E6A-45B5-4E25-ABBD-C23FE2BD6E1E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4EC48E6A-45B5-4E25-ABBD-C23FE2BD6E1E}.Release|Any CPU.Build.0 = Release|Any CPU + {4EC48E6A-45B5-4E25-ABBD-C23FE2BD6E1E}.Release|x64.ActiveCfg = Release|Any CPU + {4EC48E6A-45B5-4E25-ABBD-C23FE2BD6E1E}.Release|x64.Build.0 = Release|Any CPU + {4EC48E6A-45B5-4E25-ABBD-C23FE2BD6E1E}.Release|x86.ActiveCfg = Release|Any CPU + {4EC48E6A-45B5-4E25-ABBD-C23FE2BD6E1E}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + + GlobalSection(NestedProjects) = preSolution + {ACED222F-BDEB-48B6-BA6E-A28659080766} = {73C9B1E5-3893-47E8-B373-17E5F5D7E6F5} + {7A6A2996-1F41-4C94-A0A2-3AE963247243} = {73C9B1E5-3893-47E8-B373-17E5F5D7E6F5} + {3BA6251D-DE4E-4547-AAA9-25F4BA04C636} = {73C9B1E5-3893-47E8-B373-17E5F5D7E6F5} + {1A3AC28C-3AEE-40FE-B229-9E38BB609547} = {73C9B1E5-3893-47E8-B373-17E5F5D7E6F5} + {B68A0D0A-4785-48CB-864F-29E3A8ACA526} = {1CFF5568-8486-475F-81F6-06105C437528} + {A422C742-2CF9-409D-BDAE-15825AB62113} = {1CFF5568-8486-475F-81F6-06105C437528} + {4EC48E6A-45B5-4E25-ABBD-C23FE2BD6E1E} = {1CFF5568-8486-475F-81F6-06105C437528} + {A040AED5-BBB8-4BFA-B2A5-BBD82817B8A5} = {1CFF5568-8486-475F-81F6-06105C437528} + EndGlobalSection +EndGlobal diff --git a/libraries/AWSLogo128x128.png b/libraries/AWSLogo128x128.png new file mode 100644 index 000000000..545664a95 Binary files /dev/null and b/libraries/AWSLogo128x128.png differ diff --git a/libraries/src/AWS.Lambda.Powertools.Common/AWS.Lambda.Powertools.Common.csproj b/libraries/src/AWS.Lambda.Powertools.Common/AWS.Lambda.Powertools.Common.csproj new file mode 100644 index 000000000..d2b9c8570 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Common/AWS.Lambda.Powertools.Common.csproj @@ -0,0 +1,33 @@ + + + + net6.0 + AWS.Lambda.Powertools.Common + 0.0.1 + Amazon Web Services + Amazon.com, Inc + default + AWS Lambda Powertools for .NET + Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + https://github.com/awslabs/aws-lambda-powertools-dotnet + Apache-2.0 + AWS;Amazon;Lambda;Powertools + AWSLogo128x128.png + true + AWS.Lambda.Powertools.Common + AWS.Lambda.Powertools.Common + + + + true + + + + + + + + + + + \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Common/AWS.Lambda.Powertools.Common.csproj.DotSettings b/libraries/src/AWS.Lambda.Powertools.Common/AWS.Lambda.Powertools.Common.csproj.DotSettings new file mode 100644 index 000000000..65c20a8ce --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Common/AWS.Lambda.Powertools.Common.csproj.DotSettings @@ -0,0 +1,5 @@ + + True + True + True + True \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Common/Aspects/AspectEventArgs.cs b/libraries/src/AWS.Lambda.Powertools.Common/Aspects/AspectEventArgs.cs new file mode 100644 index 000000000..32b2e6126 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Common/Aspects/AspectEventArgs.cs @@ -0,0 +1,70 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Reflection; + +namespace AWS.Lambda.Powertools.Common; + +/// +/// Class AspectEventArgs. +/// Implements the +/// +/// +public class AspectEventArgs : EventArgs +{ + /// + /// Gets the instance. + /// + /// The instance. + public object Instance { get; internal set; } + + /// + /// Gets the type. + /// + /// The type. + public Type Type { get; internal set; } + + /// + /// Gets the method. + /// + /// The method. + public MethodBase Method { get; internal set; } + + /// + /// Gets the name. + /// + /// The name. + public string Name { get; internal set; } + + /// + /// Gets the arguments. + /// + /// The arguments. + public IReadOnlyList Args { get; internal set; } + + /// + /// Gets the type of the return. + /// + /// The type of the return. + public Type ReturnType { get; internal set; } + + /// + /// Gets the triggers. + /// + /// The triggers. + public Attribute[] Triggers { get; internal set; } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Common/Aspects/IMethodAspectHandler.cs b/libraries/src/AWS.Lambda.Powertools.Common/Aspects/IMethodAspectHandler.cs new file mode 100644 index 000000000..2554db78a --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Common/Aspects/IMethodAspectHandler.cs @@ -0,0 +1,52 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; + +namespace AWS.Lambda.Powertools.Common; + +/// +/// Interface IMethodAspectHandler +/// +public interface IMethodAspectHandler +{ + /// + /// Handles the event. + /// + /// The instance containing the event data. + void OnEntry(AspectEventArgs eventArgs); + + /// + /// Called when [success]. + /// + /// The instance containing the event data. + /// The result. + void OnSuccess(AspectEventArgs eventArgs, object result); + + /// + /// Called when [exception]. + /// + /// + /// The instance containing the event data. + /// The exception. + /// T. + T OnException(AspectEventArgs eventArgs, Exception exception); + + /// + /// Handles the event. + /// + /// The instance containing the event data. + void OnExit(AspectEventArgs eventArgs); +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Common/Aspects/MethodAspectAttribute.cs b/libraries/src/AWS.Lambda.Powertools.Common/Aspects/MethodAspectAttribute.cs new file mode 100644 index 000000000..c66d5087a --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Common/Aspects/MethodAspectAttribute.cs @@ -0,0 +1,102 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Threading.Tasks; +using AspectInjector.Broker; + +namespace AWS.Lambda.Powertools.Common; + +/// +/// Class MethodAspectAttribute. +/// Implements the +/// +/// +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] +[Injection(typeof(UniversalWrapperAspect), Inherited = true)] +public abstract class MethodAspectAttribute : UniversalWrapperAttribute +{ + /// + /// The aspect handler + /// + private IMethodAspectHandler _aspectHandler; + + /// + /// Gets the aspect handler. + /// + /// The aspect handler. + private IMethodAspectHandler AspectHandler => _aspectHandler ??= CreateHandler(); + + /// + /// Creates the handler. + /// + /// IMethodAspectHandler. + protected abstract IMethodAspectHandler CreateHandler(); + + /// + /// Wraps as a synchronous operation. + /// + /// + /// The target. + /// The arguments. + /// The instance containing the event data. + /// T. + protected internal sealed override T WrapSync(Func target, object[] args, AspectEventArgs eventArgs) + { + AspectHandler.OnEntry(eventArgs); + try + { + var result = base.WrapSync(target, args, eventArgs); + AspectHandler.OnSuccess(eventArgs, result); + return result; + } + catch (Exception exception) + { + return AspectHandler.OnException(eventArgs, exception); + } + finally + { + AspectHandler.OnExit(eventArgs); + } + } + + /// + /// Wrap as an asynchronous operation. + /// + /// + /// The target. + /// The arguments. + /// The instance containing the event data. + /// A Task<T> representing the asynchronous operation. + protected internal sealed override async Task WrapAsync(Func> target, object[] args, + AspectEventArgs eventArgs) + { + AspectHandler.OnEntry(eventArgs); + try + { + var result = await base.WrapAsync(target, args, eventArgs); + AspectHandler.OnSuccess(eventArgs, result); + return result; + } + catch (Exception exception) + { + return AspectHandler.OnException(eventArgs, exception); + } + finally + { + AspectHandler.OnExit(eventArgs); + } + } +} diff --git a/libraries/src/AWS.Lambda.Powertools.Common/Aspects/UniversalWrapperAspect.cs b/libraries/src/AWS.Lambda.Powertools.Common/Aspects/UniversalWrapperAspect.cs new file mode 100644 index 000000000..fedf45031 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Common/Aspects/UniversalWrapperAspect.cs @@ -0,0 +1,167 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Threading.Tasks; +using AspectInjector.Broker; + +namespace AWS.Lambda.Powertools.Common; + +/// +/// Class UniversalWrapperAspect. +/// +[Aspect(Scope.Global)] +public class UniversalWrapperAspect +{ + /// + /// The delegate cache + /// + private static readonly Dictionary _delegateCache = new(); + + /// + /// The asynchronous generic handler + /// + private static readonly MethodInfo _asyncGenericHandler = + typeof(UniversalWrapperAttribute).GetMethod(nameof(UniversalWrapperAttribute.WrapAsync), + BindingFlags.NonPublic | BindingFlags.Instance); + + /// + /// The synchronize generic handler + /// + private static readonly MethodInfo _syncGenericHandler = + typeof(UniversalWrapperAttribute).GetMethod(nameof(UniversalWrapperAttribute.WrapSync), + BindingFlags.NonPublic | BindingFlags.Instance); + + /// + /// Handles the specified instance. + /// + /// The instance. + /// The type. + /// The method. + /// The target. + /// The name. + /// The arguments. + /// Type of the return. + /// The triggers. + /// System.Object. + [Advice(Kind.Around, Targets = Target.Method)] + public object Handle( + [Argument(Source.Instance)] object instance, + [Argument(Source.Type)] Type type, + [Argument(Source.Metadata)] MethodBase method, + [Argument(Source.Target)] Func target, + [Argument(Source.Name)] string name, + [Argument(Source.Arguments)] object[] args, + [Argument(Source.ReturnType)] Type returnType, + [Argument(Source.Triggers)] Attribute[] triggers) + { + var eventArgs = new AspectEventArgs + { + Instance = instance, + Type = type, + Method = method, + Name = name, + Args = args, + ReturnType = returnType, + Triggers = triggers + }; + + var wrappers = triggers.OfType().ToArray(); + var handler = GetMethodHandler(method, returnType, wrappers); + return handler(target, args, eventArgs); + } + + /// + /// Creates the method handler. + /// + /// Type of the return. + /// The wrappers. + /// Handler. + private static Handler CreateMethodHandler(Type returnType, IEnumerable wrappers) + { + var targetParam = Expression.Parameter(typeof(Func), "orig"); + var eventArgsParam = Expression.Parameter(typeof(AspectEventArgs), "event"); + + MethodInfo wrapperMethod; + + if (typeof(Task).IsAssignableFrom(returnType)) + { + var taskType = returnType.IsConstructedGenericType + ? returnType.GenericTypeArguments[0] + : Type.GetType("System.Threading.Tasks.VoidTaskResult"); + returnType = typeof(Task<>).MakeGenericType(taskType); + wrapperMethod = _asyncGenericHandler.MakeGenericMethod(taskType); + } + else + { + if (returnType == typeof(void)) + returnType = typeof(object); + wrapperMethod = _syncGenericHandler.MakeGenericMethod(returnType); + } + + var converArgs = Expression.Parameter(typeof(object[]), "args"); + var next = Expression.Lambda(Expression.Convert(Expression.Invoke(targetParam, converArgs), returnType), + converArgs); + + foreach (var wrapper in wrappers) + { + var argsParam = Expression.Parameter(typeof(object[]), "args"); + next = Expression.Lambda( + Expression.Call(Expression.Constant(wrapper), wrapperMethod, next, argsParam, eventArgsParam), + argsParam); + } + + var orig_args = Expression.Parameter(typeof(object[]), "orig_args"); + var handler = Expression.Lambda(Expression.Convert(Expression.Invoke(next, orig_args), typeof(object)), + targetParam, orig_args, eventArgsParam); + + var handlerCompiled = handler.Compile(); + + return handlerCompiled; + } + + /// + /// Gets the method handler. + /// + /// The method. + /// Type of the return. + /// The wrappers. + /// Handler. + private static Handler GetMethodHandler(MethodBase method, Type returnType, + IEnumerable wrappers) + { + if (!_delegateCache.TryGetValue(method, out var handler)) + lock (method) + { + if (!_delegateCache.TryGetValue(method, out handler)) + _delegateCache[method] = handler = CreateMethodHandler(returnType, wrappers); + } + + return handler; + } + + /// + /// Delegate Handler + /// + /// The next. + /// The arguments. + /// The instance containing the event data. + /// System.Object. + private delegate object Handler(Func next, object[] args, AspectEventArgs eventArgs); +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Common/Aspects/UniversalWrapperAttribute.cs b/libraries/src/AWS.Lambda.Powertools.Common/Aspects/UniversalWrapperAttribute.cs new file mode 100644 index 000000000..97d857ce2 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Common/Aspects/UniversalWrapperAttribute.cs @@ -0,0 +1,54 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Threading.Tasks; + +namespace AWS.Lambda.Powertools.Common; + +/// +/// Class UniversalWrapperAttribute. +/// Implements the +/// +/// +public abstract class UniversalWrapperAttribute : Attribute +{ + /// + /// Wraps as a synchronous operation. + /// + /// + /// The target. + /// The arguments. + /// The instance containing the event data. + /// T. + protected internal virtual T WrapSync(Func target, object[] args, AspectEventArgs eventArgs) + { + return target(args); + } + + /// + /// Wraps as an asynchronous operation. + /// + /// + /// The target. + /// The arguments. + /// The instance containing the event data. + /// Task<T>. + protected internal virtual Task WrapAsync(Func> target, object[] args, + AspectEventArgs eventArgs) + { + return target(args); + } +} diff --git a/libraries/src/AWS.Lambda.Powertools.Common/Core/Constants.cs b/libraries/src/AWS.Lambda.Powertools.Common/Core/Constants.cs new file mode 100644 index 000000000..d84baaae3 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Common/Core/Constants.cs @@ -0,0 +1,83 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace AWS.Lambda.Powertools.Common; + +/// +/// Class Constants +/// +internal static class Constants +{ + /// + /// Constant for POWERTOOLS_SERVICE_NAME environment variable + /// + internal const string ServiceNameEnv = "POWERTOOLS_SERVICE_NAME"; + + /// + /// Constant for AWS_SAM_LOCAL environment variable + /// + internal const string SamLocalEnv = "AWS_SAM_LOCAL"; + + /// + /// Constant for POWERTOOLS_TRACER_CAPTURE_RESPONSE environment variable + /// + internal const string TracerCaptureResponseEnv = "POWERTOOLS_TRACER_CAPTURE_RESPONSE"; + + /// + /// Constant for POWERTOOLS_TRACER_CAPTURE_ERROR environment variable + /// + internal const string TracerCaptureErrorEnv = "POWERTOOLS_TRACER_CAPTURE_ERROR"; + + /// + /// Constant for POWERTOOLS_TRACE_DISABLED environment variable + /// + internal const string TracingDisabledEnv = "POWERTOOLS_TRACE_DISABLED"; + + /// + /// Constant for POWERTOOLS_METRICS_NAMESPACE environment variable + /// + internal const string MetricsNamespaceEnv = "POWERTOOLS_METRICS_NAMESPACE"; + + /// + /// Constant for LOG_LEVEL environment variable + /// + internal const string LogLevelNameEnv = "LOG_LEVEL"; + + /// + /// Constant for POWERTOOLS_LOGGER_SAMPLE_RATE environment variable + /// + internal const string LoggerSampleRateNameEnv = "POWERTOOLS_LOGGER_SAMPLE_RATE"; + + /// + /// Constant for POWERTOOLS_LOGGER_LOG_EVENT environment variable + /// + internal const string LoggerLogEventNameEnv = "POWERTOOLS_LOGGER_LOG_EVENT"; + + /// + /// Constant for POWERTOOLS_LOGGER_CASE environment variable + /// Defaults to snake case + /// + internal const string LoggerOutputCaseEnv = "POWERTOOLS_LOGGER_CASE"; + + /// + /// Constant for AWS X-Ray trace identifier environment variable + /// + internal const string XrayTraceIdEnv = "_X_AMZN_TRACE_ID"; + + /// + /// Constant for LAMBDA_TASK_ROOT environment variable + /// + internal const string LambdaTaskRoot = "LAMBDA_TASK_ROOT"; +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Common/Core/IPowertoolsConfigurations.cs b/libraries/src/AWS.Lambda.Powertools.Common/Core/IPowertoolsConfigurations.cs new file mode 100644 index 000000000..d9dc90cb1 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Common/Core/IPowertoolsConfigurations.cs @@ -0,0 +1,123 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace AWS.Lambda.Powertools.Common; + +/// +/// Interface IPowertoolsConfigurations +/// +public interface IPowertoolsConfigurations +{ + /// + /// Gets the service. + /// + /// The service. + string Service { get; } + + /// + /// Gets a value indicating whether this instance is service defined. + /// + /// true if this instance is service defined; otherwise, false. + bool IsServiceDefined { get; } + + /// + /// Gets a value indicating whether [tracer capture response]. + /// + /// true if [tracer capture response]; otherwise, false. + bool TracerCaptureResponse { get; } + + /// + /// Gets a value indicating whether [tracer capture error]. + /// + /// true if [tracer capture error]; otherwise, false. + bool TracerCaptureError { get; } + + /// + /// Gets a value indicating whether this instance is sam local. + /// + /// true if this instance is sam local; otherwise, false. + bool IsSamLocal { get; } + + /// + /// Gets the metrics namespace. + /// + /// The metrics namespace. + string MetricsNamespace { get; } + + /// + /// Gets the log level. + /// + /// The log level. + string LogLevel { get; } + + /// + /// Gets the logger sample rate. + /// + /// The logger sample rate. + double? LoggerSampleRate { get; } + + /// + /// Gets a value indicating whether [logger log event]. + /// + /// true if [logger log event]; otherwise, false. + bool LoggerLogEvent { get; } + + /// + /// Gets the logger output casing. + /// + /// The logger output casing. Defaults to snake case. + string LoggerOutputCase { get; } + + /// + /// Gets the X-Ray trace identifier. + /// + /// The X-Ray trace identifier. + string XRayTraceId { get; } + + /// + /// Gets a value indicating whether this instance is Lambda. + /// + /// true if this instance is Lambda; otherwise, false. + bool IsLambdaEnvironment { get; } + + /// + /// Gets a value indicating whether [tracing is disabled]. + /// + /// true if [tracing is disabled]; otherwise, false. + bool TracingDisabled { get; } + + /// + /// Gets the environment variable. + /// + /// The variable. + /// System.String. + string GetEnvironmentVariable(string variable); + + /// + /// Gets the environment variable or default. + /// + /// The variable. + /// The default value. + /// System.String. + string GetEnvironmentVariableOrDefault(string variable, string defaultValue); + + /// + /// Gets the environment variable or default. + /// + /// The variable. + /// if set to true [default value]. + /// true if XXXX, false otherwise. + bool GetEnvironmentVariableOrDefault(string variable, bool defaultValue); +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Common/Core/ISystemWrapper.cs b/libraries/src/AWS.Lambda.Powertools.Common/Core/ISystemWrapper.cs new file mode 100644 index 000000000..92ec9e3e2 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Common/Core/ISystemWrapper.cs @@ -0,0 +1,47 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace AWS.Lambda.Powertools.Common; + +/// +/// Interface ISystemWrapper +/// +public interface ISystemWrapper +{ + /// + /// Gets the environment variable. + /// + /// The variable. + /// System.String. + string GetEnvironmentVariable(string variable); + + /// + /// Logs the specified value. + /// + /// The value. + void Log(string value); + + /// + /// Logs the line. + /// + /// The value. + void LogLine(string value); + + /// + /// Gets random number + /// + /// System.Double. + double GetRandom(); +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Common/Core/PowertoolsConfigurations.cs b/libraries/src/AWS.Lambda.Powertools.Common/Core/PowertoolsConfigurations.cs new file mode 100644 index 000000000..f73631d68 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Common/Core/PowertoolsConfigurations.cs @@ -0,0 +1,187 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace AWS.Lambda.Powertools.Common; + +/// +/// Class PowertoolsConfigurations. +/// Implements the +/// +/// +public class PowertoolsConfigurations : IPowertoolsConfigurations +{ + /// + /// The maximum dimensions + /// + public const int MaxDimensions = 9; + + /// + /// The maximum metrics + /// + public const int MaxMetrics = 100; + + /// + /// The instance + /// + private static IPowertoolsConfigurations _instance; + + /// + /// The system wrapper + /// + private readonly ISystemWrapper _systemWrapper; + + /// + /// Initializes a new instance of the class. + /// + /// The system wrapper. + internal PowertoolsConfigurations(ISystemWrapper systemWrapper) + { + _systemWrapper = systemWrapper; + } + + /// + /// Gets the instance. + /// + /// The instance. + public static IPowertoolsConfigurations Instance => + _instance ??= new PowertoolsConfigurations(SystemWrapper.Instance); + + /// + /// Gets the environment variable. + /// + /// The variable. + /// System.String. + public string GetEnvironmentVariable(string variable) + { + return _systemWrapper.GetEnvironmentVariable(variable); + } + + /// + /// Gets the environment variable or default. + /// + /// The variable. + /// The default value. + /// System.String. + public string GetEnvironmentVariableOrDefault(string variable, string defaultValue) + { + var result = _systemWrapper.GetEnvironmentVariable(variable); + return string.IsNullOrWhiteSpace(result) ? defaultValue : result; + } + + /// + /// Gets the environment variable or default. + /// + /// The variable. + /// if set to true [default value]. + /// true if XXXX, false otherwise. + public bool GetEnvironmentVariableOrDefault(string variable, bool defaultValue) + { + return bool.TryParse(_systemWrapper.GetEnvironmentVariable(variable), out var result) + ? result + : defaultValue; + } + + /// + /// Gets the service. + /// + /// The service. + public string Service => + GetEnvironmentVariableOrDefault(Constants.ServiceNameEnv, "service_undefined"); + + /// + /// Gets a value indicating whether this instance is service defined. + /// + /// true if this instance is service defined; otherwise, false. + public bool IsServiceDefined => + !string.IsNullOrWhiteSpace(GetEnvironmentVariable(Constants.ServiceNameEnv)); + + /// + /// Gets a value indicating whether [tracer capture response]. + /// + /// true if [tracer capture response]; otherwise, false. + public bool TracerCaptureResponse => + GetEnvironmentVariableOrDefault(Constants.TracerCaptureResponseEnv, true); + + /// + /// Gets a value indicating whether [tracer capture error]. + /// + /// true if [tracer capture error]; otherwise, false. + public bool TracerCaptureError => + GetEnvironmentVariableOrDefault(Constants.TracerCaptureErrorEnv, true); + + /// + /// Gets a value indicating whether this instance is sam local. + /// + /// true if this instance is sam local; otherwise, false. + public bool IsSamLocal => + GetEnvironmentVariableOrDefault(Constants.SamLocalEnv, false); + + /// + /// Gets the metrics namespace. + /// + /// The metrics namespace. + public string MetricsNamespace => + GetEnvironmentVariable(Constants.MetricsNamespaceEnv); + + /// + /// Gets the log level. + /// + /// The log level. + public string LogLevel => + GetEnvironmentVariable(Constants.LogLevelNameEnv); + + /// + /// Gets the logger sample rate. + /// + /// The logger sample rate. + public double? LoggerSampleRate => + double.TryParse(_systemWrapper.GetEnvironmentVariable(Constants.LoggerSampleRateNameEnv), out var result) + ? result + : null; + + /// + /// Gets a value indicating whether [logger log event]. + /// + /// true if [logger log event]; otherwise, false. + public bool LoggerLogEvent => + GetEnvironmentVariableOrDefault(Constants.LoggerLogEventNameEnv, false); + + /// + /// Gets the logger output casing. + /// + /// The logger output casing. Defaults to snake case. + public string LoggerOutputCase => + GetEnvironmentVariableOrDefault(Constants.LoggerOutputCaseEnv, "SnakeCase"); + + /// + /// Gets the X-Ray trace identifier. + /// + /// The X-Ray trace identifier. + public string XRayTraceId => + GetEnvironmentVariable(Constants.XrayTraceIdEnv); + + /// + /// Gets a value indicating whether this instance is Lambda. + /// + /// true if this instance is Lambda; otherwise, false. + public bool IsLambdaEnvironment => GetEnvironmentVariable(Constants.LambdaTaskRoot) is not null; + + /// + /// Gets a value indicating whether [tracing is disabled]. + /// + /// true if [tracing is disabled]; otherwise, false. + public bool TracingDisabled => + GetEnvironmentVariableOrDefault(Constants.TracingDisabledEnv, false); +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Common/Core/PowertoolsLambdaContext.cs b/libraries/src/AWS.Lambda.Powertools.Common/Core/PowertoolsLambdaContext.cs new file mode 100644 index 000000000..b07013a88 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Common/Core/PowertoolsLambdaContext.cs @@ -0,0 +1,131 @@ +using System; +using System.Linq; +using System.Reflection; + +namespace AWS.Lambda.Powertools.Common; + +internal class PowertoolsLambdaContext +{ + /// + /// The AWS request ID associated with the request. + /// This is the same ID returned to the client that called invoke(). + /// This ID is reused for retries on the same request. + /// + internal string AwsRequestId { get; private set; } + + /// Name of the Lambda function that is running. + internal string FunctionName { get; private set; } + + /// + /// The Lambda function version that is executing. + /// If an alias is used to invoke the function, then this will be + /// the version the alias points to. + /// + internal string FunctionVersion { get; private set; } + + /// + /// The ARN used to invoke this function. + /// It can be function ARN or alias ARN. + /// An unqualified ARN executes the $LATEST version and aliases execute + /// the function version they are pointing to. + /// + internal string InvokedFunctionArn { get; private set; } + + /// + /// The CloudWatch log group name associated with the invoked function. + /// It can be null if the IAM user provided does not have permission for + /// CloudWatch actions. + /// + internal string LogGroupName { get; private set; } + + /// + /// The CloudWatch log stream name for this function execution. + /// It can be null if the IAM user provided does not have permission + /// for CloudWatch actions. + /// + internal string LogStreamName { get; private set; } + + /// + /// Memory limit, in MB, you configured for the Lambda function. + /// + internal int MemoryLimitInMB { get; private set; } + + /// + /// The instance + /// + internal static PowertoolsLambdaContext Instance { get; private set; } + + /// + /// Extract the lambda context from Lambda handler arguments. + /// + /// + /// The instance containing the + /// event data. + /// + internal static bool Extract(AspectEventArgs eventArgs) + { + if (Instance is not null) + return false; + + if (eventArgs?.Args is null) + return false; + + foreach (var arg in eventArgs.Args) + { + if (arg is null) + continue; + + var argType = arg.GetType(); + if (!argType.Name.EndsWith("LambdaContext")) + continue; + + Instance = new PowertoolsLambdaContext(); + + foreach (var prop in argType.GetProperties()) + { + if (prop.Name.Equals("AwsRequestId", StringComparison.CurrentCultureIgnoreCase)) + { + Instance.AwsRequestId = prop.GetValue(arg) as string; + } + else if (prop.Name.Equals("FunctionName", StringComparison.CurrentCultureIgnoreCase)) + { + Instance.FunctionName = prop.GetValue(arg) as string; + } + else if (prop.Name.Equals("FunctionVersion", StringComparison.CurrentCultureIgnoreCase)) + { + Instance.FunctionVersion = prop.GetValue(arg) as string; + } + else if (prop.Name.Equals("InvokedFunctionArn", StringComparison.CurrentCultureIgnoreCase)) + { + Instance.InvokedFunctionArn = prop.GetValue(arg) as string; + } + else if (prop.Name.Equals("LogGroupName", StringComparison.CurrentCultureIgnoreCase)) + { + Instance.LogGroupName = prop.GetValue(arg) as string; + } + else if (prop.Name.Equals("LogStreamName", StringComparison.CurrentCultureIgnoreCase)) + { + Instance.LogStreamName = prop.GetValue(arg) as string; + } + else if (prop.Name.Equals("MemoryLimitInMB", StringComparison.CurrentCultureIgnoreCase)) + { + var propVal = prop.GetValue(arg); + if (propVal is null || !int.TryParse(propVal.ToString(), out var intVal)) continue; + Instance.MemoryLimitInMB = intVal; + } + } + + return true; + } + + return false; + } + + /// + /// Clear the extracted lambda context. + /// + internal static void Clear() + { + Instance = null; + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Common/Core/SystemWrapper.cs b/libraries/src/AWS.Lambda.Powertools.Common/Core/SystemWrapper.cs new file mode 100644 index 000000000..f6906a607 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Common/Core/SystemWrapper.cs @@ -0,0 +1,81 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; + +namespace AWS.Lambda.Powertools.Common; + +/// +/// Class SystemWrapper. +/// Implements the +/// +/// +public class SystemWrapper : ISystemWrapper +{ + /// + /// The instance + /// + private static ISystemWrapper _instance; + + /// + /// Prevents a default instance of the class from being created. + /// + private SystemWrapper() + { + } + + /// + /// Gets the instance. + /// + /// The instance. + public static ISystemWrapper Instance => _instance ??= new SystemWrapper(); + + /// + /// Gets the environment variable. + /// + /// The variable. + /// System.String. + public string GetEnvironmentVariable(string variable) + { + return Environment.GetEnvironmentVariable(variable); + } + + /// + /// Logs the specified value. + /// + /// The value. + public void Log(string value) + { + Console.Write(value); + } + + /// + /// Logs the line. + /// + /// The value. + public void LogLine(string value) + { + Console.WriteLine(value); + } + + /// + /// Gets random number + /// + /// System.Double. + public double GetRandom() + { + return new Random().NextDouble(); + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Common/InternalsVisibleTo.cs b/libraries/src/AWS.Lambda.Powertools.Common/InternalsVisibleTo.cs new file mode 100644 index 000000000..f88809b35 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Common/InternalsVisibleTo.cs @@ -0,0 +1,23 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("AWS.Lambda.Powertools.Logging")] +[assembly: InternalsVisibleTo("AWS.Lambda.Powertools.Metrics")] +[assembly: InternalsVisibleTo("AWS.Lambda.Powertools.Common.Tests")] +[assembly: InternalsVisibleTo("AWS.Lambda.Powertools.Tracing.Tests")] +[assembly: InternalsVisibleTo("AWS.Lambda.Powertools.Metrics.Tests")] +[assembly: InternalsVisibleTo("AWS.Lambda.Powertools.Logging.Tests")] \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Common/JsonSerialization/PascalCaseNamingPolicy.cs b/libraries/src/AWS.Lambda.Powertools.Common/JsonSerialization/PascalCaseNamingPolicy.cs new file mode 100644 index 000000000..7a3f7ed99 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Common/JsonSerialization/PascalCaseNamingPolicy.cs @@ -0,0 +1,42 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + + +using System.Text.Json; + +namespace AWS.Lambda.Powertools.Common; + +/// +/// Class PascalCaseNamingPolicy +/// Implements the +/// +public class PascalCaseNamingPolicy : JsonNamingPolicy +{ + /// + /// Instance of PascalCaseNamingPolicy + /// + public static PascalCaseNamingPolicy Instance { get; } = new PascalCaseNamingPolicy(); + + + /// + /// Converts key to pascal case + /// + /// Name of key + /// + public override string ConvertName(string name) + { + return name.ToPascalCase(); + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Common/JsonSerialization/SnakeCaseNamingPolicy.cs b/libraries/src/AWS.Lambda.Powertools.Common/JsonSerialization/SnakeCaseNamingPolicy.cs new file mode 100644 index 000000000..3c612760c --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Common/JsonSerialization/SnakeCaseNamingPolicy.cs @@ -0,0 +1,40 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System.Text.Json; + +namespace AWS.Lambda.Powertools.Common; + +/// +/// Class SnakeCaseNamingPolicy +/// Implements the +/// +public class SnakeCaseNamingPolicy : JsonNamingPolicy +{ + /// + /// Instance of SnakeCaseNamingPolicy + /// + public static SnakeCaseNamingPolicy Instance { get; } = new SnakeCaseNamingPolicy(); + + /// + /// Converts key name to snake case + /// + /// Name of key + /// + public override string ConvertName(string name) + { + return name.ToSnakeCase(); + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Common/Utils/StringUtils.cs b/libraries/src/AWS.Lambda.Powertools.Common/Utils/StringUtils.cs new file mode 100644 index 000000000..94ffc7bb6 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Common/Utils/StringUtils.cs @@ -0,0 +1,44 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System.Linq; + +namespace AWS.Lambda.Powertools.Common; + +/// +/// Class StringUtils +/// +public static class StringUtils +{ + /// + /// Extension method to convert string to snake case + /// + /// string + /// Snake case formatted string + public static string ToSnakeCase(this string str) + { + return string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString())).ToLower(); + } + + /// + /// Extension method to convert string to pascal case + /// + /// string + /// Pascal case formatted string + public static string ToPascalCase(this string str) + { + return string.Concat(char.ToUpper(str[0]), str.Substring(1)); + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Logging/AWS.Lambda.Powertools.Logging.csproj b/libraries/src/AWS.Lambda.Powertools.Logging/AWS.Lambda.Powertools.Logging.csproj new file mode 100644 index 000000000..a6f5c5b35 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Logging/AWS.Lambda.Powertools.Logging.csproj @@ -0,0 +1,42 @@ + + + + net6.0 + default + AWS.Lambda.Powertools.Logging + 0.0.1 + Amazon Web Services + Amazon.com, Inc + AWS Lambda Powertools for .NET + AWS Lambda Powertools for .NET - Logging package. + Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + https://github.com/awslabs/aws-lambda-powertools-dotnet + Apache-2.0 + AWS;Amazon;Lambda;Powertools + README.md + AWSLogo128x128.png + true + AWS.Lambda.Powertools.Logging + AWS.Lambda.Powertools.Logging + + + + true + + + + + + + + + + + + + + + + + + diff --git a/libraries/src/AWS.Lambda.Powertools.Logging/CorrelationIdPaths.cs b/libraries/src/AWS.Lambda.Powertools.Logging/CorrelationIdPaths.cs new file mode 100644 index 000000000..daded5397 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Logging/CorrelationIdPaths.cs @@ -0,0 +1,44 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace AWS.Lambda.Powertools.Logging; + +/// +/// Supported Event types from which Correlation ID can be extracted +/// +public static class CorrelationIdPaths +{ + internal const char Separator = '/'; + + /// + /// To use when function is expecting API Gateway Rest API request event + /// + public const string ApiGatewayRest = "/RequestContext/RequestId"; + + /// + /// To use when function is expecting API Gateway HTTP API request event + /// + public const string ApiGatewayHttp = "/RequestContext/RequestId"; + + /// + /// To use when function is expecting Application Load balancer request event + /// + public const string ApplicationLoadBalancer = "/Headers/x-amzn-trace-id"; + + /// + /// To use when function is expecting EventBridge request event + /// + public const string EventBridge = "/Id"; +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Logging/Internal/LoggerOutputCase.cs b/libraries/src/AWS.Lambda.Powertools.Logging/Internal/LoggerOutputCase.cs new file mode 100644 index 000000000..6c64e2f0d --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Logging/Internal/LoggerOutputCase.cs @@ -0,0 +1,39 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System.Runtime.Serialization; + +namespace AWS.Lambda.Powertools.Logging; + +/// +/// Enum LoggerOutputCase +/// +public enum LoggerOutputCase +{ + /// + /// Camel Case + /// + [EnumMember(Value = "CamelCase")] CamelCase, + + /// + /// Pascal Case + /// + [EnumMember(Value = "PascalCase")] PascalCase, + + /// + /// Snake Case + /// + [EnumMember(Value = "SnakeCase")] SnakeCase, +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Logging/Internal/LoggerProvider.cs b/libraries/src/AWS.Lambda.Powertools.Logging/Internal/LoggerProvider.cs new file mode 100644 index 000000000..15ec1e662 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Logging/Internal/LoggerProvider.cs @@ -0,0 +1,94 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System.Collections.Concurrent; +using AWS.Lambda.Powertools.Common; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace AWS.Lambda.Powertools.Logging.Internal; + +/// +/// Class LoggerProvider. This class cannot be inherited. +/// Implements the +/// +/// +internal sealed class LoggerProvider : ILoggerProvider +{ + /// + /// The loggers + /// + private readonly ConcurrentDictionary _loggers = new(); + + + /// + /// The current configuration + /// + private LoggerConfiguration _currentConfig; + + /// + /// Initializes a new instance of the class. + /// + /// The configuration. + internal LoggerProvider(IOptions config) + { + _currentConfig = config?.Value; + } + + /// + /// Creates a new instance. + /// + /// The category name for messages produced by the logger. + /// The instance of that was created. + public ILogger CreateLogger(string categoryName) + { + return _loggers.GetOrAdd(categoryName, + name => new PowertoolsLogger(name, + PowertoolsConfigurations.Instance, + SystemWrapper.Instance, + GetCurrentConfig)); + } + + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + public void Dispose() + { + _loggers.Clear(); + } + + /// + /// Gets the current configuration. + /// + /// LoggerConfiguration. + private LoggerConfiguration GetCurrentConfig() + { + return _currentConfig; + } + + /// + /// Configures the loggers. + /// + /// The configuration. + internal void Configure(IOptions config) + { + if (_currentConfig is not null || config is null) + return; + + _currentConfig = config.Value; + foreach (var logger in _loggers.Values) + logger.ClearConfig(); + } +} diff --git a/libraries/src/AWS.Lambda.Powertools.Logging/Internal/LoggingAspectHandler.cs b/libraries/src/AWS.Lambda.Powertools.Logging/Internal/LoggingAspectHandler.cs new file mode 100644 index 000000000..2e649e297 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Logging/Internal/LoggingAspectHandler.cs @@ -0,0 +1,364 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.IO; +using System.Linq; +using System.Text.Json; +using AWS.Lambda.Powertools.Common; +using Microsoft.Extensions.Logging; + +namespace AWS.Lambda.Powertools.Logging.Internal; + +/// +/// Class LoggingAspectHandler. +/// Implements the +/// +/// +internal class LoggingAspectHandler : IMethodAspectHandler +{ + /// + /// The is cold start + /// + private static bool _isColdStart = true; + + /// + /// The initialize context + /// + private static bool _initializeContext = true; + + /// + /// Clear state? + /// + private readonly bool _clearState; + + /// + /// The correlation identifier path + /// + private readonly string _correlationIdPath; + + /// + /// The log event + /// + private readonly bool? _logEvent; + + /// + /// The log level + /// + private readonly LogLevel? _logLevel; + + /// + /// The logger output case + /// + private readonly LoggerOutputCase? _loggerOutputCase; + + /// + /// The Powertools configurations + /// + private readonly IPowertoolsConfigurations _powertoolsConfigurations; + + /// + /// The sampling rate + /// + private readonly double? _samplingRate; + + /// + /// Service name + /// + private readonly string _service; + + /// + /// The system wrapper + /// + private readonly ISystemWrapper _systemWrapper; + + /// + /// The is context initialized + /// + private bool _isContextInitialized; + + /// + /// Specify to clear Lambda Context on exit + /// + private bool _clearLambdaContext; + + /// + /// Initializes a new instance of the class. + /// + /// Service name + /// The log level. + /// The logger output case. + /// The sampling rate. + /// if set to true [log event]. + /// The correlation identifier path. + /// if set to true [clear state]. + /// The Powertools configurations. + /// The system wrapper. + internal LoggingAspectHandler + ( + string service, + LogLevel? logLevel, + LoggerOutputCase? loggerOutputCase, + double? samplingRate, + bool? logEvent, + string correlationIdPath, + bool clearState, + IPowertoolsConfigurations powertoolsConfigurations, + ISystemWrapper systemWrapper + ) + { + _service = service; + _logLevel = logLevel; + _loggerOutputCase = loggerOutputCase; + _samplingRate = samplingRate; + _logEvent = logEvent; + _clearState = clearState; + _correlationIdPath = correlationIdPath; + _powertoolsConfigurations = powertoolsConfigurations; + _systemWrapper = systemWrapper; + } + + /// + /// Handles the event. + /// + /// + /// The instance containing the + /// event data. + /// + public void OnEntry(AspectEventArgs eventArgs) + { + var loggerConfig = new LoggerConfiguration + { + Service = _service, + MinimumLevel = _logLevel, + SamplingRate = _samplingRate, + LoggerOutputCase = _loggerOutputCase + }; + + switch (Logger.LoggerProvider) + { + case null: + Logger.LoggerProvider = new LoggerProvider(loggerConfig); + break; + case LoggerProvider: + ((LoggerProvider) Logger.LoggerProvider).Configure(loggerConfig); + break; + } + + if (!_initializeContext) + return; + + Logger.AppendKey(LoggingConstants.KeyColdStart, _isColdStart); + + _isColdStart = false; + _initializeContext = false; + _isContextInitialized = true; + + var eventObject = eventArgs.Args.FirstOrDefault(); + CaptureXrayTraceId(); + CaptureLambdaContext(eventArgs); + CaptureCorrelationId(eventObject); + if (_logEvent ?? _powertoolsConfigurations.LoggerLogEvent) + LogEvent(eventObject); + } + + /// + /// Called when [success]. + /// + /// + /// The instance containing the + /// event data. + /// + /// The result. + public void OnSuccess(AspectEventArgs eventArgs, object result) + { + } + + /// + /// Called when [exception]. + /// + /// + /// + /// The instance containing the + /// event data. + /// + /// The exception. + /// T. + public T OnException(AspectEventArgs eventArgs, Exception exception) + { + throw exception; + } + + /// + /// Handles the event. + /// + /// + /// The instance containing the + /// event data. + /// + public void OnExit(AspectEventArgs eventArgs) + { + if (!_isContextInitialized) + return; + if (_clearLambdaContext) + PowertoolsLambdaContext.Clear(); + if (_clearState) + Logger.RemoveAllKeys(); + _initializeContext = true; + } + + /// + /// Determines whether this instance is debug. + /// + /// true if this instance is debug; otherwise, false. + private bool IsDebug() + { + return LogLevel.Debug >= _powertoolsConfigurations.GetLogLevel(_logLevel); + } + + /// + /// Captures the xray trace identifier. + /// + private void CaptureXrayTraceId() + { + var xRayTraceId = _powertoolsConfigurations.XRayTraceId; + if (string.IsNullOrWhiteSpace(xRayTraceId)) + return; + + xRayTraceId = xRayTraceId + .Split(';', StringSplitOptions.RemoveEmptyEntries) + .First() + .Replace("Root=", ""); + + Logger.AppendKey(LoggingConstants.KeyXRayTraceId, xRayTraceId); + } + + /// + /// Captures the lambda context. + /// + /// + /// The instance containing the + /// event data. + /// + private void CaptureLambdaContext(AspectEventArgs eventArgs) + { + _clearLambdaContext = PowertoolsLambdaContext.Extract(eventArgs); + if (PowertoolsLambdaContext.Instance is null && IsDebug()) + _systemWrapper.LogLine( + "Skipping Lambda Context injection because ILambdaContext context parameter not found."); + } + + /// + /// Captures the correlation identifier. + /// + /// The event argument. + private void CaptureCorrelationId(object eventArg) + { + if (string.IsNullOrWhiteSpace(_correlationIdPath)) + return; + + var correlationIdPaths = _correlationIdPath + .Split(CorrelationIdPaths.Separator, StringSplitOptions.RemoveEmptyEntries); + + if (!correlationIdPaths.Any()) + return; + + if (eventArg is null) + { + if (IsDebug()) + _systemWrapper.LogLine( + "Skipping CorrelationId capture because event parameter not found."); + return; + } + + try + { + var correlationId = string.Empty; + var jsonDoc = JsonDocument.Parse(JsonSerializer.Serialize(eventArg)); + var element = jsonDoc.RootElement; + + for (var i = 0; i < correlationIdPaths.Length; i++) + { + if (!element.TryGetProperty(correlationIdPaths[i], out var childElement)) + break; + + element = childElement; + if (i == correlationIdPaths.Length - 1) + correlationId = element.ToString(); + } + + if (!string.IsNullOrWhiteSpace(correlationId)) + Logger.AppendKey(LoggingConstants.KeyCorrelationId, correlationId); + } + catch (Exception e) + { + if (IsDebug()) + _systemWrapper.LogLine( + $"Skipping CorrelationId capture because of error caused while parsing the event object {e.Message}."); + } + } + + /// + /// Logs the event. + /// + /// The event argument. + private void LogEvent(object eventArg) + { + switch (eventArg) + { + case null: + { + if (IsDebug()) + _systemWrapper.LogLine( + "Skipping Event Log because event parameter not found."); + break; + } + case Stream: + try + { + Logger.LogInformation(eventArg); + } + catch (Exception e) + { + Logger.LogError(e, "Failed to log event from supplied input stream."); + } + + break; + default: + try + { + Logger.LogInformation(eventArg); + } + catch (Exception e) + { + Logger.LogError(e, "Failed to log event from supplied input object."); + } + + break; + } + } + + /// + /// Resets for test. + /// + internal static void ResetForTest() + { + _isColdStart = true; + _initializeContext = true; + PowertoolsLambdaContext.Clear(); + Logger.LoggerProvider = null; + Logger.RemoveAllKeys(); + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Logging/Internal/LoggingConstants.cs b/libraries/src/AWS.Lambda.Powertools.Logging/Internal/LoggingConstants.cs new file mode 100644 index 000000000..1ff29c35f --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Logging/Internal/LoggingConstants.cs @@ -0,0 +1,114 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using Microsoft.Extensions.Logging; + +namespace AWS.Lambda.Powertools.Logging.Internal; + +/// +/// Class LoggingConstants. +/// +internal static class LoggingConstants +{ + /// + /// Constant for default log level + /// + internal const LogLevel DefaultLogLevel = LogLevel.Information; + + /// + /// Constant for default log output case + /// + internal const LoggerOutputCase DefaultLoggerOutputCase = LoggerOutputCase.SnakeCase; + + /// + /// Constant for key json formatter + /// + internal const string KeyJsonFormatter = "{@json}"; + + /// + /// Constant for key cold start + /// + internal const string KeyColdStart = "ColdStart"; + + /// + /// Constant for key function name + /// + internal const string KeyFunctionName = "FunctionName"; + + /// + /// Constant for key function version + /// + internal const string KeyFunctionVersion = "FunctionVersion"; + + /// + /// Constant for key function memory size + /// + internal const string KeyFunctionMemorySize = "FunctionMemorySize"; + + /// + /// Constant for key function arn + /// + internal const string KeyFunctionArn = "FunctionArn"; + + /// + /// Constant for key function request identifier + /// + internal const string KeyFunctionRequestId = "FunctionRequestId"; + + /// + /// Constant for key x ray trace identifier + /// + internal const string KeyXRayTraceId = "XrayTraceId"; + + /// + /// Constant for key correlation identifier + /// + internal const string KeyCorrelationId = "CorrelationId"; + + /// + /// Constant for key timestamp + /// + internal const string KeyTimestamp = "Timestamp"; + + /// + /// Constant for key log level + /// + internal const string KeyLogLevel = "Level"; + + /// + /// Constant for key service + /// + internal const string KeyService = "Service"; + + /// + /// Constant for key logger name + /// + internal const string KeyLoggerName = "Name"; + + /// + /// Constant for key message + /// + internal const string KeyMessage = "Message"; + + /// + /// Constant for key sampling rate + /// + internal const string KeySamplingRate = "SamplingRate"; + + /// + /// Constant for key exception + /// + internal const string KeyException = "Exception"; +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Logging/Internal/PowertoolsConfigurations.cs b/libraries/src/AWS.Lambda.Powertools.Logging/Internal/PowertoolsConfigurations.cs new file mode 100644 index 000000000..f05eca49c --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Logging/Internal/PowertoolsConfigurations.cs @@ -0,0 +1,56 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using AWS.Lambda.Powertools.Common; +using Microsoft.Extensions.Logging; + +namespace AWS.Lambda.Powertools.Logging.Internal; + +/// +/// Class PowertoolsConfigurationsExtension. +/// +internal static class PowertoolsConfigurationsExtension +{ + /// + /// Gets the log level. + /// + /// The Powertools configurations. + /// The log level. + /// LogLevel. + internal static LogLevel GetLogLevel(this IPowertoolsConfigurations powertoolsConfigurations, + LogLevel? logLevel = null) + { + if (logLevel.HasValue) + return logLevel.Value; + + if (Enum.TryParse((powertoolsConfigurations.LogLevel ?? "").Trim(), true, out LogLevel result)) + return result; + + return LoggingConstants.DefaultLogLevel; + } + + internal static LoggerOutputCase GetLoggerOutputCase(this IPowertoolsConfigurations powertoolsConfigurations, + LoggerOutputCase? loggerOutputCase = null) + { + if (loggerOutputCase.HasValue) + return loggerOutputCase.Value; + + if (Enum.TryParse((powertoolsConfigurations.LoggerOutputCase ?? "").Trim(), true, out LoggerOutputCase result)) + return result; + + return LoggingConstants.DefaultLoggerOutputCase; + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Logging/Internal/PowertoolsLogger.cs b/libraries/src/AWS.Lambda.Powertools.Logging/Internal/PowertoolsLogger.cs new file mode 100644 index 000000000..947dfb771 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Logging/Internal/PowertoolsLogger.cs @@ -0,0 +1,343 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using AWS.Lambda.Powertools.Common; +using Microsoft.Extensions.Logging; + +namespace AWS.Lambda.Powertools.Logging.Internal; + +/// +/// Class PowertoolsLogger. This class cannot be inherited. +/// Implements the +/// +/// +internal sealed class PowertoolsLogger : ILogger +{ + /// + /// The get current configuration + /// + private readonly Func _getCurrentConfig; + + /// + /// The name + /// + private readonly string _name; + + /// + /// The Powertools configurations + /// + private readonly IPowertoolsConfigurations _powertoolsConfigurations; + + /// + /// The system wrapper + /// + private readonly ISystemWrapper _systemWrapper; + + /// + /// The current configuration + /// + private LoggerConfiguration _currentConfig; + + /// + /// Initializes a new instance of the class. + /// + /// The name. + /// The Powertools configurations. + /// The system wrapper. + /// The get current configuration. + public PowertoolsLogger( + string name, + IPowertoolsConfigurations powertoolsConfigurations, + ISystemWrapper systemWrapper, + Func getCurrentConfig) + { + (_name, _powertoolsConfigurations, _systemWrapper, _getCurrentConfig) = (name, + powertoolsConfigurations, systemWrapper, getCurrentConfig); + } + + /// + /// Sets the current configuration. + /// + /// The current configuration. + private LoggerConfiguration CurrentConfig => + _currentConfig ??= GetCurrentConfig(); + + /// + /// Sets the minimum level. + /// + /// The minimum level. + private LogLevel MinimumLevel => + CurrentConfig.MinimumLevel ?? LoggingConstants.DefaultLogLevel; + + /// + /// Sets the service. + /// + /// The service. + private string Service => + !string.IsNullOrWhiteSpace(CurrentConfig.Service) + ? CurrentConfig.Service + : _powertoolsConfigurations.Service; + + internal PowertoolsLoggerScope CurrentScope { get; private set; } + + /// + /// Begins the scope. + /// + /// The type of the t state. + /// The state. + /// System.IDisposable. + public IDisposable BeginScope(TState state) + { + CurrentScope = new PowertoolsLoggerScope(this, GetScopeKeys(state)); + return CurrentScope; + } + + /// + /// Ends the scope. + /// + internal void EndScope() + { + CurrentScope = null; + } + + /// + /// Extract provided scope keys + /// + /// The type of the t state. + /// The state. + /// Key/Value pair of provided scope keys + private static Dictionary GetScopeKeys(TState state) + { + var keys = new Dictionary(); + + if (state is null) + return keys; + + switch (state) + { + case IEnumerable> pairs: + { + foreach (var (key, value) in pairs) + { + if (!string.IsNullOrWhiteSpace(key)) + keys.TryAdd(key, value); + } + break; + } + case IEnumerable> pairs: + { + foreach (var (key, value) in pairs) + { + if (!string.IsNullOrWhiteSpace(key)) + keys.TryAdd(key, value); + } + break; + } + default: + { + foreach (var property in state.GetType().GetProperties()) + { + keys.TryAdd(property.Name, property.GetValue(state)); + } + break; + } + } + + return keys; + } + + /// + /// Determines whether the specified log level is enabled. + /// + /// The log level. + /// bool. + public bool IsEnabled(LogLevel logLevel) + { + return logLevel != LogLevel.None && logLevel >= MinimumLevel; + } + + /// + /// Writes a log entry. + /// + /// Entry will be written on this level. + /// Id of the event. + /// The entry to be written. Can be also an object. + /// The exception related to this entry. + /// Function to create a message of the and . + /// The type of the object to be written. + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, + Func formatter) + { + if (formatter is null) + throw new ArgumentNullException(nameof(formatter)); + + if (!IsEnabled(logLevel)) + return; + + var message = new Dictionary(StringComparer.Ordinal); + + // Add Custom Keys + foreach (var (key, value) in Logger.GetAllKeys()) + message.TryAdd(key, value); + + // Add Lambda Context Keys + if (PowertoolsLambdaContext.Instance is not null) + { + message.TryAdd(LoggingConstants.KeyFunctionName, PowertoolsLambdaContext.Instance.FunctionName); + message.TryAdd(LoggingConstants.KeyFunctionVersion, PowertoolsLambdaContext.Instance.FunctionVersion); + message.TryAdd(LoggingConstants.KeyFunctionMemorySize, PowertoolsLambdaContext.Instance.MemoryLimitInMB); + message.TryAdd(LoggingConstants.KeyFunctionArn, PowertoolsLambdaContext.Instance.InvokedFunctionArn); + message.TryAdd(LoggingConstants.KeyFunctionRequestId, PowertoolsLambdaContext.Instance.AwsRequestId); + } + + // Add Extra Fields + if (CurrentScope?.ExtraKeys is not null) + { + foreach (var (key, value) in CurrentScope.ExtraKeys) + { + if (!string.IsNullOrWhiteSpace(key)) + message.TryAdd(key, value); + } + } + + message.TryAdd(LoggingConstants.KeyTimestamp, DateTime.UtcNow.ToString("o")); + message.TryAdd(LoggingConstants.KeyLogLevel, logLevel.ToString()); + message.TryAdd(LoggingConstants.KeyService, Service); + message.TryAdd(LoggingConstants.KeyLoggerName, _name); + message.TryAdd(LoggingConstants.KeyMessage, + CustomFormatter(state, exception, out var customMessage) && customMessage is not null + ? customMessage + : formatter(state, exception)); + if (CurrentConfig.SamplingRate.HasValue) + message.TryAdd(LoggingConstants.KeySamplingRate, CurrentConfig.SamplingRate.Value); + if (exception != null) + message.TryAdd(LoggingConstants.KeyException, exception.Message); + + var options = BuildCaseSerializerOptions(); + _systemWrapper.LogLine(JsonSerializer.Serialize(message, options)); + } + + private JsonSerializerOptions BuildCaseSerializerOptions() + { + switch (CurrentConfig.LoggerOutputCase) + { + case LoggerOutputCase.CamelCase: + return new(JsonSerializerDefaults.Web) + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DictionaryKeyPolicy = JsonNamingPolicy.CamelCase + }; + case LoggerOutputCase.PascalCase: + return new() + { + PropertyNamingPolicy = PascalCaseNamingPolicy.Instance, + DictionaryKeyPolicy = PascalCaseNamingPolicy.Instance + }; + default: // Snake case is the default + return new() + { + PropertyNamingPolicy = SnakeCaseNamingPolicy.Instance, + DictionaryKeyPolicy = SnakeCaseNamingPolicy.Instance + }; + } + } + + /// + /// Clears the configuration. + /// + internal void ClearConfig() + { + _currentConfig = null; + } + + /// + /// Gets the current configuration. + /// + /// AWS.Lambda.Powertools.Logging.LoggerConfiguration. + private LoggerConfiguration GetCurrentConfig() + { + var currConfig = _getCurrentConfig(); + var minimumLevel = _powertoolsConfigurations.GetLogLevel(currConfig?.MinimumLevel); + var samplingRate = currConfig?.SamplingRate ?? _powertoolsConfigurations.LoggerSampleRate; + var loggerOutputCase = _powertoolsConfigurations.GetLoggerOutputCase(currConfig?.LoggerOutputCase); + + var config = new LoggerConfiguration + { + Service = currConfig?.Service, + MinimumLevel = minimumLevel, + SamplingRate = samplingRate, + LoggerOutputCase = loggerOutputCase + }; + + if (!samplingRate.HasValue) + return config; + + if (samplingRate.Value < 0 || samplingRate.Value > 1) + { + if (minimumLevel is LogLevel.Debug or LogLevel.Trace) + _systemWrapper.LogLine( + $"Skipping sampling rate configuration because of invalid value. Sampling rate: {samplingRate.Value}"); + config.SamplingRate = null; + return config; + } + + if (samplingRate.Value == 0) + return config; + + var sample = _systemWrapper.GetRandom(); + if (samplingRate.Value > sample) + { + _systemWrapper.LogLine( + $"Changed log level to DEBUG based on Sampling configuration. Sampling Rate: {samplingRate.Value}, Sampler Value: {sample}."); + config.MinimumLevel = LogLevel.Debug; + } + + return config; + } + + /// + /// Formats message for a log entry. + /// + /// The type of the object to be formatted. + /// The entry to be formatted. Can be also an object. + /// The exception related to this entry. + /// The formatted message + /// bool + private static bool CustomFormatter(TState state, Exception exception, out object message) + { + message = null; + if (exception is not null) + return false; + + var stateKeys = (state as IEnumerable>)? + .ToDictionary(i => i.Key, i => i.Value); + + if (stateKeys is null || stateKeys.Count != 2) + return false; + + if (!stateKeys.TryGetValue("{OriginalFormat}", out var originalFormat)) + return false; + + if (originalFormat?.ToString() != LoggingConstants.KeyJsonFormatter) + return false; + + message = stateKeys.First(k => k.Key != "{OriginalFormat}").Value; + return true; + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Logging/Internal/PowertoolsLoggerScope.cs b/libraries/src/AWS.Lambda.Powertools.Logging/Internal/PowertoolsLoggerScope.cs new file mode 100644 index 000000000..006f62938 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Logging/Internal/PowertoolsLoggerScope.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; + +namespace AWS.Lambda.Powertools.Logging.Internal; + +/// +/// Class PowertoolsLoggerScope. +/// +internal class PowertoolsLoggerScope : IDisposable +{ + /// + /// The associated logger + /// + private readonly PowertoolsLogger _logger; + + /// + /// The provided extra keys + /// + internal Dictionary ExtraKeys { get; } + + /// + /// Creates a PowertoolsLoggerScope object + /// + internal PowertoolsLoggerScope(PowertoolsLogger logger, Dictionary extraKeys) + { + _logger = logger; + ExtraKeys = extraKeys; + } + + /// + /// Implements IDisposable interface + /// + public void Dispose() + { + _logger?.EndScope(); + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Logging/InternalsVisibleTo.cs b/libraries/src/AWS.Lambda.Powertools.Logging/InternalsVisibleTo.cs new file mode 100644 index 000000000..308debcfe --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Logging/InternalsVisibleTo.cs @@ -0,0 +1,18 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("AWS.Lambda.Powertools.Logging.Tests")] \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Logging/Logger.cs b/libraries/src/AWS.Lambda.Powertools.Logging/Logger.cs new file mode 100644 index 000000000..0989abac4 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Logging/Logger.cs @@ -0,0 +1,1157 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using AWS.Lambda.Powertools.Logging.Internal; +using Microsoft.Extensions.Logging; + +namespace AWS.Lambda.Powertools.Logging; + +/// +/// Class Logger. +/// +public class Logger +{ + /// + /// The logger instance + /// + private static ILogger _loggerInstance; + + /// + /// Gets the logger instance. + /// + /// The logger instance. + private static ILogger LoggerInstance => _loggerInstance ??= Create(); + + /// + /// Gets or sets the logger provider. + /// + /// The logger provider. + internal static ILoggerProvider LoggerProvider { get; set; } + + /// + /// Gets the scope. + /// + /// The scope. + private static IDictionary _scope { get; } = new Dictionary(StringComparer.Ordinal); + + /// + /// Creates a new instance. + /// + /// The category name for messages produced by the logger. + /// The instance of that was created. + /// categoryName + public static ILogger Create(string categoryName) + { + if (string.IsNullOrWhiteSpace(categoryName)) + throw new ArgumentNullException(nameof(categoryName)); + + LoggerProvider ??= new LoggerProvider(null); + + return LoggerProvider.CreateLogger(categoryName); + } + + /// + /// Creates a new instance. + /// + /// + /// The instance of that was created. + public static ILogger Create() + { + return Create(typeof(T).FullName); + } + + #region Scope Variables + + /// + /// Appending additional key to the log context. + /// + /// The key. + /// The value. + /// key + /// value + public static void AppendKey(string key, object value) + { + if (string.IsNullOrWhiteSpace(key)) + throw new ArgumentNullException(nameof(key)); + + if (value is null) + throw new ArgumentNullException(nameof(value)); + + if (_scope.ContainsKey(key)) + _scope[key] = value; + else + _scope.Add(key, value); + } + + /// + /// Appending additional key to the log context. + /// + /// The list of keys. + public static void AppendKeys(IEnumerable> keys) + { + foreach (var (key, value) in keys) + AppendKey(key, value); + } + + /// + /// Appending additional key to the log context. + /// + /// The list of keys. + public static void AppendKeys(IEnumerable> keys) + { + foreach (var (key, value) in keys) + AppendKey(key, value); + } + + /// + /// Remove additional keys from the log context. + /// + /// The list of keys. + public static void RemoveKeys(params string[] keys) + { + if (keys == null) return; + foreach (var key in keys) + if (_scope.ContainsKey(key)) + _scope.Remove(key); + } + + /// + /// Returns all additional keys added to the log context. + /// + /// IEnumerable<KeyValuePair<System.String, System.Object>>. + public static IEnumerable> GetAllKeys() + { + return _scope.AsEnumerable(); + } + + /// + /// Removes all additional keys from the log context. + /// + internal static void RemoveAllKeys() + { + _scope.Clear(); + } + + #endregion + + #region Core Logger Methods + + #region Debug + + /// + /// Formats and writes a debug log message. + /// + /// The event id associated with the log. + /// The exception to log. + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogDebug(0, exception, "Error while processing request from {Address}", address) + public static void LogDebug(EventId eventId, Exception exception, string message, params object[] args) + { + LoggerInstance.LogDebug(eventId, exception, message, args); + } + + /// + /// Formats and writes a debug log message. + /// + /// The event id associated with the log. + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogDebug(0, "Processing request from {Address}", address) + public static void LogDebug(EventId eventId, string message, params object[] args) + { + LoggerInstance.LogDebug(eventId, message, args); + } + + /// + /// Formats and writes a debug log message. + /// + /// The exception to log. + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogDebug(exception, "Error while processing request from {Address}", address) + public static void LogDebug(Exception exception, string message, params object[] args) + { + LoggerInstance.LogDebug(exception, message, args); + } + + /// + /// Formats and writes a debug log message. + /// + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogDebug("Processing request from {Address}", address) + public static void LogDebug(string message, params object[] args) + { + LoggerInstance.LogDebug(message, args); + } + + #endregion + + #region Trace + + /// + /// Formats and writes a trace log message. + /// + /// The event id associated with the log. + /// The exception to log. + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogTrace(0, exception, "Error while processing request from {Address}", address) + public static void LogTrace(EventId eventId, Exception exception, string message, params object[] args) + { + LoggerInstance.LogTrace(eventId, exception, message, args); + } + + /// + /// Formats and writes a trace log message. + /// + /// The event id associated with the log. + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogTrace(0, "Processing request from {Address}", address) + public static void LogTrace(EventId eventId, string message, params object[] args) + { + LoggerInstance.LogTrace(eventId, message, args); + } + + /// + /// Formats and writes a trace log message. + /// + /// The exception to log. + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogTrace(exception, "Error while processing request from {Address}", address) + public static void LogTrace(Exception exception, string message, params object[] args) + { + LoggerInstance.LogTrace(exception, message, args); + } + + /// + /// Formats and writes a trace log message. + /// + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogTrace("Processing request from {Address}", address) + public static void LogTrace(string message, params object[] args) + { + LoggerInstance.LogTrace(message, args); + } + + #endregion + + #region Information + + /// + /// Formats and writes an informational log message. + /// + /// The event id associated with the log. + /// The exception to log. + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogInformation(0, exception, "Error while processing request from {Address}", address) + public static void LogInformation(EventId eventId, Exception exception, string message, params object[] args) + { + LoggerInstance.LogInformation(eventId, exception, message, args); + } + + /// + /// Formats and writes an informational log message. + /// + /// The event id associated with the log. + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogInformation(0, "Processing request from {Address}", address) + public static void LogInformation(EventId eventId, string message, params object[] args) + { + LoggerInstance.LogInformation(eventId, message, args); + } + + /// + /// Formats and writes an informational log message. + /// + /// The exception to log. + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogInformation(exception, "Error while processing request from {Address}", address) + public static void LogInformation(Exception exception, string message, params object[] args) + { + LoggerInstance.LogInformation(exception, message, args); + } + + /// + /// Formats and writes an informational log message. + /// + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogInformation("Processing request from {Address}", address) + public static void LogInformation(string message, params object[] args) + { + LoggerInstance.LogInformation(message, args); + } + + #endregion + + #region Warning + + /// + /// Formats and writes a warning log message. + /// + /// The event id associated with the log. + /// The exception to log. + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogWarning(0, exception, "Error while processing request from {Address}", address) + public static void LogWarning(EventId eventId, Exception exception, string message, params object[] args) + { + LoggerInstance.LogWarning(eventId, exception, message, args); + } + + /// + /// Formats and writes a warning log message. + /// + /// The event id associated with the log. + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogWarning(0, "Processing request from {Address}", address) + public static void LogWarning(EventId eventId, string message, params object[] args) + { + LoggerInstance.LogWarning(eventId, message, args); + } + + /// + /// Formats and writes a warning log message. + /// + /// The exception to log. + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogWarning(exception, "Error while processing request from {Address}", address) + public static void LogWarning(Exception exception, string message, params object[] args) + { + LoggerInstance.LogWarning(exception, message, args); + } + + /// + /// Formats and writes a warning log message. + /// + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogWarning("Processing request from {Address}", address) + public static void LogWarning(string message, params object[] args) + { + LoggerInstance.LogWarning(message, args); + } + + #endregion + + #region Error + + /// + /// Formats and writes an error log message. + /// + /// The event id associated with the log. + /// The exception to log. + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogError(0, exception, "Error while processing request from {Address}", address) + public static void LogError(EventId eventId, Exception exception, string message, params object[] args) + { + LoggerInstance.LogError(eventId, exception, message, args); + } + + /// + /// Formats and writes an error log message. + /// + /// The event id associated with the log. + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogError(0, "Processing request from {Address}", address) + public static void LogError(EventId eventId, string message, params object[] args) + { + LoggerInstance.LogError(eventId, message, args); + } + + /// + /// Formats and writes an error log message. + /// + /// The exception to log. + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// > + /// Logger.LogError(exception, "Error while processing request from {Address}", address) + public static void LogError(Exception exception, string message, params object[] args) + { + LoggerInstance.LogError(exception, message, args); + } + + /// + /// Formats and writes an error log message. + /// + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogError("Processing request from {Address}", address) + public static void LogError(string message, params object[] args) + { + LoggerInstance.LogError(message, args); + } + + #endregion + + #region Critical + + /// + /// Formats and writes a critical log message. + /// + /// The event id associated with the log. + /// The exception to log. + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogCritical(0, exception, "Error while processing request from {Address}", address) + public static void LogCritical(EventId eventId, Exception exception, string message, params object[] args) + { + LoggerInstance.LogCritical(eventId, exception, message, args); + } + + /// + /// Formats and writes a critical log message. + /// + /// The event id associated with the log. + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogCritical(0, "Processing request from {Address}", address) + public static void LogCritical(EventId eventId, string message, params object[] args) + { + LoggerInstance.LogCritical(eventId, message, args); + } + + /// + /// Formats and writes a critical log message. + /// + /// The exception to log. + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogCritical(exception, "Error while processing request from {Address}", address) + public static void LogCritical(Exception exception, string message, params object[] args) + { + LoggerInstance.LogCritical(exception, message, args); + } + + /// + /// Formats and writes a critical log message. + /// + /// + /// Format string of the log message in message template format. Example: + /// "User {User} logged in from {Address}" + /// + /// An object array that contains zero or more objects to format. + /// Logger.LogCritical("Processing request from {Address}", address) + public static void LogCritical(string message, params object[] args) + { + LoggerInstance.LogCritical(message, args); + } + + #endregion + + #region Log + + /// + /// Formats and writes a log message at the specified log level. + /// + /// Entry will be written on this level. + /// Format string of the log message. + /// An object array that contains zero or more objects to format. + public static void Log(LogLevel logLevel, string message, params object[] args) + { + LoggerInstance.Log(logLevel, message, args); + } + + /// + /// Formats and writes a log message at the specified log level. + /// + /// Entry will be written on this level. + /// The event id associated with the log. + /// Format string of the log message. + /// An object array that contains zero or more objects to format. + public static void Log(LogLevel logLevel, EventId eventId, string message, params object[] args) + { + LoggerInstance.Log(logLevel, eventId, message, args); + } + + /// + /// Formats and writes a log message at the specified log level. + /// + /// Entry will be written on this level. + /// The exception to log. + /// Format string of the log message. + /// An object array that contains zero or more objects to format. + public static void Log(LogLevel logLevel, Exception exception, string message, params object[] args) + { + LoggerInstance.Log(logLevel, exception, message, args); + } + + /// + /// Formats and writes a log message at the specified log level. + /// + /// Entry will be written on this level. + /// The event id associated with the log. + /// The exception to log. + /// Format string of the log message. + /// An object array that contains zero or more objects to format. + public static void Log(LogLevel logLevel, EventId eventId, Exception exception, string message, + params object[] args) + { + LoggerInstance.Log(logLevel, eventId, exception, message, args); + } + + /// + /// Writes a log entry. + /// + /// The type of the object to be written. + /// Entry will be written on this level. + /// Id of the event. + /// The entry to be written. Can be also an object. + /// The exception related to this entry. + /// + /// Function to create a message of the + /// and . + /// + public static void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, + Func formatter) + { + LoggerInstance.Log(logLevel, eventId, state, exception, formatter); + } + + #endregion + + #endregion + + #region JSON Logger Methods + + /// + /// Formats and writes a trace log message as JSON. + /// + /// The object to be serialized as JSON. + /// logger.LogTrace(new {User = user, Address = address}) + public static void LogTrace(object message) + { + LoggerInstance.LogTrace(message); + } + + /// + /// Formats and writes an trace log message. + /// + /// The exception to log. + /// logger.LogTrace(exception) + public static void LogTrace(Exception exception) + { + LoggerInstance.LogTrace(exception); + } + + /// + /// Formats and writes a debug log message as JSON. + /// + /// The object to be serialized as JSON. + /// logger.LogDebug(new {User = user, Address = address}) + public static void LogDebug(object message) + { + LoggerInstance.LogDebug(message); + } + + /// + /// Formats and writes an debug log message. + /// + /// The exception to log. + /// logger.LogDebug(exception) + public static void LogDebug(Exception exception) + { + LoggerInstance.LogDebug(exception); + } + + /// + /// Formats and writes an information log message as JSON. + /// + /// The object to be serialized as JSON. + /// logger.LogInformation(new {User = user, Address = address}) + public static void LogInformation(object message) + { + LoggerInstance.LogInformation(message); + } + + /// + /// Formats and writes an information log message. + /// + /// The exception to log. + /// logger.LogInformation(exception) + public static void LogInformation(Exception exception) + { + LoggerInstance.LogInformation(exception); + } + + /// + /// Formats and writes a warning log message as JSON. + /// + /// The object to be serialized as JSON. + /// logger.LogWarning(new {User = user, Address = address}) + public static void LogWarning(object message) + { + LoggerInstance.LogWarning(message); + } + + /// + /// Formats and writes an warning log message. + /// + /// The exception to log. + /// logger.LogWarning(exception) + public static void LogWarning(Exception exception) + { + LoggerInstance.LogWarning(exception); + } + + /// + /// Formats and writes a error log message as JSON. + /// + /// The object to be serialized as JSON. + /// logger.LogCritical(new {User = user, Address = address}) + public static void LogError(object message) + { + LoggerInstance.LogError(message); + } + + /// + /// Formats and writes an error log message. + /// + /// The exception to log. + /// logger.LogError(exception) + public static void LogError(Exception exception) + { + LoggerInstance.LogError(exception); + } + + /// + /// Formats and writes a critical log message as JSON. + /// + /// The object to be serialized as JSON. + /// logger.LogCritical(new {User = user, Address = address}) + public static void LogCritical(object message) + { + LoggerInstance.LogCritical(message); + } + + /// + /// Formats and writes an critical log message. + /// + /// The exception to log. + /// logger.LogCritical(exception) + public static void LogCritical(Exception exception) + { + LoggerInstance.LogCritical(exception); + } + + /// + /// Formats and writes a log message as JSON at the specified log level. + /// + /// Entry will be written on this level. + /// The object to be serialized as JSON. + /// logger.Log(LogLevel.Information, new {User = user, Address = address}) + public static void Log(LogLevel logLevel, object message) + { + LoggerInstance.Log(logLevel, message); + } + + /// + /// Formats and writes a log message at the specified log level. + /// + /// Entry will be written on this level. + /// The exception to log. + /// logger.Log(LogLevel.Information, exception) + public static void Log(LogLevel logLevel, Exception exception) + { + LoggerInstance.Log(logLevel, exception); + } + + #endregion + + #region ExtraKeys Logger Methods + + #region Debug + + /// + /// Formats and writes a debug log message. + /// + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogDebug(extraKeys, 0, exception, "Error while processing request from {Address}", address) + public static void LogDebug(T extraKeys, EventId eventId, Exception exception, string message, params object[] args) where T : class + { + LoggerInstance.LogDebug(extraKeys, eventId, exception, message, args); + } + + /// + /// Formats and writes a debug log message. + /// + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogDebug(extraKeys, 0, "Processing request from {Address}", address) + public static void LogDebug(T extraKeys, EventId eventId, string message, params object[] args) where T : class + { + LoggerInstance.LogDebug(extraKeys, eventId, message, args); + } + + /// + /// Formats and writes a debug log message. + /// + /// Additional keys will be appended to the log entry. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogDebug(extraKeys, exception, "Error while processing request from {Address}", address) + public static void LogDebug(T extraKeys, Exception exception, string message, params object[] args) where T : class + { + LoggerInstance.LogDebug(extraKeys, exception, message, args); + } + + /// + /// Formats and writes a debug log message. + /// + /// Additional keys will be appended to the log entry. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogDebug(extraKeys, "Processing request from {Address}", address) + public static void LogDebug(T extraKeys, string message, params object[] args) where T : class + { + LoggerInstance.LogDebug(extraKeys, message, args); + } + + #endregion + + #region Trace + + /// + /// Formats and writes a trace log message. + /// + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogTrace(extraKeys, 0, exception, "Error while processing request from {Address}", address) + public static void LogTrace(T extraKeys, EventId eventId, Exception exception, string message, params object[] args) where T : class + { + LoggerInstance.LogTrace(extraKeys, eventId, exception, message, args); + } + + /// + /// Formats and writes a trace log message. + /// + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogTrace(extraKeys, 0, "Processing request from {Address}", address) + public static void LogTrace(T extraKeys, EventId eventId, string message, params object[] args) where T : class + { + LoggerInstance.LogTrace(extraKeys, eventId, message, args); + } + + /// + /// Formats and writes a trace log message. + /// + /// Additional keys will be appended to the log entry. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogTrace(extraKeys, exception, "Error while processing request from {Address}", address) + public static void LogTrace(T extraKeys, Exception exception, string message, params object[] args) where T : class + { + LoggerInstance.LogTrace(extraKeys, exception, message, args); + } + + /// + /// Formats and writes a trace log message. + /// + /// Additional keys will be appended to the log entry. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogTrace(extraKeys, "Processing request from {Address}", address) + public static void LogTrace(T extraKeys, string message, params object[] args) where T : class + { + LoggerInstance.LogTrace(extraKeys, message, args); + } + + #endregion + + #region Information + + /// + /// Formats and writes an informational log message. + /// + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogInformation(extraKeys, 0, exception, "Error while processing request from {Address}", address) + public static void LogInformation(T extraKeys, EventId eventId, Exception exception, string message, params object[] args) where T : class + { + LoggerInstance.LogInformation(extraKeys, eventId, exception, message, args); + } + + /// + /// Formats and writes an informational log message. + /// + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogInformation(extraKeys, 0, "Processing request from {Address}", address) + public static void LogInformation(T extraKeys, EventId eventId, string message, params object[] args) where T : class + { + LoggerInstance.LogInformation(extraKeys, eventId, message, args); + } + + /// + /// Formats and writes an informational log message. + /// + /// Additional keys will be appended to the log entry. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogInformation(extraKeys, exception, "Error while processing request from {Address}", address) + public static void LogInformation(T extraKeys, Exception exception, string message, params object[] args) where T : class + { + LoggerInstance.LogInformation(extraKeys, exception, message, args); + } + + /// + /// Formats and writes an informational log message. + /// + /// Additional keys will be appended to the log entry. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogInformation(extraKeys, "Processing request from {Address}", address) + public static void LogInformation(T extraKeys, string message, params object[] args) where T : class + { + LoggerInstance.LogInformation(extraKeys, message, args); + } + + #endregion + + #region Warning + + /// + /// Formats and writes a warning log message. + /// + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogWarning(extraKeys, 0, exception, "Error while processing request from {Address}", address) + public static void LogWarning(T extraKeys, EventId eventId, Exception exception, string message, params object[] args) where T : class + { + LoggerInstance.LogWarning(extraKeys, eventId, exception, message, args); + } + + /// + /// Formats and writes a warning log message. + /// + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogWarning(extraKeys, 0, "Processing request from {Address}", address) + public static void LogWarning(T extraKeys, EventId eventId, string message, params object[] args) where T : class + { + LoggerInstance.LogWarning(extraKeys, eventId, message, args); + } + + /// + /// Formats and writes a warning log message. + /// + /// Additional keys will be appended to the log entry. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogWarning(extraKeys, exception, "Error while processing request from {Address}", address) + public static void LogWarning(T extraKeys, Exception exception, string message, params object[] args) where T : class + { + LoggerInstance.LogWarning(extraKeys, exception, message, args); + } + + /// + /// Formats and writes a warning log message. + /// + /// Additional keys will be appended to the log entry. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogWarning(extraKeys, "Processing request from {Address}", address) + public static void LogWarning(T extraKeys, string message, params object[] args) where T : class + { + LoggerInstance.LogWarning(extraKeys, message, args); + } + + #endregion + + #region Error + + /// + /// Formats and writes an error log message. + /// + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogError(extraKeys, 0, exception, "Error while processing request from {Address}", address) + public static void LogError(T extraKeys, EventId eventId, Exception exception, string message, params object[] args) where T : class + { + LoggerInstance.LogError(extraKeys, eventId, exception, message, args); + } + + /// + /// Formats and writes an error log message. + /// + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogError(extraKeys, 0, "Processing request from {Address}", address) + public static void LogError(T extraKeys, EventId eventId, string message, params object[] args) where T : class + { + LoggerInstance.LogError(extraKeys, eventId, message, args); + } + + /// + /// Formats and writes an error log message. + /// + /// Additional keys will be appended to the log entry. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogError(extraKeys, exception, "Error while processing request from {Address}", address) + public static void LogError(T extraKeys, Exception exception, string message, params object[] args) where T : class + { + LoggerInstance.LogError(extraKeys, exception, message, args); + } + + /// + /// Formats and writes an error log message. + /// + /// Additional keys will be appended to the log entry. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogError(extraKeys, "Processing request from {Address}", address) + public static void LogError(T extraKeys, string message, params object[] args) where T : class + { + LoggerInstance.LogError(extraKeys, message, args); + } + + #endregion + + #region Critical + + /// + /// Formats and writes a critical log message. + /// + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogCritical(extraKeys, 0, exception, "Error while processing request from {Address}", address) + public static void LogCritical(T extraKeys, EventId eventId, Exception exception, string message, params object[] args) where T : class + { + LoggerInstance.LogCritical(extraKeys, eventId, exception, message, args); + } + + /// + /// Formats and writes a critical log message. + /// + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogCritical(extraKeys, 0, "Processing request from {Address}", address) + public static void LogCritical(T extraKeys, EventId eventId, string message, params object[] args) where T : class + { + LoggerInstance.LogCritical(extraKeys, eventId, message, args); + } + + /// + /// Formats and writes a critical log message. + /// + /// Additional keys will be appended to the log entry. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogCritical(extraKeys, exception, "Error while processing request from {Address}", address) + public static void LogCritical(T extraKeys, Exception exception, string message, params object[] args) where T : class + { + LoggerInstance.LogCritical(extraKeys, exception, message, args); + } + + /// + /// Formats and writes a critical log message. + /// + /// Additional keys will be appended to the log entry. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogCritical(extraKeys, "Processing request from {Address}", address) + public static void LogCritical(T extraKeys, string message, params object[] args) where T : class + { + LoggerInstance.LogCritical(extraKeys, message, args); + } + + #endregion + + #region Log + + /// + /// Formats and writes a log message at the specified log level. + /// + /// Entry will be written on this level. + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.Log(LogLevel.Information, extraKeys, 0, exception, "Error while processing request from {Address}", address) + public static void Log(LogLevel logLevel, T extraKeys, EventId eventId, Exception exception, string message, params object[] args) where T : class + { + LoggerInstance.Log(logLevel, extraKeys, eventId, exception, message, args); + } + + /// + /// Formats and writes a log message at the specified log level. + /// + /// Entry will be written on this level. + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.Log(LogLevel.Information, extraKeys, 0, "Processing request from {Address}", address) + public static void Log(LogLevel logLevel, T extraKeys, EventId eventId, string message, params object[] args) where T : class + { + LoggerInstance.Log(logLevel, extraKeys, eventId, message, args); + } + + /// + /// Formats and writes a log message at the specified log level. + /// + /// Entry will be written on this level. + /// Additional keys will be appended to the log entry. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.Log(LogLevel.Information, extraKeys, exception, "Error while processing request from {Address}", address) + public static void Log(LogLevel logLevel, T extraKeys, Exception exception, string message, params object[] args) where T : class + { + LoggerInstance.Log(logLevel, extraKeys, exception, message, args); + } + + /// + /// Formats and writes a log message at the specified log level. + /// + /// Entry will be written on this level. + /// Additional keys will be appended to the log entry. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.Log(LogLevel.Information, extraKeys, "Processing request from {Address}", address) + public static void Log(LogLevel logLevel, T extraKeys, string message, params object[] args) where T : class + { + LoggerInstance.Log(logLevel, extraKeys, message, args); + } + + #endregion + + #endregion +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Logging/LoggerConfiguration.cs b/libraries/src/AWS.Lambda.Powertools.Logging/LoggerConfiguration.cs new file mode 100644 index 000000000..da2297939 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Logging/LoggerConfiguration.cs @@ -0,0 +1,62 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace AWS.Lambda.Powertools.Logging; + +/// +/// Class LoggerConfiguration. +/// Implements the +/// +/// +/// +public class LoggerConfiguration : IOptions +{ + /// + /// Service name is used for logging. + /// This can be also set using the environment variable POWERTOOLS_SERVICE_NAME. + /// + /// The service. + public string Service { get; set; } + + /// + /// Specify the minimum log level for logging (Information, by default). + /// This can be also set using the environment variable LOG_LEVEL. + /// + /// The minimum level. + public LogLevel? MinimumLevel { get; set; } + + /// + /// Dynamically set a percentage of logs to DEBUG level. + /// This can be also set using the environment variable POWERTOOLS_LOGGER_SAMPLE_RATE. + /// + /// The sampling rate. + public double? SamplingRate { get; set; } + + /// + /// The default configured options instance + /// + /// The value. + LoggerConfiguration IOptions.Value => this; + + /// + /// The logger output case. + /// This can be also set using the environment variable POWERTOOLS_LOGGER_CASE. + /// + /// The logger output case. + public LoggerOutputCase? LoggerOutputCase { get; set; } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Logging/LoggerExtensions.cs b/libraries/src/AWS.Lambda.Powertools.Logging/LoggerExtensions.cs new file mode 100644 index 000000000..3c22c3da0 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Logging/LoggerExtensions.cs @@ -0,0 +1,639 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using AWS.Lambda.Powertools.Logging.Internal; +using Microsoft.Extensions.Logging; + +namespace AWS.Lambda.Powertools.Logging; + +/// +/// Class LoggerExtensions. +/// +public static class LoggerExtensions +{ + #region JSON Logger Extentions + + /// + /// Formats and writes a trace log message as JSON. + /// + /// The to write to. + /// The object to be serialized as JSON. + /// logger.LogTrace(new {User = user, Address = address}) + public static void LogTrace(this ILogger logger, object message) + { + logger.LogTrace(LoggingConstants.KeyJsonFormatter, message); + } + + /// + /// Formats and writes an trace log message. + /// + /// The to write to. + /// The exception to log. + /// logger.LogTrace(exception) + public static void LogTrace(this ILogger logger, Exception exception) + { + logger.LogTrace(exception: exception, message: exception.Message); + } + + /// + /// Formats and writes a debug log message as JSON. + /// + /// The to write to. + /// The object to be serialized as JSON. + /// logger.LogDebug(new {User = user, Address = address}) + public static void LogDebug(this ILogger logger, object message) + { + logger.LogDebug(LoggingConstants.KeyJsonFormatter, message); + } + + /// + /// Formats and writes an debug log message. + /// + /// The to write to. + /// The exception to log. + /// logger.LogDebug(exception) + public static void LogDebug(this ILogger logger, Exception exception) + { + logger.LogDebug(exception: exception, message: exception.Message); + } + + /// + /// Formats and writes an information log message as JSON. + /// + /// The to write to. + /// The object to be serialized as JSON. + /// logger.LogInformation(new {User = user, Address = address}) + public static void LogInformation(this ILogger logger, object message) + { + logger.LogInformation(LoggingConstants.KeyJsonFormatter, message); + } + + /// + /// Formats and writes an information log message. + /// + /// The to write to. + /// The exception to log. + /// logger.LogInformation(exception) + public static void LogInformation(this ILogger logger, Exception exception) + { + logger.LogInformation(exception: exception, message: exception.Message); + } + + /// + /// Formats and writes a warning log message as JSON. + /// + /// The to write to. + /// The object to be serialized as JSON. + /// logger.LogWarning(new {User = user, Address = address}) + public static void LogWarning(this ILogger logger, object message) + { + logger.LogWarning(LoggingConstants.KeyJsonFormatter, message); + } + + /// + /// Formats and writes an warning log message. + /// + /// The to write to. + /// The exception to log. + /// logger.LogWarning(exception) + public static void LogWarning(this ILogger logger, Exception exception) + { + logger.LogWarning(exception: exception, message: exception.Message); + } + + /// + /// Formats and writes a error log message as JSON. + /// + /// The to write to. + /// The object to be serialized as JSON. + /// logger.LogCritical(new {User = user, Address = address}) + public static void LogError(this ILogger logger, object message) + { + logger.LogError(LoggingConstants.KeyJsonFormatter, message); + } + + /// + /// Formats and writes an error log message. + /// + /// The to write to. + /// The exception to log. + /// logger.LogError(exception) + public static void LogError(this ILogger logger, Exception exception) + { + logger.LogError(exception: exception, message: exception.Message); + } + + /// + /// Formats and writes a critical log message as JSON. + /// + /// The to write to. + /// The object to be serialized as JSON. + /// logger.LogCritical(new {User = user, Address = address}) + public static void LogCritical(this ILogger logger, object message) + { + logger.LogCritical(LoggingConstants.KeyJsonFormatter, message); + } + + /// + /// Formats and writes an critical log message. + /// + /// The to write to. + /// The exception to log. + /// logger.LogCritical(exception) + public static void LogCritical(this ILogger logger, Exception exception) + { + logger.LogCritical(exception: exception, message: exception.Message); + } + + /// + /// Formats and writes a log message as JSON at the specified log level. + /// + /// The to write to. + /// Entry will be written on this level. + /// The object to be serialized as JSON. + /// logger.Log(LogLevel.Information, new {User = user, Address = address}) + public static void Log(this ILogger logger, LogLevel logLevel, object message) + { + logger.Log(logLevel, LoggingConstants.KeyJsonFormatter, message); + } + + /// + /// Formats and writes a log message at the specified log level. + /// + /// The to write to. + /// Entry will be written on this level. + /// The exception to log. + /// logger.Log(LogLevel.Information, exception) + public static void Log(this ILogger logger, LogLevel logLevel, Exception exception) + { + logger.Log(logLevel, exception: exception, message: exception.Message); + } + + #endregion + + #region ExtraKeys Logger Extentions + + #region Debug + + /// + /// Formats and writes a debug log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogDebug(extraKeys, 0, exception, "Error while processing request from {Address}", address) + public static void LogDebug(this ILogger logger, T extraKeys, EventId eventId, Exception exception, + string message, params object[] args) where T : class + { + Log(logger, LogLevel.Debug, extraKeys, eventId, exception, message, args); + } + + /// + /// Formats and writes a debug log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogDebug(extraKeys, 0, "Processing request from {Address}", address) + public static void LogDebug(this ILogger logger, T extraKeys, EventId eventId, string message, + params object[] args) where T : class + { + Log(logger, LogLevel.Debug, extraKeys, eventId, message, args); + } + + /// + /// Formats and writes a debug log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogDebug(extraKeys, exception, "Error while processing request from {Address}", address) + public static void LogDebug(this ILogger logger, T extraKeys, Exception exception, string message, + params object[] args) where T : class + { + Log(logger, LogLevel.Debug, extraKeys, exception, message, args); + } + + /// + /// Formats and writes a debug log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogDebug(extraKeys, "Processing request from {Address}", address) + public static void LogDebug(this ILogger logger, T extraKeys, string message, params object[] args) where T : class + { + Log(logger, LogLevel.Debug, extraKeys, message, args); + } + + #endregion + + #region Trace + + /// + /// Formats and writes a trace log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogTrace(extraKeys, 0, exception, "Error while processing request from {Address}", address) + public static void LogTrace(this ILogger logger, T extraKeys, EventId eventId, Exception exception, + string message, params object[] args) where T : class + { + Log(logger, LogLevel.Trace, extraKeys, eventId, exception, message, args); + } + + /// + /// Formats and writes a trace log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogTrace(extraKeys, 0, "Processing request from {Address}", address) + public static void LogTrace(this ILogger logger, T extraKeys, EventId eventId, string message, + params object[] args) where T : class + { + Log(logger, LogLevel.Trace, extraKeys, eventId, message, args); + } + + /// + /// Formats and writes a trace log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogTrace(extraKeys, exception, "Error while processing request from {Address}", address) + public static void LogTrace(this ILogger logger, T extraKeys, Exception exception, string message, + params object[] args) where T : class + { + Log(logger, LogLevel.Trace, extraKeys, exception, message, args); + } + + /// + /// Formats and writes a trace log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogTrace(extraKeys, "Processing request from {Address}", address) + public static void LogTrace(this ILogger logger, T extraKeys, string message, params object[] args) where T : class + { + Log(logger, LogLevel.Trace, extraKeys, message, args); + } + + #endregion + + #region Information + + /// + /// Formats and writes an informational log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogInformation(extraKeys, 0, exception, "Error while processing request from {Address}", address) + public static void LogInformation(this ILogger logger, T extraKeys, EventId eventId, Exception exception, + string message, params object[] args) where T : class + { + Log(logger, LogLevel.Information, extraKeys, eventId, exception, message, args); + } + + /// + /// Formats and writes an informational log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogInformation(extraKeys, 0, "Processing request from {Address}", address) + public static void LogInformation(this ILogger logger, T extraKeys, EventId eventId, string message, + params object[] args) where T : class + { + Log(logger, LogLevel.Information, extraKeys, eventId, message, args); + } + + /// + /// Formats and writes an informational log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogInformation(extraKeys, exception, "Error while processing request from {Address}", address) + public static void LogInformation(this ILogger logger, T extraKeys, Exception exception, string message, + params object[] args) where T : class + { + Log(logger, LogLevel.Information, extraKeys, exception, message, args); + } + + /// + /// Formats and writes an informational log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogInformation(extraKeys, "Processing request from {Address}", address) + public static void LogInformation(this ILogger logger, T extraKeys, string message, params object[] args) where T : class + { + Log(logger, LogLevel.Information, extraKeys, message, args); + } + + #endregion + + #region Warning + + /// + /// Formats and writes a warning log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogWarning(extraKeys, 0, exception, "Error while processing request from {Address}", address) + public static void LogWarning(this ILogger logger, T extraKeys, EventId eventId, Exception exception, + string message, params object[] args) where T : class + { + Log(logger, LogLevel.Warning, extraKeys, eventId, exception, message, args); + } + + /// + /// Formats and writes a warning log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogWarning(extraKeys, 0, "Processing request from {Address}", address) + public static void LogWarning(this ILogger logger, T extraKeys, EventId eventId, string message, + params object[] args) where T : class + { + Log(logger, LogLevel.Warning, extraKeys, eventId, message, args); + } + + /// + /// Formats and writes a warning log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogWarning(extraKeys, exception, "Error while processing request from {Address}", address) + public static void LogWarning(this ILogger logger, T extraKeys, Exception exception, string message, + params object[] args) where T : class + { + Log(logger, LogLevel.Warning, extraKeys, exception, message, args); + } + + /// + /// Formats and writes a warning log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogWarning(extraKeys, "Processing request from {Address}", address) + public static void LogWarning(this ILogger logger, T extraKeys, string message, params object[] args) where T : class + { + Log(logger, LogLevel.Warning, extraKeys, message, args); + } + + #endregion + + #region Error + + /// + /// Formats and writes an error log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogError(extraKeys, 0, exception, "Error while processing request from {Address}", address) + public static void LogError(this ILogger logger, T extraKeys, EventId eventId, Exception exception, + string message, params object[] args) where T : class + { + Log(logger, LogLevel.Error, extraKeys, eventId, exception, message, args); + } + + /// + /// Formats and writes an error log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogError(extraKeys, 0, "Processing request from {Address}", address) + public static void LogError(this ILogger logger, T extraKeys, EventId eventId, string message, + params object[] args) where T : class + { + Log(logger, LogLevel.Error, extraKeys, eventId, message, args); + } + + /// + /// Formats and writes an error log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogError(extraKeys, exception, "Error while processing request from {Address}", address) + public static void LogError(this ILogger logger, T extraKeys, Exception exception, string message, + params object[] args) where T : class + { + Log(logger, LogLevel.Error, extraKeys, exception, message, args); + } + + /// + /// Formats and writes an error log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogError(extraKeys, "Processing request from {Address}", address) + public static void LogError(this ILogger logger, T extraKeys, string message, params object[] args) where T : class + { + Log(logger, LogLevel.Error, extraKeys, message, args); + } + + #endregion + + #region Critical + + /// + /// Formats and writes a critical log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogCritical(extraKeys, 0, exception, "Error while processing request from {Address}", address) + public static void LogCritical(this ILogger logger, T extraKeys, EventId eventId, Exception exception, + string message, params object[] args) where T : class + { + Log(logger, LogLevel.Critical, extraKeys, eventId, exception, message, args); + } + + /// + /// Formats and writes a critical log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogCritical(extraKeys, 0, "Processing request from {Address}", address) + public static void LogCritical(this ILogger logger, T extraKeys, EventId eventId, string message, + params object[] args) where T : class + { + Log(logger, LogLevel.Critical, extraKeys, eventId, message, args); + } + + /// + /// Formats and writes a critical log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogCritical(extraKeys, exception, "Error while processing request from {Address}", address) + public static void LogCritical(this ILogger logger, T extraKeys, Exception exception, string message, + params object[] args) where T : class + { + Log(logger, LogLevel.Critical, extraKeys, exception, message, args); + } + + /// + /// Formats and writes a critical log message. + /// + /// The to write to. + /// Additional keys will be appended to the log entry. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.LogCritical(extraKeys, "Processing request from {Address}", address) + public static void LogCritical(this ILogger logger, T extraKeys, string message, params object[] args) where T : class + { + Log(logger, LogLevel.Critical, extraKeys, message, args); + } + + #endregion + + #region Log + + /// + /// Formats and writes a log message at the specified log level. + /// + /// The to write to. + /// Entry will be written on this level. + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.Log(LogLevel.Information, extraKeys, 0, exception, "Error while processing request from {Address}", address) + public static void Log(this ILogger logger, LogLevel logLevel, T extraKeys, EventId eventId, Exception exception, + string message, params object[] args) where T : class + { + if (extraKeys is not null) + using (logger.BeginScope(extraKeys)) + logger.Log(logLevel, eventId, exception, message, args); + else + logger.Log(logLevel, eventId, exception, message, args); + } + + /// + /// Formats and writes a log message at the specified log level. + /// + /// The to write to. + /// Entry will be written on this level. + /// Additional keys will be appended to the log entry. + /// The event id associated with the log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.Log(LogLevel.Information, extraKeys, 0, "Processing request from {Address}", address) + public static void Log(this ILogger logger, LogLevel logLevel, T extraKeys, EventId eventId, string message, + params object[] args) where T : class + { + Log(logger, logLevel, extraKeys, eventId, null, message, args); + } + + /// + /// Formats and writes a log message at the specified log level. + /// + /// The to write to. + /// Entry will be written on this level. + /// Additional keys will be appended to the log entry. + /// The exception to log. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.Log(LogLevel.Information, extraKeys, exception, "Error while processing request from {Address}", address) + public static void Log(this ILogger logger, LogLevel logLevel, T extraKeys, Exception exception, string message, + params object[] args) where T : class + { + Log(logger, logLevel, extraKeys, 0, exception, message, args); + } + + /// + /// Formats and writes a log message at the specified log level. + /// + /// The to write to. + /// Entry will be written on this level. + /// Additional keys will be appended to the log entry. + /// Format string of the log message in message template format. Example: "User {User} logged in from {Address}" + /// An object array that contains zero or more objects to format. + /// logger.Log(LogLevel.Information, extraKeys, "Processing request from {Address}", address) + public static void Log(this ILogger logger, LogLevel logLevel, T extraKeys, string message, params object[] args) where T : class + { + Log(logger, logLevel, extraKeys, 0, null, message, args); + } + + #endregion + + #endregion +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Logging/LoggingAttribute.cs b/libraries/src/AWS.Lambda.Powertools.Logging/LoggingAttribute.cs new file mode 100644 index 000000000..80c26aa0f --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Logging/LoggingAttribute.cs @@ -0,0 +1,139 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using AWS.Lambda.Powertools.Common; +using AWS.Lambda.Powertools.Logging.Internal; +using Microsoft.Extensions.Logging; + +namespace AWS.Lambda.Powertools.Logging; + +/// +/// Class LoggingAttribute. +/// Implements the +/// +/// +[AttributeUsage(AttributeTargets.Method)] +public class LoggingAttribute : MethodAspectAttribute +{ + /// + /// The log event + /// + private bool? _logEvent; + + /// + /// The log level + /// + private LogLevel? _logLevel; + + /// + /// The logger output case + /// + private LoggerOutputCase? _loggerOutputCase; + + /// + /// The sampling rate + /// + private double? _samplingRate; + + /// + /// Service name is used for logging. + /// This can be also set using the environment variable POWERTOOLS_SERVICE_NAME. + /// + /// The service. + public string Service { get; set; } + + /// + /// Specify the minimum log level for logging (Information, by default). + /// This can be also set using the environment variable LOG_LEVEL. + /// + /// The log level. + public LogLevel LogLevel + { + get => _logLevel ?? LoggingConstants.DefaultLogLevel; + set => _logLevel = value; + } + + /// + /// Dynamically set a percentage of logs to DEBUG level. + /// This can be also set using the environment variable POWERTOOLS_LOGGER_SAMPLE_RATE. + /// + /// The sampling rate. + public double SamplingRate + { + get => _samplingRate.GetValueOrDefault(); + set => _samplingRate = value; + } + + /// + /// Explicitly log any incoming event, The first handler parameter is the input to the handler, + /// which can be event data (published by an event source) or custom input that you provide + /// such as a string or any custom data object. + /// + /// true if [log event]; otherwise, false. + public bool LogEvent + { + get => _logEvent.GetValueOrDefault(); + set => _logEvent = value; + } + + /// + /// Pointer path to extract correlation id from input parameter. + /// The first handler parameter is the input to the handler, which can be + /// event data (published by an event source) or custom input that you provide + /// such as a string or any custom data object. + /// + /// The correlation identifier path. + public string CorrelationIdPath { get; set; } + + /// + /// Logger is commonly initialized in the global scope. + /// Due to Lambda Execution Context reuse, this means that custom keys can be persisted across invocations. + /// Set this attribute to true if you want all custom keys to be deleted on each request. + /// + /// true if [clear state]; otherwise, false. + public bool ClearState { get; set; } = false; + + /// + /// Specify output case for logging (SnakeCase, by default). + /// This can be also set using the environment variable POWERTOOLS_LOGGER_CASE. + /// + /// The log level. + public LoggerOutputCase LoggerOutputCase + { + get => _loggerOutputCase ?? LoggingConstants.DefaultLoggerOutputCase; + set => _loggerOutputCase = value; + } + + /// + /// Creates the handler. + /// + /// IMethodAspectHandler. + protected override IMethodAspectHandler CreateHandler() + { + return new LoggingAspectHandler + ( + Service, + _logLevel, + _loggerOutputCase, + _samplingRate, + _logEvent, + CorrelationIdPath, + ClearState, + PowertoolsConfigurations.Instance, + SystemWrapper.Instance + ); + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Logging/README.md b/libraries/src/AWS.Lambda.Powertools.Logging/README.md new file mode 100644 index 000000000..7d398b86b --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Logging/README.md @@ -0,0 +1,48 @@ +# AWS.Lambda.Powertools.Logging + +This package contains classes that can be used as.... + +## Sample Function + +Below is a sample class and Lambda function that illustrates how.... + +```csharp +public class Function +{ + private static readonly HttpClient client = new HttpClient(); + + [Logging(LogEvent = true, SamplingRate = 0.7)] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + try + { + var body = new Dictionary + { + { "message", "hello world" }, + { "location", location } + }; + + // Append Log Key + Logger.AppendKey("test", "willBeLogged"); + Logger.LogInformation($"log something out for inline subsegment 1"); + + Task.WaitAll(task, anotherTask); + + return new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(body), + StatusCode = 200, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + catch (Exception ex) + { + return new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(ex.Message), + StatusCode = 500, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + } +``` \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/AWS.Lambda.PowerTools.Metrics.csproj.DotSettings b/libraries/src/AWS.Lambda.Powertools.Metrics/AWS.Lambda.PowerTools.Metrics.csproj.DotSettings new file mode 100644 index 000000000..778f81dde --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/AWS.Lambda.PowerTools.Metrics.csproj.DotSettings @@ -0,0 +1,5 @@ + + True + False + True + True \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/AWS.Lambda.Powertools.Metrics.csproj b/libraries/src/AWS.Lambda.Powertools.Metrics/AWS.Lambda.Powertools.Metrics.csproj new file mode 100644 index 000000000..2175283c8 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/AWS.Lambda.Powertools.Metrics.csproj @@ -0,0 +1,39 @@ + + + net6.0 + default + AWS.Lambda.Powertools.Metrics + 0.0.1 + Amazon Web Services + Amazon.com, Inc + AWS Lambda Powertools for .NET + AWS Lambda Powertools for .NET - Metrics package. + Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + https://github.com/awslabs/aws-lambda-powertools-dotnet + Apache-2.0 + AWS;Amazon;Lambda;Powertools + README.md + AWSLogo128x128.png + true + AWS.Lambda.Powertools.Metrics + AWS.Lambda.Powertools.Metrics + + + + true + + + + + + + + + + + + + + + + diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/Exception/SchemaValidationException.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/Exception/SchemaValidationException.cs new file mode 100644 index 000000000..6ef6a4d22 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/Exception/SchemaValidationException.cs @@ -0,0 +1,44 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; + +namespace AWS.Lambda.Powertools.Metrics; + +/// +/// Class SchemaValidationException. +/// Implements the +/// +/// +[Serializable] +public class SchemaValidationException : Exception +{ + /// + /// Thrown when required property is missing on Metrics Object + /// + /// Missing property name + public SchemaValidationException(string propertyName) : base( + $"EMF schema is invalid. '{propertyName}' is mandatory and not specified.") + { + } + + /// + /// Initializes a new instance of the class. + /// + /// if set to true [raise empty metrics]. + public SchemaValidationException(bool raiseEmptyMetrics) : base("No metrics have been provided.") + { + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/IMetrics.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/IMetrics.cs new file mode 100644 index 000000000..0fc67a24e --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/IMetrics.cs @@ -0,0 +1,97 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Collections.Generic; + +namespace AWS.Lambda.Powertools.Metrics; + +/// +/// Interface IMetrics +/// Implements the +/// +/// +public interface IMetrics : IDisposable +{ + /// + /// Adds metric + /// + /// Metric key + /// Metric value + /// Metric unit + void AddMetric(string key, double value, MetricUnit unit); + + /// + /// Adds a dimension + /// + /// Dimension key + /// Dimension value + void AddDimension(string key, string value); + + /// + /// Sets the default dimensions + /// + /// Default dimensions + void SetDefaultDimensions(Dictionary defaultDimension); + + /// + /// Adds metadata + /// + /// Metadata key + /// Metadata value + void AddMetadata(string key, object value); + + /// + /// Pushes a single metric with custom namespace, service and dimensions. + /// + /// Name of the metric + /// Metric value + /// Metric unit + /// Metric namespace + /// Metric service + /// Metric default dimensions + void PushSingleMetric(string metricName, double value, MetricUnit unit, string nameSpace = null, + string service = null, Dictionary defaultDimensions = null); + + /// + /// Sets the namespace + /// + /// Metrics namespace + void SetNamespace(string nameSpace); + + /// + /// Gets the namespace + /// + /// System.String. + string GetNamespace(); + + /// + /// Gets the service + /// + /// System.String. + string GetService(); + + /// + /// Serializes metrics instance + /// + /// System.String. + string Serialize(); + + /// + /// Flushes metrics to CloudWatch + /// + /// if set to true [metrics overflow]. + void Flush(bool metricsOverflow = false); +} diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/Internal/MetricsAspectHandler.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/Internal/MetricsAspectHandler.cs new file mode 100644 index 000000000..da851e67f --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/Internal/MetricsAspectHandler.cs @@ -0,0 +1,140 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Collections.Generic; +using AWS.Lambda.Powertools.Common; + +namespace AWS.Lambda.Powertools.Metrics; + +/// +/// Class MetricsAspectHandler. +/// Implements the +/// +/// +internal class MetricsAspectHandler : IMethodAspectHandler +{ + /// + /// The is cold start + /// + private static bool _isColdStart = true; + + /// + /// The capture cold start enabled + /// + private readonly bool _captureColdStartEnabled; + + /// + /// The metrics + /// + private readonly IMetrics _metrics; + + /// + /// Specify to clear Lambda Context on exit + /// + private bool _clearLambdaContext; + + /// + /// Creates MetricsAspectHandler to supports running code before and after marked methods. + /// + /// AWS.Lambda.Powertools.Metrics Instance + /// If 'true', captures cold start during Lambda execution + internal MetricsAspectHandler + ( + IMetrics metricsInstance, + bool captureColdStartEnabled + ) + { + _metrics = metricsInstance; + _captureColdStartEnabled = captureColdStartEnabled; + } + + /// + /// OnExit runs after the execution of the method marked with the Metrics Attribute + /// + /// Aspect Arguments + public void OnExit(AspectEventArgs eventArgs) + { + _metrics.Flush(); + if (_clearLambdaContext) + PowertoolsLambdaContext.Clear(); + } + + /// + /// OnEntry runs before the execution of the method marked with the Metrics Attribute + /// + /// Aspect Arguments + public void OnEntry(AspectEventArgs eventArgs) + { + if (!_isColdStart || !_captureColdStartEnabled) return; + + var nameSpace = _metrics.GetNamespace(); + var service = _metrics.GetService(); + Dictionary dimensions = null; + + _clearLambdaContext = PowertoolsLambdaContext.Extract(eventArgs); + + if (PowertoolsLambdaContext.Instance is not null) + { + dimensions = new Dictionary + { + {"FunctionName", PowertoolsLambdaContext.Instance.FunctionName} + }; + } + + _metrics.PushSingleMetric( + "ColdStart", + 1.0, + MetricUnit.Count, + nameSpace, + service, + dimensions + ); + + _isColdStart = false; + } + + /// + /// OnSuccess run after successful execution of the method marked with the Metrics Attribute + /// + /// Aspect Arguments + /// Object returned by the method marked with Metrics Attribute + public void OnSuccess(AspectEventArgs eventArgs, object result) + { + } + + /// + /// OnException runs when an unhandled exception occurs inside the method marked with the Metrics Attribute + /// + /// Type of Exception expected + /// Aspect Arguments + /// Exception thrown by the method marked with Metrics Attribute + /// Type of the Exception expected + /// Generic unhandled exception + public T OnException(AspectEventArgs eventArgs, Exception exception) + { + throw exception; + } + + /// + /// Helper method for testing purposes. Clears static instance between test execution + /// + internal void ResetForTest() + { + _isColdStart = true; + Metrics.ResetForTest(); + PowertoolsLambdaContext.Clear(); + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/InternalsVisibleTo.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/InternalsVisibleTo.cs new file mode 100644 index 000000000..0e44da1ca --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/InternalsVisibleTo.cs @@ -0,0 +1,18 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("AWS.Lambda.Powertools.Metrics.Tests")] \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/Metrics.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/Metrics.cs new file mode 100644 index 000000000..d0e9975b8 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/Metrics.cs @@ -0,0 +1,388 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Collections.Generic; +using AWS.Lambda.Powertools.Common; + +namespace AWS.Lambda.Powertools.Metrics; + +/// +/// Class Metrics. +/// Implements the +/// +/// +public class Metrics : IMetrics +{ + /// + /// The instance + /// + private static IMetrics _instance; + + /// + /// The context + /// + private readonly MetricsContext _context; + + /// + /// The Powertools configurations + /// + private readonly IPowertoolsConfigurations _powertoolsConfigurations; + + /// + /// If true, Powertools will throw an exception on empty metrics when trying to flush + /// + private readonly bool _raiseOnEmptyMetrics; + + /// + /// Creates a Metrics object that provides features to send metrics to Amazon Cloudwatch using the Embedded metric + /// format (EMF). See + /// https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html + /// + /// Lambda Powertools Configuration + /// Metrics Namespace Identifier + /// Metrics Service Name + /// Instructs metrics validation to throw exception if no metrics are provided + internal Metrics(IPowertoolsConfigurations powertoolsConfigurations, string nameSpace = null, string service = null, + bool raiseOnEmptyMetrics = false) + { + if (_instance != null) return; + + _instance = this; + _powertoolsConfigurations = powertoolsConfigurations; + _raiseOnEmptyMetrics = raiseOnEmptyMetrics; + _context = InitializeContext(nameSpace, service, null); + } + + /// + /// Implements interface that adds new metric to memory. + /// + /// Metric Key + /// Metric Value + /// Metric Unit + /// + /// 'AddMetric' method requires a valid metrics key. 'Null' or empty values + /// are not allowed. + /// + void IMetrics.AddMetric(string key, double value, MetricUnit unit) + { + if (string.IsNullOrWhiteSpace(key)) + throw new ArgumentNullException( + "'AddMetric' method requires a valid metrics key. 'Null' or empty values are not allowed."); + + if (value < 0) { + throw new ArgumentException( + "'AddMetric' method requires a valid metrics value. Value must be >= 0."); + } + + if (_context.GetMetrics().Count == 100) _instance.Flush(true); + + _context.AddMetric(key, value, unit); + } + + /// + /// Implements interface that sets metrics namespace identifier. + /// + /// Metrics Namespace Identifier + void IMetrics.SetNamespace(string nameSpace) + { + _context.SetNamespace(nameSpace); + } + + /// + /// Implements interface that allows retrieval of namespace identifier. + /// + /// Namespace identifier + string IMetrics.GetNamespace() + { + return _context.GetNamespace(); + } + + /// + /// Implements interface to get service name + /// + /// System.String. + string IMetrics.GetService() + { + return _context.GetService(); + } + + /// + /// Implements interface that adds a dimension. + /// + /// Dimension key. Must not be null, empty or whitespace + /// Dimension value + /// + /// 'AddDimension' method requires a valid dimension key. 'Null' or empty + /// values are not allowed. + /// + void IMetrics.AddDimension(string key, string value) + { + if (string.IsNullOrWhiteSpace(key)) + throw new ArgumentNullException( + "'AddDimension' method requires a valid dimension key. 'Null' or empty values are not allowed."); + + _context.AddDimension(key, value); + } + + /// + /// Implements interface that adds metadata. + /// + /// Metadata key. Must not be null, empty or whitespace + /// Metadata value + /// + /// 'AddMetadata' method requires a valid metadata key. 'Null' or empty + /// values are not allowed. + /// + void IMetrics.AddMetadata(string key, object value) + { + if (string.IsNullOrWhiteSpace(key)) + throw new ArgumentNullException( + "'AddMetadata' method requires a valid metadata key. 'Null' or empty values are not allowed."); + + _context.AddMetadata(key, value); + } + + /// + /// Implements interface that sets default dimension list + /// + /// Default Dimension List + /// + /// 'SetDefaultDimensions' method requires a valid key pair. 'Null' or empty + /// values are not allowed. + /// + void IMetrics.SetDefaultDimensions(Dictionary defaultDimensions) + { + foreach (var item in defaultDimensions) + if (string.IsNullOrWhiteSpace(item.Key) || string.IsNullOrWhiteSpace(item.Value)) + throw new ArgumentNullException( + "'SetDefaultDimensions' method requires a valid key pair. 'Null' or empty values are not allowed."); + + _context.SetDefaultDimensions(DictionaryToList(defaultDimensions)); + } + + /// + /// Flushes metrics in Embedded Metric Format (EMF) to Standard Output. In Lambda, this output is collected + /// automatically and sent to Cloudwatch. + /// + /// If enabled, non-default dimensions are cleared after flushing metrics + /// true + void IMetrics.Flush(bool metricsOverflow) + { + if (_context.GetMetrics().Count == 0 + && _raiseOnEmptyMetrics) + throw new SchemaValidationException(true); + + if (_context.IsSerializable) + { + var emfPayload = _context.Serialize(); + + Console.WriteLine(emfPayload); + + _context.ClearMetrics(); + + if (!metricsOverflow) _context.ClearNonDefaultDimensions(); + } + else + { + Console.WriteLine( + "##WARNING## Metrics and Metadata have not been specified. No data will be sent to Cloudwatch Metrics."); + } + } + + /// + /// Serialize global context object + /// + /// Serialized global context object + public string Serialize() + { + return _context.Serialize(); + } + + /// + /// Implements the interface that pushes single metric to CloudWatch using Embedded Metric Format. This can be used to + /// push metrics with a different context. + /// + /// Metric Name. Metric key cannot be null, empty or whitespace + /// Metric Value + /// Metric Unit + /// Metric Namespace + /// Service Name + /// Default dimensions list + /// + /// 'PushSingleMetric' method requires a valid metrics key. 'Null' or empty + /// values are not allowed. + /// + void IMetrics.PushSingleMetric(string metricName, double value, MetricUnit unit, string nameSpace, string service, + Dictionary defaultDimensions) + { + if (string.IsNullOrWhiteSpace(metricName)) + throw new ArgumentNullException( + "'PushSingleMetric' method requires a valid metrics key. 'Null' or empty values are not allowed."); + + using var context = InitializeContext(nameSpace, service, defaultDimensions); + context.AddMetric(metricName, value, unit); + + Flush(context); + } + + /// + /// Implementation of IDisposable interface + /// + public void Dispose() + { + _instance.Flush(); + } + + /// + /// Adds new metric to memory. + /// + /// Metric Key. Must not be null, empty or whitespace + /// Metric Value + /// Metric Unit + public static void AddMetric(string key, double value, MetricUnit unit = MetricUnit.None) + { + _instance.AddMetric(key, value, unit); + } + + /// + /// Sets metrics namespace identifier. + /// + /// Metrics Namespace Identifier + public static void SetNamespace(string nameSpace) + { + _instance.SetNamespace(nameSpace); + } + + /// + /// Retrieves namespace identifier. + /// + /// Namespace identifier + public static string GetNamespace() + { + return _instance.GetNamespace(); + } + + /// + /// Adds new dimension to memory. + /// + /// Dimension key. Must not be null, empty or whitespace. + /// Dimension value + public static void AddDimension(string key, string value) + { + _instance.AddDimension(key, value); + } + + /// + /// Adds metadata to memory. + /// + /// Metadata key. Must not be null, empty or whitespace + /// Metadata value + public static void AddMetadata(string key, object value) + { + _instance.AddMetadata(key, value); + } + + /// + /// Set default dimension list + /// + /// Default Dimension List + public static void SetDefaultDimensions(Dictionary defaultDimensions) + { + _instance.SetDefaultDimensions(defaultDimensions); + } + + /// + /// Flushes metrics in Embedded Metric Format (EMF) to Standard Output. In Lambda, this output is collected + /// automatically and sent to Cloudwatch. + /// + /// If context is provided it is serialized instead of the global context object + private void Flush(MetricsContext context) + { + var emfPayload = context.Serialize(); + + Console.WriteLine(emfPayload); + } + + /// + /// Pushes single metric to CloudWatch using Embedded Metric Format. This can be used to push metrics with a different + /// context. + /// + /// Metric Name. Metric key cannot be null, empty or whitespace + /// Metric Value + /// Metric Unit + /// Metric Namespace + /// Service Name + /// Default dimensions list + public static void PushSingleMetric(string metricName, double value, MetricUnit unit, string nameSpace = null, + string service = null, Dictionary defaultDimensions = null) + { + _instance.PushSingleMetric(metricName, value, unit, nameSpace, service, defaultDimensions); + } + + /// + /// Sets global namespace, service name and default dimensions list. Service name is automatically added as a default + /// dimension + /// + /// Metrics namespace + /// Service Name + /// Default Dimensions List + /// MetricsContext. + private MetricsContext InitializeContext(string nameSpace, string service, + Dictionary defaultDimensions) + { + var context = new MetricsContext(); + + context.SetNamespace(!string.IsNullOrWhiteSpace(nameSpace) + ? nameSpace + : _powertoolsConfigurations.MetricsNamespace); + + context.SetService(!string.IsNullOrWhiteSpace(service) + ? service + : _powertoolsConfigurations.Service); + + var defaultDimensionsList = DictionaryToList(defaultDimensions); + + // Add service as a default dimension + defaultDimensionsList.Add(new DimensionSet("Service", context.GetService())); + + context.SetDefaultDimensions(defaultDimensionsList); + + return context; + } + + /// + /// Helper method to convert default dimensions dictionary to list + /// + /// Default dimensions dictionary + /// Default dimensions list + private List DictionaryToList(Dictionary defaultDimensions) + { + var defaultDimensionsList = new List(); + if (defaultDimensions != null) + foreach (var item in defaultDimensions) + defaultDimensionsList.Add(new DimensionSet(item.Key, item.Value)); + + return defaultDimensionsList; + } + + /// + /// Helper method for testing purposes. Clears static instance between test execution + /// + internal static void ResetForTest() + { + _instance = null; + } +} diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/MetricsAttribute.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/MetricsAttribute.cs new file mode 100644 index 000000000..ce0bde4dd --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/MetricsAttribute.cs @@ -0,0 +1,84 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using AWS.Lambda.Powertools.Common; + +namespace AWS.Lambda.Powertools.Metrics; + +/// +/// Class MetricsAttribute. +/// Implements the +/// +/// +[AttributeUsage(AttributeTargets.Method)] +public class MetricsAttribute : MethodAspectAttribute +{ + /// + /// The metrics instance + /// + private IMetrics _metricsInstance; + + /// + /// Set namespace. + /// The default is the environment variable POWERTOOLS_METRICS_NAMESPACE. + /// + /// The namespace. + public string Namespace { get; set; } + + /// + /// Service name is used for metric dimension across all metrics. + /// This can be also set using the environment variable POWERTOOLS_SERVICE_NAME. + /// + /// The service. + public string Service { get; set; } + + /// + /// Captures cold start during Lambda execution + /// + /// true if [capture cold start]; otherwise, false. + public bool CaptureColdStart { get; set; } + + /// + /// Instructs metrics validation to throw exception if no metrics are provided. + /// + /// true if [raise on empty metrics]; otherwise, false. + public bool RaiseOnEmptyMetrics { get; set; } + + /// + /// Gets the metrics instance. + /// + /// The metrics instance. + private IMetrics MetricsInstance => + _metricsInstance ??= new Metrics( + PowertoolsConfigurations.Instance, + Namespace, + Service, + RaiseOnEmptyMetrics + ); + + /// + /// Creates the handler. + /// + /// IMethodAspectHandler. + protected override IMethodAspectHandler CreateHandler() + { + return new MetricsAspectHandler + ( + MetricsInstance, + CaptureColdStart + ); + } +} diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/Model/DimensionSet.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/Model/DimensionSet.cs new file mode 100644 index 000000000..6c1e2d754 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/Model/DimensionSet.cs @@ -0,0 +1,47 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System.Collections.Generic; +using System.Linq; + +namespace AWS.Lambda.Powertools.Metrics; + +/// +/// List of key-value pairs with Metric Dimensions +/// +public class DimensionSet +{ + /// + /// Initializes a new instance of the class. + /// + /// The key. + /// The value. + public DimensionSet(string key, string value) + { + Dimensions[key] = value; + } + + /// + /// Gets the dimensions. + /// + /// The dimensions. + internal Dictionary Dimensions { get; } = new(); + + /// + /// Gets the dimension keys. + /// + /// The dimension keys. + public List DimensionKeys => Dimensions.Keys.ToList(); +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/Model/Metadata.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/Model/Metadata.cs new file mode 100644 index 000000000..2b711a7c8 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/Model/Metadata.cs @@ -0,0 +1,178 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Text.Json.Serialization; + +namespace AWS.Lambda.Powertools.Metrics; + +/// +/// Class Metadata. +/// +public class Metadata +{ + /// + /// Create Metadata object + /// + public Metadata() + { + CloudWatchMetrics = new List {new()}; + Timestamp = DateTime.Now; + CustomMetadata = new Dictionary(); + } + + /// + /// Gets the timestamp. + /// + /// The timestamp. + [JsonConverter(typeof(UnixMillisecondDateTimeConverter))] + public DateTime Timestamp { get; } + + /// + /// Gets the cloud watch metrics. + /// + /// The cloud watch metrics. + [JsonPropertyName(nameof(CloudWatchMetrics))] + public List CloudWatchMetrics { get; } + + /// + /// Gets the metric directive. + /// + /// The metric directive. + private MetricDirective _metricDirective => CloudWatchMetrics[0]; + + /// + /// Gets the custom metadata. + /// + /// The custom metadata. + [JsonIgnore] + public Dictionary CustomMetadata { get; } + + /// + /// Deletes all metrics from memory + /// + internal void ClearMetrics() + { + _metricDirective.Metrics.Clear(); + } + + /// + /// Deletes non-default dimensions from memory + /// + internal void ClearNonDefaultDimensions() + { + _metricDirective.Dimensions.Clear(); + } + + /// + /// Adds metric to memory + /// + /// Metric key. Cannot be null, empty or whitespace + /// Metric value + /// Metric Unit + internal void AddMetric(string key, double value, MetricUnit unit) + { + _metricDirective.AddMetric(key, value, unit); + } + + /// + /// Sets global metrics namespace + /// + /// Global metrics namespace + internal void SetNamespace(string metricNamespace) + { + _metricDirective.SetNamespace(metricNamespace); + } + + /// + /// Retrieves global namespace identifier + /// + /// Global namespace identifier + internal string GetNamespace() + { + return _metricDirective.Namespace; + } + + /// + /// Sets service name + /// + /// Service name + internal void SetService(string service) + { + _metricDirective.SetService(service); + } + + /// + /// Retrieves service name + /// + /// Service name + internal string GetService() + { + return _metricDirective.Service; + } + + /// + /// Adds new Dimension + /// + /// Dimension to add + internal void AddDimensionSet(DimensionSet dimension) + { + _metricDirective.AddDimension(dimension); + } + + /// + /// Sets default dimensions list + /// + /// Default dimensions list + internal void SetDefaultDimensions(List defaultDimensionSets) + { + _metricDirective.SetDefaultDimensions(defaultDimensionSets); + } + + /// + /// Retrieves metrics stored in memory + /// + /// List of metrics stored in memory + internal List GetMetrics() + { + return _metricDirective.Metrics; + } + + /// + /// Adds metadata to memory + /// + /// Metadata key. Cannot be null, empty or whitespace + /// Metadata value + internal void AddMetadata(string key, object value) + { + CustomMetadata.Add(key, value); + } + + /// + /// Creates Dictionary with all Dimensions. Needed for correct EMF payload serialization + /// + /// Dictionary with all dimensions + internal Dictionary ExpandAllDimensionSets() + { + Dictionary dimensionSets; + if (CloudWatchMetrics.Count > 0) + dimensionSets = _metricDirective.ExpandAllDimensionSets(); + else + dimensionSets = new Dictionary(); + + return dimensionSets; + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/Model/MetricDefinition.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/Model/MetricDefinition.cs new file mode 100644 index 000000000..bd26f90f0 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/Model/MetricDefinition.cs @@ -0,0 +1,87 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System.Collections.Generic; +using System.Text.Json.Serialization; + +namespace AWS.Lambda.Powertools.Metrics; + +/// +/// Class MetricDefinition. +/// +public class MetricDefinition +{ + /// + /// Creates a MetricDefinition object. MetricUnit is set to NONE since it is not provided. + /// + /// Metric name + /// Metric value + public MetricDefinition(string name, double value) : this(name, MetricUnit.None, new List {value}) + { + } + + /// + /// Creates a MetricDefinition object + /// + /// Metric name + /// Metric unit + /// Metric value + public MetricDefinition(string name, MetricUnit unit, double value) : this(name, unit, new List {value}) + { + } + + /// + /// Creates a MetricDefinition object with multiple values + /// + /// Metric name + /// Metric unit + /// List of metric values + public MetricDefinition(string name, MetricUnit unit, List values) + { + Name = name; + Unit = unit; + Values = values; + } + + /// + /// Gets or sets the name. + /// + /// The name. + [JsonPropertyName(nameof(Name))] + public string Name { get; set; } + + /// + /// Gets the values. + /// + /// The values. + [JsonIgnore] + public List Values { get; } + + /// + /// Gets or sets the unit. + /// + /// The unit. + [JsonPropertyName(nameof(Unit))] + public MetricUnit Unit { get; set; } + + /// + /// Adds value to existing metric with same key + /// + /// Metric value to add to existing key + public void AddValue(double value) + { + Values.Add(value); + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/Model/MetricDirective.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/Model/MetricDirective.cs new file mode 100644 index 000000000..aa5faaddd --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/Model/MetricDirective.cs @@ -0,0 +1,227 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json.Serialization; +using AWS.Lambda.Powertools.Common; + +namespace AWS.Lambda.Powertools.Metrics; + +/// +/// Class MetricDirective. +/// +public class MetricDirective +{ + /// + /// Creates empty MetricDirective object + /// + public MetricDirective() : this(null, new List(), new List()) + { + } + + /// + /// Creates MetricDirective object with specific namespace identifier + /// + /// Metrics namespace identifier + public MetricDirective(string nameSpace) : this(nameSpace, new List(), new List()) + { + } + + /// + /// Creates MetricDirective object with specific namespace identifier and default dimensions list + /// + /// Metrics namespace identifier + /// Default dimensions list + public MetricDirective(string nameSpace, List defaultDimensions) : this(nameSpace, + new List(), defaultDimensions) + { + } + + /// + /// Creates MetricDirective object with specific namespace identifier, list of metrics and default dimensions list + /// + /// Metrics namespace identifier + /// List of metrics + /// Default dimensions list + private MetricDirective(string nameSpace, List metrics, List defaultDimensions) + { + Namespace = nameSpace; + Metrics = metrics; + Dimensions = new List(); + DefaultDimensions = defaultDimensions; + } + + /// + /// Gets the namespace. + /// + /// The namespace. + [JsonPropertyName(nameof(Namespace))] + public string Namespace { get; private set; } + + /// + /// Gets the service. + /// + /// The service. + [JsonIgnore] + public string Service { get; private set; } + + /// + /// Gets the metrics. + /// + /// The metrics. + [JsonPropertyName(nameof(Metrics))] + public List Metrics { get; private set; } + + /// + /// Gets the dimensions. + /// + /// The dimensions. + [JsonIgnore] + public List Dimensions { get; private set; } + + /// + /// Gets the default dimensions. + /// + /// The default dimensions. + [JsonIgnore] + public List DefaultDimensions { get; private set; } + + /// + /// Creates list with all dimensions. Needed for correct EMF payload creation + /// + /// All dimension keys. + [JsonPropertyName("Dimensions")] + public List> AllDimensionKeys + { + get + { + var defaultKeys = DefaultDimensions + .Where(d => d.DimensionKeys.Any()) + .Select(s => s.DimensionKeys) + .ToList(); + + var keys = Dimensions + .Where(d => d.DimensionKeys.Any()) + .Select(s => s.DimensionKeys) + .ToList(); + + defaultKeys.AddRange(keys); + + if (defaultKeys.Count == 0) defaultKeys.Add(new List()); + + return defaultKeys; + } + } + + /// + /// Adds metric to memory + /// + /// Metric name. Cannot be null, empty or whitespace + /// Metric value + /// Metric unit + /// Metrics - Cannot add more than 100 metrics at the same time. + public void AddMetric(string name, double value, MetricUnit unit) + { + if (Metrics.Count < PowertoolsConfigurations.MaxMetrics) + { + var metric = Metrics.FirstOrDefault(m => m.Name == name); + if (metric != null) + metric.AddValue(value); + else + Metrics.Add(new MetricDefinition(name, unit, value)); + } + else + { + throw new ArgumentOutOfRangeException(nameof(Metrics), + "Cannot add more than 100 metrics at the same time."); + } + } + + /// + /// Sets metrics namespace identifier + /// + /// Metrics namespace identifier + internal void SetNamespace(string nameSpace) + { + Namespace = nameSpace; + } + + /// + /// Sets service name + /// + /// Service name + internal void SetService(string service) + { + Service = service; + } + + /// + /// Adds new dimension to memory + /// + /// Metrics Dimension + /// Dimensions - Cannot add more than 9 dimensions at the same time. + internal void AddDimension(DimensionSet dimension) + { + if (Dimensions.Count < PowertoolsConfigurations.MaxDimensions) + { + var matchingKeys = AllDimensionKeys.Where(x => x.Contains(dimension.DimensionKeys[0])); + if (!matchingKeys.Any()) + Dimensions.Add(dimension); + else + Console.WriteLine( + $"##WARNING##: Failed to Add dimension '{dimension.DimensionKeys[0]}'. Dimension already exists."); + } + else + { + throw new ArgumentOutOfRangeException(nameof(Dimensions), + "Cannot add more than 9 dimensions at the same time."); + } + } + + /// + /// Sets default dimensions + /// + /// Default dimensions list + internal void SetDefaultDimensions(List defaultDimensions) + { + if (!DefaultDimensions.Any()) + DefaultDimensions = defaultDimensions; + else + foreach (var item in defaultDimensions) + if (!DefaultDimensions.Any(d => d.DimensionKeys.Contains(item.DimensionKeys[0]))) + DefaultDimensions.Add(item); + } + + /// + /// Appends dimension and default dimension lists + /// + /// Dictionary with dimension and default dimension list appended + internal Dictionary ExpandAllDimensionSets() + { + var dimensions = new Dictionary(); + + foreach (var dimensionSet in DefaultDimensions) + foreach (var (key, value) in dimensionSet.Dimensions) + dimensions.TryAdd(key, value); + + foreach (var dimensionSet in Dimensions) + foreach (var (key, value) in dimensionSet.Dimensions) + dimensions.TryAdd(key, value); + + return dimensions; + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/Model/MetricUnit.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/Model/MetricUnit.cs new file mode 100644 index 000000000..fd4b97602 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/Model/MetricUnit.cs @@ -0,0 +1,169 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace AWS.Lambda.Powertools.Metrics; + +/// +/// Enum MetricUnit +/// +[JsonConverter(typeof(StringEnumConverter))] +public enum MetricUnit +{ + /// + /// Metrics unit none + /// + [EnumMember(Value = "None")] None, + + /// + /// Metrics unit in seconds + /// + [EnumMember(Value = "Seconds")] Seconds, + + /// + /// Metrics unit in microseconds + /// + [EnumMember(Value = "Microseconds")] Microseconds, + + /// + /// Metrics unit in milliseconds + /// + [EnumMember(Value = "Milliseconds")] Milliseconds, + + /// + /// Metrics unit in bytes + /// + [EnumMember(Value = "Bytes")] Bytes, + + /// + /// Metrics unit in kilobytes + /// + [EnumMember(Value = "Kilobytes")] Kilobytes, + + /// + /// Metrics unit in megabytes + /// + [EnumMember(Value = "Megabytes")] Megabytes, + + /// + /// Metrics unit in gigabytes + /// + [EnumMember(Value = "Gigabytes")] Gigabytes, + + /// + /// Metrics unit in terabytes + /// + [EnumMember(Value = "Terabytes")] Terabytes, + + /// + /// Metrics unit in bits + /// + [EnumMember(Value = "Bits")] Bits, + + /// + /// Metrics unit in kilobits + /// + [EnumMember(Value = "Kilobits")] Kilobits, + + /// + /// Metrics unit in megabits + /// + [EnumMember(Value = "Megabits")] Megabits, + + /// + /// Metrics unit in gigabits + /// + [EnumMember(Value = "Gigabits")] Gigabits, + + /// + /// Metrics unit in terabits + /// + [EnumMember(Value = "Terabits")] Terabits, + + /// + /// Metrics unit in percent + /// + [EnumMember(Value = "Percent")] Percent, + + /// + /// Metrics unit count + /// + [EnumMember(Value = "Count")] Count, + + /// + /// Metrics unit in bytes per second + /// + [EnumMember(Value = "Bytes/Second")] BytesPerSecond, + + /// + /// Metrics unit in kilobytes per second + /// + [EnumMember(Value = "Kilobytes/Second")] + KilobytesPerSecond, + + /// + /// Metrics unit in megabytes per second + /// + [EnumMember(Value = "Megabytes/Second")] + MegabytesPerSecond, + + /// + /// Metrics unit in gigabytes per second + /// + [EnumMember(Value = "Gigabytes/Second")] + GigabytesPerSecond, + + /// + /// Metrics unit in terabytes per second + /// + [EnumMember(Value = "Terabytes/Second")] + TerabytesPerSecond, + + /// + /// Metrics unit in bits per second + /// + [EnumMember(Value = "Bits/Second")] BitsPerSecond, + + /// + /// Metrics unit in kilobits per second + /// + [EnumMember(Value = "Kilobits/Second")] + KilobitsPerSecond, + + /// + /// Metrics unit in megabits per second + /// + [EnumMember(Value = "Megabits/Second")] + MegabitsPerSecond, + + /// + /// Metrics unit in gigabits per second + /// + [EnumMember(Value = "Gigabits/Second")] + GigabitsPerSecond, + + /// + /// Metrics unit in terabits per second + /// + [EnumMember(Value = "Terabits/Second")] + TerabitsPerSecond, + + /// + /// Metrics unit in count per second + /// + [EnumMember(Value = "Count/Second")] CountPerSecond +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/Model/MetricsContext.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/Model/MetricsContext.cs new file mode 100644 index 000000000..8206d099f --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/Model/MetricsContext.cs @@ -0,0 +1,164 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Collections.Generic; + +namespace AWS.Lambda.Powertools.Metrics; + +/// +/// Class MetricsContext. +/// Implements the +/// +/// +public class MetricsContext : IDisposable +{ + /// + /// The root node + /// + private RootNode _rootNode; + + /// + /// Creates empty MetricsContext object + /// + public MetricsContext() + { + _rootNode = new RootNode(); + } + + /// + /// Gets a value indicating whether this instance is serializable. + /// + /// true if this instance is serializable; otherwise, false. + internal bool IsSerializable => !(GetMetrics().Count == 0 && _rootNode.AWS.CustomMetadata.Count == 0); + + /// + /// Implements IDisposable interface + /// + public void Dispose() + { + _rootNode = null; + } + + /// + /// Retrieves all metrics stored in memory + /// + /// List of Metrics + public List GetMetrics() + { + return _rootNode.AWS.GetMetrics(); + } + + /// + /// Clears all metrics from memory + /// + public void ClearMetrics() + { + _rootNode.AWS.ClearMetrics(); + } + + /// + /// Clears non-default dimensions from memory + /// + internal void ClearNonDefaultDimensions() + { + _rootNode.AWS.ClearNonDefaultDimensions(); + } + + /// + /// Adds Metric to memory + /// + /// Metric key. Cannot be null, empty or whitespace + /// Metric value + /// Metric unit + public void AddMetric(string key, double value, MetricUnit unit) + { + _rootNode.AWS.AddMetric(key, value, unit); + } + + /// + /// Sets metrics namespace identifier + /// + /// Metrics namespace identifier + public void SetNamespace(string metricNamespace) + { + _rootNode.AWS.SetNamespace(metricNamespace); + } + + /// + /// Retrieves metrics namespace identifier from memory + /// + /// Metrics namespace identifier + internal string GetNamespace() + { + return _rootNode.AWS.GetNamespace(); + } + + /// + /// Sets service name identifier + /// + /// Service name + public void SetService(string service) + { + _rootNode.AWS.SetService(service); + } + + /// + /// Retrieves service name from memory + /// + /// Service name + internal string GetService() + { + return _rootNode.AWS.GetService(); + } + + /// + /// Adds new dimension to memory + /// + /// Dimension key. Cannot be null, empty or whitespace + /// Dimension value + public void AddDimension(string key, string value) + { + _rootNode.AWS.AddDimensionSet(new DimensionSet(key, value)); + } + + /// + /// Sets default dimensions list + /// + /// Default dimensions list + public void SetDefaultDimensions(List defaultDimensions) + { + _rootNode.AWS.SetDefaultDimensions(defaultDimensions); + } + + /// + /// Adds metadata to memory + /// + /// Metadata key + /// Metadata value + public void AddMetadata(string key, object value) + { + _rootNode.AWS.AddMetadata(key, value); + } + + /// + /// Serializes metrics object to string using Embedded Metric Format (EMF) + /// + /// String object representing all metrics in memory + public string Serialize() + { + return _rootNode.Serialize(); + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/Model/RootNode.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/Model/RootNode.cs new file mode 100644 index 000000000..f386f32a7 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/Model/RootNode.cs @@ -0,0 +1,70 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System.Collections.Generic; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace AWS.Lambda.Powertools.Metrics; + +/// +/// Class RootNode. +/// +public class RootNode +{ + /// + /// Gets the aws. + /// + /// The aws. + [JsonPropertyName("_aws")] + public Metadata AWS { get; } = new(); + + /// + /// Gets the metric data. + /// + /// The metric data. + [JsonExtensionData] + public Dictionary MetricData + { + get + { + var targetMembers = new Dictionary(); + + foreach (var dimension in AWS.ExpandAllDimensionSets()) targetMembers.Add(dimension.Key, dimension.Value); + + foreach (var metadata in AWS.CustomMetadata) targetMembers.Add(metadata.Key, metadata.Value); + + foreach (var metricDefinition in AWS.GetMetrics()) + { + var values = metricDefinition.Values; + targetMembers.Add(metricDefinition.Name, values.Count == 1 ? values[0] : values); + } + + return targetMembers; + } + } + + /// + /// Serializes metrics object to a valid string in JSON format + /// + /// JSON EMF payload in string format + /// namespace + public string Serialize() + { + if (string.IsNullOrWhiteSpace(AWS.GetNamespace())) throw new SchemaValidationException("namespace"); + + return JsonSerializer.Serialize(this); + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/README.md b/libraries/src/AWS.Lambda.Powertools.Metrics/README.md new file mode 100644 index 000000000..8aaf6dab7 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/README.md @@ -0,0 +1,302 @@ +# AWS.Lambda.Powertools.Metrics + +The `AWS.Lambda.Powertools.Metrics` package is part of **AWS Lambda Powertools for .NET** and allows developers to collect metrics from AWS Lambda functions according to best practices. + +The `Metrics` utility captures metrics by using [Embedded Metrics Format (EMF)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html) specification. EMF is a JSON specification that allows CloudWatch to automatically extract metric values embedded in structured event logs. With this approach, your metrics collection process becomes very efficient as it isn't performed on the AWS Lambda function but instead, performed on CloudWatch. + +## Examples + +**AWS Lambda Powertools for .NET** uses an `Aspect` oriented approach by enabling developers to use `Attributes` to inject a static `Metrics` object to be used for metrics collection. + +This optimizes developer experience by reducing repetition for utility object initialization. + +Below are some implementation examples: + +### Metrics initialization + +The [EMF](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html) specification requires that `namespace` and `service name` properties are provided. In our implementation we enforce developers to define the namespace in *code* or as an *environment variable*. + +> If you want these properties to be easily updated you should have them as environment variables + +If using [SAM](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) just add the following environment variables to your `template.yaml` file. +```yaml +... + Environment: + Variables: + POWERTOOLS_SERVICE_NAME: [YOUR-SERVICE-NAME] + POWERTOOLS_METRICS_NAMESPACE: [YOUR_NAMESPACE] +... +``` + +Once your environment variables are defined you can initialize your `Metrics` object without parameters. + +```csharp +public class Function +{ + [Metrics()] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + try + { + // Add Metrics + var watch = Stopwatch.StartNew(); + var location = await GetCallingIP(); + watch.Stop(); + + Metrics.AddMetric("ElapsedExecutionTime", watch.ElapsedMilliseconds, MetricUnit.Milliseconds); + Metrics.AddMetric("SuccessfulLocations", 1, MetricUnit.Count); + + var body = new Dictionary + { + { "message", "sample metrics" }, + { "location", location } + }; + + return new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(body), + StatusCode = 200, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + catch (Exception ex) + { + return new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(ex.Message), + StatusCode = 500, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + } +} +``` + +### Override metrics namespace and Service name + +As mentioned before, metrics `namespace` and `service name` can be provided as environment variables. Still you can override them in code during initialization. + +```csharp +public class Function +{ + [Metrics(Namespace = "dotnet-lambdapowertools", Service = "lambda-example")] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + try + { + // Add Metrics + var watch = Stopwatch.StartNew(); + var location = await GetCallingIP(); + watch.Stop(); + + Metrics.AddMetric("ElapsedExecutionTime", watch.ElapsedMilliseconds, MetricUnit.Milliseconds); + Metrics.AddMetric("SuccessfulLocations", 1, MetricUnit.Count); + + var body = new Dictionary + { + { "message", "sample metrics" }, + { "location", location } + }; + + return new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(body), + StatusCode = 200, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + catch (Exception ex) + { + return new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(ex.Message), + StatusCode = 500, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + } +} +``` + +### Capture Cold Starts + +`Metrics` utility can be configured to capture cold starts, which can be set during initialization. *This feature is by default disabled.* + +Enabling this feature will generate one additional metric with the same `namespace` and `service name` defined for the AWS Lambda function. + +```csharp +public class Function +{ + [Metrics(CaptureColdStart = true)] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + try + { + // Add Metrics + var watch = Stopwatch.StartNew(); + var location = await GetCallingIP(); + watch.Stop(); + + Metrics.AddMetric("ElapsedExecutionTime", watch.ElapsedMilliseconds, MetricUnit.Milliseconds); + Metrics.AddMetric("SuccessfulLocations", 1, MetricUnit.Count); + + var body = new Dictionary + { + { "message", "sample metrics" }, + { "location", location } + }; + + return new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(body), + StatusCode = 200, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + catch (Exception ex) + { + return new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(ex.Message), + StatusCode = 500, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + } +} +``` + +### Throw Exception if no metrics are provided + +`Metrics` utility can be configured to throw a `SchemaValidationException` in case no metrics were collected before a metrics flush operation - which takes place when the *AWS Lambda function handler* completes execution. + +This flag is used to enforce *metrics* collection but it might not apply to all scenarios, and for that reason it is *disabled by default*. + +```csharp +public class Function +{ + [Metrics(RaiseOnEmptyMetrics = true)] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + try + { + // Add Metrics + var watch = Stopwatch.StartNew(); + var location = await GetCallingIP(); + watch.Stop(); + + Metrics.AddMetric("ElapsedExecutionTime", watch.ElapsedMilliseconds, MetricUnit.Milliseconds); + Metrics.AddMetric("SuccessfulLocations", 1, MetricUnit.Count); + + var body = new Dictionary + { + { "message", "sample metrics" }, + { "location", location } + }; + + return new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(body), + StatusCode = 200, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + catch (Exception ex) + { + return new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(ex.Message), + StatusCode = 500, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + } +} +``` + +### Adding Metrics + +After `Metrics` object initialization, you can collect metrics by using the `AddMetric` method that takes 3 parameters: *Metric name*, *Metric value* and *Metric unit*. + +**Metric unit** is implemented as an enum to improve developer experience and prevent coding errors. + +```csharp + +Metrics.AddMetric("ElapsedExecutionTime", watch.ElapsedMilliseconds, MetricUnit.Milliseconds); +``` + +### Add Dimensions + +Adding `Dimensions` to your metric collection process allows for metric segmentation and easier filtering which facilitates the process of adding metrics to charts and dashboards in *Amazon CloudWatch*. + +*By default, the `service name` is added automatically as a dimension*. You can add your custom dimensions by using the `AddDimension` method as shown in the example below. + +```csharp + +Metrics.AddDimension("Environment", "Prod"); +``` + +### Add Metadata + +You can add high-cardinality data as part of your Metrics log with the `AddMetadata` method. This is useful when you want to search highly contextual information along with your metrics in your logs. + +```csharp + +Metrics.AddMetadata("BookingId", "e36469c2-524a-4265-af07-214be7ad2297"); +``` + +### Collect single Metric with custom namespace and service name + +In the case that you want to capture individual metrics, or capture metrics with different namespace or service name you can use the `PushSingleMetric` method. + +```csharp +public class Function +{ + [Metrics()] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + try + { + // Add Single Metric + Metrics.PushSingleMetric( + metricName: "CallingIP", + value: 1, + unit: MetricUnit.Count, + nameSpace: "dotnet-lambdapowertools", + service: "lambda-example", + defaultDimensions: new Dictionary + { + {"Metric Type", "Single"} + }); + + + var body = new Dictionary + { + { "message", "hello world" } + }; + + return new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(body), + StatusCode = 200, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + catch (Exception ex) + { + return new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(ex.Message), + StatusCode = 500, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + } +} +``` + +## Disclaimer + +This is not an extensive list of examples but we tried to cover the most common use cases for the library. + +If you would like to see other examples please open an issue on the repo or create a Pull Request with more examples. diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/Serializer/DictionaryLookupNamingPolicy.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/Serializer/DictionaryLookupNamingPolicy.cs new file mode 100644 index 000000000..f2214b0d1 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/Serializer/DictionaryLookupNamingPolicy.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Text.Json; + +namespace AWS.Lambda.Powertools.Metrics; + +internal class DictionaryLookupNamingPolicy : JsonNamingPolicyDecorator +{ + private readonly Dictionary _dictionary; + + public DictionaryLookupNamingPolicy(Dictionary dictionary, JsonNamingPolicy underlyingNamingPolicy) + : base(underlyingNamingPolicy) + { + _dictionary = dictionary ?? throw new ArgumentNullException(); + } + + public override string ConvertName(string name) + { + return _dictionary.TryGetValue(name, out var value) ? value : base.ConvertName(name); + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/Serializer/JsonNamingPolicyDecorator.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/Serializer/JsonNamingPolicyDecorator.cs new file mode 100644 index 000000000..f694d5846 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/Serializer/JsonNamingPolicyDecorator.cs @@ -0,0 +1,27 @@ +using System.Text.Json; + +namespace AWS.Lambda.Powertools.Metrics; + +/// +/// Class JsonNamingPolicyDecorator +/// Implements the +/// +public class JsonNamingPolicyDecorator : JsonNamingPolicy +{ + private readonly JsonNamingPolicy _underlyingNamingPolicy; + + /// + /// JsonNamingPolicy decorator + /// + /// Name of the underlying JsonNamingPolicy + protected JsonNamingPolicyDecorator(JsonNamingPolicy underlyingNamingPolicy) + { + _underlyingNamingPolicy = underlyingNamingPolicy; + } + + /// + public override string ConvertName(string name) + { + return _underlyingNamingPolicy == null ? name : _underlyingNamingPolicy.ConvertName(name); + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/Serializer/StringEnumConverter.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/Serializer/StringEnumConverter.cs new file mode 100644 index 000000000..28c0d54b9 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/Serializer/StringEnumConverter.cs @@ -0,0 +1,98 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.Serialization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace AWS.Lambda.Powertools.Metrics; + +/// +/// Class StringEnumConverter. +/// Implements the +/// +/// +public class StringEnumConverter : JsonConverterFactory +{ + /// + /// The allow integer values + /// + private readonly bool _allowIntegerValues; + + /// + /// The base converter + /// + private readonly JsonStringEnumConverter _baseConverter; + + /// + /// The naming policy + /// + private readonly JsonNamingPolicy _namingPolicy; + + /// + /// Initializes a new instance of the class. + /// + public StringEnumConverter() : this(null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The naming policy. + /// if set to true [allow integer values]. + private StringEnumConverter(JsonNamingPolicy namingPolicy = null, bool allowIntegerValues = true) + { + _namingPolicy = namingPolicy; + _allowIntegerValues = allowIntegerValues; + _baseConverter = new JsonStringEnumConverter(namingPolicy, allowIntegerValues); + } + + /// + /// When overridden in a derived class, determines whether the converter instance can convert the specified object + /// type. + /// + /// The type of the object to check whether it can be converted by this converter instance. + /// + /// if the instance can convert the specified object type; otherwise, + /// . + /// + public override bool CanConvert(Type typeToConvert) + { + return _baseConverter.CanConvert(typeToConvert); + } + + /// + /// Creates a converter for a specified type. + /// + /// The type handled by the converter. + /// The serialization options to use. + /// A converter for which type is compatible with . + public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + var query = from field in typeToConvert.GetFields(BindingFlags.Public | BindingFlags.Static) + let attr = field.GetCustomAttribute() + where attr != null + select (field.Name, attr.Value); + var dictionary = query.ToDictionary(p => p.Item1, p => p.Item2); + return dictionary.Count > 0 + ? new JsonStringEnumConverter(new DictionaryLookupNamingPolicy(dictionary, _namingPolicy), + _allowIntegerValues).CreateConverter(typeToConvert, options) + : _baseConverter.CreateConverter(typeToConvert, options); + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/Serializer/UnixMillisecondDateTimeConverter.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/Serializer/UnixMillisecondDateTimeConverter.cs new file mode 100644 index 000000000..3cae1867c --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/Serializer/UnixMillisecondDateTimeConverter.cs @@ -0,0 +1,57 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace AWS.Lambda.Powertools.Metrics; + +/// +/// Class UnixMillisecondDateTimeConverter. +/// Implements the +/// +/// +public class UnixMillisecondDateTimeConverter : JsonConverter +{ + /// + /// Writes a specified value as JSON. + /// + /// The writer to write to. + /// The value to convert to JSON. + /// An object that specifies serialization options to use. + /// Invalid date + public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) + { + var ms = (long) (value.ToUniversalTime() - DateTime.UnixEpoch).TotalMilliseconds; + + if (ms < 0) throw new JsonException("Invalid date"); + + writer.WriteNumberValue(ms); + } + + /// + /// Reads and converts the JSON to DateTime />. + /// + /// The reader. + /// The type to convert. + /// An object that specifies serialization options to use. + /// The converted value. + /// + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + throw new NotImplementedException(); + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Tracing/AWS.Lambda.Powertools.Tracing.csproj b/libraries/src/AWS.Lambda.Powertools.Tracing/AWS.Lambda.Powertools.Tracing.csproj new file mode 100644 index 000000000..7a0c34f5f --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Tracing/AWS.Lambda.Powertools.Tracing.csproj @@ -0,0 +1,42 @@ + + + + net6.0 + default + AWS.Lambda.Powertools.Tracing + 0.0.1 + Amazon Web Services + Amazon.com, Inc + AWS Lambda Powertools for .NET + AWS Lambda Powertools for .NET - Tracing package. + Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + https://github.com/awslabs/aws-lambda-powertools-dotnet + Apache-2.0 + AWS;Amazon;Lambda;Powertools + https://sdk-for-net.amazonwebservices.com/images/AWSLogo128x128.png + README.md + AWSLogo128x128.png + true + AWS.Lambda.Powertools.Tracing + AWS.Lambda.Powertools.Tracing + + + + true + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Tracing/Internal/IXRayRecorder.cs b/libraries/src/AWS.Lambda.Powertools.Tracing/Internal/IXRayRecorder.cs new file mode 100644 index 000000000..7fa00aed9 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Tracing/Internal/IXRayRecorder.cs @@ -0,0 +1,96 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using Amazon.XRay.Recorder.Core.Internal.Emitters; +using Amazon.XRay.Recorder.Core.Internal.Entities; +using Amazon.XRay.Recorder.Core.Strategies; + +namespace AWS.Lambda.Powertools.Tracing.Internal; + +/// +/// Interface IXRayRecorder +/// +public interface IXRayRecorder +{ + /// + /// Gets the emitter. + /// + /// The emitter. + ISegmentEmitter Emitter { get; } + + /// + /// Gets the streaming strategy. + /// + /// The streaming strategy. + IStreamingStrategy StreamingStrategy { get; } + + /// + /// Begins the subsegment. + /// + /// The name. + void BeginSubsegment(string name); + + /// + /// Sets the namespace. + /// + /// The value. + void SetNamespace(string value); + + /// + /// Adds the annotation. + /// + /// The key. + /// The value. + void AddAnnotation(string key, object value); + + /// + /// Adds the metadata. + /// + /// The name space. + /// The key. + /// The value. + void AddMetadata(string nameSpace, string key, object value); + + /// + /// Ends the subsegment. + /// + void EndSubsegment(); + + /// + /// Gets the entity. + /// + /// Entity. + Entity GetEntity(); + + /// + /// Sets the entity. + /// + /// The entity. + void SetEntity(Entity entity); + + /// + /// Adds the exception. + /// + /// The exception. + void AddException(Exception exception); + + /// + /// Adds the HTTP information. + /// + /// The key. + /// The value. + void AddHttpInformation(string key, object value); +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Tracing/Internal/TracingAspectHandler.cs b/libraries/src/AWS.Lambda.Powertools.Tracing/Internal/TracingAspectHandler.cs new file mode 100644 index 000000000..4b4ba96a9 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Tracing/Internal/TracingAspectHandler.cs @@ -0,0 +1,286 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using AWS.Lambda.Powertools.Common; + +namespace AWS.Lambda.Powertools.Tracing.Internal; + +/// +/// Class TracingAspectHandler. +/// Implements the +/// +/// +internal class TracingAspectHandler : IMethodAspectHandler +{ + /// + /// If true, then is cold start + /// + private static bool _isColdStart = true; + + /// + /// If true, capture annotations + /// + private static bool _captureAnnotations = true; + + /// + /// If true, tracing is disabled + /// + private static bool? _isTracingDisabled; + + /// + /// The capture mode + /// + private readonly TracingCaptureMode _captureMode; + + /// + /// Tracing namespace + /// + private readonly string _namespace; + + /// + /// The Powertools configurations + /// + private readonly IPowertoolsConfigurations _powertoolsConfigurations; + + /// + /// The segment name + /// + private readonly string _segmentName; + + /// + /// X-Ray Recorder + /// + private readonly IXRayRecorder _xRayRecorder; + + /// + /// If true, annotations have been captured + /// + private bool _isAnnotationsCaptured; + + /// + /// Initializes a new instance of the class. + /// + /// Name of the segment. + /// The namespace. + /// The capture mode. + /// The Powertools configurations. + /// The X-Ray recorder. + internal TracingAspectHandler + ( + string segmentName, + string nameSpace, + TracingCaptureMode captureMode, + IPowertoolsConfigurations powertoolsConfigurations, + IXRayRecorder xRayRecorder + ) + { + _segmentName = segmentName; + _namespace = nameSpace; + _captureMode = captureMode; + _powertoolsConfigurations = powertoolsConfigurations; + _xRayRecorder = xRayRecorder; + } + + /// + /// Handles the event. + /// + /// + /// The instance containing the + /// event data. + /// + public void OnEntry(AspectEventArgs eventArgs) + { + if(TracingDisabled()) + return; + + var segmentName = !string.IsNullOrWhiteSpace(_segmentName) ? _segmentName : $"## {eventArgs.Name}"; + var nameSpace = GetNamespace(); + + _xRayRecorder.BeginSubsegment(segmentName); + _xRayRecorder.SetNamespace(nameSpace); + + if (_captureAnnotations) + { + _xRayRecorder.AddAnnotation("ColdStart", _isColdStart); + + _isColdStart = false; + _captureAnnotations = false; + _isAnnotationsCaptured = true; + + if (_powertoolsConfigurations.IsServiceDefined) + _xRayRecorder.AddAnnotation("Service", _powertoolsConfigurations.Service); + } + } + + /// + /// Called when [success]. + /// + /// + /// The instance containing the + /// event data. + /// + /// The result. + public void OnSuccess(AspectEventArgs eventArgs, object result) + { + if (CaptureResponse()) + { + var nameSpace = GetNamespace(); + + _xRayRecorder.AddMetadata + ( + nameSpace, + $"{eventArgs.Name} response", + result + ); + } + } + + /// + /// Called when [exception]. + /// + /// + /// + /// The instance containing the + /// event data. + /// + /// The exception. + /// T. + public T OnException(AspectEventArgs eventArgs, Exception exception) + { + if (CaptureError()) + { + var nameSpace = GetNamespace(); + + _xRayRecorder.AddMetadata + ( + nameSpace, + $"{eventArgs.Name} error", + exception + ); + } + + throw exception; + } + + /// + /// Handles the event. + /// + /// + /// The instance containing the + /// event data. + /// + public void OnExit(AspectEventArgs eventArgs) + { + if(TracingDisabled()) + return; + + if (_isAnnotationsCaptured) + _captureAnnotations = true; + + _xRayRecorder.EndSubsegment(); + } + + /// + /// Gets the namespace. + /// + /// System.String. + private string GetNamespace() + { + return !string.IsNullOrWhiteSpace(_namespace) ? _namespace : _powertoolsConfigurations.Service; + } + + /// + /// Captures the response. + /// + /// true if tracing should capture responses, false otherwise. + private bool CaptureResponse() + { + if(TracingDisabled()) + return false; + + switch (_captureMode) + { + case TracingCaptureMode.EnvironmentVariable: + return _powertoolsConfigurations.TracerCaptureResponse; + case TracingCaptureMode.Response: + case TracingCaptureMode.ResponseAndError: + return true; + case TracingCaptureMode.Error: + case TracingCaptureMode.Disabled: + default: + return false; + } + } + + /// + /// Captures the error. + /// + /// true if tracing should capture errors, false otherwise. + private bool CaptureError() + { + if(TracingDisabled()) + return false; + + switch (_captureMode) + { + case TracingCaptureMode.EnvironmentVariable: + return _powertoolsConfigurations.TracerCaptureError; + case TracingCaptureMode.Error: + case TracingCaptureMode.ResponseAndError: + return true; + case TracingCaptureMode.Response: + case TracingCaptureMode.Disabled: + default: + return false; + } + } + + /// + /// Tracing disabled. + /// + /// true if tracing is disabled, false otherwise. + private bool TracingDisabled() + { + if (_isTracingDisabled.HasValue) + return _isTracingDisabled.Value; + + if (_powertoolsConfigurations.TracingDisabled) + { + _isTracingDisabled = true; + Console.WriteLine("Tracing has been disabled via env var POWERTOOLS_TRACE_DISABLED"); + } + else if (!_powertoolsConfigurations.IsLambdaEnvironment) + { + _isTracingDisabled = true; + Console.WriteLine("Running outside Lambda environment; disabling Tracing"); + } + else + { + _isTracingDisabled = false; + } + return _isTracingDisabled.Value; + } + + /// + /// Resets static variables for test. + /// + internal static void ResetForTest() + { + _isColdStart = true; + _captureAnnotations = true; + _isTracingDisabled = null; + } +} diff --git a/libraries/src/AWS.Lambda.Powertools.Tracing/Internal/XRayRecorder.cs b/libraries/src/AWS.Lambda.Powertools.Tracing/Internal/XRayRecorder.cs new file mode 100644 index 000000000..51d511a1d --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Tracing/Internal/XRayRecorder.cs @@ -0,0 +1,153 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using Amazon.XRay.Recorder.Core; +using Amazon.XRay.Recorder.Core.Internal.Emitters; +using Amazon.XRay.Recorder.Core.Internal.Entities; +using Amazon.XRay.Recorder.Core.Strategies; + +namespace AWS.Lambda.Powertools.Tracing.Internal; + +/// +/// Class XRayRecorder. +/// Implements the +/// +/// +internal class XRayRecorder : IXRayRecorder +{ + /// + /// The instance + /// + private static IXRayRecorder _instance; + + /// + /// Gets the instance. + /// + /// The instance. + public static IXRayRecorder Instance => _instance ??= new XRayRecorder(); + + /// + /// Checks whether current execution is in AWS Lambda. + /// + /// Returns true if current execution is in AWS Lambda. + private static readonly bool _isLambda = AWSXRayRecorder.IsLambda(); + + /// + /// Gets the emitter. + /// + /// The emitter. + public ISegmentEmitter Emitter => _isLambda ? AWSXRayRecorder.Instance.Emitter : null; + + /// + /// Gets the streaming strategy. + /// + /// The streaming strategy. + public IStreamingStrategy StreamingStrategy => _isLambda ? AWSXRayRecorder.Instance.StreamingStrategy : null; + + /// + /// Begins the subsegment. + /// + /// The name. + public void BeginSubsegment(string name) + { + if (_isLambda) + AWSXRayRecorder.Instance.BeginSubsegment(name); + } + + /// + /// Sets the namespace. + /// + /// The value. + public void SetNamespace(string value) + { + if (_isLambda) + AWSXRayRecorder.Instance.SetNamespace(value); + } + + /// + /// Adds the annotation. + /// + /// The key. + /// The value. + public void AddAnnotation(string key, object value) + { + if (_isLambda) + AWSXRayRecorder.Instance.AddAnnotation(key, value); + } + + /// + /// Adds the metadata. + /// + /// The name space. + /// The key. + /// The value. + public void AddMetadata(string nameSpace, string key, object value) + { + if (_isLambda) + AWSXRayRecorder.Instance.AddMetadata(nameSpace, key, value); + } + + /// + /// Ends the subsegment. + /// + public void EndSubsegment() + { + if (_isLambda) + AWSXRayRecorder.Instance.EndSubsegment(); + } + + /// + /// Gets the entity. + /// + /// Entity. + public Entity GetEntity() + { + return _isLambda + ? AWSXRayRecorder.Instance.GetEntity() + : new Segment("Root"); + } + + /// + /// Sets the entity. + /// + /// The entity. + public void SetEntity(Entity entity) + { + if (_isLambda) + AWSXRayRecorder.Instance.SetEntity(entity); + } + + /// + /// Adds the exception. + /// + /// The exception. + public void AddException(Exception exception) + { + if (_isLambda) + AWSXRayRecorder.Instance.AddException(exception); + } + + /// + /// Adds the HTTP information. + /// + /// The key. + /// The value. + public void AddHttpInformation(string key, object value) + { + if (_isLambda) + AWSXRayRecorder.Instance.AddHttpInformation(key, value); + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Tracing/InternalsVisibleTo.cs b/libraries/src/AWS.Lambda.Powertools.Tracing/InternalsVisibleTo.cs new file mode 100644 index 000000000..2e9c5120d --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Tracing/InternalsVisibleTo.cs @@ -0,0 +1,18 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("AWS.Lambda.Powertools.Tracing.Tests")] \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Tracing/README.md b/libraries/src/AWS.Lambda.Powertools.Tracing/README.md new file mode 100644 index 000000000..df2cc67bb --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Tracing/README.md @@ -0,0 +1,119 @@ +# AWS.Lambda.Powertools.Tracing + +This package contains classes that can be used as.... + +## Sample Function + +Below is a sample class and Lambda function that illustrates how.... + +```csharp +public class Function +{ + private static readonly HttpClient client = new HttpClient(); + + [Logging(LogEvent = true, SamplingRate = 0.7)] + [Tracing(CaptureMode = TracingCaptureMode.ResponseAndError)] + [Metrics(Namespace = "dotnet-lambdapowertools", CaptureColdStart = true)] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + try + { + // Add Metrics + var watch = Stopwatch.StartNew(); + Metrics.PushSingleMetric( + metricName: "CallingIP", + value: 1, + unit: MetricUnit.Count, + nameSpace: "dotnet-lambdapowertools", + service: "lambda-example", + defaultDimensions: new Dictionary + { + {"Metric Type", "Single"} + }); + var location = await GetCallingIP(); + watch.Stop(); + + Metrics.AddMetric("ElapsedExecutionTime", watch.ElapsedMilliseconds, MetricUnit.Milliseconds); + Metrics.AddMetric("SuccessfulLocations", 1, MetricUnit.Count); + + var body = new Dictionary + { + { "message", "hello world" }, + { "location", location } + }; + + // Append Log Key + Logger.AppendKey("test", "willBeLogged"); + + // Trace Nested Methods + NestedMethodsParent(); + + // Trace Fluent API + Tracing.WithSubsegment("LoggingResponse", subsegment => + { + subsegment.AddAnnotation("Test", "New"); + Logger.LogInformation("log something out"); + Logger.LogInformation(body); + }); + + // Trace Parallel Tasks + var entity = Tracing.GetEntity(); + var task = Task.Run(() => + { + Tracing.WithSubsegment("Inline Subsegment 1", entity, _ => + { + Logger.LogInformation($"log something out for inline subsegment 1"); + }); + }); + var anotherTask = Task.Run(() => + { + Tracing.WithSubsegment("Inline Subsegment 2", entity, _ => + { + Logger.LogInformation($"log something out for inline subsegment 2"); + }); + }); + Task.WaitAll(task, anotherTask); + + return new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(body), + StatusCode = 200, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + catch (Exception ex) + { + return new APIGatewayProxyResponse + { + Body = JsonSerializer.Serialize(ex.Message), + StatusCode = 500, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + } + + [Tracing(Namespace = "GetCallingIP", CaptureMode = TracingCaptureMode.Disabled)] + private static async Task GetCallingIP() + { + client.DefaultRequestHeaders.Accept.Clear(); + client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); + var msg = await client.GetStringAsync("http://checkip.amazonaws.com/") + .ConfigureAwait(continueOnCapturedContext:false); + return msg.Replace("\n",""); + } + + [Tracing(CaptureMode = TracingCaptureMode.Disabled)] + private static void NestedMethodsParent() + { + Logger.LogInformation($"NestedMethodsParent method"); + NestedMethodsChild(1); + NestedMethodsChild(1); + } + + [Tracing(CaptureMode = TracingCaptureMode.Disabled)] + private static void NestedMethodsChild(int childId) + { + Logger.LogInformation($"NestedMethodsChild method for child {childId}"); + } +} +``` \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Tracing/Tracing.cs b/libraries/src/AWS.Lambda.Powertools.Tracing/Tracing.cs new file mode 100644 index 000000000..357987b01 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Tracing/Tracing.cs @@ -0,0 +1,242 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using Amazon.XRay.Recorder.Core.Internal.Entities; +using AWS.Lambda.Powertools.Common; +using AWS.Lambda.Powertools.Tracing.Internal; + +namespace AWS.Lambda.Powertools.Tracing; + +/// +/// Class Tracing. +/// +public static class Tracing +{ + /// + /// Gets entity (segment/subsegment) from the + /// . + /// + /// The entity (segment/subsegment) + /// + /// Thrown when the entity is not + /// available to get. + /// + public static Entity GetEntity() + { + return XRayRecorder.Instance.GetEntity(); + } + + /// + /// Set the specified entity (segment/subsegment) into + /// . + /// + /// The entity to be set + /// + /// Thrown when the entity is not + /// available to set + /// + public static void SetEntity(Entity entity) + { + XRayRecorder.Instance.SetEntity(entity); + } + + /// + /// Adds the specified key and value as annotation to current segment. + /// The type of value is restricted. Only , , + /// , + /// and are supported. + /// + /// The key of the annotation to add. + /// The value of the annotation to add. + /// + /// Entity is not available in trace + /// context. + /// + public static void AddAnnotation(string key, object value) + { + XRayRecorder.Instance.AddAnnotation(key, value); + } + + /// + /// Adds the specified key and value to metadata with given namespace. + /// + /// The key. + /// The value. + public static void AddMetadata(string key, object value) + { + XRayRecorder.Instance.AddMetadata(GetNamespaceOrDefault(null), key, value); + } + + /// + /// Adds the specified key and value to metadata with given namespace. + /// + /// The namespace. + /// The key. + /// The value. + public static void AddMetadata(string nameSpace, string key, object value) + { + XRayRecorder.Instance.AddMetadata(GetNamespaceOrDefault(nameSpace), key, value); + } + + /// + /// Add the exception to current segment and also mark current segment as fault. + /// + /// The exception to be added. + /// + /// Entity is not available in trace + /// context. + /// + public static void AddException(Exception exception) + { + XRayRecorder.Instance.AddException(exception); + } + + /// + /// Adds the specified key and value as http information to current segment. + /// + /// The key of the http information to add. + /// The value of the http information to add. + /// Key is null or empty. + /// Value is null. + /// + /// Entity is not available in trace + /// context. + /// + public static void AddHttpInformation(string key, object value) + { + XRayRecorder.Instance.AddHttpInformation(key, value); + } + + /// + /// Adds a new subsegment around the passed consumer. This also provides access to + /// the newly created subsegment. + /// The namespace used follows the flow as described in + /// + /// + /// The name of the subsegment. + /// The AWS X-Ray subsegment for the wrapped consumer. + /// Thrown when the name is not provided. + public static void WithSubsegment(string name, Action subsegment) + { + WithSubsegment(null, name, subsegment); + } + + /// + /// Adds a new subsegment around the passed consumer. This also provides access to + /// the newly created subsegment. + /// The namespace used follows the flow as described in + /// + /// + /// The name space. + /// The name of the subsegment. + /// The AWS X-Ray subsegment for the wrapped consumer. + /// name + public static void WithSubsegment(string nameSpace, string name, Action subsegment) + { + if (string.IsNullOrWhiteSpace(name)) + throw new ArgumentNullException(nameof(name)); + + XRayRecorder.Instance.BeginSubsegment("## " + name); + XRayRecorder.Instance.SetNamespace(GetNamespaceOrDefault(nameSpace)); + try + { + subsegment?.Invoke((Subsegment) XRayRecorder.Instance.GetEntity()); + } + finally + { + XRayRecorder.Instance.EndSubsegment(); + } + } + + + /// + /// Adds a new subsegment around the passed consumer. This also provides access to + /// the newly created subsegment. + /// This method is intended for use with multi-threaded programming where the + /// context is lost between threads. + /// + /// The name of the subsegment. + /// The current AWS X-Ray context. + /// The AWS X-Ray subsegment for the wrapped consumer. + /// Thrown when the name is not provided. + /// Thrown when the entity is not provided. + public static void WithSubsegment(string name, Entity entity, Action subsegment) + { + WithSubsegment(null, name, subsegment); + } + + /// + /// Adds a new subsegment around the passed consumer. This also provides access to + /// the newly created subsegment. + /// This method is intended for use with multi-threaded programming where the + /// context is lost between threads. + /// + /// The namespace of the subsegment. + /// The name of the subsegment. + /// The current AWS X-Ray context. + /// The AWS X-Ray subsegment for the wrapped consumer. + /// name + /// entity + public static void WithSubsegment(string nameSpace, string name, Entity entity, Action subsegment) + { + if (string.IsNullOrWhiteSpace(name)) + throw new ArgumentNullException(nameof(name)); + + if (entity is null) + throw new ArgumentNullException(nameof(entity)); + + var childSubsegment = new Subsegment($"## {name}"); + entity.AddSubsegment(childSubsegment); + childSubsegment.Sampled = entity.Sampled; + childSubsegment.SetStartTimeToNow(); + childSubsegment.Namespace = GetNamespaceOrDefault(nameSpace); + try + { + subsegment?.Invoke(childSubsegment); + } + finally + { + childSubsegment.IsInProgress = false; + childSubsegment.Release(); + childSubsegment.SetEndTimeToNow(); + if (PowertoolsConfigurations.Instance.IsLambdaEnvironment) + { + if (childSubsegment.IsEmittable()) + XRayRecorder.Instance.Emitter.Send(childSubsegment.RootSegment); + else if (XRayRecorder.Instance.StreamingStrategy.ShouldStream(childSubsegment)) + XRayRecorder.Instance.StreamingStrategy.Stream(childSubsegment.RootSegment, + XRayRecorder.Instance.Emitter); + } + } + } + + /// + /// Gets the namespace or default. + /// + /// The name space. + /// System.String. + private static string GetNamespaceOrDefault(string nameSpace) + { + if (!string.IsNullOrWhiteSpace(nameSpace)) + return nameSpace; + + nameSpace = (GetEntity() as Subsegment)?.Namespace; + if (!string.IsNullOrWhiteSpace(nameSpace)) + return nameSpace; + + return PowertoolsConfigurations.Instance.Service; + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Tracing/TracingAttribute.cs b/libraries/src/AWS.Lambda.Powertools.Tracing/TracingAttribute.cs new file mode 100644 index 000000000..b2aec39b7 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Tracing/TracingAttribute.cs @@ -0,0 +1,65 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using AWS.Lambda.Powertools.Common; +using AWS.Lambda.Powertools.Tracing.Internal; + +namespace AWS.Lambda.Powertools.Tracing; + +/// +/// Class TracingAttribute. +/// Implements the +/// +/// +public class TracingAttribute : MethodAspectAttribute +{ + /// + /// Set custom segment name for the operation. + /// The default is '## {MethodName}'. + /// + /// The name of the segment. + public string SegmentName { get; set; } = ""; + + /// + /// Set namespace to current subsegment. + /// The default is the environment variable POWERTOOLS_SERVICE_NAME. + /// + /// The namespace. + public string Namespace { get; set; } = ""; + + /// + /// Set capture mode to record method responses and exceptions. + /// The defaults are the environment variables POWERTOOLS_TRACER_CAPTURE_RESPONSE and + /// POWERTOOLS_TRACER_CAPTURE_ERROR. + /// + /// The capture mode. + public TracingCaptureMode CaptureMode { get; set; } = TracingCaptureMode.EnvironmentVariable; + + /// + /// Creates the handler. + /// + /// IMethodAspectHandler. + protected override IMethodAspectHandler CreateHandler() + { + return new TracingAspectHandler + ( + SegmentName, + Namespace, + CaptureMode, + PowertoolsConfigurations.Instance, + XRayRecorder.Instance + ); + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Tracing/TracingCaptureMode.cs b/libraries/src/AWS.Lambda.Powertools.Tracing/TracingCaptureMode.cs new file mode 100644 index 000000000..6e3ad5b63 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Tracing/TracingCaptureMode.cs @@ -0,0 +1,58 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace AWS.Lambda.Powertools.Tracing; + +/// +/// Enum TracingCaptureMode +/// +public enum TracingCaptureMode +{ + /// + /// Enables attribute to capture only response. If this mode is explicitly overridden + /// on { attribute, it will override value of + /// environment variable POWERTOOLS_TRACER_CAPTURE_RESPONSE + /// + Response, + + /// + /// Enabled attribute to capture only error from the method. If this mode is explicitly overridden + /// on attribute, it will override value of + /// environment variable POWERTOOLS_TRACER_CAPTURE_ERROR + /// + Error, + + /// + /// Enabled attribute to capture both response error from the method. If this mode is explicitly overridden + /// on attribute, it will override value of + /// environment variables POWERTOOLS_TRACER_CAPTURE_RESPONSE + /// and POWERTOOLS_TRACER_CAPTURE_ERROR + /// + ResponseAndError, + + /// + /// Disables attribute to capture both response and error from the method. If this mode is explicitly overridden + /// on attribute, it will override values of + /// environment variable POWERTOOLS_TRACER_CAPTURE_RESPONSE + /// and POWERTOOLS_TRACER_CAPTURE_ERROR + /// + Disabled, + + /// + /// Enables/Disables attribute to capture response and error from the method based on the value of + /// environment variable POWERTOOLS_TRACER_CAPTURE_RESPONSE and POWERTOOLS_TRACER_CAPTURE_ERROR + /// + EnvironmentVariable +} \ No newline at end of file diff --git a/libraries/tests/AWS.Lambda.Powertools.Common.Tests/AWS.Lambda.Powertools.Common.Tests.csproj b/libraries/tests/AWS.Lambda.Powertools.Common.Tests/AWS.Lambda.Powertools.Common.Tests.csproj new file mode 100644 index 000000000..5d4c97b3d --- /dev/null +++ b/libraries/tests/AWS.Lambda.Powertools.Common.Tests/AWS.Lambda.Powertools.Common.Tests.csproj @@ -0,0 +1,23 @@ + + + + net6.0 + AWS.Lambda.Powertools.Common.Tests + AWS.Lambda.Powertools.Common.Tests + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + diff --git a/libraries/tests/AWS.Lambda.Powertools.Common.Tests/AWS.Lambda.Powertools.Common.Tests.csproj.DotSettings b/libraries/tests/AWS.Lambda.Powertools.Common.Tests/AWS.Lambda.Powertools.Common.Tests.csproj.DotSettings new file mode 100644 index 000000000..77449f83f --- /dev/null +++ b/libraries/tests/AWS.Lambda.Powertools.Common.Tests/AWS.Lambda.Powertools.Common.Tests.csproj.DotSettings @@ -0,0 +1,2 @@ + + True \ No newline at end of file diff --git a/libraries/tests/AWS.Lambda.Powertools.Common.Tests/Core/PowertoolsConfigurationsTest.cs b/libraries/tests/AWS.Lambda.Powertools.Common.Tests/Core/PowertoolsConfigurationsTest.cs new file mode 100644 index 000000000..54b6b6c5d --- /dev/null +++ b/libraries/tests/AWS.Lambda.Powertools.Common.Tests/Core/PowertoolsConfigurationsTest.cs @@ -0,0 +1,644 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using Moq; +using Xunit; + +namespace AWS.Lambda.Powertools.Common.Tests +{ + public class PowertoolsConfigurationsTest + { + #region GetEnvironmentVariable Tests + + [Fact] + public void GetEnvironmentVariableOrDefault_WhenEnvironmentVariableIsNull_ReturnsDefaultValueString() + { + // Arrange + var key = Guid.NewGuid().ToString(); + var defaultValue = Guid.NewGuid().ToString(); + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(key) + ).Returns(string.Empty); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.GetEnvironmentVariableOrDefault(key, defaultValue); + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == key) + ), Times.Once); + + Assert.Equal(result, defaultValue); + } + + [Fact] + public void GetEnvironmentVariableOrDefault_WhenEnvironmentVariableIsNull_ReturnsDefaultValueFalse() + { + // Arrange + var key = Guid.NewGuid().ToString(); + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(key) + ).Returns(string.Empty); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.GetEnvironmentVariableOrDefault(key, false); + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == key) + ), Times.Once); + + Assert.False(result); + } + + [Fact] + public void GetEnvironmentVariableOrDefault_WhenEnvironmentVariableIsNull_ReturnsDefaultValueTrue() + { + // Arrange + var key = Guid.NewGuid().ToString(); + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(key) + ).Returns(string.Empty); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.GetEnvironmentVariableOrDefault(key, true); + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == key) + ), Times.Once); + + Assert.True(result); + } + + [Fact] + public void GetEnvironmentVariableOrDefault_WhenEnvironmentVariableHasValue_ReturnsValueString() + { + // Arrange + var key = Guid.NewGuid().ToString(); + var defaultValue = Guid.NewGuid().ToString(); + var value = Guid.NewGuid().ToString(); + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(key) + ).Returns(value); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.GetEnvironmentVariableOrDefault(key, defaultValue); + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == key) + ), Times.Once); + + Assert.Equal(result, value); + } + + [Fact] + public void GetEnvironmentVariableOrDefault_WhenEnvironmentVariableHasValue_ReturnsValueTrue() + { + // Arrange + var key = Guid.NewGuid().ToString(); + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(key) + ).Returns("true"); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.GetEnvironmentVariableOrDefault(key, false); + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == key) + ), Times.Once); + + Assert.True(result); + } + + [Fact] + public void GetEnvironmentVariableOrDefault_WhenEnvironmentVariableHasValue_ReturnsValueFalse() + { + // Arrange + var key = Guid.NewGuid().ToString(); + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(key) + ).Returns("false"); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.GetEnvironmentVariableOrDefault(key, true); + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == key) + ), Times.Once); + + Assert.False(result); + } + + #endregion + + #region Service Tests + + [Fact] + public void Service_WhenEnvironmentIsNull_ReturnsDefaultValue() + { + // Arrange + var defaultService = "service_undefined"; + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(Constants.ServiceNameEnv) + ).Returns(string.Empty); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.Service; + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == Constants.ServiceNameEnv) + ), Times.Once); + + Assert.Equal(result, defaultService); + } + + [Fact] + public void Service_WhenEnvironmentHasValue_ReturnsValue() + { + // Arrange + var service = Guid.NewGuid().ToString(); + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(Constants.ServiceNameEnv) + ).Returns(service); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.Service; + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == Constants.ServiceNameEnv) + ), Times.Once); + + Assert.Equal(result, service); + } + + #endregion + + #region IsServiceDefined Tests + + [Fact] + public void IsServiceDefined_WhenEnvironmentHasValue_ReturnsTrue() + { + // Arrange + var service = Guid.NewGuid().ToString(); + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(Constants.ServiceNameEnv) + ).Returns(service); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.IsServiceDefined; + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == Constants.ServiceNameEnv) + ), Times.Once); + + Assert.True(result); + } + + [Fact] + public void IsServiceDefined_WhenEnvironmentDoesNotHaveValue_ReturnsFalse() + { + // Arrange + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(Constants.ServiceNameEnv) + ).Returns(string.Empty); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.IsServiceDefined; + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == Constants.ServiceNameEnv) + ), Times.Once); + + Assert.False(result); + } + + #endregion + + #region TracerCaptureResponse Tests + + [Fact] + public void TracerCaptureResponse_WhenEnvironmentIsNull_ReturnsDefaultValue() + { + // Arrange + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(Constants.TracerCaptureResponseEnv) + ).Returns(string.Empty); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.TracerCaptureResponse; + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == Constants.TracerCaptureResponseEnv) + ), Times.Once); + + Assert.True(result); + } + + [Fact] + public void TracerCaptureResponse_WhenEnvironmentHasValue_ReturnsValueFalse() + { + // Arrange + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(Constants.TracerCaptureResponseEnv) + ).Returns("false"); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.TracerCaptureResponse; + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == Constants.TracerCaptureResponseEnv) + ), Times.Once); + + Assert.False(result); + } + + [Fact] + public void TracerCaptureResponse_WhenEnvironmentHasValue_ReturnsValueTrue() + { + // Arrange + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(Constants.TracerCaptureResponseEnv) + ).Returns("true"); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.TracerCaptureResponse; + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == Constants.TracerCaptureResponseEnv) + ), Times.Once); + + Assert.True(result); + } + + #endregion + + #region TracerCaptureError Tests + + [Fact] + public void TracerCaptureError_WhenEnvironmentIsNull_ReturnsDefaultValue() + { + // Arrange + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(Constants.TracerCaptureErrorEnv) + ).Returns(string.Empty); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.TracerCaptureError; + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == Constants.TracerCaptureErrorEnv) + ), Times.Once); + + Assert.True(result); + } + + [Fact] + public void TracerCaptureError_WhenEnvironmentHasValue_ReturnsValueFalse() + { + // Arrange + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(Constants.TracerCaptureErrorEnv) + ).Returns("false"); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.TracerCaptureError; + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == Constants.TracerCaptureErrorEnv) + ), Times.Once); + + Assert.False(result); + } + + [Fact] + public void TracerCaptureError_WhenEnvironmentHasValue_ReturnsValueTrue() + { + // Arrange + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(Constants.TracerCaptureErrorEnv) + ).Returns("true"); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.TracerCaptureError; + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == Constants.TracerCaptureErrorEnv) + ), Times.Once); + + Assert.True(result); + } + + #endregion + + #region IsSamLocal Tests + + [Fact] + public void IsSamLocal_WhenEnvironmentIsNull_ReturnsDefaultValue() + { + // Arrange + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(Constants.SamLocalEnv) + ).Returns(string.Empty); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.IsSamLocal; + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == Constants.SamLocalEnv) + ), Times.Once); + + Assert.False(result); + } + + [Fact] + public void IsSamLocal_WhenEnvironmentHasValue_ReturnsValueFalse() + { + // Arrange + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(Constants.SamLocalEnv) + ).Returns("false"); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.IsSamLocal; + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == Constants.SamLocalEnv) + ), Times.Once); + + Assert.False(result); + } + + [Fact] + public void IsSamLocal_WhenEnvironmentHasValue_ReturnsValueTrue() + { + // Arrange + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(Constants.SamLocalEnv) + ).Returns("true"); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.IsSamLocal; + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == Constants.SamLocalEnv) + ), Times.Once); + + Assert.True(result); + } + + #endregion + + #region TracingDisabled Tests + + [Fact] + public void TracingDisabled_WhenEnvironmentIsNull_ReturnsDefaultValue() + { + // Arrange + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(Constants.TracingDisabledEnv) + ).Returns(string.Empty); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.TracingDisabled; + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == Constants.TracingDisabledEnv) + ), Times.Once); + + Assert.False(result); + } + + [Fact] + public void TracingDisabled_WhenEnvironmentHasValue_ReturnsValueFalse() + { + // Arrange + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(Constants.TracingDisabledEnv) + ).Returns("false"); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.TracingDisabled; + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == Constants.TracingDisabledEnv) + ), Times.Once); + + Assert.False(result); + } + + [Fact] + public void TracingDisabled_WhenEnvironmentHasValue_ReturnsValueTrue() + { + // Arrange + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(Constants.TracingDisabledEnv) + ).Returns("true"); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.TracingDisabled; + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == Constants.TracingDisabledEnv) + ), Times.Once); + + Assert.True(result); + } + + #endregion + + #region IsLambdaEnvironment Tests + + [Fact] + public void IsLambdaEnvironment_WhenEnvironmentIsNull_ReturnsFalse() + { + // Arrange + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(Constants.LambdaTaskRoot) + ).Returns((string)null); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.IsLambdaEnvironment; + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == Constants.LambdaTaskRoot) + ), Times.Once); + + Assert.False(result); + } + + [Fact] + public void IsLambdaEnvironment_WhenEnvironmentHasValue_ReturnsTrue() + { + // Arrange + var systemWrapper = new Mock(); + + systemWrapper.Setup(c => + c.GetEnvironmentVariable(Constants.LambdaTaskRoot) + ).Returns(Guid.NewGuid().ToString); + + var configurations = new PowertoolsConfigurations(systemWrapper.Object); + + // Act + var result = configurations.IsLambdaEnvironment; + + // Assert + systemWrapper.Verify(v => + v.GetEnvironmentVariable( + It.Is(i => i == Constants.LambdaTaskRoot) + ), Times.Once); + + Assert.True(result); + } + + #endregion + } +} \ No newline at end of file diff --git a/libraries/tests/AWS.Lambda.Powertools.Common.Tests/Core/PowertoolsLambdaContextTest.cs b/libraries/tests/AWS.Lambda.Powertools.Common.Tests/Core/PowertoolsLambdaContextTest.cs new file mode 100644 index 000000000..d6f87faee --- /dev/null +++ b/libraries/tests/AWS.Lambda.Powertools.Common.Tests/Core/PowertoolsLambdaContextTest.cs @@ -0,0 +1,65 @@ +using System; +using Xunit; + +namespace AWS.Lambda.Powertools.Common.Tests; + +public class PowertoolsLambdaContextTest +{ + private class TestLambdaContext + { + public string AwsRequestId { get; set; } + public string FunctionName { get; set; } + public string FunctionVersion { get; set; } + public string InvokedFunctionArn { get; set; } + public string LogGroupName { get; set; } + public string LogStreamName { get; set; } + public int MemoryLimitInMB { get; set; } + } + + private static TestLambdaContext NewLambdaContext() + { + return new TestLambdaContext + { + AwsRequestId = Guid.NewGuid().ToString(), + FunctionName = Guid.NewGuid().ToString(), + FunctionVersion = Guid.NewGuid().ToString(), + InvokedFunctionArn = Guid.NewGuid().ToString(), + LogGroupName = Guid.NewGuid().ToString(), + LogStreamName = Guid.NewGuid().ToString(), + MemoryLimitInMB = new Random().Next() + }; + } + + [Fact] + public void Extract_WhenHasLambdaContextArgument_InitializesLambdaContextInfo() + { + // Arrange + var lambdaContext = NewLambdaContext(); + var eventArg = new {Source = "Test"}; + var eventArgs = new AspectEventArgs + { + Name = Guid.NewGuid().ToString(), + Args = new object [] + { + eventArg, + lambdaContext + } + }; + + // Act && Assert + PowertoolsLambdaContext.Clear(); + Assert.Null(PowertoolsLambdaContext.Instance); + Assert.True(PowertoolsLambdaContext.Extract(eventArgs)); + Assert.NotNull(PowertoolsLambdaContext.Instance); + Assert.False(PowertoolsLambdaContext.Extract(eventArgs)); + Assert.Equal(PowertoolsLambdaContext.Instance.AwsRequestId, lambdaContext.AwsRequestId); + Assert.Equal(PowertoolsLambdaContext.Instance.FunctionName, lambdaContext.FunctionName); + Assert.Equal(PowertoolsLambdaContext.Instance.FunctionVersion, lambdaContext.FunctionVersion); + Assert.Equal(PowertoolsLambdaContext.Instance.InvokedFunctionArn, lambdaContext.InvokedFunctionArn); + Assert.Equal(PowertoolsLambdaContext.Instance.LogGroupName, lambdaContext.LogGroupName); + Assert.Equal(PowertoolsLambdaContext.Instance.LogStreamName, lambdaContext.LogStreamName); + Assert.Equal(PowertoolsLambdaContext.Instance.MemoryLimitInMB, lambdaContext.MemoryLimitInMB); + PowertoolsLambdaContext.Clear(); + Assert.Null(PowertoolsLambdaContext.Instance); + } +} \ No newline at end of file diff --git a/libraries/tests/AWS.Lambda.Powertools.Logging.Tests/AWS.Lambda.Powertools.Logging.Tests.csproj b/libraries/tests/AWS.Lambda.Powertools.Logging.Tests/AWS.Lambda.Powertools.Logging.Tests.csproj new file mode 100644 index 000000000..4eeca4842 --- /dev/null +++ b/libraries/tests/AWS.Lambda.Powertools.Logging.Tests/AWS.Lambda.Powertools.Logging.Tests.csproj @@ -0,0 +1,27 @@ + + + + net6.0 + default + AWS.Lambda.Powertools.Logging.Tests + AWS.Lambda.Powertools.Logging.Tests + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + diff --git a/libraries/tests/AWS.Lambda.Powertools.Logging.Tests/LoggingAttributeTest.cs b/libraries/tests/AWS.Lambda.Powertools.Logging.Tests/LoggingAttributeTest.cs new file mode 100644 index 000000000..55b0134b7 --- /dev/null +++ b/libraries/tests/AWS.Lambda.Powertools.Logging.Tests/LoggingAttributeTest.cs @@ -0,0 +1,310 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using Amazon.Lambda.APIGatewayEvents; +using Amazon.Lambda.ApplicationLoadBalancerEvents; +using AWS.Lambda.Powertools.Common; +using AWS.Lambda.Powertools.Logging.Internal; +using Microsoft.Extensions.Logging; +using Moq; +using Xunit; + +[assembly: CollectionBehavior(DisableTestParallelization = true)] + +namespace AWS.Lambda.Powertools.Logging.Tests +{ + [Collection("Sequential")] + public class LoggingAttributeTestWithoutLambdaContext + { + [Fact] + public void OnEntry_WhenLambdaContextDoesNotExist_IgnoresLambdaContext() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var logLevel = LogLevel.Information; + + var configurations = new Mock(); + var systemWrapper = new Mock(); + + var eventArgs = new AspectEventArgs + { + Name = methodName, + Args = new object [] { } + }; + + LoggingAspectHandler.ResetForTest(); + var handler = new LoggingAspectHandler(service, logLevel, null, null, true, null, true, configurations.Object, + systemWrapper.Object); + + // Act + handler.OnEntry(eventArgs); + + var allKeys = Logger.GetAllKeys() + .ToDictionary(keyValuePair => keyValuePair.Key, keyValuePair => keyValuePair.Value); + + Assert.NotNull(Logger.LoggerProvider); + Assert.True(allKeys.ContainsKey(LoggingConstants.KeyColdStart)); + Assert.True((bool) allKeys[LoggingConstants.KeyColdStart]); + Assert.False(allKeys.ContainsKey(LoggingConstants.KeyFunctionName)); + Assert.False(allKeys.ContainsKey(LoggingConstants.KeyFunctionVersion)); + Assert.False(allKeys.ContainsKey(LoggingConstants.KeyFunctionMemorySize)); + Assert.False(allKeys.ContainsKey(LoggingConstants.KeyFunctionArn)); + Assert.False(allKeys.ContainsKey(LoggingConstants.KeyFunctionRequestId)); + + systemWrapper.Verify(v => + v.LogLine( + It.IsAny() + ), Times.Never); + } + } + + [Collection("Sequential")] + public class LoggingAttributeTestWithoutLambdaContextDebug + { + [Fact] + public void OnEntry_WhenLambdaContextDoesNotExist_IgnoresLambdaContextAndLogDebug() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var logLevel = LogLevel.Trace; + + var configurations = new Mock(); + var systemWrapper = new Mock(); + + var eventArgs = new AspectEventArgs + { + Name = methodName, + Args = new object [] { } + }; + + LoggingAspectHandler.ResetForTest(); + var handler = new LoggingAspectHandler(service, logLevel, null, null, true, null, true, configurations.Object, + systemWrapper.Object); + + // Act + handler.OnEntry(eventArgs); + + var allKeys = Logger.GetAllKeys() + .ToDictionary(keyValuePair => keyValuePair.Key, keyValuePair => keyValuePair.Value); + + Assert.NotNull(Logger.LoggerProvider); + Assert.True(allKeys.ContainsKey(LoggingConstants.KeyColdStart)); + Assert.True((bool) allKeys[LoggingConstants.KeyColdStart]); + Assert.False(allKeys.ContainsKey(LoggingConstants.KeyFunctionName)); + Assert.False(allKeys.ContainsKey(LoggingConstants.KeyFunctionVersion)); + Assert.False(allKeys.ContainsKey(LoggingConstants.KeyFunctionMemorySize)); + Assert.False(allKeys.ContainsKey(LoggingConstants.KeyFunctionArn)); + Assert.False(allKeys.ContainsKey(LoggingConstants.KeyFunctionRequestId)); + + systemWrapper.Verify(v => + v.LogLine( + It.Is(i => i == $"Skipping Lambda Context injection because ILambdaContext context parameter not found.") + ), Times.Once); + } + } + + [Collection("Sequential")] + public class LoggingAttributeTestWithoutEventArg + { + [Fact] + public void OnEntry_WhenEventArgDoesNotExist_DoesNotLogEventArg() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var logLevel = LogLevel.Information; + + var configurations = new Mock(); + var systemWrapper = new Mock(); + + var eventArgs = new AspectEventArgs + { + Name = methodName, + Args = new object [] { } + }; + + LoggingAspectHandler.ResetForTest(); + var handler = new LoggingAspectHandler(service, logLevel, null, null, true, null, true, configurations.Object, + systemWrapper.Object); + + // Act + handler.OnEntry(eventArgs); + + systemWrapper.Verify(v => + v.LogLine( + It.IsAny() + ), Times.Never); + } + } + + [Collection("Sequential")] + public class LoggingAttributeTestWithoutEventArgDebug + { + [Fact] + public void OnEntry_WhenEventArgDoesNotExist_DoesNotLogEventArgAndLogDebug() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var logLevel = LogLevel.Trace; + + var configurations = new Mock(); + var systemWrapper = new Mock(); + + var eventArgs = new AspectEventArgs + { + Name = methodName, + Args = new object [] { } + }; + + LoggingAspectHandler.ResetForTest(); + var handler = new LoggingAspectHandler(service, logLevel, null, null, true, null, true, configurations.Object, + systemWrapper.Object); + + // Act + handler.OnEntry(eventArgs); + + systemWrapper.Verify(v => + v.LogLine( + It.Is(i => i == $"Skipping Event Log because event parameter not found.") + ), Times.Once); + } + } + + [Collection("Sequential")] + public class LoggingAttributeTestForClearContext + { + [Fact] + public void OnExit_WhenHandler_ClearKeys() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var logLevel = LogLevel.Trace; + + var configurations = new Mock(); + var systemWrapper = new Mock(); + + var eventArgs = new AspectEventArgs + { + Name = methodName, + Args = new object [] { } + }; + + LoggingAspectHandler.ResetForTest(); + var handler = new LoggingAspectHandler(service, logLevel, null, null, true, null, true, configurations.Object, + systemWrapper.Object); + + // Act + handler.OnEntry(eventArgs); + + var allKeys = Logger.GetAllKeys() + .ToDictionary(keyValuePair => keyValuePair.Key, keyValuePair => keyValuePair.Value); + + Assert.NotNull(Logger.LoggerProvider); + Assert.True(allKeys.ContainsKey(LoggingConstants.KeyColdStart)); + Assert.True((bool) allKeys[LoggingConstants.KeyColdStart]); + + handler.OnExit(eventArgs); + + Assert.NotNull(Logger.LoggerProvider); + Assert.False(Logger.GetAllKeys().Any()); + } + } + + public abstract class LoggingAttributeTestWithEventArgCorrelationId + { + protected void OnEntry_WhenEventArgExists_CapturesCorrelationIdBase(string correlationId, string correlationIdPath, object eventArg) + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var logLevel = LogLevel.Information; + + var configurations = new Mock(); + var systemWrapper = new Mock(); + + var eventArgs = new AspectEventArgs + { + Name = methodName, + Args = new[] { eventArg } + }; + + LoggingAspectHandler.ResetForTest(); + var handler = new LoggingAspectHandler(service, logLevel, null, null, false, correlationIdPath, + true, configurations.Object, + systemWrapper.Object); + + // Act + handler.OnEntry(eventArgs); + + var allKeys = Logger.GetAllKeys() + .ToDictionary(keyValuePair => keyValuePair.Key, keyValuePair => keyValuePair.Value); + + // Assert + Assert.True(allKeys.ContainsKey(LoggingConstants.KeyCorrelationId)); + Assert.Equal((string) allKeys[LoggingConstants.KeyCorrelationId], correlationId); + } + } + + [Collection("Sequential")] + public class LoggingAttributeTestWithEventArgCorrelationIdAPIGateway : LoggingAttributeTestWithEventArgCorrelationId + { + [Fact] + public void OnEntry_WhenEventArgExists_CapturesCorrelationId() + { + var correlationId = Guid.NewGuid().ToString(); + OnEntry_WhenEventArgExists_CapturesCorrelationIdBase + ( + correlationId, + CorrelationIdPaths.ApiGatewayRest, + new APIGatewayProxyRequest + { + RequestContext = new APIGatewayProxyRequest.ProxyRequestContext + { + RequestId = correlationId + } + } + ); + } + } + + [Collection("Sequential")] + public class LoggingAttributeTestWithEventArgCorrelationIdApplicationLoadBalancer : LoggingAttributeTestWithEventArgCorrelationId + { + [Fact] + public void OnEntry_WhenEventArgExists_CapturesCorrelationId() + { + var correlationId = Guid.NewGuid().ToString(); + OnEntry_WhenEventArgExists_CapturesCorrelationIdBase + ( + correlationId, + CorrelationIdPaths.ApplicationLoadBalancer, + new ApplicationLoadBalancerRequest + { + Headers = new Dictionary + { + {"x-amzn-trace-id", correlationId} + } + } + ); + } + } +} \ No newline at end of file diff --git a/libraries/tests/AWS.Lambda.Powertools.Logging.Tests/PowertoolsLoggerTest.cs b/libraries/tests/AWS.Lambda.Powertools.Logging.Tests/PowertoolsLoggerTest.cs new file mode 100644 index 000000000..e75b2eaa9 --- /dev/null +++ b/libraries/tests/AWS.Lambda.Powertools.Logging.Tests/PowertoolsLoggerTest.cs @@ -0,0 +1,1012 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using AWS.Lambda.Powertools.Common; +using AWS.Lambda.Powertools.Logging.Internal; +using Microsoft.Extensions.Logging; +using Moq; +using Xunit; + +namespace AWS.Lambda.Powertools.Logging.Tests +{ + public class PowertoolsLoggerTest + { + private static void Log_WhenMinimumLevelIsBelowLogLevel_Logs(LogLevel logLevel, LogLevel minimumLevel) + { + // Arrange + var loggerName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + + var configurations = new Mock(); + var systemWrapper = new Mock(); + + var logger = new PowertoolsLogger(loggerName,configurations.Object, systemWrapper.Object, () => + new LoggerConfiguration + { + Service = service, + MinimumLevel = minimumLevel + }); + + switch (logLevel) + { + // Act + case LogLevel.Critical: + logger.LogCritical("Test"); + break; + case LogLevel.Debug: + logger.LogDebug("Test"); + break; + case LogLevel.Error: + logger.LogError("Test"); + break; + case LogLevel.Information: + logger.LogInformation("Test"); + break; + case LogLevel.Trace: + logger.LogTrace("Test"); + break; + case LogLevel.Warning: + logger.LogWarning("Test"); + break; + case LogLevel.None: + break; + default: + throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null); + } + + // Assert + systemWrapper.Verify(v => + v.LogLine( + It.Is(s=> s.Contains(service)) + ), Times.Once); + + } + + private static void Log_WhenMinimumLevelIsAboveLogLevel_DoesNotLog(LogLevel logLevel, LogLevel minimumLevel) + { + // Arrange + var loggerName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + + var configurations = new Mock(); + var systemWrapper = new Mock(); + + var logger = new PowertoolsLogger(loggerName,configurations.Object, systemWrapper.Object, () => + new LoggerConfiguration + { + Service = service, + MinimumLevel = minimumLevel + }); + + switch (logLevel) + { + // Act + case LogLevel.Critical: + logger.LogCritical("Test"); + break; + case LogLevel.Debug: + logger.LogDebug("Test"); + break; + case LogLevel.Error: + logger.LogError("Test"); + break; + case LogLevel.Information: + logger.LogInformation("Test"); + break; + case LogLevel.Trace: + logger.LogTrace("Test"); + break; + case LogLevel.Warning: + logger.LogWarning("Test"); + break; + case LogLevel.None: + break; + default: + throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null); + } + + // Assert + systemWrapper.Verify(v => + v.LogLine( + It.IsAny() + ), Times.Never); + + } + + [Theory] + [InlineData(LogLevel.Trace)] + public void LogTrace_WhenMinimumLevelIsBelowLogLevel_Logs(LogLevel minimumLevel) + { + Log_WhenMinimumLevelIsBelowLogLevel_Logs(LogLevel.Trace, minimumLevel); + } + + [Theory] + [InlineData(LogLevel.Trace)] + [InlineData(LogLevel.Debug)] + public void LogDebug_WhenMinimumLevelIsBelowLogLevel_Logs(LogLevel minimumLevel) + { + Log_WhenMinimumLevelIsBelowLogLevel_Logs(LogLevel.Debug, minimumLevel); + } + + [Theory] + [InlineData(LogLevel.Trace)] + [InlineData(LogLevel.Debug)] + [InlineData(LogLevel.Information)] + public void LogInformation_WhenMinimumLevelIsBelowLogLevel_Logs(LogLevel minimumLevel) + { + Log_WhenMinimumLevelIsBelowLogLevel_Logs(LogLevel.Information, minimumLevel); + } + + [Theory] + [InlineData(LogLevel.Trace)] + [InlineData(LogLevel.Debug)] + [InlineData(LogLevel.Information)] + [InlineData(LogLevel.Warning)] + public void LogWarning_WhenMinimumLevelIsBelowLogLevel_Logs(LogLevel minimumLevel) + { + Log_WhenMinimumLevelIsBelowLogLevel_Logs(LogLevel.Warning, minimumLevel); + } + + [Theory] + [InlineData(LogLevel.Trace)] + [InlineData(LogLevel.Debug)] + [InlineData(LogLevel.Information)] + [InlineData(LogLevel.Warning)] + [InlineData(LogLevel.Error)] + public void LogError_WhenMinimumLevelIsBelowLogLevel_Logs(LogLevel minimumLevel) + { + Log_WhenMinimumLevelIsBelowLogLevel_Logs(LogLevel.Error, minimumLevel); + } + + [Theory] + [InlineData(LogLevel.Trace)] + [InlineData(LogLevel.Debug)] + [InlineData(LogLevel.Information)] + [InlineData(LogLevel.Warning)] + [InlineData(LogLevel.Error)] + [InlineData(LogLevel.Critical)] + public void LogCritical_WhenMinimumLevelIsBelowLogLevel_Logs(LogLevel minimumLevel) + { + Log_WhenMinimumLevelIsBelowLogLevel_Logs(LogLevel.Critical, minimumLevel); + } + + + [Theory] + [InlineData(LogLevel.Debug)] + [InlineData(LogLevel.Information)] + [InlineData(LogLevel.Warning)] + [InlineData(LogLevel.Error)] + [InlineData(LogLevel.Critical)] + public void LogTrace_WhenMinimumLevelIsAboveLogLevel_DoesNotLog(LogLevel minimumLevel) + { + Log_WhenMinimumLevelIsAboveLogLevel_DoesNotLog(LogLevel.Trace, minimumLevel); + } + + + [Theory] + [InlineData(LogLevel.Information)] + [InlineData(LogLevel.Warning)] + [InlineData(LogLevel.Error)] + [InlineData(LogLevel.Critical)] + public void LogDebug_WhenMinimumLevelIsAboveLogLevel_DoesNotLog(LogLevel minimumLevel) + { + Log_WhenMinimumLevelIsAboveLogLevel_DoesNotLog(LogLevel.Debug, minimumLevel); + } + + [Theory] + [InlineData(LogLevel.Warning)] + [InlineData(LogLevel.Error)] + [InlineData(LogLevel.Critical)] + public void LogInformation_WhenMinimumLevelIsAboveLogLevel_DoesNotLog(LogLevel minimumLevel) + { + Log_WhenMinimumLevelIsAboveLogLevel_DoesNotLog(LogLevel.Information, minimumLevel); + } + + [Theory] + [InlineData(LogLevel.Error)] + [InlineData(LogLevel.Critical)] + public void LogWarning_WhenMinimumLevelIsAboveLogLevel_DoesNotLog(LogLevel minimumLevel) + { + Log_WhenMinimumLevelIsAboveLogLevel_DoesNotLog(LogLevel.Warning, minimumLevel); + } + + [Theory] + [InlineData(LogLevel.Critical)] + public void LogError_WhenMinimumLevelIsAboveLogLevel_DoesNotLog(LogLevel minimumLevel) + { + Log_WhenMinimumLevelIsAboveLogLevel_DoesNotLog(LogLevel.Error, minimumLevel); + } + + [Theory] + [InlineData(LogLevel.Trace)] + [InlineData(LogLevel.Debug)] + [InlineData(LogLevel.Information)] + [InlineData(LogLevel.Warning)] + [InlineData(LogLevel.Error)] + [InlineData(LogLevel.Critical)] + public void LogNone_WithAnyMinimumLevel_DoesNotLog(LogLevel minimumLevel) + { + Log_WhenMinimumLevelIsAboveLogLevel_DoesNotLog(LogLevel.None, minimumLevel); + } + + [Fact] + public void Log_ConfigurationIsNotProvided_ReadsFromEnvironmentVariables() + { + // Arrange + var loggerName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var logLevel = LogLevel.Trace; + var loggerSampleRate = 0.7; + var randomSampleRate = 0.5; + + var configurations = new Mock(); + configurations.Setup(c => c.Service).Returns(service); + configurations.Setup(c => c.LogLevel).Returns(logLevel.ToString); + configurations.Setup(c => c.LoggerSampleRate).Returns(loggerSampleRate); + + var systemWrapper = new Mock(); + systemWrapper.Setup(c => c.GetRandom()).Returns(randomSampleRate); + + var logger = new PowertoolsLogger(loggerName,configurations.Object, systemWrapper.Object, () => + new LoggerConfiguration + { + Service = null, + MinimumLevel = null + }); + + logger.LogInformation("Test"); + + // Assert + systemWrapper.Verify(v => + v.LogLine( + It.Is + (s=> + s.Contains(service) && + s.Contains(loggerSampleRate.ToString(CultureInfo.InvariantCulture)) + ) + ), Times.Once); + } + + [Fact] + public void Log_SamplingRateGreaterThanRandom_ChangedLogLevelToDebug() + { + // Arrange + var loggerName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var logLevel = LogLevel.Trace; + var loggerSampleRate = 0.7; + var randomSampleRate = 0.5; + + var configurations = new Mock(); + configurations.Setup(c => c.Service).Returns(service); + configurations.Setup(c => c.LogLevel).Returns(logLevel.ToString); + configurations.Setup(c => c.LoggerSampleRate).Returns(loggerSampleRate); + + var systemWrapper = new Mock(); + systemWrapper.Setup(c => c.GetRandom()).Returns(randomSampleRate); + + var logger = new PowertoolsLogger(loggerName,configurations.Object, systemWrapper.Object, () => + new LoggerConfiguration + { + Service = null, + MinimumLevel = null + }); + + logger.LogInformation("Test"); + + // Assert + systemWrapper.Verify(v => + v.LogLine( + It.Is + (s=> + s == $"Changed log level to DEBUG based on Sampling configuration. Sampling Rate: {loggerSampleRate}, Sampler Value: {randomSampleRate}." + ) + ), Times.Once); + + } + + [Fact] + public void Log_SamplingRateGreaterThanOne_SkipsSamplingRateConfiguration() + { + // Arrange + var loggerName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var logLevel = LogLevel.Trace; + var loggerSampleRate = 2; + + var configurations = new Mock(); + configurations.Setup(c => c.Service).Returns(service); + configurations.Setup(c => c.LogLevel).Returns(logLevel.ToString); + configurations.Setup(c => c.LoggerSampleRate).Returns(loggerSampleRate); + + var systemWrapper = new Mock(); + + var logger = new PowertoolsLogger(loggerName,configurations.Object, systemWrapper.Object, () => + new LoggerConfiguration + { + Service = null, + MinimumLevel = null + }); + + logger.LogInformation("Test"); + + // Assert + systemWrapper.Verify(v => + v.LogLine( + It.Is + (s=> + s == $"Skipping sampling rate configuration because of invalid value. Sampling rate: {loggerSampleRate}" + ) + ), Times.Once); + + } + + [Fact] + public void Log_EnvVarSetsCaseToCamelCase_OutputsCamelCaseLog() + { + // Arrange + var loggerName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var logLevel = LogLevel.Information; + var randomSampleRate = 0.5; + + var configurations = new Mock(); + configurations.Setup(c => c.Service).Returns(service); + configurations.Setup(c => c.LogLevel).Returns(logLevel.ToString); + configurations.Setup(c => c.LoggerOutputCase).Returns(LoggerOutputCase.CamelCase.ToString); + + var systemWrapper = new Mock(); + systemWrapper.Setup(c => c.GetRandom()).Returns(randomSampleRate); + + var logger = new PowertoolsLogger(loggerName, configurations.Object, systemWrapper.Object, () => + new LoggerConfiguration + { + Service = null, + MinimumLevel = null + }); + + var message = new { + PropOne = "Value 1", + PropTwo = "Value 2" + }; + + logger.LogInformation(message); + + // Assert + systemWrapper.Verify(v => + v.LogLine( + It.Is + (s => + s.Contains("\"message\":{\"propOne\":\"Value 1\",\"propTwo\":\"Value 2\"}") + ) + ), Times.Once); + } + + [Fact] + public void Log_AttributeSetsCaseToCamelCase_OutputsCamelCaseLog() + { + // Arrange + var loggerName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var logLevel = LogLevel.Information; + var randomSampleRate = 0.5; + + var configurations = new Mock(); + configurations.Setup(c => c.Service).Returns(service); + configurations.Setup(c => c.LogLevel).Returns(logLevel.ToString); + + var systemWrapper = new Mock(); + systemWrapper.Setup(c => c.GetRandom()).Returns(randomSampleRate); + + var logger = new PowertoolsLogger(loggerName, configurations.Object, systemWrapper.Object, () => + new LoggerConfiguration + { + Service = null, + MinimumLevel = null, + LoggerOutputCase = LoggerOutputCase.CamelCase + }); + + var message = new + { + PropOne = "Value 1", + PropTwo = "Value 2" + }; + + logger.LogInformation(message); + + // Assert + systemWrapper.Verify(v => + v.LogLine( + It.Is + (s => + s.Contains("\"message\":{\"propOne\":\"Value 1\",\"propTwo\":\"Value 2\"}") + ) + ), Times.Once); + } + + [Fact] + public void Log_EnvVarSetsCaseToPascalCase_OutputsPascalCaseLog() + { + // Arrange + var loggerName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var logLevel = LogLevel.Information; + var randomSampleRate = 0.5; + + var configurations = new Mock(); + configurations.Setup(c => c.Service).Returns(service); + configurations.Setup(c => c.LogLevel).Returns(logLevel.ToString); + configurations.Setup(c => c.LoggerOutputCase).Returns(LoggerOutputCase.PascalCase.ToString); + + var systemWrapper = new Mock(); + systemWrapper.Setup(c => c.GetRandom()).Returns(randomSampleRate); + + var logger = new PowertoolsLogger(loggerName, configurations.Object, systemWrapper.Object, () => + new LoggerConfiguration + { + Service = null, + MinimumLevel = null + }); + + var message = new + { + PropOne = "Value 1", + PropTwo = "Value 2" + }; + + logger.LogInformation(message); + + // Assert + systemWrapper.Verify(v => + v.LogLine( + It.Is + (s => + s.Contains("\"Message\":{\"PropOne\":\"Value 1\",\"PropTwo\":\"Value 2\"}") + ) + ), Times.Once); + } + + [Fact] + public void Log_AttributeSetsCaseToPascalCase_OutputsPascalCaseLog() + { + // Arrange + var loggerName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var logLevel = LogLevel.Information; + var randomSampleRate = 0.5; + + var configurations = new Mock(); + configurations.Setup(c => c.Service).Returns(service); + configurations.Setup(c => c.LogLevel).Returns(logLevel.ToString); + + var systemWrapper = new Mock(); + systemWrapper.Setup(c => c.GetRandom()).Returns(randomSampleRate); + + var logger = new PowertoolsLogger(loggerName, configurations.Object, systemWrapper.Object, () => + new LoggerConfiguration + { + Service = null, + MinimumLevel = null, + LoggerOutputCase = LoggerOutputCase.PascalCase + }); + + var message = new + { + PropOne = "Value 1", + PropTwo = "Value 2" + }; + + logger.LogInformation(message); + + // Assert + systemWrapper.Verify(v => + v.LogLine( + It.Is + (s => + s.Contains("\"Message\":{\"PropOne\":\"Value 1\",\"PropTwo\":\"Value 2\"}") + ) + ), Times.Once); + } + + [Fact] + public void Log_EnvVarSetsCaseToSnakeCase_OutputsSnakeCaseLog() + { + // Arrange + var loggerName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var logLevel = LogLevel.Information; + var randomSampleRate = 0.5; + + var configurations = new Mock(); + configurations.Setup(c => c.Service).Returns(service); + configurations.Setup(c => c.LogLevel).Returns(logLevel.ToString); + configurations.Setup(c => c.LoggerOutputCase).Returns(LoggerOutputCase.SnakeCase.ToString); + + var systemWrapper = new Mock(); + systemWrapper.Setup(c => c.GetRandom()).Returns(randomSampleRate); + + var logger = new PowertoolsLogger(loggerName, configurations.Object, systemWrapper.Object, () => + new LoggerConfiguration + { + Service = null, + MinimumLevel = null + }); + + var message = new + { + PropOne = "Value 1", + PropTwo = "Value 2" + }; + + logger.LogInformation(message); + + // Assert + systemWrapper.Verify(v => + v.LogLine( + It.Is + (s => + s.Contains("\"message\":{\"prop_one\":\"Value 1\",\"prop_two\":\"Value 2\"}") + ) + ), Times.Once); + } + + [Fact] + public void Log_AttributeSetsCaseToSnakeCase_OutputsSnakeCaseLog() + { + // Arrange + var loggerName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var logLevel = LogLevel.Information; + var randomSampleRate = 0.5; + + var configurations = new Mock(); + configurations.Setup(c => c.Service).Returns(service); + configurations.Setup(c => c.LogLevel).Returns(logLevel.ToString); + + var systemWrapper = new Mock(); + systemWrapper.Setup(c => c.GetRandom()).Returns(randomSampleRate); + + var logger = new PowertoolsLogger(loggerName, configurations.Object, systemWrapper.Object, () => + new LoggerConfiguration + { + Service = null, + MinimumLevel = null, + LoggerOutputCase = LoggerOutputCase.SnakeCase + }); + + var message = new + { + PropOne = "Value 1", + PropTwo = "Value 2" + }; + + logger.LogInformation(message); + + // Assert + systemWrapper.Verify(v => + v.LogLine( + It.Is + (s => + s.Contains("\"message\":{\"prop_one\":\"Value 1\",\"prop_two\":\"Value 2\"}") + ) + ), Times.Once); + } + + [Fact] + public void Log_NoOutputCaseSet_OutputDefaultsToSnakeCaseLog() + { + // Arrange + var loggerName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var logLevel = LogLevel.Information; + var randomSampleRate = 0.5; + + var configurations = new Mock(); + configurations.Setup(c => c.Service).Returns(service); + configurations.Setup(c => c.LogLevel).Returns(logLevel.ToString); + + var systemWrapper = new Mock(); + systemWrapper.Setup(c => c.GetRandom()).Returns(randomSampleRate); + + var logger = new PowertoolsLogger(loggerName, configurations.Object, systemWrapper.Object, () => + new LoggerConfiguration + { + Service = null, + MinimumLevel = null + }); + + var message = new + { + PropOne = "Value 1", + PropTwo = "Value 2" + }; + + logger.LogInformation(message); + + // Assert + systemWrapper.Verify(v => + v.LogLine( + It.Is + (s => + s.Contains("\"message\":{\"prop_one\":\"Value 1\",\"prop_two\":\"Value 2\"}") + ) + ), Times.Once); + } + + [Fact] + public void BeginScope_WhenScopeIsObject_ExtractScopeKeys() + { + // Arrange + var loggerName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var logLevel = LogLevel.Information; + + var configurations = new Mock(); + configurations.Setup(c => c.Service).Returns(service); + configurations.Setup(c => c.LogLevel).Returns(logLevel.ToString); + var systemWrapper = new Mock(); + + var logger = new PowertoolsLogger(loggerName,configurations.Object, systemWrapper.Object, () => + new LoggerConfiguration + { + Service = service, + MinimumLevel = logLevel + }); + + var scopeKeys = new + { + PropOne = "Value 1", + PropTwo = "Value 2" + }; + + using (var loggerScope = logger.BeginScope(scopeKeys) as PowertoolsLoggerScope) + { + Assert.NotNull(loggerScope); + Assert.NotNull(loggerScope.ExtraKeys); + Assert.True(loggerScope.ExtraKeys.Count == 2); + Assert.True(loggerScope.ExtraKeys.ContainsKey("PropOne")); + Assert.True((string)loggerScope.ExtraKeys["PropOne"] == scopeKeys.PropOne); + Assert.True(loggerScope.ExtraKeys.ContainsKey("PropTwo")); + Assert.True((string)loggerScope.ExtraKeys["PropTwo"] == scopeKeys.PropTwo); + } + Assert.Null(logger.CurrentScope?.ExtraKeys); + } + + [Fact] + public void BeginScope_WhenScopeIsObjectDictionary_ExtractScopeKeys() + { + // Arrange + var loggerName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var logLevel = LogLevel.Information; + + var configurations = new Mock(); + configurations.Setup(c => c.Service).Returns(service); + configurations.Setup(c => c.LogLevel).Returns(logLevel.ToString); + var systemWrapper = new Mock(); + + var logger = new PowertoolsLogger(loggerName,configurations.Object, systemWrapper.Object, () => + new LoggerConfiguration + { + Service = service, + MinimumLevel = logLevel + }); + + var scopeKeys = new Dictionary + { + { "PropOne", "Value 1" }, + { "PropTwo", "Value 2" } + }; + + using (var loggerScope = logger.BeginScope(scopeKeys) as PowertoolsLoggerScope) + { + Assert.NotNull(loggerScope); + Assert.NotNull(loggerScope.ExtraKeys); + Assert.True(loggerScope.ExtraKeys.Count == 2); + Assert.True(loggerScope.ExtraKeys.ContainsKey("PropOne")); + Assert.True(loggerScope.ExtraKeys["PropOne"] == scopeKeys["PropOne"]); + Assert.True(loggerScope.ExtraKeys.ContainsKey("PropTwo")); + Assert.True(loggerScope.ExtraKeys["PropTwo"] == scopeKeys["PropTwo"]); + } + Assert.Null(logger.CurrentScope?.ExtraKeys); + } + + [Fact] + public void BeginScope_WhenScopeIsStringDictionary_ExtractScopeKeys() + { + // Arrange + var loggerName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var logLevel = LogLevel.Information; + + var configurations = new Mock(); + configurations.Setup(c => c.Service).Returns(service); + configurations.Setup(c => c.LogLevel).Returns(logLevel.ToString); + var systemWrapper = new Mock(); + + var logger = new PowertoolsLogger(loggerName,configurations.Object, systemWrapper.Object, () => + new LoggerConfiguration + { + Service = service, + MinimumLevel = logLevel + }); + + var scopeKeys = new Dictionary + { + { "PropOne", "Value 1" }, + { "PropTwo", "Value 2" } + }; + + using (var loggerScope = logger.BeginScope(scopeKeys) as PowertoolsLoggerScope) + { + Assert.NotNull(loggerScope); + Assert.NotNull(loggerScope.ExtraKeys); + Assert.True(loggerScope.ExtraKeys.Count == 2); + Assert.True(loggerScope.ExtraKeys.ContainsKey("PropOne")); + Assert.True((string)loggerScope.ExtraKeys["PropOne"] == scopeKeys["PropOne"]); + Assert.True(loggerScope.ExtraKeys.ContainsKey("PropTwo")); + Assert.True((string)loggerScope.ExtraKeys["PropTwo"] == scopeKeys["PropTwo"]); + } + Assert.Null(logger.CurrentScope?.ExtraKeys); + } + + [Theory] + [InlineData(LogLevel.Trace, true)] + [InlineData(LogLevel.Debug, true)] + [InlineData(LogLevel.Information, true)] + [InlineData(LogLevel.Warning, true)] + [InlineData(LogLevel.Error, true)] + [InlineData(LogLevel.Critical, true)] + [InlineData(LogLevel.Trace, false)] + [InlineData(LogLevel.Debug, false)] + [InlineData(LogLevel.Information, false)] + [InlineData(LogLevel.Warning, false)] + [InlineData(LogLevel.Error, false)] + [InlineData(LogLevel.Critical, false)] + public void Log_WhenExtraKeysIsObjectDictionary_AppendExtraKeys(LogLevel logLevel, bool logMethod) + { + // Arrange + var loggerName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var message = Guid.NewGuid().ToString(); + + var configurations = new Mock(); + configurations.Setup(c => c.Service).Returns(service); + configurations.Setup(c => c.LogLevel).Returns(logLevel.ToString); + configurations.Setup(c => c.LoggerOutputCase).Returns(LoggerOutputCase.PascalCase.ToString); + var systemWrapper = new Mock(); + + var logger = new PowertoolsLogger(loggerName,configurations.Object, systemWrapper.Object, () => + new LoggerConfiguration + { + Service = service, + MinimumLevel = LogLevel.Trace, + }); + + var scopeKeys = new Dictionary + { + { "PropOne", "Value 1" }, + { "PropTwo", "Value 2" } + }; + + if(logMethod) + logger.Log(logLevel, scopeKeys, message); + else switch (logLevel) + { + case LogLevel.Trace: + logger.LogTrace(scopeKeys, message); + break; + case LogLevel.Debug: + logger.LogDebug(scopeKeys, message); + break; + case LogLevel.Information: + logger.LogInformation(scopeKeys, message); + break; + case LogLevel.Warning: + logger.LogWarning(scopeKeys, message); + break; + case LogLevel.Error: + logger.LogError(scopeKeys, message); + break; + case LogLevel.Critical: + logger.LogCritical(scopeKeys, message); + break; + case LogLevel.None: + break; + default: + throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null); + } + + systemWrapper.Verify(v => + v.LogLine( + It.Is + (s=> + s.Contains(scopeKeys.Keys.First()) && + s.Contains(scopeKeys.Keys.Last()) && + s.Contains(scopeKeys.Values.First().ToString()) && + s.Contains(scopeKeys.Values.Last().ToString()) + ) + ), Times.Once); + + Assert.Null(logger.CurrentScope?.ExtraKeys); + } + + [Theory] + [InlineData(LogLevel.Trace, true)] + [InlineData(LogLevel.Debug, true)] + [InlineData(LogLevel.Information, true)] + [InlineData(LogLevel.Warning, true)] + [InlineData(LogLevel.Error, true)] + [InlineData(LogLevel.Critical, true)] + [InlineData(LogLevel.Trace, false)] + [InlineData(LogLevel.Debug, false)] + [InlineData(LogLevel.Information, false)] + [InlineData(LogLevel.Warning, false)] + [InlineData(LogLevel.Error, false)] + [InlineData(LogLevel.Critical, false)] + public void Log_WhenExtraKeysIsStringDictionary_AppendExtraKeys(LogLevel logLevel, bool logMethod) + { + // Arrange + var loggerName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var message = Guid.NewGuid().ToString(); + + var configurations = new Mock(); + configurations.Setup(c => c.Service).Returns(service); + configurations.Setup(c => c.LogLevel).Returns(logLevel.ToString); + configurations.Setup(c => c.LoggerOutputCase).Returns(LoggerOutputCase.PascalCase.ToString); + var systemWrapper = new Mock(); + + var logger = new PowertoolsLogger(loggerName,configurations.Object, systemWrapper.Object, () => + new LoggerConfiguration + { + Service = service, + MinimumLevel = LogLevel.Trace, + }); + + var scopeKeys = new Dictionary + { + { "PropOne", "Value 1" }, + { "PropTwo", "Value 2" } + }; + + if(logMethod) + logger.Log(logLevel, scopeKeys, message); + else switch (logLevel) + { + case LogLevel.Trace: + logger.LogTrace(scopeKeys, message); + break; + case LogLevel.Debug: + logger.LogDebug(scopeKeys, message); + break; + case LogLevel.Information: + logger.LogInformation(scopeKeys, message); + break; + case LogLevel.Warning: + logger.LogWarning(scopeKeys, message); + break; + case LogLevel.Error: + logger.LogError(scopeKeys, message); + break; + case LogLevel.Critical: + logger.LogCritical(scopeKeys, message); + break; + case LogLevel.None: + break; + default: + throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null); + } + + systemWrapper.Verify(v => + v.LogLine( + It.Is + (s=> + s.Contains(scopeKeys.Keys.First()) && + s.Contains(scopeKeys.Keys.Last()) && + s.Contains(scopeKeys.Values.First()) && + s.Contains(scopeKeys.Values.Last()) + ) + ), Times.Once); + + Assert.Null(logger.CurrentScope?.ExtraKeys); + } + + [Theory] + [InlineData(LogLevel.Trace, true)] + [InlineData(LogLevel.Debug, true)] + [InlineData(LogLevel.Information, true)] + [InlineData(LogLevel.Warning, true)] + [InlineData(LogLevel.Error, true)] + [InlineData(LogLevel.Critical, true)] + [InlineData(LogLevel.Trace, false)] + [InlineData(LogLevel.Debug, false)] + [InlineData(LogLevel.Information, false)] + [InlineData(LogLevel.Warning, false)] + [InlineData(LogLevel.Error, false)] + [InlineData(LogLevel.Critical, false)] + public void Log_WhenExtraKeysAsObject_AppendExtraKeys(LogLevel logLevel, bool logMethod) + { + // Arrange + var loggerName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var message = Guid.NewGuid().ToString(); + + var configurations = new Mock(); + configurations.Setup(c => c.Service).Returns(service); + configurations.Setup(c => c.LogLevel).Returns(logLevel.ToString); + configurations.Setup(c => c.LoggerOutputCase).Returns(LoggerOutputCase.PascalCase.ToString); + var systemWrapper = new Mock(); + + var logger = new PowertoolsLogger(loggerName,configurations.Object, systemWrapper.Object, () => + new LoggerConfiguration + { + Service = service, + MinimumLevel = LogLevel.Trace, + }); + + var scopeKeys = new + { + PropOne = "Value 1", + PropTwo = "Value 2" + }; + + if(logMethod) + logger.Log(logLevel, scopeKeys, message); + else switch (logLevel) + { + case LogLevel.Trace: + logger.LogTrace(scopeKeys, message); + break; + case LogLevel.Debug: + logger.LogDebug(scopeKeys, message); + break; + case LogLevel.Information: + logger.LogInformation(scopeKeys, message); + break; + case LogLevel.Warning: + logger.LogWarning(scopeKeys, message); + break; + case LogLevel.Error: + logger.LogError(scopeKeys, message); + break; + case LogLevel.Critical: + logger.LogCritical(scopeKeys, message); + break; + case LogLevel.None: + break; + default: + throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null); + } + + systemWrapper.Verify(v => + v.LogLine( + It.Is + (s=> + s.Contains("PropOne") && + s.Contains("PropTwo") && + s.Contains(scopeKeys.PropOne) && + s.Contains(scopeKeys.PropTwo) + ) + ), Times.Once); + + Assert.Null(logger.CurrentScope?.ExtraKeys); + } + } +} \ No newline at end of file diff --git a/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/AWS.Lambda.Powertools.Metrics.Tests.csproj b/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/AWS.Lambda.Powertools.Metrics.Tests.csproj new file mode 100644 index 000000000..52ef59b02 --- /dev/null +++ b/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/AWS.Lambda.Powertools.Metrics.Tests.csproj @@ -0,0 +1,27 @@ + + + + net6.0 + + false + + default + + AWS.Lambda.Powertools.Metrics.Tests + + AWS.Lambda.Powertools.Metrics.Tests + + + + + + + + + + + + + + + diff --git a/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/EMFValidationTests.cs b/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/EMFValidationTests.cs new file mode 100644 index 000000000..a9b98da8a --- /dev/null +++ b/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/EMFValidationTests.cs @@ -0,0 +1,558 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.IO; +using AWS.Lambda.Powertools.Common; +using Moq; +using Xunit; + +[assembly: CollectionBehavior(DisableTestParallelization = true)] + +namespace AWS.Lambda.Powertools.Metrics.Tests +{ + [Collection("Sequential")] + public class EmfValidationTests + { + [Trait("Category", value: "SchemaValidation")] + [Fact] + public void WhenCaptureColdStart_CreateSeparateBlob() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var consoleOut = new StringWriter(); + Console.SetOut(consoleOut); + + var configurations = new Mock(); + + var logger = new Powertools.Metrics.Metrics( + configurations.Object, + nameSpace: "dotnet-powertools-test", + service: "testService" + ); + + var handler = new MetricsAspectHandler( + logger, + true + ); + + var eventArgs = new AspectEventArgs { Name = methodName }; + + // Act + handler.OnEntry(eventArgs); + Powertools.Metrics.Metrics.AddMetric("TestMetric", 1, MetricUnit.Count); + handler.OnExit(eventArgs); + + var metricsOutput = consoleOut.ToString(); + + // Assert + var metricBlobs = AllIndexesOf(metricsOutput.ToString(), "_aws"); + + Assert.Equal(2, metricBlobs.Count); + + // Reset + handler.ResetForTest(); + } + + [Trait("Category", "SchemaValidation")] + [Fact] + public void WhenCaptureColdStartEnabled_ValidateExists() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var consoleOut = new StringWriter(); + Console.SetOut(consoleOut); + + var configurations = new Mock(); + + var logger = new Powertools.Metrics.Metrics( + configurations.Object, + nameSpace: "dotnet-powertools-test", + service: "testService" + ); + + var handler = new MetricsAspectHandler( + logger, + true + ); + + var eventArgs = new AspectEventArgs { Name = methodName }; + + // Act + handler.OnEntry(eventArgs); + Powertools.Metrics.Metrics.AddMetric("TestMetric", 1, MetricUnit.Count); + handler.OnExit(eventArgs); + + var result = consoleOut.ToString(); + + // Assert + Assert.Contains("\"Metrics\":[{\"Name\":\"ColdStart\",\"Unit\":\"Count\"}]", result); + Assert.Contains("\"ColdStart\":1", result); + + handler.ResetForTest(); + } + + [Trait("Category", "EMFLimits")] + [Fact] + public void When100MetricsAreAdded_FlushAutomatically() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var consoleOut = new StringWriter(); + Console.SetOut(consoleOut); + + var configurations = new Mock(); + + var logger = new Powertools.Metrics.Metrics( + configurations.Object, + nameSpace: "dotnet-powertools-test", + service: "testService" + ); + + var handler = new MetricsAspectHandler( + logger, + false + ); + + var eventArgs = new AspectEventArgs { Name = methodName }; + + // Act + handler.OnEntry(eventArgs); + + for (int i = 0; i <= 100; i++) + { + Powertools.Metrics.Metrics.AddMetric($"Metric Name {i + 1}", i, MetricUnit.Count); + } + + handler.OnExit(eventArgs); + + var metricsOutput = consoleOut.ToString(); + + // Assert + Assert.Contains("{\"Namespace\":\"dotnet-powertools-test\",\"Metrics\":[{\"Name\":\"Metric Name 101\",\"Unit\":\"Count\"}],\"Dimensions\":[[\"Service\"]", metricsOutput); + + // Reset + handler.ResetForTest(); + } + + + + [Trait("Category", "EMFLimits")] + [Fact] + public void WhenMoreThan9DimensionsAdded_ThrowArgumentOutOfRangeException() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var configurations = new Mock(); + + var logger = new Powertools.Metrics.Metrics( + configurations.Object, + nameSpace: "dotnet-powertools-test", + service: "testService" + ); + + var handler = new MetricsAspectHandler( + logger, + false + ); + + var eventArgs = new AspectEventArgs { Name = methodName }; + + // Act + handler.OnEntry(eventArgs); + + Action act = () => + { + for (var i = 0; i <= 9; i++) + { + Powertools.Metrics.Metrics.AddDimension($"Dimension Name {i + 1}", $"Dimension Value {i + 1}"); + } + }; + + handler.OnExit(eventArgs); + + // Assert + Assert.Throws(act); + + // Reset + handler.ResetForTest(); + } + + [Trait("Category", "SchemaValidation")] + [Fact] + public void WhenNamespaceNotDefined_ThrowSchemaValidationException() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var configurations = new Mock(); + + var logger = new Powertools.Metrics.Metrics( + configurations.Object + ); + + var handler = new MetricsAspectHandler( + logger, + false + ); + + var eventArgs = new AspectEventArgs { Name = methodName }; + + // Act + Action act = () => + { + handler.OnEntry(eventArgs); + Powertools.Metrics.Metrics.AddMetric("TestMetric", 1, MetricUnit.Count); + handler.OnExit(eventArgs); + }; + + // Assert + var exception = Assert.Throws(act); + Assert.Equal("EMF schema is invalid. 'namespace' is mandatory and not specified.", exception.Message); + + // RESET + handler.ResetForTest(); + } + + [Trait("Category", "SchemaValidation")] + [Fact] + public void WhenDimensionsAreAdded_MustExistAsMembers() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var consoleOut = new StringWriter(); + Console.SetOut(consoleOut); + + var configurations = new Mock(); + + var logger = new Powertools.Metrics.Metrics( + configurations.Object, + nameSpace: "dotnet-powertools-test", + service: "testService" + ); + + var handler = new MetricsAspectHandler( + logger, + false + ); + + var eventArgs = new AspectEventArgs { Name = methodName }; + + // Act + handler.OnEntry(eventArgs); + Powertools.Metrics.Metrics.AddDimension("functionVersion", "$LATEST"); + Powertools.Metrics.Metrics.AddMetric("TestMetric", 1, MetricUnit.Count); + handler.OnExit(eventArgs); + + var result = consoleOut.ToString(); + + // Assert + Assert.Contains("\"Dimensions\":[[\"Service\"],[\"functionVersion\"]]" + , result); + Assert.Contains("\"Service\":\"testService\",\"functionVersion\":\"$LATEST\"" + , result); + + // Reset + handler.ResetForTest(); + } + + [Trait("Category", "MetricsImplementation")] + [Fact] + public void WhenNamespaceIsDefined_AbleToRetrieveNamespace() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var configurations = new Mock(); + var logger = new Powertools.Metrics.Metrics(configurations.Object); + + var handler = new MetricsAspectHandler( + logger, + false + ); + + var eventArgs = new AspectEventArgs { Name = methodName }; + + // Act + handler.OnEntry(eventArgs); + Powertools.Metrics.Metrics.SetNamespace("dotnet-powertools-test"); + + var result = Powertools.Metrics.Metrics.GetNamespace(); + + // Assert + Assert.Equal("dotnet-powertools-test", result); + + // Reset + handler.ResetForTest(); + } + + [Trait("Category", "MetricsImplementation")] + [Fact] + public void WhenMetricsDefined_AbleToAddMetadata() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var consoleOut = new StringWriter(); + Console.SetOut(consoleOut); + + var configurations = new Mock(); + var logger = new Powertools.Metrics.Metrics( + configurations.Object, + nameSpace: "dotnet-powertools-test", + service: "testService" + ); + + var handler = new MetricsAspectHandler( + logger, + false + ); + + var eventArgs = new AspectEventArgs { Name = methodName }; + + // Act + handler.OnEntry(eventArgs); + Powertools.Metrics.Metrics.AddMetadata("test_metadata", "test_value"); + handler.OnExit(eventArgs); + + var result = consoleOut.ToString(); + + // Assert + Assert.Contains("\"test_metadata\":\"test_value\"", result); + + // Reset + handler.ResetForTest(); + } + + [Trait("Category", "MetricsImplementation")] + [Fact] + public void WhenDefaultDimensionsSet_ValidInitialization() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var consoleOut = new StringWriter(); + Console.SetOut(consoleOut); + + var defaultDimensions = new Dictionary { { "CustomDefaultDimension", "CustomDefaultDimensionValue" } }; + var configurations = new Mock(); + + var logger = new Powertools.Metrics.Metrics( + configurations.Object, + nameSpace: "dotnet-powertools-test", + service: "testService" + ); + + var handler = new MetricsAspectHandler( + logger, + false + ); + + var eventArgs = new AspectEventArgs { Name = methodName }; + + // Act + handler.OnEntry(eventArgs); + Powertools.Metrics.Metrics.SetDefaultDimensions(defaultDimensions); + Powertools.Metrics.Metrics.AddMetric("TestMetric", 1, MetricUnit.Count); + handler.OnExit(eventArgs); + + var result = consoleOut.ToString(); + + // Assert + Assert.Contains("\"Dimensions\":[[\"Service\"],[\"CustomDefaultDimension\"]", result); + Assert.Contains("\"CustomDefaultDimension\":\"CustomDefaultDimensionValue\"", result); + + // Reset + handler.ResetForTest(); + } + + [Trait("Category", "MetricsImplementation")] + [Fact] + public void WhenMetricIsNegativeValue_ThrowException() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var configurations = new Mock(); + + var logger = new Powertools.Metrics.Metrics( + configurations.Object, + nameSpace: "dotnet-powertools-test", + service: "testService" + ); + + var handler = new MetricsAspectHandler( + logger, + false + ); + + var eventArgs = new AspectEventArgs { Name = methodName }; + + // Act + Action act = () => + { + int metricValue = -1; + handler.OnEntry(eventArgs); + Powertools.Metrics.Metrics.AddMetric("TestMetric", metricValue, MetricUnit.Count); + handler.OnExit(eventArgs); + }; + + // Assert + var exception = Assert.Throws(act); + Assert.Equal("'AddMetric' method requires a valid metrics value. Value must be >= 0.", exception.Message); + + // RESET + handler.ResetForTest(); + } + + [Trait("Category", "SchemaValidation")] + [Fact] + public void WhenDefaultDimensionSet_IgnoreDuplicates() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var consoleOut = new StringWriter(); + Console.SetOut(consoleOut); + var configurations = new Mock(); + var defaultDimensions = new Dictionary { { "CustomDefaultDimension", "CustomDefaultDimensionValue" } }; + + var logger = new Powertools.Metrics.Metrics( + configurations.Object, + nameSpace: "dotnet-powertools-test", + service: "testService" + ); + + var handler = new MetricsAspectHandler( + logger, + false + ); + + var eventArgs = new AspectEventArgs { Name = methodName }; + + // Act + handler.OnEntry(eventArgs); + Powertools.Metrics.Metrics.SetDefaultDimensions(defaultDimensions); + Powertools.Metrics.Metrics.SetDefaultDimensions(defaultDimensions); + Powertools.Metrics.Metrics.AddMetric("TestMetric", 1, MetricUnit.Count); + handler.OnExit(eventArgs); + + var result = consoleOut.ToString(); + + // Assert + Assert.Contains("\"Dimensions\":[[\"Service\"],[\"CustomDefaultDimension\"]", result); + Assert.Contains("\"CustomDefaultDimension\":\"CustomDefaultDimensionValue\"", result); + + // Reset + handler.ResetForTest(); + } + + [Fact] + public void WhenMetricsAndMetadataAdded_ValidateOutput() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var consoleOut = new StringWriter(); + Console.SetOut(consoleOut); + var configurations = new Mock(); + + var logger = new Powertools.Metrics.Metrics( + configurations.Object, + nameSpace: "dotnet-powertools-test", + service: "testService" + ); + + var handler = new MetricsAspectHandler( + logger, + false + ); + + var eventArgs = new AspectEventArgs { Name = methodName }; + + // Act + handler.OnEntry(eventArgs); + Powertools.Metrics.Metrics.AddDimension("functionVersion", "$LATEST"); + Powertools.Metrics.Metrics.AddMetric("Time", 100.7, MetricUnit.Milliseconds); + Powertools.Metrics.Metrics.AddMetadata("env", "dev"); + handler.OnExit(eventArgs); + + var result = consoleOut.ToString(); + + // Assert + Assert.Contains("CloudWatchMetrics\":[{\"Namespace\":\"dotnet-powertools-test\",\"Metrics\":[{\"Name\":\"Time\",\"Unit\":\"Milliseconds\"}],\"Dimensions\":[[\"Service\"],[\"functionVersion\"]]}]},\"Service\":\"testService\",\"functionVersion\":\"$LATEST\",\"env\":\"dev\",\"Time\":100.7}" + , result); + + // Reset + handler.ResetForTest(); + } + + [Trait("Category", "MetricsImplementation")] + [Fact] + public void WhenMetricsWithSameNameAdded_ValidateMetricArray() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var consoleOut = new StringWriter(); + Console.SetOut(consoleOut); + + var configurations = new Mock(); + + var logger = new Powertools.Metrics.Metrics( + configurations.Object, + nameSpace: "dotnet-powertools-test", + service: "testService" + ); + + var handler = new MetricsAspectHandler( + logger, + false + ); + + var eventArgs = new AspectEventArgs { Name = methodName }; + + // Act + handler.OnEntry(eventArgs); + Powertools.Metrics.Metrics.AddDimension("functionVersion", "$LATEST"); + Powertools.Metrics.Metrics.AddMetric("Time", 100.5, MetricUnit.Milliseconds); + Powertools.Metrics.Metrics.AddMetric("Time", 200, MetricUnit.Milliseconds); + handler.OnExit(eventArgs); + + var result = consoleOut.ToString(); + + // Assert + Assert.Contains("\"Metrics\":[{\"Name\":\"Time\",\"Unit\":\"Milliseconds\"}]" + , result); + Assert.Contains("\"Time\":[100.5,200]" + , result); + + // Reset + handler.ResetForTest(); + } + + #region Helpers + + private List AllIndexesOf(string str, string value) + { + var indexes = new List(); + + if (string.IsNullOrEmpty(value)) return indexes; + + for (var index = 0; ; index += value.Length) + { + index = str.IndexOf(value, index, StringComparison.Ordinal); + if (index == -1) + return indexes; + indexes.Add(index); + } + } + + #endregion + } +} diff --git a/libraries/tests/AWS.Lambda.Powertools.Tracing.Tests/AWS.Lambda.Powertools.Tracing.Tests.csproj b/libraries/tests/AWS.Lambda.Powertools.Tracing.Tests/AWS.Lambda.Powertools.Tracing.Tests.csproj new file mode 100644 index 000000000..38d46e895 --- /dev/null +++ b/libraries/tests/AWS.Lambda.Powertools.Tracing.Tests/AWS.Lambda.Powertools.Tracing.Tests.csproj @@ -0,0 +1,25 @@ + + + + net6.0 + default + AWS.Lambda.Powertools.Tracing.Tests + AWS.Lambda.Powertools.Tracing.Tests + + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + diff --git a/libraries/tests/AWS.Lambda.Powertools.Tracing.Tests/TracingAttributeTest.cs b/libraries/tests/AWS.Lambda.Powertools.Tracing.Tests/TracingAttributeTest.cs new file mode 100644 index 000000000..c5cf016df --- /dev/null +++ b/libraries/tests/AWS.Lambda.Powertools.Tracing.Tests/TracingAttributeTest.cs @@ -0,0 +1,790 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; +using System.Linq; +using AWS.Lambda.Powertools.Common; +using AWS.Lambda.Powertools.Tracing.Internal; +using Moq; +using Xunit; + +[assembly: CollectionBehavior(DisableTestParallelization = true)] + +namespace AWS.Lambda.Powertools.Tracing.Tests +{ + [Collection("Sequential")] + public class TracingAttributeColdStartTest + { + [Fact] + public void OnEntry_WhenFirstCall_CapturesColdStart() + { + // Arrange + const bool isColdStart = true; + var methodName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + + var configurations1 = new Mock(); + configurations1.Setup(c => c.TracingDisabled).Returns(false); + configurations1.Setup(c => c.IsLambdaEnvironment).Returns(true); + configurations1.Setup(c => c.IsServiceDefined).Returns(true); + configurations1.Setup(c => c.Service).Returns(service); + + var configurations2 = new Mock(); + configurations2.Setup(c => c.TracingDisabled).Returns(false); + configurations2.Setup(c => c.IsLambdaEnvironment).Returns(true); + configurations2.Setup(c => c.IsServiceDefined).Returns(false); + + var recorder1 = new Mock(); + var recorder2 = new Mock(); + var recorder3 = new Mock(); + var recorder4 = new Mock(); + + TracingAspectHandler.ResetForTest(); + var handler1 = new TracingAspectHandler(null, null, TracingCaptureMode.EnvironmentVariable, + configurations1.Object, recorder1.Object); + var handler2 = new TracingAspectHandler(null, null, TracingCaptureMode.EnvironmentVariable, + configurations1.Object, recorder2.Object); + var handler3 = new TracingAspectHandler(null, null, TracingCaptureMode.EnvironmentVariable, + configurations2.Object, recorder3.Object); + var handler4 = new TracingAspectHandler(null, null, TracingCaptureMode.EnvironmentVariable, + configurations2.Object, recorder4.Object); + + var eventArgs = new AspectEventArgs {Name = methodName}; + + // Act + // Cold Start Execution + handler1.OnEntry(eventArgs); + handler2.OnEntry(eventArgs); + handler2.OnExit(eventArgs); + handler1.OnExit(eventArgs); + + // Warm Start Execution + handler3.OnEntry(eventArgs); + handler4.OnEntry(eventArgs); + handler4.OnExit(eventArgs); + handler3.OnExit(eventArgs); + + // Assert + recorder1.Verify(v => + v.AddAnnotation( + It.Is(i => i == "ColdStart"), + It.Is(i => i == isColdStart) + ), Times.Once); + + recorder1.Verify(v => + v.AddAnnotation( + It.Is(i => i == "Service"), + It.Is(i => i == service) + ), Times.Once); + + recorder2.Verify(v => + v.AddAnnotation( + It.IsAny(), + It.IsAny() + ), Times.Never); + + recorder2.Verify(v => + v.AddAnnotation( + It.IsAny(), + It.IsAny() + ), Times.Never); + + recorder3.Verify(v => + v.AddAnnotation( + It.Is(i => i == "ColdStart"), + It.Is(i => i == !isColdStart) + ), Times.Once); + + recorder3.Verify(v => + v.AddAnnotation( + It.IsAny(), + It.IsAny() + ), Times.Never); + + recorder4.Verify(v => + v.AddAnnotation( + It.IsAny(), + It.IsAny() + ), Times.Never); + + recorder3.Verify(v => + v.AddAnnotation( + It.IsAny(), + It.IsAny() + ), Times.Never); + } + } + + [Collection("Sequential")] + public class TracingAttributeDisableTest + { + [Fact] + public void Tracing_WhenTracerDisabled_DDisablesTracing() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var configurations1 = new Mock(); + configurations1.Setup(c => c.TracingDisabled).Returns(true); + configurations1.Setup(c => c.IsLambdaEnvironment).Returns(true); + + var configurations2 = new Mock(); + configurations2.Setup(c => c.TracingDisabled).Returns(true); + configurations2.Setup(c => c.IsLambdaEnvironment).Returns(true); + + var recorder1 = new Mock(); + var recorder2 = new Mock(); + + TracingAspectHandler.ResetForTest(); + var handler1 = new TracingAspectHandler(null, null, TracingCaptureMode.EnvironmentVariable, + configurations1.Object, recorder1.Object); + var handler2 = new TracingAspectHandler(null, null, TracingCaptureMode.EnvironmentVariable, + configurations1.Object, recorder2.Object); + + var results = new[] {"A", "B"}; + var exception = new Exception("Test Exception"); + var eventArgs = new AspectEventArgs { Name = methodName }; + + // Act + // Cold Start Execution + handler1.OnEntry(eventArgs); + handler1.OnSuccess(eventArgs, results); + object Act1() => handler1.OnException(eventArgs, exception); + handler1.OnExit(eventArgs); + + // Warm Start Execution + handler2.OnEntry(eventArgs); + handler2.OnSuccess(eventArgs, results); + object Act2() => handler2.OnException(eventArgs, exception); + handler2.OnExit(eventArgs); + + // Assert + recorder1.Verify(v => v.BeginSubsegment(It.IsAny()), Times.Never); + recorder1.Verify(v => v.EndSubsegment(), Times.Never); + recorder1.Verify(v => + v.AddMetadata( + It.IsAny(), + It.IsAny(), + It.IsAny() + ), Times.Never); + Assert.Throws(Act1); + recorder1.Verify(v => + v.AddMetadata( + It.IsAny(), + It.IsAny(), + It.IsAny() + ), Times.Never); + + recorder2.Verify(v => v.BeginSubsegment(It.IsAny()), Times.Never); + recorder2.Verify(v => v.EndSubsegment(), Times.Never); + recorder2.Verify(v => + v.AddMetadata( + It.IsAny(), + It.IsAny(), + It.IsAny() + ), Times.Never); + Assert.Throws(Act2); + recorder2.Verify(v => + v.AddMetadata( + It.IsAny(), + It.IsAny(), + It.IsAny() + ), Times.Never); + } + } + + [Collection("Sequential")] + public class TracingAttributeLambdaEnvironmentTest + { + [Fact] + public void Tracing_WhenOutsideOfLambdaEnv_DisablesTracing() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var configurations1 = new Mock(); + configurations1.Setup(c => c.TracingDisabled).Returns(false); + configurations1.Setup(c => c.IsLambdaEnvironment).Returns(false); + + var configurations2 = new Mock(); + configurations2.Setup(c => c.TracingDisabled).Returns(true); + configurations2.Setup(c => c.IsLambdaEnvironment).Returns(true); + + var recorder1 = new Mock(); + var recorder2 = new Mock(); + + TracingAspectHandler.ResetForTest(); + var handler1 = new TracingAspectHandler(null, null, TracingCaptureMode.EnvironmentVariable, + configurations1.Object, recorder1.Object); + var handler2 = new TracingAspectHandler(null, null, TracingCaptureMode.EnvironmentVariable, + configurations1.Object, recorder2.Object); + + var results = new[] {"A", "B"}; + var exception = new Exception("Test Exception"); + var eventArgs = new AspectEventArgs { Name = methodName }; + + // Act + // Cold Start Execution + handler1.OnEntry(eventArgs); + handler1.OnSuccess(eventArgs, results); + object Act1() => handler1.OnException(eventArgs, exception); + handler1.OnExit(eventArgs); + + // Warm Start Execution + handler2.OnEntry(eventArgs); + handler2.OnSuccess(eventArgs, results); + object Act2() => handler2.OnException(eventArgs, exception); + handler2.OnExit(eventArgs); + + // Assert + recorder1.Verify(v => v.BeginSubsegment(It.IsAny()), Times.Never); + recorder1.Verify(v => v.EndSubsegment(), Times.Never); + recorder1.Verify(v => + v.AddMetadata( + It.IsAny(), + It.IsAny(), + It.IsAny() + ), Times.Never); + Assert.Throws(Act1); + recorder1.Verify(v => + v.AddMetadata( + It.IsAny(), + It.IsAny(), + It.IsAny() + ), Times.Never); + + recorder2.Verify(v => v.BeginSubsegment(It.IsAny()), Times.Never); + recorder2.Verify(v => v.EndSubsegment(), Times.Never); + recorder2.Verify(v => + v.AddMetadata( + It.IsAny(), + It.IsAny(), + It.IsAny() + ), Times.Never); + Assert.Throws(Act2); + recorder2.Verify(v => + v.AddMetadata( + It.IsAny(), + It.IsAny(), + It.IsAny() + ), Times.Never); + } + } + + [Collection("Sequential")] + public class TracingAttributeTest + { + public TracingAttributeTest() + { + TracingAspectHandler.ResetForTest(); + } + + #region OnEntry Tests + + [Fact] + public void OnEntry_WhenSegmentNameIsNull_BeginSubsegmentWithMethodName() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var configurations = new Mock(); + configurations.Setup(c => c.IsLambdaEnvironment).Returns(true); + configurations.Setup(c => c.TracingDisabled).Returns(false); + var recorder = new Mock(); + + var handler = new TracingAspectHandler(null, null, TracingCaptureMode.EnvironmentVariable, + configurations.Object, recorder.Object); + var eventArgs = new AspectEventArgs {Name = methodName}; + + // Act + handler.OnEntry(eventArgs); + + // Assert + recorder.Verify(v => + v.BeginSubsegment( + It.Is(i => i == $"## {methodName}") + ), Times.Once); + } + + [Fact] + public void OnEntry_WhenSegmentNameHasValue_BeginSubsegmentWithValue() + { + // Arrange + var segmentName = Guid.NewGuid().ToString(); + var methodName = Guid.NewGuid().ToString(); + var configurations = new Mock(); + configurations.Setup(c => c.IsLambdaEnvironment).Returns(true); + configurations.Setup(c => c.TracingDisabled).Returns(false); + var recorder = new Mock(); + + var handler = new TracingAspectHandler(segmentName, null, TracingCaptureMode.EnvironmentVariable, + configurations.Object, recorder.Object); + var eventArgs = new AspectEventArgs {Name = methodName}; + + // Act + handler.OnEntry(eventArgs); + + // Assert + recorder.Verify(v => + v.BeginSubsegment( + It.Is(i => i == segmentName) + ), Times.Once); + } + + [Fact] + public void OnEntry_WhenNamespaceIsNull_SetNamespaceWithService() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var service = Guid.NewGuid().ToString(); + var configurations = new Mock(); + configurations.Setup(c => c.IsLambdaEnvironment).Returns(true); + configurations.Setup(c => c.TracingDisabled).Returns(false); + configurations.Setup(c => c.Service).Returns(service); + var recorder = new Mock(); + + var handler = new TracingAspectHandler(null, null, TracingCaptureMode.EnvironmentVariable, + configurations.Object, recorder.Object); + var eventArgs = new AspectEventArgs {Name = methodName}; + + // Act + handler.OnEntry(eventArgs); + + // Assert + recorder.Verify(v => + v.SetNamespace( + It.Is(i => i == service) + ), Times.Once); + } + + [Fact] + public void OnEntry_WhenNamespaceHasValue_SetNamespaceWithValue() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var nameSpace = Guid.NewGuid().ToString(); + var configurations = new Mock(); + configurations.Setup(c => c.IsLambdaEnvironment).Returns(true); + configurations.Setup(c => c.TracingDisabled).Returns(false); + var recorder = new Mock(); + + var handler = new TracingAspectHandler(null, nameSpace, TracingCaptureMode.EnvironmentVariable, + configurations.Object, recorder.Object); + var eventArgs = new AspectEventArgs {Name = methodName}; + + // Act + handler.OnEntry(eventArgs); + + // Assert + recorder.Verify(v => + v.SetNamespace( + It.Is(i => i == nameSpace) + ), Times.Once); + } + + #endregion + + #region OnSuccess Tests + + [Fact] + public void OnSuccess_WhenTracerCaptureResponseEnvironmentVariableIsTrue_CapturesResponse() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var nameSpace = Guid.NewGuid().ToString(); + var configurations = new Mock(); + configurations.Setup(c => c.IsLambdaEnvironment).Returns(true); + configurations.Setup(c => c.TracingDisabled).Returns(false); + configurations.Setup(c => c.TracerCaptureResponse).Returns(true); + var recorder = new Mock(); + var results = new[] {"A", "B"}; + + var handler = new TracingAspectHandler(null, nameSpace, TracingCaptureMode.EnvironmentVariable, + configurations.Object, recorder.Object); + var eventArgs = new AspectEventArgs {Name = methodName}; + + // Act + handler.OnSuccess(eventArgs, results); + + // Assert + recorder.Verify(v => + v.AddMetadata( + It.Is(i => i == nameSpace), + It.Is(i => i == $"{methodName} response"), + It.Is(i => + i.First() == results.First() && + i.Last() == results.Last() + ) + ), Times.Once); + } + + [Fact] + public void OnSuccess_WhenTracerCaptureResponseEnvironmentVariableIsFalse_DoesNotCaptureResponse() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var nameSpace = Guid.NewGuid().ToString(); + var configurations = new Mock(); + configurations.Setup(c => c.IsLambdaEnvironment).Returns(true); + configurations.Setup(c => c.TracingDisabled).Returns(false); + configurations.Setup(c => c.TracerCaptureResponse).Returns(false); + var recorder = new Mock(); + var results = new[] {"A", "B"}; + + var handler = new TracingAspectHandler(null, nameSpace, TracingCaptureMode.EnvironmentVariable, + configurations.Object, recorder.Object); + var eventArgs = new AspectEventArgs {Name = methodName}; + + // Act + handler.OnSuccess(eventArgs, results); + + // Assert + recorder.Verify(v => + v.AddMetadata( + It.IsAny(), + It.IsAny(), + It.IsAny() + ), Times.Never); + } + + [Fact] + public void OnSuccess_WhenTracerCaptureModeIsResponse_CapturesResponse() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var nameSpace = Guid.NewGuid().ToString(); + var configurations = new Mock(); + configurations.Setup(c => c.IsLambdaEnvironment).Returns(true); + configurations.Setup(c => c.TracingDisabled).Returns(false); + var recorder = new Mock(); + var results = new[] {"A", "B"}; + + var handler = new TracingAspectHandler(null, nameSpace, TracingCaptureMode.Response, + configurations.Object, recorder.Object); + var eventArgs = new AspectEventArgs {Name = methodName}; + + // Act + handler.OnSuccess(eventArgs, results); + + // Assert + recorder.Verify(v => + v.AddMetadata( + It.Is(i => i == nameSpace), + It.Is(i => i == $"{methodName} response"), + It.Is(i => + i.First() == results.First() && + i.Last() == results.Last() + ) + ), Times.Once); + } + + [Fact] + public void OnSuccess_WhenTracerCaptureModeIsResponseAndError_CapturesResponse() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var nameSpace = Guid.NewGuid().ToString(); + var configurations = new Mock(); + configurations.Setup(c => c.IsLambdaEnvironment).Returns(true); + configurations.Setup(c => c.TracingDisabled).Returns(false); + var recorder = new Mock(); + var results = new[] {"A", "B"}; + + var handler = new TracingAspectHandler(null, nameSpace, TracingCaptureMode.ResponseAndError, + configurations.Object, recorder.Object); + var eventArgs = new AspectEventArgs {Name = methodName}; + + // Act + handler.OnSuccess(eventArgs, results); + + // Assert + recorder.Verify(v => + v.AddMetadata( + It.Is(i => i == nameSpace), + It.Is(i => i == $"{methodName} response"), + It.Is(i => + i.First() == results.First() && + i.Last() == results.Last() + ) + ), Times.Once); + } + + [Fact] + public void OnSuccess_WhenTracerCaptureModeIsError_DoesNotCaptureResponse() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var nameSpace = Guid.NewGuid().ToString(); + var configurations = new Mock(); + configurations.Setup(c => c.IsLambdaEnvironment).Returns(true); + configurations.Setup(c => c.TracingDisabled).Returns(false); + var recorder = new Mock(); + var results = new[] {"A", "B"}; + + var handler = new TracingAspectHandler(null, nameSpace, TracingCaptureMode.Error, + configurations.Object, recorder.Object); + var eventArgs = new AspectEventArgs {Name = methodName}; + + // Act + handler.OnSuccess(eventArgs, results); + + // Assert + recorder.Verify(v => + v.AddMetadata( + It.IsAny(), + It.IsAny(), + It.IsAny() + ), Times.Never); + } + + [Fact] + public void OnSuccess_WhenTracerCaptureModeIsDisabled_DoesNotCaptureResponse() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var nameSpace = Guid.NewGuid().ToString(); + var configurations = new Mock(); + configurations.Setup(c => c.IsLambdaEnvironment).Returns(true); + configurations.Setup(c => c.TracingDisabled).Returns(false); + var recorder = new Mock(); + var results = new[] {"A", "B"}; + + var handler = new TracingAspectHandler(null, nameSpace, TracingCaptureMode.Disabled, + configurations.Object, recorder.Object); + var eventArgs = new AspectEventArgs {Name = methodName}; + + // Act + handler.OnSuccess(eventArgs, results); + + // Assert + recorder.Verify(v => + v.AddMetadata( + It.IsAny(), + It.IsAny(), + It.IsAny() + ), Times.Never); + } + + #endregion + + #region OnException Tests + + [Fact] + public void OnException_WhenTracerCaptureErrorEnvironmentVariableIsTrue_CapturesError() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var nameSpace = Guid.NewGuid().ToString(); + var configurations = new Mock(); + configurations.Setup(c => c.IsLambdaEnvironment).Returns(true); + configurations.Setup(c => c.TracingDisabled).Returns(false); + configurations.Setup(c => c.TracerCaptureError).Returns(true); + var recorder = new Mock(); + var exception = new Exception("Test Exception"); + + var handler = new TracingAspectHandler(null, nameSpace, TracingCaptureMode.EnvironmentVariable, + configurations.Object, recorder.Object); + var eventArgs = new AspectEventArgs {Name = methodName}; + + // Act + object Act() => handler.OnException(eventArgs, exception); + + // Assert + Assert.Throws(Act); + recorder.Verify(v => + v.AddMetadata( + It.Is(i => i == nameSpace), + It.Is(i => i == $"{methodName} error"), + It.Is(i => i == exception + ) + ), Times.Once); + } + + [Fact] + public void OnException_WhenTracerCaptureErrorEnvironmentVariableIsTrueFalse_DoesNotCaptureError() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var nameSpace = Guid.NewGuid().ToString(); + var configurations = new Mock(); + configurations.Setup(c => c.IsLambdaEnvironment).Returns(true); + configurations.Setup(c => c.TracingDisabled).Returns(false); + configurations.Setup(c => c.TracerCaptureError).Returns(false); + var recorder = new Mock(); + var exception = new Exception("Test Exception"); + + var handler = new TracingAspectHandler(null, nameSpace, TracingCaptureMode.EnvironmentVariable, + configurations.Object, recorder.Object); + var eventArgs = new AspectEventArgs {Name = methodName}; + + // Act + object Act() => handler.OnException(eventArgs, exception); + + // Assert + Assert.Throws(Act); + recorder.Verify(v => + v.AddMetadata( + It.IsAny(), + It.IsAny(), + It.IsAny() + ), Times.Never); + } + + [Fact] + public void OnException_WhenTracerCaptureModeIsError_CapturesError() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var nameSpace = Guid.NewGuid().ToString(); + var configurations = new Mock(); + configurations.Setup(c => c.IsLambdaEnvironment).Returns(true); + configurations.Setup(c => c.TracingDisabled).Returns(false); + var recorder = new Mock(); + var exception = new Exception("Test Exception"); + + var handler = new TracingAspectHandler(null, nameSpace, TracingCaptureMode.Error, + configurations.Object, recorder.Object); + var eventArgs = new AspectEventArgs {Name = methodName}; + + // Act + object Act() => handler.OnException(eventArgs, exception); + + // Assert + Assert.Throws(Act); + recorder.Verify(v => + v.AddMetadata( + It.Is(i => i == nameSpace), + It.Is(i => i == $"{methodName} error"), + It.Is(i => i == exception + ) + ), Times.Once); + } + + [Fact] + public void OnException_WhenTracerCaptureModeIsResponseAndError_CapturesError() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var nameSpace = Guid.NewGuid().ToString(); + var configurations = new Mock(); + configurations.Setup(c => c.IsLambdaEnvironment).Returns(true); + configurations.Setup(c => c.TracingDisabled).Returns(false); + var recorder = new Mock(); + var exception = new Exception("Test Exception"); + + var handler = new TracingAspectHandler(null, nameSpace, TracingCaptureMode.ResponseAndError, + configurations.Object, recorder.Object); + var eventArgs = new AspectEventArgs {Name = methodName}; + + // Act + object Act() => handler.OnException(eventArgs, exception); + + // Assert + Assert.Throws(Act); + recorder.Verify(v => + v.AddMetadata( + It.Is(i => i == nameSpace), + It.Is(i => i == $"{methodName} error"), + It.Is(i => i == exception + ) + ), Times.Once); + } + + [Fact] + public void OnException_WhenTracerCaptureModeIsResponse_DoesNotCaptureError() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var nameSpace = Guid.NewGuid().ToString(); + var configurations = new Mock(); + configurations.Setup(c => c.IsLambdaEnvironment).Returns(true); + configurations.Setup(c => c.TracingDisabled).Returns(false); + configurations.Setup(c => c.TracerCaptureError).Returns(false); + var recorder = new Mock(); + var exception = new Exception("Test Exception"); + + var handler = new TracingAspectHandler(null, nameSpace, TracingCaptureMode.Response, + configurations.Object, recorder.Object); + var eventArgs = new AspectEventArgs {Name = methodName}; + + // Act + object Act() => handler.OnException(eventArgs, exception); + + // Assert + Assert.Throws(Act); + recorder.Verify(v => + v.AddMetadata( + It.IsAny(), + It.IsAny(), + It.IsAny() + ), Times.Never); + } + + [Fact] + public void OnException_WhenTracerCaptureModeIsDisabled_DoesNotCaptureError() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var nameSpace = Guid.NewGuid().ToString(); + var configurations = new Mock(); + configurations.Setup(c => c.IsLambdaEnvironment).Returns(true); + configurations.Setup(c => c.TracingDisabled).Returns(false); + configurations.Setup(c => c.TracerCaptureError).Returns(false); + var recorder = new Mock(); + var exception = new Exception("Test Exception"); + + var handler = new TracingAspectHandler(null, nameSpace, TracingCaptureMode.Disabled, + configurations.Object, recorder.Object); + var eventArgs = new AspectEventArgs {Name = methodName}; + + // Act + object Act() => handler.OnException(eventArgs, exception); + + // Assert + Assert.Throws(Act); + recorder.Verify(v => + v.AddMetadata( + It.IsAny(), + It.IsAny(), + It.IsAny() + ), Times.Never); + } + + #endregion + + #region OnExit Tests + + [Fact] + public void OnExit_WhenOutsideOfLambdaEnvironment_DoesNotEndSubsegment() + { + // Arrange + var methodName = Guid.NewGuid().ToString(); + var configurations = new Mock(); + configurations.Setup(c => c.IsLambdaEnvironment).Returns(false); + configurations.Setup(c => c.TracingDisabled).Returns(true); + configurations.Setup(c => c.IsSamLocal).Returns(false); + var recorder = new Mock(); + + var handler = new TracingAspectHandler(null, null, TracingCaptureMode.EnvironmentVariable, + configurations.Object, recorder.Object); + var eventArgs = new AspectEventArgs {Name = methodName}; + + // Act + handler.OnExit(eventArgs); + + // Assert + recorder.Verify(v => v.EndSubsegment(), Times.Never); + } + + #endregion + } +} \ No newline at end of file diff --git a/mkdocs.yml b/mkdocs.yml new file mode 100644 index 000000000..75b59574b --- /dev/null +++ b/mkdocs.yml @@ -0,0 +1,76 @@ +site_name: Lambda Powertools .NET +site_description: AWS Lambda Powertools for .NET +site_author: Amazon Web Services +repo_url: https://github.com/awslabs/aws-lambda-powertools-dotnet +edit_uri: edit/develop/docs + +nav: + - Homepage: index.md + - Our tenets: tenets.md + - References: references.md + - Changelog: changelog.md + - Roadmap: https://github.com/awslabs/aws-lambda-powertools-roadmap/projects/1" target="_blank + - API Reference: api/" target="_blank + - Core utilities: + - core/tracing.md + - core/logging.md + - core/metrics.md + +theme: + name: material + palette: + - scheme: default + primary: blue + accent: deep orange + toggle: + icon: material/toggle-switch-off-outline + name: Switch to dark mode + - scheme: slate + primary: blue + accent: orange + toggle: + icon: material/toggle-switch + name: Switch to light mode + features: + - navigation.sections + - navigation.expand + - navigation.top + icon: + repo: fontawesome/brands/github + logo: media/aws-logo-light.svg + favicon: media/aws-logo-light.svg + custom_dir: docs/overrides + +markdown_extensions: + - admonition + - pymdownx.tabbed + - pymdownx.highlight: + linenums: true + - pymdownx.superfences + - pymdownx.details + - pymdownx.snippets: + base_path: '.' + check_paths: true + - meta + - toc: + permalink: true + toc_depth: 4 + - attr_list + - pymdownx.emoji + - pymdownx.inlinehilite + +copyright: Copyright © 2021 Amazon Web Services + +plugins: + - git-revision-date + - search + +extra_css: + - stylesheets/extra.css +extra_javascript: + - javascript/aws-amplify.min.js + - javascript/extra.js + +extra: + version: + provider: mike diff --git a/poetry.lock b/poetry.lock new file mode 100644 index 000000000..465b69e28 --- /dev/null +++ b/poetry.lock @@ -0,0 +1,553 @@ +[[package]] +name = "click" +version = "8.0.1" +description = "Composable command line interface toolkit" +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +colorama = {version = "*", markers = "platform_system == \"Windows\""} + +[[package]] +name = "colorama" +version = "0.4.4" +description = "Cross-platform colored terminal text." +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[[package]] +name = "ghp-import" +version = "2.0.1" +description = "Copy your docs directly to the gh-pages branch." +category = "main" +optional = false +python-versions = "*" + +[package.dependencies] +python-dateutil = ">=2.8.1" + +[package.extras] +dev = ["twine", "markdown", "flake8", "wheel"] + +[[package]] +name = "gitdb" +version = "4.0.7" +description = "Git Object Database" +category = "main" +optional = false +python-versions = ">=3.4" + +[package.dependencies] +smmap = ">=3.0.1,<5" + +[[package]] +name = "gitpython" +version = "3.1.20" +description = "Python Git Library" +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +gitdb = ">=4.0.1,<5" +typing-extensions = {version = ">=3.7.4.3", markers = "python_version < \"3.10\""} + +[[package]] +name = "importlib-metadata" +version = "4.6.4" +description = "Read metadata from Python packages" +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +zipp = ">=0.5" + +[package.extras] +docs = ["sphinx", "jaraco.packaging (>=8.2)", "rst.linker (>=1.9)"] +perf = ["ipython"] +testing = ["pytest (>=4.6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "pytest-cov", "pytest-enabler (>=1.0.1)", "packaging", "pep517", "pyfakefs", "flufl.flake8", "pytest-perf (>=0.9.2)", "pytest-black (>=0.3.7)", "pytest-mypy", "importlib-resources (>=1.3)"] + +[[package]] +name = "jinja2" +version = "3.0.1" +description = "A very fast and expressive template engine." +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +MarkupSafe = ">=2.0" + +[package.extras] +i18n = ["Babel (>=2.7)"] + +[[package]] +name = "markdown" +version = "3.3.4" +description = "Python implementation of Markdown." +category = "main" +optional = false +python-versions = ">=3.6" + +[package.extras] +testing = ["coverage", "pyyaml"] + +[[package]] +name = "markupsafe" +version = "2.0.1" +description = "Safely add untrusted strings to HTML/XML markup." +category = "main" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "mergedeep" +version = "1.3.4" +description = "A deep merge function for 🐍." +category = "main" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "mike" +version = "1.0.1" +description = "Manage multiple versions of your MkDocs-powered documentation" +category = "main" +optional = false +python-versions = "*" + +[package.dependencies] +jinja2 = "*" +mkdocs = ">=1.0" +pyyaml = "*" +verspec = "*" + +[package.extras] +dev = ["coverage", "flake8 (>=3.0)"] +test = ["coverage", "flake8 (>=3.0)"] + +[[package]] +name = "mkdocs" +version = "1.2.3" +description = "Project documentation with Markdown." +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +click = ">=3.3" +ghp-import = ">=1.0" +importlib-metadata = ">=3.10" +Jinja2 = ">=2.10.1" +Markdown = ">=3.2.1" +mergedeep = ">=1.3.4" +packaging = ">=20.5" +PyYAML = ">=3.10" +pyyaml-env-tag = ">=0.1" +watchdog = ">=2.0" + +[package.extras] +i18n = ["babel (>=2.9.0)"] + +[[package]] +name = "mkdocs-git-revision-date-plugin" +version = "0.3.1" +description = "MkDocs plugin for setting revision date from git per markdown file." +category = "main" +optional = false +python-versions = ">=3.4" + +[package.dependencies] +GitPython = "*" +jinja2 = "*" +mkdocs = ">=0.17" + +[[package]] +name = "mkdocs-material" +version = "7.2.4" +description = "A Material Design theme for MkDocs" +category = "main" +optional = false +python-versions = "*" + +[package.dependencies] +markdown = ">=3.2" +mkdocs = ">=1.2.2" +mkdocs-material-extensions = ">=1.0" +Pygments = ">=2.4" +pymdown-extensions = ">=7.0" + +[[package]] +name = "mkdocs-material-extensions" +version = "1.0.1" +description = "Extension pack for Python Markdown." +category = "main" +optional = false +python-versions = ">=3.5" + +[package.dependencies] +mkdocs-material = ">=5.0.0" + +[[package]] +name = "packaging" +version = "21.0" +description = "Core utilities for Python packages" +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +pyparsing = ">=2.0.2" + +[[package]] +name = "pygments" +version = "2.10.0" +description = "Pygments is a syntax highlighting package written in Python." +category = "main" +optional = false +python-versions = ">=3.5" + +[[package]] +name = "pymdown-extensions" +version = "8.2" +description = "Extension pack for Python Markdown." +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +Markdown = ">=3.2" + +[[package]] +name = "pyparsing" +version = "2.4.7" +description = "Python parsing module" +category = "main" +optional = false +python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*" + +[[package]] +name = "python-dateutil" +version = "2.8.2" +description = "Extensions to the standard Python datetime module" +category = "main" +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7" + +[package.dependencies] +six = ">=1.5" + +[[package]] +name = "pyyaml" +version = "5.4.1" +description = "YAML parser and emitter for Python" +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*" + +[[package]] +name = "pyyaml-env-tag" +version = "0.1" +description = "A custom YAML tag for referencing environment variables in YAML files. " +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +pyyaml = "*" + +[[package]] +name = "six" +version = "1.16.0" +description = "Python 2 and 3 compatibility utilities" +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*" + +[[package]] +name = "smmap" +version = "4.0.0" +description = "A pure Python implementation of a sliding window memory map manager" +category = "main" +optional = false +python-versions = ">=3.5" + +[[package]] +name = "typing-extensions" +version = "3.10.0.0" +description = "Backported and Experimental Type Hints for Python 3.5+" +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "verspec" +version = "0.1.0" +description = "Flexible version handling" +category = "main" +optional = false +python-versions = "*" + +[package.extras] +test = ["coverage", "flake8 (>=3.7)", "mypy", "pretend", "pytest"] + +[[package]] +name = "watchdog" +version = "2.1.4" +description = "Filesystem events monitoring" +category = "main" +optional = false +python-versions = ">=3.6" + +[package.extras] +watchmedo = ["PyYAML (>=3.10)", "argh (>=0.24.1)"] + +[[package]] +name = "zipp" +version = "3.5.0" +description = "Backport of pathlib-compatible object wrapper for zip files" +category = "main" +optional = false +python-versions = ">=3.6" + +[package.extras] +docs = ["sphinx", "jaraco.packaging (>=8.2)", "rst.linker (>=1.9)"] +testing = ["pytest (>=4.6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "pytest-cov", "pytest-enabler (>=1.0.1)", "jaraco.itertools", "func-timeout", "pytest-black (>=0.3.7)", "pytest-mypy"] + +[metadata] +lock-version = "1.1" +python-versions = "^3.9" +content-hash = "f082f3c26f0efb74521bfc86a3242f15f24e7108ee3f1bf455a08f11594cda75" + +[metadata.files] +click = [ + {file = "click-8.0.1-py3-none-any.whl", hash = "sha256:fba402a4a47334742d782209a7c79bc448911afe1149d07bdabdf480b3e2f4b6"}, + {file = "click-8.0.1.tar.gz", hash = "sha256:8c04c11192119b1ef78ea049e0a6f0463e4c48ef00a30160c704337586f3ad7a"}, +] +colorama = [ + {file = "colorama-0.4.4-py2.py3-none-any.whl", hash = "sha256:9f47eda37229f68eee03b24b9748937c7dc3868f906e8ba69fbcbdd3bc5dc3e2"}, + {file = "colorama-0.4.4.tar.gz", hash = "sha256:5941b2b48a20143d2267e95b1c2a7603ce057ee39fd88e7329b0c292aa16869b"}, +] +ghp-import = [ + {file = "ghp-import-2.0.1.tar.gz", hash = "sha256:753de2eace6e0f7d4edfb3cce5e3c3b98cd52aadb80163303d1d036bda7b4483"}, + {file = "ghp_import-2.0.1-py3-none-any.whl", hash = "sha256:8241a8e9f8dd3c1fafe9696e6e081b57a208ef907e9939c44e7415e407ab40ea"}, +] +gitdb = [ + {file = "gitdb-4.0.7-py3-none-any.whl", hash = "sha256:6c4cc71933456991da20917998acbe6cf4fb41eeaab7d6d67fbc05ecd4c865b0"}, + {file = "gitdb-4.0.7.tar.gz", hash = "sha256:96bf5c08b157a666fec41129e6d327235284cca4c81e92109260f353ba138005"}, +] +gitpython = [ + {file = "GitPython-3.1.20-py3-none-any.whl", hash = "sha256:b1e1c269deab1b08ce65403cf14e10d2ef1f6c89e33ea7c5e5bb0222ea593b8a"}, + {file = "GitPython-3.1.20.tar.gz", hash = "sha256:df0e072a200703a65387b0cfdf0466e3bab729c0458cf6b7349d0e9877636519"}, +] +importlib-metadata = [ + {file = "importlib_metadata-4.6.4-py3-none-any.whl", hash = "sha256:ed5157fef23a4bc4594615a0dd8eba94b2bb36bf2a343fa3d8bb2fa0a62a99d5"}, + {file = "importlib_metadata-4.6.4.tar.gz", hash = "sha256:7b30a78db2922d78a6f47fb30683156a14f3c6aa5cc23f77cc8967e9ab2d002f"}, +] +jinja2 = [ + {file = "Jinja2-3.0.1-py3-none-any.whl", hash = "sha256:1f06f2da51e7b56b8f238affdd6b4e2c61e39598a378cc49345bc1bd42a978a4"}, + {file = "Jinja2-3.0.1.tar.gz", hash = "sha256:703f484b47a6af502e743c9122595cc812b0271f661722403114f71a79d0f5a4"}, +] +markdown = [ + {file = "Markdown-3.3.4-py3-none-any.whl", hash = "sha256:96c3ba1261de2f7547b46a00ea8463832c921d3f9d6aba3f255a6f71386db20c"}, + {file = "Markdown-3.3.4.tar.gz", hash = "sha256:31b5b491868dcc87d6c24b7e3d19a0d730d59d3e46f4eea6430a321bed387a49"}, +] +markupsafe = [ + {file = "MarkupSafe-2.0.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:d8446c54dc28c01e5a2dbac5a25f071f6653e6e40f3a8818e8b45d790fe6ef53"}, + {file = "MarkupSafe-2.0.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:36bc903cbb393720fad60fc28c10de6acf10dc6cc883f3e24ee4012371399a38"}, + {file = "MarkupSafe-2.0.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2d7d807855b419fc2ed3e631034685db6079889a1f01d5d9dac950f764da3dad"}, + {file = "MarkupSafe-2.0.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:add36cb2dbb8b736611303cd3bfcee00afd96471b09cda130da3581cbdc56a6d"}, + {file = "MarkupSafe-2.0.1-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:168cd0a3642de83558a5153c8bd34f175a9a6e7f6dc6384b9655d2697312a646"}, + {file = "MarkupSafe-2.0.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:4dc8f9fb58f7364b63fd9f85013b780ef83c11857ae79f2feda41e270468dd9b"}, + {file = "MarkupSafe-2.0.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:20dca64a3ef2d6e4d5d615a3fd418ad3bde77a47ec8a23d984a12b5b4c74491a"}, + {file = "MarkupSafe-2.0.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:cdfba22ea2f0029c9261a4bd07e830a8da012291fbe44dc794e488b6c9bb353a"}, + {file = "MarkupSafe-2.0.1-cp310-cp310-win32.whl", hash = "sha256:99df47edb6bda1249d3e80fdabb1dab8c08ef3975f69aed437cb69d0a5de1e28"}, + {file = "MarkupSafe-2.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:e0f138900af21926a02425cf736db95be9f4af72ba1bb21453432a07f6082134"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:f9081981fe268bd86831e5c75f7de206ef275defcb82bc70740ae6dc507aee51"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:0955295dd5eec6cb6cc2fe1698f4c6d84af2e92de33fbcac4111913cd100a6ff"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:0446679737af14f45767963a1a9ef7620189912317d095f2d9ffa183a4d25d2b"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux2010_i686.whl", hash = "sha256:f826e31d18b516f653fe296d967d700fddad5901ae07c622bb3705955e1faa94"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux2010_x86_64.whl", hash = "sha256:fa130dd50c57d53368c9d59395cb5526eda596d3ffe36666cd81a44d56e48872"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:905fec760bd2fa1388bb5b489ee8ee5f7291d692638ea5f67982d968366bef9f"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bf5d821ffabf0ef3533c39c518f3357b171a1651c1ff6827325e4489b0e46c3c"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:0d4b31cc67ab36e3392bbf3862cfbadac3db12bdd8b02a2731f509ed5b829724"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:baa1a4e8f868845af802979fcdbf0bb11f94f1cb7ced4c4b8a351bb60d108145"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:deb993cacb280823246a026e3b2d81c493c53de6acfd5e6bfe31ab3402bb37dd"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:63f3268ba69ace99cab4e3e3b5840b03340efed0948ab8f78d2fd87ee5442a4f"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:8d206346619592c6200148b01a2142798c989edcb9c896f9ac9722a99d4e77e6"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-win32.whl", hash = "sha256:6c4ca60fa24e85fe25b912b01e62cb969d69a23a5d5867682dd3e80b5b02581d"}, + {file = "MarkupSafe-2.0.1-cp36-cp36m-win_amd64.whl", hash = "sha256:b2f4bf27480f5e5e8ce285a8c8fd176c0b03e93dcc6646477d4630e83440c6a9"}, + {file = "MarkupSafe-2.0.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:0717a7390a68be14b8c793ba258e075c6f4ca819f15edfc2a3a027c823718567"}, + {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:6557b31b5e2c9ddf0de32a691f2312a32f77cd7681d8af66c2692efdbef84c18"}, + {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:49e3ceeabbfb9d66c3aef5af3a60cc43b85c33df25ce03d0031a608b0a8b2e3f"}, + {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux2010_i686.whl", hash = "sha256:d7f9850398e85aba693bb640262d3611788b1f29a79f0c93c565694658f4071f"}, + {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux2010_x86_64.whl", hash = "sha256:6a7fae0dd14cf60ad5ff42baa2e95727c3d81ded453457771d02b7d2b3f9c0c2"}, + {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:b7f2d075102dc8c794cbde1947378051c4e5180d52d276987b8d28a3bd58c17d"}, + {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e9936f0b261d4df76ad22f8fee3ae83b60d7c3e871292cd42f40b81b70afae85"}, + {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:2a7d351cbd8cfeb19ca00de495e224dea7e7d919659c2841bbb7f420ad03e2d6"}, + {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:60bf42e36abfaf9aff1f50f52644b336d4f0a3fd6d8a60ca0d054ac9f713a864"}, + {file = "MarkupSafe-2.0.1-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:d6c7ebd4e944c85e2c3421e612a7057a2f48d478d79e61800d81468a8d842207"}, + {file = "MarkupSafe-2.0.1-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:f0567c4dc99f264f49fe27da5f735f414c4e7e7dd850cfd8e69f0862d7c74ea9"}, + {file = "MarkupSafe-2.0.1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:89c687013cb1cd489a0f0ac24febe8c7a666e6e221b783e53ac50ebf68e45d86"}, + {file = "MarkupSafe-2.0.1-cp37-cp37m-win32.whl", hash = "sha256:a30e67a65b53ea0a5e62fe23682cfe22712e01f453b95233b25502f7c61cb415"}, + {file = "MarkupSafe-2.0.1-cp37-cp37m-win_amd64.whl", hash = "sha256:611d1ad9a4288cf3e3c16014564df047fe08410e628f89805e475368bd304914"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:5bb28c636d87e840583ee3adeb78172efc47c8b26127267f54a9c0ec251d41a9"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:be98f628055368795d818ebf93da628541e10b75b41c559fdf36d104c5787066"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux1_i686.whl", hash = "sha256:1d609f577dc6e1aa17d746f8bd3c31aa4d258f4070d61b2aa5c4166c1539de35"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:7d91275b0245b1da4d4cfa07e0faedd5b0812efc15b702576d103293e252af1b"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux2010_i686.whl", hash = "sha256:01a9b8ea66f1658938f65b93a85ebe8bc016e6769611be228d797c9d998dd298"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux2010_x86_64.whl", hash = "sha256:47ab1e7b91c098ab893b828deafa1203de86d0bc6ab587b160f78fe6c4011f75"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:97383d78eb34da7e1fa37dd273c20ad4320929af65d156e35a5e2d89566d9dfb"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6fcf051089389abe060c9cd7caa212c707e58153afa2c649f00346ce6d260f1b"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:5855f8438a7d1d458206a2466bf82b0f104a3724bf96a1c781ab731e4201731a"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:3dd007d54ee88b46be476e293f48c85048603f5f516008bee124ddd891398ed6"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:aca6377c0cb8a8253e493c6b451565ac77e98c2951c45f913e0b52facdcff83f"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:04635854b943835a6ea959e948d19dcd311762c5c0c6e1f0e16ee57022669194"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:6300b8454aa6930a24b9618fbb54b5a68135092bc666f7b06901f897fa5c2fee"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-win32.whl", hash = "sha256:023cb26ec21ece8dc3907c0e8320058b2e0cb3c55cf9564da612bc325bed5e64"}, + {file = "MarkupSafe-2.0.1-cp38-cp38-win_amd64.whl", hash = "sha256:984d76483eb32f1bcb536dc27e4ad56bba4baa70be32fa87152832cdd9db0833"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:2ef54abee730b502252bcdf31b10dacb0a416229b72c18b19e24a4509f273d26"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:3c112550557578c26af18a1ccc9e090bfe03832ae994343cfdacd287db6a6ae7"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux1_i686.whl", hash = "sha256:53edb4da6925ad13c07b6d26c2a852bd81e364f95301c66e930ab2aef5b5ddd8"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:f5653a225f31e113b152e56f154ccbe59eeb1c7487b39b9d9f9cdb58e6c79dc5"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux2010_i686.whl", hash = "sha256:4efca8f86c54b22348a5467704e3fec767b2db12fc39c6d963168ab1d3fc9135"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux2010_x86_64.whl", hash = "sha256:ab3ef638ace319fa26553db0624c4699e31a28bb2a835c5faca8f8acf6a5a902"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:f8ba0e8349a38d3001fae7eadded3f6606f0da5d748ee53cc1dab1d6527b9509"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c47adbc92fc1bb2b3274c4b3a43ae0e4573d9fbff4f54cd484555edbf030baf1"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:37205cac2a79194e3750b0af2a5720d95f786a55ce7df90c3af697bfa100eaac"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:1f2ade76b9903f39aa442b4aadd2177decb66525062db244b35d71d0ee8599b6"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:4296f2b1ce8c86a6aea78613c34bb1a672ea0e3de9c6ba08a960efe0b0a09047"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:9f02365d4e99430a12647f09b6cc8bab61a6564363f313126f775eb4f6ef798e"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:5b6d930f030f8ed98e3e6c98ffa0652bdb82601e7a016ec2ab5d7ff23baa78d1"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-win32.whl", hash = "sha256:10f82115e21dc0dfec9ab5c0223652f7197feb168c940f3ef61563fc2d6beb74"}, + {file = "MarkupSafe-2.0.1-cp39-cp39-win_amd64.whl", hash = "sha256:693ce3f9e70a6cf7d2fb9e6c9d8b204b6b39897a2c4a1aa65728d5ac97dcc1d8"}, + {file = "MarkupSafe-2.0.1.tar.gz", hash = "sha256:594c67807fb16238b30c44bdf74f36c02cdf22d1c8cda91ef8a0ed8dabf5620a"}, +] +mergedeep = [ + {file = "mergedeep-1.3.4-py3-none-any.whl", hash = "sha256:70775750742b25c0d8f36c55aed03d24c3384d17c951b3175d898bd778ef0307"}, + {file = "mergedeep-1.3.4.tar.gz", hash = "sha256:0096d52e9dad9939c3d975a774666af186eda617e6ca84df4c94dec30004f2a8"}, +] +mike = [ + {file = "mike-1.0.1-py3-none-any.whl", hash = "sha256:29b39a725510a67590db261ca8292f583dcfe06c6ea6842793c96ae631d6e2e1"}, + {file = "mike-1.0.1.tar.gz", hash = "sha256:7888f01d05d752bd43e03f6d971608a0b876f23787cf49a1f2b43be304b1789e"}, +] +mkdocs = [ + {file = "mkdocs-1.2.3-py3-none-any.whl", hash = "sha256:a1fa8c2d0c1305d7fc2b9d9f607c71778572a8b110fb26642aa00296c9e6d072"}, + {file = "mkdocs-1.2.3.tar.gz", hash = "sha256:89f5a094764381cda656af4298727c9f53dc3e602983087e1fe96ea1df24f4c1"}, +] +mkdocs-git-revision-date-plugin = [ + {file = "mkdocs-git-revision-date-plugin-0.3.1.tar.gz", hash = "sha256:4abaef720763a64c952bed6829dcc180f67c97c60dd73914e90715e05d1cfb23"}, + {file = "mkdocs_git_revision_date_plugin-0.3.1-py3-none-any.whl", hash = "sha256:8ae50b45eb75d07b150a69726041860801615aae5f4adbd6b1cf4d51abaa03d5"}, +] +mkdocs-material = [ + {file = "mkdocs-material-7.2.4.tar.gz", hash = "sha256:0e19402480a80add9b0fe777e9be80fafb9583ec2c91e43deaef29d1a432d018"}, + {file = "mkdocs_material-7.2.4-py2.py3-none-any.whl", hash = "sha256:f554c84286b485c7d47e89c14c2fc062fc57b65f9c26fa1687720fe4f569b837"}, +] +mkdocs-material-extensions = [ + {file = "mkdocs-material-extensions-1.0.1.tar.gz", hash = "sha256:6947fb7f5e4291e3c61405bad3539d81e0b3cd62ae0d66ced018128af509c68f"}, + {file = "mkdocs_material_extensions-1.0.1-py3-none-any.whl", hash = "sha256:d90c807a88348aa6d1805657ec5c0b2d8d609c110e62b9dce4daf7fa981fa338"}, +] +packaging = [ + {file = "packaging-21.0-py3-none-any.whl", hash = "sha256:c86254f9220d55e31cc94d69bade760f0847da8000def4dfe1c6b872fd14ff14"}, + {file = "packaging-21.0.tar.gz", hash = "sha256:7dc96269f53a4ccec5c0670940a4281106dd0bb343f47b7471f779df49c2fbe7"}, +] +pygments = [ + {file = "Pygments-2.10.0-py3-none-any.whl", hash = "sha256:b8e67fe6af78f492b3c4b3e2970c0624cbf08beb1e493b2c99b9fa1b67a20380"}, + {file = "Pygments-2.10.0.tar.gz", hash = "sha256:f398865f7eb6874156579fdf36bc840a03cab64d1cde9e93d68f46a425ec52c6"}, +] +pymdown-extensions = [ + {file = "pymdown-extensions-8.2.tar.gz", hash = "sha256:b6daa94aad9e1310f9c64c8b1f01e4ce82937ab7eb53bfc92876a97aca02a6f4"}, + {file = "pymdown_extensions-8.2-py3-none-any.whl", hash = "sha256:141452d8ed61165518f2c923454bf054866b85cf466feedb0eb68f04acdc2560"}, +] +pyparsing = [ + {file = "pyparsing-2.4.7-py2.py3-none-any.whl", hash = "sha256:ef9d7589ef3c200abe66653d3f1ab1033c3c419ae9b9bdb1240a85b024efc88b"}, + {file = "pyparsing-2.4.7.tar.gz", hash = "sha256:c203ec8783bf771a155b207279b9bccb8dea02d8f0c9e5f8ead507bc3246ecc1"}, +] +python-dateutil = [ + {file = "python-dateutil-2.8.2.tar.gz", hash = "sha256:0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86"}, + {file = "python_dateutil-2.8.2-py2.py3-none-any.whl", hash = "sha256:961d03dc3453ebbc59dbdea9e4e11c5651520a876d0f4db161e8674aae935da9"}, +] +pyyaml = [ + {file = "PyYAML-5.4.1-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:3b2b1824fe7112845700f815ff6a489360226a5609b96ec2190a45e62a9fc922"}, + {file = "PyYAML-5.4.1-cp27-cp27m-win32.whl", hash = "sha256:129def1b7c1bf22faffd67b8f3724645203b79d8f4cc81f674654d9902cb4393"}, + {file = "PyYAML-5.4.1-cp27-cp27m-win_amd64.whl", hash = "sha256:4465124ef1b18d9ace298060f4eccc64b0850899ac4ac53294547536533800c8"}, + {file = "PyYAML-5.4.1-cp27-cp27mu-manylinux1_x86_64.whl", hash = "sha256:bb4191dfc9306777bc594117aee052446b3fa88737cd13b7188d0e7aa8162185"}, + {file = "PyYAML-5.4.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:6c78645d400265a062508ae399b60b8c167bf003db364ecb26dcab2bda048253"}, + {file = "PyYAML-5.4.1-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:4e0583d24c881e14342eaf4ec5fbc97f934b999a6828693a99157fde912540cc"}, + {file = "PyYAML-5.4.1-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:72a01f726a9c7851ca9bfad6fd09ca4e090a023c00945ea05ba1638c09dc3347"}, + {file = "PyYAML-5.4.1-cp36-cp36m-manylinux2014_s390x.whl", hash = "sha256:895f61ef02e8fed38159bb70f7e100e00f471eae2bc838cd0f4ebb21e28f8541"}, + {file = "PyYAML-5.4.1-cp36-cp36m-win32.whl", hash = "sha256:3bd0e463264cf257d1ffd2e40223b197271046d09dadf73a0fe82b9c1fc385a5"}, + {file = "PyYAML-5.4.1-cp36-cp36m-win_amd64.whl", hash = "sha256:e4fac90784481d221a8e4b1162afa7c47ed953be40d31ab4629ae917510051df"}, + {file = "PyYAML-5.4.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:5accb17103e43963b80e6f837831f38d314a0495500067cb25afab2e8d7a4018"}, + {file = "PyYAML-5.4.1-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:e1d4970ea66be07ae37a3c2e48b5ec63f7ba6804bdddfdbd3cfd954d25a82e63"}, + {file = "PyYAML-5.4.1-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:cb333c16912324fd5f769fff6bc5de372e9e7a202247b48870bc251ed40239aa"}, + {file = "PyYAML-5.4.1-cp37-cp37m-manylinux2014_s390x.whl", hash = "sha256:fe69978f3f768926cfa37b867e3843918e012cf83f680806599ddce33c2c68b0"}, + {file = "PyYAML-5.4.1-cp37-cp37m-win32.whl", hash = "sha256:dd5de0646207f053eb0d6c74ae45ba98c3395a571a2891858e87df7c9b9bd51b"}, + {file = "PyYAML-5.4.1-cp37-cp37m-win_amd64.whl", hash = "sha256:08682f6b72c722394747bddaf0aa62277e02557c0fd1c42cb853016a38f8dedf"}, + {file = "PyYAML-5.4.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:d2d9808ea7b4af864f35ea216be506ecec180628aced0704e34aca0b040ffe46"}, + {file = "PyYAML-5.4.1-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:8c1be557ee92a20f184922c7b6424e8ab6691788e6d86137c5d93c1a6ec1b8fb"}, + {file = "PyYAML-5.4.1-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:fd7f6999a8070df521b6384004ef42833b9bd62cfee11a09bda1079b4b704247"}, + {file = "PyYAML-5.4.1-cp38-cp38-manylinux2014_s390x.whl", hash = "sha256:bfb51918d4ff3d77c1c856a9699f8492c612cde32fd3bcd344af9be34999bfdc"}, + {file = "PyYAML-5.4.1-cp38-cp38-win32.whl", hash = "sha256:fa5ae20527d8e831e8230cbffd9f8fe952815b2b7dae6ffec25318803a7528fc"}, + {file = "PyYAML-5.4.1-cp38-cp38-win_amd64.whl", hash = "sha256:0f5f5786c0e09baddcd8b4b45f20a7b5d61a7e7e99846e3c799b05c7c53fa696"}, + {file = "PyYAML-5.4.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:294db365efa064d00b8d1ef65d8ea2c3426ac366c0c4368d930bf1c5fb497f77"}, + {file = "PyYAML-5.4.1-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:74c1485f7707cf707a7aef42ef6322b8f97921bd89be2ab6317fd782c2d53183"}, + {file = "PyYAML-5.4.1-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:d483ad4e639292c90170eb6f7783ad19490e7a8defb3e46f97dfe4bacae89122"}, + {file = "PyYAML-5.4.1-cp39-cp39-manylinux2014_s390x.whl", hash = "sha256:fdc842473cd33f45ff6bce46aea678a54e3d21f1b61a7750ce3c498eedfe25d6"}, + {file = "PyYAML-5.4.1-cp39-cp39-win32.whl", hash = "sha256:49d4cdd9065b9b6e206d0595fee27a96b5dd22618e7520c33204a4a3239d5b10"}, + {file = "PyYAML-5.4.1-cp39-cp39-win_amd64.whl", hash = "sha256:c20cfa2d49991c8b4147af39859b167664f2ad4561704ee74c1de03318e898db"}, + {file = "PyYAML-5.4.1.tar.gz", hash = "sha256:607774cbba28732bfa802b54baa7484215f530991055bb562efbed5b2f20a45e"}, +] +pyyaml-env-tag = [ + {file = "pyyaml_env_tag-0.1-py3-none-any.whl", hash = "sha256:af31106dec8a4d68c60207c1886031cbf839b68aa7abccdb19868200532c2069"}, + {file = "pyyaml_env_tag-0.1.tar.gz", hash = "sha256:70092675bda14fdec33b31ba77e7543de9ddc88f2e5b99160396572d11525bdb"}, +] +six = [ + {file = "six-1.16.0-py2.py3-none-any.whl", hash = "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254"}, + {file = "six-1.16.0.tar.gz", hash = "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926"}, +] +smmap = [ + {file = "smmap-4.0.0-py2.py3-none-any.whl", hash = "sha256:a9a7479e4c572e2e775c404dcd3080c8dc49f39918c2cf74913d30c4c478e3c2"}, + {file = "smmap-4.0.0.tar.gz", hash = "sha256:7e65386bd122d45405ddf795637b7f7d2b532e7e401d46bbe3fb49b9986d5182"}, +] +typing-extensions = [ + {file = "typing_extensions-3.10.0.0-py2-none-any.whl", hash = "sha256:0ac0f89795dd19de6b97debb0c6af1c70987fd80a2d62d1958f7e56fcc31b497"}, + {file = "typing_extensions-3.10.0.0-py3-none-any.whl", hash = "sha256:779383f6086d90c99ae41cf0ff39aac8a7937a9283ce0a414e5dd782f4c94a84"}, + {file = "typing_extensions-3.10.0.0.tar.gz", hash = "sha256:50b6f157849174217d0656f99dc82fe932884fb250826c18350e159ec6cdf342"}, +] +verspec = [ + {file = "verspec-0.1.0-py3-none-any.whl", hash = "sha256:741877d5633cc9464c45a469ae2a31e801e6dbbaa85b9675d481cda100f11c31"}, + {file = "verspec-0.1.0.tar.gz", hash = "sha256:c4504ca697b2056cdb4bfa7121461f5a0e81809255b41c03dda4ba823637c01e"}, +] +watchdog = [ + {file = "watchdog-2.1.4-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:073b379d74aecc7fcba3ee8c2a7b4ac5d56deca52bd47bab024464a47c084d34"}, + {file = "watchdog-2.1.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:1dd5e0e1577a0f3362f6ab986264d9695e40dfba247b994a522bfab254544fc1"}, + {file = "watchdog-2.1.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:34e1517e745b223eb682d09a7ba2532cbb55ce9c8c778daba0955e1af37c903e"}, + {file = "watchdog-2.1.4-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:bee7eb674850f052599d19f1efdd4db9bc4690593462b760662a38298f1d65b4"}, + {file = "watchdog-2.1.4-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:e6e6b3a9920ca84d6cc22b313c87fac426e92114d1927ade2909ada3de243d45"}, + {file = "watchdog-2.1.4-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:407524dc30d9e3bb46017987b100574eeb810d9cc50488aabf81a03ae70c4962"}, + {file = "watchdog-2.1.4-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:78e36af08a94325b7852827004f4bea1a9b472a532498026a4b8529189797a15"}, + {file = "watchdog-2.1.4-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:9e0a159fedb9d83dee80b00759a82acd2596a3ed70247088f8a175ce46116096"}, + {file = "watchdog-2.1.4-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:39a0711a6439a6fa8d9c78c93759fbb07bc61bb06378eaa5a32148a1468a8e87"}, + {file = "watchdog-2.1.4-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:d8bd7eec21964687b2364e7ab38fda6b4567809d590a0506f74cc48b2a2dfce4"}, + {file = "watchdog-2.1.4-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:f743b2581c241f55b716e35b451f53076a07e15e1f2f0a83016c2ecaf6ace78e"}, + {file = "watchdog-2.1.4-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:9b332a20029ebdff605829219fe858070b128471d60a9b6cc4797bb167fe22ff"}, + {file = "watchdog-2.1.4-py3-none-manylinux2014_aarch64.whl", hash = "sha256:becbe589b63891cfaa24afe8e31fa7ac0d541701644767c9c28f14da1d5489b7"}, + {file = "watchdog-2.1.4-py3-none-manylinux2014_armv7l.whl", hash = "sha256:73782538f9ab7d0fc1f78abd34fe94feea119bd2644c2659d71068d7252a774e"}, + {file = "watchdog-2.1.4-py3-none-manylinux2014_i686.whl", hash = "sha256:60785287032cc2cbd428486c0ff0a4b5c098d1ad256449ffe5fdd69657f5a126"}, + {file = "watchdog-2.1.4-py3-none-manylinux2014_ppc64.whl", hash = "sha256:2cca4c2725112d5a8b5b89ea24a51dad702db7048ae08dba0435b2c382f08e6d"}, + {file = "watchdog-2.1.4-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:536bca6bc9661279310e5946ad4c2dfa5b2b1624e44a7acdf8cb37a10cc45f00"}, + {file = "watchdog-2.1.4-py3-none-manylinux2014_s390x.whl", hash = "sha256:0d4602a93e404b3b01e249297ce950ed249295a0c124cdb4b3fbc696032918fb"}, + {file = "watchdog-2.1.4-py3-none-manylinux2014_x86_64.whl", hash = "sha256:afb03a13c8a75a74f2894a313298ee95ff09fba1f02081ead249e790a5304a18"}, + {file = "watchdog-2.1.4-py3-none-win32.whl", hash = "sha256:47480f3a82694fe1f4d552b3da8420fecfc5273ba7996d7ceadd838d1970b31a"}, + {file = "watchdog-2.1.4-py3-none-win_amd64.whl", hash = "sha256:a56c7631dde228d81834466ebf4ebcc8996678b0f794e3e6dc401e9e71e9388d"}, + {file = "watchdog-2.1.4-py3-none-win_ia64.whl", hash = "sha256:6c58d1cbf01884602afcbc631f79f709812e20ec100a6526c91895d3238d4474"}, + {file = "watchdog-2.1.4.tar.gz", hash = "sha256:438efbbd929b6436add7ce89f3466ca836f31588220433efeb757b5947a9c979"}, +] +zipp = [ + {file = "zipp-3.5.0-py3-none-any.whl", hash = "sha256:957cfda87797e389580cb8b9e3870841ca991e2125350677b2ca83a0e99390a3"}, + {file = "zipp-3.5.0.tar.gz", hash = "sha256:f5812b1e007e48cff63449a5e9f4e7ebea716b4111f9c4f9a645f91d579bf0c4"}, +] diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 000000000..da01f9225 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,17 @@ +[tool.poetry] +name = "aws-lambda-powertools-dotnet" +version = "0.1.0" +description = "Python utilities for AWS Lambda functions including but not limited to tracing, logging and custom metric" +authors = ["Amazon Web Services"] + +[tool.poetry.dependencies] +python = "^3.9" +mike = "^1.0.1" +mkdocs-material = "^7.2.4" +mkdocs-git-revision-date-plugin = "^0.3.1" + +[tool.poetry.dev-dependencies] + +[build-system] +requires = ["poetry-core>=1.0.0"] +build-backend = "poetry.core.masonry.api" diff --git a/version.json b/version.json new file mode 100644 index 000000000..8722d98ff --- /dev/null +++ b/version.json @@ -0,0 +1,8 @@ +{ + "Core": { + "Common": "0.0.1", + "Logging": "0.0.1", + "Metrics": "0.0.1", + "Tracing": "0.0.1" + } +}