├── .all-contributorsrc ├── .asyncapi-tool.yaml ├── .dockerignore ├── .eslintignore ├── .eslintrc ├── .github ├── assets │ └── banner.png └── workflows │ ├── add-good-first-issue-labels.yml │ ├── automerge-for-humans-add-ready-to-merge-or-do-not-merge-label.yml │ ├── automerge-for-humans-merging.yml │ ├── automerge-for-humans-remove-ready-to-merge-label-on-edit.yml │ ├── automerge-orphans.yml │ ├── automerge.yml │ ├── autoupdate.yml │ ├── bounty-program-commands.yml │ ├── bump.yml │ ├── help-command.yml │ ├── if-docker-pr-testing.yml │ ├── if-nodejs-pr-testing.yml │ ├── if-nodejs-release.yml │ ├── if-nodejs-version-bump.yml │ ├── issues-prs-notifications.yml │ ├── lint-pr-title.yml │ ├── notify-tsc-members-mention.yml │ ├── please-take-a-look-command.yml │ ├── release-announcements.yml │ ├── release-docker.yml │ ├── scripts │ ├── README.md │ └── mailchimp │ │ ├── htmlContent.js │ │ ├── index.js │ │ ├── package-lock.json │ │ └── package.json │ ├── stale-issues-prs.yml │ ├── transfer-issue.yml │ ├── update-maintainers-trigger.yaml │ ├── update-pr.yml │ └── welcome-first-time-contrib.yml ├── .gitignore ├── .npmrc ├── .releaserc ├── .sonarcloud.properties ├── CODEOWNERS ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── README.md ├── deployments └── apps │ ├── .gitignore │ ├── .terraform.lock.hcl │ └── main.tf ├── jest.config.js ├── nodemon.json ├── openapi.yaml ├── package-lock.json ├── package.json ├── src ├── app.ts ├── configs │ ├── development.json │ ├── production.json │ └── test.json ├── constants.ts ├── controllers │ ├── bundle.controller.ts │ ├── convert.controller.ts │ ├── diff.controller.ts │ ├── docs.controller.ts │ ├── generate.controller.ts │ ├── help.controller.ts │ ├── parse.controller.ts │ ├── tests │ │ ├── bundle.controller.test.ts │ │ ├── convert.controller.test.ts │ │ ├── diff.controller.test.ts │ │ ├── generate.controller.test.ts │ │ ├── help.controller.test.ts │ │ ├── parse.controller.test.ts │ │ └── validate.controller.test.ts │ └── validate.controller.ts ├── exceptions │ └── problem.exception.ts ├── interfaces.ts ├── middlewares │ ├── problem.middleware.ts │ ├── tests │ │ ├── problem.middleware.test.ts │ │ └── validation.middleware.test.ts │ └── validation.middleware.ts ├── server-api.d.ts ├── server.ts ├── services │ ├── archiver.service.ts │ ├── convert.service.ts │ ├── generator.service.ts │ └── tests │ │ ├── convert.service.test.ts │ │ └── generator.service.test.ts └── utils │ ├── ajv.ts │ ├── app-openapi.ts │ ├── logger.ts │ ├── parser.ts │ ├── retrieve-language.ts │ ├── temp-dir.ts │ └── tests │ ├── app-openapi.test.ts │ ├── retrieve-language.test.ts │ └── temp-dir.test.ts ├── tests ├── jest.setup.ts └── test.controller.ts ├── tsconfig.json └── tsconfig.test.json /.all-contributorsrc: -------------------------------------------------------------------------------- 1 | { 2 | "projectName": "server-api", 3 | "projectOwner": "asyncapi", 4 | "repoType": "github", 5 | "repoHost": "https://github.com", 6 | "files": [ 7 | "README.md" 8 | ], 9 | "imageSize": 100, 10 | "commit": false, 11 | "commitConvention": "none", 12 | "contributors": [ 13 | { 14 | "login": "magicmatatjahu", 15 | "name": "Maciej Urbańczyk", 16 | "avatar_url": "https://avatars.githubusercontent.com/u/20404945?v=4", 17 | "profile": "https://github.com/magicmatatjahu", 18 | "contributions": [ 19 | "maintenance", 20 | "code", 21 | "doc", 22 | "bug", 23 | "ideas", 24 | "review", 25 | "test", 26 | "infra", 27 | "mentoring" 28 | ] 29 | }, 30 | { 31 | "login": "BOLT04", 32 | "name": "David Pereira", 33 | "avatar_url": "https://avatars.githubusercontent.com/u/18630253?v=4", 34 | "profile": "https://bolt04.github.io/react-ultimate-resume/", 35 | "contributions": [ 36 | "maintenance", 37 | "code", 38 | "doc", 39 | "bug", 40 | "ideas", 41 | "review", 42 | "test", 43 | "infra", 44 | "mentoring" 45 | ] 46 | }, 47 | { 48 | "login": "smoya", 49 | "name": "Sergio Moya", 50 | "avatar_url": "https://avatars.githubusercontent.com/u/1083296?v=4", 51 | "profile": "https://github.com/smoya", 52 | "contributions": [ 53 | "maintenance", 54 | "code", 55 | "doc", 56 | "bug", 57 | "ideas", 58 | "review", 59 | "test", 60 | "infra", 61 | "mentoring" 62 | ] 63 | }, 64 | { 65 | "login": "ritik307", 66 | "name": "Ritik Rawal", 67 | "avatar_url": "https://avatars.githubusercontent.com/u/22374829?v=4", 68 | "profile": "https://ritik307.github.io/portfolio/", 69 | "contributions": [ 70 | "code", 71 | "doc" 72 | ] 73 | }, 74 | { 75 | "login": "everly-gif", 76 | "name": "Everly Precia Suresh", 77 | "avatar_url": "https://avatars.githubusercontent.com/u/77877486?v=4", 78 | "profile": "https://everly-precia.netlify.app/", 79 | "contributions": [ 80 | "code", 81 | "doc" 82 | ] 83 | }, 84 | { 85 | "login": "Shurtu-gal", 86 | "name": "Ashish Padhy", 87 | "avatar_url": "https://avatars.githubusercontent.com/u/100484401?v=4", 88 | "profile": "http://ashishpadhy.live", 89 | "contributions": [ 90 | "doc", 91 | "infra" 92 | ] 93 | } 94 | ], 95 | "contributorsPerLine": 7, 96 | "commitType": "docs" 97 | } 98 | -------------------------------------------------------------------------------- /.asyncapi-tool.yaml: -------------------------------------------------------------------------------- 1 | title: AsyncAPI Server API 2 | links: 3 | websiteUrl: https://api.asyncapi.com/v1 4 | docsUrl: https://api.asyncapi.com/v1/docs 5 | filters: 6 | technology: 7 | - Node.js 8 | - TypeScript 9 | categories: 10 | - api -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | npm-debug.log 3 | Dockerfile 4 | .dockerignore 5 | .git 6 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | public 3 | docs 4 | lib 5 | dist 6 | build 7 | dist 8 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | env: 2 | es6: true 3 | node: true 4 | 5 | parser: "@typescript-eslint/parser" 6 | 7 | plugins: 8 | - "@typescript-eslint" 9 | - sonarjs 10 | - security 11 | 12 | extends: 13 | - eslint:recommended 14 | - plugin:@typescript-eslint/eslint-recommended 15 | - plugin:@typescript-eslint/recommended 16 | - plugin:sonarjs/recommended 17 | - plugin:security/recommended 18 | 19 | parserOptions: 20 | ecmaVersion: 2018 21 | sourceType: module 22 | ecmaFeatures: 23 | jsx: true 24 | settings: 25 | react: 26 | version: detect 27 | 28 | rules: 29 | # Ignore Rules 30 | strict: 0 31 | no-underscore-dangle: 0 32 | no-mixed-requires: 0 33 | no-process-exit: 0 34 | no-warning-comments: 0 35 | curly: 0 36 | no-multi-spaces: 0 37 | no-alert: 0 38 | consistent-return: 0 39 | consistent-this: [0, self] 40 | func-style: 0 41 | max-nested-callbacks: 0 42 | camelcase: 0 43 | 44 | # Warnings 45 | no-debugger: 1 46 | no-empty: 1 47 | no-invalid-regexp: 1 48 | no-unused-expressions: 0 49 | no-native-reassign: 1 50 | no-fallthrough: 1 51 | sonarjs/cognitive-complexity: 1 52 | 53 | # Errors 54 | eqeqeq: 2 55 | no-undef: 2 56 | no-dupe-keys: 2 57 | no-empty-character-class: 2 58 | no-self-compare: 2 59 | valid-typeof: 2 60 | no-unused-vars: [2, { "args": "none" }] 61 | handle-callback-err: 2 62 | no-shadow-restricted-names: 2 63 | no-new-require: 2 64 | no-mixed-spaces-and-tabs: 2 65 | block-scoped-var: 2 66 | no-else-return: 2 67 | no-throw-literal: 2 68 | no-void: 2 69 | radix: 2 70 | wrap-iife: [2, outside] 71 | no-shadow: 0 72 | no-path-concat: 2 73 | valid-jsdoc: [0, {requireReturn: false, requireParamDescription: false, requireReturnDescription: false}] 74 | 75 | # stylistic errors 76 | no-spaced-func: 2 77 | semi-spacing: 2 78 | quotes: [2, 'single'] 79 | key-spacing: [2, { beforeColon: false, afterColon: true }] 80 | indent: [2, 2] 81 | no-lonely-if: 2 82 | no-floating-decimal: 2 83 | brace-style: [2, 1tbs, { allowSingleLine: true }] 84 | comma-style: [2, last] 85 | no-multiple-empty-lines: [2, {max: 1}] 86 | no-nested-ternary: 2 87 | operator-assignment: [2, always] 88 | padded-blocks: [2, never] 89 | quote-props: [2, as-needed] 90 | keyword-spacing: [2, {'before': true, 'after': true, 'overrides': {}}] 91 | space-before-blocks: [2, always] 92 | array-bracket-spacing: [2, never] 93 | computed-property-spacing: [2, never] 94 | space-in-parens: [2, never] 95 | space-unary-ops: [2, {words: true, nonwords: false}] 96 | wrap-regex: 2 97 | linebreak-style: 0 98 | semi: [2, always] 99 | arrow-spacing: [2, {before: true, after: true}] 100 | no-class-assign: 2 101 | no-const-assign: 2 102 | no-dupe-class-members: 2 103 | no-this-before-super: 2 104 | no-var: 2 105 | object-shorthand: [2, always] 106 | prefer-arrow-callback: 2 107 | prefer-const: 2 108 | prefer-spread: 2 109 | prefer-template: 2 110 | 111 | # Security 112 | "security/detect-non-literal-fs-filename": off 113 | 114 | # TypeScript 115 | "@typescript-eslint/no-empty-interface": "off" 116 | # disable JS rule 117 | no-use-before-define: "off" 118 | "@typescript-eslint/no-use-before-define": ["error"] 119 | "@typescript-eslint/no-empty-function": "off" 120 | "@typescript-eslint/ban-ts-comment": "off" 121 | "@typescript-eslint/no-explicit-any": "off" 122 | "@typescript-eslint/explicit-module-boundary-types": "off" 123 | "@typescript-eslint/no-this-alias": "off" 124 | 125 | overrides: 126 | - files: 127 | - "*.spec.ts" 128 | - "*.test.ts" 129 | rules: 130 | no-undef: "off" 131 | no-console: "off" 132 | prefer-arrow-callback: 0 133 | sonarjs/no-duplicate-string: 0 134 | security/detect-object-injection: 0 -------------------------------------------------------------------------------- /.github/assets/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asyncapi/server-api/1870f8bc2838ce5ff9d67c401804c896bc79b5a8/.github/assets/banner.png -------------------------------------------------------------------------------- /.github/workflows/add-good-first-issue-labels.yml: -------------------------------------------------------------------------------- 1 | # This workflow is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # Purpose of this workflow is to enable anyone to label issue with 'Good First Issue' and 'area/*' with a single command. 5 | name: Add 'Good First Issue' and 'area/*' labels # if proper comment added 6 | 7 | on: 8 | issue_comment: 9 | types: 10 | - created 11 | 12 | jobs: 13 | add-labels: 14 | if: ${{(!github.event.issue.pull_request && github.event.issue.state != 'closed' && github.actor != 'asyncapi-bot') && (contains(github.event.comment.body, '/good-first-issue') || contains(github.event.comment.body, '/gfi' ))}} 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Add label 18 | uses: actions/github-script@v7 19 | with: 20 | github-token: ${{ secrets.GH_TOKEN }} 21 | script: | 22 | const areas = ['javascript', 'typescript', 'java' , 'go', 'docs', 'ci-cd', 'design']; 23 | const words = context.payload.comment.body.trim().split(" "); 24 | const areaIndex = words.findIndex((word)=> word === '/gfi' || word === '/good-first-issue') + 1 25 | let area = words[areaIndex]; 26 | switch(area){ 27 | case 'ts': 28 | area = 'typescript'; 29 | break; 30 | case 'js': 31 | area = 'javascript'; 32 | break; 33 | case 'markdown': 34 | area = 'docs'; 35 | break; 36 | } 37 | if(!areas.includes(area)){ 38 | const message = `Hey @${context.payload.sender.login}, your message doesn't follow the requirements, you can try \`/help\`.` 39 | 40 | await github.rest.issues.createComment({ 41 | issue_number: context.issue.number, 42 | owner: context.repo.owner, 43 | repo: context.repo.repo, 44 | body: message 45 | }) 46 | } else { 47 | 48 | // remove area if there is any before adding new labels. 49 | const currentLabels = (await github.rest.issues.listLabelsOnIssue({ 50 | issue_number: context.issue.number, 51 | owner: context.repo.owner, 52 | repo: context.repo.repo, 53 | })).data.map(label => label.name); 54 | 55 | const shouldBeRemoved = currentLabels.filter(label => (label.startsWith('area/') && !label.endsWith(area))); 56 | shouldBeRemoved.forEach(label => { 57 | github.rest.issues.deleteLabel({ 58 | owner: context.repo.owner, 59 | repo: context.repo.repo, 60 | name: label, 61 | }); 62 | }); 63 | 64 | // Add new labels. 65 | github.rest.issues.addLabels({ 66 | issue_number: context.issue.number, 67 | owner: context.repo.owner, 68 | repo: context.repo.repo, 69 | labels: ['good first issue', `area/${area}`] 70 | }); 71 | } 72 | -------------------------------------------------------------------------------- /.github/workflows/automerge-for-humans-add-ready-to-merge-or-do-not-merge-label.yml: -------------------------------------------------------------------------------- 1 | # This workflow is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # Purpose of this workflow is to enable anyone to label PR with the following labels: 5 | # `ready-to-merge` and `do-not-merge` labels to get stuff merged or blocked from merging 6 | # `autoupdate` to keep a branch up-to-date with the target branch 7 | 8 | name: Label PRs # if proper comment added 9 | 10 | on: 11 | issue_comment: 12 | types: 13 | - created 14 | 15 | jobs: 16 | add-ready-to-merge-label: 17 | if: > 18 | github.event.issue.pull_request && 19 | github.event.issue.state != 'closed' && 20 | github.actor != 'asyncapi-bot' && 21 | ( 22 | contains(github.event.comment.body, '/ready-to-merge') || 23 | contains(github.event.comment.body, '/rtm' ) 24 | ) 25 | 26 | runs-on: ubuntu-latest 27 | steps: 28 | - name: Add ready-to-merge label 29 | uses: actions/github-script@v7 30 | with: 31 | github-token: ${{ secrets.GH_TOKEN }} 32 | script: | 33 | const prDetailsUrl = context.payload.issue.pull_request.url; 34 | const { data: pull } = await github.request(prDetailsUrl); 35 | const { draft: isDraft} = pull; 36 | if(!isDraft) { 37 | console.log('adding ready-to-merge label...'); 38 | github.rest.issues.addLabels({ 39 | issue_number: context.issue.number, 40 | owner: context.repo.owner, 41 | repo: context.repo.repo, 42 | labels: ['ready-to-merge'] 43 | }) 44 | } 45 | 46 | const { data: comparison } = 47 | await github.rest.repos.compareCommitsWithBasehead({ 48 | owner: pull.head.repo.owner.login, 49 | repo: pull.head.repo.name, 50 | basehead: `${pull.base.label}...${pull.head.label}`, 51 | }); 52 | if (comparison.behind_by !== 0 && pull.mergeable_state === 'behind') { 53 | console.log(`This branch is behind the target by ${comparison.behind_by} commits`) 54 | console.log('adding out-of-date comment...'); 55 | github.rest.issues.createComment({ 56 | issue_number: context.issue.number, 57 | owner: context.repo.owner, 58 | repo: context.repo.repo, 59 | body: `Hello, @${{ github.actor }}! 👋🏼 60 | This PR is not up to date with the base branch and can't be merged. 61 | Please update your branch manually with the latest version of the base branch. 62 | PRO-TIP: To request an update from the upstream branch, simply comment \`/u\` or \`/update\` and our bot will handle the update operation promptly. 63 | 64 | The only requirement for this to work is to enable [Allow edits from maintainers](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/allowing-changes-to-a-pull-request-branch-created-from-a-fork) option in your PR. Also the update will not work if your fork is located in an organization, not under your personal profile. 65 | Thanks 😄` 66 | }) 67 | } 68 | 69 | add-do-not-merge-label: 70 | if: > 71 | github.event.issue.pull_request && 72 | github.event.issue.state != 'closed' && 73 | github.actor != 'asyncapi-bot' && 74 | ( 75 | contains(github.event.comment.body, '/do-not-merge') || 76 | contains(github.event.comment.body, '/dnm' ) 77 | ) 78 | runs-on: ubuntu-latest 79 | steps: 80 | - name: Add do-not-merge label 81 | uses: actions/github-script@v7 82 | with: 83 | github-token: ${{ secrets.GH_TOKEN }} 84 | script: | 85 | github.rest.issues.addLabels({ 86 | issue_number: context.issue.number, 87 | owner: context.repo.owner, 88 | repo: context.repo.repo, 89 | labels: ['do-not-merge'] 90 | }) 91 | add-autoupdate-label: 92 | if: > 93 | github.event.issue.pull_request && 94 | github.event.issue.state != 'closed' && 95 | github.actor != 'asyncapi-bot' && 96 | ( 97 | contains(github.event.comment.body, '/autoupdate') || 98 | contains(github.event.comment.body, '/au' ) 99 | ) 100 | runs-on: ubuntu-latest 101 | steps: 102 | - name: Add autoupdate label 103 | uses: actions/github-script@v7 104 | with: 105 | github-token: ${{ secrets.GH_TOKEN }} 106 | script: | 107 | github.rest.issues.addLabels({ 108 | issue_number: context.issue.number, 109 | owner: context.repo.owner, 110 | repo: context.repo.repo, 111 | labels: ['autoupdate'] 112 | }) 113 | -------------------------------------------------------------------------------- /.github/workflows/automerge-for-humans-merging.yml: -------------------------------------------------------------------------------- 1 | # This workflow is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # Purpose of this workflow is to allow people to merge PR without a need of maintainer doing it. If all checks are in place (including maintainers approval) - JUST MERGE IT! 5 | name: Automerge For Humans 6 | 7 | on: 8 | pull_request_target: 9 | types: 10 | - labeled 11 | - unlabeled 12 | - synchronize 13 | - opened 14 | - edited 15 | - ready_for_review 16 | - reopened 17 | - unlocked 18 | 19 | jobs: 20 | automerge-for-humans: 21 | # it runs only if PR actor is not a bot, at least not a bot that we know 22 | if: | 23 | github.event.pull_request.draft == false && 24 | (github.event.pull_request.user.login != 'asyncapi-bot' || 25 | github.event.pull_request.user.login != 'dependabot[bot]' || 26 | github.event.pull_request.user.login != 'dependabot-preview[bot]') 27 | runs-on: ubuntu-latest 28 | steps: 29 | - name: Get PR authors 30 | id: authors 31 | uses: actions/github-script@v7 32 | with: 33 | script: | 34 | // Get paginated list of all commits in the PR 35 | try { 36 | const commitOpts = github.rest.pulls.listCommits.endpoint.merge({ 37 | owner: context.repo.owner, 38 | repo: context.repo.repo, 39 | pull_number: context.issue.number 40 | }); 41 | 42 | const commits = await github.paginate(commitOpts); 43 | 44 | if (commits.length === 0) { 45 | core.setFailed('No commits found in the PR'); 46 | return ''; 47 | } 48 | 49 | // Get unique authors from the commits list 50 | const authors = commits.reduce((acc, commit) => { 51 | const username = commit.author?.login || commit.commit.author?.name; 52 | if (username && !acc[username]) { 53 | acc[username] = { 54 | name: commit.commit.author?.name, 55 | email: commit.commit.author?.email, 56 | } 57 | } 58 | 59 | return acc; 60 | }, {}); 61 | 62 | return authors; 63 | } catch (error) { 64 | core.setFailed(error.message); 65 | return []; 66 | } 67 | 68 | - name: Create commit message 69 | id: create-commit-message 70 | uses: actions/github-script@v7 71 | with: 72 | script: | 73 | const authors = ${{ steps.authors.outputs.result }}; 74 | 75 | if (Object.keys(authors).length === 0) { 76 | core.setFailed('No authors found in the PR'); 77 | return ''; 78 | } 79 | 80 | // Create a string of the form "Co-authored-by: Name " 81 | // ref: https://docs.github.com/en/pull-requests/committing-changes-to-your-project/creating-and-editing-commits/creating-a-commit-with-multiple-authors 82 | const coAuthors = Object.values(authors).map(author => { 83 | return `Co-authored-by: ${author.name} <${author.email}>`; 84 | }).join('\n'); 85 | 86 | core.debug(coAuthors);; 87 | 88 | return coAuthors; 89 | 90 | - name: Automerge PR 91 | uses: pascalgn/automerge-action@22948e0bc22f0aa673800da838595a3e7347e584 #v0.15.6 https://github.com/pascalgn/automerge-action/releases/tag/v0.15.6 92 | env: 93 | GITHUB_TOKEN: "${{ secrets.GH_TOKEN }}" 94 | MERGE_LABELS: "!do-not-merge,ready-to-merge" 95 | MERGE_METHOD: "squash" 96 | # Using the output of the previous step (`Co-authored-by: ...` lines) as commit description. 97 | # Important to keep 2 empty lines as https://docs.github.com/en/pull-requests/committing-changes-to-your-project/creating-and-editing-commits/creating-a-commit-with-multiple-authors#creating-co-authored-commits-on-the-command-line mentions 98 | MERGE_COMMIT_MESSAGE: "{pullRequest.title} (#{pullRequest.number})\n\n\n${{ fromJSON(steps.create-commit-message.outputs.result) }}" 99 | MERGE_RETRIES: "20" 100 | MERGE_RETRY_SLEEP: "30000" 101 | -------------------------------------------------------------------------------- /.github/workflows/automerge-for-humans-remove-ready-to-merge-label-on-edit.yml: -------------------------------------------------------------------------------- 1 | # This workflow is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # Defence from evil contributor that after adding `ready-to-merge` all suddenly makes evil commit or evil change in PR title 5 | # Label is removed once above action is detected 6 | name: Remove ready-to-merge label 7 | 8 | on: 9 | pull_request_target: 10 | types: 11 | - synchronize 12 | - edited 13 | 14 | jobs: 15 | remove-ready-label: 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Remove label 19 | uses: actions/github-script@v7 20 | with: 21 | github-token: ${{ secrets.GH_TOKEN }} 22 | script: | 23 | const labelToRemove = 'ready-to-merge'; 24 | const labels = context.payload.pull_request.labels; 25 | const isLabelPresent = labels.some(label => label.name === labelToRemove) 26 | if(!isLabelPresent) return; 27 | github.rest.issues.removeLabel({ 28 | issue_number: context.issue.number, 29 | owner: context.repo.owner, 30 | repo: context.repo.repo, 31 | name: labelToRemove 32 | }) 33 | -------------------------------------------------------------------------------- /.github/workflows/automerge-orphans.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | name: 'Notify on failing automerge' 5 | 6 | on: 7 | schedule: 8 | - cron: "0 0 * * *" 9 | 10 | jobs: 11 | identify-orphans: 12 | if: startsWith(github.repository, 'asyncapi/') 13 | name: Find orphans and notify 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Checkout repository 17 | uses: actions/checkout@v4 18 | - name: Get list of orphans 19 | uses: actions/github-script@v7 20 | id: orphans 21 | with: 22 | github-token: ${{ secrets.GITHUB_TOKEN }} 23 | script: | 24 | const query = `query($owner:String!, $name:String!) { 25 | repository(owner:$owner, name:$name){ 26 | pullRequests(first: 100, states: OPEN){ 27 | nodes{ 28 | title 29 | url 30 | author { 31 | resourcePath 32 | } 33 | } 34 | } 35 | } 36 | }`; 37 | const variables = { 38 | owner: context.repo.owner, 39 | name: context.repo.repo 40 | }; 41 | const { repository: { pullRequests: { nodes } } } = await github.graphql(query, variables); 42 | 43 | let orphans = nodes.filter( (pr) => pr.author.resourcePath === '/asyncapi-bot' || pr.author.resourcePath === '/apps/dependabot') 44 | 45 | if (orphans.length) { 46 | core.setOutput('found', 'true'); 47 | //Yes, this is very naive approach to assume there is just one PR causing issues, there can be a case that more PRs are affected the same day 48 | //The thing is that handling multiple PRs will increase a complexity in this PR that in my opinion we should avoid 49 | //The other PRs will be reported the next day the action runs, or person that checks first url will notice the other ones 50 | core.setOutput('url', orphans[0].url); 51 | core.setOutput('title', orphans[0].title); 52 | } 53 | - if: steps.orphans.outputs.found == 'true' 54 | name: Convert markdown to slack markdown 55 | uses: asyncapi/.github/.github/actions/slackify-markdown@master 56 | id: issuemarkdown 57 | with: 58 | markdown: "-> [${{steps.orphans.outputs.title}}](${{steps.orphans.outputs.url}})" 59 | - if: steps.orphans.outputs.found == 'true' 60 | name: Send info about orphan to slack 61 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2 62 | env: 63 | SLACK_WEBHOOK: ${{secrets.SLACK_CI_FAIL_NOTIFY}} 64 | SLACK_TITLE: 🚨 Not merged PR that should be automerged 🚨 65 | SLACK_MESSAGE: ${{steps.issuemarkdown.outputs.text}} 66 | MSG_MINIMAL: true -------------------------------------------------------------------------------- /.github/workflows/automerge.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo. 3 | 4 | name: Automerge PRs from bots 5 | 6 | on: 7 | pull_request_target: 8 | types: 9 | - opened 10 | - synchronize 11 | 12 | jobs: 13 | autoapprove-for-bot: 14 | name: Autoapprove PR comming from a bot 15 | if: > 16 | contains(fromJson('["asyncapi-bot", "dependabot[bot]", "dependabot-preview[bot]"]'), github.event.pull_request.user.login) && 17 | contains(fromJson('["asyncapi-bot", "dependabot[bot]", "dependabot-preview[bot]"]'), github.actor) && 18 | !contains(github.event.pull_request.labels.*.name, 'released') 19 | runs-on: ubuntu-latest 20 | steps: 21 | - name: Autoapproving 22 | uses: hmarr/auto-approve-action@44888193675f29a83e04faf4002fa8c0b537b1e4 # v3.2.1 is used https://github.com/hmarr/auto-approve-action/releases/tag/v3.2.1 23 | with: 24 | github-token: "${{ secrets.GH_TOKEN_BOT_EVE }}" 25 | 26 | - name: Label autoapproved 27 | uses: actions/github-script@v7 28 | with: 29 | github-token: ${{ secrets.GH_TOKEN }} 30 | script: | 31 | github.rest.issues.addLabels({ 32 | issue_number: context.issue.number, 33 | owner: context.repo.owner, 34 | repo: context.repo.repo, 35 | labels: ['autoapproved', 'autoupdate'] 36 | }) 37 | 38 | automerge-for-bot: 39 | name: Automerge PR autoapproved by a bot 40 | needs: [autoapprove-for-bot] 41 | runs-on: ubuntu-latest 42 | steps: 43 | - name: Automerging 44 | uses: pascalgn/automerge-action@22948e0bc22f0aa673800da838595a3e7347e584 #v0.15.6 https://github.com/pascalgn/automerge-action/releases/tag/v0.15.6 45 | env: 46 | GITHUB_TOKEN: "${{ secrets.GH_TOKEN }}" 47 | GITHUB_LOGIN: asyncapi-bot 48 | MERGE_LABELS: "!do-not-merge" 49 | MERGE_METHOD: "squash" 50 | MERGE_COMMIT_MESSAGE: "{pullRequest.title} (#{pullRequest.number})" 51 | MERGE_RETRIES: "20" 52 | MERGE_RETRY_SLEEP: "30000" 53 | -------------------------------------------------------------------------------- /.github/workflows/autoupdate.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # This workflow is designed to work with: 5 | # - autoapprove and automerge workflows for dependabot and asyncapibot. 6 | # - special release branches that we from time to time create in upstream repos. If we open up PRs for them from the very beginning of the release, the release branch will constantly update with new things from the destination branch they are opened against 7 | 8 | # It uses GitHub Action that auto-updates pull requests branches, whenever changes are pushed to their destination branch. 9 | # Autoupdating to latest destination branch works only in the context of upstream repo and not forks 10 | 11 | name: autoupdate 12 | 13 | on: 14 | push: 15 | branches-ignore: 16 | - 'version-bump/**' 17 | - 'dependabot/**' 18 | - 'bot/**' 19 | - 'all-contributors/**' 20 | 21 | jobs: 22 | autoupdate-for-bot: 23 | if: startsWith(github.repository, 'asyncapi/') 24 | name: Autoupdate autoapproved PR created in the upstream 25 | runs-on: ubuntu-latest 26 | steps: 27 | - name: Autoupdating 28 | uses: docker://chinthakagodawita/autoupdate-action:v1 29 | env: 30 | GITHUB_TOKEN: '${{ secrets.GH_TOKEN_BOT_EVE }}' 31 | PR_FILTER: "labelled" 32 | PR_LABELS: "autoupdate" 33 | PR_READY_STATE: "ready_for_review" 34 | MERGE_CONFLICT_ACTION: "ignore" 35 | -------------------------------------------------------------------------------- /.github/workflows/bounty-program-commands.yml: -------------------------------------------------------------------------------- 1 | # This workflow is centrally managed at https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repository, as they will be overwritten with 3 | # changes made to the same file in the abovementioned repository. 4 | 5 | # The purpose of this workflow is to allow Bounty Team members 6 | # (https://github.com/orgs/asyncapi/teams/bounty_team) to issue commands to the 7 | # organization's global AsyncAPI bot related to the Bounty Program, while at the 8 | # same time preventing unauthorized users from misusing them. 9 | 10 | name: Bounty Program commands 11 | 12 | on: 13 | issue_comment: 14 | types: 15 | - created 16 | 17 | env: 18 | BOUNTY_PROGRAM_LABELS_JSON: | 19 | [ 20 | {"name": "bounty", "color": "0e8a16", "description": "Participation in the Bounty Program"} 21 | ] 22 | 23 | jobs: 24 | guard-against-unauthorized-use: 25 | if: > 26 | github.actor != ('aeworxet' || 'thulieblack') && 27 | ( 28 | startsWith(github.event.comment.body, '/bounty' ) 29 | ) 30 | 31 | runs-on: ubuntu-latest 32 | 33 | steps: 34 | - name: ❌ @${{github.actor}} made an unauthorized attempt to use a Bounty Program's command 35 | uses: actions/github-script@v7 36 | with: 37 | github-token: ${{ secrets.GH_TOKEN }} 38 | script: | 39 | const commentText = `❌ @${{github.actor}} is not authorized to use the Bounty Program's commands. 40 | These commands can only be used by members of the [Bounty Team](https://github.com/orgs/asyncapi/teams/bounty_team).`; 41 | 42 | console.log(`❌ @${{github.actor}} made an unauthorized attempt to use a Bounty Program's command.`); 43 | github.rest.issues.createComment({ 44 | issue_number: context.issue.number, 45 | owner: context.repo.owner, 46 | repo: context.repo.repo, 47 | body: commentText 48 | }) 49 | 50 | add-label-bounty: 51 | if: > 52 | github.actor == ('aeworxet' || 'thulieblack') && 53 | ( 54 | startsWith(github.event.comment.body, '/bounty' ) 55 | ) 56 | 57 | runs-on: ubuntu-latest 58 | 59 | steps: 60 | - name: Add label `bounty` 61 | uses: actions/github-script@v7 62 | with: 63 | github-token: ${{ secrets.GH_TOKEN }} 64 | script: | 65 | const BOUNTY_PROGRAM_LABELS = JSON.parse(process.env.BOUNTY_PROGRAM_LABELS_JSON); 66 | let LIST_OF_LABELS_FOR_REPO = await github.rest.issues.listLabelsForRepo({ 67 | owner: context.repo.owner, 68 | repo: context.repo.repo, 69 | }); 70 | 71 | LIST_OF_LABELS_FOR_REPO = LIST_OF_LABELS_FOR_REPO.data.map(key => key.name); 72 | 73 | if (!LIST_OF_LABELS_FOR_REPO.includes(BOUNTY_PROGRAM_LABELS[0].name)) { 74 | await github.rest.issues.createLabel({ 75 | owner: context.repo.owner, 76 | repo: context.repo.repo, 77 | name: BOUNTY_PROGRAM_LABELS[0].name, 78 | color: BOUNTY_PROGRAM_LABELS[0].color, 79 | description: BOUNTY_PROGRAM_LABELS[0].description 80 | }); 81 | } 82 | 83 | console.log('Adding label `bounty`...'); 84 | github.rest.issues.addLabels({ 85 | issue_number: context.issue.number, 86 | owner: context.repo.owner, 87 | repo: context.repo.repo, 88 | labels: [BOUNTY_PROGRAM_LABELS[0].name] 89 | }) 90 | 91 | remove-label-bounty: 92 | if: > 93 | github.actor == ('aeworxet' || 'thulieblack') && 94 | ( 95 | startsWith(github.event.comment.body, '/unbounty' ) 96 | ) 97 | 98 | runs-on: ubuntu-latest 99 | 100 | steps: 101 | - name: Remove label `bounty` 102 | uses: actions/github-script@v7 103 | with: 104 | github-token: ${{ secrets.GH_TOKEN }} 105 | script: | 106 | const BOUNTY_PROGRAM_LABELS = JSON.parse(process.env.BOUNTY_PROGRAM_LABELS_JSON); 107 | let LIST_OF_LABELS_FOR_ISSUE = await github.rest.issues.listLabelsOnIssue({ 108 | owner: context.repo.owner, 109 | repo: context.repo.repo, 110 | issue_number: context.issue.number, 111 | }); 112 | 113 | LIST_OF_LABELS_FOR_ISSUE = LIST_OF_LABELS_FOR_ISSUE.data.map(key => key.name); 114 | 115 | if (LIST_OF_LABELS_FOR_ISSUE.includes(BOUNTY_PROGRAM_LABELS[0].name)) { 116 | console.log('Removing label `bounty`...'); 117 | github.rest.issues.removeLabel({ 118 | issue_number: context.issue.number, 119 | owner: context.repo.owner, 120 | repo: context.repo.repo, 121 | name: [BOUNTY_PROGRAM_LABELS[0].name] 122 | }) 123 | } 124 | -------------------------------------------------------------------------------- /.github/workflows/bump.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # Purpose of this action is to update npm package in libraries that use it. It is like dependabot for asyncapi npm modules only. 5 | # It runs in a repo after merge of release commit and searches for other packages that use released package. Every found package gets updated with lates version 6 | 7 | name: Bump package version in dependent repos - if Node project 8 | 9 | on: 10 | # It cannot run on release event as when release is created then version is not yet bumped in package.json 11 | # This means we cannot extract easily latest version and have a risk that package is not yet on npm 12 | push: 13 | branches: 14 | - master 15 | 16 | jobs: 17 | bump-in-dependent-projects: 18 | name: Bump this package in repositories that depend on it 19 | if: startsWith(github.event.commits[0].message, 'chore(release):') 20 | runs-on: ubuntu-latest 21 | steps: 22 | - name: Checkout repo 23 | uses: actions/checkout@v4 24 | - name: Check if Node.js project and has package.json 25 | id: packagejson 26 | run: test -e ./package.json && echo "exists=true" >> $GITHUB_OUTPUT || echo "exists=false" >> $GITHUB_OUTPUT 27 | - if: steps.packagejson.outputs.exists == 'true' 28 | name: Bumping latest version of this package in other repositories 29 | uses: derberg/npm-dependency-manager-for-your-github-org@1eafd3bf3974f21d395c1abac855cb04b295d570 # using v6.-.- https://github.com/derberg/npm-dependency-manager-for-your-github-org/releases/tag/v6 30 | with: 31 | github_token: ${{ secrets.GH_TOKEN }} 32 | committer_username: asyncapi-bot 33 | committer_email: info@asyncapi.io 34 | repos_to_ignore: spec,bindings,saunter,server-api 35 | custom_id: "dependency update from asyncapi bot" 36 | -------------------------------------------------------------------------------- /.github/workflows/help-command.yml: -------------------------------------------------------------------------------- 1 | # This workflow is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | name: Create help comment 5 | 6 | on: 7 | issue_comment: 8 | types: 9 | - created 10 | 11 | jobs: 12 | create_help_comment_pr: 13 | if: ${{ github.event.issue.pull_request && startsWith(github.event.comment.body, '/help') && github.actor != 'asyncapi-bot' }} 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Add comment to PR 17 | uses: actions/github-script@v7 18 | with: 19 | github-token: ${{ secrets.GH_TOKEN }} 20 | script: | 21 | //Yes to add comment to PR the same endpoint is use that we use to create a comment in issue 22 | //For more details http://developer.github.com/v3/issues/comments/ 23 | //Also proved by this action https://github.com/actions-ecosystem/action-create-comment/blob/main/src/main.ts 24 | github.rest.issues.createComment({ 25 | issue_number: context.issue.number, 26 | owner: context.repo.owner, 27 | repo: context.repo.repo, 28 | body: `Hello, @${{ github.actor }}! 👋🏼 29 | 30 | I'm 🧞🧞🧞 Genie 🧞🧞🧞 from the magic lamp. Looks like somebody needs a hand! 31 | 32 | At the moment the following comments are supported in pull requests: 33 | 34 | - \`/please-take-a-look\` or \`/ptal\` - This comment will add a comment to the PR asking for attention from the reviewrs who have not reviewed the PR yet. 35 | - \`/ready-to-merge\` or \`/rtm\` - This comment will trigger automerge of PR in case all required checks are green, approvals in place and do-not-merge label is not added 36 | - \`/do-not-merge\` or \`/dnm\` - This comment will block automerging even if all conditions are met and ready-to-merge label is added 37 | - \`/autoupdate\` or \`/au\` - This comment will add \`autoupdate\` label to the PR and keeps your PR up-to-date to the target branch's future changes. Unless there is a merge conflict or it is a draft PR. (Currently only works for upstream branches.) 38 | - \`/update\` or \`/u\` - This comment will update the PR with the latest changes from the target branch. Unless there is a merge conflict or it is a draft PR. NOTE: this only updates the PR once, so if you need to update again, you need to call the command again.` 39 | }) 40 | 41 | create_help_comment_issue: 42 | if: ${{ !github.event.issue.pull_request && startsWith(github.event.comment.body, '/help') && github.actor != 'asyncapi-bot' }} 43 | runs-on: ubuntu-latest 44 | steps: 45 | - name: Add comment to Issue 46 | uses: actions/github-script@v7 47 | with: 48 | github-token: ${{ secrets.GH_TOKEN }} 49 | script: | 50 | github.rest.issues.createComment({ 51 | issue_number: context.issue.number, 52 | owner: context.repo.owner, 53 | repo: context.repo.repo, 54 | body: `Hello, @${{ github.actor }}! 👋🏼 55 | 56 | I'm 🧞🧞🧞 Genie 🧞🧞🧞 from the magic lamp. Looks like somebody needs a hand! 57 | 58 | At the moment the following comments are supported in issues: 59 | 60 | - \`/good-first-issue {js | ts | java | go | docs | design | ci-cd}\` or \`/gfi {js | ts | java | go | docs | design | ci-cd}\` - label an issue as a \`good first issue\`. 61 | example: \`/gfi js\` or \`/good-first-issue ci-cd\` 62 | - \`/transfer-issue {repo-name}\` or \`/ti {repo-name}\` - transfer issue from the source repository to the other repository passed by the user. example: \`/ti cli\` or \`/transfer-issue cli\`.` 63 | }) -------------------------------------------------------------------------------- /.github/workflows/if-docker-pr-testing.yml: -------------------------------------------------------------------------------- 1 | #This action is centrally managed in https://github.com/asyncapi/.github/ 2 | #Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | #It does magic only if there is a Dockerfile in the root of the project 4 | name: PR testing - if Docker 5 | 6 | on: 7 | pull_request: 8 | types: [opened, reopened, synchronize, ready_for_review] 9 | 10 | env: 11 | IMAGE_NAME: ${{ github.repository }} 12 | 13 | jobs: 14 | test-docker-pr: 15 | name: Test Docker build 16 | runs-on: ubuntu-latest 17 | 18 | steps: 19 | - if: > 20 | !github.event.pull_request.draft && !( 21 | (github.actor == 'asyncapi-bot' && ( 22 | startsWith(github.event.pull_request.title, 'ci: update of files from global .github repo') || 23 | startsWith(github.event.pull_request.title, 'chore(release):') 24 | )) || 25 | (github.actor == 'asyncapi-bot-eve' && ( 26 | startsWith(github.event.pull_request.title, 'ci: update of files from global .github repo') || 27 | startsWith(github.event.pull_request.title, 'chore(release):') 28 | )) || 29 | (github.actor == 'allcontributors[bot]' && 30 | startsWith(github.event.pull_request.title, 'docs: add') 31 | ) 32 | ) 33 | id: should_run 34 | name: Should Run 35 | run: echo "shouldrun=true" >> $GITHUB_OUTPUT 36 | 37 | - if: steps.should_run.outputs.shouldrun == 'true' 38 | name: Checkout repository 39 | uses: actions/checkout@v4 40 | 41 | - if: steps.should_run.outputs.shouldrun == 'true' 42 | name: Check if project has a Dockerfile 43 | id: docker 44 | run: test -e ./Dockerfile && echo "exists=true" >> $GITHUB_OUTPUT || echo "exists=false" >> $GITHUB_OUTPUT 45 | shell: bash 46 | 47 | - if: steps.docker.outputs.exists == 'true' 48 | name: Set up Docker Buildx 49 | uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # use 3.10.0 https://github.com/docker/setup-buildx-action/releases/tag/v2.5.0 50 | 51 | - if: steps.docker.outputs.exists == 'true' 52 | name: Extract metadata for Docker 53 | id: meta 54 | uses: docker/metadata-action@902fa8ec7d6ecbf8d84d538b9b233a880e428804 # use 5.7.0 https://github.com/docker/metadata-action/releases/tag/v4.3.0 55 | with: 56 | images: ${{ env.IMAGE_NAME }} 57 | 58 | - if: steps.docker.outputs.exists == 'true' 59 | name: Build Docker image 60 | uses: docker/build-push-action@471d1dc4e07e5cdedd4c2171150001c434f0b7a4 # use 6.15.0 https://github.com/docker/build-push-action/releases/tag/v4.0.0 61 | with: 62 | context: . 63 | push: false 64 | tags: ${{ steps.meta.outputs.tags }} 65 | labels: ${{ steps.meta.outputs.labels }} 66 | cache-from: type=gha 67 | cache-to: type=gha,mode=max 68 | -------------------------------------------------------------------------------- /.github/workflows/if-nodejs-pr-testing.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # It does magic only if there is package.json file in the root of the project 5 | name: PR testing - if Node project 6 | 7 | on: 8 | pull_request: 9 | types: [opened, reopened, synchronize, ready_for_review] 10 | 11 | jobs: 12 | test-nodejs-pr: 13 | name: Test NodeJS PR - ${{ matrix.os }} 14 | runs-on: ${{ matrix.os }} 15 | strategy: 16 | matrix: 17 | # Using macos-13 instead of latest (macos-14) due to an issue with Puppeteer and such runner. 18 | # See: https://github.com/puppeteer/puppeteer/issues/12327 and https://github.com/asyncapi/parser-js/issues/1001 19 | os: [ubuntu-latest, macos-13, windows-latest] 20 | steps: 21 | - if: > 22 | !github.event.pull_request.draft && !( 23 | (github.actor == 'asyncapi-bot' && ( 24 | startsWith(github.event.pull_request.title, 'ci: update of files from global .github repo') || 25 | startsWith(github.event.pull_request.title, 'chore(release):') 26 | )) || 27 | (github.actor == 'asyncapi-bot-eve' && ( 28 | startsWith(github.event.pull_request.title, 'ci: update of files from global .github repo') || 29 | startsWith(github.event.pull_request.title, 'chore(release):') 30 | )) || 31 | (github.actor == 'allcontributors[bot]' && 32 | startsWith(github.event.pull_request.title, 'docs: add') 33 | ) 34 | ) 35 | id: should_run 36 | name: Should Run 37 | run: echo "shouldrun=true" >> $GITHUB_OUTPUT 38 | shell: bash 39 | - if: steps.should_run.outputs.shouldrun == 'true' 40 | name: Set git to use LF #to once and for all finish neverending fight between Unix and Windows 41 | run: | 42 | git config --global core.autocrlf false 43 | git config --global core.eol lf 44 | shell: bash 45 | - if: steps.should_run.outputs.shouldrun == 'true' 46 | name: Checkout repository 47 | uses: actions/checkout@v4 48 | - if: steps.should_run.outputs.shouldrun == 'true' 49 | name: Check if Node.js project and has package.json 50 | id: packagejson 51 | run: test -e ./package.json && echo "exists=true" >> $GITHUB_OUTPUT || echo "exists=false" >> $GITHUB_OUTPUT 52 | shell: bash 53 | - if: steps.packagejson.outputs.exists == 'true' 54 | name: Check package-lock version 55 | uses: asyncapi/.github/.github/actions/get-node-version-from-package-lock@master 56 | id: lockversion 57 | - if: steps.packagejson.outputs.exists == 'true' 58 | name: Setup Node.js 59 | uses: actions/setup-node@v4 60 | with: 61 | node-version: "${{ steps.lockversion.outputs.version }}" 62 | - if: steps.lockversion.outputs.version == '18' && matrix.os == 'windows-latest' 63 | #npm cli 10 is buggy because of some cache issue 64 | name: Install npm cli 8 65 | shell: bash 66 | run: npm install -g npm@8.19.4 67 | - if: steps.packagejson.outputs.exists == 'true' 68 | name: Install dependencies 69 | shell: bash 70 | run: npm ci 71 | - if: steps.packagejson.outputs.exists == 'true' 72 | name: Test 73 | run: npm test --if-present 74 | - if: steps.packagejson.outputs.exists == 'true' && matrix.os == 'ubuntu-latest' 75 | #linting should run just one and not on all possible operating systems 76 | name: Run linter 77 | run: npm run lint --if-present 78 | - if: steps.packagejson.outputs.exists == 'true' 79 | name: Run release assets generation to make sure PR does not break it 80 | shell: bash 81 | run: npm run generate:assets --if-present 82 | -------------------------------------------------------------------------------- /.github/workflows/if-nodejs-release.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # It does magic only if there is package.json file in the root of the project 5 | name: Release - if Node project 6 | 7 | on: 8 | push: 9 | branches: 10 | - master 11 | # below lines are not enough to have release supported for these branches 12 | # make sure configuration of `semantic-release` package mentions these branches 13 | - next-spec 14 | - next-major 15 | - next-major-spec 16 | - beta 17 | - alpha 18 | - next 19 | 20 | jobs: 21 | 22 | test-nodejs: 23 | # We just check the message of first commit as there is always just one commit because we squash into one before merging 24 | # "commits" contains array of objects where one of the properties is commit "message" 25 | # Release workflow will be skipped if release conventional commits are not used 26 | if: | 27 | startsWith( github.repository, 'asyncapi/' ) && 28 | (startsWith( github.event.commits[0].message , 'fix:' ) || 29 | startsWith( github.event.commits[0].message, 'fix!:' ) || 30 | startsWith( github.event.commits[0].message, 'feat:' ) || 31 | startsWith( github.event.commits[0].message, 'feat!:' )) 32 | name: Test NodeJS release on ${{ matrix.os }} 33 | runs-on: ${{ matrix.os }} 34 | strategy: 35 | matrix: 36 | # Using macos-13 instead of latest (macos-14) due to an issue with Puppeteer and such runner. 37 | # See: https://github.com/puppeteer/puppeteer/issues/12327 and https://github.com/asyncapi/parser-js/issues/1001 38 | os: [ubuntu-latest, macos-13, windows-latest] 39 | steps: 40 | - name: Set git to use LF #to once and for all finish neverending fight between Unix and Windows 41 | run: | 42 | git config --global core.autocrlf false 43 | git config --global core.eol lf 44 | shell: bash 45 | - name: Checkout repository 46 | uses: actions/checkout@v4 47 | - name: Check if Node.js project and has package.json 48 | id: packagejson 49 | run: test -e ./package.json && echo "exists=true" >> $GITHUB_OUTPUT || echo "exists=false" >> $GITHUB_OUTPUT 50 | shell: bash 51 | - if: steps.packagejson.outputs.exists == 'true' 52 | name: Check package-lock version 53 | uses: asyncapi/.github/.github/actions/get-node-version-from-package-lock@master 54 | id: lockversion 55 | - if: steps.packagejson.outputs.exists == 'true' 56 | name: Setup Node.js 57 | uses: actions/setup-node@v4 58 | with: 59 | node-version: "${{ steps.lockversion.outputs.version }}" 60 | - if: steps.lockversion.outputs.version == '18' && matrix.os == 'windows-latest' 61 | name: Install npm cli 8 62 | shell: bash 63 | #npm cli 10 is buggy because of some cache issues 64 | run: npm install -g npm@8.19.4 65 | - if: steps.packagejson.outputs.exists == 'true' 66 | name: Install dependencies 67 | shell: bash 68 | run: npm ci 69 | - if: steps.packagejson.outputs.exists == 'true' 70 | name: Run test 71 | run: npm test --if-present 72 | - if: failure() # Only, on failure, send a message on the 94_bot-failing-ci slack channel 73 | name: Report workflow run status to Slack 74 | uses: 8398a7/action-slack@28ba43ae48961b90635b50953d216767a6bea486 #using https://github.com/8398a7/action-slack/releases/tag/v3.16.2 75 | with: 76 | status: ${{ job.status }} 77 | fields: repo,action,workflow 78 | text: 'Release workflow failed in testing job' 79 | env: 80 | SLACK_WEBHOOK_URL: ${{ secrets.SLACK_CI_FAIL_NOTIFY }} 81 | 82 | release: 83 | needs: [test-nodejs] 84 | name: Publish to any of NPM, Github, or Docker Hub 85 | runs-on: ubuntu-latest 86 | steps: 87 | - name: Set git to use LF #to once and for all finish neverending fight between Unix and Windows 88 | run: | 89 | git config --global core.autocrlf false 90 | git config --global core.eol lf 91 | - name: Checkout repository 92 | uses: actions/checkout@v4 93 | - name: Check if Node.js project and has package.json 94 | id: packagejson 95 | run: test -e ./package.json && echo "exists=true" >> $GITHUB_OUTPUT || echo "exists=false" >> $GITHUB_OUTPUT 96 | shell: bash 97 | - if: steps.packagejson.outputs.exists == 'true' 98 | name: Check package-lock version 99 | uses: asyncapi/.github/.github/actions/get-node-version-from-package-lock@master 100 | id: lockversion 101 | - if: steps.packagejson.outputs.exists == 'true' 102 | name: Setup Node.js 103 | uses: actions/setup-node@v4 104 | with: 105 | node-version: "${{ steps.lockversion.outputs.version }}" 106 | - if: steps.packagejson.outputs.exists == 'true' 107 | name: Install dependencies 108 | shell: bash 109 | run: npm ci 110 | - if: steps.packagejson.outputs.exists == 'true' 111 | name: Add plugin for conventional commits for semantic-release 112 | run: npm install --save-dev conventional-changelog-conventionalcommits@5.0.0 113 | - if: steps.packagejson.outputs.exists == 'true' 114 | name: Publish to any of NPM, Github, and Docker Hub 115 | id: release 116 | env: 117 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} 118 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 119 | DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} 120 | DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} 121 | GIT_AUTHOR_NAME: asyncapi-bot 122 | GIT_AUTHOR_EMAIL: info@asyncapi.io 123 | GIT_COMMITTER_NAME: asyncapi-bot 124 | GIT_COMMITTER_EMAIL: info@asyncapi.io 125 | run: npx semantic-release@19.0.4 126 | - if: failure() # Only, on failure, send a message on the 94_bot-failing-ci slack channel 127 | name: Report workflow run status to Slack 128 | uses: 8398a7/action-slack@28ba43ae48961b90635b50953d216767a6bea486 #using https://github.com/8398a7/action-slack/releases/tag/v3.16.2 129 | with: 130 | status: ${{ job.status }} 131 | fields: repo,action,workflow 132 | text: 'Release workflow failed in release job' 133 | env: 134 | SLACK_WEBHOOK_URL: ${{ secrets.SLACK_CI_FAIL_NOTIFY }} 135 | -------------------------------------------------------------------------------- /.github/workflows/if-nodejs-version-bump.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # It does magic only if there is package.json file in the root of the project 5 | name: Version bump - if Node.js project 6 | 7 | on: 8 | release: 9 | types: 10 | - published 11 | 12 | jobs: 13 | version_bump: 14 | name: Generate assets and bump NodeJS 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Checkout repository 18 | uses: actions/checkout@v4 19 | with: 20 | # target branch of release. More info https://docs.github.com/en/rest/reference/repos#releases 21 | # in case release is created from release branch then we need to checkout from given branch 22 | # if @semantic-release/github is used to publish, the minimum version is 7.2.0 for proper working 23 | ref: ${{ github.event.release.target_commitish }} 24 | - name: Check if Node.js project and has package.json 25 | id: packagejson 26 | run: test -e ./package.json && echo "exists=true" >> $GITHUB_OUTPUT || echo "exists=false" >> $GITHUB_OUTPUT 27 | - if: steps.packagejson.outputs.exists == 'true' 28 | name: Check package-lock version 29 | uses: asyncapi/.github/.github/actions/get-node-version-from-package-lock@master 30 | id: lockversion 31 | - if: steps.packagejson.outputs.exists == 'true' 32 | name: Setup Node.js 33 | uses: actions/setup-node@v4 34 | with: 35 | node-version: "${{ steps.lockversion.outputs.version }}" 36 | cache: 'npm' 37 | cache-dependency-path: '**/package-lock.json' 38 | - if: steps.packagejson.outputs.exists == 'true' 39 | name: Install dependencies 40 | run: npm ci 41 | - if: steps.packagejson.outputs.exists == 'true' 42 | name: Assets generation 43 | run: npm run generate:assets --if-present 44 | - if: steps.packagejson.outputs.exists == 'true' 45 | name: Bump version in package.json 46 | # There is no need to substract "v" from the tag as version script handles it 47 | # When adding "bump:version" script in package.json, make sure no tags are added by default (--no-git-tag-version) as they are already added by release workflow 48 | # When adding "bump:version" script in package.json, make sure --allow-same-version is set in case someone forgot and updated package.json manually and we want to avoide this action to fail and raise confusion 49 | run: VERSION=${{github.event.release.tag_name}} npm run bump:version 50 | - if: steps.packagejson.outputs.exists == 'true' 51 | name: Create Pull Request with updated asset files including package.json 52 | uses: peter-evans/create-pull-request@38e0b6e68b4c852a5500a94740f0e535e0d7ba54 # use 4.2.4 https://github.com/peter-evans/create-pull-request/releases/tag/v4.2.4 53 | with: 54 | token: ${{ secrets.GH_TOKEN }} 55 | commit-message: 'chore(release): ${{github.event.release.tag_name}}' 56 | committer: asyncapi-bot 57 | author: asyncapi-bot 58 | title: 'chore(release): ${{github.event.release.tag_name}}' 59 | body: 'Version bump in package.json for release [${{github.event.release.tag_name}}](${{github.event.release.html_url}})' 60 | branch: version-bump/${{github.event.release.tag_name}} 61 | - if: failure() # Only, on failure, send a message on the 94_bot-failing-ci slack channel 62 | name: Report workflow run status to Slack 63 | uses: 8398a7/action-slack@28ba43ae48961b90635b50953d216767a6bea486 #using https://github.com/8398a7/action-slack/releases/tag/v3.16.2 64 | with: 65 | status: ${{ job.status }} 66 | fields: repo,action,workflow 67 | text: 'Unable to bump the version in package.json after the release' 68 | env: 69 | SLACK_WEBHOOK_URL: ${{ secrets.SLACK_CI_FAIL_NOTIFY }} -------------------------------------------------------------------------------- /.github/workflows/issues-prs-notifications.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # This action notifies community on slack whenever there is a new issue, PR or discussion started in given repository 5 | name: Notify slack 6 | 7 | on: 8 | issues: 9 | types: [opened, reopened] 10 | 11 | pull_request_target: 12 | types: [opened, reopened, ready_for_review] 13 | 14 | discussion: 15 | types: [created] 16 | 17 | jobs: 18 | issue: 19 | if: github.event_name == 'issues' && github.actor != 'asyncapi-bot' && github.actor != 'dependabot[bot]' && github.actor != 'dependabot-preview[bot]' 20 | name: Notify slack on every new issue 21 | runs-on: ubuntu-latest 22 | steps: 23 | - name: Convert markdown to slack markdown for issue 24 | uses: asyncapi/.github/.github/actions/slackify-markdown@master 25 | id: issuemarkdown 26 | with: 27 | markdown: "[${{github.event.issue.title}}](${{github.event.issue.html_url}}) \n ${{github.event.issue.body}}" 28 | - name: Send info about issue 29 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2 30 | env: 31 | SLACK_WEBHOOK: ${{secrets.SLACK_GITHUB_NEWISSUEPR}} 32 | SLACK_TITLE: 🐛 New Issue in ${{github.repository}} 🐛 33 | SLACK_MESSAGE: ${{steps.issuemarkdown.outputs.text}} 34 | MSG_MINIMAL: true 35 | 36 | pull_request: 37 | if: github.event_name == 'pull_request_target' && github.actor != 'asyncapi-bot' && github.actor != 'dependabot[bot]' && github.actor != 'dependabot-preview[bot]' 38 | name: Notify slack on every new pull request 39 | runs-on: ubuntu-latest 40 | steps: 41 | - name: Convert markdown to slack markdown for pull request 42 | uses: asyncapi/.github/.github/actions/slackify-markdown@master 43 | id: prmarkdown 44 | with: 45 | markdown: "[${{github.event.pull_request.title}}](${{github.event.pull_request.html_url}}) \n ${{github.event.pull_request.body}}" 46 | - name: Send info about pull request 47 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2 48 | env: 49 | SLACK_WEBHOOK: ${{secrets.SLACK_GITHUB_NEWISSUEPR}} 50 | SLACK_TITLE: 💪 New Pull Request in ${{github.repository}} 💪 51 | SLACK_MESSAGE: ${{steps.prmarkdown.outputs.text}} 52 | MSG_MINIMAL: true 53 | 54 | discussion: 55 | if: github.event_name == 'discussion' && github.actor != 'asyncapi-bot' && github.actor != 'dependabot[bot]' && github.actor != 'dependabot-preview[bot]' 56 | name: Notify slack on every new pull request 57 | runs-on: ubuntu-latest 58 | steps: 59 | - name: Convert markdown to slack markdown for pull request 60 | uses: asyncapi/.github/.github/actions/slackify-markdown@master 61 | id: discussionmarkdown 62 | with: 63 | markdown: "[${{github.event.discussion.title}}](${{github.event.discussion.html_url}}) \n ${{github.event.discussion.body}}" 64 | - name: Send info about pull request 65 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2 66 | env: 67 | SLACK_WEBHOOK: ${{secrets.SLACK_GITHUB_NEWISSUEPR}} 68 | SLACK_TITLE: 💬 New Discussion in ${{github.repository}} 💬 69 | SLACK_MESSAGE: ${{steps.discussionmarkdown.outputs.text}} 70 | MSG_MINIMAL: true 71 | -------------------------------------------------------------------------------- /.github/workflows/lint-pr-title.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | name: Lint PR title 5 | 6 | on: 7 | pull_request_target: 8 | types: [opened, reopened, synchronize, edited, ready_for_review] 9 | 10 | jobs: 11 | lint-pr-title: 12 | name: Lint PR title 13 | runs-on: ubuntu-latest 14 | steps: 15 | # Since this workflow is REQUIRED for a PR to be mergable, we have to have this 'if' statement in step level instead of job level. 16 | - if: ${{ !contains(fromJson('["asyncapi-bot", "dependabot[bot]", "dependabot-preview[bot]", "allcontributors[bot]"]'), github.actor) }} 17 | uses: amannn/action-semantic-pull-request@c3cd5d1ea3580753008872425915e343e351ab54 #version 5.2.0 https://github.com/amannn/action-semantic-pull-request/releases/tag/v5.2.0 18 | id: lint_pr_title 19 | env: 20 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN}} 21 | with: 22 | subjectPattern: ^(?![A-Z]).+$ 23 | subjectPatternError: | 24 | The subject "{subject}" found in the pull request title "{title}" should start with a lowercase character. 25 | 26 | # Comments the error message from the above lint_pr_title action 27 | - if: ${{ always() && steps.lint_pr_title.outputs.error_message != null && !contains(fromJson('["asyncapi-bot", "dependabot[bot]", "dependabot-preview[bot]", "allcontributors[bot]"]'), github.actor)}} 28 | name: Comment on PR 29 | uses: marocchino/sticky-pull-request-comment@3d60a5b2dae89d44e0c6ddc69dd7536aec2071cd #use 2.5.0 https://github.com/marocchino/sticky-pull-request-comment/releases/tag/v2.5.0 30 | with: 31 | header: pr-title-lint-error 32 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN}} 33 | message: | 34 | 35 | We require all PRs to follow [Conventional Commits specification](https://www.conventionalcommits.org/en/v1.0.0/). 36 | More details 👇🏼 37 | ``` 38 | ${{ steps.lint_pr_title.outputs.error_message}} 39 | ``` 40 | # deletes the error comment if the title is correct 41 | - if: ${{ steps.lint_pr_title.outputs.error_message == null }} 42 | name: delete the comment 43 | uses: marocchino/sticky-pull-request-comment@3d60a5b2dae89d44e0c6ddc69dd7536aec2071cd #use 2.5.0 https://github.com/marocchino/sticky-pull-request-comment/releases/tag/v2.5.0 44 | with: 45 | header: pr-title-lint-error 46 | delete: true 47 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN}} 48 | -------------------------------------------------------------------------------- /.github/workflows/please-take-a-look-command.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # It uses Github actions to listen for comments on issues and pull requests and 5 | # if the comment contains /please-take-a-look or /ptal it will add a comment pinging 6 | # the code-owners who are reviewers for PR 7 | 8 | name: Please take a Look 9 | 10 | on: 11 | issue_comment: 12 | types: [created] 13 | 14 | jobs: 15 | ping-for-attention: 16 | if: > 17 | github.event.issue.pull_request && 18 | github.event.issue.state != 'closed' && 19 | github.actor != 'asyncapi-bot' && 20 | ( 21 | contains(github.event.comment.body, '/please-take-a-look') || 22 | contains(github.event.comment.body, '/ptal') || 23 | contains(github.event.comment.body, '/PTAL') 24 | ) 25 | runs-on: ubuntu-latest 26 | steps: 27 | - name: Check for Please Take a Look Command 28 | uses: actions/github-script@v7 29 | with: 30 | github-token: ${{ secrets.GH_TOKEN }} 31 | script: | 32 | const prDetailsUrl = context.payload.issue.pull_request.url; 33 | const { data: pull } = await github.request(prDetailsUrl); 34 | const reviewers = pull.requested_reviewers.map(reviewer => reviewer.login); 35 | 36 | const { data: reviews } = await github.rest.pulls.listReviews({ 37 | owner: context.repo.owner, 38 | repo: context.repo.repo, 39 | pull_number: context.issue.number 40 | }); 41 | 42 | const reviewersWhoHaveReviewed = reviews.map(review => review.user.login); 43 | 44 | const reviewersWhoHaveNotReviewed = reviewers.filter(reviewer => !reviewersWhoHaveReviewed.includes(reviewer)); 45 | 46 | if (reviewersWhoHaveNotReviewed.length > 0) { 47 | const comment = reviewersWhoHaveNotReviewed.filter(reviewer => reviewer !== 'asyncapi-bot-eve' ).map(reviewer => `@${reviewer}`).join(' '); 48 | await github.rest.issues.createComment({ 49 | issue_number: context.issue.number, 50 | owner: context.repo.owner, 51 | repo: context.repo.repo, 52 | body: `${comment} Please take a look at this PR. Thanks! :wave:` 53 | }); 54 | } 55 | -------------------------------------------------------------------------------- /.github/workflows/release-announcements.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | name: 'Announce releases in different channels' 5 | 6 | on: 7 | release: 8 | types: 9 | - published 10 | 11 | jobs: 12 | 13 | slack-announce: 14 | name: Slack - notify on every release 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Checkout repository 18 | uses: actions/checkout@v4 19 | - name: Convert markdown to slack markdown for issue 20 | uses: asyncapi/.github/.github/actions/slackify-markdown@master 21 | id: markdown 22 | with: 23 | markdown: "[${{github.event.release.tag_name}}](${{github.event.release.html_url}}) \n ${{ github.event.release.body }}" 24 | - name: Send info about release to Slack 25 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2 26 | env: 27 | SLACK_WEBHOOK: ${{ secrets.SLACK_RELEASES }} 28 | SLACK_TITLE: Release ${{github.event.release.tag_name}} for ${{github.repository}} is out in the wild 😱💪🍾🎂 29 | SLACK_MESSAGE: ${{steps.markdown.outputs.text}} 30 | MSG_MINIMAL: true 31 | 32 | twitter-announce: 33 | name: Twitter - notify on minor and major releases 34 | runs-on: ubuntu-latest 35 | steps: 36 | - name: Checkout repo 37 | uses: actions/checkout@v4 38 | - name: Get version of last and previous release 39 | uses: actions/github-script@v7 40 | id: versions 41 | with: 42 | github-token: ${{ secrets.GITHUB_TOKEN }} 43 | script: | 44 | const query = `query($owner:String!, $name:String!) { 45 | repository(owner:$owner, name:$name){ 46 | releases(first: 2, orderBy: {field: CREATED_AT, direction: DESC}) { 47 | nodes { 48 | name 49 | } 50 | } 51 | } 52 | }`; 53 | const variables = { 54 | owner: context.repo.owner, 55 | name: context.repo.repo 56 | }; 57 | const { repository: { releases: { nodes } } } = await github.graphql(query, variables); 58 | core.setOutput('lastver', nodes[0].name); 59 | // In case of first release in the package, there is no such thing as previous error, so we set info about previous version only once we have it 60 | // We should tweet about the release no matter of the type as it is initial release 61 | if (nodes.length != 1) core.setOutput('previousver', nodes[1].name); 62 | - name: Identify release type 63 | id: releasetype 64 | # if previousver is not provided then this steps just logs information about missing version, no errors 65 | run: echo "type=$(npx -q -p semver-diff-cli semver-diff ${{steps.versions.outputs.previousver}} ${{steps.versions.outputs.lastver}})" >> $GITHUB_OUTPUT 66 | - name: Get name of the person that is behind the newly released version 67 | id: author 68 | run: echo "name=$(git log -1 --pretty=format:'%an')" >> $GITHUB_OUTPUT 69 | - name: Publish information about the release to Twitter # tweet only if detected version change is not a patch 70 | # tweet goes out even if the type is not major or minor but "You need provide version number to compare." 71 | # it is ok, it just means we did not identify previous version as we are tweeting out information about the release for the first time 72 | if: steps.releasetype.outputs.type != 'null' && steps.releasetype.outputs.type != 'patch' # null means that versions are the same 73 | uses: m1ner79/Github-Twittction@d1e508b6c2170145127138f93c49b7c46c6ff3a7 # using 2.0.0 https://github.com/m1ner79/Github-Twittction/releases/tag/v2.0.0 74 | with: 75 | twitter_status: "Release ${{github.event.release.tag_name}} for ${{github.repository}} is out in the wild 😱💪🍾🎂\n\nThank you for the contribution ${{ steps.author.outputs.name }} ${{github.event.release.html_url}}" 76 | twitter_consumer_key: ${{ secrets.TWITTER_CONSUMER_KEY }} 77 | twitter_consumer_secret: ${{ secrets.TWITTER_CONSUMER_SECRET }} 78 | twitter_access_token_key: ${{ secrets.TWITTER_ACCESS_TOKEN_KEY }} 79 | twitter_access_token_secret: ${{ secrets.TWITTER_ACCESS_TOKEN_SECRET }} -------------------------------------------------------------------------------- /.github/workflows/release-docker.yml: -------------------------------------------------------------------------------- 1 | name: Release Docker Image 2 | on: 3 | release: 4 | types: 5 | - published 6 | jobs: 7 | 8 | publish-docker: 9 | name: Generating Docker 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout repository 13 | uses: actions/checkout@v3 14 | - name: Get version without v character 15 | id: version 16 | run: | 17 | VERSION=${{github.event.release.tag_name}} 18 | VERSION_WITHOUT_V=${VERSION:1} 19 | echo "value=${VERSION_WITHOUT_V}" >> $GITHUB_OUTPUT 20 | 21 | - name: Release to Docker 22 | run: | 23 | echo ${{secrets.DOCKER_PASSWORD}} | docker login -u ${{secrets.DOCKER_USERNAME}} --password-stdin 24 | npm run docker:build 25 | docker tag asyncapi/server-api:latest asyncapi/server-api:${{ steps.version.outputs.value }} 26 | docker push asyncapi/server-api:${{ steps.version.outputs.value }} 27 | docker push asyncapi/server-api:latest 28 | 29 | - uses: meeDamian/sync-readme@82715041300710d9be7c726c9d6c683b70451087 #version 1.0.6 https://github.com/meeDamian/sync-readme/releases/tag/v1.0.6 30 | with: 31 | user: ${{secrets.DOCKER_USERNAME}} 32 | pass: ${{ secrets.DOCKER_PASSWORD }} 33 | slug: asyncapi/server-api 34 | description: Server API providing official AsyncAPI tools 35 | 36 | deploy-app: 37 | name: Deploy to DigitalOcean App 38 | needs: publish-docker 39 | runs-on: ubuntu-latest 40 | steps: 41 | - name: Deploy to DigitalOcean App 42 | uses: digitalocean/app_action@v1.1.5 43 | with: 44 | app_name: "server-api" 45 | token: ${{ secrets.DIGITALOCEAN_ACCESS_TOKEN }} 46 | images: '[{"name":"asyncapi-server-api","image":{"registry_type":"DOCKER_HUB","registry":"asyncapi","repository":"server-api","tag":"latest"}}]' 47 | -------------------------------------------------------------------------------- /.github/workflows/scripts/README.md: -------------------------------------------------------------------------------- 1 | The entire `scripts` directory is centrally managed in [.github](https://github.com/asyncapi/.github/) repository. Any changes in this folder should be done in central repository. -------------------------------------------------------------------------------- /.github/workflows/scripts/mailchimp/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This code is centrally managed in https://github.com/asyncapi/.github/ 3 | * Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 4 | */ 5 | const mailchimp = require('@mailchimp/mailchimp_marketing'); 6 | const core = require('@actions/core'); 7 | const htmlContent = require('./htmlContent.js'); 8 | 9 | /** 10 | * Sending API request to mailchimp to schedule email to subscribers 11 | * Input is the URL to issue/discussion or other resource 12 | */ 13 | module.exports = async (link, title) => { 14 | 15 | let newCampaign; 16 | 17 | mailchimp.setConfig({ 18 | apiKey: process.env.MAILCHIMP_API_KEY, 19 | server: 'us12' 20 | }); 21 | 22 | /* 23 | * First we create campaign 24 | */ 25 | try { 26 | newCampaign = await mailchimp.campaigns.create({ 27 | type: 'regular', 28 | recipients: { 29 | list_id: '6e3e437abe', 30 | segment_opts: { 31 | match: 'any', 32 | conditions: [{ 33 | condition_type: 'Interests', 34 | field: 'interests-2801e38b9f', 35 | op: 'interestcontains', 36 | value: ['f7204f9b90'] 37 | }] 38 | } 39 | }, 40 | settings: { 41 | subject_line: `TSC attention required: ${ title }`, 42 | preview_text: 'Check out the latest topic that TSC members have to be aware of', 43 | title: `New topic info - ${ new Date(Date.now()).toUTCString()}`, 44 | from_name: 'AsyncAPI Initiative', 45 | reply_to: 'info@asyncapi.io', 46 | } 47 | }); 48 | } catch (error) { 49 | return core.setFailed(`Failed creating campaign: ${ JSON.stringify(error) }`); 50 | } 51 | 52 | /* 53 | * Content of the email is added separately after campaign creation 54 | */ 55 | try { 56 | await mailchimp.campaigns.setContent(newCampaign.id, { html: htmlContent(link, title) }); 57 | } catch (error) { 58 | return core.setFailed(`Failed adding content to campaign: ${ JSON.stringify(error) }`); 59 | } 60 | 61 | /* 62 | * We schedule an email to send it immediately 63 | */ 64 | try { 65 | //schedule for next hour 66 | //so if this code was created by new issue creation at 9:46, the email is scheduled for 10:00 67 | //is it like this as schedule has limitiations and you cannot schedule email for 9:48 68 | const scheduleDate = new Date(Date.parse(new Date(Date.now()).toISOString()) + 1 * 1 * 60 * 60 * 1000); 69 | scheduleDate.setUTCMinutes(00); 70 | 71 | await mailchimp.campaigns.schedule(newCampaign.id, { 72 | schedule_time: scheduleDate.toISOString(), 73 | }); 74 | } catch (error) { 75 | return core.setFailed(`Failed scheduling email: ${ JSON.stringify(error) }`); 76 | } 77 | 78 | core.info(`New email campaign created`); 79 | } -------------------------------------------------------------------------------- /.github/workflows/scripts/mailchimp/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "schedule-email", 3 | "description": "This code is responsible for scheduling an email campaign. This file is centrally managed in https://github.com/asyncapi/.github/", 4 | "license": "Apache 2.0", 5 | "dependencies": { 6 | "@actions/core": "1.6.0", 7 | "@mailchimp/mailchimp_marketing": "3.0.74" 8 | } 9 | } -------------------------------------------------------------------------------- /.github/workflows/stale-issues-prs.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | name: Manage stale issues and PRs 5 | 6 | on: 7 | schedule: 8 | - cron: "0 0 * * *" 9 | 10 | jobs: 11 | stale: 12 | if: startsWith(github.repository, 'asyncapi/') 13 | name: Mark issue or PR as stale 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/stale@5bef64f19d7facfb25b37b414482c7164d639639 #v9.1.0 but pointing to commit for security reasons 17 | with: 18 | repo-token: ${{ secrets.GITHUB_TOKEN }} 19 | stale-issue-message: | 20 | This issue has been automatically marked as stale because it has not had recent activity :sleeping: 21 | 22 | It will be closed in 120 days if no further activity occurs. To unstale this issue, add a comment with a detailed explanation. 23 | 24 | There can be many reasons why some specific issue has no activity. The most probable cause is lack of time, not lack of interest. AsyncAPI Initiative is a Linux Foundation project not owned by a single for-profit company. It is a community-driven initiative ruled under [open governance model](https://github.com/asyncapi/community/blob/master/CHARTER.md). 25 | 26 | Let us figure out together how to push this issue forward. Connect with us through [one of many communication channels](https://github.com/asyncapi/community/issues/1) we established here. 27 | 28 | Thank you for your patience :heart: 29 | stale-pr-message: | 30 | This pull request has been automatically marked as stale because it has not had recent activity :sleeping: 31 | 32 | It will be closed in 120 days if no further activity occurs. To unstale this pull request, add a comment with detailed explanation. 33 | 34 | There can be many reasons why some specific pull request has no activity. The most probable cause is lack of time, not lack of interest. AsyncAPI Initiative is a Linux Foundation project not owned by a single for-profit company. It is a community-driven initiative ruled under [open governance model](https://github.com/asyncapi/community/blob/master/CHARTER.md). 35 | 36 | Let us figure out together how to push this pull request forward. Connect with us through [one of many communication channels](https://github.com/asyncapi/community/issues/1) we established here. 37 | 38 | Thank you for your patience :heart: 39 | days-before-stale: 120 40 | days-before-close: 120 41 | stale-issue-label: stale 42 | stale-pr-label: stale 43 | exempt-issue-labels: keep-open 44 | exempt-pr-labels: keep-open 45 | close-issue-reason: not_planned 46 | -------------------------------------------------------------------------------- /.github/workflows/transfer-issue.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | name: Transfer Issues between repositories 5 | 6 | on: 7 | issue_comment: 8 | types: 9 | - created 10 | 11 | permissions: 12 | issues: write 13 | 14 | jobs: 15 | transfer: 16 | if: ${{(!github.event.issue.pull_request && github.event.issue.state != 'closed' && github.actor != 'asyncapi-bot') && (startsWith(github.event.comment.body, '/transfer-issue') || startsWith(github.event.comment.body, '/ti'))}} 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: Checkout Repository 20 | uses: actions/checkout@v4 21 | - name: Extract Input 22 | id: extract_step 23 | env: 24 | COMMENT: "${{ github.event.comment.body }}" 25 | run: | 26 | REPO=$(echo $COMMENT | awk '{print $2}') 27 | echo repo=$REPO >> $GITHUB_OUTPUT 28 | - name: Check Repo 29 | uses: actions/github-script@v7 30 | with: 31 | github-token: ${{secrets.GH_TOKEN}} 32 | script: | 33 | const r = "${{github.repository}}" 34 | const [owner, repo] = r.split('/') 35 | const repoToMove = process.env.REPO_TO_MOVE 36 | const issue_number = context.issue.number 37 | try { 38 | const {data} = await github.rest.repos.get({ 39 | owner, 40 | repo: repoToMove 41 | }) 42 | }catch (e) { 43 | const body = `${repoToMove} is not a repo under ${owner}. You can only transfer issue to repos that belong to the same organization.` 44 | await github.rest.issues.createComment({ 45 | owner, 46 | repo, 47 | issue_number, 48 | body 49 | }) 50 | process.exit(1) 51 | } 52 | env: 53 | REPO_TO_MOVE: ${{steps.extract_step.outputs.repo}} 54 | - name: Transfer Issue 55 | id: transferIssue 56 | working-directory: ./ 57 | run: | 58 | gh issue transfer ${{github.event.issue.number}} asyncapi/${{steps.extract_step.outputs.repo}} 59 | env: 60 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 61 | 62 | -------------------------------------------------------------------------------- /.github/workflows/update-maintainers-trigger.yaml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | name: Trigger MAINTAINERS.yaml file update 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | paths: 10 | # Check all valid CODEOWNERS locations: 11 | # https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners#codeowners-file-location 12 | - 'CODEOWNERS' 13 | - '.github/CODEOWNERS' 14 | - '.docs/CODEOWNERS' 15 | 16 | jobs: 17 | trigger-maintainers-update: 18 | name: Trigger updating MAINTAINERS.yaml because of CODEOWNERS change 19 | runs-on: ubuntu-latest 20 | 21 | steps: 22 | - name: Repository Dispatch 23 | uses: peter-evans/repository-dispatch@ff45666b9427631e3450c54a1bcbee4d9ff4d7c0 # https://github.com/peter-evans/repository-dispatch/releases/tag/v3.0.0 24 | with: 25 | # The PAT with the 'public_repo' scope is required 26 | token: ${{ secrets.GH_TOKEN }} 27 | repository: ${{ github.repository_owner }}/community 28 | event-type: trigger-maintainers-update 29 | -------------------------------------------------------------------------------- /.github/workflows/update-pr.yml: -------------------------------------------------------------------------------- 1 | # This workflow is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # This workflow will run on every comment with /update or /u. And will create merge-commits for the PR. 5 | # This also works with forks, not only with branches in the same repository/organization. 6 | # Currently, does not work with forks in different organizations. 7 | 8 | # This workflow will be distributed to all repositories in the AsyncAPI organization 9 | 10 | name: Update PR branches from fork 11 | 12 | on: 13 | issue_comment: 14 | types: [created] 15 | 16 | jobs: 17 | update-pr: 18 | if: > 19 | startsWith(github.repository, 'asyncapi/') && 20 | github.event.issue.pull_request && 21 | github.event.issue.state != 'closed' && ( 22 | contains(github.event.comment.body, '/update') || 23 | contains(github.event.comment.body, '/u') 24 | ) 25 | runs-on: ubuntu-latest 26 | steps: 27 | - name: Get Pull Request Details 28 | id: pr 29 | uses: actions/github-script@v7 30 | with: 31 | github-token: ${{ secrets.GH_TOKEN || secrets.GITHUB_TOKEN }} 32 | previews: 'merge-info-preview' # https://docs.github.com/en/graphql/overview/schema-previews#merge-info-preview-more-detailed-information-about-a-pull-requests-merge-state-preview 33 | script: | 34 | const prNumber = context.payload.issue.number; 35 | core.debug(`PR Number: ${prNumber}`); 36 | const { data: pr } = await github.rest.pulls.get({ 37 | owner: context.repo.owner, 38 | repo: context.repo.repo, 39 | pull_number: prNumber 40 | }); 41 | 42 | // If the PR has conflicts, we don't want to update it 43 | const updateable = ['behind', 'blocked', 'unknown', 'draft', 'clean'].includes(pr.mergeable_state); 44 | console.log(`PR #${prNumber} is ${pr.mergeable_state} and is ${updateable ? 'updateable' : 'not updateable'}`); 45 | core.setOutput('updateable', updateable); 46 | 47 | core.debug(`Updating PR #${prNumber} with head ${pr.head.sha}`); 48 | 49 | return { 50 | id: pr.node_id, 51 | number: prNumber, 52 | head: pr.head.sha, 53 | } 54 | - name: Update the Pull Request 55 | if: steps.pr.outputs.updateable == 'true' 56 | uses: actions/github-script@v7 57 | with: 58 | github-token: ${{ secrets.GH_TOKEN || secrets.GITHUB_TOKEN }} 59 | script: | 60 | const mutation = `mutation update($input: UpdatePullRequestBranchInput!) { 61 | updatePullRequestBranch(input: $input) { 62 | pullRequest { 63 | mergeable 64 | } 65 | } 66 | }`; 67 | 68 | const pr_details = ${{ steps.pr.outputs.result }}; 69 | 70 | try { 71 | const { data } = await github.graphql(mutation, { 72 | input: { 73 | pullRequestId: pr_details.id, 74 | expectedHeadOid: pr_details.head, 75 | } 76 | }); 77 | } catch (GraphQLError) { 78 | core.debug(GraphQLError); 79 | if ( 80 | GraphQLError.name === 'GraphqlResponseError' && 81 | GraphQLError.errors.some( 82 | error => error.type === 'FORBIDDEN' || error.type === 'UNAUTHORIZED' 83 | ) 84 | ) { 85 | // Add comment to PR if the bot doesn't have permissions to update the PR 86 | const comment = `Hi @${context.actor}. Update of PR has failed. It can be due to one of the following reasons: 87 | - I don't have permissions to update this PR. To update your fork with upstream using bot you need to enable [Allow edits from maintainers](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/allowing-changes-to-a-pull-request-branch-created-from-a-fork) option in the PR. 88 | - The fork is located in an organization, not under your personal profile. No solution for that. You are on your own with manual update. 89 | - There may be a conflict in the PR. Please resolve the conflict and try again.`; 90 | 91 | await github.rest.issues.createComment({ 92 | owner: context.repo.owner, 93 | repo: context.repo.repo, 94 | issue_number: context.issue.number, 95 | body: comment 96 | }); 97 | 98 | core.setFailed('Bot does not have permissions to update the PR'); 99 | } else { 100 | core.setFailed(GraphQLError.message); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /.github/workflows/welcome-first-time-contrib.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | name: Welcome first time contributors 5 | 6 | on: 7 | pull_request_target: 8 | types: 9 | - opened 10 | issues: 11 | types: 12 | - opened 13 | 14 | jobs: 15 | welcome: 16 | name: Post welcome message 17 | if: ${{ !contains(fromJson('["asyncapi-bot", "dependabot[bot]", "dependabot-preview[bot]", "allcontributors[bot]"]'), github.actor) }} 18 | runs-on: ubuntu-latest 19 | steps: 20 | - uses: actions/github-script@v7 21 | with: 22 | github-token: ${{ secrets.GITHUB_TOKEN }} 23 | script: | 24 | const issueMessage = `Welcome to AsyncAPI. Thanks a lot for reporting your first issue. Please check out our [contributors guide](https://github.com/asyncapi/community/blob/master/CONTRIBUTING.md) and the instructions about a [basic recommended setup](https://github.com/asyncapi/community/blob/master/git-workflow.md) useful for opening a pull request.
Keep in mind there are also other channels you can use to interact with AsyncAPI community. For more details check out [this issue](https://github.com/asyncapi/asyncapi/issues/115).`; 25 | const prMessage = `Welcome to AsyncAPI. Thanks a lot for creating your first pull request. Please check out our [contributors guide](https://github.com/asyncapi/community/blob/master/CONTRIBUTING.md) useful for opening a pull request.
Keep in mind there are also other channels you can use to interact with AsyncAPI community. For more details check out [this issue](https://github.com/asyncapi/asyncapi/issues/115).`; 26 | if (!issueMessage && !prMessage) { 27 | throw new Error('Action must have at least one of issue-message or pr-message set'); 28 | } 29 | const isIssue = !!context.payload.issue; 30 | let isFirstContribution; 31 | if (isIssue) { 32 | const query = `query($owner:String!, $name:String!, $contributer:String!) { 33 | repository(owner:$owner, name:$name){ 34 | issues(first: 1, filterBy: {createdBy:$contributer}){ 35 | totalCount 36 | } 37 | } 38 | }`; 39 | const variables = { 40 | owner: context.repo.owner, 41 | name: context.repo.repo, 42 | contributer: context.payload.sender.login 43 | }; 44 | const { repository: { issues: { totalCount } } } = await github.graphql(query, variables); 45 | isFirstContribution = totalCount === 1; 46 | } else { 47 | const query = `query($qstr: String!) { 48 | search(query: $qstr, type: ISSUE, first: 1) { 49 | issueCount 50 | } 51 | }`; 52 | const variables = { 53 | "qstr": `repo:${context.repo.owner}/${context.repo.repo} type:pr author:${context.payload.sender.login}`, 54 | }; 55 | const { search: { issueCount } } = await github.graphql(query, variables); 56 | isFirstContribution = issueCount === 1; 57 | } 58 | 59 | if (!isFirstContribution) { 60 | console.log(`Not the users first contribution.`); 61 | return; 62 | } 63 | const message = isIssue ? issueMessage : prMessage; 64 | // Add a comment to the appropriate place 65 | if (isIssue) { 66 | const issueNumber = context.payload.issue.number; 67 | console.log(`Adding message: ${message} to issue #${issueNumber}`); 68 | await github.rest.issues.createComment({ 69 | owner: context.payload.repository.owner.login, 70 | repo: context.payload.repository.name, 71 | issue_number: issueNumber, 72 | body: message 73 | }); 74 | } 75 | else { 76 | const pullNumber = context.payload.pull_request.number; 77 | console.log(`Adding message: ${message} to pull request #${pullNumber}`); 78 | await github.rest.pulls.createReview({ 79 | owner: context.payload.repository.owner.login, 80 | repo: context.payload.repository.name, 81 | pull_number: pullNumber, 82 | body: message, 83 | event: 'COMMENT' 84 | }); 85 | } 86 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .vscode 3 | coverage 4 | lib 5 | dist 6 | examples 7 | logs 8 | *.DS_Store -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | access=public -------------------------------------------------------------------------------- /.releaserc: -------------------------------------------------------------------------------- 1 | --- 2 | branches: 3 | - master 4 | # by default release workflow reacts on push not only to master. 5 | #This is why out of the box sematic release is configured for all these branches 6 | - name: next-spec 7 | prerelease: true 8 | - name: next-major 9 | prerelease: true 10 | - name: next-major-spec 11 | prerelease: true 12 | - name: beta 13 | prerelease: true 14 | - name: alpha 15 | prerelease: true 16 | - name: next 17 | prerelease: true 18 | plugins: 19 | - - "@semantic-release/commit-analyzer" 20 | - preset: conventionalcommits 21 | - - "@semantic-release/release-notes-generator" 22 | - preset: conventionalcommits 23 | - "@semantic-release/npm" 24 | - "@semantic-release/github" 25 | -------------------------------------------------------------------------------- /.sonarcloud.properties: -------------------------------------------------------------------------------- 1 | # Disable duplicate code in tests since it would introduce more complexity to reduce it. 2 | sonar.cpd.exclusions=**/*.test.ts,**/*.spec.ts -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | # This file provides an overview of code owners in this repository. 2 | 3 | # Each line is a file pattern followed by one or more owners. 4 | # The last matching pattern has the most precedence. 5 | # For more details, read the following article on GitHub: https://help.github.com/articles/about-codeowners/. 6 | 7 | # The default owners are automatically added as reviewers when you open a pull request unless different owners are specified in the file. 8 | 9 | * @smoya @BOLT04 @magicmatatjahu @asyncapi-bot-eve 10 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | - Using welcoming and inclusive language 12 | - Being respectful of differing viewpoints and experiences 13 | - Gracefully accepting constructive criticism 14 | - Focusing on what is best for the community 15 | - Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | - The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | - Trolling, insulting/derogatory comments, and personal or political attacks 21 | - Public or private harassment 22 | - Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | - Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at fmvilas@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to AsyncAPI 2 | We love your input! We want to make contributing to this project as easy and transparent as possible. 3 | 4 | ## Contribution recogniton 5 | 6 | We use [All Contributors](https://allcontributors.org/docs/en/specification) specification to handle recognitions. For more details read [this](https://github.com/asyncapi/community/blob/master/recognize-contributors.md) document. 7 | 8 | ## Summary of the contribution flow 9 | 10 | The following is a summary of the ideal contribution flow. Please, note that Pull Requests can also be rejected by the maintainers when appropriate. 11 | 12 | ``` 13 | ┌───────────────────────┐ 14 | │ │ 15 | │ Open an issue │ 16 | │ (a bug report or a │ 17 | │ feature request) │ 18 | │ │ 19 | └───────────────────────┘ 20 | ⇩ 21 | ┌───────────────────────┐ 22 | │ │ 23 | │ Open a Pull Request │ 24 | │ (only after issue │ 25 | │ is approved) │ 26 | │ │ 27 | └───────────────────────┘ 28 | ⇩ 29 | ┌───────────────────────┐ 30 | │ │ 31 | │ Your changes will │ 32 | │ be merged and │ 33 | │ published on the next │ 34 | │ release │ 35 | │ │ 36 | └───────────────────────┘ 37 | ``` 38 | 39 | ## Code of Conduct 40 | AsyncAPI has adopted a Code of Conduct that we expect project participants to adhere to. Please [read the full text](./CODE_OF_CONDUCT.md) so that you can understand what sort of behaviour is expected. 41 | 42 | ## Our Development Process 43 | We use Github to host code, to track issues and feature requests, as well as accept pull requests. 44 | 45 | ## Issues 46 | [Open an issue](https://github.com/asyncapi/asyncapi/issues/new) **only** if you want to report a bug or a feature. Don't open issues for questions or support, instead join our [Slack workspace](https://www.asyncapi.com/slack-invite) and ask there. Don't forget to follow our [Slack Etiquette](https://github.com/asyncapi/community/blob/master/slack-etiquette.md) while interacting with community members! It's more likely you'll get help, and much faster! 47 | 48 | ## Bug Reports and Feature Requests 49 | 50 | Please use our issues templates that provide you with hints on what information we need from you to help you out. 51 | 52 | ## Pull Requests 53 | 54 | **Please, make sure you open an issue before starting with a Pull Request, unless it's a typo or a really obvious error.** Pull requests are the best way to propose changes to the specification. Get familiar with our document that explains [Git workflow](https://github.com/asyncapi/community/blob/master/git-workflow.md) used in our repositories. 55 | 56 | ## Conventional commits 57 | 58 | Our repositories follow [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/#summary) specification. Releasing to GitHub and NPM is done with the support of [semantic-release](https://semantic-release.gitbook.io/semantic-release/). 59 | 60 | Pull requests should have a title that follows the specification, otherwise, merging is blocked. If you are not familiar with the specification simply ask maintainers to modify. You can also use this cheatsheet if you want: 61 | 62 | - `fix: ` prefix in the title indicates that PR is a bug fix and PATCH release must be triggered. 63 | - `feat: ` prefix in the title indicates that PR is a feature and MINOR release must be triggered. 64 | - `docs: ` prefix in the title indicates that PR is only related to the documentation and there is no need to trigger release. 65 | - `chore: ` prefix in the title indicates that PR is only related to cleanup in the project and there is no need to trigger release. 66 | - `test: ` prefix in the title indicates that PR is only related to tests and there is no need to trigger release. 67 | - `refactor: ` prefix in the title indicates that PR is only related to refactoring and there is no need to trigger release. 68 | 69 | What about MAJOR release? just add `!` to the prefix, like `fix!: ` or `refactor!: ` 70 | 71 | Prefix that follows specification is not enough though. Remember that the title must be clear and descriptive with usage of [imperative mood](https://chris.beams.io/posts/git-commit/#imperative). 72 | 73 | Happy contributing :heart: 74 | 75 | ## License 76 | When you submit changes, your submissions are understood to be under the same [Apache 2.0 License](https://github.com/asyncapi/asyncapi/blob/master/LICENSE) that covers the project. Feel free to [contact the maintainers](https://www.asyncapi.com/slack-invite) if that's a concern. 77 | 78 | ## References 79 | This document was adapted from the open-source contribution guidelines for [Facebook's Draft](https://github.com/facebook/draft-js/blob/master/CONTRIBUTING.md). -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # ---- Base Alpine with installed Node ---- 2 | FROM node:14-alpine3.14 AS base 3 | 4 | # install node 5 | RUN apk add --update \ 6 | nghttp2 7 | 8 | # ---- Install dependencies ---- 9 | FROM base AS build 10 | 11 | WORKDIR /app 12 | COPY . . 13 | 14 | # install dependencies 15 | # remove package-lock.json with lockVersion: 1 due to problem described in the https://github.com/asyncapi/.github/issues/123 16 | # remove first run and switch to the `npm ci` when mentioned issue will be resolved 17 | RUN rm package-lock.json; npm install 18 | 19 | # build to a production Javascript 20 | RUN npm run build:prod 21 | 22 | # ---- Serve ---- 23 | FROM base AS release 24 | 25 | WORKDIR /app 26 | COPY --from=build /app/dist ./dist 27 | # A wildcard is used to ensure both package.json AND package-lock.json are copied 28 | COPY --from=build /app/package* ./ 29 | # install only production dependencies (defined in "dependencies") 30 | RUN npm ci --only=production 31 | # copy OpenaAPI document 32 | COPY openapi.yaml ./ 33 | 34 | EXPOSE 80 35 | CMD ["npm", "run", "start:docker"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright The Linux Foundation 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![AsyncAPI Server API](./.github/assets/banner.png)](https://www.asyncapi.com) 2 | 3 | Server API providing official AsyncAPI tools. 4 | 5 | 6 | [![All Contributors](https://img.shields.io/badge/all_contributors-6-orange.svg?style=flat-square)](#contributors-) 7 | 8 | 9 | --- 10 | 11 | ## :loudspeaker: ATTENTION: 12 | 13 | This package is still under development and has not published and reached version 1.0.0 yet. This means that its API may contain breaking changes until we're able to deploy the first stable version and begin semantic versioning. 14 | 15 | --- 16 | 17 | 18 | 19 | 20 | 21 | - [Requirements](#requirements) 22 | - [Using it locally](#using-it-locally) 23 | - [Using it via Docker](#using-it-via-docker) 24 | - [Development](#development) 25 | - [Deployment](#deployment) 26 | * [How the GitHub workflow works](#how-the-github-workflow-works) 27 | - [Contribution](#contribution) 28 | - [Supported by](#supported-by) 29 | - [Contributors](#contributors) 30 | 31 | 32 | 33 | ## Requirements 34 | 35 | - [NodeJS](https://nodejs.org/en/) >= 14 36 | 37 | ## Using it locally 38 | 39 | Run: 40 | 41 | ```bash 42 | npm install 43 | npm run start:prod 44 | ``` 45 | 46 | server is ready to use on [http://localhost:80](http://localhost:80). 47 | 48 | ## Using it via Docker 49 | 50 | Run: 51 | 52 | ```bash 53 | docker run -it -p 80:80 asyncapi/server-api 54 | ``` 55 | 56 | server is ready to use on [http://localhost:80](http://localhost:80). 57 | 58 | ## Development 59 | 60 | 1. Setup project by installing dependencies `npm install` 61 | 2. Write code and tests. 62 | 3. Make sure all tests pass `npm test` 63 | 64 | ## Deployment 65 | 66 | This project is deployed to [DigitalOcean App Platform](https://www.digitalocean.com/products/app-platform/) using [Terraform](https://www.terraform.io/) and [GitHub Actions](https://www.github.com/digitalocean/app_action/). To deploy it to your own account, follow these steps: 67 | 68 | 1. Fork this repository. 69 | 2. Create a [DigitalOcean Personal Access Token](https://cloud.digitalocean.com/account/api/tokens) with `read` and `write` permissions. For more information, see [DigitalOcean's documentation](https://docs.digitalocean.com/reference/api/create-personal-access-token/). 70 | 3. Run `terraform init` to initialize the Terraform project as can be seen [here](./deployments/apps/main.tf). This should be run being located at ./deployments/apps directory preferably. 71 | 4. Run `terraform apply` to create the necessary infrastructure. 72 | 73 | > [!NOTE] 74 | > You need to export the following environment variables before running `terraform apply`: 75 | > - `DIGITALOCEAN_ACCESS_TOKEN`: Your DigitalOcean Personal Access Token. 76 | 77 | 78 | ### How the GitHub workflow works 79 | 80 | The [GitHub workflow](./.github/workflows/release-docker.yml) is triggered when a new tag is pushed to the repository. It will build a new Docker image and push it to the [Docker Hub](https://hub.docker.com/r/asyncapi/server-api) repository. Then the [DigitalOcean App Platform GitHub Action](https://www.github.com/digitalocean/app_action/) updates the application with the new image. 81 | 82 | ## Contribution 83 | 84 | Read [CONTRIBUTING](https://github.com/asyncapi/.github/blob/master/CONTRIBUTING.md) guide. 85 | 86 | ## Supported by 87 | 88 |

89 | 90 | 91 | 92 |

93 | 94 | ## Contributors 95 | 96 | Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 |
Maciej Urbańczyk
Maciej Urbańczyk

🚧 💻 📖 🐛 🤔 👀 ⚠️ 🚇 🧑‍🏫
David Pereira
David Pereira

🚧 💻 📖 🐛 🤔 👀 ⚠️ 🚇 🧑‍🏫
Sergio Moya
Sergio Moya

🚧 💻 📖 🐛 🤔 👀 ⚠️ 🚇 🧑‍🏫
Ritik Rawal
Ritik Rawal

💻 📖
Everly Precia Suresh
Everly Precia Suresh

💻 📖
Ashish Padhy
Ashish Padhy

📖 🚇
113 | 114 | 115 | 116 | 117 | 118 | 119 | This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! 120 | -------------------------------------------------------------------------------- /deployments/apps/.gitignore: -------------------------------------------------------------------------------- 1 | .terraform 2 | terraform.tfstate 3 | terraform.tfstate.backup 4 | -------------------------------------------------------------------------------- /deployments/apps/.terraform.lock.hcl: -------------------------------------------------------------------------------- 1 | # This file is maintained automatically by "terraform init". 2 | # Manual edits may be lost in future updates. 3 | 4 | provider "registry.terraform.io/digitalocean/digitalocean" { 5 | version = "2.34.1" 6 | constraints = ">= 2.0.0" 7 | hashes = [ 8 | "h1:iRyhFUfKnDRWx75+alSOEtdS0BtNUkrvLusC15s34eo=", 9 | "zh:022d4c97af3d022d4e3735a81c6a7297aa43c3b28a8cecaa0ff58273a5677e2e", 10 | "zh:1922f86d5710707eb497fbebcb1a1c5584c843a7e95c3900d750d81bd2785204", 11 | "zh:1b7ab7c67a26c399eb5aa8a7a695cb59279c6a1a562ead3064e4a6b17cdacabe", 12 | "zh:1dc666faa2ec0efc32329b4c8ff79813b54741ef1741bc42d90513e5ba904048", 13 | "zh:220dec61ffd9448a91cca92f2bc6642df10db57b25d3d27036c3a370e9870cb7", 14 | "zh:262301545057e654bd6193dc04b01666531fccfcf722f730827695098d93afa7", 15 | "zh:63677684a14e6b7790833982d203fb2f84b105ad6b9b490b3a4ecc7043cdba81", 16 | "zh:67a2932227623073aa9431a12916b52ce1ccddb96f9a2d6cdae2aaf7558ccbf8", 17 | "zh:70dfc6ac33ee140dcb29a971df7eeb15117741b5a75b9f8486c5468c9dd28f24", 18 | "zh:7e3b3b62754e86442048b4b1284e10807e3e58f417e1d59a4575dd29ac6ba518", 19 | "zh:7e6fe662b1e283ad498eb2549d0c2260b908ab5b848e05f84fa4acdca5b4d5ca", 20 | "zh:9c554170f20e659222896533a3a91954fb1d210eea60de05aea803b36d5ccd5d", 21 | "zh:ad2f64d758bd718eb39171f1c31219900fd2bfb552a14f6a90b18cfd178a74b4", 22 | "zh:cfce070000e95dfe56a901340ac256f9d2f84a73bf62391cba8a8e9bf1f857e0", 23 | "zh:d5ae30eccd53ca7314157e62d8ec53151697ed124e43b24b2d16c565054730c6", 24 | "zh:fbe5edf5337adb7360f9ffef57d02b397555b6a89bba68d1b60edfec6e23f02c", 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /deployments/apps/main.tf: -------------------------------------------------------------------------------- 1 | terraform { 2 | required_version = ">= 1.0.0" 3 | 4 | required_providers { 5 | digitalocean = { 6 | source = "digitalocean/digitalocean" 7 | version = ">= 2.0.0" 8 | } 9 | } 10 | } 11 | 12 | provider "digitalocean" {} 13 | 14 | resource "digitalocean_app" "server-api" { 15 | spec { 16 | name = "server-api" 17 | region = "sfo3" 18 | 19 | domain { 20 | name = "api.asyncapi.com" 21 | type = "PRIMARY" 22 | } 23 | 24 | ingress { 25 | rule { 26 | component { 27 | name = "asyncapi-server-api" 28 | } 29 | match { 30 | path { 31 | prefix = "/" 32 | } 33 | } 34 | cors { 35 | allow_origins { 36 | exact = "*" 37 | } 38 | allow_methods = ["GET", "POST", "PUT", "DELETE", "OPTIONS"] 39 | allow_headers = ["*"] 40 | } 41 | } 42 | } 43 | 44 | service { 45 | name = "asyncapi-server-api" 46 | http_port = 80 47 | health_check { 48 | http_path = "/v1/help/validate" 49 | port = 80 50 | } 51 | env { 52 | key = "PORT" 53 | value = "80" 54 | } 55 | 56 | image { 57 | registry_type = "DOCKER_HUB" 58 | registry = "asyncapi" 59 | repository = "server-api" 60 | tag = "latest" 61 | } 62 | 63 | instance_count = 1 64 | instance_size_slug = "basic-xs" // $10/month 65 | 66 | alert { 67 | rule = "CPU_UTILIZATION" 68 | value = 80 69 | operator = "GREATER_THAN" 70 | window = "TEN_MINUTES" 71 | } 72 | } 73 | 74 | alert { 75 | rule = "DEPLOYMENT_FAILED" 76 | } 77 | } 78 | } 79 | 80 | output "live_url" { 81 | value = digitalocean_app.server-api.default_ingress 82 | } 83 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | coverageReporters: ['json-summary', 'lcov', 'text'], 3 | collectCoverageFrom: ['src/**'], 4 | 5 | preset: 'ts-jest', 6 | testEnvironment: 'node', 7 | transform: { 8 | '^.+\\.tsx?$': 'ts-jest', 9 | '^.+\\.ts?$': 'ts-jest', 10 | }, 11 | 12 | // Test spec file resolution pattern 13 | // Matches parent folder `tests` or `__tests__` and filename 14 | // should contain `test` or `spec`. 15 | testMatch: ['**/__tests__/**/*.ts?(x)', '**/?(*.)+(spec|test).ts?(x)'], 16 | // Module file extensions for importing 17 | moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], 18 | 19 | testTimeout: 20000, 20 | 21 | setupFiles: ['./tests/jest.setup.ts'], 22 | globals: { 23 | 'ts-jest': { 24 | tsconfig: 'tsconfig.test.json', 25 | }, 26 | }, 27 | }; 28 | -------------------------------------------------------------------------------- /nodemon.json: -------------------------------------------------------------------------------- 1 | { 2 | "watch": [ 3 | "src", 4 | ".env" 5 | ], 6 | "ext": "js,ts,json", 7 | "ignore": [ 8 | "src/**/*.spec.ts", 9 | "src/**/*.test.ts" 10 | ], 11 | "exec": "ts-node --transpile-only src/server.ts" 12 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@asyncapi/server-api", 3 | "version": "0.16.22", 4 | "description": "Server API providing official AsyncAPI tools", 5 | "license": "Apache-2.0", 6 | "homepage": "https://github.com/asyncapi/server-api", 7 | "bugs": { 8 | "url": "https://github.com/asyncapi/server-api/issues" 9 | }, 10 | "engines": { 11 | "node": ">=14" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "git://github.com/asyncapi/server-api.git" 16 | }, 17 | "keywords": [ 18 | "server", 19 | "api", 20 | "asyncapi", 21 | "generator", 22 | "tooling" 23 | ], 24 | "author": { 25 | "name": "The AsyncAPI maintainers" 26 | }, 27 | "scripts": { 28 | "start:dev": "npm run build:dev && cross-env NODE_ENV=development node dist/server.js", 29 | "start:prod": "npm run build:prod && cross-env NODE_ENV=production node dist/server.js", 30 | "start:docker": "NODE_ENV=production node dist/server.js", 31 | "dev": "cross-env NODE_ENV=development nodemon", 32 | "build:dev": "tsc", 33 | "build:prod": "tsc", 34 | "test": "cross-env NODE_ENV=test jest", 35 | "lint": "eslint --max-warnings 0 --config .eslintrc .", 36 | "lint:fix": "eslint --max-warnings 0 --config .eslintrc . --fix", 37 | "generate:assets": "npm run generate:readme:toc", 38 | "generate:readme:toc": "markdown-toc -i README.md", 39 | "docker:build": "docker build --tag asyncapi/server-api .", 40 | "bump:version": "npm --no-git-tag-version --allow-same-version version $VERSION" 41 | }, 42 | "dependencies": { 43 | "@apidevtools/json-schema-ref-parser": "^10.1.0", 44 | "@asyncapi/avro-schema-parser": "^1.1.0", 45 | "@asyncapi/bundler": "^0.4.0", 46 | "@asyncapi/converter": "^1.4.17", 47 | "@asyncapi/diff": "^0.4.1", 48 | "@asyncapi/dotnet-nats-template": "^0.12.1", 49 | "@asyncapi/generator": "^1.9.18", 50 | "@asyncapi/go-watermill-template": "^0.2.74", 51 | "@asyncapi/html-template": "^0.28.4", 52 | "@asyncapi/java-spring-cloud-stream-template": "^0.13.4", 53 | "@asyncapi/java-spring-template": "^1.5.0", 54 | "@asyncapi/java-template": "^0.2.0", 55 | "@asyncapi/markdown-template": "^1.4.0", 56 | "@asyncapi/nodejs-template": "^2.0.1", 57 | "@asyncapi/nodejs-ws-template": "^0.9.33", 58 | "@asyncapi/openapi-schema-parser": "^2.0.3", 59 | "@asyncapi/parser": "^1.18.1", 60 | "@asyncapi/problem": "^1.0.0", 61 | "@asyncapi/python-paho-template": "^0.2.13", 62 | "@asyncapi/raml-dt-schema-parser": "^2.0.1", 63 | "@asyncapi/specs": "^4.2.1", 64 | "@asyncapi/ts-nats-template": "^0.10.3", 65 | "ajv": "^8.8.2", 66 | "ajv-formats": "^2.1.1", 67 | "archiver": "^5.3.0", 68 | "body-parser": "^1.19.0", 69 | "compression": "^1.7.4", 70 | "config": "^3.3.6", 71 | "cors": "^2.8.5", 72 | "express": "^4.17.1", 73 | "helmet": "^6.0.1", 74 | "js-yaml": "^4.1.0", 75 | "redoc-express": "^1.0.0", 76 | "types": "^0.1.1", 77 | "uuid": "^8.3.2", 78 | "winston": "^3.3.3" 79 | }, 80 | "devDependencies": { 81 | "@types/archiver": "^5.1.1", 82 | "@types/body-parser": "^1.19.1", 83 | "@types/compression": "^1.7.2", 84 | "@types/config": "0.0.40", 85 | "@types/cookie-parser": "^1.4.2", 86 | "@types/cors": "^2.8.12", 87 | "@types/express": "^4.17.13", 88 | "@types/jest": "^27.0.3", 89 | "@types/js-yaml": "^4.0.5", 90 | "@types/node": "^16.10.3", 91 | "@types/supertest": "^2.0.11", 92 | "@types/uuid": "^8.3.1", 93 | "@typescript-eslint/eslint-plugin": "^5.7.0", 94 | "@typescript-eslint/parser": "^5.7.0", 95 | "cross-env": "^7.0.3", 96 | "eslint": "^8.4.1", 97 | "eslint-plugin-security": "^1.4.0", 98 | "eslint-plugin-sonarjs": "^0.11.0", 99 | "jest": "^27.4.1", 100 | "markdown-toc": "^1.2.0", 101 | "nodemon": "^2.0.13", 102 | "supertest": "^6.1.6", 103 | "ts-jest": "^27.0.7", 104 | "ts-node": "^10.2.1", 105 | "typescript": "^4.4.3" 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/app.ts: -------------------------------------------------------------------------------- 1 | import bodyParser from 'body-parser'; 2 | import compression from 'compression'; 3 | import config from 'config'; 4 | import cors from 'cors'; 5 | import express from 'express'; 6 | import helmet from 'helmet'; 7 | 8 | import { Controller } from './interfaces'; 9 | 10 | import { problemMiddleware } from './middlewares/problem.middleware'; 11 | 12 | import { logger } from './utils/logger'; 13 | import { API_VERSION } from './constants'; 14 | 15 | export class App { 16 | private app: express.Application; 17 | private port: string | number; 18 | private env: string; 19 | 20 | constructor( 21 | private readonly controllers: Controller[] 22 | ) { 23 | this.app = express(); 24 | this.port = process.env.PORT || 80; 25 | this.env = process.env.NODE_ENV || 'development'; 26 | } 27 | 28 | public async init() { 29 | // initialize core middlewares 30 | await this.initializeMiddlewares(); 31 | // initialize controllers 32 | await this.initializeControllers(); 33 | // initialize error handling 34 | await this.initializeErrorHandling(); 35 | } 36 | 37 | public listen() { 38 | this.app.listen(this.port, () => { 39 | logger.info('================================='); 40 | logger.info(`= ENV: ${this.env}`); 41 | logger.info(`= 🚀 AsyncAPI Server API listening on the port ${this.port}`); 42 | logger.info('================================='); 43 | }); 44 | } 45 | 46 | public getServer() { 47 | return this.app; 48 | } 49 | 50 | private async initializeMiddlewares() { 51 | const requestBodyLimit = config.get('request.body.limit'); 52 | 53 | this.app.use(cors({ origin: config.get('cors.origin'), credentials: config.get('cors.credentials') })); 54 | this.app.use(compression()); 55 | this.app.use(bodyParser.text({ type: ['text/*'], limit: requestBodyLimit })); 56 | this.app.use(bodyParser.urlencoded({ extended: true, limit: requestBodyLimit })); 57 | this.app.use(bodyParser.json({ type: ['json', '*/json', '+json'], limit: requestBodyLimit })); 58 | this.app.use(helmet({ 59 | contentSecurityPolicy: { 60 | directives: { 61 | // for `/docs` path - we need to fetch redoc component from unpkg.com domain 62 | 'script-src': ['\'self\'', 'unpkg.com'], 63 | 'worker-src': ['\'self\' blob:'] 64 | }, 65 | }, 66 | // for `/docs` path 67 | crossOriginEmbedderPolicy: false, 68 | })); 69 | } 70 | 71 | private async initializeControllers() { 72 | for (const controller of this.controllers) { 73 | this.app.use(`/${API_VERSION}/`, await controller.boot()); 74 | } 75 | } 76 | 77 | private async initializeErrorHandling() { 78 | this.app.use(problemMiddleware); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/configs/development.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": "development", 3 | "log": { 4 | "format": "dev", 5 | "dir": "../logs" 6 | }, 7 | "cors": { 8 | "origin": true, 9 | "credentials": false 10 | }, 11 | "request": { 12 | "body": { 13 | "limit": "5mb" 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/configs/production.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": "production", 3 | "log": { 4 | "format": "combined", 5 | "dir": "../logs" 6 | }, 7 | "cors": { 8 | "origin": true, 9 | "credentials": false 10 | }, 11 | "request": { 12 | "body": { 13 | "limit": "5mb" 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /src/configs/test.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": "test", 3 | "log": { 4 | "format": "dev", 5 | "dir": "../logs" 6 | }, 7 | "cors": { 8 | "origin": true, 9 | "credentials": false 10 | }, 11 | "request": { 12 | "body": { 13 | "limit": "5mb" 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /src/constants.ts: -------------------------------------------------------------------------------- 1 | export const API_VERSION = 'v1'; -------------------------------------------------------------------------------- /src/controllers/bundle.controller.ts: -------------------------------------------------------------------------------- 1 | import { NextFunction, Request, Response, Router } from 'express'; 2 | import bundler from '@asyncapi/bundler'; 3 | 4 | import { validationMiddleware } from '../middlewares/validation.middleware'; 5 | 6 | import { ProblemException } from '../exceptions/problem.exception'; 7 | import { Controller } from '../interfaces'; 8 | 9 | export class BundleController implements Controller { 10 | public basepath = '/bundle'; 11 | 12 | private async bundle(req: Request, res: Response, next: NextFunction) { 13 | const asyncapis: Array = req.body.asyncapis; 14 | const base = req.body.base; 15 | 16 | try { 17 | const document = await bundler(asyncapis, { base }); 18 | const bundled = document.json(); 19 | res.status(200).json({ bundled }); 20 | } catch (err) { 21 | return next( 22 | new ProblemException({ 23 | type: 'internal-bundler-error', 24 | title: 'Internal Bundler error', 25 | status: 500, 26 | detail: (err as Error).message, 27 | }) 28 | ); 29 | } 30 | } 31 | 32 | public async boot(): Promise { 33 | const router = Router(); 34 | 35 | router.post( 36 | this.basepath, 37 | await validationMiddleware({ 38 | path: this.basepath, 39 | method: 'post', 40 | documents: ['asyncapis', 'base'], 41 | }), 42 | this.bundle.bind(this) 43 | ); 44 | 45 | return router; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/controllers/convert.controller.ts: -------------------------------------------------------------------------------- 1 | import { NextFunction, Request, Response, Router } from 'express'; 2 | 3 | import { Controller, AsyncAPIDocument, SpecsEnum } from '../interfaces'; 4 | 5 | import { validationMiddleware } from '../middlewares/validation.middleware'; 6 | 7 | import { ConvertService } from '../services/convert.service'; 8 | 9 | import { ProblemException } from '../exceptions/problem.exception'; 10 | 11 | type ConvertRequestDto = { 12 | asyncapi: AsyncAPIDocument; 13 | /** 14 | * Spec version to upgrade to. 15 | * Default is 'latest'. 16 | */ 17 | version?: SpecsEnum; 18 | /** 19 | * Language to convert the file to. 20 | */ 21 | language?: 'json' | 'yaml' | 'yml', 22 | } 23 | 24 | /** 25 | * Controller which exposes the Convert functionality 26 | */ 27 | export class ConvertController implements Controller { 28 | public basepath = '/convert'; 29 | 30 | private convertService = new ConvertService(); 31 | 32 | private async convert(req: Request, res: Response, next: NextFunction) { 33 | try { 34 | const { version, language, asyncapi } = req.body as ConvertRequestDto; 35 | const convertedSpec = await this.convertService.convert( 36 | asyncapi, 37 | version, 38 | language, 39 | ); 40 | 41 | res.status(200).json({ 42 | converted: convertedSpec 43 | }); 44 | } catch (err: unknown) { 45 | if (err instanceof ProblemException) { 46 | return next(err); 47 | } 48 | 49 | return next(new ProblemException({ 50 | type: 'internal-server-error', 51 | title: 'Internal server error', 52 | status: 500, 53 | detail: (err as Error).message, 54 | })); 55 | } 56 | } 57 | 58 | public async boot(): Promise { 59 | const router = Router(); 60 | 61 | router.post( 62 | this.basepath, 63 | await validationMiddleware({ 64 | path: this.basepath, 65 | method: 'post', 66 | documents: ['asyncapi'], 67 | }), 68 | this.convert.bind(this) 69 | ); 70 | 71 | return router; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/controllers/diff.controller.ts: -------------------------------------------------------------------------------- 1 | import { NextFunction, Request, Response, Router } from 'express'; 2 | import { diff } from '@asyncapi/diff'; 3 | 4 | import { validationMiddleware } from '../middlewares/validation.middleware'; 5 | 6 | import { ProblemException } from '../exceptions/problem.exception'; 7 | import { Controller } from '../interfaces'; 8 | 9 | export class DiffController implements Controller { 10 | public basepath = '/diff'; 11 | 12 | private async diff(req: Request, res: Response, next: NextFunction) { 13 | const { asyncapis } = req.body; 14 | 15 | try { 16 | const output = diff(asyncapis[0], asyncapis[1]).getOutput(); 17 | res.status(200).json({ diff: output }); 18 | } catch (err) { 19 | return next( 20 | new ProblemException({ 21 | type: 'internal-diff-error', 22 | title: 'Internal Diff error', 23 | status: 500, 24 | detail: (err as Error).message, 25 | }) 26 | ); 27 | } 28 | } 29 | 30 | public async boot(): Promise { 31 | const router = Router(); 32 | 33 | router.post( 34 | this.basepath, 35 | await validationMiddleware({ 36 | path: this.basepath, 37 | method: 'post', 38 | documents: ['asyncapis'], 39 | }), 40 | this.diff.bind(this) 41 | ); 42 | 43 | return router; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/controllers/docs.controller.ts: -------------------------------------------------------------------------------- 1 | import { Router } from 'express'; 2 | import redoc from 'redoc-express'; 3 | 4 | import { Controller } from '../interfaces'; 5 | 6 | import { API_VERSION } from '../constants'; 7 | 8 | export class DocsController implements Controller { 9 | public basepath = '/docs'; 10 | 11 | public boot(): Router { 12 | const router = Router(); 13 | 14 | router.get(`${this.basepath}/openapi.yaml`, (_, res) => { 15 | res.sendFile('openapi.yaml', { root: '.' }); 16 | }); 17 | 18 | router.get( 19 | this.basepath, 20 | redoc({ 21 | title: 'OpenAPI Documentation', 22 | specUrl: `/${API_VERSION}${this.basepath}/openapi.yaml` 23 | }), 24 | ); 25 | 26 | return router; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/controllers/generate.controller.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import path from 'path'; 3 | import { NextFunction, Request, Response, Router } from 'express'; 4 | import Ajv from 'ajv'; 5 | 6 | import { Controller } from '../interfaces'; 7 | 8 | import { validationMiddleware } from '../middlewares/validation.middleware'; 9 | 10 | import { ArchiverService } from '../services/archiver.service'; 11 | import { GeneratorService } from '../services/generator.service'; 12 | 13 | import { ProblemException } from '../exceptions/problem.exception'; 14 | import { prepareParserConfig } from '../utils/parser'; 15 | 16 | /** 17 | * Controller which exposes the Generator functionality 18 | */ 19 | export class GenerateController implements Controller { 20 | public basepath = '/generate'; 21 | 22 | private archiverService = new ArchiverService(); 23 | private generatorService = new GeneratorService(); 24 | private ajv: Ajv; 25 | 26 | private async generate(req: Request, res: Response, next: NextFunction) { 27 | try { 28 | await this.validateTemplateParameters(req); 29 | } catch (err) { 30 | return next(err); 31 | } 32 | 33 | const zip = this.archiverService.createZip(res); 34 | 35 | let tmpDir: string; 36 | try { 37 | tmpDir = await this.archiverService.createTempDirectory(); 38 | const { asyncapi, template, parameters } = req.body; 39 | 40 | try { 41 | await this.generatorService.generate( 42 | asyncapi, 43 | template, 44 | parameters, 45 | tmpDir, 46 | prepareParserConfig(req) 47 | ); 48 | } catch (genErr: unknown) { 49 | return next( 50 | new ProblemException({ 51 | type: 'internal-generator-error', 52 | title: 'Internal Generator error', 53 | status: 500, 54 | detail: (genErr as Error).message, 55 | }) 56 | ); 57 | } 58 | 59 | this.archiverService.appendDirectory(zip, tmpDir, 'template'); 60 | this.archiverService.appendAsyncAPIDocument(zip, asyncapi); 61 | 62 | res.status(200); 63 | return await this.archiverService.finalize(zip); 64 | } catch (err: unknown) { 65 | return next( 66 | new ProblemException({ 67 | type: 'internal-server-error', 68 | title: 'Internal server error', 69 | status: 500, 70 | detail: (err as Error).message, 71 | }) 72 | ); 73 | } finally { 74 | this.archiverService.removeTempDirectory(tmpDir); 75 | } 76 | } 77 | 78 | private async validateTemplateParameters(req: Request) { 79 | const { template, parameters } = req.body; 80 | 81 | const validate = await this.getAjvValidator(template); 82 | const valid = validate(parameters || {}); 83 | const errors = validate.errors && [...validate.errors]; 84 | 85 | if (valid === false) { 86 | throw new ProblemException({ 87 | type: 'invalid-template-parameters', 88 | title: 'Invalid Generator Template parameters', 89 | status: 422, 90 | validationErrors: errors as any, 91 | }); 92 | } 93 | } 94 | 95 | /** 96 | * Retrieve proper AJV's validator function, create or reuse it. 97 | */ 98 | public async getAjvValidator(templateName: string) { 99 | let validate = this.ajv.getSchema(templateName); 100 | if (!validate) { 101 | this.ajv.addSchema( 102 | await this.serializeTemplateParameters(templateName), 103 | templateName 104 | ); 105 | validate = this.ajv.getSchema(templateName); 106 | } 107 | return validate; 108 | } 109 | 110 | /** 111 | * Serialize template parameters. Read all parameters from template's package.json and create a proper JSON Schema for validating parameters. 112 | */ 113 | public async serializeTemplateParameters( 114 | templateName: string 115 | ): Promise { 116 | const pathToPackageJSON = path.join( 117 | __dirname, 118 | `../../node_modules/${templateName}/package.json` 119 | ); 120 | const packageJSONContent = await fs.promises.readFile( 121 | pathToPackageJSON, 122 | 'utf-8' 123 | ); 124 | const packageJSON = JSON.parse(packageJSONContent); 125 | if (!packageJSON) { 126 | return; 127 | } 128 | 129 | const generator = packageJSON.generator; 130 | if (!generator || !generator.parameters) { 131 | return; 132 | } 133 | 134 | const parameters = generator.parameters || {}; 135 | const required: string[] = []; 136 | for (const parameter in parameters) { 137 | // at the moment all parameters have to be passed to the Generator instance as string 138 | parameters[String(parameter)].type = 'string'; 139 | if (parameters[String(parameter)].required) { 140 | required.push(parameter); 141 | } 142 | delete parameters[String(parameter)].required; 143 | } 144 | 145 | return { 146 | $schema: 'http://json-schema.org/draft-07/schema#', 147 | type: 'object', 148 | properties: parameters, 149 | required, 150 | // don't allow non supported properties 151 | additionalProperties: false, 152 | }; 153 | } 154 | 155 | public async boot(): Promise { 156 | this.ajv = new Ajv({ 157 | inlineRefs: true, 158 | allErrors: true, 159 | schemaId: 'id', 160 | logger: false, 161 | }); 162 | const router = Router(); 163 | 164 | router.post( 165 | `${this.basepath}`, 166 | await validationMiddleware({ 167 | path: this.basepath, 168 | method: 'post', 169 | documents: ['asyncapi'], 170 | }), 171 | this.generate.bind(this) 172 | ); 173 | 174 | return router; 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /src/controllers/help.controller.ts: -------------------------------------------------------------------------------- 1 | import { Router, Request, Response, NextFunction } from 'express'; 2 | import { Controller } from '../interfaces'; 3 | import { ProblemException } from '../exceptions/problem.exception'; 4 | import { getAppOpenAPI } from '../utils/app-openapi'; 5 | 6 | const getCommandsFromRequest = (req: Request): string[] => { 7 | return req.params.command ? req.params.command.split('/').filter(cmd => cmd.trim()) : []; 8 | }; 9 | 10 | const isKeyValid = (key: string, obj: any): boolean => { 11 | return Object.keys(obj).includes(key); 12 | }; 13 | 14 | const getPathKeysMatchingCommands = (commands: string[], pathKeys: string[]): string | undefined => { 15 | if (!Array.isArray(pathKeys) || !pathKeys.every(key => typeof key === 'string')) { 16 | return undefined; 17 | } 18 | return pathKeys.find(pathKey => { 19 | const pathParts = pathKey.split('/').filter(part => part !== ''); 20 | return pathParts.every((pathPart, i) => { 21 | const command = commands[Number(i)]; 22 | return pathPart === command || pathPart.startsWith('{'); 23 | }); 24 | }); 25 | }; 26 | 27 | const getFullRequestBodySpec = (operationDetails: any) => { 28 | return isKeyValid('requestBody', operationDetails) ? operationDetails.requestBody.content['application/json'].schema : null; 29 | }; 30 | 31 | const buildResponseObject = (matchedPathKey: string, method: string, operationDetails: any, requestBodySchema: any) => { 32 | return { 33 | command: matchedPathKey, 34 | method: method.toUpperCase(), 35 | summary: operationDetails.summary || '', 36 | requestBody: requestBodySchema 37 | }; 38 | }; 39 | 40 | export class HelpController implements Controller { 41 | public basepath = '/help'; 42 | 43 | public async boot(): Promise { 44 | const router: Router = Router(); 45 | 46 | router.get('/help/:command*?', async (req: Request, res: Response, next: NextFunction) => { 47 | const commands = getCommandsFromRequest(req); 48 | let openapiSpec: any; 49 | 50 | try { 51 | openapiSpec = await getAppOpenAPI(); 52 | } catch (err) { 53 | return next(err); 54 | } 55 | 56 | if (commands.length === 0) { 57 | const routes = isKeyValid('paths', openapiSpec) ? Object.keys(openapiSpec.paths).map(path => ({ command: path.replace(/^\//, ''), url: `${this.basepath}${path}` })) : []; 58 | return res.json(routes); 59 | } 60 | 61 | const pathKeys = isKeyValid('paths', openapiSpec) ? Object.keys(openapiSpec.paths) : []; 62 | const matchedPathKey = getPathKeysMatchingCommands(commands, pathKeys); 63 | 64 | if (!matchedPathKey) { 65 | return next(new ProblemException({ 66 | type: 'invalid-asyncapi-command', 67 | title: 'Invalid AsyncAPI Command', 68 | status: 404, 69 | detail: 'The given AsyncAPI command is not valid.' 70 | })); 71 | } 72 | 73 | const pathInfo = isKeyValid(matchedPathKey, openapiSpec.paths) ? openapiSpec.paths[String(matchedPathKey)] : undefined; 74 | const method = commands.length > 1 ? 'get' : 'post'; 75 | const operationDetails = isKeyValid(method, pathInfo) ? pathInfo[String(method)] : undefined; 76 | if (!operationDetails) { 77 | return next(new ProblemException({ 78 | type: 'invalid-asyncapi-command', 79 | title: 'Invalid AsyncAPI Command', 80 | status: 404, 81 | detail: 'The given AsyncAPI command is not valid.' 82 | })); 83 | } 84 | 85 | const requestBodySchema = getFullRequestBodySpec(operationDetails); 86 | 87 | return res.json(buildResponseObject(matchedPathKey, method, operationDetails, requestBodySchema)); 88 | }); 89 | 90 | return router; 91 | } 92 | } -------------------------------------------------------------------------------- /src/controllers/parse.controller.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, Router } from 'express'; 2 | import { AsyncAPIDocument } from '@asyncapi/parser'; 3 | 4 | import { validationMiddleware } from '../middlewares/validation.middleware'; 5 | 6 | import { Controller} from '../interfaces'; 7 | 8 | /** 9 | * Controller which exposes the Parser functionality, to parse the AsyncAPI document. 10 | */ 11 | export class ParseController implements Controller { 12 | public basepath = '/parse'; 13 | 14 | private async parse(req: Request, res: Response) { 15 | const stringified = AsyncAPIDocument.stringify(req.asyncapi?.parsedDocument); 16 | res.status(200).json({ 17 | parsed: stringified, 18 | }); 19 | } 20 | 21 | public async boot(): Promise { 22 | const router = Router(); 23 | 24 | router.post( 25 | `${this.basepath}`, 26 | await validationMiddleware({ 27 | path: this.basepath, 28 | method: 'post', 29 | documents: ['asyncapi'], 30 | }), 31 | this.parse.bind(this) 32 | ); 33 | 34 | return router; 35 | } 36 | } -------------------------------------------------------------------------------- /src/controllers/tests/bundle.controller.test.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | 3 | import { App } from '../../app'; 4 | import { ProblemException } from '../../exceptions/problem.exception'; 5 | 6 | import { BundleController } from '../bundle.controller'; 7 | 8 | describe('BundleController', () => { 9 | describe('[POST] /bundle', () => { 10 | it('should bundle files', async () => { 11 | const app = new App([new BundleController()]); 12 | await app.init(); 13 | 14 | await request(app.getServer()) 15 | .post('/v1/bundle') 16 | .send({ 17 | asyncapis: [{ 18 | asyncapi: '2.2.0', 19 | info: { 20 | title: 'Test Service', 21 | version: '1.0.0', 22 | }, 23 | channels: { 24 | 'test-channel-2': { 25 | publish: { 26 | message: { 27 | payload: { 28 | type: 'object', 29 | }, 30 | }, 31 | } 32 | }, 33 | }, 34 | }], 35 | base: { 36 | asyncapi: '2.2.0', 37 | info: { 38 | title: 'Merged test service', 39 | version: '1.2.0', 40 | }, 41 | channels: { 42 | 'test-channel-1': { 43 | publish: { 44 | message: { 45 | payload: { 46 | type: 'object', 47 | }, 48 | }, 49 | } 50 | }, 51 | }, 52 | } 53 | }) 54 | .expect(200, { 55 | bundled: { 56 | asyncapi: '2.2.0', 57 | info: { title: 'Merged test service', version: '1.2.0' }, 58 | channels: { 59 | 'test-channel-1': { 60 | publish: { 61 | message: { 62 | payload: { 63 | type: 'object', 64 | }, 65 | }, 66 | } 67 | }, 68 | 'test-channel-2': { 69 | publish: { 70 | message: { 71 | payload: { 72 | type: 'object', 73 | }, 74 | }, 75 | } 76 | }, 77 | } 78 | } 79 | }); 80 | }); 81 | 82 | it('should throw error with invalid AsyncAPI document in the `base` list', async () => { 83 | const app = new App([new BundleController()]); 84 | await app.init(); 85 | 86 | await request(app.getServer()) 87 | .post('/v1/bundle') 88 | .send({ 89 | asyncapis: [{ 90 | asyncapi: '2.2.0', 91 | info: { 92 | title: 'Test Service', 93 | version: '1.0.0', 94 | }, 95 | channels: { 96 | 'test-channel-2': { 97 | publish: { 98 | message: { 99 | payload: { 100 | type: 'object', 101 | }, 102 | }, 103 | } 104 | }, 105 | }, 106 | }], 107 | base: { 108 | asyncapi: '2.2.0', 109 | info: { 110 | tite: 'My API', // spelled wrong on purpose to throw an error in the test 111 | version: '1.0.0' 112 | }, 113 | channels: {} 114 | } 115 | }) 116 | .expect(422, { 117 | type: ProblemException.createType('validation-errors'), 118 | title: 'There were errors validating the AsyncAPI document.', 119 | status: 422, 120 | validationErrors: [ 121 | { 122 | title: '/info should NOT have additional properties', 123 | location: { 124 | jsonPointer: '/info' 125 | } 126 | }, 127 | { 128 | title: '/info should have required property \'title\'', 129 | location: { 130 | jsonPointer: '/info' 131 | } 132 | } 133 | ], 134 | parsedJSON: { 135 | asyncapi: '2.2.0', 136 | info: { 137 | tite: 'My API', 138 | version: '1.0.0' 139 | }, 140 | channels: {} 141 | } 142 | }); 143 | }); 144 | 145 | it('should throw error with invalid AsyncAPI document in the `asyncapis` list', async () => { 146 | const app = new App([new BundleController()]); 147 | await app.init(); 148 | 149 | await request(app.getServer()) 150 | .post('/v1/bundle') 151 | .send({ 152 | asyncapis: [{ 153 | asyncapi: '2.2.0', 154 | info: { 155 | tite: 'My API', // spelled wrong on purpose to throw an error in the test 156 | version: '1.0.0' 157 | }, 158 | channels: {} 159 | }], 160 | base: { 161 | asyncapi: '2.2.0', 162 | info: { 163 | title: 'Merged test service', 164 | version: '1.2.0', 165 | }, 166 | channels: { 167 | 'test-channel-1': { 168 | publish: { 169 | message: { 170 | payload: { 171 | type: 'object', 172 | }, 173 | }, 174 | } 175 | }, 176 | }, 177 | } 178 | }) 179 | .expect(422, { 180 | type: ProblemException.createType('validation-errors'), 181 | title: 'There were errors validating the AsyncAPI document.', 182 | status: 422, 183 | validationErrors: [ 184 | { 185 | title: '/info should NOT have additional properties', 186 | location: { 187 | jsonPointer: '/info' 188 | } 189 | }, 190 | { 191 | title: '/info should have required property \'title\'', 192 | location: { 193 | jsonPointer: '/info' 194 | } 195 | } 196 | ], 197 | parsedJSON: { 198 | asyncapi: '2.2.0', 199 | info: { 200 | tite: 'My API', 201 | version: '1.0.0' 202 | }, 203 | channels: {} 204 | } 205 | }); 206 | }); 207 | }); 208 | }); -------------------------------------------------------------------------------- /src/controllers/tests/convert.controller.test.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | 3 | import { App } from '../../app'; 4 | import { ProblemException } from '../../exceptions/problem.exception'; 5 | import { ALL_SPECS } from '../../interfaces'; 6 | 7 | import { ConvertController } from '../convert.controller'; 8 | 9 | const validJsonAsyncAPI2_0_0 = { 10 | asyncapi: '2.0.0', 11 | info: { 12 | title: 'Super test', 13 | version: '1.0.0' 14 | }, 15 | channels: {} 16 | }; 17 | 18 | const validJsonAsyncAPI2_1_0 = { 19 | asyncapi: '2.1.0', 20 | info: { 21 | title: 'Super test', 22 | version: '1.0.0' 23 | }, 24 | channels: {} 25 | }; 26 | 27 | const validYamlAsyncAPI2_4_0 = ` 28 | asyncapi: 2.4.0 29 | info: 30 | title: Super test 31 | version: 1.0.0 32 | channels: {} 33 | `; 34 | 35 | describe('ConvertController', () => { 36 | describe('[POST] /convert', () => { 37 | it('should throw error with invalid version', async () => { 38 | const app = new App([new ConvertController()]); 39 | await app.init(); 40 | 41 | return request(app.getServer()) 42 | .post('/v1/convert') 43 | .send({ 44 | asyncapi: { 45 | asyncapi: '2.2.0', 46 | info: { 47 | title: 'Test Service', 48 | version: '1.0.0', 49 | }, 50 | channels: {}, 51 | }, 52 | version: '1' 53 | }) 54 | .expect(422, { 55 | type: ProblemException.createType('invalid-request-body'), 56 | title: 'Invalid Request Body', 57 | status: 422, 58 | validationErrors: [ 59 | { 60 | instancePath: '/version', 61 | schemaPath: '#/properties/version/enum', 62 | keyword: 'enum', 63 | params: { 64 | allowedValues: [...ALL_SPECS, 'latest'], 65 | }, 66 | message: 'must be equal to one of the allowed values' 67 | } 68 | ] 69 | }); 70 | }); 71 | 72 | it('should throw error that the converter cannot convert to a lower version', async () => { 73 | const app = new App([new ConvertController()]); 74 | await app.init(); 75 | 76 | return request(app.getServer()) 77 | .post('/v1/convert') 78 | .send({ 79 | asyncapi: validJsonAsyncAPI2_1_0, 80 | version: '2.0.0' 81 | }) 82 | .expect(422, { 83 | type: 'https://api.asyncapi.com/problem/internal-converter-error', 84 | title: 'Could not convert document', 85 | status: 422, 86 | detail: 'Cannot downgrade from 2.1.0 to 2.0.0.', 87 | }); 88 | }); 89 | 90 | it('should pass when converting to 2.4.0 version', async () => { 91 | const app = new App([new ConvertController()]); 92 | await app.init(); 93 | 94 | return request(app.getServer()) 95 | .post('/v1/convert') 96 | .send({ 97 | asyncapi: validJsonAsyncAPI2_0_0, 98 | version: '2.4.0' 99 | }) 100 | .expect(200, { 101 | converted: { 102 | asyncapi: '2.4.0', 103 | info: { 104 | title: 'Super test', 105 | version: '1.0.0' 106 | }, 107 | channels: {}, 108 | }, 109 | }); 110 | }); 111 | 112 | it('should pass when converting to latest version', async () => { 113 | const app = new App([new ConvertController()]); 114 | await app.init(); 115 | 116 | return request(app.getServer()) 117 | .post('/v1/convert') 118 | .send({ 119 | asyncapi: validJsonAsyncAPI2_0_0, 120 | }) 121 | .expect(200, { 122 | converted: { 123 | asyncapi: '2.6.0', 124 | info: { 125 | title: 'Super test', 126 | version: '1.0.0' 127 | }, 128 | channels: {}, 129 | }, 130 | }); 131 | }); 132 | 133 | it('should correctly convert JSON to YAML', async () => { 134 | const app = new App([new ConvertController()]); 135 | await app.init(); 136 | 137 | return request(app.getServer()) 138 | .post('/v1/convert') 139 | .send({ 140 | asyncapi: validJsonAsyncAPI2_0_0, 141 | version: '2.4.0', 142 | language: 'yaml' 143 | }) 144 | .expect(200, { 145 | converted: validYamlAsyncAPI2_4_0.trimStart(), 146 | }); 147 | }); 148 | }); 149 | }); 150 | -------------------------------------------------------------------------------- /src/controllers/tests/diff.controller.test.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | 3 | import { App } from '../../app'; 4 | import { ProblemException } from '../../exceptions/problem.exception'; 5 | 6 | import { DiffController } from '../../controllers/diff.controller'; 7 | 8 | describe('DiffController', () => { 9 | describe('[POST] /diff', () => { 10 | it('should diff AsyncAPI documents', async () => { 11 | const app = new App([new DiffController()]); 12 | await app.init(); 13 | 14 | await request(app.getServer()) 15 | .post('/v1/diff') 16 | .send({ 17 | asyncapis: [ 18 | { 19 | asyncapi: '2.3.0', 20 | info: { 21 | title: 'Super test', 22 | version: '1.0.0' 23 | }, 24 | channels: { 25 | 'test-channel-1': { 26 | publish: { 27 | message: { 28 | payload: { 29 | type: 'object', 30 | }, 31 | }, 32 | } 33 | }, 34 | }, 35 | }, 36 | { 37 | asyncapi: '2.3.0', 38 | info: { 39 | title: 'Changed super test', 40 | version: '1.1.0' 41 | }, 42 | channels: { 43 | 'test-channel-1': { 44 | publish: { 45 | message: { 46 | payload: { 47 | type: 'object', 48 | }, 49 | }, 50 | } 51 | }, 52 | }, 53 | }, 54 | ], 55 | }) 56 | .expect(200, { 57 | diff: { 58 | changes: [ 59 | { 60 | action: 'edit', 61 | path: '/info/version', 62 | before: '1.0.0', 63 | after: '1.1.0', 64 | type: 'breaking', 65 | }, 66 | { 67 | action: 'edit', 68 | path: '/info/title', 69 | before: 'Super test', 70 | after: 'Changed super test', 71 | type: 'non-breaking', 72 | }, 73 | ], 74 | } 75 | }); 76 | }); 77 | 78 | it('should throw error with invalid AsyncAPI document', async () => { 79 | const app = new App([new DiffController()]); 80 | await app.init(); 81 | 82 | await request(app.getServer()) 83 | .post('/v1/diff') 84 | .send({ 85 | asyncapis: [ 86 | { 87 | asyncapi: '2.2.0', 88 | info: { 89 | title: 'Test Service', 90 | version: '1.0.0', 91 | }, 92 | channels: { 93 | 'test-channel-2': { 94 | publish: { 95 | message: { 96 | payload: { 97 | type: 'object', 98 | }, 99 | }, 100 | } 101 | }, 102 | }, 103 | }, 104 | { 105 | asyncapi: '2.2.0', 106 | info: { 107 | tite: 'My API', // spelled wrong on purpose to throw an error in the test 108 | version: '1.0.0' 109 | }, 110 | channels: {}, 111 | } 112 | ], 113 | }) 114 | .expect(422, { 115 | type: ProblemException.createType('validation-errors'), 116 | title: 'There were errors validating the AsyncAPI document.', 117 | status: 422, 118 | validationErrors: [ 119 | { 120 | title: '/info should NOT have additional properties', 121 | location: { 122 | jsonPointer: '/info' 123 | } 124 | }, 125 | { 126 | title: '/info should have required property \'title\'', 127 | location: { 128 | jsonPointer: '/info' 129 | } 130 | } 131 | ], 132 | parsedJSON: { 133 | asyncapi: '2.2.0', 134 | info: { 135 | tite: 'My API', 136 | version: '1.0.0' 137 | }, 138 | channels: {} 139 | } 140 | }); 141 | }); 142 | }); 143 | }); 144 | -------------------------------------------------------------------------------- /src/controllers/tests/generate.controller.test.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | 3 | import { App } from '../../app'; 4 | import { ProblemException } from '../../exceptions/problem.exception'; 5 | 6 | import { GenerateController } from '../generate.controller'; 7 | 8 | describe('GeneratorController', () => { 9 | describe('[POST] /generate', () => { 10 | it('should generate template ', async () => { 11 | const app = new App([new GenerateController()]); 12 | await app.init(); 13 | 14 | return request(app.getServer()) 15 | .post('/v1/generate') 16 | .send({ 17 | asyncapi: { 18 | asyncapi: '2.2.0', 19 | info: { 20 | title: 'Test Service', 21 | version: '1.0.0', 22 | }, 23 | channels: {}, 24 | }, 25 | template: '@asyncapi/html-template', 26 | parameters: { 27 | version: '2.1.37', 28 | } 29 | }) 30 | .expect(200); 31 | }); 32 | 33 | it('should pass when sent template parameters are empty', async () => { 34 | const app = new App([new GenerateController()]); 35 | await app.init(); 36 | 37 | return request(app.getServer()) 38 | .post('/v1/generate') 39 | .send({ 40 | asyncapi: { 41 | asyncapi: '2.2.0', 42 | info: { 43 | title: 'Test Service', 44 | version: '1.0.0', 45 | }, 46 | channels: {}, 47 | }, 48 | template: '@asyncapi/html-template', 49 | }) 50 | .expect(200); 51 | }); 52 | 53 | it('should throw error when sent template parameters are invalid', async () => { 54 | const app = new App([new GenerateController()]); 55 | await app.init(); 56 | 57 | return request(app.getServer()) 58 | .post('/v1/generate') 59 | .send({ 60 | asyncapi: { 61 | asyncapi: '2.2.0', 62 | info: { 63 | title: 'Test Service', 64 | version: '1.0.0', 65 | }, 66 | channels: {}, 67 | }, 68 | template: '@asyncapi/html-template', 69 | parameters: { 70 | customParameter: 'customValue', 71 | } 72 | }) 73 | .expect(422, { 74 | type: ProblemException.createType('invalid-template-parameters'), 75 | title: 'Invalid Generator Template parameters', 76 | status: 422, 77 | validationErrors: [ 78 | { 79 | instancePath: '', 80 | schemaPath: '#/additionalProperties', 81 | keyword: 'additionalProperties', 82 | params: { 83 | additionalProperty: 'customParameter' 84 | }, 85 | message: 'must NOT have additional properties' 86 | } 87 | ] 88 | }); 89 | }); 90 | 91 | it('should throw error when required parameter is not sent', async () => { 92 | const app = new App([new GenerateController()]); 93 | await app.init(); 94 | 95 | return request(app.getServer()) 96 | .post('/v1/generate') 97 | .send({ 98 | asyncapi: { 99 | asyncapi: '2.2.0', 100 | info: { 101 | title: 'Test Service', 102 | version: '1.0.0', 103 | }, 104 | channels: {}, 105 | }, 106 | template: '@asyncapi/nodejs-template', 107 | parameters: { 108 | invalidServer: 'invalidServer', 109 | } 110 | }) 111 | .expect(422, { 112 | type: ProblemException.createType('invalid-template-parameters'), 113 | title: 'Invalid Generator Template parameters', 114 | status: 422, 115 | validationErrors: [ 116 | { 117 | instancePath: '', 118 | schemaPath: '#/required', 119 | keyword: 'required', 120 | params: { missingProperty: 'server' }, 121 | message: 'must have required property \'server\'' 122 | }, 123 | { 124 | instancePath: '', 125 | schemaPath: '#/additionalProperties', 126 | keyword: 'additionalProperties', 127 | params: { additionalProperty: 'invalidServer' }, 128 | message: 'must NOT have additional properties' 129 | } 130 | ] 131 | }); 132 | }); 133 | }); 134 | }); 135 | -------------------------------------------------------------------------------- /src/controllers/tests/help.controller.test.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | import { App } from '../../app'; 3 | import { HelpController } from '../help.controller'; 4 | import { getAppOpenAPI } from '../../utils/app-openapi'; 5 | 6 | jest.mock('../../utils/app-openapi', () => ({ 7 | getAppOpenAPI: jest.fn(), 8 | })); 9 | 10 | describe('HelpController', () => { 11 | let app; 12 | beforeAll(async () => { 13 | app = new App([new HelpController()]); 14 | await app.init(); 15 | }); 16 | 17 | describe('[GET] /help', () => { 18 | it('should return all commands', async () => { 19 | (getAppOpenAPI as jest.Mock).mockResolvedValue({ 20 | paths: { 21 | '/validate': {}, 22 | '/parse': {}, 23 | '/generate': {}, 24 | '/convert': {}, 25 | '/bundle': {}, 26 | '/help': {}, 27 | '/diff': {} 28 | } 29 | }); 30 | 31 | const response = await request(app.getServer()) 32 | .get('/v1/help') 33 | .expect(200); 34 | 35 | expect(response.body).toEqual([ 36 | { 37 | command: 'validate', 38 | url: '/help/validate' 39 | }, 40 | { 41 | command: 'parse', 42 | url: '/help/parse' 43 | }, 44 | { 45 | command: 'generate', 46 | url: '/help/generate' 47 | }, 48 | { 49 | command: 'convert', 50 | url: '/help/convert' 51 | }, 52 | { 53 | command: 'bundle', 54 | url: '/help/bundle' 55 | }, 56 | { 57 | command: 'help', 58 | url: '/help/help' 59 | }, 60 | { 61 | command: 'diff', 62 | url: '/help/diff' 63 | } 64 | ]); 65 | }); 66 | 67 | it('should return 404 error for an invalid command', async () => { 68 | const response = await request(app.getServer()) 69 | .get('/v1/help/invalidCommand') 70 | .expect(404); 71 | 72 | expect(response.body).toEqual({ 73 | type: 'https://api.asyncapi.com/problem/invalid-asyncapi-command', 74 | title: 'Invalid AsyncAPI Command', 75 | status: 404, 76 | detail: 'The given AsyncAPI command is not valid.' 77 | }); 78 | }); 79 | 80 | it('should return 404 error for a command without a method', async () => { 81 | (getAppOpenAPI as jest.Mock).mockResolvedValue({ 82 | paths: { 83 | '/someCommand': {} 84 | } 85 | }); 86 | 87 | const response = await request(app.getServer()) 88 | .get('/v1/help/someCommand') 89 | .expect(404); 90 | 91 | expect(response.body).toEqual({ 92 | type: 'https://api.asyncapi.com/problem/invalid-asyncapi-command', 93 | title: 'Invalid AsyncAPI Command', 94 | status: 404, 95 | detail: 'The given AsyncAPI command is not valid.' 96 | }); 97 | }); 98 | }); 99 | }); -------------------------------------------------------------------------------- /src/controllers/tests/parse.controller.test.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | 3 | import { App } from '../../app'; 4 | import { ProblemException } from '../../exceptions/problem.exception'; 5 | 6 | import { ParseController } from '../parse.controller'; 7 | 8 | const validJSONAsyncAPI = { 9 | asyncapi: '2.0.0', 10 | info: { 11 | title: 'My API', 12 | version: '1.0.0' 13 | }, 14 | channels: {} 15 | }; 16 | const invalidJSONAsyncAPI = { 17 | asyncapi: '2.0.0', 18 | info: { 19 | tite: 'My API', // spelled wrong on purpose to throw an error in the test 20 | version: '1.0.0' 21 | }, 22 | channels: {} 23 | }; 24 | 25 | describe('ParseController', () => { 26 | describe('[POST] /parse', () => { 27 | it('should return stringified AsyncAPI document', async () => { 28 | const app = new App([new ParseController()]); 29 | await app.init(); 30 | 31 | return request(app.getServer()) 32 | .post('/v1/parse') 33 | .send({ 34 | asyncapi: validJSONAsyncAPI 35 | }) 36 | .expect(200, { 37 | parsed: '{"asyncapi":"2.0.0","info":{"title":"My API","version":"1.0.0"},"channels":{},"x-parser-spec-parsed":true,"x-parser-spec-stringified":true}', 38 | }); 39 | }); 40 | 41 | it('should throw error when sent an invalid AsyncAPI document', async () => { 42 | const app = new App([new ParseController()]); 43 | await app.init(); 44 | 45 | return request(app.getServer()) 46 | .post('/v1/parse') 47 | .send({ 48 | asyncapi: invalidJSONAsyncAPI 49 | }) 50 | .expect(422, { 51 | type: ProblemException.createType('validation-errors'), 52 | title: 'There were errors validating the AsyncAPI document.', 53 | status: 422, 54 | validationErrors: [ 55 | { 56 | title: '/info should NOT have additional properties', 57 | location: { 58 | jsonPointer: '/info' 59 | } 60 | }, 61 | { 62 | title: '/info should have required property \'title\'', 63 | location: { 64 | jsonPointer: '/info' 65 | } 66 | } 67 | ], 68 | parsedJSON: { 69 | asyncapi: '2.0.0', 70 | info: { 71 | tite: 'My API', 72 | version: '1.0.0' 73 | }, 74 | channels: {} 75 | } 76 | }); 77 | }); 78 | }); 79 | }); 80 | -------------------------------------------------------------------------------- /src/controllers/tests/validate.controller.test.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | 3 | import { App } from '../../app'; 4 | import { ProblemException } from '../../exceptions/problem.exception'; 5 | 6 | import { ValidateController } from '../validate.controller'; 7 | 8 | const validJSONAsyncAPI = { 9 | asyncapi: '2.2.0', 10 | info: { 11 | title: 'Account Service', 12 | version: '1.0.0', 13 | description: 'This service is in charge of processing user signups' 14 | }, 15 | channels: { 16 | 'user/signedup': { 17 | subscribe: { 18 | message: { 19 | $ref: '#/components/messages/UserSignedUp' 20 | } 21 | } 22 | } 23 | }, 24 | components: { 25 | messages: { 26 | UserSignedUp: { 27 | payload: { 28 | type: 'object', 29 | properties: { 30 | displayName: { 31 | type: 'string', 32 | description: 'Name of the user' 33 | }, 34 | email: { 35 | type: 'string', 36 | format: 'email', 37 | description: 'Email of the user' 38 | } 39 | } 40 | } 41 | } 42 | } 43 | } 44 | }; 45 | const validYAMLAsyncAPI = ` 46 | asyncapi: '2.2.0' 47 | info: 48 | title: Account Service 49 | version: 1.0.0 50 | description: This service is in charge of processing user signups 51 | channels: 52 | user/signedup: 53 | subscribe: 54 | message: 55 | $ref: '#/components/messages/UserSignedUp' 56 | components: 57 | messages: 58 | UserSignedUp: 59 | payload: 60 | type: object 61 | properties: 62 | displayName: 63 | type: string 64 | description: Name of the user 65 | email: 66 | type: string 67 | format: email 68 | description: Email of the user 69 | `; 70 | const invalidJSONAsyncAPI = { 71 | asyncapi: '2.0.0', 72 | info: { 73 | tite: 'My API', // spelled wrong on purpose to throw an error in the test 74 | version: '1.0.0' 75 | }, 76 | channels: {} 77 | }; 78 | 79 | describe('ValidateController', () => { 80 | describe('[POST] /validate', () => { 81 | it('should validate AsyncAPI document in JSON', async () => { 82 | const app = new App([new ValidateController()]); 83 | await app.init(); 84 | 85 | return request(app.getServer()) 86 | .post('/v1/validate') 87 | .send({ 88 | asyncapi: validJSONAsyncAPI 89 | }) 90 | .expect(204); 91 | }); 92 | 93 | it('should validate AsyncAPI document in YAML', async () => { 94 | const app = new App([new ValidateController()]); 95 | await app.init(); 96 | 97 | return request(app.getServer()) 98 | .post('/v1/validate') 99 | .send({ 100 | asyncapi: validYAMLAsyncAPI 101 | }) 102 | .expect(204); 103 | }); 104 | 105 | it('should throw error when sent an empty document', async () => { 106 | const app = new App([new ValidateController()]); 107 | await app.init(); 108 | 109 | return request(app.getServer()) 110 | .post('/v1/validate') 111 | .send({}) 112 | .expect(422, { 113 | type: ProblemException.createType('invalid-request-body'), 114 | title: 'Invalid Request Body', 115 | status: 422, 116 | validationErrors: [ 117 | { 118 | instancePath: '', 119 | schemaPath: '#/required', 120 | keyword: 'required', 121 | params: { 122 | missingProperty: 'asyncapi' 123 | }, 124 | message: 'must have required property \'asyncapi\'' 125 | } 126 | ] 127 | }); 128 | }); 129 | 130 | it('should throw error when sent an invalid AsyncAPI document', async () => { 131 | const app = new App([new ValidateController()]); 132 | await app.init(); 133 | 134 | return request(app.getServer()) 135 | .post('/v1/validate') 136 | .send({ 137 | asyncapi: invalidJSONAsyncAPI 138 | }) 139 | .expect(422, { 140 | type: ProblemException.createType('validation-errors'), 141 | title: 'There were errors validating the AsyncAPI document.', 142 | status: 422, 143 | validationErrors: [ 144 | { 145 | title: '/info should NOT have additional properties', 146 | location: { 147 | jsonPointer: '/info' 148 | } 149 | }, 150 | { 151 | title: '/info should have required property \'title\'', 152 | location: { 153 | jsonPointer: '/info' 154 | } 155 | } 156 | ], 157 | parsedJSON: { 158 | asyncapi: '2.0.0', 159 | info: { 160 | tite: 'My API', 161 | version: '1.0.0' 162 | }, 163 | channels: {} 164 | } 165 | }); 166 | }); 167 | }); 168 | }); 169 | -------------------------------------------------------------------------------- /src/controllers/validate.controller.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, Router } from 'express'; 2 | 3 | import { validationMiddleware } from '../middlewares/validation.middleware'; 4 | 5 | import { Controller } from '../interfaces'; 6 | 7 | /** 8 | * Controller which exposes the Parser functionality, to validate the AsyncAPI document. 9 | */ 10 | export class ValidateController implements Controller { 11 | public basepath = '/validate'; 12 | 13 | private async validate(_: Request, res: Response) { 14 | res.status(204).end(); 15 | } 16 | 17 | public async boot(): Promise { 18 | const router = Router(); 19 | 20 | router.post( 21 | `${this.basepath}`, 22 | await validationMiddleware({ 23 | path: this.basepath, 24 | method: 'post', 25 | documents: ['asyncapi'], 26 | }), 27 | this.validate.bind(this) 28 | ); 29 | 30 | return router; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/exceptions/problem.exception.ts: -------------------------------------------------------------------------------- 1 | import { ProblemMixin } from '@asyncapi/problem'; 2 | 3 | export interface ProblemExceptionProps { 4 | status: number; 5 | [key: string]: any; 6 | } 7 | 8 | const typePrefix = 'https://api.asyncapi.com/problem'; 9 | 10 | export class ProblemException extends ProblemMixin({ typePrefix }) {} 11 | -------------------------------------------------------------------------------- /src/interfaces.ts: -------------------------------------------------------------------------------- 1 | import specs from '@asyncapi/specs'; 2 | import { Router } from 'express'; 3 | 4 | export interface Controller { 5 | basepath: string; 6 | boot(): Router | Promise; 7 | } 8 | 9 | export interface Problem { 10 | type: string; 11 | title: string; 12 | status: number; 13 | detail?: string; 14 | instance?: string; 15 | [key: string]: any; 16 | } 17 | 18 | export type AsyncAPIDocument = { asyncapi: string } & Record; 19 | 20 | export const ALL_SPECS = [...Object.keys(specs)]; 21 | export const LAST_SPEC_VERSION = ALL_SPECS[ALL_SPECS.length - 1]; 22 | 23 | export type SpecsEnum = keyof typeof specs | 'latest'; 24 | -------------------------------------------------------------------------------- /src/middlewares/problem.middleware.ts: -------------------------------------------------------------------------------- 1 | import { NextFunction, Request, Response } from 'express'; 2 | 3 | import { ProblemException } from '../exceptions/problem.exception'; 4 | import { logger } from '../utils/logger'; 5 | 6 | /** 7 | * Catch problem exception, log it and serialize error to human readable form. 8 | */ 9 | export function problemMiddleware(error: ProblemException, req: Request, res: Response, next: NextFunction) { 10 | if (res.headersSent) { 11 | return next(error); 12 | } 13 | 14 | try { 15 | const problemShape = error.get(); 16 | const status = problemShape.status = problemShape.status || 500; 17 | problemShape.title = problemShape.title || 'Internal server error'; 18 | 19 | logger.error(`[${req.method}] ${req.path} >> Status:: ${status}, Type:: ${problemShape.type.replace('https://api.asyncapi.com/problem/', '')}, Title:: ${problemShape.title}, Detail:: ${problemShape.detail}`); 20 | 21 | const isError = status >= 500; 22 | const problem = error.toObject({ includeStack: isError, includeCause: isError }); 23 | res.status(status).json(problem); 24 | } catch (err: unknown) { 25 | next(err); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/middlewares/tests/problem.middleware.test.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | 3 | import { App } from '../../app'; 4 | import { ProblemException } from '../../exceptions/problem.exception'; 5 | 6 | import { createTestController } from '../../../tests/test.controller'; 7 | 8 | // problemMiddleware is added to every route 9 | describe('problemMiddleware', () => { 10 | describe('[POST] /test', () => { 11 | it('should handle throwed exception', async () => { 12 | const TestController = createTestController({ 13 | path: '/test', 14 | method: 'post', 15 | callback: () => { 16 | throw new ProblemException({ 17 | type: 'custom-problem', 18 | title: 'Custom problem', 19 | status: 422, 20 | }); 21 | }, 22 | }); 23 | const app = new App([new TestController()]); 24 | await app.init(); 25 | 26 | return await request(app.getServer()) 27 | .post('/v1/test') 28 | .send({}) 29 | .expect(422, { 30 | type: ProblemException.createType('custom-problem'), 31 | title: 'Custom problem', 32 | status: 422, 33 | }); 34 | }); 35 | 36 | it('should not have executed when there was success call', async () => { 37 | const TestController = createTestController({ 38 | path: '/test', 39 | method: 'post', 40 | callback: (_, res) => { 41 | res.status(200).send({ success: true }); 42 | }, 43 | }); 44 | const app = new App([new TestController()]); 45 | await app.init(); 46 | 47 | return await request(app.getServer()) 48 | .post('/v1/test') 49 | .send({}) 50 | .expect(200, { 51 | success: true, 52 | }); 53 | }); 54 | }); 55 | }); 56 | -------------------------------------------------------------------------------- /src/middlewares/tests/validation.middleware.test.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | 3 | import { App } from '../../app'; 4 | import { ProblemException } from '../../exceptions/problem.exception'; 5 | import { validationMiddleware } from '../validation.middleware'; 6 | 7 | import { createTestController } from '../../../tests/test.controller'; 8 | import { getAppOpenAPI } from '../../utils/app-openapi'; 9 | 10 | // test /generate route to check validation of custom requestBody 11 | describe('validationMiddleware', () => { 12 | it('should pass when request body is valid', async () => { 13 | const TestController = createTestController({ 14 | path: '/generate', 15 | method: 'post', 16 | callback: (_, res) => { 17 | res.status(200).send({ success: true }); 18 | }, 19 | middlewares: [ 20 | await validationMiddleware({ 21 | path: '/generate', 22 | method: 'post', 23 | documents: ['asyncapi'], 24 | }), 25 | ], 26 | }); 27 | const app = new App([new TestController()]); 28 | await app.init(); 29 | 30 | return await request(app.getServer()) 31 | .post('/v1/generate') 32 | .send({ 33 | asyncapi: { 34 | asyncapi: '2.2.0', 35 | info: { 36 | title: 'Test Service', 37 | version: '1.0.0', 38 | }, 39 | channels: {}, 40 | }, 41 | template: '@asyncapi/html-template' 42 | }) 43 | .expect(200, { 44 | success: true, 45 | }); 46 | }); 47 | 48 | it('should throw error when request body is invalid', async () => { 49 | const TestController = createTestController({ 50 | path: '/generate', 51 | method: 'post', 52 | callback: (_, res) => { 53 | res.status(200).send({ success: true }); 54 | }, 55 | middlewares: [ 56 | await validationMiddleware({ 57 | path: '/generate', 58 | method: 'post', 59 | documents: ['asyncapi'], 60 | }), 61 | ], 62 | }); 63 | const app = new App([new TestController()]); 64 | await app.init(); 65 | 66 | const openApi = await getAppOpenAPI(); 67 | const availableTemplates = openApi.components.schemas.GenerateRequest.properties.template.enum; 68 | 69 | return await request(app.getServer()) 70 | .post('/v1/generate') 71 | .send({ 72 | asyncapi: { 73 | asyncapi: '2.2.0', 74 | info: { 75 | title: 'Test Service', 76 | version: '1.0.0', 77 | }, 78 | channels: {}, 79 | }, 80 | template: 'custom template' 81 | }) 82 | .expect(422, { 83 | type: ProblemException.createType('invalid-request-body'), 84 | title: 'Invalid Request Body', 85 | status: 422, 86 | validationErrors: [ 87 | { 88 | instancePath: '/template', 89 | schemaPath: '#/properties/template/enum', 90 | keyword: 'enum', 91 | params: { 92 | allowedValues: availableTemplates, 93 | }, 94 | message: 'must be equal to one of the allowed values' 95 | } 96 | ] 97 | }); 98 | }); 99 | 100 | it('should pass when `asyncapi` field is defined as valid AsyncAPI document', async () => { 101 | const TestController = createTestController({ 102 | path: '/generate', 103 | method: 'post', 104 | callback: (_, res) => { 105 | res.status(200).send({ success: true }); 106 | }, 107 | middlewares: [ 108 | await validationMiddleware({ 109 | path: '/generate', 110 | method: 'post', 111 | documents: ['asyncapi'], 112 | }), 113 | ], 114 | }); 115 | const app = new App([new TestController()]); 116 | await app.init(); 117 | 118 | return await request(app.getServer()) 119 | .post('/v1/generate') 120 | .send({ 121 | template: '@asyncapi/html-template', 122 | asyncapi: { 123 | asyncapi: '2.2.0', 124 | info: { 125 | title: 'Account Service', 126 | version: '1.0.0', 127 | description: 'This service is in charge of processing user signups' 128 | }, 129 | channels: { 130 | 'user/signedup': { 131 | subscribe: { 132 | message: { 133 | $ref: '#/components/messages/UserSignedUp' 134 | } 135 | } 136 | } 137 | }, 138 | components: { 139 | messages: { 140 | UserSignedUp: { 141 | payload: { 142 | type: 'object', 143 | properties: { 144 | displayName: { 145 | type: 'string', 146 | description: 'Name of the user' 147 | }, 148 | email: { 149 | type: 'string', 150 | format: 'email', 151 | description: 'Email of the user' 152 | } 153 | } 154 | } 155 | } 156 | } 157 | } 158 | } 159 | }) 160 | .expect(200, { 161 | success: true, 162 | }); 163 | }); 164 | 165 | it('should throw error when `asyncapi` field is defined as invalid AsyncAPI document', async () => { 166 | const TestController = createTestController({ 167 | path: '/generate', 168 | method: 'post', 169 | callback: (_, res) => { 170 | res.status(200).send({ success: true }); 171 | }, 172 | middlewares: [ 173 | await validationMiddleware({ 174 | path: '/generate', 175 | method: 'post', 176 | documents: ['asyncapi'], 177 | }), 178 | ], 179 | }); 180 | const app = new App([new TestController()]); 181 | await app.init(); 182 | 183 | return await request(app.getServer()) 184 | .post('/v1/generate') 185 | .send({ 186 | template: '@asyncapi/html-template', 187 | // without title, version and channels 188 | asyncapi: { 189 | asyncapi: '2.2.0', 190 | info: { 191 | description: 'This service is in charge of processing user signups' 192 | } 193 | } 194 | }) 195 | .expect(422, { 196 | type: ProblemException.createType('validation-errors'), 197 | title: 'There were errors validating the AsyncAPI document.', 198 | status: 422, 199 | validationErrors: [ 200 | { 201 | title: '/info should have required property \'title\'', 202 | location: { jsonPointer: '/info' } 203 | }, 204 | { 205 | title: '/info should have required property \'version\'', 206 | location: { jsonPointer: '/info' } 207 | }, 208 | { 209 | title: '/ should have required property \'channels\'', 210 | location: { jsonPointer: '/' } 211 | } 212 | ], 213 | parsedJSON: { 214 | asyncapi: '2.2.0', 215 | info: { 216 | description: 'This service is in charge of processing user signups', 217 | }, 218 | } 219 | }); 220 | }); 221 | }); 222 | -------------------------------------------------------------------------------- /src/middlewares/validation.middleware.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, NextFunction } from 'express'; 2 | import { AsyncAPIDocument } from '@asyncapi/parser'; 3 | 4 | import { ProblemException } from '../exceptions/problem.exception'; 5 | import { createAjvInstance } from '../utils/ajv'; 6 | import { getAppOpenAPI } from '../utils/app-openapi'; 7 | import { 8 | parse, 9 | prepareParserConfig, 10 | tryConvertToProblemException, 11 | } from '../utils/parser'; 12 | 13 | import type { ValidateFunction } from 'ajv'; 14 | 15 | export interface ValidationMiddlewareOptions { 16 | path: string; 17 | method: 18 | | 'all' 19 | | 'get' 20 | | 'post' 21 | | 'put' 22 | | 'delete' 23 | | 'patch' 24 | | 'options' 25 | | 'head'; 26 | documents?: Array; 27 | version?: 'v1'; 28 | } 29 | 30 | const ajvInstance = createAjvInstance(); 31 | 32 | /** 33 | * Create AJV's validator function for given path in the OpenAPI document. 34 | */ 35 | async function compileAjv(options: ValidationMiddlewareOptions) { 36 | const appOpenAPI = await getAppOpenAPI(); 37 | const paths = appOpenAPI.paths || {}; 38 | 39 | const pathName = options.path; 40 | const path = paths[String(pathName)]; 41 | if (!path) { 42 | throw new Error( 43 | `Path "${pathName}" doesn't exist in the OpenAPI document.` 44 | ); 45 | } 46 | 47 | const methodName = options.method; 48 | const method = path[String(methodName)]; 49 | if (!method) { 50 | throw new Error( 51 | `Method "${methodName}" for "${pathName}" path doesn't exist in the OpenAPI document.` 52 | ); 53 | } 54 | 55 | const requestBody = method.requestBody; 56 | if (!requestBody) return; 57 | 58 | let schema = requestBody.content['application/json'].schema; 59 | if (!schema) return; 60 | 61 | schema = { ...schema }; 62 | schema['$schema'] = 'http://json-schema.org/draft-07/schema'; 63 | 64 | if (options.documents && schema.properties) { 65 | schema.properties = { ...schema.properties }; 66 | options.documents.forEach((field) => { 67 | if (schema.properties[String(field)].items) { 68 | schema.properties[String(field)] = { 69 | ...schema.properties[String(field)], 70 | }; 71 | schema.properties[String(field)].items = true; 72 | } else { 73 | schema.properties[String(field)] = true; 74 | } 75 | }); 76 | } 77 | 78 | return ajvInstance.compile(schema); 79 | } 80 | 81 | async function validateRequestBody(validate: ValidateFunction, body: any) { 82 | const valid = validate(body); 83 | const errors = validate.errors && [...validate.errors]; 84 | 85 | if (valid === false) { 86 | throw new ProblemException({ 87 | type: 'invalid-request-body', 88 | title: 'Invalid Request Body', 89 | status: 422, 90 | validationErrors: errors as any, 91 | }); 92 | } 93 | } 94 | 95 | async function validateSingleDocument( 96 | asyncapi: string | AsyncAPIDocument, 97 | parserConfig: ReturnType 98 | ) { 99 | if (typeof asyncapi === 'object') { 100 | asyncapi = JSON.parse(JSON.stringify(asyncapi)); 101 | } 102 | return parse(asyncapi, parserConfig); 103 | } 104 | 105 | async function validateListDocuments( 106 | asyncapis: Array, 107 | parserConfig: ReturnType 108 | ) { 109 | const parsedDocuments: Array = []; 110 | for (const asyncapi of asyncapis) { 111 | const parsed = await validateSingleDocument(asyncapi, parserConfig); 112 | parsedDocuments.push(parsed); 113 | } 114 | return parsedDocuments; 115 | } 116 | 117 | /** 118 | * Validate RequestBody and sent AsyncAPI document(s) for given path and method based on the OpenAPI Document. 119 | */ 120 | export async function validationMiddleware( 121 | options: ValidationMiddlewareOptions 122 | ) { 123 | options.version = options.version || 'v1'; 124 | const validate = await compileAjv(options); 125 | const documents = options.documents; 126 | 127 | return async function (req: Request, _: Response, next: NextFunction) { 128 | // validate request body 129 | try { 130 | await validateRequestBody(validate, req.body); 131 | } catch (err: unknown) { 132 | return next(err); 133 | } 134 | 135 | // validate AsyncAPI document(s) 136 | const parserConfig = prepareParserConfig(req); 137 | try { 138 | req.asyncapi = req.asyncapi || {}; 139 | for (const field of documents) { 140 | const body = req.body[String(field)]; 141 | if (Array.isArray(body)) { 142 | const parsed = await validateListDocuments(body, parserConfig); 143 | req.asyncapi.parsedDocuments = parsed; 144 | } else { 145 | const parsed = await validateSingleDocument(body, parserConfig); 146 | req.asyncapi.parsedDocument = parsed; 147 | } 148 | } 149 | 150 | next(); 151 | } catch (err: unknown) { 152 | return next(tryConvertToProblemException(err)); 153 | } 154 | }; 155 | } 156 | -------------------------------------------------------------------------------- /src/server-api.d.ts: -------------------------------------------------------------------------------- 1 | import { AsyncAPIDocument } from '@asyncapi/parser'; 2 | 3 | declare module 'express' { 4 | export interface Request { 5 | asyncapi?: { 6 | parsedDocument?: AsyncAPIDocument; 7 | parsedDocuments?: Array; 8 | }, 9 | } 10 | } -------------------------------------------------------------------------------- /src/server.ts: -------------------------------------------------------------------------------- 1 | // include production config in the `dist` folder 2 | import './configs/production.json'; 3 | 4 | // for `config` module 5 | process.env['NODE_CONFIG_DIR'] = `${__dirname}/configs`; 6 | 7 | import { App } from './app'; 8 | import { ValidateController } from './controllers/validate.controller'; 9 | import { ParseController } from './controllers/parse.controller'; 10 | import { GenerateController } from './controllers/generate.controller'; 11 | import { ConvertController } from './controllers/convert.controller'; 12 | import { BundleController } from './controllers/bundle.controller'; 13 | import { DiffController } from './controllers/diff.controller'; 14 | import { DocsController } from './controllers/docs.controller'; 15 | import { HelpController } from './controllers/help.controller'; 16 | 17 | async function main() { 18 | const app = new App([ 19 | new ValidateController(), 20 | new ParseController(), 21 | new GenerateController(), 22 | new ConvertController(), 23 | new BundleController(), 24 | new DiffController(), 25 | new DocsController(), 26 | new HelpController(), 27 | ]); 28 | await app.init(); 29 | app.listen(); 30 | } 31 | main(); 32 | -------------------------------------------------------------------------------- /src/services/archiver.service.ts: -------------------------------------------------------------------------------- 1 | import archiver, { Archiver } from 'archiver'; 2 | import { Response } from 'express'; 3 | 4 | import { retrieveLangauge } from '../utils/retrieve-language'; 5 | import { createTempDirectory, removeTempDirectory } from '../utils/temp-dir'; 6 | 7 | /** 8 | * Service wrapping the `archiver` module: 9 | - easier zip creation 10 | - adding proper `Content-Type` header 11 | - easier adding an AsyncAPI document to the archive 12 | - easier stream finalization 13 | */ 14 | export class ArchiverService { 15 | public createZip(res?: Response) { 16 | const zip = archiver('zip', { zlib: { level: 9 } }); 17 | if (res) { 18 | zip.pipe(res); 19 | res.attachment('asyncapi.zip'); 20 | } 21 | return zip; 22 | } 23 | 24 | public appendDirectory(archive: Archiver, from: string, to: string) { 25 | archive.directory(from, to); 26 | } 27 | 28 | public appendAsyncAPIDocument(archive: Archiver, asyncapi: string, fileName = 'asyncapi') { 29 | asyncapi = JSON.stringify(asyncapi); 30 | const language = retrieveLangauge(asyncapi); 31 | if (language === 'yaml') { 32 | archive.append(asyncapi, { name: `${fileName}.yml` }); 33 | } else { 34 | archive.append(asyncapi, { name: `${fileName}.json`}); 35 | } 36 | } 37 | 38 | public async finalize(archive: Archiver) { 39 | await new Promise((resolve) => { 40 | // wait for end stream 41 | archive.on('end', resolve); 42 | archive.finalize(); 43 | }); 44 | } 45 | 46 | public createTempDirectory() { 47 | return createTempDirectory(); 48 | } 49 | 50 | public removeTempDirectory(tmpDir: string) { 51 | return removeTempDirectory(tmpDir); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/services/convert.service.ts: -------------------------------------------------------------------------------- 1 | import { convert } from '@asyncapi/converter'; 2 | 3 | import YAML from 'js-yaml'; 4 | 5 | import { AsyncAPIDocument, LAST_SPEC_VERSION, SpecsEnum } from '../interfaces'; 6 | import { ProblemException } from '../exceptions/problem.exception'; 7 | 8 | import type { ConvertVersion } from '@asyncapi/converter'; 9 | 10 | /** 11 | * Service providing `@asyncapi/converter` functionality. 12 | */ 13 | export class ConvertService { 14 | /** 15 | * Convert the given spec to the desired version and format. 16 | * @param spec AsyncAPI spec 17 | * @param language Language to convert to, YAML or JSON 18 | * @param version AsyncAPI spec version 19 | * @returns converted spec 20 | */ 21 | public async convert( 22 | spec: string | AsyncAPIDocument, 23 | version: SpecsEnum = LAST_SPEC_VERSION as SpecsEnum, 24 | language?: 'json' | 'yaml' | 'yml' 25 | ): Promise { 26 | if (version === 'latest') { 27 | version = LAST_SPEC_VERSION as SpecsEnum; 28 | } 29 | 30 | try { 31 | const asyncapiSpec = 32 | typeof spec === 'object' ? JSON.stringify(spec) : spec; 33 | const convertedSpec = convert(asyncapiSpec, version as ConvertVersion); 34 | 35 | if (!language) { 36 | return convertedSpec; 37 | } 38 | return this.convertToFormat(convertedSpec, language); 39 | } catch (err) { 40 | if (err instanceof ProblemException) { 41 | throw err; 42 | } 43 | 44 | throw new ProblemException({ 45 | type: 'internal-converter-error', 46 | title: 'Could not convert document', 47 | status: 422, 48 | detail: (err as Error).message, 49 | }); 50 | } 51 | } 52 | 53 | private convertToFormat( 54 | spec: string | Record, 55 | language: 'json' | 'yaml' | 'yml' 56 | ) { 57 | if (typeof spec === 'object') { 58 | spec = JSON.stringify(spec, undefined, 2); 59 | } 60 | 61 | try { 62 | if (language === 'json') { 63 | return this.convertToJSON(spec); 64 | } 65 | return this.convertToYaml(spec); 66 | } catch (err) { 67 | throw new ProblemException({ 68 | type: 'converter-output-format', 69 | title: `Could not transform output to ${language}`, 70 | status: 422, 71 | detail: (err as Error).message, 72 | }); 73 | } 74 | } 75 | 76 | private convertToJSON(spec: string) { 77 | // JSON or YAML String -> JS object 78 | const jsonContent = YAML.load(spec); 79 | // JS Object -> pretty JSON string 80 | return JSON.stringify(jsonContent, undefined, 2); 81 | } 82 | 83 | private convertToYaml(spec: string) { 84 | // Editor content -> JS object -> YAML string 85 | const jsonContent = YAML.load(spec); 86 | return YAML.dump(jsonContent); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/services/generator.service.ts: -------------------------------------------------------------------------------- 1 | // @ts-ignore 2 | import AsyncAPIGenerator from '@asyncapi/generator'; 3 | import { AsyncAPIDocument } from '@asyncapi/parser'; 4 | 5 | import { prepareParserConfig } from '../utils/parser'; 6 | 7 | /** 8 | * Service providing `@asyncapi/generate` functionality. 9 | */ 10 | export class GeneratorService { 11 | public async generate( 12 | asyncapi: AsyncAPIDocument | string, 13 | template: string, 14 | parameters: Record, 15 | destDir: string, 16 | parserOptions: ReturnType, 17 | ) { 18 | const generator = new AsyncAPIGenerator(template, destDir, { 19 | forceWrite: true, 20 | templateParams: parameters, 21 | }); 22 | 23 | if (typeof asyncapi === 'string') { 24 | await generator.generateFromString(asyncapi, parserOptions); 25 | } else if (asyncapi instanceof AsyncAPIDocument) { 26 | await generator.generate(asyncapi); 27 | } else { // object case 28 | await generator.generateFromString(JSON.stringify(asyncapi), parserOptions); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/services/tests/convert.service.test.ts: -------------------------------------------------------------------------------- 1 | import { ConvertService } from '../convert.service'; 2 | import { ProblemException } from '../../exceptions/problem.exception'; 3 | 4 | const validJsonAsyncAPI2_0_0 = { 5 | asyncapi: '2.0.0', 6 | info: { 7 | title: 'Super test', 8 | version: '1.0.0' 9 | }, 10 | channels: {} 11 | }; 12 | 13 | const validJsonAsyncAPI2_1_0 = { 14 | asyncapi: '2.1.0', 15 | info: { 16 | title: 'Super test', 17 | version: '1.0.0' 18 | }, 19 | channels: {} 20 | }; 21 | 22 | const validYamlAsyncAPI2_4_0 = ` 23 | asyncapi: 2.4.0 24 | info: 25 | title: Super test 26 | version: 1.0.0 27 | channels: {} 28 | `; 29 | 30 | describe('ConvertService', () => { 31 | const convertService = new ConvertService(); 32 | 33 | describe('.convert()', () => { 34 | it('should throw error that the converter cannot convert to a lower version', async () => { 35 | let err: ProblemException | null = null; 36 | try { 37 | await convertService.convert(validJsonAsyncAPI2_1_0, '2.0.0'); 38 | } catch (e) { 39 | err = e; 40 | } 41 | 42 | expect(err).toEqual(new ProblemException({ 43 | type: 'internal-converter-error', 44 | title: 'Could not convert document', 45 | status: 422, 46 | detail: 'Cannot downgrade from 2.1.0 to 2.0.0.', 47 | })); 48 | }); 49 | 50 | it('should pass when converting to 2.4.0 version', async () => { 51 | const converted = await convertService.convert(validJsonAsyncAPI2_0_0, '2.4.0'); 52 | 53 | expect(converted).toEqual({ 54 | asyncapi: '2.4.0', 55 | info: { 56 | title: 'Super test', 57 | version: '1.0.0' 58 | }, 59 | channels: {}, 60 | }); 61 | }); 62 | 63 | it('should pass when converting to latest version', async () => { 64 | const converted = await convertService.convert(validJsonAsyncAPI2_0_0); 65 | 66 | expect(converted).toEqual({ 67 | asyncapi: '2.6.0', 68 | info: { 69 | title: 'Super test', 70 | version: '1.0.0' 71 | }, 72 | channels: {}, 73 | }); 74 | }); 75 | 76 | it('should correctly convert JSON to YAML', async () => { 77 | const converted = await convertService.convert(validJsonAsyncAPI2_0_0, '2.4.0', 'yaml'); 78 | 79 | expect(converted).toEqual(validYamlAsyncAPI2_4_0.trimStart()); 80 | }); 81 | }); 82 | }); 83 | -------------------------------------------------------------------------------- /src/services/tests/generator.service.test.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import path from 'path'; 3 | 4 | import { GeneratorService } from '../generator.service'; 5 | import { createTempDirectory, removeTempDirectory } from '../../utils/temp-dir'; 6 | import { prepareParserConfig } from '../../utils/parser'; 7 | 8 | describe('GeneratorService', () => { 9 | const generatorService = new GeneratorService(); 10 | 11 | describe('.generate()', () => { 12 | it('should generate given template to the destination dir', async () => { 13 | const asyncapi = { 14 | asyncapi: '2.2.0', 15 | info: { 16 | title: 'Test Service', 17 | version: '1.0.0', 18 | }, 19 | channels: {}, 20 | }; 21 | const template = '@asyncapi/html-template'; 22 | const parameters = { 23 | version: '2.1.37', 24 | }; 25 | 26 | const tmpDir = await createTempDirectory(); 27 | try { 28 | await generatorService.generate( 29 | JSON.stringify(asyncapi), 30 | template, 31 | parameters, 32 | tmpDir, 33 | prepareParserConfig(), 34 | ); 35 | 36 | expect(fs.existsSync(path.join(tmpDir, 'template'))).toEqual(true); 37 | expect(fs.existsSync(path.join(tmpDir, 'template/index.html'))).toEqual(true); 38 | } catch (e: any) { 39 | await removeTempDirectory(tmpDir); 40 | } 41 | }); 42 | }); 43 | }); 44 | -------------------------------------------------------------------------------- /src/utils/ajv.ts: -------------------------------------------------------------------------------- 1 | import Ajv from 'ajv'; 2 | import addFormats from 'ajv-formats'; 3 | 4 | import type AjvCore from 'ajv/dist/core'; 5 | 6 | export function createAjvInstance(): AjvCore { 7 | const ajv = new Ajv({ 8 | allErrors: true, 9 | meta: true, 10 | strict: false, 11 | allowUnionTypes: true, 12 | logger: false, 13 | unicodeRegExp: false, 14 | }); 15 | addFormats(ajv); 16 | return ajv; 17 | } 18 | -------------------------------------------------------------------------------- /src/utils/app-openapi.ts: -------------------------------------------------------------------------------- 1 | import { promises as fs } from 'fs'; 2 | import path from 'path'; 3 | 4 | import YAML from 'js-yaml'; 5 | import $RefParser from '@apidevtools/json-schema-ref-parser'; 6 | 7 | let parsedOpenAPI = undefined; 8 | 9 | /** 10 | * Retrieve application's OpenAPI document. 11 | */ 12 | export async function getAppOpenAPI(): Promise { 13 | if (parsedOpenAPI) { 14 | return parsedOpenAPI; 15 | } 16 | 17 | const openaAPI = await fs.readFile(path.join(__dirname, '../../openapi.yaml'), 'utf-8'); 18 | parsedOpenAPI = YAML.load(openaAPI); 19 | // due to the fact that `@asyncapi/specs: 3.0.0` have moved to a new way of bundling schemas, it makes no sense to resolve the references for AsyncAPI specs 20 | parsedOpenAPI.components.schemas.AsyncAPIDocument.oneOf = { type: ['string', 'object'] }; 21 | const refParser = new $RefParser; 22 | await refParser.dereference(parsedOpenAPI); 23 | 24 | return parsedOpenAPI; 25 | } 26 | -------------------------------------------------------------------------------- /src/utils/logger.ts: -------------------------------------------------------------------------------- 1 | import config from 'config'; 2 | import fs from 'fs'; 3 | import path from 'path'; 4 | import winston from 'winston'; 5 | 6 | const logDir: string = path.join(__dirname, config.get('log.dir')); 7 | if (!fs.existsSync(logDir)) { 8 | fs.mkdirSync(logDir); 9 | } 10 | 11 | /* 12 | * Log Level 13 | * error: 0, warn: 1, info: 2, http: 3, verbose: 4, debug: 5, silly: 6 14 | */ 15 | const logger = winston.createLogger({ 16 | format: winston.format.combine( 17 | winston.format.timestamp({ 18 | format: 'YYYY-MM-DD HH:mm:ss', 19 | }), 20 | // Define log format 21 | winston.format.printf(({ timestamp, level, message }) => `${timestamp} ${level}: ${message}`), 22 | ), 23 | }); 24 | 25 | logger.add( 26 | new winston.transports.Console({ 27 | format: winston.format.combine(winston.format.splat(), winston.format.colorize()), 28 | }), 29 | ); 30 | 31 | const stream = { 32 | write: (message: string) => { 33 | logger.info(message.substring(0, message.lastIndexOf('\n'))); 34 | }, 35 | }; 36 | 37 | export { logger, stream }; -------------------------------------------------------------------------------- /src/utils/parser.ts: -------------------------------------------------------------------------------- 1 | import { registerSchemaParser, parse, ParserError } from '@asyncapi/parser'; 2 | import { Request } from 'express'; 3 | import ramlDtParser from '@asyncapi/raml-dt-schema-parser'; 4 | import openapiSchemaParser from '@asyncapi/openapi-schema-parser'; 5 | import avroSchemaParser from '@asyncapi/avro-schema-parser'; 6 | 7 | import { ProblemException } from '../exceptions/problem.exception'; 8 | 9 | registerSchemaParser(openapiSchemaParser); 10 | registerSchemaParser(ramlDtParser); 11 | registerSchemaParser(avroSchemaParser); 12 | 13 | function prepareParserConfig(req?: Request) { 14 | if (!req) { 15 | return { 16 | resolve: { 17 | file: false, 18 | }, 19 | }; 20 | } 21 | 22 | return { 23 | resolve: { 24 | file: false, 25 | http: { 26 | headers: { 27 | Cookie: req.header('Cookie'), 28 | }, 29 | withCredentials: true, 30 | }, 31 | }, 32 | path: 33 | req.header('x-asyncapi-base-url') || 34 | req.header('referer') || 35 | req.header('origin'), 36 | }; 37 | } 38 | 39 | const TYPES_400 = [ 40 | 'null-or-falsey-document', 41 | 'impossible-to-convert-to-json', 42 | 'invalid-document-type', 43 | 'invalid-json', 44 | 'invalid-yaml', 45 | ]; 46 | 47 | /** 48 | * Some error types have to be treated as 400 HTTP Status Code, another as 422. 49 | */ 50 | function retrieveStatusCode(type: string): number { 51 | if (TYPES_400.includes(type)) { 52 | return 400; 53 | } 54 | return 422; 55 | } 56 | 57 | /** 58 | * Merges fields from ParserError to ProblemException. 59 | */ 60 | function mergeParserError(error: ProblemException, parserError: any): ProblemException { 61 | if (parserError.detail) { 62 | error.set('detail', parserError.detail); 63 | } 64 | if (parserError.validationErrors) { 65 | error.set('validationErrors', parserError.validationErrors); 66 | } 67 | if (parserError.parsedJSON) { 68 | error.set('parsedJSON', parserError.parsedJSON); 69 | } 70 | if (parserError.location) { 71 | error.set('location', parserError.location); 72 | } 73 | if (parserError.refs) { 74 | error.set('refs', parserError.refs); 75 | } 76 | return error; 77 | } 78 | 79 | function tryConvertToProblemException(err: any) { 80 | let error = err; 81 | if (error instanceof ParserError) { 82 | const typeName = err.type.replace( 83 | 'https://github.com/asyncapi/parser-js/', 84 | '' 85 | ); 86 | error = new ProblemException({ 87 | type: typeName, 88 | title: err.title, 89 | status: retrieveStatusCode(typeName), 90 | }); 91 | mergeParserError(error, err); 92 | } 93 | 94 | return error; 95 | } 96 | 97 | export { 98 | prepareParserConfig, 99 | parse, 100 | mergeParserError, 101 | retrieveStatusCode, 102 | tryConvertToProblemException, 103 | }; 104 | -------------------------------------------------------------------------------- /src/utils/retrieve-language.ts: -------------------------------------------------------------------------------- 1 | export function retrieveLangauge(content: string): 'json' | 'yaml' { 2 | if (content.trim()[0] === '{') { 3 | return 'json'; 4 | } 5 | return 'yaml'; 6 | } -------------------------------------------------------------------------------- /src/utils/temp-dir.ts: -------------------------------------------------------------------------------- 1 | import os from 'os'; 2 | import fs, { promises as fsp } from 'fs'; 3 | import path from 'path'; 4 | import { v4 as uuidv4 } from 'uuid'; 5 | 6 | import { logger } from './logger'; 7 | 8 | export function createTempDirectory() { 9 | return fsp.mkdtemp(path.join(os.tmpdir(), uuidv4())); 10 | } 11 | 12 | export async function removeTempDirectory(tmpDir: string) { 13 | try { 14 | tmpDir && fs.existsSync(tmpDir) && await fsp.rm(tmpDir, { recursive: true }); 15 | } catch (e) { 16 | logger.error(`An error has occurred while removing the temp folder at ${tmpDir}. Please remove it manually. Error: ${e}`); 17 | } 18 | } -------------------------------------------------------------------------------- /src/utils/tests/app-openapi.test.ts: -------------------------------------------------------------------------------- 1 | import { getAppOpenAPI } from '../app-openapi'; 2 | 3 | describe('getAppOpenAPI()', () => { 4 | test('should return OpenAPI document as JSON', async () => { 5 | const openapi = await getAppOpenAPI(); 6 | expect(openapi.openapi).toEqual('3.1.0'); 7 | expect(openapi.info.title).toEqual('AsyncAPI Server API'); 8 | }); 9 | 10 | test('should return always this same instance of JSON', async () => { 11 | const openapi1 = await getAppOpenAPI(); 12 | const openapi2 = await getAppOpenAPI(); 13 | // assert references 14 | expect(openapi1 === openapi2).toEqual(true); 15 | }); 16 | }); -------------------------------------------------------------------------------- /src/utils/tests/retrieve-language.test.ts: -------------------------------------------------------------------------------- 1 | import { retrieveLangauge } from '../retrieve-language'; 2 | 3 | describe('retrieveLangauge()', () => { 4 | test('should check that content is yaml', () => { 5 | const result = retrieveLangauge('asyncapi: 2.2.0\nfoobar: barfoo\n'); 6 | expect(result).toEqual('yaml'); 7 | }); 8 | 9 | test('should check that content is json', () => { 10 | const result = retrieveLangauge('{"asyncapi": "2.2.0", "foobar": "barfoo"}'); 11 | expect(result).toEqual('json'); 12 | }); 13 | 14 | test('should check that content is yaml - fallback for non json content', () => { 15 | const result = retrieveLangauge(''); 16 | expect(result).toEqual('yaml'); 17 | }); 18 | }); -------------------------------------------------------------------------------- /src/utils/tests/temp-dir.test.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import { createTempDirectory, removeTempDirectory } from '../temp-dir'; 3 | 4 | describe('createTempDirectory() & removeTempDirectory()', () => { 5 | test('should create and then remove temp folder', async () => { 6 | // create dir 7 | const tempDir = await createTempDirectory(); 8 | expect(fs.existsSync(tempDir)).toEqual(true); 9 | 10 | // remove dir 11 | await removeTempDirectory(tempDir); 12 | expect(fs.existsSync(tempDir)).toEqual(false); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /tests/jest.setup.ts: -------------------------------------------------------------------------------- 1 | import path from 'path'; 2 | 3 | // for `config` module 4 | process.env['NODE_CONFIG_DIR'] = path.join(__dirname, '../src/configs'); 5 | -------------------------------------------------------------------------------- /tests/test.controller.ts: -------------------------------------------------------------------------------- 1 | import { NextFunction, Request, Response, Router } from 'express'; 2 | 3 | import { Controller } from '../src/interfaces'; 4 | 5 | interface Path { 6 | path: string, 7 | method: 'all' | 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options' | 'head', 8 | callback: (req: Request, res: Response, next: NextFunction) => any; 9 | middlewares?: Array<(req: Request, res: Response, next: NextFunction) => any>; 10 | } 11 | 12 | export function createTestController(paths: Path | Path[]) { 13 | return class implements Controller { 14 | public basepath = '/'; 15 | 16 | public boot(): Router { 17 | const router = Router(); 18 | 19 | const p = Array.isArray(paths) ? paths : [paths]; 20 | p.forEach(path => { 21 | router[path.method]( 22 | path.path, 23 | ...(path.middlewares || []), 24 | path.callback, 25 | ); 26 | }); 27 | 28 | return router; 29 | } 30 | }; 31 | } 32 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "./dist", 4 | "module": "commonjs", 5 | "target": "es6", 6 | "rootDir": "./src", 7 | "resolveJsonModule": true, 8 | "esModuleInterop": true, 9 | }, 10 | "include": ["src/*.ts", "src/**/*.ts"], 11 | "exclude": ["src/*.test.ts", "src/**/*.test.ts", "src/*.spec.ts", "src/**/*.spec.ts", "tests/*.ts", "tests/**/*.ts"] 12 | } -------------------------------------------------------------------------------- /tsconfig.test.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "include": ["src/*.ts", "src/**/*.ts", "tests/*.ts", "tests/**/*.ts"], 4 | } --------------------------------------------------------------------------------