refactor: move core-tools to monorepo

This commit is contained in:
2023-03-14 17:08:48 +01:00
parent 0ebfc57fd6
commit 721ea0fe67
73 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,15 @@
# editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false

View File

@@ -0,0 +1,2 @@
resources
openapi

View File

@@ -0,0 +1,102 @@
{
"root": true,
"ignorePatterns": [
"projects/**/*"
],
"overrides": [
{
"files": [
"*.ts"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2020,
"sourceType": "module",
"project": [
"tsconfig.json"
],
"createDefaultProgram": true
},
"extends": [
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended",
"plugin:prettier/recommended",
"plugin:jsdoc/recommended",
"plugin:unicorn/recommended"
],
"plugins": [
"eslint-plugin-unicorn",
"eslint-plugin-jsdoc",
"prettier"
],
"settings": {
"jsdoc": {
"mode": "typescript"
}
},
"rules": {
"unicorn/filename-case": "error",
"unicorn/no-array-callback-reference": "off",
"unicorn/no-useless-undefined": "off",
"unicorn/prefer-node-protocol": "off",
"unicorn/no-process-exit": "off",
"unicorn/prevent-abbreviations": [
"error",
{
"replacements": {
"ref": false,
"i": false
}
}
],
"unicorn/no-nested-ternary": "off",
"unicorn/better-regex": "off",
"jsdoc/no-types": "error",
"jsdoc/require-param": "off",
"jsdoc/require-param-description": "error",
"jsdoc/check-param-names": "error",
"jsdoc/require-returns": "off",
"jsdoc/require-param-type": "off",
"jsdoc/require-returns-type": "off",
"jsdoc/check-tag-names": [
"error",
{
"definedTags": ["internal"]
}
],
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-unused-vars": [
"error",
{
"args": "after-used",
"argsIgnorePattern": "^_"
}
],
"@typescript-eslint/lines-between-class-members": [
"error",
"always"
],
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/no-non-null-assertion": "off",
"prettier/prettier": [
"error",
{
"tabWidth": 2,
"printWidth": 110,
"useTabs": false,
"semi": true,
"singleQuote": true,
"quoteProps": "consistent",
"trailingComma": "all",
"bracketSpacing": false,
"arrowParens": "avoid",
"endOfLine": "lf"
}
]
}
}
]
}

98
packages/core-tools/.gitignore vendored Normal file
View File

@@ -0,0 +1,98 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
.DS_Store
# Schema generation data
Diagram-*.svg
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
# parcel-bundler cache (https://parceljs.org/)
.cache
# next.js build output
.next
# nuxt.js build output
.nuxt
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
#DynamoDB Local files
.dynamodb/
########## end of https://github.com/github/gitignore/blob/master/Node.gitignore
# ignore ide files
.idea
.vscode
# ignore lib directory
lib/
# ignore docs directory
docs/
# ignore openapi resources
openapi/

View File

@@ -0,0 +1,88 @@
image: registry.gitlab.com/openstapps/projectmanagement/node
before_script:
- npm ci
stages:
- build
- test
- audit
- deploy
build:
stage: build
script:
- npm run build
artifacts:
paths:
- lib
test:
stage: test
script:
- npm test
audit:
stage: audit
script:
- npm audit
allow_failure: true
except:
- schedules
scheduled-audit:
stage: audit
script:
- npm audit --audit-level=high
only:
- schedules
openapi:
dependencies:
- build
stage: test
script:
- npm install @openstapps/core
- node lib/cli.js openapi node_modules/@openstapps/core/lib openapi
- NUMBER_OF_LINES=$(cat openapi/openapi.json | wc -l)
- if [ "$NUMBER_OF_LINES" -lt 100 ]; then exit 1; fi
artifacts:
paths:
- openapi/openapi.json
package:
dependencies:
- build
tags:
- secrecy
stage: deploy
script:
- echo "//registry.npmjs.org/:_authToken=$NPM_AUTH_TOKEN" > ~/.npmrc
- npm publish
only:
- /^v[0-9]+.[0-9]+.[0-9]+$/
artifacts:
paths:
- lib
uml:
dependencies:
- build
stage: test
services:
- name: registry.gitlab.com/openstapps/core-tools:latest
alias: plantuml
script:
- node lib/cli.js plantuml test/model http://plantuml:8080 --showProperties --showOptionalProperties --showInheritedProperties --showEnumValues --showAssociations --showInheritance --excludeExternals
pages:
stage: deploy
script:
- npm run documentation
- mv docs public
only:
- /^v[0-9]+\.[0-9]+\.[0-9]+$/
artifacts:
paths:
- public

View File

