├── .circleci └── config.yml ├── .editorconfig ├── .eslintrc.js ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── dependabot.yml └── workflows │ └── lint.yml ├── .gitignore ├── .node-version ├── .releaserc ├── BUILDING.md ├── CONTRIBUTING.md ├── CONVENTIONAL_COMMITS.md ├── LICENSE.md ├── README.md ├── RELEASING.md ├── VERSIONING.md ├── jest.config.js ├── package-lock.json ├── package.json ├── src ├── error.ts ├── index.ts ├── router.test.ts ├── router.ts ├── server.test.ts ├── server.ts └── transports │ ├── http.test.ts │ ├── http.ts │ ├── https.test.ts │ ├── https.ts │ ├── index.ts │ ├── ipc.test.ts │ ├── ipc.ts │ ├── server-transport.test.ts │ ├── server-transport.ts │ ├── websocket.test.ts │ └── websocket.ts ├── test-cert ├── server.cert └── server.key ├── tsconfig.json └── tsfmt.json /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | aliases: 4 | # ------------------------- 5 | # ALIASES: Caches 6 | # ------------------------- 7 | - &restore-deps-cache 8 | key: deps-cache-{{ checksum "package.json" }} 9 | 10 | - &save-deps-cache 11 | key: deps-cache-{{ checksum "package.json" }} 12 | paths: 13 | - ~/server-js/node_modules 14 | 15 | # ------------------------- 16 | # ALIASES: Branch Filters 17 | # ------------------------- 18 | - &filter-only-master 19 | branches: 20 | only: master 21 | - &filter-only-semantic-pr 22 | branches: 23 | only: /^(pull|dependabot|fix|feat)\/.*$/ 24 | - &filter-only-fork-pr 25 | branches: 26 | only: /^pull\/.*$/ 27 | 28 | defaults: &defaults 29 | working_directory: ~/server-js 30 | docker: 31 | - image: cimg/node:20.12.1 32 | jobs: 33 | test: 34 | <<: *defaults 35 | steps: 36 | - checkout 37 | - restore_cache: *restore-deps-cache 38 | - run: npm install 39 | - run: npm install codecov 40 | - run: npm test 41 | - run: ./node_modules/.bin/codecov 42 | - save_cache: *save-deps-cache 43 | 44 | build: 45 | <<: *defaults 46 | steps: 47 | - checkout 48 | - restore_cache: *restore-deps-cache 49 | - run: npm install 50 | - run: npm run build 51 | - save_cache: *save-deps-cache 52 | 53 | release: 54 | <<: *defaults 55 | steps: 56 | - checkout 57 | - restore_cache: *restore-deps-cache 58 | - run: npm install 59 | - run: npm run build 60 | - run: npm install semantic-release @semantic-release/changelog @semantic-release/git @semantic-release/github @semantic-release/npm @semantic-release/commit-analyzer @semantic-release/release-notes-generator @qiwi/semantic-release-gh-pages-plugin 61 | - run: git checkout package.json package-lock.json 62 | - run: ./node_modules/.bin/semantic-release 63 | - save_cache: *save-deps-cache 64 | 65 | workflows: 66 | version: 2 67 | analysis: 68 | jobs: 69 | - test: 70 | filters: *filter-only-semantic-pr 71 | - build: 72 | filters: *filter-only-semantic-pr 73 | requires: 74 | - test 75 | 76 | release: 77 | jobs: 78 | - test: 79 | filters: *filter-only-master 80 | - build: 81 | filters: *filter-only-master 82 | - hold: 83 | filters: *filter-only-master 84 | type: approval 85 | requires: 86 | - test 87 | - build 88 | - release: 89 | filters: *filter-only-master 90 | context: open-rpc-deployer 91 | requires: 92 | - hold 93 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: http://EditorConfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | # Unix-style newlines with a newline ending every file 7 | [*] 8 | indent_style = space 9 | indent_size = 2 10 | tab_width = 2 11 | end_of_line = lf 12 | charset = utf-8 13 | trim_trailing_whitespace = true 14 | insert_final_newline = true 15 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | parser: '@typescript-eslint/parser', 4 | plugins: [ 5 | '@typescript-eslint', 6 | ], 7 | extends: [ 8 | 'eslint:recommended', 9 | 'plugin:@typescript-eslint/eslint-recommended', 10 | 'plugin:@typescript-eslint/recommended', 11 | ], 12 | }; 13 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: npm 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | open-pull-requests-limit: 10 8 | ignore: 9 | - dependency-name: "@open-rpc/meta-schema" 10 | versions: 11 | - 1.14.1 12 | - dependency-name: "@types/node" 13 | versions: 14 | - 14.14.30 15 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | on: 2 | pull_request: 3 | 4 | jobs: 5 | lint: 6 | name: lint 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v1 10 | - uses: actions/setup-node@v4 11 | - name: npm install 12 | run: npm install 13 | - name: lint 14 | run: npm run lint 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **/node_modules 2 | **/build 3 | **/coverage 4 | **/docs 5 | **/.idea 6 | coverage 7 | docs 8 | .DS_Store 9 | test 10 | src/method-handlers -------------------------------------------------------------------------------- /.node-version: -------------------------------------------------------------------------------- 1 | 20.12.1 2 | -------------------------------------------------------------------------------- /.releaserc: -------------------------------------------------------------------------------- 1 | { 2 | "tagFormat": "${version}" 3 | } 4 | -------------------------------------------------------------------------------- /BUILDING.md: -------------------------------------------------------------------------------- 1 | # Building 2 | 3 | The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [BCP 14](https://tools.ietf.org/html/bcp14) [RFC2119](https://tools.ietf.org/html/rfc2119) [RFC8174](https://tools.ietf.org/html/rfc8174) when, and only when, they appear in all capitals, as shown here. 4 | 5 | This document is licensed under [The Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.html). 6 | 7 | ## Introduction 8 | 9 | This document is to describe the functionality a project MUST provide in terms of creating build artifacts. It also describes the structure in which project's MUST write build artifacts in. 10 | 11 | A project MUST provide: 12 | 13 | - a folder name convention for build artifacts 14 | - a folder structure for the above-mentioned build artifacts folder 15 | - a list of targets 16 | - a file called `bin/build.{target}.{ext}` to target each of the build targets 17 | - a build pipeline given the above pretext 18 | 19 | The purpose of having a uniform way of producing a build is that we may ALL produce builds for any of the projects, making the onramp for new developers less steep, while still maintaining an exceptionally high level of quality. 20 | 21 | The projects should follow the 'architecture as code' principle - and should require a very minimal set of dependencies. 22 | 23 | It is the responsibilty of the build tooling to write artifacts to the appropriate location as outlined in this specification. 24 | 25 | ## Build Folder Name 26 | 27 | The cannonical folder for builds SHALL be named `build` and be located at the root of the project repository. 28 | Each project MUST `git ignore` the `build` folder. 29 | 30 | ## Build Folder Structure 31 | 32 | Files and folder names MUST be lowercase. 33 | The result of the build process should create a folder structure as follows: 34 | 35 | ``` 36 | . 37 | └── build 38 | └── {target} 39 | └── {project-name}.{ext} 40 | ``` 41 | 42 | 43 | Below is an example: 44 | ``` 45 | . 46 | └── build 47 | └── windows 48 | └── my-build.exe 49 | ``` 50 | 51 | ## Build Targets 52 | 53 | Below is a list of suggested targets for a project 54 | 1. windows 55 | 2. linux 56 | 3. macos 57 | 58 | ## Build script 59 | 60 | Each release target MUST have a `bin/build.{target}.{ext}` file. 61 | 62 | The result of this is that every project MUST produce a build for each target when the following command is invoked: 63 | 64 | ``` 65 | bin/build.{target}.{ext} 66 | ``` 67 | 68 | The file MUST be placed in the project's `bin` directory. 69 | 70 | ## Build Pipeline 71 | 72 | ### Building targets 73 | 74 | `bin/build.{target}.{ext}` should create builds for each of the targets, and place the build artifacts in a folder structure outlined above. 75 | 76 | ### Windows 77 | 78 | ``` 79 | bin/build.windows.bat 80 | ``` 81 | 82 | ### Linux 83 | 84 | ``` 85 | bin/build.linux.sh 86 | ``` 87 | 88 | ### Macos 89 | 90 | ``` 91 | bin/build.macos.sh 92 | ``` 93 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | > This document is inspired by [elasticsearch/CONTRIBUTING.md](https://github.com/elastic/elasticsearch/blob/master/CONTRIBUTING.md) 4 | 5 | Adding a `CONTRIBUTING.md` to a Github repository enables a link to that file in the pull request or create an issue page. This document should guide potential contributors toward making a successful and meaningful impact on the project, and can save maintainers time and hassle caused by improper pull requests and issues. You can learn more about the features that are enabled by Github when this file is present [here](https://help.github.com/articles/setting-guidelines-for-repository-contributors/). 6 | 7 | ## How to contribute 8 | 9 | There are many ways to contribute, from writing tutorials or blog posts, improving the documentation, [submitting Github issues](https://help.github.com/articles/creating-an-issue/), bug reports, feature requests and writing code. 10 | 11 | ## License 12 | 13 | This repository uses the [The Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.html). 14 | 15 | ## Bug reports 16 | 17 | If you think you've found a bug in the software, first make sure you're testing against the *latest* version of the software -- your issue may have been fixed already. If it's not, please check out the issues list on Github and search for similar issues that have already been opened. If there are no issues then please [submit a Github issue](https://help.github.com/articles/creating-an-issue/). 18 | 19 | If you can provide a small test case it would greatly help the reproduction of a bug, as well as a a screenshot, and any other information you can provide. 20 | 21 | 22 | ## Feature Requests 23 | 24 | If there are features that do not exist yet, we are definitely open to feature requests and detailed proposals. [Open an issue](https://help.github.com/articles/creating-an-issue/) on our Github which describes the feature or proposal in detail, answer questions like why? how? 25 | 26 | ## Contributing Code and Documentation Changes 27 | 28 | Bug fixes, patches and new features are welcome. Please find or open an issue about it first. Talk about what exactly want to do, someone may already be working on it, or there might be some issues that you need to be aware of before implementing the fix. 29 | 30 | There are many ways to fix a problem and it is important to find the best approach before writing a ton of code. 31 | 32 | ##### Documentation Changes 33 | 34 | For small documentation changes and fixes, these can be done quickly following this video guide on [how to contribute to Open Source in 1 minute on Github](https://www.youtube.com/watch?v=kRYk1-yKwWs). 35 | 36 | ### Forking the repository 37 | 38 | [How to fork a repository](https://help.github.com/articles/fork-a-repo/). 39 | 40 | ### Submitting changes 41 | 42 | 1. Review & Test changes 43 | * If the code changed, then test it. If documentation changed, then preview the rendered Markdown. 44 | 2. Commiting 45 | * Follow the [Conventional Commits](CONVENTIONAL_COMMITS.md) guidelines to create a commit message. 46 | 3. Sign the CLA 47 | * Make sure you've signed the repository's Contributor License Agreement. We are not asking you to assign copyright to us, but to give us the right to distribute your code without restriction. We ask this of all contributors in order to assure our users of the origin and continuing existence of the code. You only need to sign the CLA once. 48 | 4. Submit a pull request 49 | * Push local changes to your forked repository and make a pull request. Follow the [Convention Commits](CONVENTIONAL_COMMITS.md) guidelines for naming Github pull requests and what to put in the body. 50 | 51 | 52 | ## Building 53 | 54 | Follow the build process is outlined in [BUILDING.md](BUILDING.md) to create a build. 55 | 56 | 57 | ## Releasing 58 | 59 | Follow the release process is outlined in [RELEASING.md](RELEASING.md) to create a release. 60 | 61 | 62 | -------------------------------------------------------------------------------- /CONVENTIONAL_COMMITS.md: -------------------------------------------------------------------------------- 1 | # Conventional Commits 1.0.0-beta.2 2 | 3 | > This spec is a direct copy from [http://conventionalcommits.org](http://conventionalcommits.org). It lives here as a reference document for new contributors. 4 | 5 | ## Summary 6 | 7 | The [Conventional Commits](http://conventionalcommits.org) specification is a lightweight convention on top of commit messages. 8 | It provides an easy set of rules for creating an explicit commit history; 9 | which makes it easier to write automated tools on top of. 10 | This convention dovetails with [SemVer](http://semver.org), 11 | by describing the features, fixes, and breaking changes made in commit messages. 12 | 13 | The commit message should be structured as follows: 14 | 15 | --- 16 | 17 | ``` 18 | [optional scope]: 19 | 20 | [optional body] 21 | 22 | [optional footer] 23 | ``` 24 | --- 25 | 26 |
27 | The commit contains the following structural elements, to communicate intent to the 28 | consumers of your library: 29 | 30 | 1. **fix:** a commit of the _type_ `fix` patches a bug in your codebase (this correlates with [`PATCH`](http://semver.org/#summary) in semantic versioning). 31 | 1. **feat:** a commit of the _type_ `feat` introduces a new feature to the codebase (this correlates with [`MINOR`](http://semver.org/#summary) in semantic versioning). 32 | 1. **BREAKING CHANGE:** a commit that has the text `BREAKING CHANGE:` at the beginning of its optional body or footer section introduces a breaking API change (correlating with [`MAJOR`](http://semver.org/#summary) in semantic versioning). 33 | A BREAKING CHANGE can be part of commits of any _type_. 34 | 1. Others: commit _types_ other than `fix:` and `feat:` are allowed, for example [commitlint-config-conventional](https://github.com/marionebl/commitlint/tree/master/%40commitlint/config-conventional) (based on the [the Angular convention](https://github.com/angular/angular/blob/22b96b9/CONTRIBUTING.md#-commit-message-guidelines)) recommends `chore:`, `docs:`, `style:`, `refactor:`, `perf:`, `test:`, and others. 35 | We also recommend `improvement` for commits that improve a current implementation without adding a new feature or fixing a bug. 36 | Notice these types are not mandated by the conventional commits specification, and have no implicit effect in semantic versioning (unless they include a BREAKING CHANGE). 37 |
38 | A scope may be provided to a commit's type, to provide additional contextual information and is contained within parenthesis, e.g., `feat(parser): add ability to parse arrays`. 39 | 40 | ## Examples 41 | 42 | ### Commit message with description and breaking change in body 43 | ``` 44 | feat: allow provided config object to extend other configs 45 | 46 | BREAKING CHANGE: `extends` key in config file is now used for extending other config files 47 | ``` 48 | 49 | ### Commit message with no body 50 | ``` 51 | docs: correct spelling of CHANGELOG 52 | ``` 53 | 54 | ### Commit message with scope 55 | ``` 56 | feat(lang): added polish language 57 | ``` 58 | 59 | ### Commit message for a fix using an (optional) issue number. 60 | ``` 61 | fix: minor typos in code 62 | 63 | see the issue for details on the typos fixed 64 | 65 | fixes issue #12 66 | ``` 67 | ## Specification 68 | 69 | The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in [RFC 2119](https://www.ietf.org/rfc/rfc2119.txt). 70 | 71 | 1. Commits MUST be prefixed with a type, which consists of a noun, `feat`, `fix`, etc., followed by a colon and a space. 72 | 1. The type `feat` MUST be used when a commit adds a new feature to your application or library. 73 | 1. The type `fix` MUST be used when a commit represents a bug fix for your application. 74 | 1. An optional scope MAY be provided after a type. A scope is a phrase describing a section of the codebase enclosed in parenthesis, e.g., `fix(parser):` 75 | 1. A description MUST immediately follow the type/scope prefix. 76 | The description is a short description of the code changes, e.g., _fix: array parsing issue when multiple spaces were contained in string._ 77 | 1. A longer commit body MAY be provided after the short description, providing additional contextual information about the code changes. The body MUST begin one blank line after the description. 78 | 1. A footer MAY be provided one blank line after the body. 79 | The footer SHOULD contain additional issue references about the code changes (such as the issues it fixes, e.g.,`Fixes #13`). 80 | 1. Breaking changes MUST be indicated at the very beginning of the footer or body section of a commit. A breaking change MUST consist of the uppercase text `BREAKING CHANGE`, followed by a colon and a space. 81 | 1. A description MUST be provided after the `BREAKING CHANGE: `, describing what has changed about the API, e.g., _BREAKING CHANGE: environment variables now take precedence over config files._ 82 | 1. The footer MUST only contain `BREAKING CHANGE`, external links, issue references, and other meta-information. 83 | 1. Types other than `feat` and `fix` MAY be used in your commit messages. 84 | 85 | ## Why Use Conventional Commits 86 | 87 | * Automatically generating CHANGELOGs. 88 | * Automatically determining a semantic version bump (based on the types of commits landed). 89 | * Communicating the nature of changes to teammates, the public, and other stakeholders. 90 | * Triggering build and publish processes. 91 | * Making it easier for people to contribute to your projects, by allowing them to explore 92 | a more structured commit history. 93 | 94 | ## FAQ 95 | 96 | ### How should I deal with commit messages in the initial development phase? 97 | 98 | We recommend that you proceed as if you've an already released product. Typically *somebody*, even if its your fellow software developers, is using your software. They'll want to know what's fixed, what breaks etc. 99 | 100 | ### Are the types in the commit title uppercase or lowercase? 101 | 102 | Any casing may be used, but it's best to be consistent. 103 | 104 | ### What do I do if the commit conforms to more than one of the commit types? 105 | 106 | Go back and make multiple commits whenever possible. Part of the benefit of Conventional Commits is its ability to drive us to make more organized commits and PRs. 107 | 108 | ### Doesn’t this discourage rapid development and fast iteration? 109 | 110 | It discourages moving fast in a disorganized way. It helps you be able to move fast long term across multiple projects with varied contributors. 111 | 112 | ### Might Conventional Commits lead developers to limit the type of commits they make because they'll be thinking in the types provided? 113 | 114 | Conventional Commits encourages us to make more of certain types of commits such as fixes. Other than that, the flexibility of Conventional Commits allows your team to come up with their own types and change those types over time. 115 | 116 | ### How does this relate to SemVer? 117 | 118 | `fix` type commits should be translated to `PATCH` releases. `feat` type commits should be translated to `MINOR` releases. Commits with `BREAKING CHANGE` in the commits, regardless of type, should be translated to `MAJOR` releases. 119 | 120 | ### How should I version my extensions to the Conventional Commits Specification, e.g. `@jameswomack/conventional-commit-spec`? 121 | 122 | We recommend using SemVer to release your own extensions to this specification (and 123 | encourage you to make these extensions!) 124 | 125 | ### What do I do if I accidentally use the wrong commit type? 126 | 127 | #### When you used a type that's of the spec but not the correct type, e.g. `fix` instead of `feat` 128 | 129 | Prior to merging or releasing the mistake, we recommend using `git rebase -i` to edit the commit history. After release, the cleanup will be different according to what tools and processes you use. 130 | 131 | #### When you used a type *not* of the spec, e.g. `feet` instead of `feat` 132 | 133 | In a worst case scenario, it's not the end of the world if a commit lands that does not meet the conventional commit specification. It simply means that commit will be missed by tools that are based on the spec. 134 | 135 | ### Do all my contributors need to use the conventional commit specification? 136 | 137 | No! If you use a squash based workflow on Git lead maintainers can cleanup the commit messages as they're merged—adding no workload to casual committers. 138 | A common workflow for this is to have your git system automatically squash commits from a pull request and present a form for the lead maintainer to enter the proper git commit message for the merge. 139 | 140 | ## About 141 | 142 | The Conventional Commit specification is inspired by, and based heavily on, the [Angular Commit Guidelines](https://github.com/angular/angular/blob/22b96b9/CONTRIBUTING.md#-commit-message-guidelines). 143 | 144 | The first draft of this specification has been written in collaboration with some of the folks contributing to: 145 | 146 | * [conventional-changelog](https://github.com/conventional-changelog/conventional-changelog): a set of tools for parsing conventional commit messages from git histories. 147 | * [bumped](https://bumped.github.io): a tool for releasing software that makes it easy to perform actions before and after releasing a new version of your software. 148 | * [unleash](https://github.com/netflix/unleash): a tool for automating the software release and publishing lifecycle. 149 | * [lerna](https://github.com/lerna/lerna): a tool for managing monorepos, which grew out of the Babel project. 150 | 151 | ## Tooling for Conventional Commits 152 | 153 | * [conform](https://github.com/autonomy/conform): a tool that can be used to enforce policies on git repositories, including conventional commits. 154 | 155 | ## Projects Using Conventional Commits 156 | 157 | * [yargs](https://github.com/yargs/yargs): everyone's favorite pirate themed command line argument parser. 158 | * [istanbuljs](https://github.com/istanbuljs/istanbuljs): a collection of open-source tools and libraries for adding test coverage to your JavaScript tests. 159 | * [standard-version](https://github.com/conventional-changelog/standard-version): Automatic versioning and CHANGELOG management, using GitHub's new squash button and the recommended Conventional Commits workflow. 160 | * [uPortal-home](https://github.com/UW-Madison-DoIT/angularjs-portal) and [uPortal-application-framework](https://github.com/UW-Madison-DoIT/uw-frame): Optional supplemental user interface enhancing [Apereo uPortal](https://www.apereo.org/projects/uportal). 161 | * [massive.js](https://github.com/dmfay/massive-js): A data access library for Node and PostgreSQL. 162 | * [electron](https://github.com/electron/electron): Build cross-platform desktop apps with JavaScript, HTML, and CSS. 163 | * [scroll-utility](https://github.com/LeDDGroup/scroll-utility): A simple to use scroll utility package for centering elements, and smooth animations 164 | * [Blaze UI](https://github.com/BlazeUI/blaze): Framework-free open source modular toolkit. 165 | 166 | [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) 167 | 168 | _want your project on this list?_ [send a pull request](https://github.com/conventional-changelog/conventionalcommits.org/pulls). 169 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 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 [yyyy] [name of copyright owner] 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 | # OpenRPC Server JS 2 | 3 |
4 | 5 | CircleCI branch 6 | 7 | Dependabot status 8 | npm 9 | GitHub release 10 | GitHub commits since latest release 11 | 12 |
13 | 14 | JSON-RPC 2.0 + OpenRPC Server implementation that supports multiple transport protocols. Built to run with node 10+. 15 | 16 | Need help or have a question? Join us on [Discord](https://discord.gg/gREUKuF)! 17 | 18 | ## Features 19 | 20 | - [x] Multiple Transports 21 | - [x] HTTP 22 | - [x] HTTPS1/2 23 | - [x] WebSockets 24 | - [x] IPC 25 | - [x] UDP 26 | - [x] TCP 27 | - [x] Automatically Validate JSON Schemas for [ContentDescriptor#schemas](https://spec.open-rpc.org/#content-descriptor-schema) [MethodObject#params](https://spec.open-rpc.org/#method-result). 28 | - [x] CLI to start a server by configuration 29 | 30 | ## How to Use 31 | 32 | install server, and optionally schema-utils-js if you want to dereference/validate the open-rpc document before running. 33 | ```bash 34 | npm install --save @open-rpc/server-js @open-rpc/schema-utils-js 35 | ``` 36 | 37 | Write an open-rpc document describing your service 38 | `./src/openrpc.json` 39 | see: https://raw.githubusercontent.com/open-rpc/examples/master/service-descriptions/simple-math-openrpc.json 40 | or write your own in [playground](https://playground.open-rpc.org/). 41 | 42 | 43 | For each of the methods, create a function that has the same name 44 | `src/method-mapping` 45 | ```typescript 46 | import { MethodMapping } from "@open-rpc/server-js/build/router"; 47 | export const methodMapping: MethodMapping = { 48 | addition: (a: number, b: number) => a + b, 49 | subtraction: (a: number, b: number) => a - b 50 | }; 51 | export default methodMapping; 52 | ``` 53 | 54 | Create a server with the methods and the document, serve it over http and websocket 55 | `src/server.ts` 56 | ```typescript 57 | import { Server, ServerOptions } from "@open-rpc/server-js"; 58 | import { HTTPServerTransportOptions } from "@open-rpc/server-js/build/transports/http"; 59 | import { WebSocketServerTransportOptions } from "@open-rpc/server-js/build/transports/websocket"; 60 | import { OpenrpcDocument } from "@open-rpc/meta-schema"; 61 | import { parseOpenRPCDocument } from "@open-rpc/schema-utils-js"; 62 | import methodMapping from "./method-mapping"; 63 | import doc from "./openrpc.json"; 64 | 65 | export async function start() { 66 | const serverOptions: ServerOptions = { 67 | openrpcDocument: await parseOpenRPCDocument(doc as OpenrpcDocument), 68 | transportConfigs: [ 69 | { 70 | type: "HTTPTransport", 71 | options: { 72 | port: 3330, 73 | middleware: [], 74 | } as HTTPServerTransportOptions, 75 | }, 76 | { 77 | type: "WebSocketTransport", 78 | options: { 79 | port: 3331, 80 | middleware: [], 81 | } as WebSocketServerTransportOptions, 82 | }, 83 | ], 84 | methodMapping, 85 | }; 86 | 87 | console.log("Starting Server"); // tslint:disable-line 88 | const s = new Server(serverOptions); 89 | 90 | s.start(); 91 | } 92 | ``` 93 | 94 | #### Lower Level Bits 95 | 96 | ##### Creating Routers 97 | 98 | ###### using method mapping and OpenRPC document 99 | 100 | ```typescript 101 | import { types } from "@open-rpc/meta-schema"; 102 | import { Router } from "@open-rpc/server-js"; 103 | 104 | const openrpcDocument = { 105 | openrpc: "1.0.0", 106 | info: { 107 | title: "node-json-rpc-server example", 108 | version: "1.0.0" 109 | }, 110 | methods: [ 111 | { 112 | name: "addition", 113 | params: [ 114 | { name: "a", schema: { type: "integer" } }, 115 | { name: "b", schema: { type: "integer" } } 116 | ], 117 | result: { 118 | { name: "c", schema: { type: "integer" } } 119 | } 120 | } 121 | ] 122 | } as types.OpenRPC; 123 | 124 | const methodHandlerMapping = { 125 | addition: (a: number, b: number) => Promise.resolve(a + b) 126 | }; 127 | 128 | const router = new Router(openrpcDocument, methodHandlerMapping); 129 | ``` 130 | 131 | ###### mock mode 132 | 133 | ```typescript 134 | const router = new Router(openrpcDocument, { mockMode: true }); 135 | ``` 136 | 137 | ##### Creating Transports 138 | 139 | ###### IPC 140 | 141 | ```typescript 142 | import { TCPIPCServerTranport, UDPIPCServerTranport } from "@open-rpc/server-js"; 143 | 144 | const ipcOptions = { maxConnetions: 20 }; // https://www.npmjs.com/package/node-ipc#ipc-config 145 | const TCPIPCOptions = { ...ipcOptions, networkPort: 4343 }; 146 | const UDPIPCOptions = { ...ipcOptions, networkPort: 4343, udp: true }; 147 | 148 | const tcpIpcTransport = new IPCServerTranport(TCPIPCTransportOptions); 149 | const UdpIpcTransport = new IPCServerTranport(UDPIPCTransportOptions); 150 | ``` 151 | 152 | ###### HTTP/S 153 | 154 | ``` 155 | import { HTTPServerTransport, HTTPSServerTransport } from "@open-rpc/server-js"; 156 | import express from "express"; 157 | 158 | const existingApp = express(); 159 | 160 | const httpOptions = { 161 | middleware: [ cors({ origin: "*" }) ], 162 | port: 4345, 163 | app: existingApp, // optional existing express/connect app 164 | }; 165 | const httpsOptions = { // extends https://nodejs.org/api/https.html#https_https_createserver_options_requestlistener 166 | middleware: [ cors({ origin: "*" }) ], 167 | port: 4346, 168 | key: await fs.readFile("test/fixtures/keys/agent2-key.pem"), 169 | cert: await fs.readFile("test/fixtures/keys/agent2-cert.pem"), 170 | ca: fs.readFileSync("ssl/ca.crt") 171 | }; 172 | 173 | const httpTransport = new HTTPServerTransport(httpOptions); 174 | const httpsTransport = new HTTPSServerTransport(httpsOptions); // Defaults to using HTTP2, allows HTTP1. 175 | ``` 176 | 177 | ###### WebSockets 178 | 179 | ``` 180 | import { WebSocketServerTransport } from "@open-rpc/server-js"; 181 | 182 | const webSocketFromHttpsOptions = { // extends https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback 183 | server: httpsTransport.server 184 | }; 185 | 186 | const webSocketOptions = { // extends https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback 187 | port: 4347 188 | }; 189 | const wsFromHttpsTransport = new WebSocketServerTransport(webSocketFromHttpsOptions); // Accepts http transport as well. 190 | const wsTransport = new WebSocketServerTransport(webSocketOptions); // Accepts http transport as well. 191 | ``` 192 | 193 | ###### Add components as you go 194 | ``` 195 | const server = new Server(); 196 | server.start(); 197 | 198 | server.addTransport(httpsTransport); // will be started immediately 199 | server.setRouter(router); 200 | server.addTransports([ wsTransport, wsFromHttpsTransport, httpsTransport ]); // will be started immediately. 201 | ``` 202 | 203 | ### Contributing 204 | 205 | How to contribute, build and release are outlined in [CONTRIBUTING.md](CONTRIBUTING.md), [BUILDING.md](BUILDING.md) and [RELEASING.md](RELEASING.md) respectively. Commits in this repository follow the [CONVENTIONAL_COMMITS.md](CONVENTIONAL_COMMITS.md) specification. 206 | -------------------------------------------------------------------------------- /RELEASING.md: -------------------------------------------------------------------------------- 1 | # Releasing 2 | 3 | The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [BCP 14](https://tools.ietf.org/html/bcp14) [RFC2119](https://tools.ietf.org/html/rfc2119) [RFC8174](https://tools.ietf.org/html/rfc8174) when, and only when, they appear in all capitals, as shown here. 4 | 5 | This document is licensed under [The Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.html). 6 | 7 | When using the name 'version' we mean the versioning scheme described in [VERSIONING.md](VERSIONING.md) 8 | 9 | ## Introduction 10 | 11 | This document is to describe the release pipeline, which is taking the result of the artifacts created according to [BUILDING.md](BUILDING.md) and publish a release to the various release targets for the project. 12 | 13 | We propose: 14 | - a set of release targets that are allowable 15 | - a pipeline for handling the release folder's artifacts 16 | 17 | It is NOT the purpose of this document to describe how a project might create a build, NOR is it describing a strcture in which projects MUST write build artifacts to. It is describing the structure of the releases themselves. 18 | 19 | ## Release Pipeline 20 | 21 | Each Pristine project MUST provide a `bin/release.sh` script which will make a release to the various targets. 22 | 23 | Each target may be scripted directly into the `bin/release.sh` shell script, or it may be broken down into files following the pattern:`./bin/release.{target}.sh`. 24 | 25 | While the `.sh` extension is mandatory, the scripts may be written with one of the following headers: 26 | - `#!bin/sh` 27 | - `#!bin/node` 28 | - `#!/usr/bin/env node` 29 | 30 | ### Create a build from current branch 31 | 32 | Process is outlined in [BUILDING.md](BUILDING.md) 33 | 34 | 1. Clean the build directory 35 | 2. run: `bin/build.{target}.{ext}` 36 | 37 | ### Bump the version of the project 38 | 39 | Projects SHOULD automate the version bump following [CONVENTIONAL_COMMITS.md](CONVENTIONAL_COMMITS.md). 40 | 41 | ### Generate Changelog 42 | 43 | Projects SHOULD use generated changelogs from following [CONVENTIONAL_COMMITS.md](CONVENTIONAL_COMMITS.md). 44 | 45 | ### Commit the bump + changelog update 46 | 47 | A project MUST generate a commit with the changes. 48 | 49 | ### Tag the commit with the bumped version 50 | 51 | A project MUST be tagged with the semantic versioning scheme from [VERSIONING.md](VERSIONING.md). 52 | 53 | ### Sign the releases. 54 | 55 | - MUST be a pgp signature 56 | - MUST be the same pgp key as is registered with Github 57 | - MUST be a detached ascii-armored (.asc) signature 58 | - All files in the build folder MUST have an associated signature file 59 | 60 | ### Push changelog & version bump 61 | 62 | ### Run Release Targets 63 | 64 | For each of the desired release targets, prepare and push the release. 65 | 66 | #### Example Release Targets 67 | 68 | 1. Github 69 | 2. Docker Hub 70 | 71 | ## Resources 72 | 73 | - [semantic-release](https://github.com/semantic-release/semantic-release) 74 | - [Conventional Commits](https://conventionalcommits.org/) 75 | -------------------------------------------------------------------------------- /VERSIONING.md: -------------------------------------------------------------------------------- 1 | # Versioning 2 | 3 | The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [BCP 14](https://tools.ietf.org/html/bcp14) [RFC2119](https://tools.ietf.org/html/rfc2119) [RFC8174](https://tools.ietf.org/html/rfc8174) when, and only when, they appear in all capitals, as shown here. 4 | 5 | This document is licensed under [The Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.html). 6 | 7 | ## Introduction 8 | This document is to describe how a project is to version its releases 9 | 10 | It also describes standardized tooling around manipulating the version 11 | 12 | ## Semver 13 | A project MUST use Semantic Versioning [semver](https://semver.org). Build metadata MAY NOT be used in a project. Build metadata SHOULD be ignored. 14 | 15 | A Basic summary of Semantic Versioning taken from: [semver.org](https://semver.org) 16 | 17 | ### Summary: 18 | 19 | Given a version number MAJOR.MINOR.PATCH, increment the: 20 | 21 | MAJOR version when you make incompatible API changes, 22 | MINOR version when you add functionality in a backwards-compatible manner, and 23 | PATCH version when you make backwards-compatible bug fixes. 24 | Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format. 25 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | clearMocks: true, 3 | coverageDirectory: '../coverage', 4 | resetMocks: true, 5 | restoreMocks: true, 6 | rootDir: './src', 7 | preset: 'ts-jest', 8 | } 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@open-rpc/server-js", 3 | "private": false, 4 | "version": "0.0.0-semantic-release-dev", 5 | "description": "", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/open-rpc/server-js.git" 9 | }, 10 | "main": "./build/index.js", 11 | "files": [ 12 | "build", 13 | "!build/**/*.test.*", 14 | ".node-version" 15 | ], 16 | "scripts": { 17 | "start": "./build/cli.js", 18 | "test": "npm run build && npm run test:unit", 19 | "test:unit": "jest --coverage", 20 | "build": "tsc", 21 | "watch:build": "tsc --watch", 22 | "watch:test": "jest --watch", 23 | "lint": "eslint . --ext .ts", 24 | "lint:fix": "eslint . --ext .ts --fix" 25 | }, 26 | "author": "", 27 | "license": "Apache-2.0", 28 | "dependencies": { 29 | "@open-rpc/schema-utils-js": "^2.0.2", 30 | "body-parser": "^1.19.0", 31 | "connect": "^3.7.0", 32 | "cors": "^2.8.5", 33 | "json-schema-faker": "^0.5.0-rcv.26", 34 | "lodash": "^4.17.19", 35 | "node-ipc": "9.1.1", 36 | "ws": "^8.0.0" 37 | }, 38 | "devDependencies": { 39 | "@open-rpc/examples": "^1.7.2", 40 | "@open-rpc/meta-schema": "^1.14.9", 41 | "@types/body-parser": "^1.19.5", 42 | "@types/connect": "^3.4.38", 43 | "@types/cors": "^2.8.17", 44 | "@types/fs-extra": "^11.0.4", 45 | "@types/jest": "^29.5.12", 46 | "@types/json-schema": "^7.0.15", 47 | "@types/lodash": "^4.17.1", 48 | "@types/node": "^20.12.11", 49 | "@types/node-ipc": "^9.2.3", 50 | "@types/ws": "^8.5.10", 51 | "@typescript-eslint/eslint-plugin": "^4.33.0", 52 | "@typescript-eslint/parser": "^4.33.0", 53 | "eslint": "^7.17.0", 54 | "jest": "^29.7.0", 55 | "ts-jest": "^29.1.2", 56 | "typescript": "^4.9.5", 57 | "undici": "^6.16.0" 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/error.ts: -------------------------------------------------------------------------------- 1 | export class JSONRPCError extends Error { 2 | public code: number; 3 | public message: string; 4 | public data?: any; 5 | constructor(message: string, code: number, data?: any) { 6 | super(); 7 | this.code = code; 8 | this.message = message; 9 | this.data = data; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import Server, { ServerOptions } from "./server"; 2 | import { Router } from "./router"; 3 | import { JSONRPCError } from "./error"; 4 | export * as transports from "./transports" 5 | 6 | export { 7 | Server, 8 | ServerOptions, 9 | Router, 10 | JSONRPCError, 11 | }; 12 | -------------------------------------------------------------------------------- /src/router.test.ts: -------------------------------------------------------------------------------- 1 | import { Router, MethodMapping } from "./router"; 2 | import examples from "@open-rpc/examples"; 3 | import _ from "lodash"; 4 | import { parseOpenRPCDocument } from "@open-rpc/schema-utils-js"; 5 | import { 6 | OpenrpcDocument as OpenRPC, 7 | ContentDescriptorObject, 8 | ExampleObject, 9 | ExamplePairingObject, 10 | MethodObject, 11 | } from "@open-rpc/meta-schema"; 12 | import { JSONRPCError } from "./error"; 13 | import { JSONRPCErrorObject } from "./transports/server-transport"; 14 | 15 | const jsf = require("json-schema-faker"); // eslint-disable-line 16 | 17 | const makeMethodMapping = (methods: MethodObject[]): MethodMapping => { 18 | const methodMapping = _.chain(methods) 19 | .keyBy("name") 20 | .mapValues((methodObject: MethodObject) => async (...args: any): Promise => { 21 | const foundExample = _.find( 22 | methodObject.examples as ExamplePairingObject[], 23 | ({ params }: ExamplePairingObject) => _.isMatch(_.map(params, "value"), args), 24 | ); 25 | if (foundExample) { 26 | const foundExampleResult = foundExample.result as ExampleObject; 27 | return foundExampleResult.value; 28 | } else { 29 | const result = methodObject.result as ContentDescriptorObject; 30 | return jsf.generate(result.schema); 31 | } 32 | }) 33 | .value(); 34 | methodMapping["test-error"] = async () => { throw new JSONRPCError("test error", 9998, { meta: "data" }); }; 35 | methodMapping["unknown-error"] = async () => { throw new Error("unanticpated crash"); }; 36 | return methodMapping; 37 | }; 38 | 39 | describe("router", () => { 40 | Object.entries(examples).forEach(([exampleName, example]) => { 41 | describe(exampleName, () => { 42 | 43 | let parsedExample: OpenRPC; 44 | beforeAll(async () => { 45 | parsedExample = await parseOpenRPCDocument(JSON.stringify(example)); 46 | // Mock error methods used to test routing calls 47 | const testErrorMethod = { name: "test-error", params: [], result: { name: "test-error-result", schema: {} } }; 48 | const unknownErrorMethod = Object.assign({}, testErrorMethod, { name: "unknown-error" }); 49 | parsedExample.methods.push(testErrorMethod); 50 | parsedExample.methods.push(unknownErrorMethod); 51 | }); 52 | 53 | it("is constructed with an OpenRPC document and a method mapping", () => { 54 | const methodMapping = makeMethodMapping(parsedExample.methods as MethodObject[]); 55 | 56 | expect(new Router(parsedExample, methodMapping)).toBeInstanceOf(Router); 57 | }); 58 | 59 | it("it may be constructed in mock mode", () => { 60 | expect(new Router(parsedExample, { mockMode: true })).toBeInstanceOf(Router); 61 | }); 62 | 63 | if (exampleName === "petstoreByName") { 64 | it("handles params by name", async () => { 65 | const router = new Router(parsedExample, makeMethodMapping(parsedExample.methods as MethodObject[])); 66 | const result = await router.call("list_pets", { limit: 1 }); 67 | expect(result).toBeDefined(); 68 | expect(result.result.length).toBeGreaterThan(0); 69 | expect(result.result[0].name).toBe("fluffy"); 70 | expect(result.result[0].id).toBe(7); 71 | expect(result.result[0].tag).toBe("poodle"); 72 | }); 73 | } 74 | if (exampleName === "simpleMath") { 75 | it("Simple math call works", async () => { 76 | const router = new Router(parsedExample, makeMethodMapping(parsedExample.methods as MethodObject[])); 77 | const { result } = await router.call("addition", [2, 2]); 78 | expect(result).toBe(4); 79 | }); 80 | 81 | it("returns not found error when using incorrect method", async () => { 82 | const router = new Router(parsedExample, makeMethodMapping(parsedExample.methods as MethodObject[])); 83 | const { error } = await router.call("foobar", [2, 2]); 84 | expect((error as JSONRPCErrorObject).code).toBe(-32601); 85 | }); 86 | 87 | it("returns param validation error when passing incorrect params", async () => { 88 | const router = new Router(parsedExample, makeMethodMapping(parsedExample.methods as MethodObject[])); 89 | const { error } = await router.call("addition", ["123", "321"]); 90 | expect(error).toBeDefined(); 91 | expect((error as JSONRPCErrorObject).code).toBe(-32602); 92 | }); 93 | 94 | it("returns JSONRPCError data when thrown", async () => { 95 | const router = new Router(parsedExample, makeMethodMapping(parsedExample.methods as MethodObject[])); 96 | const { error } = await router.call("test-error", []); 97 | expect((error as JSONRPCErrorObject).code).toBe(9998); 98 | expect((error as JSONRPCErrorObject).message).toBe("test error"); 99 | }); 100 | 101 | it("returns Unknown Error data when thrown", async () => { 102 | const router = new Router(parsedExample, makeMethodMapping(parsedExample.methods as MethodObject[])); 103 | const { error } = await router.call("unknown-error", []); 104 | expect((error as JSONRPCErrorObject).code).toBe(6969); 105 | expect((error as JSONRPCErrorObject).message).toBe("unknown error"); 106 | }); 107 | 108 | it("implements service discovery", async () => { 109 | const router = new Router(parsedExample, makeMethodMapping(parsedExample.methods as MethodObject[])); 110 | const { result } = await router.call("rpc.discover", []); 111 | expect(result).toEqual(parsedExample); 112 | }); 113 | 114 | it("can call rpc.discover with empty object", async () => { 115 | const router = new Router(parsedExample, makeMethodMapping(parsedExample.methods as MethodObject[])); 116 | const { result } = await router.call("rpc.discover", {}); 117 | expect(result).toEqual(parsedExample); 118 | }); 119 | 120 | it("Simple math call validates params", async () => { 121 | const router = new Router(parsedExample, makeMethodMapping(parsedExample.methods as MethodObject[])); 122 | const { error } = await router.call("addition", ["2", 2]); 123 | expect(error).toEqual({ 124 | code: -32602, 125 | data: expect.any(Array), 126 | message: "Invalid params", 127 | }); 128 | }); 129 | 130 | it("works in mock mode with valid examplePairing params", async () => { 131 | const router = new Router(parsedExample, { mockMode: true }); 132 | const { result } = await router.call("addition", [2, 2]); 133 | expect(result).toBe(4); 134 | }); 135 | 136 | it("works in mock mode with valid examplePairing params with by-name", async () => { 137 | const router = new Router(parsedExample, { mockMode: true }); 138 | const { result } = await router.call("addition", {a: 2, b: 2}); 139 | expect(result).toBe(4); 140 | }); 141 | 142 | it("works in mock mode with unknown params", async () => { 143 | const router = new Router(parsedExample, { mockMode: true }); 144 | const { result } = await router.call("addition", [6, 2]); 145 | expect(typeof result).toBe("number"); 146 | }); 147 | } 148 | 149 | }); 150 | }); 151 | }); 152 | -------------------------------------------------------------------------------- /src/router.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ExamplePairingObject, 3 | MethodObject, 4 | ExampleObject, 5 | ContentDescriptorObject, 6 | OpenrpcDocument, 7 | } from "@open-rpc/meta-schema"; 8 | import { MethodCallValidator, MethodNotFoundError, ParameterValidationError } from "@open-rpc/schema-utils-js"; 9 | import _ from "lodash"; 10 | import { JSONRPCError } from "./error"; 11 | 12 | const jsf = require("json-schema-faker"); // eslint-disable-line 13 | 14 | export interface MethodMapping { 15 | [methodName: string]: (...params: any) => Promise; 16 | } 17 | 18 | export interface MockModeSettings { 19 | mockMode: boolean; 20 | } 21 | 22 | export type TMethodHandler = (...args: any) => Promise; 23 | 24 | const toArray = (method?: MethodObject, params?: Record) => { 25 | if (!method) { 26 | return []; 27 | } 28 | if (!params) { 29 | return []; 30 | } 31 | const docParams = method.params as ContentDescriptorObject[]; 32 | const methodParamsOrder: { [k: string]: number } = docParams 33 | .map((p) => p.name) 34 | .reduce((m, pn, i) => ({ ...m, [pn]: i }), {}); 35 | 36 | return Object.entries(params) 37 | .reduce((params: unknown[], [key, val]) => { 38 | params[methodParamsOrder[key]] = val; 39 | return params; 40 | }, []); 41 | }; 42 | 43 | export class Router { 44 | 45 | public static methodNotFoundHandler(methodName: string) { 46 | return { 47 | error: { 48 | code: -32601, 49 | data: `The method ${methodName} does not exist / is not available.`, 50 | message: "Method not found", 51 | }, 52 | }; 53 | } 54 | private methods: MethodMapping; 55 | private methodCallValidator: MethodCallValidator; 56 | 57 | constructor( 58 | private openrpcDocument: OpenrpcDocument, 59 | methodMapping: MethodMapping | MockModeSettings, 60 | ) { 61 | if (methodMapping.mockMode) { 62 | this.methods = this.buildMockMethodMapping(openrpcDocument.methods as MethodObject[]); 63 | } else { 64 | this.methods = methodMapping as MethodMapping; 65 | } 66 | this.methods["rpc.discover"] = this.serviceDiscoveryHandler.bind(this); 67 | 68 | this.methodCallValidator = new MethodCallValidator(openrpcDocument); 69 | } 70 | 71 | public async call(methodName: string, params: any) { 72 | const validationErrors = this.methodCallValidator.validate(methodName, params); 73 | 74 | if (validationErrors instanceof MethodNotFoundError) { 75 | return Router.methodNotFoundHandler(methodName); 76 | } 77 | 78 | if (validationErrors.length > 0) { 79 | return this.invalidParamsHandler(validationErrors); 80 | } 81 | 82 | const methodObject = (this.openrpcDocument.methods as MethodObject[]).find((m) => m.name === methodName) as MethodObject; 83 | 84 | const paramsAsArray = params instanceof Array ? params : toArray(methodObject, params); 85 | 86 | try { 87 | return { result: await this.methods[methodName](...paramsAsArray) }; 88 | } catch (e) { 89 | if (e instanceof JSONRPCError) { 90 | return { error: { code: e.code, message: e.message, data: e.data } }; 91 | } 92 | return { error: { code: 6969, message: "unknown error" } }; 93 | } 94 | } 95 | 96 | public isMethodImplemented(methodName: string): boolean { 97 | return this.methods[methodName] !== undefined; 98 | } 99 | 100 | private serviceDiscoveryHandler(): Promise { 101 | return Promise.resolve(this.openrpcDocument); 102 | } 103 | 104 | private buildMockMethodMapping(methods: MethodObject[]): MethodMapping { 105 | const methMap: MethodMapping = {}; 106 | 107 | methods.forEach((method) => { 108 | methMap[method.name] = (...args: any): Promise => { 109 | if (method.examples === undefined) { 110 | const result = method.result as ContentDescriptorObject; 111 | return Promise.resolve(jsf.generate(result.schema)); 112 | } 113 | 114 | const foundExample = (method.examples as ExamplePairingObject[]).find(({ params }) => { 115 | let isMatch = true; 116 | (params as ExampleObject[]).forEach((p, i) => { 117 | const eq = _.isEqual(p.value, args[i]); 118 | if (!eq) { isMatch = false; } 119 | }); 120 | return isMatch; 121 | }); 122 | 123 | if (foundExample) { 124 | const foundExampleResult = foundExample.result as ExampleObject; 125 | return Promise.resolve(foundExampleResult.value); 126 | } else { 127 | const result = method.result as ContentDescriptorObject; 128 | return Promise.resolve(jsf.generate(result.schema)); 129 | } 130 | }; 131 | }); 132 | 133 | return methMap; 134 | } 135 | 136 | private invalidParamsHandler(errs: ParameterValidationError[]) { 137 | return { 138 | error: { 139 | code: -32602, 140 | data: errs, 141 | message: "Invalid params", 142 | }, 143 | }; 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/server.test.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/no-var-requires */ 2 | import Server from './server'; 3 | import { ServerTransport } from './transports/server-transport'; 4 | import { Router } from './router'; 5 | 6 | // Create test classes we'll use directly 7 | class TestRouter implements Partial { 8 | public isMethodImplemented = jest.fn(); 9 | public call = jest.fn(); 10 | } 11 | 12 | class TestTransport extends ServerTransport { 13 | public options: any; 14 | 15 | constructor(options: any = {}) { 16 | super(); 17 | this.options = options; 18 | } 19 | 20 | public start = jest.fn().mockResolvedValue(undefined); 21 | public stop = jest.fn().mockResolvedValue(undefined); 22 | } 23 | 24 | // Create factory functions to use in tests 25 | const createTestRouter = () => new TestRouter() as unknown as Router; 26 | const createTestTransport = (options: any = {}) => new TestTransport(options); 27 | 28 | // Mock MethodCallValidator 29 | jest.mock('@open-rpc/schema-utils-js', () => ({ 30 | MethodCallValidator: jest.fn().mockImplementation(() => ({ 31 | validate: jest.fn(), 32 | })), 33 | })); 34 | 35 | describe('Server', () => { 36 | beforeEach(() => { 37 | jest.clearAllMocks(); 38 | jest.spyOn(console, 'log').mockImplementation(() => { /* no-op */ }); 39 | }); 40 | 41 | it('initializes without routers or transports when no options provided', () => { 42 | const server = new Server({ openrpcDocument: {} as any }); 43 | expect((server as any).routers).toHaveLength(0); 44 | expect((server as any).transports).toHaveLength(0); 45 | }); 46 | 47 | it('adds router when constructed with methodMapping', () => { 48 | // Mock Router constructor 49 | const originalRouter = require('./router').Router; 50 | const mockRouter = createTestRouter(); 51 | require('./router').Router = jest.fn().mockReturnValue(mockRouter); 52 | 53 | const mapping = {} as any; 54 | const server = new Server({ openrpcDocument: {} as any, methodMapping: mapping }); 55 | 56 | // Verify Router was created with expected args 57 | expect(require('./router').Router).toHaveBeenCalledWith({} as any, mapping); 58 | expect((server as any).routers).toHaveLength(1); 59 | 60 | // Restore original Router 61 | require('./router').Router = originalRouter; 62 | }); 63 | 64 | it('adds default transport when constructed with transportConfigs', () => { 65 | // Mock the transport factory 66 | const originalTransports = require('./transports').default; 67 | const mockTransport = createTestTransport({ port: 123 }); 68 | require('./transports').default = { 69 | HTTPTransport: jest.fn().mockReturnValue(mockTransport) 70 | }; 71 | 72 | // Mock the Router class to prevent it from trying to use actual MethodCallValidator 73 | const originalRouter = require('./router').Router; 74 | require('./router').Router = jest.fn().mockReturnValue(createTestRouter()); 75 | 76 | const opts = { port: 123 } as any; 77 | const server = new Server({ 78 | openrpcDocument: {} as any, 79 | methodMapping: {} as any, 80 | transportConfigs: [{ type: 'HTTPTransport', options: opts }], 81 | }); 82 | 83 | expect(console.log).toHaveBeenCalledWith( 84 | `Adding Transport of the type HTTPTransport on port ${opts.port}`, 85 | ); 86 | 87 | expect((server as any).transports).toHaveLength(1); 88 | expect((server as any).transports[0]).toBe(mockTransport); 89 | expect(mockTransport.options).toEqual(opts); 90 | 91 | // Restore original modules 92 | require('./transports').default = originalTransports; 93 | require('./router').Router = originalRouter; 94 | }); 95 | 96 | it('throws error on invalid transport type in addDefaultTransport', () => { 97 | const server = new Server({ openrpcDocument: {} as any }); 98 | expect(() => { 99 | (server as any).addDefaultTransport('InvalidTransport' as any, {} as any); 100 | }).toThrow( 101 | 'The transport "InvalidTransport" is not a valid transport type.', 102 | ); 103 | }); 104 | 105 | it('registers transport and attaches existing routers in addTransport', () => { 106 | const server = new Server({ openrpcDocument: {} as any }); 107 | 108 | // Create test data 109 | const router1 = createTestRouter(); 110 | const router2 = createTestRouter(); 111 | (server as any).routers = [router1, router2]; 112 | 113 | const transport = createTestTransport(); 114 | jest.spyOn(transport, 'addRouter'); 115 | 116 | server.addTransport(transport); 117 | 118 | expect(transport.addRouter).toHaveBeenCalledTimes(2); 119 | expect(transport.addRouter).toHaveBeenCalledWith(router1); 120 | expect(transport.addRouter).toHaveBeenCalledWith(router2); 121 | expect((server as any).transports).toContain(transport); 122 | }); 123 | 124 | it('registers router and attaches to existing transports in addRouter', () => { 125 | // Mock Router constructor 126 | const originalRouter = require('./router').Router; 127 | const mockRouter = createTestRouter(); 128 | require('./router').Router = jest.fn().mockReturnValue(mockRouter); 129 | 130 | const server = new Server({ openrpcDocument: {} as any }); 131 | 132 | // Create test data 133 | const transport = createTestTransport(); 134 | jest.spyOn(transport, 'addRouter'); 135 | (server as any).transports = [transport]; 136 | 137 | const router = server.addRouter({} as any, {} as any); 138 | 139 | expect(require('./router').Router).toHaveBeenCalledWith({}, {} as any); 140 | expect(transport.addRouter).toHaveBeenCalledWith(router); 141 | expect((server as any).routers).toContain(router); 142 | 143 | // Restore original Router 144 | require('./router').Router = originalRouter; 145 | }); 146 | 147 | it('deregisters router and detaches from transports in removeRouter', () => { 148 | const server = new Server({ openrpcDocument: {} as any }); 149 | 150 | // Create test data 151 | const router = createTestRouter(); 152 | const transport = createTestTransport(); 153 | jest.spyOn(transport, 'removeRouter'); 154 | 155 | (server as any).transports = [transport]; 156 | (server as any).routers = [router]; 157 | 158 | server.removeRouter(router); 159 | 160 | expect((server as any).routers).not.toContain(router); 161 | expect(transport.removeRouter).toHaveBeenCalledWith(router); 162 | }); 163 | 164 | it('calls start on transports in start', async () => { 165 | const server = new Server({ openrpcDocument: {} as any }); 166 | 167 | // Create test data 168 | const transport = createTestTransport(); 169 | 170 | (server as any).transports = [transport]; 171 | 172 | await server.start(); 173 | 174 | expect(transport.start).toHaveBeenCalled(); 175 | }); 176 | 177 | it('calls stop on transports in stop', async () => { 178 | const server = new Server({ openrpcDocument: {} as any }); 179 | 180 | // Create test data 181 | const transport = createTestTransport(); 182 | 183 | (server as any).transports = [transport]; 184 | 185 | await server.stop(); 186 | 187 | expect(transport.stop).toHaveBeenCalled(); 188 | }); 189 | }); 190 | -------------------------------------------------------------------------------- /src/server.ts: -------------------------------------------------------------------------------- 1 | import { Router, MethodMapping } from "./router"; 2 | import { OpenrpcDocument as OpenRPC } from "@open-rpc/meta-schema"; 3 | import Transports, {ServerTransport, TransportOptions, TransportClasses, TransportNames } from "./transports"; 4 | 5 | interface TransportConfig { 6 | type: TransportNames; 7 | options: TransportOptions; 8 | } 9 | 10 | export interface MockModeOptions { 11 | mockMode: boolean; 12 | } 13 | 14 | export interface ServerOptions { 15 | openrpcDocument: OpenRPC; 16 | transportConfigs?: TransportConfig[]; 17 | methodMapping?: MethodMapping | MockModeOptions; 18 | } 19 | 20 | export default class Server { 21 | private routers: Router[] = []; 22 | private transports: TransportClasses[] = []; 23 | 24 | constructor(options: ServerOptions) { 25 | if (options.methodMapping) { 26 | this.addRouter( 27 | options.openrpcDocument, 28 | options.methodMapping, 29 | ); 30 | } 31 | 32 | if (options.transportConfigs) { 33 | options.transportConfigs.forEach((transportConfig) => { 34 | this.addDefaultTransport(transportConfig.type, transportConfig.options); 35 | }); 36 | } 37 | } 38 | 39 | public addTransport(transport: ServerTransport): void{ 40 | this.routers.forEach((router) => { 41 | transport.addRouter(router); 42 | }); 43 | 44 | this.transports.push(transport); 45 | } 46 | 47 | public addDefaultTransport(transportType: TransportNames, transportOptions: TransportOptions) { 48 | const TransportClass = Transports[transportType]; 49 | 50 | console.log(`Adding Transport of the type ${transportType} on port ${transportOptions.port}`); 51 | 52 | if (TransportClass === undefined) { 53 | throw new Error(`The transport "${transportType}" is not a valid transport type.`); 54 | } 55 | 56 | const transport = new TransportClass(transportOptions); 57 | this.addTransport(transport); 58 | } 59 | 60 | public addRouter(openrpcDocument: OpenRPC, methodMapping: MethodMapping | MockModeOptions) { 61 | const router = new Router(openrpcDocument, methodMapping); 62 | 63 | this.routers.push(router); 64 | this.transports.forEach((transport) => transport.addRouter(router)); 65 | 66 | return router; 67 | } 68 | 69 | public removeRouter(routerToRemove: Router) { 70 | this.routers = this.routers.filter((r) => r !== routerToRemove); 71 | this.transports.forEach((transport) => transport.removeRouter(routerToRemove)); 72 | } 73 | 74 | public async start() { 75 | for (const transport of this.transports) { 76 | await transport.start(); 77 | } 78 | } 79 | 80 | public async stop() { 81 | for (const transport of this.transports) { 82 | await transport.stop(); 83 | } 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /src/transports/http.test.ts: -------------------------------------------------------------------------------- 1 | import examples from "@open-rpc/examples"; 2 | import { parseOpenRPCDocument } from "@open-rpc/schema-utils-js"; 3 | import { Router } from "../router"; 4 | import HTTPTransport from "./http"; 5 | import { JSONRPCResponse } from "./server-transport"; 6 | import connect from "connect"; 7 | import http from "http"; 8 | 9 | describe("http transport", () => { 10 | let transport: HTTPTransport; 11 | beforeAll(async () => { 12 | const simpleMathExample = await parseOpenRPCDocument(examples.simpleMath); 13 | transport = new HTTPTransport({ 14 | middleware: [], 15 | port: 9696, 16 | }); 17 | 18 | const router = new Router(simpleMathExample, { mockMode: true }); 19 | 20 | transport.addRouter(router); 21 | 22 | await transport.start(); 23 | }); 24 | 25 | afterAll(async () => { 26 | await transport.stop(); 27 | }); 28 | 29 | it("can start an http server that works", async () => { 30 | const { result } = await fetch("http://localhost:9696", { 31 | body: JSON.stringify({ 32 | id: "0", 33 | jsonrpc: "2.0", 34 | method: "addition", 35 | params: [2, 2], 36 | }), 37 | headers: { "Content-Type": "application/json" }, 38 | method: "post", 39 | }).then((res) => res.json() as Promise); 40 | 41 | expect(result).toBe(4); 42 | }); 43 | it("works with batching", async () => { 44 | const result = await fetch("http://localhost:9696", { 45 | body: JSON.stringify([ 46 | { 47 | id: "0", 48 | jsonrpc: "2.0", 49 | method: "addition", 50 | params: [2, 2], 51 | }, { 52 | id: "1", 53 | jsonrpc: "2.0", 54 | method: "addition", 55 | params: [4, 4], 56 | }, 57 | ]), 58 | headers: { "Content-Type": "application/json" }, 59 | method: "post", 60 | }).then((res) => res.json() as Promise); 61 | 62 | const pluckedResult = result.map((r: JSONRPCResponse) => r.result); 63 | expect(pluckedResult).toEqual([4, 8]); 64 | }); 65 | 66 | it("allows using an existing app", async () => { 67 | const app = connect(); 68 | const simpleMathExample = await parseOpenRPCDocument(examples.simpleMath); 69 | const localTransport = new HTTPTransport({ middleware: [], port: 9700, app }); 70 | const router = new Router(simpleMathExample, { mockMode: true }); 71 | localTransport.addRouter(router); 72 | 73 | try { 74 | await localTransport.start(); 75 | 76 | const { result } = await fetch("http://localhost:9700", { 77 | body: JSON.stringify({ 78 | id: "2", 79 | jsonrpc: "2.0", 80 | method: "addition", 81 | params: [2, 2], 82 | }), 83 | headers: { "Content-Type": "application/json" }, 84 | method: "post", 85 | }).then((res) => res.json() as Promise); 86 | 87 | expect(result).toBe(4); 88 | } finally { 89 | await localTransport.stop(); 90 | } 91 | }, 30000); 92 | 93 | it("handles errors when stopping the server", async () => { 94 | const errorTransport = new HTTPTransport({ 95 | middleware: [], 96 | port: 9703, 97 | }); 98 | let serverInstance: any; 99 | let originalCloseFn: ((callback?: (err?: Error) => void) => http.Server) | null = null; 100 | 101 | try { 102 | await errorTransport.start(); 103 | serverInstance = (errorTransport as any).server; 104 | originalCloseFn = serverInstance.close.bind(serverInstance); 105 | 106 | const mockError = new Error("Mock close error"); 107 | serverInstance.close = (callback: (err?: Error) => void) => { 108 | callback(mockError); 109 | originalCloseFn?.((_err?: Error) => { /* an actual close attempt */ }); 110 | }; 111 | 112 | await expect(errorTransport.stop()).rejects.toThrow("Mock close error"); 113 | 114 | } finally { 115 | if (serverInstance && serverInstance.listening) { 116 | // Restore original close method before attempting to stop for cleanup 117 | if (originalCloseFn) { 118 | serverInstance.close = originalCloseFn; 119 | } 120 | try { 121 | await errorTransport.stop(); // Attempt to stop for cleanup 122 | } catch (cleanupError) { 123 | // Ignore cleanup errors if the main test assertion passed/failed as expected 124 | console.warn("Error during test server cleanup (port 9703):", cleanupError); 125 | } 126 | } 127 | } 128 | }); 129 | 130 | it("handles errors when starting the server", async () => { 131 | const errorTransport = new HTTPTransport({ 132 | middleware: [], 133 | port: 9707, 134 | }); 135 | const serverInstance = (errorTransport as any).server; 136 | const originalListen = serverInstance.listen.bind(serverInstance); 137 | serverInstance.listen = (port: number, cb: (err?: Error) => void) => { 138 | cb(new Error("Mock listen error")); 139 | return serverInstance; 140 | }; 141 | await expect(errorTransport.start()).rejects.toThrow("Mock listen error"); 142 | serverInstance.listen = originalListen; 143 | // Do not call stop, since server never started 144 | }); 145 | }); 146 | -------------------------------------------------------------------------------- /src/transports/http.ts: -------------------------------------------------------------------------------- 1 | import cors from "cors"; 2 | import { json as jsonParser } from "body-parser"; 3 | import connect, { HandleFunction, Server as ConnectApp } from "connect"; 4 | import http, { ServerOptions } from "http"; 5 | import ServerTransport, { JSONRPCRequest } from "./server-transport"; 6 | 7 | export interface HTTPServerTransportOptions extends ServerOptions { 8 | middleware: HandleFunction[]; 9 | port: number; 10 | cors?: cors.CorsOptions; 11 | app?: ConnectApp; 12 | } 13 | 14 | export default class HTTPServerTransport extends ServerTransport { 15 | private static defaultCorsOptions = { origin: "*" }; 16 | private server: http.Server; 17 | private options: HTTPServerTransportOptions; 18 | 19 | constructor(options: HTTPServerTransportOptions) { 20 | super(); 21 | const app = options.app || connect(); 22 | 23 | const corsOptions = options.cors || HTTPServerTransport.defaultCorsOptions; 24 | this.options = { 25 | ...options, 26 | app, 27 | middleware: [ 28 | cors(corsOptions) as HandleFunction, 29 | jsonParser({ 30 | limit: "1mb" 31 | }), 32 | ...options.middleware, 33 | ], 34 | }; 35 | 36 | this.options.middleware.forEach((mw) => app.use(mw)); 37 | 38 | app.use(this.httpRouterHandler.bind(this) as HandleFunction); 39 | 40 | this.server = http.createServer(app); 41 | } 42 | 43 | public async start(): Promise { 44 | return new Promise((resolve, reject) => { 45 | this.server.listen(this.options.port, (err?: Error) => { 46 | if (err) return reject(err); 47 | resolve(); 48 | }); 49 | }); 50 | } 51 | 52 | public async stop(): Promise { 53 | return new Promise((resolve, reject) => { 54 | this.server.close((err?: Error) => { 55 | if (err) { 56 | return reject(err); 57 | } 58 | resolve(); 59 | }); 60 | }); 61 | } 62 | 63 | private async httpRouterHandler(req: any, res: any): Promise { 64 | let result = null; 65 | if (req.body instanceof Array) { 66 | result = await Promise.all(req.body.map((r: JSONRPCRequest) => super.routerHandler(r))); 67 | } else { 68 | result = await super.routerHandler(req.body); 69 | } 70 | res.setHeader("Content-Type", "application/json"); 71 | res.end(JSON.stringify(result)); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/transports/https.test.ts: -------------------------------------------------------------------------------- 1 | import examples from "@open-rpc/examples"; 2 | import { parseOpenRPCDocument } from "@open-rpc/schema-utils-js"; 3 | import { Router } from "../router"; 4 | import * as fs from "fs"; 5 | import { promisify } from "util"; 6 | import HTTPSTransport from "./https"; 7 | const readFile = promisify(fs.readFile); 8 | import cors from "cors"; 9 | import { json as jsonParser } from "body-parser"; 10 | import { HandleFunction } from "connect"; 11 | import { JSONRPCResponse } from "./server-transport"; 12 | import { Agent } from 'undici'; 13 | import connect from "connect"; 14 | 15 | const agent = new Agent({ 16 | connect: { 17 | rejectUnauthorized: false, 18 | }, 19 | }) as any; 20 | describe("https transport", () => { 21 | let transport: HTTPSTransport; 22 | beforeAll(async () => { 23 | const simpleMathExample = await parseOpenRPCDocument(examples.simpleMath); 24 | 25 | const corsOptions = { origin: "*" } as cors.CorsOptions; 26 | 27 | transport = new HTTPSTransport({ 28 | cert: await readFile(`${process.cwd()}/test-cert/server.cert`), 29 | key: await readFile(`${process.cwd()}/test-cert/server.key`), 30 | middleware: [ 31 | cors(corsOptions) as HandleFunction, 32 | jsonParser(), 33 | ], 34 | port: 9697, 35 | }); 36 | 37 | const router = new Router(simpleMathExample, { mockMode: true }); 38 | 39 | transport.addRouter(router); 40 | 41 | await transport.start(); 42 | }); 43 | 44 | afterAll(async () => { 45 | await transport.stop(); 46 | }); 47 | 48 | it("can start an https server that works", async () => { 49 | const { result } = await fetch("https://localhost:9697", { 50 | dispatcher: agent, 51 | body: JSON.stringify({ 52 | id: "0", 53 | jsonrpc: "2.0", 54 | method: "addition", 55 | params: [2, 2], 56 | }), 57 | headers: { "Content-Type": "application/json" }, 58 | method: "post", 59 | }).then((res) => res.json() as Promise); 60 | 61 | expect(result).toBe(4); 62 | }); 63 | 64 | it("works with batching", async () => { 65 | const result = await fetch("https://localhost:9697", { 66 | dispatcher: agent, 67 | body: JSON.stringify([ 68 | { 69 | id: "0", 70 | jsonrpc: "2.0", 71 | method: "addition", 72 | params: [2, 2], 73 | }, { 74 | id: "1", 75 | jsonrpc: "2.0", 76 | method: "addition", 77 | params: [4, 4], 78 | }, 79 | ]), 80 | headers: { "Content-Type": "application/json" }, 81 | method: "post", 82 | }).then((res) => res.json() as Promise); 83 | 84 | const pluckedResult = result.map((r: JSONRPCResponse) => r.result); 85 | expect(pluckedResult).toEqual([4, 8]); 86 | }); 87 | 88 | it("allows using an existing app (HTTPS)", async () => { 89 | const app = connect(); 90 | const simpleMathExample = await parseOpenRPCDocument(examples.simpleMath); 91 | const transport = new HTTPSTransport({ 92 | cert: await readFile(`${process.cwd()}/test-cert/server.cert`), 93 | key: await readFile(`${process.cwd()}/test-cert/server.key`), 94 | middleware: [], 95 | port: 9701, 96 | app, 97 | }); 98 | const router = new Router(simpleMathExample, { mockMode: true }); 99 | transport.addRouter(router); 100 | try { 101 | await transport.start(); 102 | const { result } = await fetch("https://localhost:9701", { 103 | dispatcher: agent, 104 | body: JSON.stringify({ 105 | id: "2", 106 | jsonrpc: "2.0", 107 | method: "addition", 108 | params: [2, 2], 109 | }), 110 | headers: { "Content-Type": "application/json" }, 111 | method: "post", 112 | }).then((res) => res.json() as Promise); 113 | expect(result).toBe(4); 114 | } finally { 115 | await transport.stop(); 116 | } 117 | }, 30000); 118 | 119 | it("handles errors when starting the server (HTTPS)", async () => { 120 | const transport = new HTTPSTransport({ 121 | cert: await readFile(`${process.cwd()}/test-cert/server.cert`), 122 | key: await readFile(`${process.cwd()}/test-cert/server.key`), 123 | middleware: [], 124 | port: 9708, 125 | }); 126 | const serverInstance = (transport as any).server; 127 | const originalListen = serverInstance.listen.bind(serverInstance); 128 | serverInstance.listen = (port: number, cb: (err?: Error) => void) => { 129 | cb(new Error("Mock listen error")); 130 | return serverInstance; 131 | }; 132 | await expect(transport.start()).rejects.toThrow("Mock listen error"); 133 | serverInstance.listen = originalListen; 134 | // Do not call stop, since server never started 135 | }); 136 | 137 | it("handles errors when stopping the server (HTTPS)", async () => { 138 | const transport = new HTTPSTransport({ 139 | cert: await readFile(`${process.cwd()}/test-cert/server.cert`), 140 | key: await readFile(`${process.cwd()}/test-cert/server.key`), 141 | middleware: [], 142 | port: 9709, // Using a new port to avoid conflicts 143 | }); 144 | await transport.start(); // Start the server first 145 | 146 | const serverInstance = (transport as any).server; 147 | const originalClose = serverInstance.close.bind(serverInstance); 148 | serverInstance.close = (cb: (err?: Error) => void) => { 149 | cb(new Error("Mock close error")); 150 | // REAL http2.Http2SecureServer.close() returns the server instance. 151 | // we need to return something that has a .close method for the promisify to work. 152 | // but it doesnt matter since we are testing the error case. 153 | return serverInstance; 154 | }; 155 | await expect(transport.stop()).rejects.toThrow("Mock close error"); 156 | serverInstance.close = originalClose; // Restore original close 157 | // Attempt to gracefully close the server if the mock wasn't called or test failed before mock. 158 | // This might not be strictly necessary if the test passes and mock is restored. 159 | try { 160 | await new Promise((resolve, reject) => { 161 | const s = (transport as any).server as any; 162 | if (s && s.listening) { 163 | s.close((err?: Error) => err ? reject(err) : resolve()); 164 | } else { 165 | resolve(); 166 | } 167 | }); 168 | } catch (e) { 169 | // ignore errors during cleanup 170 | } 171 | }); 172 | }); 173 | -------------------------------------------------------------------------------- /src/transports/https.ts: -------------------------------------------------------------------------------- 1 | import cors from "cors"; 2 | import { json as jsonParser } from "body-parser"; 3 | import connect, { HandleFunction, Server as ConnectApp } from "connect"; 4 | import http2, { Http2SecureServer, SecureServerOptions } from "http2"; 5 | import ServerTransport, { JSONRPCRequest } from "./server-transport"; 6 | 7 | export interface HTTPSServerTransportOptions extends SecureServerOptions { 8 | middleware: HandleFunction[]; 9 | port: number; 10 | cors?: cors.CorsOptions; 11 | allowHTTP1?: boolean; 12 | app?: ConnectApp; 13 | } 14 | 15 | export default class HTTPSServerTransport extends ServerTransport { 16 | private static defaultCorsOptions = { origin: "*" }; 17 | private server: Http2SecureServer; 18 | 19 | constructor(private options: HTTPSServerTransportOptions) { 20 | super(); 21 | options.allowHTTP1 = true; 22 | 23 | const app = options.app || connect(); 24 | 25 | const corsOptions = options.cors || HTTPSServerTransport.defaultCorsOptions; 26 | this.options = { 27 | ...options, 28 | app, 29 | middleware: [ 30 | cors(corsOptions) as HandleFunction, 31 | jsonParser({ 32 | limit: "1mb" 33 | }), 34 | ...options.middleware, 35 | ], 36 | }; 37 | 38 | this.options.middleware.forEach((mw) => app.use(mw)); 39 | app.use(this.httpsRouterHandler.bind(this)); 40 | this.server = http2.createSecureServer(options, (req: any, res: any) => app(req, res)); 41 | } 42 | 43 | public async start(): Promise { 44 | return new Promise((resolve, reject) => { 45 | this.server.listen(this.options.port, (err?: Error) => { 46 | if (err) return reject(err); 47 | resolve(); 48 | }); 49 | }); 50 | } 51 | 52 | public async stop(): Promise { 53 | return new Promise((resolve, reject) => { 54 | this.server.close((err?: Error) => { 55 | if (err) return reject(err); 56 | resolve(); 57 | }); 58 | }); 59 | } 60 | 61 | private async httpsRouterHandler(req: any, res: any): Promise { 62 | let result = null; 63 | if (req.body instanceof Array) { 64 | result = await Promise.all(req.body.map((r: JSONRPCRequest) => super.routerHandler(r))); 65 | } else { 66 | result = await super.routerHandler(req.body); 67 | } 68 | res.setHeader("Content-Type", "application/json"); 69 | res.end(JSON.stringify(result)); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/transports/index.ts: -------------------------------------------------------------------------------- 1 | import WebSocketTransport, { WebSocketServerTransportOptions } from "./websocket"; 2 | import HTTPTransport, { HTTPServerTransportOptions } from "./http"; 3 | import HTTPSTransport, { HTTPSServerTransportOptions } from "./https"; 4 | import IPCTransport, { IPCServerTransportOptions } from "./ipc"; 5 | import { ServerTransport } from "./server-transport"; 6 | export {HTTPSTransport, HTTPTransport, WebSocketTransport, IPCTransport, ServerTransport} 7 | 8 | export type TransportNames = "IPCTransport" | "HTTPTransport" | "HTTPSTransport" | "WebSocketTransport"; 9 | 10 | export type TransportClasses = WebSocketTransport | 11 | HTTPTransport | 12 | HTTPSTransport | 13 | IPCTransport | ServerTransport; 14 | 15 | export type TransportOptions = WebSocketServerTransportOptions | 16 | HTTPServerTransportOptions | 17 | HTTPSServerTransportOptions | 18 | IPCServerTransportOptions; 19 | 20 | export interface TransportsMapping { 21 | [name: string]: any; 22 | } 23 | 24 | const transports: TransportsMapping = { 25 | HTTPSTransport, 26 | HTTPTransport, 27 | IPCTransport, 28 | WebSocketTransport, 29 | }; 30 | 31 | export default transports; 32 | -------------------------------------------------------------------------------- /src/transports/ipc.test.ts: -------------------------------------------------------------------------------- 1 | import examples from "@open-rpc/examples"; 2 | import { parseOpenRPCDocument } from "@open-rpc/schema-utils-js"; 3 | import { Router } from "../router"; 4 | import IPCTransport from "./ipc"; 5 | import ipc from "node-ipc"; 6 | import { JSONRPCResponse } from "./server-transport"; 7 | 8 | describe("IPC transport", () => { 9 | let transport: IPCTransport; 10 | beforeAll(async () => { 11 | const simpleMathExample = await parseOpenRPCDocument(examples.simpleMath); 12 | 13 | transport = new IPCTransport({ 14 | id: "simpleMath", 15 | ipv6: false, 16 | port: 9699, 17 | udp: false, 18 | }); 19 | const router = new Router(simpleMathExample, { mockMode: true }); 20 | transport.addRouter(router); 21 | await transport.start(); 22 | ipc.config.id = "simpleMath"; 23 | ipc.config.retry = 1500; 24 | return new Promise((resolve, reject) => { 25 | ipc.connectToNet( 26 | "simpleMath", 27 | "127.0.0.1", 28 | 9699, 29 | () => { 30 | ipc.of.simpleMath.on("connect", resolve); 31 | }); 32 | }); 33 | }); 34 | 35 | afterAll(async () => { 36 | ipc.disconnect("simpleMath"); 37 | await transport.stop(); 38 | }); 39 | 40 | it("can start an IPC server that works", (done) => { 41 | const handle = (data: any) => { 42 | ipc.of.simpleMath.off("message", handle); 43 | const { result } = JSON.parse(data); 44 | expect(result).toBe(4); 45 | done(); 46 | }; 47 | 48 | ipc.of.simpleMath.on("message", handle); 49 | 50 | ipc.of.simpleMath.emit( 51 | "message", 52 | JSON.stringify({ 53 | id: "0", 54 | jsonrpc: "2.0", 55 | method: "addition", 56 | params: [2, 2], 57 | }), 58 | ); 59 | }, 60000); 60 | 61 | it("works with batching", (done) => { 62 | const handle = (data: any) => { 63 | ipc.of.simpleMath.off("message", handle); 64 | const responses = JSON.parse(data) as JSONRPCResponse[]; 65 | expect(responses.map((r) => r.result)).toEqual([4, 8]); 66 | done(); 67 | }; 68 | 69 | ipc.of.simpleMath.on("message", handle); 70 | 71 | ipc.of.simpleMath.emit( 72 | "message", 73 | JSON.stringify([ 74 | { 75 | id: "1", 76 | jsonrpc: "2.0", 77 | method: "addition", 78 | params: [2, 2], 79 | }, { 80 | id: "2", 81 | jsonrpc: "2.0", 82 | method: "addition", 83 | params: [4, 4], 84 | }, 85 | ]), 86 | ); 87 | }, 60000); 88 | }); 89 | -------------------------------------------------------------------------------- /src/transports/ipc.ts: -------------------------------------------------------------------------------- 1 | import ServerTransport, { JSONRPCRequest } from "./server-transport"; 2 | import ipc from "node-ipc"; 3 | 4 | export interface IPCServerTransportOptions { 5 | id: string; 6 | port: number; 7 | udp: boolean; 8 | ipv6: boolean; 9 | } 10 | 11 | type UdpType = "udp4" | "udp6" | undefined; 12 | 13 | export default class IPCServerTransport extends ServerTransport { 14 | private server: any; 15 | 16 | constructor(private options: IPCServerTransportOptions) { 17 | super(); 18 | 19 | const udpOption = (options.udp) ? `udp${(options.ipv6) ? "6" : "4"}` : undefined; 20 | ipc.config.id = options.id; 21 | ipc.config.logger = () => { 22 | // noop 23 | }; 24 | 25 | ipc.serveNet( 26 | undefined, 27 | options.port as number, 28 | udpOption as UdpType, 29 | () => { 30 | ipc.server.on("message", (data, socket) => { 31 | const req = JSON.parse(data); 32 | 33 | this.ipcRouterHandler(req, (result: string) => { 34 | ipc.server.emit( 35 | socket, 36 | "message", 37 | result, 38 | ); 39 | }); 40 | }); 41 | }, 42 | ); 43 | 44 | this.server = ipc.server; 45 | } 46 | 47 | public async start(): Promise { 48 | this.server.start(this.options.port); 49 | // node-ipc is sync, but yield to event loop to ensure server is ready 50 | await new Promise((resolve) => setImmediate(resolve)); 51 | } 52 | 53 | public async stop(): Promise { 54 | this.server.stop(); 55 | // node-ipc is sync, but yield to event loop to ensure server is stopped 56 | await new Promise((resolve) => setImmediate(resolve)); 57 | } 58 | 59 | private async ipcRouterHandler(req: any, respondWith: any) { 60 | let result = null; 61 | if (req instanceof Array) { 62 | result = await Promise.all(req.map((jsonrpcReq: JSONRPCRequest) => super.routerHandler(jsonrpcReq))); 63 | } else { 64 | result = await super.routerHandler(req); 65 | } 66 | respondWith(JSON.stringify(result)); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/transports/server-transport.test.ts: -------------------------------------------------------------------------------- 1 | import ServerTransport from "./server-transport"; 2 | 3 | describe("Server transport test", () => { 4 | 5 | class DummyTransport extends ServerTransport { 6 | 7 | } 8 | 9 | it("transport implementation throws without start", async () => { 10 | await expect(async () => { await new DummyTransport().start(); }).rejects.toThrowError(); 11 | }); 12 | 13 | it("throws if no router is configured", async () => { 14 | const t = new DummyTransport(); 15 | await expect(t['routerHandler']({ jsonrpc: "2.0", id: "1", method: "foo", params: [] })) 16 | .rejects.toThrow("No router configured"); 17 | }); 18 | 19 | it("returns method not found if method is not implemented", async () => { 20 | const t = new DummyTransport(); 21 | // Mock a router that doesn't implement any method 22 | const fakeRouter = { isMethodImplemented: () => false, call: jest.fn() } as unknown as import("../router").Router; 23 | t.addRouter(fakeRouter); 24 | const result = await t['routerHandler']({ jsonrpc: "2.0", id: "1", method: "foo", params: [] }); 25 | expect(result.error).toBeDefined(); 26 | expect(result.error?.code).toBe(-32601); // Method not found 27 | }); 28 | 29 | it("returns result if method is implemented", async () => { 30 | const t = new DummyTransport(); 31 | const fakeRouter = { 32 | isMethodImplemented: () => true, 33 | call: async () => ({ result: 42 }), 34 | } as unknown as import("../router").Router; 35 | t.addRouter(fakeRouter); 36 | const result = await t['routerHandler']({ jsonrpc: "2.0", id: "1", method: "bar", params: [] }); 37 | expect(result.result).toBe(42); 38 | }); 39 | 40 | it("covers the no router configured branch in routerHandler", async () => { 41 | class DummyTransport extends ServerTransport {} 42 | const t = new DummyTransport(); 43 | await expect( 44 | t['routerHandler']({ jsonrpc: "2.0", id: "no-router", method: "foo", params: [] }) 45 | ).rejects.toThrow("No router configured"); 46 | }); 47 | 48 | it("throws if stop is not implemented", async () => { 49 | class DummyTransport extends ServerTransport {} 50 | const t = new DummyTransport(); 51 | await expect(t.stop()).rejects.toThrow("Transport missing stop implementation"); 52 | }); 53 | 54 | }); 55 | -------------------------------------------------------------------------------- /src/transports/server-transport.ts: -------------------------------------------------------------------------------- 1 | import { Router } from "../router"; 2 | 3 | export interface JSONRPCRequest { 4 | jsonrpc: string; 5 | id?: string; 6 | method: string; 7 | params: any[] | Record; 8 | } 9 | 10 | export interface JSONRPCErrorObject { 11 | code: number; 12 | message: string; 13 | data: any; 14 | } 15 | 16 | export interface JSONRPCResponse { 17 | jsonrpc: string; 18 | id?: string; 19 | result?: any; 20 | error?: JSONRPCErrorObject; 21 | } 22 | 23 | export abstract class ServerTransport { 24 | public routers: Router[] = []; 25 | 26 | public addRouter(router: Router): void { 27 | this.routers.push(router); 28 | } 29 | 30 | public removeRouter(router: Router): void { 31 | this.routers = this.routers.filter((r) => r !== router); 32 | } 33 | 34 | public async start(): Promise { 35 | console.warn("Transport must implement start()"); // tslint:disable-line 36 | throw new Error("Transport missing start implementation"); 37 | } 38 | 39 | public async stop(): Promise { 40 | console.warn("Transport must implement stop()"); // tslint:disable-line 41 | throw new Error("Transport missing stop implementation"); 42 | } 43 | 44 | protected async routerHandler({ id, method, params }: JSONRPCRequest): Promise { 45 | if (this.routers.length === 0) { 46 | console.warn("transport method called without a router configured."); // tslint:disable-line 47 | throw new Error("No router configured"); 48 | } 49 | 50 | const routerForMethod = this.routers.find((r) => r.isMethodImplemented(method)); 51 | 52 | let res = { 53 | id, 54 | jsonrpc: "2.0", 55 | }; 56 | 57 | if (routerForMethod === undefined) { 58 | // method not found in any of the routers. 59 | res = { 60 | ...res, 61 | ...Router.methodNotFoundHandler(method) 62 | }; 63 | } else { 64 | res = { 65 | ...res, 66 | ...await routerForMethod.call(method, params) 67 | }; 68 | } 69 | 70 | return res; 71 | } 72 | } 73 | export default ServerTransport; -------------------------------------------------------------------------------- /src/transports/websocket.test.ts: -------------------------------------------------------------------------------- 1 | import examples from "@open-rpc/examples"; 2 | import { parseOpenRPCDocument } from "@open-rpc/schema-utils-js"; 3 | import { Router } from "../router"; 4 | import * as fs from "fs"; 5 | import { promisify } from "util"; 6 | const readFile = promisify(fs.readFile); 7 | import WebSocket from "ws"; 8 | import WebSocketTransport from "./websocket"; 9 | import { JSONRPCResponse } from "./server-transport"; 10 | import connect from "connect"; 11 | 12 | describe("WebSocket transport", () => { 13 | 14 | it("can start an https server that works", async () => { 15 | expect.assertions(1); 16 | const simpleMathExample = await parseOpenRPCDocument(examples.simpleMath); 17 | 18 | const transport = new WebSocketTransport({ 19 | cert: await readFile(`${process.cwd()}/test-cert/server.cert`), 20 | key: await readFile(`${process.cwd()}/test-cert/server.key`), 21 | middleware: [], 22 | port: 9698, 23 | }); 24 | 25 | const router = new Router(simpleMathExample, { mockMode: true }); 26 | transport.addRouter(router); 27 | await transport.start(); 28 | 29 | const ws = new WebSocket("wss://localhost:9698", { rejectUnauthorized: false }); 30 | let done: any; 31 | const handleMessage = (data: string) => { 32 | ws.off("message", handleMessage); 33 | void transport.stop(); 34 | const { result } = JSON.parse(data); 35 | expect(result).toBe(4); 36 | setTimeout(done, 3500); // give ws 3.5 seconds to shutdown 37 | }; 38 | const handleConnnect = () => { 39 | ws.off("open", handleConnnect); 40 | ws.on("message", handleMessage); 41 | ws.send(JSON.stringify({ 42 | id: "0", 43 | jsonrpc: "2.0", 44 | method: "addition", 45 | params: [2, 2], 46 | })); 47 | }; 48 | const prom = new Promise((resolve) => { 49 | done = resolve; 50 | ws.on("open", handleConnnect); 51 | }); 52 | await prom; 53 | }); 54 | 55 | it("can start an https server that works", async () => { 56 | const simpleMathExample = await parseOpenRPCDocument(examples.simpleMath); 57 | 58 | const transport = new WebSocketTransport({ 59 | middleware: [], 60 | port: 9698, 61 | }); 62 | 63 | const router = new Router(simpleMathExample, { mockMode: true }); 64 | transport.addRouter(router); 65 | await transport.start(); 66 | 67 | const ws = new WebSocket("ws://localhost:9698", { rejectUnauthorized: false }); 68 | let done: any; 69 | const handleMessage = (data: string) => { 70 | ws.off("message", handleMessage); 71 | void transport.stop(); 72 | const { result } = JSON.parse(data); 73 | expect(result).toBe(4); 74 | setTimeout(done, 3500); // give ws 3.5 seconds to shutdown 75 | }; 76 | const handleConnnect = () => { 77 | ws.off("open", handleConnnect); 78 | ws.on("message", handleMessage); 79 | ws.send(JSON.stringify({ 80 | id: "1", 81 | jsonrpc: "2.0", 82 | method: "addition", 83 | params: [2, 2], 84 | })); 85 | }; 86 | await new Promise((resolve) => { 87 | done = resolve; 88 | ws.on("open", handleConnnect); 89 | }); 90 | }); 91 | 92 | it("works with batching", async () => { 93 | const simpleMathExample = await parseOpenRPCDocument(examples.simpleMath); 94 | 95 | const transport = new WebSocketTransport({ 96 | cert: await readFile(`${process.cwd()}/test-cert/server.cert`), 97 | key: await readFile(`${process.cwd()}/test-cert/server.key`), 98 | middleware: [], 99 | port: 9698, 100 | }); 101 | 102 | const router = new Router(simpleMathExample, { mockMode: true }); 103 | transport.addRouter(router); 104 | await transport.start(); 105 | 106 | const ws = new WebSocket("wss://localhost:9698", { rejectUnauthorized: false }); 107 | let done: any; 108 | const handleMessage = (data: string) => { 109 | ws.off("message", handleMessage); 110 | void transport.stop(); 111 | const result = JSON.parse(data) as JSONRPCResponse[]; 112 | expect(result.map((r) => r.result)).toEqual([4, 8]); 113 | transport.removeRouter(router); 114 | setTimeout(done, 3500); // give ws 3.5 seconds to shutdown 115 | }; 116 | 117 | const handleConnnect = () => { 118 | ws.off("open", handleConnnect); 119 | ws.on("message", handleMessage); 120 | 121 | ws.send(JSON.stringify([ 122 | { 123 | id: "2", 124 | jsonrpc: "2.0", 125 | method: "addition", 126 | params: [2, 2], 127 | }, { 128 | id: "3", 129 | jsonrpc: "2.0", 130 | method: "addition", 131 | params: [4, 4], 132 | }, 133 | ])); 134 | }; 135 | 136 | await new Promise((resolve) => { 137 | done = resolve; 138 | ws.on("open", handleConnnect); 139 | }); 140 | }); 141 | 142 | it("allows using an existing app (WebSocket)", async () => { 143 | const app = connect(); 144 | const simpleMathExample = await parseOpenRPCDocument(examples.simpleMath); 145 | const transport = new WebSocketTransport({ 146 | middleware: [], 147 | port: 9704, 148 | app, 149 | }); 150 | const router = new Router(simpleMathExample, { mockMode: true }); 151 | transport.addRouter(router); 152 | await transport.start(); 153 | 154 | const ws = new WebSocket("ws://localhost:9704"); 155 | let done: any; 156 | const handleMessage = (data: string) => { 157 | ws.off("message", handleMessage); 158 | void transport.stop(); 159 | const { result } = JSON.parse(data); 160 | expect(result).toBe(4); 161 | setTimeout(done, 3500); // give ws 3.5 seconds to shutdown 162 | }; 163 | const handleConnnect = () => { 164 | ws.off("open", handleConnnect); 165 | ws.on("message", handleMessage); 166 | ws.send(JSON.stringify({ 167 | id: "custom-app", 168 | jsonrpc: "2.0", 169 | method: "addition", 170 | params: [2, 2], 171 | })); 172 | }; 173 | await new Promise((resolve) => { 174 | done = resolve; 175 | ws.on("open", handleConnnect); 176 | }); 177 | }, 30000); 178 | 179 | it("handles errors when starting the server (WebSocket)", async () => { 180 | const transport = new WebSocketTransport({ 181 | middleware: [], 182 | port: 9705, 183 | }); 184 | const serverInstance = (transport as any).server; 185 | const originalListen = serverInstance.listen.bind(serverInstance); 186 | serverInstance.listen = (port: number, cb: (err?: Error) => void) => { 187 | cb(new Error("Mock listen error")); 188 | return serverInstance; 189 | }; 190 | await expect(transport.start()).rejects.toThrow("Mock listen error"); 191 | serverInstance.listen = originalListen; 192 | // Do not call stop, since server never started 193 | }); 194 | 195 | it("handles errors when stopping the server (WebSocket)", async () => { 196 | const transport = new WebSocketTransport({ 197 | middleware: [], 198 | port: 9706, 199 | }); 200 | await transport.start(); 201 | const serverInstance = (transport as any).server; 202 | const originalClose = serverInstance.close.bind(serverInstance); 203 | serverInstance.close = (cb: (err?: Error) => void) => { 204 | cb(new Error("Mock close error")); 205 | }; 206 | await expect(transport.stop()).rejects.toThrow("Mock close error"); 207 | serverInstance.close = originalClose; 208 | }); 209 | 210 | it("properly terminates sockets in OPEN state during stop", async () => { 211 | // Create a transport without actually starting the server 212 | const transport = new WebSocketTransport({ 213 | middleware: [], 214 | port: 9707, 215 | }); 216 | 217 | // Create a mock WebSocket.Server with the necessary properties 218 | const mockWss = { 219 | clients: new Set(), 220 | close: jest.fn((cb) => cb()), 221 | removeAllListeners: jest.fn() 222 | }; 223 | 224 | // Replace the transport's WebSocket.Server with our mock 225 | (transport as any).wss = mockWss; 226 | 227 | // Create a mock socket in OPEN state 228 | const mockOpenSocket = { 229 | close: jest.fn(), 230 | terminate: jest.fn(), 231 | OPEN: WebSocket.OPEN, 232 | CLOSING: WebSocket.CLOSING, 233 | readyState: WebSocket.OPEN 234 | }; 235 | 236 | // Add the mock socket to our clients collection 237 | mockWss.clients.add(mockOpenSocket); 238 | 239 | // Replace the transport's server.close with a mock implementation 240 | const mockServer = { 241 | close: jest.fn((cb) => cb()) 242 | }; 243 | (transport as any).server = mockServer; 244 | 245 | // Call stop - this should invoke our mock implementations 246 | await transport.stop(); 247 | 248 | // Verify the socket was first closed softly and then terminated 249 | expect(mockOpenSocket.close).toHaveBeenCalled(); 250 | expect(mockOpenSocket.terminate).toHaveBeenCalled(); 251 | expect(mockWss.removeAllListeners).toHaveBeenCalled(); 252 | expect(mockWss.close).toHaveBeenCalled(); 253 | expect(mockServer.close).toHaveBeenCalled(); 254 | }); 255 | 256 | it("properly terminates sockets in CLOSING state during stop", async () => { 257 | // Create a transport without actually starting the server 258 | const transport = new WebSocketTransport({ 259 | middleware: [], 260 | port: 9708, 261 | }); 262 | 263 | // Create a mock WebSocket.Server with the necessary properties 264 | const mockWss = { 265 | clients: new Set(), 266 | close: jest.fn((cb) => cb()), 267 | removeAllListeners: jest.fn() 268 | }; 269 | 270 | // Replace the transport's WebSocket.Server with our mock 271 | (transport as any).wss = mockWss; 272 | 273 | // Create a mock socket in CLOSING state 274 | const mockClosingSocket = { 275 | close: jest.fn(), 276 | terminate: jest.fn(), 277 | OPEN: WebSocket.OPEN, 278 | CLOSING: WebSocket.CLOSING, 279 | readyState: WebSocket.CLOSING 280 | }; 281 | 282 | // Add the mock socket to our clients collection 283 | mockWss.clients.add(mockClosingSocket); 284 | 285 | // Replace the transport's server.close with a mock implementation 286 | const mockServer = { 287 | close: jest.fn((cb) => cb()) 288 | }; 289 | (transport as any).server = mockServer; 290 | 291 | // Call stop - this should invoke our mock implementations 292 | await transport.stop(); 293 | 294 | // Verify the socket was first closed softly and then terminated 295 | expect(mockClosingSocket.close).toHaveBeenCalled(); 296 | expect(mockClosingSocket.terminate).toHaveBeenCalled(); 297 | expect(mockWss.removeAllListeners).toHaveBeenCalled(); 298 | expect(mockWss.close).toHaveBeenCalled(); 299 | expect(mockServer.close).toHaveBeenCalled(); 300 | }); 301 | 302 | it("does not terminate sockets that are already closed", async () => { 303 | // Create a transport without actually starting the server 304 | const transport = new WebSocketTransport({ 305 | middleware: [], 306 | port: 9709, 307 | }); 308 | 309 | // Create a mock WebSocket.Server with the necessary properties 310 | const mockWss = { 311 | clients: new Set(), 312 | close: jest.fn((cb) => cb()), 313 | removeAllListeners: jest.fn() 314 | }; 315 | 316 | // Replace the transport's WebSocket.Server with our mock 317 | (transport as any).wss = mockWss; 318 | 319 | // Create a mock socket in CLOSED state 320 | const mockClosedSocket = { 321 | close: jest.fn(), 322 | terminate: jest.fn(), 323 | OPEN: WebSocket.OPEN, 324 | CLOSING: WebSocket.CLOSING, 325 | CLOSED: WebSocket.CLOSED, 326 | readyState: WebSocket.CLOSED 327 | }; 328 | 329 | // Add the mock socket to our clients collection 330 | mockWss.clients.add(mockClosedSocket); 331 | 332 | // Replace the transport's server.close with a mock implementation 333 | const mockServer = { 334 | close: jest.fn((cb) => cb()) 335 | }; 336 | (transport as any).server = mockServer; 337 | 338 | // Call stop - this should invoke our mock implementations 339 | await transport.stop(); 340 | 341 | // Verify close was called but terminate was not 342 | expect(mockClosedSocket.close).toHaveBeenCalled(); 343 | expect(mockClosedSocket.terminate).not.toHaveBeenCalled(); 344 | expect(mockWss.removeAllListeners).toHaveBeenCalled(); 345 | expect(mockWss.close).toHaveBeenCalled(); 346 | expect(mockServer.close).toHaveBeenCalled(); 347 | }); 348 | 349 | it("applies default timeout when none provided", () => { 350 | const transport = new WebSocketTransport({ 351 | middleware: [], 352 | port: 9710, 353 | }); 354 | expect((transport as any).options.timeout).toBe(3000); 355 | }); 356 | 357 | it("respects provided timeout", () => { 358 | const transport = new WebSocketTransport({ 359 | middleware: [], 360 | port: 9711, 361 | timeout: 5000, 362 | }); 363 | expect((transport as any).options.timeout).toBe(5000); 364 | }); 365 | }); 366 | -------------------------------------------------------------------------------- /src/transports/websocket.ts: -------------------------------------------------------------------------------- 1 | import cors from "cors"; 2 | import { json as jsonParser } from "body-parser"; 3 | import connect, { HandleFunction, Server as ConnectApp } from "connect"; 4 | import http2, { Http2SecureServer, SecureServerOptions } from "http2"; 5 | import http from "http"; 6 | import ServerTransport, { JSONRPCRequest } from "./server-transport"; 7 | import WebSocket from "ws"; 8 | 9 | export interface WebSocketServerTransportOptions extends SecureServerOptions { 10 | middleware: HandleFunction[]; 11 | port: number; 12 | cors?: cors.CorsOptions; 13 | allowHTTP1?: boolean; 14 | app?: ConnectApp; 15 | timeout?: number; 16 | } 17 | 18 | export default class WebSocketServerTransport extends ServerTransport { 19 | private static defaultCorsOptions = { origin: "*" }; 20 | private server: Http2SecureServer | http.Server; 21 | private wss: WebSocket.Server; 22 | 23 | constructor(private options: WebSocketServerTransportOptions) { 24 | super(); 25 | // Ensure a default timeout if none provided 26 | options.timeout = options.timeout ?? 3000; 27 | options.allowHTTP1 = true; 28 | 29 | const app = options.app || connect(); 30 | 31 | const corsOptions = options.cors || WebSocketServerTransport.defaultCorsOptions; 32 | this.options = { 33 | ...options, 34 | app, 35 | middleware: [ 36 | cors(corsOptions) as HandleFunction, 37 | jsonParser({ 38 | limit: "1mb" 39 | }), 40 | ...options.middleware, 41 | ], 42 | }; 43 | 44 | this.options.middleware.forEach((mw) => app.use(mw)); 45 | 46 | if (!this.options.cert && !this.options.key) { 47 | this.server = http.createServer((req: any, res: any) => app(req, res)); 48 | } else { 49 | this.server = http2.createSecureServer(options, (req: any, res: any) => app(req, res)); 50 | } 51 | this.wss = new WebSocket.Server({ server: this.server as any }); 52 | 53 | this.wss.on("connection", (ws: WebSocket) => { 54 | ws.on( 55 | "message", 56 | (message: string) => this.webSocketRouterHandler(JSON.parse(message), ws.send.bind(ws)), 57 | ); 58 | ws.on("close", () => ws.removeAllListeners()); 59 | }); 60 | } 61 | 62 | public async start(): Promise { 63 | return new Promise((resolve, reject) => { 64 | this.server.listen(this.options.port, (err?: Error) => { 65 | if (err) return reject(err); 66 | resolve(); 67 | }); 68 | }); 69 | } 70 | 71 | public async stop(): Promise { 72 | // First sweep, soft close 73 | this.wss.clients.forEach((socket) => { 74 | socket.close(); 75 | }); 76 | // Wait for sockets to close, then hard close any remaining 77 | await new Promise((resolve) => setTimeout(resolve, this.options.timeout)); 78 | this.wss.clients.forEach((socket) => { 79 | if ([socket.OPEN, socket.CLOSING].includes((socket as any).readyState)) { 80 | socket.terminate(); 81 | } 82 | }); 83 | this.wss.removeAllListeners(); 84 | await new Promise((resolve) => this.wss.close(() => resolve())); 85 | await new Promise((resolve, reject) => { 86 | this.server.close((err?: Error) => { 87 | if (err) return reject(err); 88 | resolve(); 89 | }); 90 | }); 91 | } 92 | 93 | private async webSocketRouterHandler(req: any, respondWith: any) { 94 | let result = null; 95 | if (req instanceof Array) { 96 | result = await Promise.all(req.map((r: JSONRPCRequest) => super.routerHandler(r))); 97 | } else { 98 | result = await super.routerHandler(req); 99 | } 100 | respondWith(JSON.stringify(result)); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /test-cert/server.cert: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIF2TCCA8GgAwIBAgIUJ6kMgLRS6+bJN7Kb4piyI2CtFkcwDQYJKoZIhvcNAQEL 3 | BQAwezELMAkGA1UEBhMCWFgxEjAQBgNVBAgMCVN0YXRlTmFtZTERMA8GA1UEBwwI 4 | Q2l0eU5hbWUxFDASBgNVBAoMC0NvbXBhbnlOYW1lMRswGQYDVQQLDBJDb21wYW55 5 | U2VjdGlvbk5hbWUxEjAQBgNVBAMMCWxvY2FsaG9zdDAgFw0yNDA1MDkxODQ2MjZa 6 | GA8yMDUwMTAxMDE4NDYyNlowezELMAkGA1UEBhMCWFgxEjAQBgNVBAgMCVN0YXRl 7 | TmFtZTERMA8GA1UEBwwIQ2l0eU5hbWUxFDASBgNVBAoMC0NvbXBhbnlOYW1lMRsw 8 | GQYDVQQLDBJDb21wYW55U2VjdGlvbk5hbWUxEjAQBgNVBAMMCWxvY2FsaG9zdDCC 9 | AiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAJOgXb064LitoIxj/PBWzZje 10 | z+zt3TxeHsA/Kq2U8Wi3zAGNPZuwOlsJ6pD9fJfNtvpZJZk4tKkOb2WykuCe+EH1 11 | fTz9DNS2WLIbzqMLXQ7GU1AIYR+Xh4lBw7D0LsdFhJfUwYE3d/6t8g2gcVWsP7bz 12 | P6oyvGGsqFkcgXjaIodF2Pk6qTdx7sKSZCeYd2L76MJmPmWnBYSMLachM7aao7zc 13 | Z30KHNJfC0qjoG8ybvK8D69NrZG9itH8ingargZrHavAUbyCXUsRF6rhB505D7dy 14 | +1Knf+oLxicgVzPH/lHiVOSNyEuN3xUQrFi9JP8EEkM97YehtRp2Z7YKZIgOSnQs 15 | acc08eR9wmTYyzeXKeZxv2AvEvd/0Jx6YdzCWkTpDOZw9wejh07erPnbkqllRqGG 16 | mBaptFx0+/zKU+ljUC16gwcc03y5jeDG0mQbDTTnsFoMM5RmNdjvdlcIdSZjMAkz 17 | zQ06lm22IttYt/1UwhFR1+lJ5HMF29uPxvwGhG8Ols2t3ilGk9XmdTXCtLTxHxEj 18 | SdEvGL79ZqUtK4V2gCT+IqCgRMATzcYPJY4zyl3ZZgFqNKbumZU/Ey+b8xXr/ldK 19 | LUfDBDfzfqROEx5uhB/MDYMq6ClHsxazMhVOREz2WDchfKPXvd6fElRFk3Pro6Mn 20 | L1RuEGc2BliL6Zm1PqrtAgMBAAGjUzBRMB0GA1UdDgQWBBTp5symPyOreKywu6g7 21 | o+nb4XxeKjAfBgNVHSMEGDAWgBTp5symPyOreKywu6g7o+nb4XxeKjAPBgNVHRMB 22 | Af8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4ICAQAySeOpomEZ6GrWTxD6J3VdFQTt 23 | GIysCISLddcNifA8yB2lAti1pNRfxv3SW3z6CyOiGDQi+8GUScVFuK0rcdLKye5Z 24 | CLJ8vOl0E3PCVl14aoYFquknPa3tGmdVmF5M0Yf3FcqXhaWagaJDKs+8WADSGTC+ 25 | GD58d/Gy+iR2hCTXSFE2lYfsw3cG2WtkrXon1AOkJi6h027SRTRLGP99JaDDX8LW 26 | sLM2CvJnJAwqc1GI6laqJ25S5/wZmdnEfzhs0dznRqmPXv1VH/xsAKnGhdbEC5pe 27 | jO6PMIbJFxaGnCg6GCs38jOgoNbWdS3XQfzF07sqM2yjkn7fvGyPzeY7JS+tL5Ix 28 | VzcJh7eBAoUygdA3yXO4zi++VJyGyK6rz+YjRlgE8YE70ESToNiZXT6iUKmx8E1f 29 | FwqTmHOsJ6EAicB5kYhXAylDdU6bYt1tbNTI729d3sR47c4fACaFsBaKsrOoNkmF 30 | gbsIEbeA1noPUwX5/DDrCMbczfPloe3M+b8tXQcYSuUYBHcBziMRD3iTuBzA4n3l 31 | shUuVkNZRgWvNg4EXEs3RQZbTW+sp0Rapw83OBE9GNTvUsOJ2kQyc7JtKrzHjdI3 32 | K2bTcZXPGiNEk7KFXwbvxhgaSEabzm5Uzr1abHT/sXlXkw0TbhWiCZyzUaFu0uBJ 33 | 9rusp0JnjfQcdTymZg== 34 | -----END CERTIFICATE----- 35 | -------------------------------------------------------------------------------- /test-cert/server.key: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQCToF29OuC4raCM 3 | Y/zwVs2Y3s/s7d08Xh7APyqtlPFot8wBjT2bsDpbCeqQ/XyXzbb6WSWZOLSpDm9l 4 | spLgnvhB9X08/QzUtliyG86jC10OxlNQCGEfl4eJQcOw9C7HRYSX1MGBN3f+rfIN 5 | oHFVrD+28z+qMrxhrKhZHIF42iKHRdj5Oqk3ce7CkmQnmHdi++jCZj5lpwWEjC2n 6 | ITO2mqO83Gd9ChzSXwtKo6BvMm7yvA+vTa2RvYrR/Ip4Gq4Gax2rwFG8gl1LEReq 7 | 4QedOQ+3cvtSp3/qC8YnIFczx/5R4lTkjchLjd8VEKxYvST/BBJDPe2HobUadme2 8 | CmSIDkp0LGnHNPHkfcJk2Ms3lynmcb9gLxL3f9CcemHcwlpE6QzmcPcHo4dO3qz5 9 | 25KpZUahhpgWqbRcdPv8ylPpY1AteoMHHNN8uY3gxtJkGw0057BaDDOUZjXY73ZX 10 | CHUmYzAJM80NOpZttiLbWLf9VMIRUdfpSeRzBdvbj8b8BoRvDpbNrd4pRpPV5nU1 11 | wrS08R8RI0nRLxi+/WalLSuFdoAk/iKgoETAE83GDyWOM8pd2WYBajSm7pmVPxMv 12 | m/MV6/5XSi1HwwQ3836kThMeboQfzA2DKugpR7MWszIVTkRM9lg3IXyj173enxJU 13 | RZNz66OjJy9UbhBnNgZYi+mZtT6q7QIDAQABAoICAB7ugk2grU7MxH++AJTMH0qJ 14 | XwguA8W/E9LkuVjDBT0Ti7mEglThfSyvnHgyQL2e8xir/qKG3OWyOlmU680ISgyp 15 | 9wqFG//i0B1LkcWcXyx2FiVGCDGiIpo6Dxp/42BJ+uEESWI9gNU6VaYQyMZyb6wx 16 | 9hQ/irSthF2diSxNCmCNHEwGREfzhZs7qKQaQGObVDcNTMQoVZHi/DrRTGBVsPqk 17 | tMNgj87tbrR+KeK6rsAJ8wBgdn57uD9M2qeVMYLzRTWEN6wXpZwRsgOSIHILL3WY 18 | 8DtukLD1tBhlIJhfLnSyR2bXJVFdYdFsW6xBP2P2kqwHqQIa+hMYHZ1pOoy+b89r 19 | o3ZY+CrLd1srYYCbTh+2gAieVOKFUTG6r04mRjGNZ06pp41VtjTM3wE+ZIplalI7 20 | w5Xw0s3MRLmymeeQTkrCJbdTmti9naT+7XThzMfvp6AiTXh51Uji5X8tGPTrPUai 21 | GF1XqoJKM6chE/sbd0u6rFFsRdcGs/EkM6uknMdzjWtSHawFsf1AZHr6i61Rr7od 22 | 06BE78iEJamCAU0s9dQ6s5EkOHO1IYKW8h9JDP2ZRFBF2lhuOWu0TZtErhz5Eg93 23 | Lg2kPrzF2l209lvekME9xJExMm6Qeo2nQL5G0F2KTFvi72oAa9aeRVzCetpIEVQd 24 | lOQBYyzfoXGzlSQaNDFhAoIBAQC5eXj7g218vWMde0vHi1lnwBZM9GdZfoXKtRDs 25 | 69j9XzJ2+YuhIcCkUSU6iTRNJZl65GTxgxGkVc6AsWhqeff8PLw6R5dCXscQtLLp 26 | vHjTK9SgsSP1Z27bAMEqhalI6seP7jrOUi7rVWdUEty/TJq4nkjWWr2yIgfr+W8x 27 | Adyqzl1lYlqs7EJZi6+dUEi+9g8ABlz8B9cw/t0VeoiP0C0KhIYPfoN6BR8wf1d/ 28 | v3BB6yTNX6GDW20JeJPfG6EQ9NsD+IE9S+qMitOTM3upC5lqrZ3TKR91XknCiv2A 29 | to9uSkHa1BxO5VY+RgFrGpreExPKTTxJpiTGciPoIzlt3sGNAoIBAQDLwqwvmz2A 30 | hmjRZ8/xhGdljEv83zZnTk7ShJm6uAzlVBz7x9IpqG6kB8uiwF8qlNtufVBLE1qm 31 | nkR8OtKfxdpu2ko1M4lS13xleORp+QxGHbM2hj3po+ZWGAsN+wJ8BDRMgUlytxPD 32 | 2r58196vzZgU8X7Ygy6v4hRnF1GEKvG5OKOFxuvlOAShnZIKLhXwCs0Y/cr2ZXTo 33 | dt7DjgKpXIO+uz2txFwbEFM6o4sesZfTJfOqiYCxp74buyhWVyJk/624Wg4qjIh4 34 | eDFn9An64pfBUb8jc1V57J8VAiKZzYxp4zJ2FcE9/PcFl7ena8UG/bJq+PLrzp+d 35 | 58QvY9qmMkbhAoIBAGJW4aqZWKfW0oKDKP64B8NWuXw76cAtsUp1DnBP7FEK9HrY 36 | fQwGFVoKHC8ZKD3vPZ1HE65pzCTRyhe5+J7b5Hw8x6Au7SgnkGxvIp2DbJyqlKZO 37 | xb4MBV7g24psLAGZWg4aRdu2/2GPeqW9CoXzW+WfJwdgPUwBdynKqwXU8uctW5+x 38 | sloVOmi4A3jpZGi7leBxf0Ox9Irp1tbYjSeTPQ5ijaIRdixwIsVX/1CgdCi/QFgT 39 | 6FL5Wqq239BfmdqfuLA2Rm/1nHq/8MYPefV7TPCe9RtMpn1YbMtVXmusYAgeHySj 40 | ag760etaus3K4Wn1u3x7zwdNrBn70sX2RzDV9tECggEAQvatY8/e/HgvxnIZksPy 41 | vxrGdkpdNMI1gVX2t7h49H0aMVzQIsSp59pwAAK8w9+75anlU2b+6bclxrYGNl/t 42 | k3TF4ooXXVRYG3kJiBJDCGAGX6rqefhVYIHyUBvoCx3Omj37B2pHYpxm8dx34Mru 43 | aiObjkg+dasVDXRKY+dBHaARjYt8Rw6L5xlDv3i52POTx9zQcP2S2DsIprfrBAHV 44 | gj9C2/KmWnaZA7JvrBytSsU0OR2LX9dC0RZHAWkNcqfcTbO66BzbVMwbYJCBHySM 45 | vwnAiUQEGVe8SEk1WdqFhN8X3Fr18QtLm1jrEGiIje2eTy2VmA2Fw31BqllkqC3p 46 | wQKCAQEAqPxodNK1vn+1buzlYGFD0dJV6T4pDavcb1Fsf4/x5n4OHRvpFi8L2V9w 47 | N9KyUYNcxYL9cIWBkoMfRDsOAzk8zjEEsJ+d9AsX6jbqA8SA1UpqZqGv8urFm1AM 48 | OeJjcrU765ljxXIjN981+mvwm/ZjkVpECD5CgsOq4wmCdG8ej/8ciimYpAuN1poT 49 | nDaLQCNtaFL/Sj9vLOzxH89JW9cNz7zIuzKgFtXZBAteb83zq1RCudvBcAF6Bcmy 50 | 1fJW1PPtEm045vKcNsQkaBrYXnraIwqMBorkFSFJEe5jZYSUJcD8zUpiwBAhaVel 51 | K10l+0l1vL5lhXAvouFIrqW0bVbfNg== 52 | -----END PRIVATE KEY----- 53 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "lib": ["ES2018"], 5 | "target": "ES2018", 6 | "module": "commonjs", 7 | "moduleResolution": "node", 8 | "declaration": true, 9 | "outDir": "./build", 10 | "strict": true, 11 | "esModuleInterop": true, 12 | "resolveJsonModule": true 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /tsfmt.json: -------------------------------------------------------------------------------- 1 | { 2 | "baseIndentSize": 0, 3 | "indentSize": 2, 4 | "tabSize": 2, 5 | "indentStyle": 2, 6 | "newLineCharacter": "\r\n", 7 | "convertTabsToSpaces": true, 8 | "insertSpaceAfterCommaDelimiter": true, 9 | "insertSpaceAfterSemicolonInForStatements": true, 10 | "insertSpaceBeforeAndAfterBinaryOperators": true, 11 | "insertSpaceAfterConstructor": false, 12 | "insertSpaceAfterKeywordsInControlFlowStatements": true, 13 | "insertSpaceAfterFunctionKeywordForAnonymousFunctions": false, 14 | "insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis": false, 15 | "insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets": false, 16 | "insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": true, 17 | "insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces": false, 18 | "insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces": false, 19 | "insertSpaceAfterTypeAssertion": false, 20 | "insertSpaceBeforeFunctionParenthesis": false, 21 | "insertSpaceBeforeTypeAnnotation": false, 22 | "placeOpenBraceOnNewLineForFunctions": false, 23 | "placeOpenBraceOnNewLineForControlBlocks": false 24 | } 25 | --------------------------------------------------------------------------------