@@ -0,0 +1,38 @@
## Summary
(Summarize the bug encountered concisely)
## Steps to reproduce
(How one can reproduce the issue - this is very important)
## Example Project
(If possible, please create an example project here on GitLab.com that exhibits the problematic behaviour, and link to it here in the bug report)
(If you are using an older version of GitLab, this will also determine whether the bug has been fixed in a more recent version)
## What is the current bug behavior?
(What actually happens)
## What is the expected correct behavior?
(What you should see instead)
## Relevant logs and/or screenshots
(Paste any relevant logs - please use code blocks (```) to format console output,
logs, and code as it's very hard to read otherwise.)
## Possible fixes
(If you can, link to the line of code that might be responsible for the problem)
/label ~meeting

View File

@@ -0,0 +1,16 @@
## Description
(Describe the feature that you're requesting concisely)
## Explanation
(Explain why the feature is necessary)
## Dependencies, issues to be resolved beforehand
(List issues or dependencies that need to be resolved before this feature can be implemented)
/label ~meeting

View File

@@ -0,0 +1,12 @@
# Ignore all files/folders by default
# See https://stackoverflow.com/a/29932318
/*
# Except these files/folders
!lib
lib/tsconfig.tsbuildinfo
!LICENSE
!package.json
!package-lock.json
!README.md
!resources
!src

View File

@@ -0,0 +1,353 @@
# [0.34.0](https://gitlab.com/openstapps/core-tools/compare/v0.33.0...v0.34.0) (2023-01-30)
# [0.33.0](https://gitlab.com/openstapps/core-tools/compare/v0.32.0...v0.33.0) (2023-01-12)
### Bug Fixes
* convert schema glob path to posix path ([c3d66b3](https://gitlab.com/openstapps/core-tools/commit/c3d66b36c8b4bdf84b3e23cd0ab8318d3fd068f9))
# [0.32.0](https://gitlab.com/openstapps/core-tools/compare/v0.31.0...v0.32.0) (2022-08-17)
### Bug Fixes
* documentation not beeing generated ([51ae246](https://gitlab.com/openstapps/core-tools/commit/51ae246a0fd10144cf6af348bc7ded88e6dab27a))
# [0.31.0](https://gitlab.com/openstapps/core-tools/compare/v0.30.1...v0.31.0) (2022-06-27)
## [0.30.1](https://gitlab.com/openstapps/core-tools/compare/v0.30.0...v0.30.1) (2022-05-27)
# [0.30.0](https://gitlab.com/openstapps/core-tools/compare/v0.29.1...v0.30.0) (2022-04-04)
## [0.29.1](https://gitlab.com/openstapps/core-tools/compare/v0.29.0...v0.29.1) (2022-03-21)
# [0.29.0](https://gitlab.com/openstapps/core-tools/compare/v0.28.0...v0.29.0) (2022-01-25)
# [0.28.0](https://gitlab.com/openstapps/core-tools/compare/v0.27.0...v0.28.0) (2021-12-17)
### Bug Fixes
* ajv related tranistive build errors ([e82f4e9](https://gitlab.com/openstapps/core-tools/commit/e82f4e92099359baed5ea89f64bd7204700c2785))
# [0.27.0](https://gitlab.com/openstapps/core-tools/compare/v0.26.0...v0.27.0) (2021-12-15)
# [0.26.0](https://gitlab.com/openstapps/core-tools/compare/v0.25.0...v0.26.0) (2021-12-15)
# [0.25.0](https://gitlab.com/openstapps/core-tools/compare/v0.24.3...v0.25.0) (2021-08-31)
### Bug Fixes
* generate schemas for type aliases ([96e3acf](https://gitlab.com/openstapps/core-tools/commit/96e3acf9ba330c3414eb1e38b347ca9e597fee88))
## [0.24.3](https://gitlab.com/openstapps/core-tools/compare/v0.24.2...v0.24.3) (2021-08-27)
### Bug Fixes
* add cruical Converter ceation option ([f82b465](https://gitlab.com/openstapps/core-tools/commit/f82b4652637808abf68f1e72b1de0c76b228457a))
## [0.24.2](https://gitlab.com/openstapps/core-tools/compare/v0.24.1...v0.24.2) (2021-08-25)
## [0.24.1](https://gitlab.com/openstapps/core-tools/compare/v0.24.0...v0.24.1) (2021-08-25)
# [0.24.0](https://gitlab.com/openstapps/core-tools/compare/v0.23.2...v0.24.0) (2021-08-25)
### Features
* modernize core-tools ([fe59204](https://gitlab.com/openstapps/core-tools/commit/fe59204b4210831b15445fa9aa7dbc20de75e96d))
## [0.23.2](https://gitlab.com/openstapps/core-tools/compare/v0.23.0...v0.23.2) (2021-08-02)
### Bug Fixes
* rollback ajv version to 6.12.6 ([7a5d2bb](https://gitlab.com/openstapps/core-tools/commit/7a5d2bb1e98b41d1143fbfe21b29e3aef2133c8f))
# [0.23.0](https://gitlab.com/openstapps/core-tools/compare/v0.22.0...v0.23.0) (2021-07-21)
### Features
* replace route markdown with openapi ([f4bf7ab](https://gitlab.com/openstapps/core-tools/commit/f4bf7abc895f87a57fa34b2269311809f2a9413d))
# [0.22.0](https://gitlab.com/openstapps/core-tools/compare/v0.21.0...v0.22.0) (2021-07-07)
### Bug Fixes
* fix inherited properties not working correctly ([f20038c](https://gitlab.com/openstapps/core-tools/commit/f20038c8f9a37424fd7a95484e744e0c672f5cfb))
# [0.21.0](https://gitlab.com/openstapps/core-tools/compare/v0.20.0...v0.21.0) (2021-05-12)
### Features
* add support for non-external premaps ([7429806](https://gitlab.com/openstapps/core-tools/commit/74298065e0386c8e4646e565e5e383b5ae08dfaa))
# [0.20.0](https://gitlab.com/openstapps/core-tools/compare/v0.19.0...v0.20.0) (2021-04-26)
### Features
* add filterable annotation option for integer ([7ba8233](https://gitlab.com/openstapps/core-tools/commit/7ba8233f5b81f4ab3c3aeec2c8a47a7bad3ae502))
# [0.19.0](https://gitlab.com/openstapps/core-tools/compare/v0.18.0...v0.19.0) (2021-04-06)
# [0.18.0](https://gitlab.com/openstapps/core-tools/compare/v0.17.0...v0.18.0) (2021-03-24)
### Features
* make Point type sortable in Elasticsearch ([724a686](https://gitlab.com/openstapps/core-tools/commit/724a6866c80a544dec4ce11d70d648bd724f9aba))
# [0.17.0](https://gitlab.com/openstapps/core-tools/compare/v0.16.0...v0.17.0) (2020-12-02)
### Features
* add support for [@inherit](https://gitlab.com/inherit)Tags ([485430b](https://gitlab.com/openstapps/core-tools/commit/485430b7f27fb9c751a6f5697e74eb5531ac7889))
* add support for date mapping ([a09be1d](https://gitlab.com/openstapps/core-tools/commit/a09be1d941df88826ccaa8aa468680ece29d35a5))
# [0.16.0](https://gitlab.com/openstapps/core-tools/compare/v0.15.0...v0.16.0) (2020-10-28)
### Bug Fixes
* use value type in IndexSignature type instead of key type ([b7cdb6a](https://gitlab.com/openstapps/core-tools/commit/b7cdb6a9ad2bdb1fc09d0f535daf4ec778501fec))
# [0.15.0](https://gitlab.com/openstapps/core-tools/compare/v0.14.0...v0.15.0) (2020-10-05)
### Bug Fixes
* array tags did not propagate ([e5511d0](https://gitlab.com/openstapps/core-tools/commit/e5511d07386e93b032b5dbefa3e6cc46c07219ed))
# [0.14.0](https://gitlab.com/openstapps/core-tools/compare/v0.13.0...v0.14.0) (2020-02-11)
# [0.13.0](https://gitlab.com/openstapps/core-tools/compare/v0.12.0...v0.13.0) (2020-01-28)
# [0.12.0](https://gitlab.com/openstapps/core-tools/compare/v0.11.0...v0.12.0) (2019-12-03)
### Bug Fixes
* make fields with index signatures a dynamic mapping ([8f5570e](https://gitlab.com/openstapps/core-tools/commit/8f5570e2e2d350d6153b34f940f4cd5c407b5bc9))
# [0.11.0](https://gitlab.com/openstapps/core-tools/compare/v0.10.0...v0.11.0) (2019-11-12)
### Bug Fixes
* use .raw field for aggregations ([4c1a374](https://gitlab.com/openstapps/core-tools/commit/4c1a374a9ee266884bd33e8a3b3f52fcef8f4019))
# [0.10.0](https://gitlab.com/openstapps/core-tools/compare/v0.9.0...v0.10.0) (2019-11-08)
### Bug Fixes
* make mapping of generics work correctly ([8f7201e](https://gitlab.com/openstapps/core-tools/commit/8f7201e2cf010ed9ef457d9cf938167a4e970963)), closes [#27](https://gitlab.com/openstapps/core-tools/issues/27)
* make mapping tags work for overwritten values ([47361d4](https://gitlab.com/openstapps/core-tools/commit/47361d412a92ae34dc1b81298402d6b441b4f4ba))
### Features
* generate aggreations from annotations in the core ([18ad651](https://gitlab.com/openstapps/core-tools/commit/18ad651286bafcbc929e14ee9429c7b852d86f3b))
# [0.9.0](https://gitlab.com/openstapps/core-tools/compare/v0.8.0...v0.9.0) (2019-09-10)
### Bug Fixes
* read type tags correctly after the first time ([77e4914](https://gitlab.com/openstapps/core-tools/commit/77e49146c0619566919815bd5d63ddf34dc19387))
### Features
* add support for [@filterable](https://gitlab.com/filterable) tag ([36bf17e](https://gitlab.com/openstapps/core-tools/commit/36bf17e3236a555e6d1193466141be880b280db9))
# [0.8.0](https://gitlab.com/openstapps/core-tools/compare/v0.7.0...v0.8.0) (2019-07-25)
### Bug Fixes
* apply stricter tslint rules ([967f946](https://gitlab.com/openstapps/core-tools/commit/967f94652723d8589b7f272454185449233ac838))
* emend the imports in the test files ([53e8047](https://gitlab.com/openstapps/core-tools/commit/53e80476c85027194cf406ad87fe8950d6c2f3a8))
* remove duplicate job ([af904a7](https://gitlab.com/openstapps/core-tools/commit/af904a7a05de56cdef6aea136a7e3bb237c4beb2))
* update the uml job to use our node image ([a478715](https://gitlab.com/openstapps/core-tools/commit/a478715d8045dd26cd345ba3cbb469fda651b84f))
### Features
* add automatic mapping generation ([7b198f9](https://gitlab.com/openstapps/core-tools/commit/7b198f95ce7bbd75454247e70757d34af462cefc)), closes [#6](https://gitlab.com/openstapps/core-tools/issues/6)
* add the uml generator ([0f21da4](https://gitlab.com/openstapps/core-tools/commit/0f21da4a92b4e0ef11a5f274468d3679fc9784ee))
* added output file name for uml generation ([843e598](https://gitlab.com/openstapps/core-tools/commit/843e59811a5a104df1c746627aa668d26fdc9f60))
# [0.7.0](https://gitlab.com/openstapps/core-tools/compare/v0.6.0...v0.7.0) (2019-06-24)
# [0.6.0](https://gitlab.com/openstapps/core-tools/compare/v0.5.1...v0.6.0) (2019-04-16)
## [0.5.1](https://gitlab.com/openstapps/core-tools/compare/v0.5.0...v0.5.1) (2019-04-09)
# [0.5.0](https://gitlab.com/openstapps/core-tools/compare/v0.4.0...v0.5.0) (2019-04-09)
# [0.4.0](https://gitlab.com/openstapps/core-tools/compare/v0.3.0...v0.4.0) (2019-04-03)
### Features
* add feature to validate schemas directly ([1022150](https://gitlab.com/openstapps/core-tools/commit/1022150ca3d2af846b819e0e0e46ead71134d5f8))
* adjust generation of route documentation ([d3ce936](https://gitlab.com/openstapps/core-tools/commit/d3ce936626751f24f20081403271d77e2c346e03)), closes [#12](https://gitlab.com/openstapps/core-tools/issues/12)
# [0.3.0](https://gitlab.com/openstapps/core-tools/compare/v0.2.1...v0.3.0) (2019-02-06)
### Features
* ensure correct path for input files ([1c74432](https://gitlab.com/openstapps/core-tools/commit/1c744328eb03dc8019fe6dc3a309f68260210146))
## [0.2.1](https://gitlab.com/openstapps/core-tools/compare/v0.2.0...v0.2.1) (2019-01-30)
### Bug Fixes
* add SC prefix to the camel cased type of the instance ([e559234](https://gitlab.com/openstapps/core-tools/commit/e559234cea9ef245733f8117ab4a27e83db54e14))
* use tsconfig.json of project for schema generation ([6b1a420](https://gitlab.com/openstapps/core-tools/commit/6b1a4202f92759c9ef36d32d0960faf4f56cc8db)), closes [#10](https://gitlab.com/openstapps/core-tools/issues/10)
### Features
* add function to find tsconfig.json ([aa645a2](https://gitlab.com/openstapps/core-tools/commit/aa645a2cc4661c58c6050196ee1944dfd9e5eea8))
# [0.2.0](https://gitlab.com/openstapps/core-tools/compare/v0.1.1...v0.2.0) (2019-01-21)
### Features
* add pack script ([7438465](https://gitlab.com/openstapps/core-tools/commit/7438465149b591ebf1583a8bd6b9da56aa9c9f57)), closes [#4](https://gitlab.com/openstapps/core-tools/issues/4)
## [0.1.1](https://gitlab.com/openstapps/core-tools/compare/v0.1.0...v0.1.1) (2019-01-14)
### Bug Fixes
* add missing dependency typedoc ([b248d1b](https://gitlab.com/openstapps/core-tools/commit/b248d1b5e0306247ce35e5c9d45637b0f3f83cac)), closes [#5](https://gitlab.com/openstapps/core-tools/issues/5)
# [0.1.0](https://gitlab.com/openstapps/core-tools/compare/v0.0.3...v0.1.0) (2019-01-08)
### Features
* validate generated schemas ([7b7299d](https://gitlab.com/openstapps/core-tools/commit/7b7299d9c475105f9d2387c9dc31974139997483)), closes [#1](https://gitlab.com/openstapps/core-tools/issues/1)
## [0.0.3](https://gitlab.com/openstapps/core-tools/compare/v0.0.2...v0.0.3) (2018-12-18)
### Bug Fixes
* do not ignore resources ([6502bcf](https://gitlab.com/openstapps/core-tools/commit/6502bcf2b517ab98909626a7b8baa08e7cdcdc3e))
## [0.0.2](https://gitlab.com/openstapps/core-tools/compare/v0.0.1...v0.0.2) (2018-12-18)
## [0.0.1](https://gitlab.com/openstapps/core-tools/compare/1ac90ef6330bcfd0ea362505a11db66453f3386f...v0.0.1) (2018-12-18)
### Features
* add core tools ([1ac90ef](https://gitlab.com/openstapps/core-tools/commit/1ac90ef6330bcfd0ea362505a11db66453f3386f))

View File

@@ -0,0 +1 @@
FROM plantuml/plantuml-server:tomcat

200
packages/core-tools/LICENSE Normal file
View File

@@ -0,0 +1,200 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/ licenses/why-not-lgpl.html>.

View File

@@ -0,0 +1,212 @@
# @openstapps/core-tools
[![pipeline status](https://img.shields.io/gitlab/pipeline/openstapps/core-tools.svg?style=flat-square)](https://gitlab.com/openstapps/core-tools/commits/master)
[![npm](https://img.shields.io/npm/v/@openstapps/core-tools.svg?style=flat-square)](https://npmjs.com/package/@openstapps/core-tools)
[![license)](https://img.shields.io/npm/l/@openstapps/core-tools.svg?style=flat-square)](https://www.gnu.org/licenses/gpl-3.0.en.html)
[![documentation](https://img.shields.io/badge/documentation-online-blue.svg?style=flat-square)](https://openstapps.gitlab.io/core-tools)
Tools to convert and validate StAppsCore
## What are the tools for?
The StAppsCore Converter is a tool for converting SC-types (TypeScript) into JSON schema files.
JSON schema files are needed for run-time validation of SC-type objects, as this is a tedious task to do using SC-types defined in TypeScript (not possible without additional coding). That said, StAppsCore Converter practically prepares SC-types to be used for object validation (determining whether a JavaScript/JSON object is a valid object of the corresponding SC-type) using StAppsCore Validator.
The StAppsCore Validator is a tool for run-time validation of objects (determining whether a JavaScript/JSON object is a valid object of the corresponding SC-type. It consumes JSON schema files from StAppsCore as the definitions of SC-types against which are validated concrete (actual) objects (as an example SCDish object in the example below).
## Installation
Installation of the npm package (using `npm install`) makes the tool available as an executable with the name `openstapps-core-tools`.
## How to use the converter?
Add `@validatable` to the Typedoc comment of the types that you want to convert to JSONSchema.
The command `openstapps-core-tools` can then be called using these arguments:
```shell
openstapps-core-tools schema <srcPath> <schemaPath>
```
where:
- `<srcPath>` is path to the project (where used `*.ts` files are, e.g. `src/core`,
- `<schemaPath>` is directory to save output files to, e.g. `lib/schema`.
Complete command with the example arguments is then:
```shell
openstapps-core-tools schema src/core lib/schema
```
Inside of a script in `package.json` or if the npm package is installed globally, the tool `stapps-convert` can be called without its local path (`node_modules/.bin`):
```shell
openstapps-core-tools schema src/core lib/schema
```
## What is Easy AST?
Easy [AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree) is a "wrapper" around the TypeScript Compiler API. The TS Compiler API is built for many
much more complex things than just accessing type declarations, and thus comes with a ton of
bloat that makes it really difficult to work with.
This is why we built the Easy AST, which converts the TS representation to a really easy and
lightweight structure, that removes a lot of the stuff you wouldn't really need.
## How to use the validator?
### Using the validator programatically
```typescript
import {Validator} from '@openstapps/core-tools/lib/validate';
import {SCDish, SCThingType} from '@openstapps/core';
import {ValidatorResult} from 'jsonschema';
import {join} from 'path';
const objectToValidate: SCDish = {
type: SCThingType.Dish,
// more properties
};
// instantiate a new validator
const validator = new Validator();
// make the validator read the schema files
validator.addSchemas(join('node_modules', '@openstapps', 'core', 'lib', 'schema')).then(() => {
// validate an object
const result: ValidatorResult = validator.validate(objectToValidate, 'SCDish');
});
```
#### Using validateFiles function
The JSON files passed to the validateFiles method have an added layer.
That layer encapsulates the actual JSON data of the object to be verified and adds a property to enable true negative testing.
Your basic JSON object:
```json
{
"property1": "value1",
"property2": "value2",
...
}
```
JSON for validateFiles:
```json
{
"errorNames": [],
"instance": {
"property1": "value1",
"property2": "value2",
...
},
"schema": "NameOfSchema"
}
```
Where `errorNames` holds the string values of the name property of the expected ValidationErrors from JSON Schema. Empty array means no errors are expected.
`schema` holds the name of the schema to validate the instance against.
### How to use validator as a CLI tool (executable)?
The command `openstapps-core-tools` can then be called using these arguments:
```shell
openstapps-core-tools validate <schemaPath> <testPath> [reportPath]
```
where:
- `<schemaPath>` is a directory where JSON schema files are, e.g. `lib/schema`,
- `<testPath>` is a directory where test files are, e.g. `src/test/resources`,
- `[reportPath]` is a file where the HTML report of the validation will be saved to, e.g. `report.html` (optional argument - if it's not provided no report will be written).
Command with the example arguments is then for example:
```shell
openstapps-core-tools validate lib/schema src/test/resources
```
Inside of a script in `package.json` or if the npm package is installed globally, the tool `openstapps-validate` can be called without its local path (`node_modules/.bin`):
```shell
openstapps-core-tools validate lib/schema src/test/resources report.html
```
## Generate openapi JSON file for routes
To generate a openapi JSON file that represents the routes according to openapi version 3.0.3 use the following command.
```shell
openstapps-core-tools openapi PATH/TO/CORE/lib PATH/TO/PUT/FILES/TO
```
## Pack definitions and implementations
To pack all the different files into two distribution files - one for definitions/one for implementations - use the following command:
```shell
openstapps-core-tools pack
```
## How to use the UML generator
The UML Generator generates PlantUML from the project reflection of the source files. By default it will include externals, which will take considerably longer to execute, you can disable this behaviour via an option. It can help you to visually explore the data model or document a specific part.
You can either use the public PlantUML-server or start your own local instance. To run, restart or stop the container use the scripts provided in the `package.json`.
### Generating from source-files
```shell
openstapps-core-tools plantuml PATH/TO/SOURCEFILES http://PLANTUMLSERVER
```
Executing this command will generate a `.svg` file in your current working directory.
Multiple options can be set to enhance the diagram. By default all additional information other than the definitions are disabled. You can use:
- `--showProperties` to show all mandatory attributes of the classes and interfaces.
- `--showOptionalProperties` to show all mandatory attributes of the classes and interfaces. `--showProperties` must be set!
- `--showInheritedProperties` to show all inherited attributes of the classes and interfaces. `--showProperties` must be set!
- `--showEnumValues` to show all enumeration and type (enumeration-like) values
- `--showInheritance` to show the hierarchy of the classes and interfaces. Inherited attributes will only be shown in their parent.
- `--showAssociations` to show all references of classes and interfaces between one another
- `--excludeExternals` to exclude external definitions
- `--definitions <definitons>` to show only specific definitions to reduce the output of the diagram. `<definitions>` is a comma seperated list of definitions.
- `--outputFileName <fileName>` for a custom file name, the file extension will be added automatically (.svg). Otherwise a generic file with a timestamp will be generated into the execution directory. If a file with the same name already exists it will be overwritten!
The best way to explore models is to enable `--showInheritance` and `--showAssociations`. Start with just one definition in your `--definition <definitions>`-list, generate the diagram, look at it, add a new definition that you have seen to your command and generate anew.
#### Examples
Show the class hierarchy of the whole project:
```shell
openstapps-core-tools plantuml PATH/TO/SRCDIR http://PLANTUMLSERVER --showInheritance
```
Show the dish-module:
```shell
openstapps-core-tools plantuml ../core http://localhost:8080 --showProperties --showOptionalProperties --showInheritance --showAssociations --showEnumValues --definitions SCDish,SCThingThatCanBeOfferedOffer
```
### Generating from existing file
The plantuml code is persisted inside the generated file at the very bottom. You can tweak the model by using the function to generate UML from a PlantUML-file(simple text file). Extract the code (starting from `@startuml` to `@enduml`), edit it manually and execute this function.
```shell
openstapps-core-tools plantuml-file /PATH/TO/Project.plantuml http://PLANTUMLSERVER OptionalCustomFileName
```
Example-File-Content of Project.plantuml
```
@startuml
interface MyClass{
myProperty: string
}
@enduml
```

4296
packages/core-tools/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,98 @@
{
"name": "@openstapps/core-tools",
"version": "0.34.0",
"description": "Tools to convert and validate StAppsCore",
"keywords": [
"converter",
"core",
"StApps",
"StAppsCore",
"validator"
],
"repository": {
"type": "git",
"url": "git@gitlab.com:openstapps/core-tools.git"
},
"license": "GPL-3.0-only",
"main": "./lib/index.js",
"types": "./lib/index.d.ts",
"bin": {
"openstapps-core-tools": "./lib/cli.js"
},
"author": "Karl-Philipp Wulfert <krlwlfrt@gmail.com>",
"contributors": [
"Anselm Stordeur <anselmstordeur@gmail.com>",
"Jovan Krunić <jovan.krunic@gmail.com>",
"Rainer Killinger <mail-openstapps@killinger.co>",
"Michel Jonathan Schmitz",
"Thea Schöbl <dev@theaninova.de>"
],
"scripts": {
"build": "npm run lint && npm run compile",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0 && git add CHANGELOG.md",
"check-configuration": "openstapps-configuration",
"compile": "rimraf lib && tsc && prepend lib/cli.js '#!/usr/bin/env node\n'",
"documentation": "typedoc --out docs --readme README.md --includeVersion --validation.invalidLink true --entryPointStrategy expand src",
"plantuml-start": "docker run --name plantuml-server -d -p 8080:8080 registry.gitlab.com/openstapps/core-tools:latest",
"plantuml-restart": "docker restart plantuml-server",
"plantuml-stop": "docker stop plantuml-server",
"version": "npm run changelog",
"prepublishOnly": "npm ci && npm run build",
"preversion": "npm run prepublishOnly",
"push": "git push && git push origin \"v$npm_package_version\"",
"test": "mocha --require ts-node/register test/*.spec.ts",
"lint:fix": "eslint --fix -c .eslintrc.json --ignore-path .eslintignore --ext .ts src/",
"lint": "eslint -c .eslintrc.json --ignore-path .eslintignore --ext .ts src/"
},
"dependencies": {
"@openstapps/logger": "1.1.1",
"ajv": "8.12.0",
"better-ajv-errors": "1.2.0",
"chai": "4.3.7",
"commander": "10.0.0",
"deepmerge": "4.3.0",
"del": "6.1.1",
"eslint": "8.33.0",
"flatted": "3.2.7",
"fs-extra": "10.1.0",
"glob": "8.1.0",
"got": "11.8.6",
"humanize-string": "3.0.0",
"json-schema": "0.4.0",
"lodash": "4.17.21",
"mustache": "4.2.0",
"openapi-types": "12.1.0",
"plantuml-encoder": "1.4.0",
"re2": "1.18.0",
"toposort": "2.0.2",
"ts-json-schema-generator": "1.2.0",
"ts-node": "10.9.1"
},
"devDependencies": {
"@openstapps/configuration": "0.34.0",
"@testdeck/mocha": "0.3.3",
"@types/chai": "4.3.4",
"@types/fs-extra": "9.0.13",
"@types/glob": "8.0.1",
"@types/json-schema": "7.0.11",
"@types/lodash": "4.14.191",
"@types/mocha": "10.0.1",
"@types/mustache": "4.2.2",
"@types/node": "14.18.36",
"@types/rimraf": "3.0.2",
"@typescript-eslint/eslint-plugin": "5.49.0",
"@typescript-eslint/parser": "5.49.0",
"conventional-changelog-cli": "2.2.2",
"eslint-config-prettier": "8.6.0",
"eslint-plugin-jsdoc": "39.7.4",
"eslint-plugin-prettier": "4.2.1",
"eslint-plugin-unicorn": "45.0.2",
"mocha": "10.2.0",
"nock": "13.3.0",
"prepend-file-cli": "1.0.6",
"prettier": "2.8.3",
"rimraf": "3.0.2",
"typedoc": "0.22.18",
"typescript": "4.4.4"
}
}

View File

@@ -0,0 +1,12 @@
<tr>
<th scope="row"><h3>{{idx}}</h3></th>
<td>
<div class="alert {{status}}">{{name}}</div>
<p>{{message}}</p>
<p>{{suggestion}}</p>
</td>
<td style="max-width: 600px">
<p>{{schemaPath}}</p>
<pre>{{instance}}</pre>
</td>
</tr>

View File

@@ -0,0 +1,17 @@
<div class="mw-100">
<h2>Errors in <code>{{testFile}}</code></h2>
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Error</th>
<th scope="col">Instance</th>
</tr>
</thead>
<tbody>
{{&errors}}
</tbody>
</table>
</div>

View File

@@ -0,0 +1,24 @@
<!doctype html>
<html lang="en">
<head>
<title>Report</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
</head>
<body>
<h1>Validation result</h1>
<p>Timestamp: {{timestamp}}</p>
{{&report}}
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
</body>
</html>

View File

@@ -0,0 +1,248 @@
/*
* Copyright (C) 2018-2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {Logger} from '@openstapps/logger';
import {Command} from 'commander';
import {existsSync, readFileSync, writeFileSync} from 'fs';
import {copy} from 'fs-extra';
import path from 'path';
import {mkdirPromisified, readFilePromisified} from './common';
import {lightweightDefinitionsFromPath, lightweightProjectFromPath} from './easy-ast/easy-ast';
import {pack} from './pack';
import {openapi3Template} from './resources/openapi-303-template';
import {gatherRouteInformation, generateOpenAPIForRoute} from './routes';
import {Converter, getValidatableTypesInPath} from './schema';
import {createDiagram, createDiagramFromString} from './uml/create-diagram';
import {UMLConfig} from './uml/uml-config';
import {capitalize} from './util/string';
import {validateFiles, writeReport} from './validate';
// handle unhandled promise rejections
process.on('unhandledRejection', async (reason: unknown) => {
if (reason instanceof Error) {
await Logger.error(reason.message);
Logger.info(reason.stack);
}
process.exit(1);
});
const commander = new Command('openstapps-core-tools');
// eslint-disable-next-line unicorn/prefer-module
commander.version(JSON.parse(readFileSync(path.resolve(__dirname, '..', 'package.json')).toString()).version);
commander.command('prototype <srcBundle> <out>').action(async (sourcePath, out) => {
const files = lightweightProjectFromPath(sourcePath);
writeFileSync(path.resolve(out), JSON.stringify(files, undefined, 2));
});
commander
.command('openapi <srcPath> <outDirPath>')
.action(async (relativeSourceBundlePath, relativeOutDirectoryPath) => {
// get absolute paths
const sourcePath = path.resolve(relativeSourceBundlePath);
const outDirectoryPath = path.resolve(relativeOutDirectoryPath);
const outDirectorySchemasPath = path.join(outDirectoryPath, 'schemas');
// get information about routes
const routes = await gatherRouteInformation(sourcePath);
routes.sort((a, b) => a.route.urlPath.localeCompare(b.route.urlPath));
// change url path parameters to openapi notation
for (const routeWithMetaInformation of routes) {
routeWithMetaInformation.route.urlPath = routeWithMetaInformation.route.urlPath.replace(
/:\w+/g,
(match: string) => `{${match.replace(':', '')}}`,
);
}
// keep openapi tags for routes that actually share url fragments
let tagsToKeep = routes.map(routeWithMetaInformation =>
capitalize(routeWithMetaInformation.route.urlPath.split('/')[1]),
);
tagsToKeep = tagsToKeep.filter(
(element, i, array) => array.indexOf(element) === i && array.lastIndexOf(element) !== i,
);
// initialize json output
const output = openapi3Template;
// names of the schemas to copy
const schemasToCopy: string[] = [];
// generate documentation for all routes
for (const routeWithMetaInformation of routes) {
routeWithMetaInformation.tags = [capitalize(routeWithMetaInformation.route.urlPath.split('/')[1])];
output.paths[routeWithMetaInformation.route.urlPath] = generateOpenAPIForRoute(
routeWithMetaInformation,
path.relative(relativeOutDirectoryPath, outDirectorySchemasPath),
schemasToCopy,
tagsToKeep,
);
}
// copy schema json schema files
try {
if (!existsSync(outDirectorySchemasPath)) {
await mkdirPromisified(outDirectorySchemasPath, {
recursive: true,
});
}
for (const fileName of schemasToCopy) {
await copy(
path.join(sourcePath, 'schema', `${fileName}.json`),
path.join(outDirectorySchemasPath, `${fileName}.json`),
);
}
} catch (error) {
await Logger.error(error);
process.exit(-2);
}
// write openapi object to file (prettified)
writeFileSync(path.join(outDirectoryPath, 'openapi.json'), JSON.stringify(output, undefined, 2));
Logger.ok(`OpenAPI representation resources written to ${outDirectoryPath} .`);
});
commander.command('schema <srcPath> <schemaPath>').action(async (relativeSourcePath, relativeSchemaPath) => {
// get absolute paths
const absoluteSourcePath = path.resolve(relativeSourcePath);
const schemaPath = path.resolve(relativeSchemaPath);
// initialize new core converter
const coreConverter = new Converter(absoluteSourcePath);
// get validatable types
const validatableTypes = getValidatableTypesInPath(absoluteSourcePath);
Logger.info(`Found ${validatableTypes.length} type(s) to generate schemas for.`);
await mkdirPromisified(schemaPath, {
recursive: true,
});
Logger.info(`Trying to find a package.json for ${absoluteSourcePath}.`);
let packagePath = absoluteSourcePath;
// TODO: this check should be less ugly! --- What is this doing anyway?
while (!existsSync(path.join(packagePath, 'package.json')) && packagePath.length > 5) {
packagePath = path.resolve(packagePath, '..');
}
const corePackageJsonPath = path.join(packagePath, 'package.json');
Logger.info(`Using ${corePackageJsonPath} to determine version for schemas.`);
const buffer = await readFilePromisified(corePackageJsonPath);
const corePackageJson = JSON.parse(buffer.toString());
const coreVersion = corePackageJson.version;
Logger.log(`Using ${coreVersion} as version for schemas.`);
// generate and write JSONSchema files for validatable types
for (const type of validatableTypes) {
const schema = coreConverter.getSchema(type, coreVersion);
const stringifiedSchema = JSON.stringify(schema, undefined, 2);
const file = path.join(schemaPath, `${type}.json`);
// write schema to file
writeFileSync(file, stringifiedSchema);
Logger.info(`Generated schema for ${type} and saved to ${file}.`);
}
Logger.ok(`Generated schemas for ${validatableTypes.length} type(s).`);
});
commander
.command('validate <schemaPath> <testPath> [reportPath]')
.action(async (relativeSchemaPath, relativeTestPath, relativeReportPath) => {
// get absolute paths
const schemaPath = path.resolve(relativeSchemaPath);
const testPath = path.resolve(relativeTestPath);
const errorsPerFile = await validateFiles(schemaPath, testPath);
let unexpected = false;
for (const file in errorsPerFile) {
if (!errorsPerFile.hasOwnProperty(file)) {
continue;
}
unexpected = unexpected || errorsPerFile[file].some(error => !error.expected);
}
if (relativeReportPath !== undefined) {
const reportPath = path.resolve(relativeReportPath);
await writeReport(reportPath, errorsPerFile);
}
if (unexpected) {
await Logger.error('Unexpected errors occurred during validation');
process.exit(1);
} else {
Logger.ok('Successfully finished validation.');
}
});
commander.command('pack').action(async () => {
await pack();
});
commander
.command('plantuml <srcPath> <plantumlserver>')
.option('--definitions <definitions>', 'Shows these specific definitions (class, interface or enum)', it =>
it.split(','),
)
.option('--showAssociations', 'Shows associations of definitions')
.option('--showInheritance', 'Shows extensions and implementations of definitions')
.option('--showEnumValues', 'Show enum values')
.option('--showProperties', 'Show attributes')
.option('--showInheritedProperties', 'Shows inherited attributes, needs --showProperties')
.option('--showOptionalProperties', 'Shows optional attributes and relations, needs --showProperties')
.option('--excludeExternals', 'Exclude external definitions')
.option('--outputFileName <fileName>', 'Defines the filename of the output')
.action(async (relativeSourcePath, plantumlServer, options) => {
const plantUmlConfig: UMLConfig = {
definitions: options.definitions === undefined ? [] : options.definitions,
showAssociations: options.showAssociations === undefined ? false : options.showAssociations,
showEnumValues: options.showEnumValues === undefined ? false : options.showEnumValues,
showInheritance: options.showInheritance === undefined ? false : options.showInheritance,
showInheritedProperties:
options.showInheritedProperties === undefined ? false : options.showInheritedProperties,
showOptionalProperties:
options.showOptionalProperties === undefined ? false : options.showOptionalProperties,
showProperties: options.showProperties === undefined ? false : options.showProperties,
};
if (options.outputFileName !== undefined) {
plantUmlConfig.outputFileName = options.outputFileName;
}
Logger.log(`PlantUML options: ${JSON.stringify(plantUmlConfig)}`);
await createDiagram(lightweightDefinitionsFromPath(relativeSourcePath), plantUmlConfig, plantumlServer);
});
commander
.command('plantuml-file <inputFile> <plantumlserver> [outputFile]')
.action(async (file: string, plantumlServer: string, outputFile: string) => {
const fileContent = readFileSync(path.resolve(file)).toString();
await createDiagramFromString(fileContent, plantumlServer, outputFile);
});
commander.parse(process.argv);

View File

@@ -0,0 +1,56 @@
/*
* Copyright (C) 2018-2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {Logger} from '@openstapps/logger';
import {existsSync, mkdir, readFile, unlink, writeFile} from 'fs';
import {Glob} from 'glob';
import {platform} from 'os';
import {promisify} from 'util';
import path from 'path';
export const globPromisified = promisify(Glob);
export const mkdirPromisified = promisify(mkdir);
export const readFilePromisified = promisify(readFile);
export const writeFilePromisified = promisify(writeFile);
export const unlinkPromisified = promisify(unlink);
/**
* Get path that contains a tsconfig.json
*
* @param startPath Path from where to start searching "upwards"
*/
export function getTsconfigPath(startPath: string): string {
let tsconfigPath = startPath;
// see https://stackoverflow.com/questions/9652043/identifying-the-file-system-root-with-node-js
const root = platform() === 'win32' ? process.cwd().split(path.sep)[0] : '/';
// repeat until a tsconfig.json is found
while (!existsSync(path.join(tsconfigPath, 'tsconfig.json'))) {
if (tsconfigPath === root) {
throw new Error(
`Reached file system root ${root} while searching for 'tsconfig.json' in ${startPath}!`,
);
}
// pop last directory
const tsconfigPathParts = tsconfigPath.split(path.sep);
tsconfigPathParts.pop();
tsconfigPath = tsconfigPathParts.join(path.sep);
}
Logger.info(`Using 'tsconfig.json' from ${tsconfigPath}.`);
return tsconfigPath;
}

View File

@@ -0,0 +1,143 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {first, last, tail, filter} from 'lodash';
import {
ArrayTypeNode,
ClassDeclaration,
ClassElement,
EnumDeclaration,
Identifier,
InterfaceDeclaration,
isArrayTypeNode,
isClassDeclaration,
isComputedPropertyName,
isEnumDeclaration,
isInterfaceDeclaration,
isPropertyDeclaration,
isPropertySignature,
isTypeAliasDeclaration,
isTypeReferenceNode,
NodeArray,
PropertyDeclaration,
PropertyName,
PropertySignature,
TypeAliasDeclaration,
TypeElement,
TypeNode,
TypeReferenceNode,
} from 'typescript';
import * as ts from 'typescript';
import {cleanupEmpty} from '../util/collections';
import {LightweightComment} from './types/lightweight-comment';
/** @internal */
export function extractComment(node: ts.Node): LightweightComment | undefined {
const jsDocument = last(
// @ts-expect-error jsDoc exists in reality
node.jsDoc as
| Array<{
comment?: string;
tags?: Array<{comment?: string; tagName?: {escapedText?: string}}>;
}>
| undefined,
);
const comment = jsDocument?.comment?.split('\n\n');
return jsDocument === undefined
? undefined
: cleanupEmpty({
shortSummary: first(comment),
description: tail(comment)?.join('\n\n'),
tags: jsDocument?.tags?.map(tag =>
cleanupEmpty({
name: tag.tagName?.escapedText ?? 'UNRESOLVED_NAME',
parameters: tag.comment?.split(' '),
}),
),
});
}
/** @internal */
export function isProperty(
node: ClassElement | TypeElement,
): node is PropertyDeclaration | PropertySignature {
return isPropertyDeclaration(node) || isPropertySignature(node);
}
/** @internal */
export function filterNodeTo<T extends ts.Node, S extends T>(
node: NodeArray<T>,
check: (node: T) => node is S,
): S[] {
return filter(node, check);
}
/** @internal */
export function filterChildrenTo<T extends ts.Node>(node: ts.Node, check: (node: ts.Node) => node is T): T[] {
const out: T[] = [];
node.forEachChild(child => {
if (check(child)) {
out.push(child);
}
});
return out;
}
/** @internal */
export function getModifiers(text: string, kind: string): string[] {
return [
...text
.split(kind)[0]
.split(/\s+/)
.filter(it => it !== ''),
kind,
];
}
/** @internal */
export function resolvePropertyName(name?: PropertyName): string | undefined {
return name === undefined
? undefined
: isComputedPropertyName(name)
? 'UNSUPPORTED_IDENTIFIER_TYPE'
: name.getText();
}
/** @internal */
export function resolveTypeName(type?: TypeNode): string | undefined {
// @ts-expect-error typeName exists in reality
return type?.typeName?.escapedText ?? type?.typeName?.right?.escapedText;
}
/** @internal */
export function isArrayLikeType(typeNode?: TypeNode): typeNode is ArrayTypeNode | TypeReferenceNode {
return typeNode !== undefined && (isArrayTypeNode(typeNode) || isArrayReference(typeNode));
}
/** @internal */
export function isArrayReference(typeNode: TypeNode): boolean {
return isTypeReferenceNode(typeNode) && (typeNode.typeName as Identifier).escapedText === 'Array';
}
/** @internal */
export function isClassLikeNode(node: ts.Node): node is ClassDeclaration | InterfaceDeclaration {
return isClassDeclaration(node) || isInterfaceDeclaration(node);
}
/** @internal */
export function isEnumLikeNode(node: ts.Node): node is EnumDeclaration | TypeAliasDeclaration {
return isEnumDeclaration(node) || isTypeAliasDeclaration(node);
}

View File

@@ -0,0 +1,83 @@
/* eslint-disable jsdoc/require-jsdoc */
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {flatMap, keyBy, isEmpty} from 'lodash';
import {TypeFlags} from 'typescript';
import {LightweightAliasDefinition} from './types/lightweight-alias-definition';
import {LightweightClassDefinition} from './types/lightweight-class-definition';
import {LightweightDefinition} from './types/lightweight-definition';
import {LightweightDefinitionKind} from './types/lightweight-definition-kind';
import {LightweightProject} from './types/lightweight-project';
import {LightweightType} from './types/lightweight-type';
/**
* Creates a printable name of a type
*/
export function expandTypeValue(type: LightweightType): string | undefined {
if (type.isArray) {
return `${type.value}[]`;
}
if (isStringLiteralType(type)) {
return `'${type.value}'`;
}
if (isUnionOrIntersectionType(type)) {
return type.specificationTypes?.map(expandTypeValue).join(isUnionType(type) ? ' | ' : ' & ');
}
if (isEmpty(type.genericsTypes)) {
return `${type.value}<${type.genericsTypes?.map(expandTypeValue).join(', ')}>`;
}
return type.value?.toString();
}
export function definitionsOf(project: LightweightProject): Record<string, LightweightDefinition> {
return keyBy(flatMap(project, Object.values), 'name');
}
export function isPrimitiveType(type: {flags: TypeFlags}): boolean {
return (type.flags & TypeFlags.NonPrimitive) === 0;
}
export function isLiteralType(type: {flags: TypeFlags}): boolean {
return (type.flags & TypeFlags.Literal) !== 0;
}
export function isEnumLiteralType(type: {flags: TypeFlags}): boolean {
return (type.flags & TypeFlags.EnumLiteral) !== 0;
}
export function isStringLiteralType(type: {flags: TypeFlags}): boolean {
return (type.flags & TypeFlags.StringLiteral) !== 0;
}
export function isUnionOrIntersectionType(type: {flags: TypeFlags}): boolean {
return (type.flags & TypeFlags.UnionOrIntersection) !== 0;
}
export function isUnionType(type: {flags: TypeFlags}): boolean {
return (type.flags & TypeFlags.Union) !== 0;
}
export function isLightweightClass(node?: LightweightDefinition): node is LightweightClassDefinition {
return node?.kind === LightweightDefinitionKind.CLASS_LIKE;
}
export function isLightweightEnum(node?: LightweightDefinition): node is LightweightAliasDefinition {
return node?.kind === LightweightDefinitionKind.ALIAS_LIKE;
}
export function isTypeVariable(type: {flags: TypeFlags}): boolean {
return (type.flags & TypeFlags.TypeVariable) !== 0;
}

View File

@@ -0,0 +1,273 @@
/* eslint-disable @typescript-eslint/no-non-null-asserted-optional-chain */
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {flatMap, groupBy, keyBy, mapValues} from 'lodash';
import * as ts from 'typescript';
import {
ClassDeclaration,
ClassElement,
EnumDeclaration,
InterfaceDeclaration,
isArrayTypeNode,
isClassDeclaration,
isEnumDeclaration,
isIndexSignatureDeclaration,
isPropertyDeclaration,
isTypeLiteralNode,
isTypeReferenceNode,
NodeArray,
Program,
SourceFile,
SyntaxKind,
Type,
TypeAliasDeclaration,
TypeChecker,
TypeElement,
TypeFlags,
TypeLiteralNode,
TypeNode,
} from 'typescript';
import {cleanupEmpty, mapNotNil, rejectNil} from '../util/collections';
import {expandPathToFilesSync} from '../util/io';
import {
extractComment,
filterChildrenTo,
filterNodeTo,
getModifiers,
isArrayLikeType,
isClassLikeNode,
isEnumLikeNode,
isProperty,
resolvePropertyName,
resolveTypeName,
} from './ast-internal-util';
import {isEnumLiteralType, isTypeVariable} from './ast-util';
import {LightweightAliasDefinition} from './types/lightweight-alias-definition';
import {LightweightClassDefinition} from './types/lightweight-class-definition';
import {LightweightDefinition} from './types/lightweight-definition';
import {LightweightDefinitionKind} from './types/lightweight-definition-kind';
import {LightweightProject} from './types/lightweight-project';
import {LightweightType} from './types/lightweight-type';
import path from 'path';
import {LightweightProperty} from './types/lightweight-property';
/**
* Convert a TypeScript project to a lightweight Type-AST representation of the project
*
* @param sourcePath either a directory or a set of input files
* @param includeComments if comments should be included (default true)
*/
export function lightweightProjectFromPath(
sourcePath: string | string[],
includeComments = true,
): LightweightProject {
return new LightweightDefinitionBuilder(sourcePath, includeComments).convert();
}
/**
* Convert a TypeScript project to a set of lightweight definition ASTs
*
* @param sourcePath either a directory or a set of input files
* @param includeComments if comments should be included (default true)
*/
export function lightweightDefinitionsFromPath(
sourcePath: string | string[],
includeComments = true,
): LightweightDefinition[] {
return rejectNil(new LightweightDefinitionBuilder(sourcePath, includeComments).convertToList());
}
/**
* Reads the reflection model and converts it into a flatter, easier to handle model
*/
class LightweightDefinitionBuilder {
readonly program: Program;
readonly sourceFiles: readonly SourceFile[];
readonly typeChecker: TypeChecker;
constructor(sourcePath: string | string[], readonly includeComments: boolean) {
const rootNames = Array.isArray(sourcePath)
? sourcePath
: expandPathToFilesSync(path.resolve(sourcePath), file => file.endsWith('ts'));
this.program = ts.createProgram({
rootNames: rootNames,
options: {
alwaysStrict: true,
charset: 'utf8',
declaration: true,
esModuleInterop: true,
experimentalDecorators: true,
inlineSourceMap: true,
module: ts.ModuleKind.CommonJS,
strict: true,
target: ts.ScriptTarget.ES2015,
},
});
this.typeChecker = this.program.getTypeChecker();
this.sourceFiles = mapNotNil(this.program.getRootFileNames(), it => this.program.getSourceFile(it));
}
private convertAliasLike(enumLike: EnumDeclaration | TypeAliasDeclaration): LightweightAliasDefinition {
return cleanupEmpty({
comment: this.includeComments ? extractComment(enumLike) : undefined,
name: enumLike.name.getText() ?? 'ERROR',
kind: LightweightDefinitionKind.ALIAS_LIKE,
modifiers: getModifiers(enumLike.getText(), isEnumDeclaration(enumLike) ? 'enum' : 'type'),
type: isEnumDeclaration(enumLike)
? enumLike.members.length > 0
? {
flags: 1_048_576,
specificationTypes: enumLike.members.map(it => this.lightweightTypeAtNode(it)),
}
: undefined
: this.lightweightTypeFromType(this.typeChecker.getTypeFromTypeNode(enumLike.type), enumLike.type),
});
}
private convertClassLike(classLike: ClassDeclaration | InterfaceDeclaration): LightweightClassDefinition {
const heritages = mapValues(
groupBy(classLike.heritageClauses, it => it.token),
heritages => flatMap(heritages, it => it.types),
);
return cleanupEmpty({
comment: this.includeComments ? extractComment(classLike) : undefined,
name: classLike.name?.escapedText ?? 'ERROR',
kind: LightweightDefinitionKind.CLASS_LIKE,
modifiers: getModifiers(classLike.getText(), isClassDeclaration(classLike) ? 'class' : 'interface'),
extendedDefinitions: heritages[ts.SyntaxKind.ExtendsKeyword]?.map(it => this.lightweightTypeAtNode(it)),
implementedDefinitions: heritages[ts.SyntaxKind.ImplementsKeyword]?.map(it =>
this.lightweightTypeAtNode(it),
),
indexSignatures: keyBy(
filterNodeTo(
classLike.members as NodeArray<ClassElement | TypeElement>,
isIndexSignatureDeclaration,
).map(indexSignature =>
cleanupEmpty({
name:
this.typeChecker.getSignatureFromDeclaration(indexSignature)?.parameters?.[0]?.escapedName ??
'UNRESOLVED_INDEX_SIGNATURE',
type: this.lightweightTypeFromType(
this.typeChecker.getTypeFromTypeNode(indexSignature.type),
indexSignature.type,
),
indexSignatureType: this.lightweightTypeFromType(
this.typeChecker.getTypeFromTypeNode(indexSignature.parameters[0].type!),
indexSignature.parameters[0].type!,
),
}),
),
it => it.name,
),
typeParameters: classLike.typeParameters?.map(it => it.name.getText()),
properties: this.collectProperties(classLike.members),
});
}
collectProperties(members: NodeArray<ClassElement | TypeElement>): Record<string, LightweightProperty> {
return keyBy(
filterNodeTo(members as NodeArray<ClassElement | TypeElement>, isProperty).map(property =>
cleanupEmpty({
comment: this.includeComments ? extractComment(property) : undefined,
name: resolvePropertyName(property.name) ?? property.getText(),
type: this.lightweightTypeAtNode(property),
properties: this.collectProperties((property.type as TypeLiteralNode)?.members),
optional: isPropertyDeclaration(property)
? property.questionToken === undefined
? undefined
: true
: undefined,
}),
),
it => it.name,
);
}
private lightweightTypeAtNode(node: ts.Node): LightweightType {
const type = this.typeChecker.getTypeAtLocation(node);
return this.lightweightTypeFromType(type, this.typeChecker.typeToTypeNode(type, node, undefined));
}
private lightweightTypeFromType(type: ts.Type, typeNode?: TypeNode): LightweightType {
if (typeNode?.kind === SyntaxKind.ConditionalType) {
return {value: 'UNSUPPORTED_CONDITIONAL_TYPE', flags: TypeFlags.Unknown};
}
if (isArrayLikeType(typeNode)) {
const elementType = isArrayTypeNode(typeNode) ? typeNode.elementType : typeNode.typeArguments?.[0]!;
const out = this.lightweightTypeFromType(
this.typeChecker.getTypeFromTypeNode(elementType),
elementType,
);
out.isArray = true;
return out;
}
const isReference = typeNode !== undefined && isTypeReferenceNode(typeNode) && !isEnumLiteralType(type);
const isTypeLiteral = typeNode !== undefined && isTypeLiteralNode(typeNode);
// @ts-expect-error intrinsic name & value exist
const intrinsicName = (type.intrinsicName ?? type.value) as string | undefined;
return cleanupEmpty({
value: intrinsicName,
referenceName: isTypeLiteral
? undefined
: resolveTypeName(typeNode) ?? (type.symbol?.escapedName as string | undefined),
flags: type.flags,
genericsTypes: isTypeVariable(type)
? undefined
: this.typeChecker
.getApparentType(type)
// @ts-expect-error resolvedTypeArguments exits
?.resolvedTypeArguments?.filter(it => !it.isThisType)
?.map((it: Type) => this.lightweightTypeFromType(it)),
specificationTypes:
type.isUnionOrIntersection() && !isReference
? type.types.map(it =>
this.lightweightTypeFromType(it, this.typeChecker.typeToTypeNode(it, undefined, undefined)),
)
: undefined,
});
}
/**
* Start the conversion process
*/
convert(): LightweightProject {
return mapValues(
keyBy(this.sourceFiles, it => it.fileName),
file =>
keyBy(
[
...filterChildrenTo(file, isClassLikeNode).map(it => this.convertClassLike(it)),
...filterChildrenTo(file, isEnumLikeNode).map(it => this.convertAliasLike(it)),
],
it => it.name,
),
);
}
/**
* Same as conversion, but generates a simple list of all definitions.
*/
convertToList(): LightweightDefinition[] {
return flatMap(this.convert(), it => it.values);
}
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {LightweightDefinitionBase} from './lightweight-definition';
import {LightweightDefinitionKind} from './lightweight-definition-kind';
import {LightweightType} from './lightweight-type';
/**
* Represents an enum definition
*/
export interface LightweightAliasDefinition extends LightweightDefinitionBase {
/**
* Kind
*/
kind: LightweightDefinitionKind.ALIAS_LIKE;
/**
* Enumeration or union values
*/
type?: LightweightType;
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {LightweightDefinitionBase} from './lightweight-definition';
import {LightweightDefinitionKind} from './lightweight-definition-kind';
import {LightweightIndexSignature, LightweightProperty} from './lightweight-property';
import {LightweightType} from './lightweight-type';
/**
* Represents a class definition
*/
export interface LightweightClassDefinition extends LightweightDefinitionBase {
/**
* String values of the extended definitions
*/
extendedDefinitions?: LightweightType[];
/**
* String values of the implemented definitions
*/
implementedDefinitions?: LightweightType[];
/**
* Index signatures
*/
indexSignatures?: Record<string, LightweightIndexSignature>;
/**
* Kind
*/
kind: LightweightDefinitionKind.CLASS_LIKE;
/**
* Properties of the definition
*/
properties?: Record<string, LightweightProperty>;
/**
* Generic type parameters of this class
*/
typeParameters?: string[];
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Represents a Comment
*/
export interface LightweightComment {
/**
* Description of the comment
*/
description?: string;
/**
* Short summary of the comment
*/
shortSummary?: string;
/**
* Tags of the comment
*/
tags?: LightweightCommentTag[];
}
/**
* Lightweight comment tag
*/
export interface LightweightCommentTag {
/**
* The name of the tag
*/
name: string;
/**
* The parameters of the tag
*/
parameters?: string[];
}

View File

@@ -0,0 +1,19 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
export enum LightweightDefinitionKind {
CLASS_LIKE = 'class-like',
ALIAS_LIKE = 'alias-like',
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {LightweightDefinitionKind} from './lightweight-definition-kind';
import {LightweightComment} from './lightweight-comment';
import {LightweightClassDefinition} from './lightweight-class-definition';
import {LightweightAliasDefinition} from './lightweight-alias-definition';
export type LightweightDefinition = LightweightClassDefinition | LightweightAliasDefinition;
/**
* Represents any definition without specifics
*/
export interface LightweightDefinitionBase {
/**
* The comment of the definition
*/
comment?: LightweightComment;
/**
* Kind of the definition
*/
kind: LightweightDefinitionKind;
/**
* The definition type
* e.g. [`abstract`, `class`] or [`enum`] or [`export`, `type`]
*/
modifiers?: string[];
/**
* Name of the definition
*/
name: string;
}

View File

@@ -0,0 +1,100 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {assign, cloneDeep, flatMap, fromPairs, trimEnd} from 'lodash';
import {mapNotNil} from '../../util/collections';
import {definitionsOf, isLightweightClass} from '../ast-util';
import {lightweightProjectFromPath} from '../easy-ast';
import {LightweightClassDefinition} from './lightweight-class-definition';
import {LightweightDefinition} from './lightweight-definition';
/**
* Build an index for a lightweight project
*/
function buildIndex(project: LightweightProject): Record<string, string> {
return fromPairs(
flatMap(project, (definitions, file) => Object.keys(definitions).map(definition => [definition, file])),
);
}
/**
* A lightweight definition class for more advanced use cases
*/
export class LightweightProjectWithIndex {
/**
* All definitions
*/
readonly definitions: Record<string, LightweightDefinition>;
/**
* Project
*/
readonly files: LightweightProject;
/**
* Index of all definitions to their respective files
*/
readonly index: {
[definitionName: string]: string;
};
constructor(project: LightweightProject | string) {
this.files = typeof project === 'string' ? lightweightProjectFromPath(project) : project;
this.index = buildIndex(this.files);
this.definitions = definitionsOf(this.files);
}
/**
* Apply inherited classes; default deeply
*/
applyInheritance(classLike: LightweightClassDefinition, deep?: boolean): LightweightDefinition {
return assign(
mapNotNil(
[...(classLike.implementedDefinitions ?? []), ...(classLike.extendedDefinitions ?? [])],
extension => {
const object = this.definitions[extension.referenceName ?? ''];
return (deep ?? true) && isLightweightClass(object)
? this.applyInheritance(object)
: cloneDeep(object);
},
),
cloneDeep(classLike),
);
}
/**
* Instantiate a definition
*
* Requires the program to be run with `--require ts-node/register`
*/
async instantiateDefinitionByName<T>(name: string, findCompiledModule = true): Promise<T | undefined> {
const fsPath = this.index[name];
if (fsPath === undefined) {
return undefined;
}
const module = await import(findCompiledModule ? `${trimEnd(fsPath, 'd.ts')}.js` : fsPath);
return new module[name]() as T;
}
}
export interface LightweightFile {
[definitionName: string]: LightweightDefinition;
}
export interface LightweightProject {
[sourcePath: string]: LightweightFile;
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {LightweightComment} from './lightweight-comment';
import {LightweightType} from './lightweight-type';
/**
* Represents a property definition
*/
export interface LightweightProperty {
/**
* The comment of the property
*/
comment?: LightweightComment;
/**
* Name of the property
*/
name: string;
/**
* Is the property marked as optional
*/
optional?: true;
/**
* A record of properties if the property happens to be a type literal
*/
properties?: Record<string, LightweightProperty>;
/**
* Type of the property
*/
type: LightweightType;
}
export interface LightweightIndexSignature extends LightweightProperty {
/**
* Type of the index signature, if it is an index signature
*/
indexSignatureType: LightweightType;
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {TypeFlags} from 'typescript';
/**
* Describes an easy to use type definition.
*/
export interface LightweightType {
/**
* Type Flags
*/
flags: TypeFlags;
/**
* Contains all types inside of <> brackets
*/
genericsTypes?: LightweightType[];
/**
* If it is an array(-like) type
*/
isArray?: true;
/**
* If it is a type parameter
*/
isTypeParameter?: true;
/**
* The name of the type that is referenced. Enum members have reference names that lead no where.
*/
referenceName?: string;
/**
* Type specifications, if the type is combined by either an array, union or a typeOperator
*/
specificationTypes?: LightweightType[];
/**
* Value of the type
*
* Literal types have their value here, non-literals their type name (for example 'string')
*/
value?: string | number | boolean;
}

View File

@@ -0,0 +1,464 @@
/* eslint-disable unicorn/error-message */
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {Logger} from '@openstapps/logger';
import del from 'del';
import {existsSync} from 'fs';
import {cwd} from 'process';
import {globPromisified, readFilePromisified, unlinkPromisified, writeFilePromisified} from './common';
import {JavaScriptModule} from './types/pack';
import path from 'path';
const PACK_IDENTIFIER = '/* PACKED BY @openstapps/pack */';
/**
* Pack cli.js
*
* This finds all internal requires and replaces the paths with `./index` or internal requires if it has been
* required already.
*
* Furthermore it checks that no shebang line is present and that it does not export anything.
*/
async function packCliJs(): Promise<void> {
const cliPath = path.join(cwd(), 'lib', 'cli.js');
if (!existsSync(cliPath)) {
return;
}
Logger.info('Adjusting JavaScript CLI...');
const buffer = await readFilePromisified(cliPath);
const content = buffer.toString();
if (content.indexOf('#!/') === 0) {
throw new Error('`cli.js` must not contain a shebang line! It is added by this script.');
}
let internalRequire: string | undefined;
const adjustedContent = content
.split('\n')
.map((line, lineNumber) => {
// check for exports (cli.js is not allowed to export anything)
if (Array.isArray(line.match(/^\s*((exports)|(module\.exports))/))) {
throw new TypeError(
`Line '${lineNumber}' in 'cli.js' exports something. cli.js is not for exporting. Line was:\n${line}`,
);
}
// replace lines with internal requires
// extract module name from line
const match = line.match(/^(\s*)(const|var) ([a-z0-9_]*) = require\(("[^"]+"|'[^']+')\);$/i);
if (match !== null) {
const importedName = match[3];
// eslint-disable-next-line unicorn/prefer-string-slice
const moduleName = match[4].substring(1, match[4].length - 1);
// if it begins with '.' and not ends with json
if (/^[.]{1,2}\/(?!.*\.json$).*$/i.test(moduleName)) {
// is the first internal require
if (internalRequire) {
return `const ${importedName} = ${internalRequire};`;
}
// only the first import needs a require
internalRequire = importedName;
return `const ${importedName} = require("./index");`;
}
}
return line;
})
.join('\n');
return writeFilePromisified(cliPath, `#!/usr/bin/env node\n\n${adjustedContent}`);
}
/**
* Get a list containing the contents of all type definition files
*/
async function getAllTypeDefinitions(): Promise<string[]> {
const fileNames = await globPromisified(path.join(cwd(), '*(lib|src)', '**', '*.d.ts'), {
ignore: [
path.join(cwd(), 'lib', 'doc', '**', '*.d.ts'),
path.join(cwd(), 'lib', 'test', '**', '*.d.ts'),
path.join(cwd(), 'lib', 'cli.d.ts'),
],
});
const promises = fileNames.map(async (fileName: string) => {
return readFilePromisified(fileName, 'utf8');
});
return Promise.all(promises);
}
/**
* Pack a list of type definitions into one file
*/
async function packTypeDefinitions(): Promise<void> {
Logger.info('Packing TypeScript definition files...');
const indexPath = path.join(cwd(), 'lib', 'index.d.ts');
await deleteFileIfExistingAndPacked(indexPath);
const typeDefinitions = await getAllTypeDefinitions();
// pack TypeScript definition files
const imports: {[k: string]: string[]} = {};
const referenceLines: string[] = [];
let allDefinitions = typeDefinitions
// concat them separated by new lines
.join('\n\n\n\n\n')
// split all lines
.split('\n')
.map(line => {
if (line.includes('export =')) {
throw new Error('`export =` is not allowed by pack. Use named imports instead.');
}
if (line.indexOf('/// <reference') === 0) {
referenceLines.push(line);
return '// moved referenced line';
}
// match import lines
const match = line.match(/^import {([^}].*)} from '([^'].*)';$/);
if (match !== null) {
const module = match[2];
// extract imported objects
const importedObjects = match[1].split(',').map(object => {
return object.trim();
});
// add list of already imported objects for module
if (imports[module] === undefined) {
imports[module] = [];
}
// count already imported objects and objects to import now
const objectsToImport: string[] = [];
for (const object of importedObjects) {
if (!imports[module].includes(object)) {
imports[module].push(object);
objectsToImport.push(object);
}
}
// replace import line
if (objectsToImport.length === 0) {
return '// extraneous removed import';
}
return `import {${objectsToImport.join(', ')}} from '${module}';`;
}
return line;
})
// filter lines which contain "local" imports
.filter(line => {
return line.match(/^import .* from '\./) === null;
})
// concat all lines separated by new lines
.join('\n');
if (allDefinitions.length > 0) {
if (referenceLines.length > 0) {
allDefinitions = `${referenceLines.join('\n')}
${allDefinitions}`;
}
// write packed TypeScript definition files
return writeFilePromisified(
indexPath,
`${PACK_IDENTIFIER}
${allDefinitions}`,
);
}
}
/**
* Get all JavaScript modules
*/
async function getAllJavaScriptModules(): Promise<JavaScriptModule[]> {
const fileNames = await globPromisified(path.join(cwd(), 'lib', '**', '*.js'), {
ignore: [
path.join(cwd(), 'lib', 'doc', '**', '*.js'),
path.join(cwd(), 'lib', 'test', '*.js'),
path.join(cwd(), 'lib', 'cli.js'),
],
});
const promises = fileNames.map(async (fileName: string) => {
const fileContent = await readFilePromisified(fileName, 'utf8');
const directory = path.dirname(fileName).replace(new RegExp(`^${path.join(cwd(), 'lib')}`), '');
return {
content: `(function() {
${fileContent}
})();
`,
dependencies: getAllInternalDependencies(fileContent),
directory: directory,
name: path.basename(fileName, '.js'),
};
});
return Promise.all(promises);
}
/**
* Pack all javascript files
*/
async function packJavaScriptFiles(): Promise<void> {
const indexPath = path.join(cwd(), 'lib', 'index.js');
Logger.info('Packing JavaScript files...');
await deleteFileIfExistingAndPacked(indexPath);
// topologically sort the modules (sort by dependencies)
const jsModules = topologicalSort(await getAllJavaScriptModules());
let wholeCode = jsModules
// convert modules to strings
.map(module => {
module.content = module.content
.split('\n')
.map(line => {
const match = line.match(
/^(\s*)(const|var) ([a-z0-9_]*) = ((require\("([^"]+)"\))|(require\('([^']+)'\)));$/i,
);
// replace lines with internal requires
if (match !== null) {
if (match[6] === undefined) {
match[6] = match[8];
}
const whiteSpace = typeof match[1] === 'string' && match[1].length > 0 ? match[1] : '';
const importedName = match[3];
const modulePath = match[6];
// leave line unchanged if it is a "global" import
if (modulePath.match(/^[.]{1,2}\//) === null) {
return line;
}
// replace internal requires with `module.exports`
if (existsSync(path.join(cwd(), 'lib', module.directory, `${modulePath}.js`))) {
return `${whiteSpace}const ${importedName} = module.exports;`;
}
if (existsSync(path.join(cwd(), 'src', module.directory, modulePath))) {
return `${whiteSpace} const ${importedName} = require(../src/${modulePath});`;
}
Logger.warn(`Import ${importedName} could not be found in module.directory ${modulePath}.`);
}
return line;
})
.join('\n');
return `// Module: ${module.name}
${module.content}`;
})
// concat them separated by new lines
.join('\n\n\n\n\n')
// split all lines
.split('\n')
// filter lines
.filter(line => {
// remove strict usage
if (line === '"use strict";') {
return false;
}
// remove esModule property
if (line === 'Object.defineProperty(exports, "__esModule", { value: true });') {
return false;
}
// remove source map references
if (line.indexOf('//# sourceMappingURL=') === 0) {
return false;
}
// keep all other lines
return true;
})
// concat all lines separated by new lines
.join('\n');
if (wholeCode.length > 0) {
// add meta lines to the file
wholeCode = `"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
${wholeCode}`;
// write packed JavaScript files
return writeFilePromisified(
indexPath,
`${PACK_IDENTIFIER}
${wholeCode}`,
);
}
}
/**
* Delete file if it exists and is packed by this script
*
* @param path Path to file to check/delete
*/
async function deleteFileIfExistingAndPacked(path: string): Promise<void> {
try {
const buffer = await readFilePromisified(path);
const content = buffer.toString();
// check if packed by this script
if (content.indexOf(PACK_IDENTIFIER) === 0) {
Logger.log(`Found '${path}' which is packed by this script. Deleting it...`);
return unlinkPromisified(path);
}
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return;
}
}
}
/**
* Get all internal dependencies from the content of a module
*
* @param moduleContent Module content to analyze
*/
function getAllInternalDependencies(moduleContent: string): string[] {
// match all const <name> = require(<moduleName>);
const requireLines = moduleContent.match(
/^\s*(const|var) [a-z0-9_]* = require\("([^"]+)"\)|require\('([^']+)'\);$/gim,
);
if (Array.isArray(requireLines)) {
return requireLines
.map(requireLine => {
const matches = requireLine.match(/require\("([^"]+)"\)|require\('([^']+)'\);$/i);
// previously matched require line does not contain a require?!
if (matches === null) {
throw new Error();
}
// return only the moduleName
return matches[1];
})
.filter(moduleName => {
// filter out internal modules beginning with './' and not ending with '.json'
return /^[.]{1,2}\/(?!.*\.json$).*$/i.test(moduleName);
})
.map(internalModuleName => {
// cut './' from the name
return internalModuleName.slice('./'.length);
});
}
return [];
}
/**
* Sort modules by their dependencies
*
* @param modules Modules to sort
*/
function topologicalSort(modules: JavaScriptModule[]): JavaScriptModule[] {
// eslint-disable-next-line unicorn/prefer-module,@typescript-eslint/no-var-requires
const topoSort = require('toposort');
// vertices are modules, an edge from a to b means that b depends on a
const edges: string[][] = [];
const nodes: string[] = [];
// add all edges
for (const module of modules) {
for (const dependencyPath of module.dependencies) {
// add edge from dependency to our module
edges.push([path.basename(dependencyPath), module.name]);
}
nodes.push(module.name);
}
// sort graph and return as an array of sorted modules
return topoSort.array(nodes, edges).map((moduleName: string) => {
return modules.find(module => {
return module.name === moduleName;
});
});
}
/**
* Pack
*/
export async function pack() {
Logger.log(`Packing project in ${process.cwd()}...`);
// run all tasks in parallel
const promises: Array<Promise<void>> = [packCliJs(), packTypeDefinitions(), packJavaScriptFiles()];
await Promise.all(promises);
// clean up afterwards
Logger.info('Deleting extraneous files...');
await del([
// delete all transpiled files
'lib/*',
// keep packed files
'!lib/index.d.ts',
'!lib/index.js',
// keep converted schema files
'!lib/schema',
'!lib/schema/*.json',
// keep documentation
'!lib/doc',
'!lib/doc/*',
'!lib/doc/**/*',
// keep cli
'!lib/cli.js',
// keep tests
'!lib/test',
'!lib/test/*',
'!lib/test/**/*',
]);
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* This is a simple interface declaration for
* testing the schema generation and validation.
*
* @validatable
*/
export interface Foo {
/**
* Dummy parameter
*/
lorem: 'lorem' | 'ipsum';
/**
* String literal type property
*/
type: FooType;
}
/**
* This is a simple type declaration for
* usage in the Foo interface.
*/
export type FooType = 'Foo';

View File

@@ -0,0 +1,41 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {OpenAPIV3} from 'openapi-types';
export const openapi3Template: OpenAPIV3.Document = {
openapi: '3.0.3',
info: {
title: 'Openstapps Backend',
description: `# Introduction
This is a human readable documentation of the backend OpenAPI representation.`,
contact: {
name: 'Openstapps Team',
url: 'https://gitlab.com/openstapps/backend',
email: 'app@uni-frankfurt.de',
},
license: {
name: 'AGPL 3.0',
url: 'https://www.gnu.org/licenses/agpl-3.0.en.html',
},
version: '2.0.0',
},
servers: [
{
url: 'https://mobile.server.uni-frankfurt.de:3000',
description: 'Production server',
},
],
paths: {},
};

View File

@@ -0,0 +1,161 @@
/*
* Copyright (C) 2018-2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {assign, filter, map} from 'lodash';
import {OpenAPIV3} from 'openapi-types';
import {isLightweightClass} from './easy-ast/ast-util';
import {LightweightProjectWithIndex} from './easy-ast/types/lightweight-project';
import {RouteInstanceWithMeta, RouteWithMetaInformation} from './types/routes';
import {rejectNil} from './util/collections';
import {capitalize} from './util/string';
import path from 'path';
import {lightweightProjectFromPath} from './easy-ast/easy-ast';
/**
* Gather relevant information of routes
*
* This gathers the information for all routes that implement the abstract class SCAbstractRoute.
* Furthermore it instantiates every route and adds it to the information.
*/
export async function gatherRouteInformation(path: string): Promise<RouteWithMetaInformation[]> {
const project = new LightweightProjectWithIndex(lightweightProjectFromPath(path));
// find all classes that implement the SCAbstractRoute
return rejectNil(
await Promise.all(
map(filter(project.definitions, isLightweightClass), async node => {
if (!node.extendedDefinitions?.some(it => it.referenceName === 'SCAbstractRoute')) {
return undefined;
}
const instantiatedRoute = (await project.instantiateDefinitionByName(
node.name,
)) as RouteInstanceWithMeta;
// instantiate all errors
instantiatedRoute.errors = await Promise.all(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
instantiatedRoute.errorNames.map(async (error: any) =>
// eslint-disable-next-line @typescript-eslint/ban-types
assign((await project.instantiateDefinitionByName(error.name)) as object, {name: error.name}),
),
);
instantiatedRoute.responseBodyDescription =
// eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain
project.definitions[instantiatedRoute.responseBodyName]?.comment?.shortSummary!;
instantiatedRoute.requestBodyDescription =
// eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain
project.definitions[instantiatedRoute.requestBodyName]?.comment?.shortSummary!;
return {
description: {
shortText: node.comment?.shortSummary,
text: node.comment?.description,
},
name: node.name!,
route: instantiatedRoute,
};
}),
),
);
}
/**
* Generate documentation snippet for one route
*
* @param routeWithInfo A route instance with its meta information
* @param outDirectorySchemasPath Path to directory that will contain relevant schemas for the route
* @param schemasToCopy Schemas identified as relevant for this route
* @param tagsToKeep Tags / keywords that can be used for grouping routes
*/
export function generateOpenAPIForRoute(
routeWithInfo: RouteWithMetaInformation,
outDirectorySchemasPath: string,
schemasToCopy: string[],
tagsToKeep: string[],
): OpenAPIV3.PathItemObject {
const route = routeWithInfo.route;
const openapiPath: OpenAPIV3.PathItemObject = {};
schemasToCopy.push(route.requestBodyName, route.responseBodyName);
openapiPath[route.method.toLowerCase() as OpenAPIV3.HttpMethods] = {
summary: capitalize(routeWithInfo.description.shortText?.replace(/(Route to |Route for )/gim, '')),
description: routeWithInfo.description.text,
requestBody: {
description: route.responseBodyDescription ?? undefined,
content: {
'application/json': {
schema: {
$ref: path.join(outDirectorySchemasPath, `${route.requestBodyName}.json`),
},
},
},
},
parameters: [
{
name: 'X-StApps-Version',
in: 'header',
schema: {
type: 'string',
example: '2.0.0',
},
required: true,
},
],
responses: {},
tags: routeWithInfo.tags?.filter(value => tagsToKeep.includes(value)),
};
openapiPath[route.method.toLowerCase() as OpenAPIV3.HttpMethods]!.responses![route.statusCodeSuccess] = {
description: route.responseBodyDescription,
content: {
'application/json': {
schema: {
$ref: path.join(outDirectorySchemasPath, `${route.responseBodyName}.json`),
},
},
},
};
for (const error of route.errors) {
schemasToCopy.push(error.name);
openapiPath[route.method.toLowerCase() as OpenAPIV3.HttpMethods]!.responses![error.statusCode] = {
description: error.message ?? capitalize(error.name.replace(/([A-Z][a-z])/g, ' $1').replace('SC ', '')),
content: {
'application/json': {
schema: {
$ref: path.join(outDirectorySchemasPath, `${error.name}.json`),
},
},
},
};
}
if (typeof route.obligatoryParameters === 'object') {
for (const [parameter, schemaDefinition] of Object.entries(route.obligatoryParameters)) {
const openapiParameter: OpenAPIV3.ParameterObject = {
in: 'path',
name: parameter,
required: true,
schema: {
// TODO make this less of a hack and search copied schemas for the first occurring definition
$ref: `schemas/SCSearchResponse.json#/definitions/${schemaDefinition}`,
},
};
openapiPath[route.method.toLowerCase() as OpenAPIV3.HttpMethods]?.parameters?.push(openapiParameter);
}
}
return openapiPath;
}

View File

@@ -0,0 +1,119 @@
/*
* Copyright (C) 2018, 2019 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import Ajv from 'ajv';
import {JSONSchema7 as JSONSchema} from 'json-schema';
import {chain} from 'lodash';
import {Config, DEFAULT_CONFIG, Definition, SchemaGenerator} from 'ts-json-schema-generator';
import {createFormatter} from 'ts-json-schema-generator/dist/factory/formatter';
import {createParser} from 'ts-json-schema-generator/dist/factory/parser';
import {createProgram} from 'ts-json-schema-generator/dist/factory/program';
import {getTsconfigPath} from './common';
import {definitionsOf} from './easy-ast/ast-util';
import {lightweightProjectFromPath} from './easy-ast/easy-ast';
import {isSchemaWithDefinitions} from './util/guards';
import path from 'path';
import re2 from './types/re2';
/**
* StAppsCore converter
*
* Converts TypeScript source files to JSON schema files
*/
export class Converter {
/**
* Generator instance
*/
private readonly generator: SchemaGenerator;
/**
* Schema validator instance
*/
private readonly schemaValidator: Ajv;
/**
* Create a new converter
*
* @param projectPath Path to the project
* @param sourcePath Path to optionally point to a different directory of / or single source file
*/
constructor(projectPath: string, sourcePath?: string) {
// set config for schema generator
const config: Config = {
...DEFAULT_CONFIG,
path: sourcePath,
sortProps: true,
topRef: false,
tsconfig: path.join(getTsconfigPath(projectPath), 'tsconfig.json'),
type: 'SC',
};
// create TypeScript program from config
const program = createProgram(config);
// create generator
this.generator = new SchemaGenerator(program, createParser(program, config), createFormatter(config));
// create Ajv instance
this.schemaValidator = new Ajv({code: {regExp: re2}});
// eslint-disable-next-line @typescript-eslint/no-var-requires,unicorn/prefer-module
this.schemaValidator.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));
}
/**
* Get schema for specific StAppsCore type
*
* @param type Type to get the schema for
* @param version Version to set for the schema
* @returns Generated schema
*/
getSchema(type: string, version: string): JSONSchema {
// generate schema for this file/type
const schema: JSONSchema = this.generator.createSchema(type);
// set id of schema
schema.$id = `https://core.stapps.tu-berlin.de/v${version}/lib/schema/${type}.json`;
if (isSchemaWithDefinitions(schema)) {
const selfReference = {
...schema,
};
delete selfReference.$schema;
delete selfReference.definitions;
delete selfReference.$id;
// add self reference to definitions
schema.definitions![`SC${type}`] = {
...(selfReference as unknown as Definition),
};
}
if (!this.schemaValidator.validateSchema(schema)) {
throw new Error(`Generated schema for ${type} is invalid!`);
}
return schema;
}
}
/**
* Get a list of validatable types from an API extractor file
*/
export function getValidatableTypesInPath(path: string): string[] {
return chain(definitionsOf(lightweightProjectFromPath(path)))
.filter(type => !!type.comment?.tags?.find(it => it.name === 'validatable'))
.map(type => type.name)
.value();
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright (C) 2018-2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* A JavaScript module representation to sort a list of them by dependencies
*/
export interface JavaScriptModule {
/**
* Content of the module
*/
content: string;
/**
* List of names of dependencies
*/
dependencies: string[];
/**
* Directory the module is in
*/
directory: string;
/**
* The name of the module
*/
name: string;
}

View File

@@ -0,0 +1,6 @@
import re2 from 're2';
type Re2 = typeof re2 & {code: string};
(re2 as Re2).code = 'require("lib/types/re2").default';
export default re2 as Re2;

View File

@@ -0,0 +1,97 @@
/*
* Copyright (C) 2018-2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type SCRoute = any;
export interface RouteInstanceWithMeta extends SCRoute {
/**
* Possible errors on a route
*/
errors: SCErrorResponse[];
/**
* Description of the request body
*/
requestBodyDescription: string;
/**
* Description of the response body
*/
responseBodyDescription: string;
}
/**
* A route instance with its relevant meta information
*/
export interface RouteWithMetaInformation {
/**
* Description of the route
*/
description: {
/**
* Short text of the description - title
*/
shortText?: string;
/**
* Text of the description
*/
text?: string;
};
/**
* Name of the route
*/
name: string;
/**
* Instance of the route
*/
route: RouteInstanceWithMeta;
/**
* Possible tags/keywords the route can be associated with
*/
tags?: [string];
}
/**
* A node with its relevant meta information
*/
export interface NodeWithMetaInformation {
/**
* Module the node belongs to
*/
module: string;
/**
* Type of the node
*/
type: string;
}
/**
* A generic error that can be returned by the backend if somethings fails during the processing of a request
*/
export interface SCErrorResponse extends Error {
/**
* Additional data that describes the error
*/
additionalData?: unknown;
/**
* HTTP status code to return this error with
*/
statusCode: number;
}

View File

@@ -0,0 +1,26 @@
/*
* Copyright (C) 2018-2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {JSONSchema7 as JSONSchema} from 'json-schema';
import {Definition} from 'ts-json-schema-generator';
/**
* A schema with definitions
*/
export interface SchemaWithDefinitions extends JSONSchema {
/**
* Definitions of the schema
*/
definitions?: {[name: string]: Definition};
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright (C) 2018-2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* The validation result
*/
export interface ValidationResult {
/**
* A list of errors that occurred
*/
errors: ValidationError[];
/**
* whether the validation was successful
*/
valid: boolean;
}
/**
* An error that occurred while validating
*
* This is a duplicate of the ValidationError in core/protocol/errors/validation because of incompatibilities
* between TypeDoc and TypeScript
*/
export interface ValidationError {
/**
* JSON schema path
*/
dataPath: string;
/**
* The instance
*/
instance: unknown;
/**
* The message
*
* Provided by https://www.npmjs.com/package/better-ajv-errors
*/
message: string;
/**
* Name of the error
*/
name: string;
/**
* Path within the Schema
*/
schemaPath: string;
/**
* Suggestion to fix the occurring error
*
* Provided by https://www.npmjs.com/package/better-ajv-errors
*/
suggestion?: string;
}
/**
* An expected error
*/
export interface ExpectedValidationError extends ValidationError {
/**
* Whether or not the error is expected
*/
expected: boolean;
}
/**
* A map of files and their expected validation errors
*/
export interface ExpectedValidationErrors {
[fileName: string]: ExpectedValidationError[];
}

View File

@@ -0,0 +1,257 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {Logger} from '@openstapps/logger';
import {createWriteStream} from 'fs';
import * as request from 'got';
import {forEach, map, isEmpty} from 'lodash';
import {expandTypeValue, isLightweightClass, isUnionOrIntersectionType} from '../easy-ast/ast-util';
import {LightweightAliasDefinition} from '../easy-ast/types/lightweight-alias-definition';
import {LightweightClassDefinition} from '../easy-ast/types/lightweight-class-definition';
import {LightweightDefinition} from '../easy-ast/types/lightweight-definition';
import {LightweightProperty} from '../easy-ast/types/lightweight-property';
import {LightweightType} from '../easy-ast/types/lightweight-type';
import {UMLConfig} from './uml-config';
/**
* Converts the lightweight class/enum definitions according to the configuration,
* to valid PlantUML Code, which will then be encoded, converted by the plantuml server
* and saved as a .svg file in directory, in which this method was called
*
* @param definitions all type definitions of the project
* @param config contains information on how the PlantUML should be generated
* @param plantUmlBaseURL Hostname of the PlantUML-Server
*/
export async function createDiagram(
definitions: LightweightDefinition[],
config: UMLConfig,
plantUmlBaseURL: string,
): Promise<string> {
// when non definitions were specified use all
config.definitions = map(definitions, 'name');
// when providing definitions and either showing associations or inheritance the
// inherited definitions will be added automatically
if (config.showInheritance) {
// TODO: showInheritance
/*const inheritedDefinitions = gatherTypeAssociations(
definitions,
config.definitions,
);*/
// config.definitions = config.definitions.concat(inheritedDefinitions);
}
// creates a UML definition for every specified definition name
// however if no definitions were provided all definitions will be transformed
const modelPlantUMLCode = map(
definitions.filter(it => !config.definitions.includes(it.name)),
definition =>
isLightweightClass(definition)
? createPlantUMLCodeForClass(config, definition)
: createPlantUMLCodeForEnum(config, definition),
).join('');
return createDiagramFromString(modelPlantUMLCode, plantUmlBaseURL, config.outputFileName);
}
/**
* This will encode the plantuml code and post the code to the plantuml server
* The server will then parse the code and create a corresponding diagram
*
* @param modelPlantUMLCode raw PlantUML code
* @param plantUmlBaseURL PlantUML server address that shall be used
* @param outputFile filename of the output file without file extension
*/
export async function createDiagramFromString(
modelPlantUMLCode: string,
plantUmlBaseURL: string,
outputFile = `Diagram-${new Date().toISOString()}`,
) {
// eslint-disable-next-line @typescript-eslint/no-var-requires,unicorn/prefer-module
const plantumlEncoder = require('plantuml-encoder');
const plantUMLCode = plantumlEncoder.encode(`@startuml\n${modelPlantUMLCode}\n@enduml`);
const url = `${plantUmlBaseURL}/svg/${plantUMLCode}`;
let response;
try {
response = await request.default.get(url);
const httpOK = 200;
if (response.statusCode !== httpOK) {
await Logger.error(`Plantuml Server responded with an error.\n${response.statusMessage}`);
throw new Error('Response not okay');
}
} catch (error) {
Logger.log(
`Please try using the public plantuml server:\nhttp://www.plantuml.com/plantuml/svg/${plantUMLCode}`,
);
throw error;
}
// attach file extension
const fileName = `${outputFile}.svg`;
try {
createWriteStream(fileName).write(response.body);
Logger.log(`Writen data to file: ${fileName}`);
} catch {
throw new Error('Could not write file. Are you missing permissions?');
}
return fileName;
}
/**
* Recursively iterates over all types, to find implemented generic types and parents
*
* @param definitions all type definitions of the project
* @param abstractionNames currently known string values of inherited classes
*/
/*function gatherTypeAssociations(
definitions: LightweightDefinition[],
abstractionNames: string[],
): string[] {
let abstractions: string[] = [];
for (const name of abstractionNames) {
const declaration = definitions.find(
(definition) => definition.name === name,
);
if (isLightweightClass(declaration)) {
const currentAbstractions: string[] = declaration.extendedDefinitions.concat(
declaration.implementedDefinitions,
);
abstractions = abstractions.concat(currentAbstractions);
abstractions = abstractions.concat(
gatherTypeAssociations(definitions, currentAbstractions),
);
}
}
return abstractions;
}*/
/**
* Collects all reference information of this type.
*
* Reference information is everything that is indirectly referencing a type or class by name.
*
* @param type Type with references to other types
*/
function getReferenceTypes(type: LightweightType): string[] {
const types: string[] = [];
if (type.referenceName !== undefined) {
types.push(type.referenceName);
}
forEach(type.genericsTypes, specificType => {
for (const value of getReferenceTypes(specificType)) {
types.push(value);
}
});
if ((isUnionOrIntersectionType(type) && isEmpty(type.specificationTypes)) || type.isArray) {
forEach(type.specificationTypes, specificType => {
for (const value of getReferenceTypes(specificType)) {
types.push(value);
}
});
}
return types;
}
/**
* Creates Plant UML code according to the config for the provided class
*
* @param config Configuration for how the UML should be tweaked
* @param readerClass Class or interface representation
*/
function createPlantUMLCodeForClass(config: UMLConfig, readerClass: LightweightClassDefinition): string {
// create the definition header, what type the definition is, it's name and it's inheritance
let model = `${readerClass.modifiers} ${readerClass.name}`;
if (readerClass.typeParameters?.length ?? 0 > 0) {
model += `<${readerClass.typeParameters!.join(', ')}>`;
}
if (config.showInheritance && (readerClass.extendedDefinitions?.length ?? 0 > 0)) {
// PlantUML will automatically create links, when using extends
model += ` extends ${readerClass.extendedDefinitions!.join(', ')}`;
}
if (config.showInheritance && (readerClass.implementedDefinitions?.length ?? 0 > 0)) {
// PlantUML will automatically create links, when using implements
model += ` implements ${readerClass.implementedDefinitions!.join(', ')}`;
}
model += '{';
// add the properties to the definition body
if (config.showProperties) {
forEach(readerClass.properties, property => {
if (property.optional && !config.showOptionalProperties) {
// don't show optional attributes
return;
}
/*if (property.inherited && !config.showInheritedProperties) {
// don't show inherited properties
continue;
}*/
model += `\n\t${createPropertyLine(property)}`;
});
}
// close the definition body
model += '\n}\n';
// add associations from properties with references
forEach(readerClass.properties, property => {
const types: string[] = getReferenceTypes(property.type);
for (const type of types) {
if (config.showAssociations) {
/*if (property.inherited && !config.showInheritedProperties) {
continue;
}*/
model += `${readerClass.name} -up-> ${type} : ${property.name} >\n`;
}
}
});
return model;
}
/**
* Creates PlantUML code according to the config for the provided enum/-like definition
*
* @param config Configuration for how the UML should be tweaked
* @param readerEnum Enum/-like representation
*/
function createPlantUMLCodeForEnum(config: UMLConfig, readerEnum: LightweightAliasDefinition): string {
// create enum header
let model = `enum ${readerEnum.name} {`;
// add values
if (config.showEnumValues) {
forEach(readerEnum.type?.specificationTypes, value => {
model += `\n\t${value.toString()}`;
});
}
model += '\n}\n';
return model;
}
/**
* Creates a property PlantUML Line
*/
function createPropertyLine(property: LightweightProperty): string {
const prefix = `${/*(property.inherited ? '/ ' : */ ''}${property.optional ? '? ' : ''}`;
return `${prefix}${property.name} : ${expandTypeValue(property.type)}`;
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Holds configuration information of how the UML code should be build
*/
export interface UMLConfig {
/**
* Defines which definitions are shown
*/
definitions: string[];
/**
* Defines the output file name without file extension
*/
outputFileName?: string;
/**
* Should the associations between definitions be shown
*/
showAssociations: boolean;
/**
* Should enum/-like values be shown
*/
showEnumValues: boolean;
/**
* Should the inheritance be shown
*/
showInheritance: boolean;
/**
* Should the inherited properties be shown
*/
showInheritedProperties: boolean;
/**
* Should optional properties be shown
*/
showOptionalProperties: boolean;
/**
* Should properties be shown
*/
showProperties: boolean;
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {omitBy, isNil, reject, isEmpty, isArray, isObject} from 'lodash';
/**
* Filters only defined elements
*/
export function rejectNil<T>(array: Array<T | undefined | null>): T[] {
return reject(array, isNil) as T[];
}
/**
* Map elements that are not null
*/
export function mapNotNil<T, S>(array: readonly T[], transform: (element: T) => S | undefined | null): S[] {
return rejectNil(array.map(transform));
}
/**
* Deletes all properties with the value 'undefined', [] or {}
*/
// eslint-disable-next-line @typescript-eslint/ban-types
export function cleanupEmpty<T extends object>(object: T): T {
return omitBy(object, it => isNil(it) || ((isObject(it) || isArray(it)) && isEmpty(it))) as T;
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {JSONSchema7 as JSONSchema} from 'json-schema';
import {SchemaWithDefinitions} from '../types/schema';
/**
* Guard for if a JSON schema is in fact a schema with definitions
*/
export function isSchemaWithDefinitions(schema: JSONSchema): schema is SchemaWithDefinitions {
return schema.definitions !== undefined;
}
/**
* Guard method for determining if an object (a thing) has a type property with a type of string
*/
export function isThingWithType(thing: unknown): thing is {type: string} {
return (
typeof thing === 'object' &&
thing !== null &&
'type' in thing &&
typeof (thing as {type: unknown}).type === 'string'
);
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {readdirSync, statSync} from 'fs';
import {flatMap} from 'lodash';
import path from 'path';
/**
* Expand a path to a list of all files deeply contained in it
*/
export function expandPathToFilesSync(sourcePath: string, accept: (fileName: string) => boolean): string[] {
const fullPath = path.resolve(sourcePath);
const directory = statSync(fullPath);
return directory.isDirectory()
? flatMap(readdirSync(fullPath), fragment =>
expandPathToFilesSync(path.resolve(sourcePath, fragment), accept),
)
: [fullPath].filter(accept);
}
/**
* Take a Windows path and make a Unix path out of it
*/
export function toUnixPath(pathString: string): string {
return pathString.replace(/\\/g, '/');
}

View File

@@ -0,0 +1,30 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import path from 'path';
import {PathLike} from 'fs';
/**
* Convert a path to a POSIX path
*
* Replaces the system separator with posix separators
* Replaces Windows drive letters with a root '/'
*/
export function toPosixPath(pathLike: PathLike, separator = path.sep): string {
return pathLike
.toString()
.split(separator)
.join(path.posix.sep)
.replace(/^[A-z]:\//, '/');
}

View File

@@ -0,0 +1,20 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Creates sentence cased string
*/
export function capitalize(string?: string): string {
return `${string?.charAt(0).toUpperCase()}${string?.slice(1).toLowerCase()}`;
}

View File

@@ -0,0 +1,311 @@
/*
* Copyright (C) 2018-2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {Logger} from '@openstapps/logger';
import Ajv from 'ajv';
import betterAjvErrors, {IOutputError} from 'better-ajv-errors';
import {PathLike} from 'fs';
import {JSONSchema7} from 'json-schema';
import * as mustache from 'mustache';
import {Schema} from 'ts-json-schema-generator';
import {globPromisified, readFilePromisified, writeFilePromisified} from './common';
import {ExpectedValidationErrors, ValidationError, ValidationResult} from './types/validator';
import {isThingWithType} from './util/guards';
import path from 'path';
import re2 from './types/re2';
import {toPosixPath} from './util/posix-path';
/**
* StAppsCore validator
*/
export class Validator {
/**
* JSON Schema Validator
*/
private readonly ajv = new Ajv({
verbose: true,
code: {regExp: re2},
});
/**
* Map of schema names to schemas
*/
private readonly schemas: {[type: string]: Schema} = {};
/**
* A wrapper function for Ajv that transforms the error into the compatible old error
*
* @param schema the schema that will be validated against
* @param instance the instance that will be validated
*/
private ajvValidateWrapper(schema: JSONSchema7, instance: unknown): ValidationResult {
return fromAjvResult(this.ajv.validate(schema, instance), schema, instance, this.ajv);
}
/**
* Feed the schema files to the validator
*
* @param schemaDirectory Path to directory that contains schema files
*/
public async addSchemas(schemaDirectory: PathLike): Promise<string[]> {
const schemaFiles = await globPromisified(path.posix.join(toPosixPath(schemaDirectory), '*.json'));
if (schemaFiles.length === 0) {
throw new Error(`No schema files in ${schemaDirectory.toString()}!`);
}
Logger.log(`Adding schemas from ${schemaDirectory} to validator.`);
await Promise.all(
schemaFiles.map(async (file: string) => {
// read schema file
const buffer = await readFilePromisified(file);
// add schema to map
this.schemas[path.basename(file, '.json')] = JSON.parse(buffer.toString());
Logger.info(`Added ${file} to validator.`);
}),
);
return schemaFiles;
}
/**
* Validates anything against a given schema name or infers schema name from object
*
* @param instance Instance to validate
* @param schema Name of schema to validate instance against or the schema itself
*/
public validate(instance: unknown, schema?: string | Schema): ValidationResult {
if (schema === undefined) {
if (isThingWithType(instance)) {
// schema name can be inferred from type string
const schemaSuffix = (instance as {type: string}).type
.split(' ')
.map((part: string) => {
return part.slice(0, 1).toUpperCase() + part.slice(1);
})
.join('');
const schemaName = `SC${schemaSuffix}`;
return this.validate(instance, schemaName);
}
throw new Error('Instance.type does not exist.');
}
if (typeof schema === 'string') {
// if you want to access a schema that is contained in the validator object
if (typeof this.schemas[schema] !== 'object') {
throw new TypeError(`No schema available for ${schema}.`);
}
// schema will be cached
return this.ajvValidateWrapper(this.schemas[schema], instance);
}
return this.ajvValidateWrapper(schema, instance);
}
}
/**
* Creates a ValidationResult from ajv
*
* Implemented for compatibility purposes
*
* @param result the result, now a ValidationResult
* @param schema the schema that has been validated against
* @param instance the data that has been validated
* @param ajvInstance the ajv instance with which the validation was done
*/
function fromAjvResult(
result: boolean | PromiseLike<unknown>,
schema: JSONSchema7,
instance: unknown,
ajvInstance: Ajv,
): ValidationResult {
const betterErrorObject: IOutputError[] | undefined = betterAjvErrors(
schema,
instance,
ajvInstance.errors ?? [],
// eslint-disable-next-line unicorn/no-null
{format: 'js', indent: null},
);
return {
errors:
ajvInstance.errors?.map((ajvError, index) => {
const error: ValidationError = {
dataPath: ajvError.instancePath,
instance: instance,
message: betterErrorObject?.[index]?.error ?? ajvError.message,
name: ajvError.keyword,
schemaPath: ajvError.schemaPath,
suggestion: betterErrorObject?.[index]?.suggestion,
};
// (validationError as ValidationError).humanReadableError = betterErrorCLI?.[index] as unknown as string;
return error;
}) ?? [],
valid: typeof result === 'boolean' ? result : false,
};
}
/**
* Validate all test files in the given resources directory against schema files in the given (schema) directory
*
* @param schemaDirectory The directory where the JSON schema files are
* @param resourcesDirectory The directory where the test files are
*/
export async function validateFiles(
schemaDirectory: string,
resourcesDirectory: string,
): Promise<ExpectedValidationErrors> {
// instantiate new validator
const v = new Validator();
await v.addSchemas(schemaDirectory);
// get list of files to test
const testFiles = await globPromisified(path.join(resourcesDirectory, '*.json'));
if (testFiles.length === 0) {
throw new Error(`No test files in ${resourcesDirectory}!`);
}
Logger.log(`Found ${testFiles.length} file(s) to test.`);
// map of errors per file
const errors: ExpectedValidationErrors = {};
await Promise.all(
testFiles.map(async (testFile: string) => {
const testFileName = path.basename(testFile);
const buffer = await readFilePromisified(path.join(resourcesDirectory, testFileName));
// read test description from file
const testDescription = JSON.parse(buffer.toString());
// validate instance from test description
const result = v.validate(testDescription.instance, testDescription.schema);
// list of expected errors for this test description
const expectedErrors: string[] = [...testDescription.errorNames];
// number of unexpected errors
let unexpectedErrors = 0;
if (result.errors.length > 0) {
errors[testFileName] = [];
// iterate over errors
for (const error of result.errors) {
const errorIndex = expectedErrors.indexOf(error.name);
let expected = false;
if (errorIndex >= 0) {
expectedErrors.splice(errorIndex, 1);
expected = true;
} else {
unexpectedErrors++;
await Logger.error(`Unexpected error ${error.name} in ${testFile}`);
}
// add error to list of errors
errors[testFileName].push({
...error,
expected,
});
}
}
if (expectedErrors.length > 0) {
for (const error of expectedErrors) {
await Logger.error(`Extraneous expected error '${error}' in ${testFile}.`);
errors[testFileName].push({
dataPath: 'undefined',
expected: false,
instance: undefined,
// instance: testDescription.instance,
message: 'undefined',
name: `expected ${error}`,
schemaPath: 'undefined',
suggestion: 'undefined',
});
}
} else if (unexpectedErrors === 0) {
Logger.info(`Successfully validated ${testFile}.`);
}
}),
);
return errors;
}
/**
* Write a report for errors that occurred in validation
*
* @param reportPath Path to write report to
* @param errors Errors that occurred in validation
*/
export async function writeReport(reportPath: PathLike, errors: ExpectedValidationErrors): Promise<void> {
// eslint-disable-next-line unicorn/prefer-module
let buffer = await readFilePromisified(path.resolve(__dirname, '..', 'resources', 'file.html.mustache'));
const fileTemplate = buffer.toString();
// eslint-disable-next-line unicorn/prefer-module
buffer = await readFilePromisified(path.resolve(__dirname, '..', 'resources', 'error.html.mustache'));
const errorTemplate = buffer.toString();
let output = '';
for (const fileName in errors) {
if (!errors.hasOwnProperty(fileName)) {
continue;
}
let fileOutput = '';
for (const [index, error] of errors[fileName].entries()) {
fileOutput += mustache.render(errorTemplate, {
idx: index + 1,
instance: JSON.stringify(error.instance, undefined, 2),
message: error.message,
name: error.name,
schemaPath: error.schemaPath,
status: error.expected ? 'alert-success' : 'alert-danger',
suggestion: error.suggestion,
});
}
output += mustache.render(fileTemplate, {
errors: fileOutput,
testFile: fileName,
});
}
// eslint-disable-next-line unicorn/prefer-module
buffer = await readFilePromisified(path.resolve(__dirname, '..', 'resources', 'report.html.mustache'));
const reportTemplate = buffer.toString();
await writeFilePromisified(
reportPath,
mustache.render(reportTemplate, {
report: output,
timestamp: new Date().toISOString(),
}),
);
Logger.ok(`Wrote report to ${reportPath}.`);
}

View File

@@ -0,0 +1,35 @@
/* eslint-disable unicorn/prefer-module */
/*
* Copyright (C) 2018-2019 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {Logger} from '@openstapps/logger';
import {expect} from 'chai';
import {slow, suite, test, timeout} from '@testdeck/mocha';
import {cwd} from 'process';
import {getTsconfigPath} from '../src/common';
process.on('unhandledRejection', (reason: unknown): void => {
if (reason instanceof Error) {
void Logger.error('UNHANDLED REJECTION', reason.stack);
}
process.exit(1);
});
@suite(timeout(20_000), slow(10_000))
export class CommonSpec {
@test
async getTsconfigPath() {
expect(getTsconfigPath(__dirname)).to.be.equal(cwd());
}
}

View File

@@ -0,0 +1,89 @@
/* eslint-disable unicorn/prefer-module */
/*
* Copyright (C) 2018-2019 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {expect} from 'chai';
import {existsSync, unlinkSync} from 'fs';
import {slow, suite, test, timeout} from '@testdeck/mocha';
import {createDiagram, createDiagramFromString} from '../src/uml/create-diagram';
import {UMLConfig} from '../src/uml/uml-config';
import {LightweightDefinition} from '../src/easy-ast/types/lightweight-definition';
import nock = require('nock');
import {lightweightDefinitionsFromPath} from '../src/easy-ast/easy-ast';
import path from 'path';
@suite(timeout(15_000), slow(5000))
export class CreateDiagramSpec {
plantUmlConfig: UMLConfig;
definitions: LightweightDefinition[];
constructor() {
this.plantUmlConfig = {
definitions: [],
showAssociations: true,
showEnumValues: true,
showInheritance: true,
showInheritedProperties: true,
showOptionalProperties: true,
showProperties: true,
};
this.definitions = lightweightDefinitionsFromPath('./test/model');
}
@test
async shouldRefuseRequest() {
const testPlantUmlCode = 'class Test{\n}';
try {
await createDiagramFromString(testPlantUmlCode, 'http://plantuml:8080');
} catch (error) {
expect([
new Error('getaddrinfo ENOTFOUND plantuml plantuml:8080').message,
new Error('getaddrinfo EAI_AGAIN plantuml plantuml:8080').message,
new Error('getaddrinfo ENOTFOUND plantuml').message,
]).to.include((error as NodeJS.ErrnoException).message);
}
}
/**
* This test will only test the functionality of the method
* - Converting the definitions to plantuml code
* - Sending the code to a server
* - Writing the response to a file
* This test will not check the file content
*/
@test
async shouldCreateDiagrams() {
nock('http://plantuml:8080')
.persist()
.get(() => true)
.reply(200, 'This will be the file content');
let fileName = await createDiagram(this.definitions, this.plantUmlConfig, 'http://plantuml:8080');
let filePath = path.resolve(__dirname, '..', fileName);
expect(await existsSync(filePath)).to.equal(true);
await unlinkSync(fileName);
this.plantUmlConfig.showAssociations = false;
this.plantUmlConfig.showInheritance = false;
fileName = await createDiagram(this.definitions, this.plantUmlConfig, 'http://plantuml:8080');
filePath = path.resolve(__dirname, '..', fileName);
expect(await existsSync(filePath)).to.equal(true);
await unlinkSync(fileName);
nock.cleanAll();
}
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {expandPathToFilesSync, toUnixPath} from '../src/util/io';
import {EasyAstSpecType} from './easy-ast/easy-ast-spec-type';
import {lightweightProjectFromPath} from '../src/easy-ast/easy-ast';
import {expect} from 'chai';
import {omitBy} from 'lodash';
describe('Easy AST', async () => {
const project = lightweightProjectFromPath('./test/easy-ast', true);
for (const file of expandPathToFilesSync('./test/easy-ast', file => file.endsWith('ast-test.ts'))) {
try {
const test = (await import(file))['testConfig'] as EasyAstSpecType;
it(test.testName, () => {
expect(omitBy(project[toUnixPath(file)], (_value, key) => key.startsWith('$'))).to.be.deep.equal(
test.expected,
);
});
} catch (error) {
console.error(error);
}
}
});

View File

@@ -0,0 +1,68 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {EasyAstSpecType} from './easy-ast-spec-type';
import {LightweightDefinitionKind} from '../../src/easy-ast/types/lightweight-definition-kind';
type TestTypeAlias = number | string;
enum TestEnum {
Foo,
Bar,
}
export const testConfig: EasyAstSpecType = {
testName: `should resolve alias-likes`,
expected: {
TestTypeAlias: {
name: 'TestTypeAlias',
kind: LightweightDefinitionKind.ALIAS_LIKE,
modifiers: ['type'],
type: {
flags: 1_048_576,
specificationTypes: [
{
value: 'string',
flags: 4,
},
{
value: 'number',
flags: 8,
},
],
},
},
TestEnum: {
name: 'TestEnum',
kind: LightweightDefinitionKind.ALIAS_LIKE,
modifiers: ['enum'],
type: {
flags: 1_048_576,
specificationTypes: [
{
referenceName: 'Foo',
value: 0,
flags: 1280,
},
{
referenceName: 'Bar',
value: 1,
flags: 1280,
},
],
},
},
},
};

View File

@@ -0,0 +1,75 @@
/* eslint-disable @typescript-eslint/no-unused-vars,@typescript-eslint/no-empty-interface */
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {EasyAstSpecType} from './easy-ast-spec-type';
import {LightweightDefinitionKind} from '../../src/easy-ast/types/lightweight-definition-kind';
interface Random {}
type TestArrayGeneric = Array<string>;
type TestArrayLiteral = number[];
type TestArrayReferenceGeneric = Array<Random>;
type TestArrayReferenceLiteral = Random[];
export const testConfig: EasyAstSpecType = {
testName: `should resolve array-likes`,
expected: {
TestArrayGeneric: {
name: 'TestArrayGeneric',
kind: LightweightDefinitionKind.ALIAS_LIKE,
modifiers: ['type'],
type: {
value: 'string',
flags: 4,
isArray: true,
},
},
TestArrayLiteral: {
name: 'TestArrayLiteral',
kind: LightweightDefinitionKind.ALIAS_LIKE,
modifiers: ['type'],
type: {
value: 'number',
flags: 8,
isArray: true,
},
},
TestArrayReferenceGeneric: {
name: 'TestArrayReferenceGeneric',
kind: LightweightDefinitionKind.ALIAS_LIKE,
modifiers: ['type'],
type: {
referenceName: 'Random',
flags: 524_288,
isArray: true,
},
},
TestArrayReferenceLiteral: {
name: 'TestArrayReferenceLiteral',
kind: LightweightDefinitionKind.ALIAS_LIKE,
modifiers: ['type'],
type: {
referenceName: 'Random',
flags: 524_288,
isArray: true,
},
},
Random: {
name: 'Random',
kind: LightweightDefinitionKind.CLASS_LIKE,
modifiers: ['interface'],
},
},
};

View File

@@ -0,0 +1,59 @@
/* eslint-disable @typescript-eslint/no-unused-vars,@typescript-eslint/no-inferrable-types */
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {EasyAstSpecType} from './easy-ast-spec-type';
import {LightweightDefinitionKind} from '../../src/easy-ast/types/lightweight-definition-kind';
interface TestInterface {
foo: number;
}
class TestClass {
bar: string = 'test';
}
export const testConfig: EasyAstSpecType = {
testName: `should resolve class-likes`,
expected: {
TestInterface: {
name: 'TestInterface',
kind: LightweightDefinitionKind.CLASS_LIKE,
modifiers: ['interface'],
properties: {
foo: {
name: 'foo',
type: {
value: 'number',
flags: 8,
},
},
},
},
TestClass: {
name: 'TestClass',
kind: LightweightDefinitionKind.CLASS_LIKE,
modifiers: ['class'],
properties: {
bar: {
name: 'bar',
type: {
value: 'string',
flags: 4,
},
},
},
},
},
};

View File

@@ -0,0 +1,161 @@
/* eslint-disable @typescript-eslint/no-unused-vars,jsdoc/check-tag-names */
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {EasyAstSpecType} from './easy-ast-spec-type';
import {LightweightDefinitionKind} from '../../src/easy-ast/types/lightweight-definition-kind';
/**
* Class comment
*
* Class description
*
* More description
*
* @classTag classParameter1 classParameter2
*/
interface TestInterface {
/**
* Property comment
*
* Property description
*
* More description
*
* @propertyTag propertyParameter1 propertyParameter2
*/
foo: string;
}
/**
* Class comment
*
* Class description
*
* More description
*
* @classTag classParameter1 classParameter2
*/
class TestClass {
/**
* Property comment
*
* Property description
*
* More description
*
* @propertyTag propertyParameter1 propertyParameter2
*/
foo = 1;
}
/**
* Enum comment
*
* Enum description
*
* More description
*
* @enumTag enumParameter1
*/
enum TestAlias {}
export const testConfig: EasyAstSpecType = {
testName: `should resolve comments`,
expected: {
TestInterface: {
comment: {
shortSummary: 'Class comment',
description: 'Class description\n\nMore description',
tags: [
{
name: 'classTag',
parameters: ['classParameter1', 'classParameter2'],
},
],
},
name: 'TestInterface',
kind: LightweightDefinitionKind.CLASS_LIKE,
modifiers: ['interface'],
properties: {
foo: {
comment: {
shortSummary: 'Property comment',
description: 'Property description\n\nMore description',
tags: [
{
name: 'propertyTag',
parameters: ['propertyParameter1', 'propertyParameter2'],
},
],
},
name: 'foo',
type: {
value: 'string',
flags: 4,
},
},
},
},
TestClass: {
comment: {
shortSummary: 'Class comment',
description: 'Class description\n\nMore description',
tags: [
{
name: 'classTag',
parameters: ['classParameter1', 'classParameter2'],
},
],
},
name: 'TestClass',
kind: LightweightDefinitionKind.CLASS_LIKE,
modifiers: ['class'],
properties: {
foo: {
comment: {
shortSummary: 'Property comment',
description: 'Property description\n\nMore description',
tags: [
{
name: 'propertyTag',
parameters: ['propertyParameter1', 'propertyParameter2'],
},
],
},
name: 'foo',
type: {
value: 'number',
flags: 8,
},
},
},
},
TestAlias: {
comment: {
shortSummary: 'Enum comment',
description: 'Enum description\n\nMore description',
tags: [
{
name: 'enumTag',
parameters: ['enumParameter1'],
},
],
},
name: 'TestAlias',
kind: LightweightDefinitionKind.ALIAS_LIKE,
modifiers: ['enum'],
},
},
};

View File

@@ -0,0 +1,66 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {EasyAstSpecType} from './easy-ast-spec-type';
import {LightweightDefinitionKind} from '../../src/easy-ast/types/lightweight-definition-kind';
interface Test1<T = number> {
foo: T;
}
interface Test2 {
bar: Test1;
}
export const testConfig: EasyAstSpecType = {
testName: `should resolve default generics`,
expected: {
Test1: {
name: 'Test1',
kind: LightweightDefinitionKind.CLASS_LIKE,
modifiers: ['interface'],
typeParameters: ['T'],
properties: {
foo: {
name: 'foo',
type: {
referenceName: 'T',
flags: 262_144,
},
},
},
},
Test2: {
name: 'Test2',
kind: LightweightDefinitionKind.CLASS_LIKE,
modifiers: ['interface'],
properties: {
bar: {
name: 'bar',
type: {
referenceName: 'Test1',
flags: 524_288,
genericsTypes: [
{
value: 'number',
flags: 8,
},
],
},
},
},
},
},
};

View File

@@ -0,0 +1,20 @@
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {LightweightFile} from '../../src/easy-ast/types/lightweight-project';
export interface EasyAstSpecType {
testName: string;
expected: LightweightFile;
}

View File

@@ -0,0 +1,73 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {EasyAstSpecType} from './easy-ast-spec-type';
import {LightweightDefinitionKind} from '../../src/easy-ast/types/lightweight-definition-kind';
enum TestAuto {
Foo,
Bar,
}
enum TestSpecified {
YES = 'yes',
NO = 'no',
}
export const testConfig: EasyAstSpecType = {
testName: `should resolve auto and specified enums`,
expected: {
TestAuto: {
name: 'TestAuto',
kind: LightweightDefinitionKind.ALIAS_LIKE,
modifiers: ['enum'],
type: {
flags: 1_048_576,
specificationTypes: [
{
referenceName: 'Foo',
value: 0,
flags: 1280,
},
{
referenceName: 'Bar',
value: 1,
flags: 1280,
},
],
},
},
TestSpecified: {
name: 'TestSpecified',
kind: LightweightDefinitionKind.ALIAS_LIKE,
modifiers: ['enum'],
type: {
flags: 1_048_576,
specificationTypes: [
{
referenceName: 'YES',
value: 'yes',
flags: 1152,
},
{
referenceName: 'NO',
value: 'no',
flags: 1152,
},
],
},
},
},
};

View File

@@ -0,0 +1,80 @@
/* eslint-disable @typescript-eslint/no-empty-interface,@typescript-eslint/no-unused-vars */
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {EasyAstSpecType} from './easy-ast-spec-type';
import {LightweightDefinitionKind} from '../../src/easy-ast/types/lightweight-definition-kind';
interface $Random {}
interface Generics {
baz: Foo<number, $Random>;
}
interface Foo<T, S> {
foo: T;
bar: S;
}
export const testConfig: EasyAstSpecType = {
testName: `should resolve generics`,
expected: {
Generics: {
name: 'Generics',
kind: LightweightDefinitionKind.CLASS_LIKE,
modifiers: ['interface'],
properties: {
baz: {
name: 'baz',
type: {
referenceName: 'Foo',
flags: 524_288,
genericsTypes: [
{
value: 'number',
flags: 8,
},
{
referenceName: '$Random',
flags: 524_288,
},
],
},
},
},
},
Foo: {
name: 'Foo',
kind: LightweightDefinitionKind.CLASS_LIKE,
modifiers: ['interface'],
typeParameters: ['T', 'S'],
properties: {
foo: {
name: 'foo',
type: {
referenceName: 'T',
flags: 262_144,
},
},
bar: {
name: 'bar',
type: {
referenceName: 'S',
flags: 262_144,
},
},
},
},
},
};

View File

@@ -0,0 +1,69 @@
/* eslint-disable @typescript-eslint/no-empty-interface,@typescript-eslint/no-unused-vars */
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {EasyAstSpecType} from './easy-ast-spec-type';
import {LightweightDefinitionKind} from '../../src/easy-ast/types/lightweight-definition-kind';
interface $Random {}
interface IndexSignatureObject {
[key: string]: $Random;
}
interface IndexSignaturePrimitive {
[key: string]: number;
}
export const testConfig: EasyAstSpecType = {
testName: `should resolve index signatures`,
expected: {
IndexSignatureObject: {
name: 'IndexSignatureObject',
kind: LightweightDefinitionKind.CLASS_LIKE,
modifiers: ['interface'],
indexSignatures: {
key: {
name: 'key',
indexSignatureType: {
value: 'string',
flags: 4,
},
type: {
referenceName: '$Random',
flags: 524_288,
},
},
},
},
IndexSignaturePrimitive: {
name: 'IndexSignaturePrimitive',
kind: LightweightDefinitionKind.CLASS_LIKE,
modifiers: ['interface'],
indexSignatures: {
key: {
name: 'key',
indexSignatureType: {
value: 'string',
flags: 4,
},
type: {
value: 'number',
flags: 8,
},
},
},
},
},
};

View File

@@ -0,0 +1,82 @@
/* eslint-disable @typescript-eslint/no-unused-vars,@typescript-eslint/no-inferrable-types */
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {EasyAstSpecType} from './easy-ast-spec-type';
import {LightweightDefinitionKind} from '../../src/easy-ast/types/lightweight-definition-kind';
interface $BaseInterface<T> {
foo: T;
}
interface $BaseInterface2 {
bar: string;
}
class $BaseClass {}
class InheritingClass extends $BaseClass implements $BaseInterface<number>, $BaseInterface2 {
bar: string = '';
foo: number = 1;
}
export const testConfig: EasyAstSpecType = {
testName: `inheritance`,
expected: {
InheritingClass: {
name: 'InheritingClass',
kind: LightweightDefinitionKind.CLASS_LIKE,
modifiers: ['class'],
implementedDefinitions: [
{
referenceName: '$BaseInterface',
genericsTypes: [
{
value: 'number',
flags: 8,
},
],
flags: 524_288,
},
{
referenceName: '$BaseInterface2',
flags: 524_288,
},
],
extendedDefinitions: [
{
referenceName: '$BaseClass',
flags: 524_288,
},
],
properties: {
foo: {
name: 'foo',
type: {
value: 'number',
flags: 8,
},
},
bar: {
name: 'bar',
type: {
value: 'string',
flags: 4,
},
},
},
},
},
};

View File

@@ -0,0 +1,61 @@
/* eslint-disable @typescript-eslint/no-empty-interface,@typescript-eslint/no-unused-vars */
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {EasyAstSpecType} from './easy-ast-spec-type';
import {LightweightDefinitionKind} from '../../src/easy-ast/types/lightweight-definition-kind';
interface NestedObject {
nested: {
deeplyNested: {
aNumber: number;
};
};
}
export const testConfig: EasyAstSpecType = {
testName: `should handle nested/type literals`,
expected: {
NestedObject: {
name: 'NestedObject',
kind: LightweightDefinitionKind.CLASS_LIKE,
modifiers: ['interface'],
properties: {
nested: {
name: 'nested',
type: {
flags: 524_288,
},
properties: {
deeplyNested: {
name: 'deeplyNested',
type: {
flags: 524_288,
},
properties: {
aNumber: {
name: 'aNumber',
type: {
flags: 8,
value: 'number',
},
},
},
},
},
},
},
},
},
};

View File

@@ -0,0 +1,99 @@
/* eslint-disable @typescript-eslint/no-unused-vars,@typescript-eslint/no-explicit-any */
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {EasyAstSpecType} from './easy-ast-spec-type';
import {LightweightDefinitionKind} from '../../src/easy-ast/types/lightweight-definition-kind';
interface Test {
number_type: number;
string_type: string;
boolean_type: boolean;
any_type: any;
unknown_type: unknown;
null_type: null;
undefined_type: undefined;
}
export const testConfig: EasyAstSpecType = {
testName: `should interpret primitive types correctly`,
expected: {
Test: {
name: 'Test',
kind: LightweightDefinitionKind.CLASS_LIKE,
modifiers: ['interface'],
properties: {
number_type: {
name: 'number_type',
type: {
value: 'number',
flags: 8,
},
},
string_type: {
name: 'string_type',
type: {
value: 'string',
flags: 4,
},
},
boolean_type: {
name: 'boolean_type',
type: {
value: 'boolean',
flags: 1_048_592,
specificationTypes: [
{
value: 'false',
flags: 512,
},
{
value: 'true',
flags: 512,
},
],
},
},
any_type: {
name: 'any_type',
type: {
value: 'any',
flags: 1,
},
},
unknown_type: {
name: 'unknown_type',
type: {
value: 'unknown',
flags: 2,
},
},
null_type: {
name: 'null_type',
type: {
value: 'null',
flags: 65_536,
},
},
undefined_type: {
name: 'undefined_type',
type: {
value: 'undefined',
flags: 32_768,
},
},
},
},
},
};

View File

@@ -0,0 +1,61 @@
/* eslint-disable @typescript-eslint/no-unused-vars,@typescript-eslint/no-explicit-any */
/*
* Copyright (C) 2021 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {EasyAstSpecType} from './easy-ast-spec-type';
import {LightweightDefinitionKind} from '../../src/easy-ast/types/lightweight-definition-kind';
interface Foo<T extends Bar<string>> {
bar: T;
}
interface Bar<T> {
foo: T;
}
export const testConfig: EasyAstSpecType = {
testName: `should ignore type constraints`,
expected: {
Foo: {
name: 'Foo',
kind: LightweightDefinitionKind.CLASS_LIKE,
modifiers: ['interface'],
typeParameters: ['T'],
properties: {
bar: {
name: 'bar',
type: {
referenceName: 'T',
flags: 262_144,
},
},
},
},
Bar: {
name: 'Bar',
kind: LightweightDefinitionKind.CLASS_LIKE,
modifiers: ['interface'],
typeParameters: ['T'],
properties: {
foo: {
name: 'foo',
type: {
referenceName: 'T',
flags: 262_144,
},
},
},
},
},
};

View File

@@ -0,0 +1,35 @@
/*
* Copyright (C) 2018-2019 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {TestFirstUnion} from './test-union';
export class TestClass<T> {
test2: T;
test4: TestFirstUnion;
constructor(type: T) {
this.test2 = type;
this.test4 = 'test1';
}
/**
* Should not be processed at all
*/
testClassFunction(): boolean {
return true;
}
}
export class TestSecondClass extends TestClass<string> {}

View File

@@ -0,0 +1,25 @@
/*
* Copyright (C) 2018-2019 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
export enum TestFirstEnum {
TEST1,
TEST2,
TEST3,
}
export enum TestSecondEnum {
TEST1 = 'one',
TEST2 = 'two',
TEST3 = 'three',
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright (C) 2018-2019 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {TestClass, TestSecondClass} from './test-class';
import {TestFirstEnum} from './test-enum';
import {TestThirdUnion} from './test-union';
export interface TestInterface {
articleBody: string[];
categorySpecificValues?: {[s: string]: string};
inputType: 'multipleChoice';
maintainer: TestThirdUnion | TestFirstEnum;
remainingAttendeeCapacity?: number;
test1: Array<TestThirdUnion | typeof TestFirstEnum>;
test2: TestClass<string>;
test3: 'test1' | 'test2';
test4: TestSecondClass;
universityRole: keyof TestFirstEnum;
}
export interface TestSecondInterface {
[k: string]: string;
}

View File

@@ -0,0 +1,22 @@
/*
* Copyright (C) 2018-2019 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
export type TestFirstUnion = 'test1' | 'test2';
export type TestSecondUnion = 'test3';
export type TestThirdUnion = TestFirstUnion | TestSecondUnion;
export type TestFourthUnion<T extends TestFirstUnion> = T extends TestFirstUnion ? TestFirstUnion : never;

View File

@@ -0,0 +1,4 @@
{
"extends": "../../node_modules/@openstapps/configuration/tsconfig.json",
"exclude": []
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright (C) 2022 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {expect} from 'chai';
import {toPosixPath} from '../src/util/posix-path';
import path from 'path';
describe('posix-path', function () {
it('should convert Windows paths', function () {
expect(toPosixPath('a\\b\\c', path.win32.sep)).to.be.equal('a/b/c');
});
it('should leave POSIX paths untouched', function () {
expect(toPosixPath('a/b/c', path.posix.sep)).to.be.equal('a/b/c');
});
it('should replace Windows drive letters', function () {
expect(toPosixPath('C:\\a\\b\\c', path.win32.sep)).to.be.equal('/a/b/c');
});
it('should leave POSIX root separator untouched', function () {
expect(toPosixPath('/a/b/c', path.posix.sep)).to.be.equal('/a/b/c');
});
});

View File

@@ -0,0 +1,81 @@
/* eslint-disable unicorn/prefer-module */
/*
* Copyright (C) 2018-2019 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {Logger} from '@openstapps/logger';
import {expect} from 'chai';
import {slow, suite, test, timeout} from '@testdeck/mocha';
import {Converter} from '../src/schema';
import path from 'path';
process.on('unhandledRejection', (error: unknown) => {
if (error instanceof Error) {
void Logger.error('UNHANDLED REJECTION', error.stack);
}
process.exit(1);
});
@suite(timeout(40_000), slow(10_000))
export class SchemaSpec {
@test
async getSchema() {
const converter = new Converter(path.join(__dirname, '..', 'src', 'resources'));
const schema = converter.getSchema('Foo', '0.0.1');
expect(schema).to.be.deep.equal({
$id: 'https://core.stapps.tu-berlin.de/v0.0.1/lib/schema/Foo.json',
$schema: 'http://json-schema.org/draft-07/schema#',
additionalProperties: false,
definitions: {
FooType: {
description: 'This is a simple type declaration for usage in the Foo interface.',
const: 'Foo',
type: 'string',
},
SCFoo: {
additionalProperties: false,
description:
'This is a simple interface declaration for testing the schema generation and validation.',
properties: {
lorem: {
description: 'Dummy parameter',
enum: ['lorem', 'ipsum'],
type: 'string',
},
type: {
$ref: '#/definitions/FooType',
description: 'String literal type property',
},
},
required: ['lorem', 'type'],
type: 'object',
},
},
description: 'This is a simple interface declaration for testing the schema generation and validation.',
properties: {
lorem: {
description: 'Dummy parameter',
enum: ['lorem', 'ipsum'],
type: 'string',
},
type: {
$ref: '#/definitions/FooType',
description: 'String literal type property',
},
},
required: ['lorem', 'type'],
type: 'object',
});
}
}

View File

@@ -0,0 +1,87 @@
/* eslint-disable unicorn/prefer-module */
/*
* Copyright (C) 2019 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {Logger} from '@openstapps/logger';
import {expect} from 'chai';
import {existsSync, mkdirSync, writeFileSync} from 'fs';
import {JSONSchema7 as Schema} from 'json-schema';
import {slow, suite, test, timeout} from '@testdeck/mocha';
import rimraf from 'rimraf';
import {Foo} from '../src/resources/foo';
import {Converter} from '../src/schema';
import {Validator} from '../src/validate';
import path from 'path';
process.on('unhandledRejection', (error: unknown) => {
if (error instanceof Error) {
void Logger.error('UNHANDLED REJECTION', error.stack);
}
process.exit(1);
});
const tmpdir = path.join(__dirname, 'tmp');
const fooInstance: Foo = {
lorem: 'ipsum',
type: 'Foo',
};
@suite(timeout(40_000), slow(5000))
export class ValidateSpec {
static converter: Converter;
static schema: Schema;
static before() {
this.converter = new Converter(path.join(__dirname, '..', 'src', 'resources'));
this.schema = this.converter.getSchema('Foo', '0.0.1');
if (!existsSync(tmpdir)) {
mkdirSync(tmpdir);
}
writeFileSync(path.join(tmpdir, 'SCFoo.json'), JSON.stringify(this.schema, undefined, 2));
}
static after() {
rimraf(tmpdir, error => {
// tslint:disable-next-line: no-unused-expression
expect(error, `Unable to remove temporary directory for tests at: ${tmpdir}`).to.be.null;
});
}
@test
async validateBySchemaIdentifyingString() {
const validator = new Validator();
await validator.addSchemas(tmpdir);
const validationResult = validator.validate(fooInstance, 'SCFoo');
// tslint:disable-next-line: no-unused-expression
expect(validationResult.errors, JSON.stringify(validationResult.errors, undefined, 2)).to.be.empty;
}
@test
async validateBySchemaInstance() {
const validator = new Validator();
const validationResult = validator.validate(fooInstance, ValidateSpec.schema);
// tslint:disable-next-line: no-unused-expression
expect(validationResult.errors, JSON.stringify(validationResult.errors, undefined, 2)).to.be.empty;
}
@test
async validateIntrinsic() {
const validator = new Validator();
await validator.addSchemas(tmpdir);
const validationResult = validator.validate(fooInstance);
// tslint:disable-next-line: no-unused-expression
expect(validationResult.errors, JSON.stringify(validationResult.errors, undefined, 2)).to.be.empty;
}
}

View File

@@ -0,0 +1,7 @@
{
"extends": "./node_modules/@openstapps/configuration/tsconfig.json",
"compilerOptions": {
"noUnusedLocals": false,
"stripInternal": true
}
}