├── .gitattributes
├── .github
├── dependabot.yml
└── workflows
│ ├── release-gradle-plugin.yml
│ └── release.yml
├── .gitignore
├── LICENSE
├── README.md
├── appveyor.yml
├── build
├── download-appveyor-artifacts.ps1
├── download-hudson-artifacts.ps1
├── how-to-release.md
├── release-build.ps1
└── typescript-generator-gradle-plugin-publisher
│ ├── build.gradle
│ └── src
│ └── main
│ └── java
│ └── cz
│ └── habarta
│ └── typescript
│ └── generator
│ └── gradle
│ └── TypeScriptGeneratorPublishedPlugin.java
├── checkstyle.xml
├── pom.xml
├── sample-gradle-spring
├── build.gradle
└── src
│ └── main
│ └── java
│ └── cz
│ └── habarta
│ └── typescript
│ └── generator
│ └── sample
│ └── spring
│ └── SpringTestApplication.java
├── sample-gradle
├── build.gradle
└── src
│ └── main
│ ├── groovy
│ └── cz
│ │ └── habarta
│ │ └── typescript
│ │ └── generator
│ │ └── sample
│ │ └── PersonGroovy.groovy
│ ├── java
│ └── cz
│ │ └── habarta
│ │ └── typescript
│ │ └── generator
│ │ └── sample
│ │ └── Person.java
│ ├── kotlin
│ └── cz
│ │ └── habarta
│ │ └── typescript
│ │ └── generator
│ │ └── sample
│ │ └── PersonKt.kt
│ └── scala
│ └── cz
│ └── habarta
│ └── typescript
│ └── generator
│ └── sample
│ └── PersonScala.scala
├── sample-maven-spring
├── pom.xml
└── src
│ └── main
│ └── java
│ └── cz
│ └── habarta
│ └── typescript
│ └── generator
│ └── sample
│ └── spring
│ └── SpringTestApplication.java
├── sample-maven
├── pom.xml
└── src
│ └── main
│ └── java
│ └── cz
│ └── habarta
│ └── typescript
│ └── generator
│ └── sample
│ └── Person.java
├── tslint.json
├── typescript-generator-core
├── package-lock.json
├── package.json
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── cz
│ │ │ └── habarta
│ │ │ └── typescript
│ │ │ └── generator
│ │ │ ├── ClassMapping.java
│ │ │ ├── CustomMappingTypeProcessor.java
│ │ │ ├── DataLibraryJson.java
│ │ │ ├── DateMapping.java
│ │ │ ├── DefaultTypeProcessor.java
│ │ │ ├── DeprecationText.java
│ │ │ ├── EnumMapping.java
│ │ │ ├── ExcludingTypeProcessor.java
│ │ │ ├── Extension.java
│ │ │ ├── GsonConfiguration.java
│ │ │ ├── IdentifierCasing.java
│ │ │ ├── Input.java
│ │ │ ├── Jackson2Configuration.java
│ │ │ ├── Jackson2ConfigurationResolved.java
│ │ │ ├── JaxrsApplicationScanner.java
│ │ │ ├── JsonLibrary.java
│ │ │ ├── JsonbConfiguration.java
│ │ │ ├── LoadedDataLibraries.java
│ │ │ ├── LoadedModuleDependencies.java
│ │ │ ├── Logger.java
│ │ │ ├── MapMapping.java
│ │ │ ├── ModuleDependency.java
│ │ │ ├── NullabilityDefinition.java
│ │ │ ├── OptionalProperties.java
│ │ │ ├── OptionalPropertiesDeclaration.java
│ │ │ ├── Output.java
│ │ │ ├── RestNamespacing.java
│ │ │ ├── Settings.java
│ │ │ ├── StringQuotes.java
│ │ │ ├── TsParameter.java
│ │ │ ├── TsProperty.java
│ │ │ ├── TsType.java
│ │ │ ├── TypeProcessor.java
│ │ │ ├── TypeScriptFileType.java
│ │ │ ├── TypeScriptGenerator.java
│ │ │ ├── TypeScriptOutputKind.java
│ │ │ ├── compiler
│ │ │ ├── EnumKind.java
│ │ │ ├── EnumMemberModel.java
│ │ │ ├── ModelCompiler.java
│ │ │ ├── ModelTransformer.java
│ │ │ ├── Symbol.java
│ │ │ ├── SymbolTable.java
│ │ │ └── TsModelTransformer.java
│ │ │ ├── emitter
│ │ │ ├── Emittable.java
│ │ │ ├── Emitter.java
│ │ │ ├── EmitterExtension.java
│ │ │ ├── EmitterExtensionFeatures.java
│ │ │ ├── InfoJson.java
│ │ │ ├── InfoJsonEmitter.java
│ │ │ ├── NpmPackageJson.java
│ │ │ ├── NpmPackageJsonEmitter.java
│ │ │ ├── TsAccessibilityModifier.java
│ │ │ ├── TsAliasModel.java
│ │ │ ├── TsArrowFunction.java
│ │ │ ├── TsAssignmentExpression.java
│ │ │ ├── TsBeanCategory.java
│ │ │ ├── TsBeanModel.java
│ │ │ ├── TsBinaryExpression.java
│ │ │ ├── TsBinaryOperator.java
│ │ │ ├── TsBooleanLiteral.java
│ │ │ ├── TsCallExpression.java
│ │ │ ├── TsCallableModel.java
│ │ │ ├── TsConstructorModel.java
│ │ │ ├── TsDeclarationModel.java
│ │ │ ├── TsDecorator.java
│ │ │ ├── TsEnumModel.java
│ │ │ ├── TsExpression.java
│ │ │ ├── TsExpressionStatement.java
│ │ │ ├── TsHelper.java
│ │ │ ├── TsIdentifierReference.java
│ │ │ ├── TsIfStatement.java
│ │ │ ├── TsMemberExpression.java
│ │ │ ├── TsMethodModel.java
│ │ │ ├── TsModel.java
│ │ │ ├── TsModifierFlags.java
│ │ │ ├── TsNewExpression.java
│ │ │ ├── TsNumberLiteral.java
│ │ │ ├── TsObjectLiteral.java
│ │ │ ├── TsParameterModel.java
│ │ │ ├── TsPrefixUnaryExpression.java
│ │ │ ├── TsPropertyDefinition.java
│ │ │ ├── TsPropertyModel.java
│ │ │ ├── TsReturnStatement.java
│ │ │ ├── TsStatement.java
│ │ │ ├── TsStringLiteral.java
│ │ │ ├── TsSuperExpression.java
│ │ │ ├── TsSwitchCaseClause.java
│ │ │ ├── TsSwitchStatement.java
│ │ │ ├── TsTaggedTemplateLiteral.java
│ │ │ ├── TsTemplateLiteral.java
│ │ │ ├── TsThisExpression.java
│ │ │ ├── TsTypeReferenceExpression.java
│ │ │ ├── TsUnaryOperator.java
│ │ │ └── TsVariableDeclarationStatement.java
│ │ │ ├── ext
│ │ │ ├── AxiosClientExtension.java
│ │ │ ├── BeanPropertyPathExtension.java
│ │ │ ├── ClassEnumExtension.java
│ │ │ ├── DefaultsFromInstanceExtension.java
│ │ │ ├── JsonDeserializationExtension.java
│ │ │ ├── OnePossiblePropertyValueAssigningExtension.java
│ │ │ ├── PropertyPolymorphismExtension.java
│ │ │ ├── RequiredPropertyConstructorExtension.java
│ │ │ └── TypeGuardsForJackson2PolymorphismExtension.java
│ │ │ ├── parser
│ │ │ ├── BeanModel.java
│ │ │ ├── DeclarationModel.java
│ │ │ ├── DeprecationEnricher.java
│ │ │ ├── EnumModel.java
│ │ │ ├── GsonParser.java
│ │ │ ├── Jackson2Parser.java
│ │ │ ├── Javadoc.java
│ │ │ ├── JaxrsApplicationParser.java
│ │ │ ├── JsonbParser.java
│ │ │ ├── MethodModel.java
│ │ │ ├── MethodParameterModel.java
│ │ │ ├── Model.java
│ │ │ ├── ModelParser.java
│ │ │ ├── PathTemplate.java
│ │ │ ├── PropertyAccess.java
│ │ │ ├── PropertyModel.java
│ │ │ ├── RestApplicationModel.java
│ │ │ ├── RestApplicationParser.java
│ │ │ ├── RestApplicationType.java
│ │ │ ├── RestMethodModel.java
│ │ │ ├── RestQueryParam.java
│ │ │ ├── SourceType.java
│ │ │ ├── Swagger.java
│ │ │ ├── SwaggerOperation.java
│ │ │ ├── SwaggerResponse.java
│ │ │ └── TypeParser.java
│ │ │ ├── type
│ │ │ ├── JGenericArrayType.java
│ │ │ ├── JParameterizedType.java
│ │ │ ├── JTypeVariable.java
│ │ │ ├── JTypeWithNullability.java
│ │ │ ├── JUnionType.java
│ │ │ └── JWildcardType.java
│ │ │ └── util
│ │ │ ├── AnnotationGetter.java
│ │ │ ├── DeprecationUtils.java
│ │ │ ├── GenericsResolver.java
│ │ │ ├── Pair.java
│ │ │ ├── PropertyMember.java
│ │ │ ├── StandardJsonPrettyPrinter.java
│ │ │ └── Utils.java
│ ├── resources
│ │ ├── cz
│ │ │ └── habarta
│ │ │ │ └── typescript
│ │ │ │ └── generator
│ │ │ │ └── ext
│ │ │ │ ├── AxiosClientExtension-client.template.ts
│ │ │ │ └── AxiosClientExtension-shared.template.ts
│ │ ├── datalibrary
│ │ │ ├── _schema.json
│ │ │ ├── guava.json
│ │ │ ├── joda.json
│ │ │ └── vavr.json
│ │ └── helpers
│ │ │ ├── jsonDeserialization.ts
│ │ │ └── uriEncoding.ts
│ └── schema
│ │ └── javadoc.xsd
│ └── test
│ ├── java
│ └── cz
│ │ └── habarta
│ │ └── typescript
│ │ └── generator
│ │ ├── ClassesTest.java
│ │ ├── CovariantPropertiesTest.java
│ │ ├── CustomTypeAliasesTest.java
│ │ ├── CustomTypeConversionTest.java
│ │ ├── CustomTypeMappingTest.java
│ │ ├── DateTest.java
│ │ ├── DecoratorsTest.java
│ │ ├── DefaultTypeProcessorTest.java
│ │ ├── DeprecationUtilsTest.java
│ │ ├── DummyBean.java
│ │ ├── DummyClassEnum.java
│ │ ├── DummyEnum.java
│ │ ├── DummyMixedCaseEnum.java
│ │ ├── DuplicatePropertyTest.java
│ │ ├── EnumTest.java
│ │ ├── ExtensionTest.java
│ │ ├── FullyQualifiedNamesTest.java
│ │ ├── GenericCustomTypeMappingsTest.java
│ │ ├── GenericsResolverTest.java
│ │ ├── GenericsTest.java
│ │ ├── ImmutablesTest.java
│ │ ├── IncludeExcludePropertyTest.java
│ │ ├── InputTest.java
│ │ ├── InterfaceTest.java
│ │ ├── Jackson2ConfigurationResolvedTest.java
│ │ ├── Jackson2DeserializableRootType.java
│ │ ├── Jackson2ParserTest.java
│ │ ├── Jackson2PolymorphismTest.java
│ │ ├── JavadocTest.java
│ │ ├── JaxbTest.java
│ │ ├── JaxbV3Test.java
│ │ ├── JaxrsApplicationTest.java
│ │ ├── JsonDeserializationTest.java
│ │ ├── JsonUnwrappedTest.java
│ │ ├── JsonViewTest.java
│ │ ├── KotlinTest.kt
│ │ ├── MapEntryTest.java
│ │ ├── MapExtensionTest.java
│ │ ├── MapTest.java
│ │ ├── ModelCompilerTest.java
│ │ ├── ModelParserTest.java
│ │ ├── ModuleDependenciesTest.java
│ │ ├── ModulesAndNamespacesTest.java
│ │ ├── NamingTest.java
│ │ ├── NullabilityTest.java
│ │ ├── NumberEnumTest.java
│ │ ├── ObjectAsIdTest.java
│ │ ├── OptionalAnnotationTest.java
│ │ ├── OptionalTest.java
│ │ ├── PathTemplateTest.java
│ │ ├── Person.java
│ │ ├── PersonTest.java
│ │ ├── ReadOnlyWriteOnlyTest.java
│ │ ├── RecordTest.java
│ │ ├── SealedClassTest.java
│ │ ├── SettingsTest.java
│ │ ├── SortedTypesTest.java
│ │ ├── StyleConfigurationTest.java
│ │ ├── Swagger3Test.java
│ │ ├── SwaggerTest.java
│ │ ├── TaggedUnionsTest.java
│ │ ├── TestEnums.java
│ │ ├── TestUtils.java
│ │ ├── TsTypeTest.java
│ │ ├── TypeGuardsForJackson2PolymorphismExtensionTest.java
│ │ ├── UtilsTest.java
│ │ ├── compiler
│ │ └── ModelCompilerUtilsTest.java
│ │ ├── ext
│ │ ├── AxiosClientExtensionTest.java
│ │ ├── BeanPropertyPathExtensionTest.java
│ │ ├── DefaultsFromInstanceExtensionTest.java
│ │ ├── OnePossiblePropertyValueAssigningExtensionTest.java
│ │ ├── PropertyPolymorphismExtensionTest.java
│ │ └── RequiredPropertyConstructorExtensionTest.java
│ │ ├── library
│ │ ├── GuavaTest.java
│ │ ├── JodaTest.java
│ │ └── VavrTest.java
│ │ ├── p1
│ │ ├── A.java
│ │ ├── C.java
│ │ └── E.java
│ │ ├── p2
│ │ ├── B.java
│ │ └── D.java
│ │ ├── parser
│ │ ├── GsonParserTest.java
│ │ ├── Jackson2ParserPropertiesTest.java
│ │ ├── JaxrsApplicationParserTest.java
│ │ └── JsonbParserTest.java
│ │ └── yield
│ │ └── KeywordInPackage.java
│ ├── javadoc
│ └── test-javadoc.xml
│ ├── resources
│ ├── cz
│ │ └── habarta
│ │ │ └── typescript
│ │ │ └── generator
│ │ │ ├── JsonDeserializationTest-expected.ts
│ │ │ └── JsonDeserializationTestWithConstructors-expected.ts
│ └── ext
│ │ ├── OnePossiblePropertyValueAssigningExtensionTest-all.ts
│ │ ├── RequiredPropertyConstructorExtensionTest-basicWithConfiguration.ts
│ │ ├── RequiredPropertyConstructorExtensionTest-basicWithReadOnly.ts
│ │ ├── RequiredPropertyConstructorExtensionTest-basicWithoutReadOnly.ts
│ │ ├── RequiredPropertyConstructorExtensionTest-enums.ts
│ │ ├── RequiredPropertyConstructorExtensionTest-inheritance.ts
│ │ ├── RequiredPropertyConstructorExtensionTest-optionalParameters.ts
│ │ └── expected.ts
│ └── ts
│ ├── JsonDeserializationTest
│ ├── JsonDeserializationTest-expected-test-data.json
│ ├── JsonDeserializationTest-expected-test.ts
│ └── tsconfig.json
│ ├── module-usage-pkg.ts
│ ├── module-usage.ts
│ ├── my-custom-types.d.ts
│ ├── my-module.d.ts
│ └── tsconfig.json
├── typescript-generator-gradle-plugin
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── cz
│ │ └── habarta
│ │ └── typescript
│ │ └── generator
│ │ └── gradle
│ │ ├── GenerateTask.java
│ │ └── TypeScriptGeneratorPlugin.java
│ └── resources
│ └── META-INF
│ └── gradle-plugins
│ └── cz.habarta.typescript-generator.properties
├── typescript-generator-maven-plugin
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── cz
│ │ └── habarta
│ │ └── typescript
│ │ └── generator
│ │ └── maven
│ │ └── GenerateMojo.java
│ └── site
│ ├── markdown
│ └── index.md
│ └── site.xml
└── typescript-generator-spring
├── pom.xml
└── src
├── main
└── java
│ └── cz
│ └── habarta
│ └── typescript
│ └── generator
│ └── spring
│ └── SpringApplicationParser.java
└── test
└── java
└── cz
└── habarta
└── typescript
└── generator
└── spring
├── SpringKotlinTest.kt
├── SpringTest.java
└── SpringTestApplication.java
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text=auto
2 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: "maven"
4 | directory: "/"
5 | schedule:
6 | interval: "monthly"
7 | open-pull-requests-limit: 10
8 |
--------------------------------------------------------------------------------
/.github/workflows/release-gradle-plugin.yml:
--------------------------------------------------------------------------------
1 |
2 | name: Release to Gradle plugin portal
3 |
4 | on:
5 | workflow_dispatch:
6 | inputs:
7 | version:
8 | description: typescript-generator version
9 | required: true
10 | type: string
11 |
12 | jobs:
13 | release:
14 | runs-on: windows-latest
15 | steps:
16 |
17 | - name: Checkout workflow
18 | uses: actions/checkout@v3
19 |
20 | - name: Setup Java
21 | uses: actions/setup-java@v3
22 | with:
23 | distribution: temurin
24 | java-version: 11
25 |
26 | - name: Execute Gradle publish
27 | uses: gradle/gradle-build-action@v2
28 | with:
29 | gradle-version: 7.5.1
30 | build-root-directory: build\typescript-generator-gradle-plugin-publisher
31 | arguments: printVersion publishPlugins
32 | env:
33 | ORG_GRADLE_PROJECT_version: ${{ inputs.version }}
34 | GRADLE_PUBLISH_KEY: ${{ secrets.GRADLE_PUBLISH_KEY }}
35 | GRADLE_PUBLISH_SECRET: ${{ secrets.GRADLE_PUBLISH_SECRET }}
36 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 |
2 | name: Release to Maven Central
3 |
4 | on:
5 | workflow_dispatch:
6 |
7 | jobs:
8 | release:
9 | runs-on: windows-latest
10 |
11 | steps:
12 | - name: Checkout workflow
13 | uses: actions/checkout@v2
14 | - name: Setup GPG signing key
15 | run: |
16 | if (-not $env:GPG_SIGNING_KEY) {
17 | Write-Error "Please set GPG_SIGNING_KEY environment variable"
18 | exit 1
19 | }
20 | mkdir target -Force | Out-Null
21 | $gpg_signing_key = [Convert]::FromBase64String($env:GPG_SIGNING_KEY)
22 | [System.IO.File]::WriteAllBytes("target/gpg_signing_key.bin", $gpg_signing_key)
23 | gpg --import target/gpg_signing_key.bin
24 | gpg --list-secret-keys
25 | env:
26 | GPG_SIGNING_KEY: ${{ secrets.GPG_SIGNING_KEY }}
27 | - name: Sign and upload
28 | run: |
29 | ./build/release-build.ps1
30 | env:
31 | OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }}
32 | OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }}
33 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Maven
2 | target/
3 | pom.xml.tag
4 | pom.xml.releaseBackup
5 | pom.xml.versionsBackup
6 | pom.xml.next
7 | release.properties
8 |
9 | # Gradle
10 | /sample-gradle/.gradle/
11 | /sample-gradle/.nb-gradle/
12 | /sample-gradle/bin/
13 | /sample-gradle/build/
14 | /sample-gradle-spring/.gradle/
15 | /sample-gradle-spring/.nb-gradle/
16 | /sample-gradle-spring/bin/
17 | /sample-gradle-spring/build/
18 | .gradle
19 | gradlew*
20 | gradle-wrapper*
21 |
22 | # nodejs
23 | node/
24 |
25 | # npm
26 | node_modules
27 |
28 | # NetBeans
29 | nbactions.xml
30 |
31 | # Eclipse
32 | **.classpath
33 | **.project
34 | **.settings
35 |
36 | # JetBrains IntelliJ
37 | .idea/
38 | *.iml
39 |
40 | # VS Code
41 | .vscode
42 |
43 | # generated files
44 | typescript-generator-core/src/test/**/*.js
45 | typescript-generator-core/src/test/**/*.js.map
46 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2014 vojtechhabarta
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
23 |
--------------------------------------------------------------------------------
/appveyor.yml:
--------------------------------------------------------------------------------
1 | version: 3.2.{build}
2 | pull_requests:
3 | do_not_increment_build_number: true
4 | skip_tags: true
5 | cache:
6 | - '%USERPROFILE%\.m2\repository -> appveyor.yml'
7 | init:
8 | - ps: |-
9 | if ($env:APPVEYOR_REPO_BRANCH -ne "main" -or $env:APPVEYOR_PULL_REQUEST_NUMBER)
10 | {
11 | $env:APPVEYOR_CACHE_SKIP_SAVE = "true"
12 | }
13 | install:
14 | - ps: |-
15 | git remote set-url origin https://github.com/vojtechhabarta/typescript-generator.git
16 | git config --global credential.helper store
17 | Add-Content "$env:USERPROFILE\.git-credentials" "https://$($env:access_token):x-oauth-basic@github.com`n"
18 | build_script:
19 | - ps: |-
20 | Write-Host -ForegroundColor Cyan "Building version: $($env:APPVEYOR_BUILD_VERSION)"
21 | $env:JAVA_HOME = "C:\Program Files\Java\jdk11"
22 | $env:PATH = "$env:JAVA_HOME\bin;$env:PATH"
23 | mvn -version
24 | mvn --batch-mode versions:set "-DnewVersion=$($env:APPVEYOR_BUILD_VERSION)"; if ($LASTEXITCODE -ne 0) { throw "Build failed" }
25 | mvn --batch-mode -P attach-artifacts clean install -P local-deploy; if ($LASTEXITCODE -ne 0) { throw "Build failed" }
26 | if ($env:APPVEYOR_REPO_BRANCH -eq "main" -and -not $env:APPVEYOR_PULL_REQUEST_NUMBER)
27 | {
28 | mvn --batch-mode site-deploy "-Dgithub.site.oauth2Token=$($env:access_token)"; if ($LASTEXITCODE -ne 0) { throw "Build failed" }
29 | }
30 |
31 | Write-Host -ForegroundColor Cyan "Archiving artifacts"
32 | del target\artifacts -Recurse -Include "maven-metadata.xml*"
33 | cd target\artifacts
34 | 7z a ..\artifacts.zip **
35 | cd ..\..
36 | artifacts:
37 | - path: target\artifacts.zip
38 | on_success:
39 | - ps: |-
40 | if ($env:APPVEYOR_REPO_BRANCH -eq "main" -and -not $env:APPVEYOR_PULL_REQUEST_NUMBER)
41 | {
42 | Write-Host -ForegroundColor Cyan "Tagging version v$($env:APPVEYOR_BUILD_VERSION)"
43 | git tag "v$($env:APPVEYOR_BUILD_VERSION)" $env:APPVEYOR_REPO_COMMIT
44 | Write-Host -ForegroundColor Cyan "Pushing tag"
45 | git push origin "v$($env:APPVEYOR_BUILD_VERSION)" 2>&1 | %{ "$_" }; if ($LASTEXITCODE -ne 0) { throw "Command returned exit code $LASTEXITCODE" } else { Write-Host "Command finished successfully" }
46 | }
47 |
--------------------------------------------------------------------------------
/build/download-appveyor-artifacts.ps1:
--------------------------------------------------------------------------------
1 | # this script uses credentials from system browser, so first sign in to appveyor then run this script
2 | # documentation: http://www.appveyor.com/docs/api/samples/download-artifacts-ps
3 | $apiUrl = 'https://ci.appveyor.com/api'
4 |
5 | Write-Host -ForegroundColor DarkCyan "Getting appveyor project..."
6 | $project = Invoke-RestMethod -Method Get -Uri "$apiUrl/projects/vojtechhabarta/typescript-generator"
7 | $jobId = $project.build.jobs[0].jobId
8 |
9 | $artifactsUri = "$apiUrl/buildjobs/$jobId/artifacts/target/artifacts.zip"
10 | Write-Host -ForegroundColor DarkCyan "Downloading '$artifactsUri'..."
11 | $zipFilePath = "target\artifacts.zip"
12 | $zipFileDirectory = New-Item -ItemType directory -Path (Split-Path $zipFilePath) -Force
13 | Invoke-RestMethod -Method Get -Uri $artifactsUri -OutFile $zipFilePath
14 | $zipFile = Get-Item $zipFilePath
15 | $zipFile.FullName
16 |
--------------------------------------------------------------------------------
/build/download-hudson-artifacts.ps1:
--------------------------------------------------------------------------------
1 |
2 | if (! $env:HUDSON_URL) {
3 | Write-Error "Please set environment variable 'HUDSON_URL'"
4 | exit
5 | }
6 |
7 | $artifactsUri = "$env:HUDSON_URL/job/typescript-generator/lastSuccessfulBuild/artifact/*zip*/archive.zip"
8 | Write-Host -ForegroundColor DarkCyan "Downloading '$artifactsUri'..."
9 | $zipFilePath = "target\archive.zip"
10 | Invoke-WebRequest $artifactsUri -OutFile $zipFilePath
11 | $zipFile = Get-Item $zipFilePath
12 | $zipFile.FullName
13 |
--------------------------------------------------------------------------------
/build/how-to-release.md:
--------------------------------------------------------------------------------
1 | # How to release typescript-generator
2 |
3 | - change version in `pom.xml` files and `appveyor.yml` (if not already changed)
4 | - wait for the build
5 | - run "Release to Maven Central" GitHub Action which releases last build
6 | - go to https://oss.sonatype.org and promote the release
7 | - "Staging Repositories"
8 | - "Close" the repo
9 | - wait for closing activities
10 | - "Release" the repo
11 | - wait for the release to appear in Maven Central - https://repo1.maven.org/maven2/cz/habarta/typescript-generator/
12 | - write release notes
13 | - run "Release to Gradle plugin portal" GitHub Action
14 | - close/update relevant issues and PRs
15 | - remove unused tags
16 |
--------------------------------------------------------------------------------
/build/release-build.ps1:
--------------------------------------------------------------------------------
1 |
2 | # Releases latest build to Maven Central Repository
3 | # Prerequisites:
4 | # - gpg with signing key without passphrase
5 | # - OSSRH_USERNAME
6 | # - OSSRH_PASSWORD
7 |
8 | if (-not $env:OSSRH_USERNAME -or -not $env:OSSRH_PASSWORD) {
9 | Write-Error "Please set OSSRH_USERNAME and OSSRH_PASSWORD environment variables"
10 | exit 1
11 | }
12 |
13 | $ErrorActionPreference = "Stop"
14 |
15 | # download
16 | $zipFile = ./build/download-appveyor-artifacts.ps1
17 |
18 | # unzip
19 | Write-Host -ForegroundColor DarkCyan "Unzipping..."
20 | $unzipDirectoryPath = "target/gpg-sign"
21 | Remove-Item -Recurse -Force $unzipDirectoryPath -ErrorAction SilentlyContinue
22 | Remove-Item -Recurse -Force $unzipDirectoryPath -ErrorAction SilentlyContinue
23 | $unzipDirectory = New-Item -ItemType directory -Path $unzipDirectoryPath -Force
24 | [System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem") | Out-Null
25 | [System.IO.Compression.ZipFile]::ExtractToDirectory($zipFile, $unzipDirectory.FullName)
26 | $basePath = (Resolve-Path $unzipDirectory).Path
27 |
28 | # sign
29 | foreach ($file in Get-ChildItem -Recurse -File $basePath -Exclude *.md5,*.sha1) {
30 | $path = $file.FullName.Substring($basePath.Length + 1)
31 | Write-Host -ForegroundColor DarkCyan "Signing $path..."
32 | gpg --detach-sign --armor $file.FullName
33 | Get-FileHash -Algorithm MD5 $file.FullName | ForEach-Object { [IO.File]::WriteAllText($file.FullName + ".md5", $_.Hash) }
34 | Get-FileHash -Algorithm SHA1 $file.FullName | ForEach-Object { [IO.File]::WriteAllText($file.FullName + ".sha1", $_.Hash) }
35 | }
36 |
37 | # upload
38 | $repoUri = "https://oss.sonatype.org/service/local/staging/deploy/maven2"
39 | $credential = New-Object -TypeName System.Net.NetworkCredential -ArgumentList $env:OSSRH_USERNAME, $env:OSSRH_PASSWORD
40 | $headers = @{"Authorization" = "Basic " + [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($credential.UserName + ":" + $credential.Password))}
41 | foreach ($file in Get-ChildItem -Recurse -File $basePath) {
42 | $path = $file.FullName.Substring($basePath.Length + 1)
43 | Write-Host -ForegroundColor DarkCyan "Uploading $path..."
44 | $pom = (Get-ChildItem $file.Directory -Filter *.pom).FullName
45 | [xml]$pomXml = Get-Content $pom
46 | $groupId = if ($pomXml.project.groupId) { $pomXml.project.groupId } else { $pomXml.project.parent.groupId }
47 | $uri = $groupId.Replace(".", "/") + $path.Substring($groupId.Length).Replace("\", "/")
48 | Invoke-WebRequest -InFile $file.FullName -Method Put "$repoUri/$uri" -Headers $headers -UseBasicParsing | Out-Null
49 | }
50 |
51 | Write-Host -ForegroundColor Cyan "Build successfully uploaded. Go to https://oss.sonatype.org and promote the release."
52 |
--------------------------------------------------------------------------------
/build/typescript-generator-gradle-plugin-publisher/build.gradle:
--------------------------------------------------------------------------------
1 |
2 | plugins {
3 | id 'com.gradle.plugin-publish' version '1.0.0'
4 | id 'java-library'
5 | }
6 |
7 | group = 'cz.habarta.typescript-generator'
8 |
9 | repositories {
10 | mavenCentral()
11 | mavenLocal()
12 | }
13 |
14 | dependencies {
15 | api "cz.habarta.typescript-generator:typescript-generator-gradle-plugin:${version}"
16 | api "cz.habarta.typescript-generator:typescript-generator-spring:${version}"
17 | }
18 |
19 | task printVersion {
20 | doLast {
21 | println "Releasing 'cz.habarta.typescript-generator' Gradle plugin version ${project.version}..."
22 | }
23 | }
24 |
25 | pluginBundle {
26 | website = 'https://github.com/vojtechhabarta/typescript-generator'
27 | vcsUrl = 'https://github.com/vojtechhabarta/typescript-generator'
28 | tags = ['java', 'kotlin', 'json', 'typescript', 'typescript-generator', 'jackson', 'jakarta', 'rest', 'client', 'spring']
29 | }
30 |
31 | gradlePlugin {
32 | plugins {
33 | typescriptGeneratorPlugin {
34 | id = 'cz.habarta.typescript-generator'
35 | displayName = 'Typescript-generator Gradle plugin'
36 | description = 'Generates TypeScript from Java - JSON declarations, REST service client'
37 | implementationClass = 'cz.habarta.typescript.generator.gradle.TypeScriptGeneratorPublishedPlugin'
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/build/typescript-generator-gradle-plugin-publisher/src/main/java/cz/habarta/typescript/generator/gradle/TypeScriptGeneratorPublishedPlugin.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.gradle;
3 |
4 | public class TypeScriptGeneratorPublishedPlugin extends TypeScriptGeneratorPlugin {
5 | }
6 |
--------------------------------------------------------------------------------
/checkstyle.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/sample-gradle-spring/build.gradle:
--------------------------------------------------------------------------------
1 |
2 | plugins {
3 | id 'java'
4 | id 'cz.habarta.typescript-generator' version 'FILL_VERSION'
5 | }
6 |
7 | version = '3.0'
8 | sourceCompatibility = 11
9 | targetCompatibility = 11
10 |
11 | repositories {
12 | mavenCentral()
13 | }
14 |
15 | dependencies {
16 | implementation 'org.springframework.boot:spring-boot-starter-web:2.7.4'
17 | }
18 |
19 | generateTypeScript {
20 | classes = [
21 | 'cz.habarta.typescript.generator.sample.spring.SpringTestApplication'
22 | ]
23 | outputFileType = 'implementationFile'
24 | jsonLibrary = 'jackson2'
25 | outputKind = 'module'
26 | scanSpringApplication = true
27 | generateSpringApplicationClient = true
28 | }
29 |
30 | build.dependsOn generateTypeScript
31 |
--------------------------------------------------------------------------------
/sample-gradle-spring/src/main/java/cz/habarta/typescript/generator/sample/spring/SpringTestApplication.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.sample.spring;
3 |
4 | import java.util.concurrent.atomic.AtomicLong;
5 | import org.springframework.boot.SpringApplication;
6 | import org.springframework.boot.autoconfigure.SpringBootApplication;
7 | import org.springframework.web.bind.annotation.RequestMapping;
8 | import org.springframework.web.bind.annotation.RequestParam;
9 | import org.springframework.web.bind.annotation.RestController;
10 |
11 |
12 | @SpringBootApplication
13 | public class SpringTestApplication {
14 |
15 | public static void main(String[] args) {
16 | SpringApplication.run(SpringTestApplication.class, args);
17 | }
18 |
19 | @RestController
20 | public static class GreetingController {
21 |
22 | private static final String template = "Hello, %s!";
23 | private final AtomicLong counter = new AtomicLong();
24 |
25 | @RequestMapping("/greeting")
26 | public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
27 | return new Greeting(counter.incrementAndGet(), String.format(template, name));
28 | }
29 |
30 | }
31 |
32 | public static class Greeting {
33 |
34 | private final long id;
35 | private final String content;
36 |
37 | public Greeting(long id, String content) {
38 | this.id = id;
39 | this.content = content;
40 | }
41 |
42 | public long getId() {
43 | return id;
44 | }
45 |
46 | public String getContent() {
47 | return content;
48 | }
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/sample-gradle/build.gradle:
--------------------------------------------------------------------------------
1 |
2 | buildscript {
3 | // /*dev*/ repositories {
4 | // /*dev*/ mavenLocal()
5 | // /*dev*/ }
6 | dependencies {
7 | classpath 'com.fasterxml.jackson.module:jackson-module-scala_2.13:2.14.2'
8 | // /*dev*/ classpath 'cz.habarta.typescript-generator:typescript-generator-gradle-plugin:FILL_VERSION-SNAPSHOT'
9 | }
10 | }
11 |
12 | plugins {
13 | id 'java'
14 | id 'groovy'
15 | id "org.jetbrains.kotlin.jvm" version "1.8.10"
16 | id 'scala'
17 | /*prod*/ id 'cz.habarta.typescript-generator' version 'FILL_VERSION'
18 | }
19 |
20 | // /*dev*/ apply plugin: 'cz.habarta.typescript-generator'
21 |
22 | version = '3.0'
23 | sourceCompatibility = 11
24 | targetCompatibility = 11
25 |
26 | repositories {
27 | mavenCentral()
28 | }
29 |
30 | dependencies {
31 | implementation 'com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:2.14.2'
32 | implementation 'org.codehaus.groovy:groovy-all:3.0.16'
33 | implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.8.10'
34 | implementation 'org.scala-lang:scala-library:2.13.10'
35 | implementation 'com.fasterxml.jackson.module:jackson-module-kotlin:2.14.2'
36 | }
37 |
38 | tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile) {
39 | kotlinOptions {
40 | jvmTarget = '11'
41 | }
42 | }
43 |
44 | generateTypeScript {
45 | classes = [
46 | 'cz.habarta.typescript.generator.sample.Person',
47 | 'cz.habarta.typescript.generator.sample.PersonGroovy',
48 | 'cz.habarta.typescript.generator.sample.PersonKt',
49 | 'cz.habarta.typescript.generator.sample.PersonScala',
50 | ]
51 | jsonLibrary = 'jackson2'
52 | outputKind = 'module'
53 | excludeClasses = [
54 | 'groovy.lang.GroovyObject',
55 | 'groovy.lang.MetaClass',
56 | 'java.io.Serializable',
57 | 'scala.Equals',
58 | 'scala.Product',
59 | 'scala.Serializable',
60 | ]
61 | jackson2Modules = [
62 | 'com.fasterxml.jackson.module.scala.DefaultScalaModule',
63 | 'com.fasterxml.jackson.module.kotlin.KotlinModule',
64 | ]
65 | }
66 |
67 | build.dependsOn generateTypeScript
68 |
--------------------------------------------------------------------------------
/sample-gradle/src/main/groovy/cz/habarta/typescript/generator/sample/PersonGroovy.groovy:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.sample
3 |
4 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties
5 |
6 | @JsonIgnoreProperties("metaClass")
7 | class PersonGroovy {
8 | public String name
9 | public int age
10 | public boolean hasChildren
11 | public List tags
12 | public Map emails
13 | }
14 |
--------------------------------------------------------------------------------
/sample-gradle/src/main/java/cz/habarta/typescript/generator/sample/Person.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.sample;
3 |
4 | import java.util.*;
5 |
6 | public class Person {
7 | public String name;
8 | public int age;
9 | public boolean hasChildren;
10 | public List tags;
11 | public Map emails;
12 | }
13 |
--------------------------------------------------------------------------------
/sample-gradle/src/main/kotlin/cz/habarta/typescript/generator/sample/PersonKt.kt:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.sample
3 |
4 | data class PersonKt (
5 | val name: String,
6 | val age: Int,
7 | val hasChildren: Boolean,
8 | val tags: List,
9 | val emails: Map
10 | )
11 |
--------------------------------------------------------------------------------
/sample-gradle/src/main/scala/cz/habarta/typescript/generator/sample/PersonScala.scala:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.sample;
3 |
4 | case class PersonScala (
5 | name: String,
6 | age: Int,
7 | hasChildren: Boolean,
8 | tags: java.util.List[String],
9 | emails: java.util.Map[String, String]
10 | )
11 |
--------------------------------------------------------------------------------
/sample-maven-spring/src/main/java/cz/habarta/typescript/generator/sample/spring/SpringTestApplication.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.sample.spring;
3 |
4 | import java.util.concurrent.atomic.AtomicLong;
5 | import org.springframework.boot.SpringApplication;
6 | import org.springframework.boot.autoconfigure.SpringBootApplication;
7 | import org.springframework.web.bind.annotation.RequestMapping;
8 | import org.springframework.web.bind.annotation.RequestParam;
9 | import org.springframework.web.bind.annotation.RestController;
10 |
11 |
12 | @SpringBootApplication
13 | public class SpringTestApplication {
14 |
15 | public static void main(String[] args) {
16 | SpringApplication.run(SpringTestApplication.class, args);
17 | }
18 |
19 | @RestController
20 | public static class GreetingController {
21 |
22 | private static final String template = "Hello, %s!";
23 | private final AtomicLong counter = new AtomicLong();
24 |
25 | @RequestMapping("/greeting")
26 | public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
27 | return new Greeting(counter.incrementAndGet(), String.format(template, name));
28 | }
29 |
30 | }
31 |
32 | public static class Greeting {
33 |
34 | private final long id;
35 | private final String content;
36 |
37 | public Greeting(long id, String content) {
38 | this.id = id;
39 | this.content = content;
40 | }
41 |
42 | public long getId() {
43 | return id;
44 | }
45 |
46 | public String getContent() {
47 | return content;
48 | }
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/sample-maven/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 |
5 | cz.habarta.typescript-generator
6 | sample-maven
7 | 3.0-SNAPSHOT
8 | jar
9 | sample-maven
10 |
11 |
12 |
13 | com.fasterxml.jackson.jaxrs
14 | jackson-jaxrs-json-provider
15 | 2.13.4
16 |
17 |
18 |
19 |
20 |
21 |
22 | org.apache.maven.plugins
23 | maven-compiler-plugin
24 | 3.10.1
25 |
26 | 11
27 | 11
28 |
29 | -parameters
30 |
31 |
32 |
33 |
34 | cz.habarta.typescript-generator
35 | typescript-generator-maven-plugin
36 | FILL_VERSION
37 |
38 |
39 | generate
40 |
41 | generate
42 |
43 | process-classes
44 |
45 |
46 |
47 | jackson2
48 |
49 | cz.habarta.typescript.generator.sample.Person
50 |
51 | module
52 |
53 |
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/sample-maven/src/main/java/cz/habarta/typescript/generator/sample/Person.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.sample;
3 |
4 | import java.util.*;
5 |
6 | public class Person {
7 | public String name;
8 | public int age;
9 | public boolean hasChildren;
10 | public List tags;
11 | public Map emails;
12 | }
13 |
--------------------------------------------------------------------------------
/tslint.json:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/typescript-generator-core/package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "typescript-generator-core",
3 | "version": "1.0.0",
4 | "lockfileVersion": 1,
5 | "requires": true,
6 | "dependencies": {
7 | "@types/node": {
8 | "version": "14.17.20",
9 | "resolved": "https://registry.npmjs.org/@types/node/-/node-14.17.20.tgz",
10 | "integrity": "sha512-gI5Sl30tmhXsqkNvopFydP7ASc4c2cLfGNQrVKN3X90ADFWFsPEsotm/8JHSUJQKTHbwowAHtcJPeyVhtKv0TQ==",
11 | "dev": true
12 | },
13 | "typescript": {
14 | "version": "4.4.3",
15 | "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.4.3.tgz",
16 | "integrity": "sha512-4xfscpisVgqqDfPaJo5vkd+Qd/ItkoagnHpufr+i2QCHBsNYp+G7UAoyFl8aPtx879u38wPV65rZ8qbGZijalA==",
17 | "dev": true
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/typescript-generator-core/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "typescript-generator-core",
3 | "version": "1.0.0",
4 | "description": "Support for tests",
5 | "scripts": {
6 | "test": "npm run ModulesAndNamespacesTest && npm run JsonDeserializationTest",
7 | "ModulesAndNamespacesTest": "tsc -p src/test/ts/tsconfig.json",
8 | "JsonDeserializationTest": "tsc -p src/test/ts/JsonDeserializationTest/tsconfig.json && node src/test/ts/JsonDeserializationTest/JsonDeserializationTest-expected-test.js"
9 | },
10 | "license": "ISC",
11 | "devDependencies": {
12 | "typescript": "^4.3.2",
13 | "@types/node": "^14.17.0"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/ClassMapping.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 |
5 | public enum ClassMapping {
6 | asInterfaces, asClasses;
7 | }
8 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/DataLibraryJson.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import com.fasterxml.jackson.annotation.JsonValue;
5 | import java.util.List;
6 |
7 |
8 | public class DataLibraryJson {
9 |
10 | public List classMappings;
11 | public List typeAliases;
12 |
13 | public static class ClassMapping {
14 | public String className;
15 | public SemanticType semanticType;
16 | public String customType;
17 | }
18 |
19 | public enum SemanticType {
20 | String("string"),
21 | Number("number"),
22 | Boolean("boolean"),
23 | Date("date"),
24 | Any("any"),
25 | Void("void"),
26 | List("list"),
27 | Map("map"),
28 | Optional("optional"),
29 | Wrapper("wrapper"),
30 | ;
31 |
32 | private final String name;
33 |
34 | private SemanticType(String name) {
35 | this.name = name;
36 | }
37 |
38 | @JsonValue
39 | public String getName() {
40 | return name;
41 | }
42 |
43 | }
44 |
45 | public static class TypeAlias {
46 | public String name;
47 | public String definition;
48 | }
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/DateMapping.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 |
5 | public enum DateMapping {
6 | asDate, asNumber, asString
7 | }
8 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/DeprecationText.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import java.lang.annotation.Retention;
5 | import java.lang.annotation.RetentionPolicy;
6 |
7 |
8 | @Retention(RetentionPolicy.RUNTIME)
9 | public @interface DeprecationText {
10 | String value();
11 | }
12 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/EnumMapping.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 |
5 | public enum EnumMapping {
6 | asUnion, asInlineUnion, asEnum, asNumberBasedEnum
7 | }
8 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/ExcludingTypeProcessor.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import cz.habarta.typescript.generator.util.Utils;
5 | import java.lang.reflect.Type;
6 | import java.util.Collections;
7 | import java.util.LinkedHashSet;
8 | import java.util.List;
9 | import java.util.Set;
10 | import java.util.function.Predicate;
11 |
12 |
13 | public class ExcludingTypeProcessor implements TypeProcessor {
14 |
15 | private final Predicate excludeFilter;
16 |
17 | public ExcludingTypeProcessor(List excludedTypes) {
18 | this(new Predicate() {
19 | final Set excludedTypesSet = excludedTypes != null ? new LinkedHashSet<>(excludedTypes) : Collections.emptySet();
20 | @Override
21 | public boolean test(String typeName) {
22 | return excludedTypesSet.contains(typeName);
23 | }
24 | });
25 | }
26 |
27 | public ExcludingTypeProcessor(Predicate excludeFilter) {
28 | this.excludeFilter = excludeFilter;
29 | }
30 |
31 | @Override
32 | public Result processType(Type javaType, Context context) {
33 | final Class> rawClass = Utils.getRawClassOrNull(javaType);
34 | if (rawClass != null && excludeFilter.test(rawClass.getName())) {
35 | return new Result(TsType.Any);
36 | }
37 | return null;
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/Extension.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import cz.habarta.typescript.generator.compiler.ModelCompiler;
5 | import cz.habarta.typescript.generator.compiler.ModelTransformer;
6 | import cz.habarta.typescript.generator.compiler.TsModelTransformer;
7 | import cz.habarta.typescript.generator.emitter.EmitterExtension;
8 | import java.util.Collections;
9 | import java.util.List;
10 | import java.util.Map;
11 |
12 |
13 | public abstract class Extension extends EmitterExtension {
14 |
15 | public void setConfiguration(Map configuration) throws RuntimeException {
16 | }
17 |
18 | public List getTransformers() {
19 | return Collections.emptyList();
20 | }
21 |
22 | public static class TransformerDefinition {
23 | public final ModelCompiler.TransformationPhase phase;
24 | public final ModelTransformer transformer;
25 | public final TsModelTransformer tsTransformer;
26 |
27 | public TransformerDefinition(ModelCompiler.TransformationPhase phase, ModelTransformer transformer) {
28 | if (phase != ModelCompiler.TransformationPhase.BeforeTsModel) {
29 | throw new IllegalArgumentException("ModelTransformer can only be applied in phase 'BeforeTsModel'");
30 | }
31 | this.phase = phase;
32 | this.transformer = transformer;
33 | this.tsTransformer = null;
34 | }
35 |
36 | public TransformerDefinition(ModelCompiler.TransformationPhase phase, TsModelTransformer transformer) {
37 | if (phase == ModelCompiler.TransformationPhase.BeforeTsModel) {
38 | throw new IllegalArgumentException("TsModelTransformer cannot be applied in phase 'BeforeTsModel'");
39 | }
40 | this.phase = phase;
41 | this.transformer = null;
42 | this.tsTransformer = transformer;
43 | }
44 |
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/GsonConfiguration.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 |
5 | /**
6 | * This class is used for configuration in Maven and Gradle plugins so we need
7 | * to pay attention to use only types supported in both build plugins.
8 | */
9 | public class GsonConfiguration {
10 |
11 | /**
12 | * Excludes all class fields that have the specified modifiers.
13 | * Modifiers are separated with |
character.
14 | * Field exclusion modifiers are public | protected | private | static | final | transient | volatile
.
15 | * Default value is static | transient
(the same as in Gson itself).
16 | * Note: single charater |
can be used to pass empty list of modifiers
17 | * (in Maven empty string is interpreted as null
which means "not set").
18 | */
19 | public String excludeFieldsWithModifiers;
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/IdentifierCasing.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 |
5 | public enum IdentifierCasing {
6 | keepOriginal,
7 | PascalCase,
8 | camelCase,
9 | // UPPER_CASE,
10 | }
11 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/JsonLibrary.java:
--------------------------------------------------------------------------------
1 | package cz.habarta.typescript.generator;
2 |
3 | public enum JsonLibrary {
4 | jackson2, jaxb, gson, jsonb
5 | }
6 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/JsonbConfiguration.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | /**
5 | * This class is used for configuration in Maven and Gradle plugins
6 | * so we need to pay attention to use only types supported in both build plugins.
7 | */
8 | public class JsonbConfiguration {
9 |
10 | /**
11 | * {@link javax.json.bind.config.PropertyNamingStrategy} name.
12 | */
13 | public String namingStrategy = "IDENTITY";
14 | }
15 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/Logger.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 |
5 | public class Logger {
6 |
7 | private final Level level;
8 |
9 | public enum Level {
10 | Debug, Verbose, Info, Warning, Error;
11 | }
12 |
13 | public Logger() {
14 | this(null);
15 | }
16 |
17 | public Logger(Level level) {
18 | this.level = level != null ? level : Level.Verbose;
19 | }
20 |
21 | protected void write(Level level, String message) {
22 | if (level.compareTo(this.level) >= 0) {
23 | System.out.println(message);
24 | }
25 | }
26 |
27 | public final void verbose(String message) {
28 | write(Level.Verbose, message);
29 | }
30 |
31 | public final void info(String message) {
32 | write(Level.Info, message);
33 | }
34 |
35 | public final void warning(String message) {
36 | write(Level.Warning, "Warning: " + message);
37 | }
38 |
39 | public final void error(String message) {
40 | write(Level.Error, "Error: " + message);
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/MapMapping.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 |
5 | public enum MapMapping {
6 | asIndexedArray, asRecord
7 | }
8 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/ModuleDependency.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import com.fasterxml.jackson.annotation.JsonInclude;
5 | import cz.habarta.typescript.generator.util.Utils;
6 | import java.io.File;
7 |
8 |
9 | @JsonInclude(JsonInclude.Include.NON_DEFAULT)
10 | public class ModuleDependency {
11 |
12 | public boolean global;
13 | public String importFrom;
14 | public String importAs;
15 | public File infoJson;
16 | public String npmPackageName;
17 | public String npmVersionRange;
18 | public boolean peerDependency;
19 |
20 | public ModuleDependency() {
21 | }
22 |
23 | private ModuleDependency(boolean global, String importFrom, String importAs, File infoJson, String npmPackageName, String npmVersionRange, boolean peerDependency) {
24 | this.global = global;
25 | this.importFrom = importFrom;
26 | this.importAs = importAs;
27 | this.infoJson = infoJson;
28 | this.npmPackageName = npmPackageName;
29 | this.npmVersionRange = npmVersionRange;
30 | this.peerDependency = peerDependency;
31 | }
32 |
33 | public static ModuleDependency module(String importFrom, String importAs, File infoJson, String npmPackageName, String npmVersionRange) {
34 | return new ModuleDependency(false, importFrom, importAs, infoJson, npmPackageName, npmVersionRange, false);
35 | }
36 |
37 | public static ModuleDependency global(File infoJson) {
38 | return new ModuleDependency(true, null, null, infoJson, null, null, false);
39 | }
40 |
41 | @Override
42 | public String toString() {
43 | return Utils.objectToString(this);
44 | }
45 |
46 | public String toShortString() {
47 | return global ? "global" : "'" + importFrom + "'";
48 | }
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/NullabilityDefinition.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import java.util.Arrays;
5 | import java.util.List;
6 |
7 |
8 | public enum NullabilityDefinition {
9 |
10 | nullAndUndefinedUnion (false, TsType.Null, TsType.Undefined),
11 | nullUnion (false, TsType.Null),
12 | undefinedUnion (false, TsType.Undefined),
13 | nullAndUndefinedInlineUnion (true, TsType.Null, TsType.Undefined),
14 | nullInlineUnion (true, TsType.Null),
15 | undefinedInlineUnion (true, TsType.Undefined);
16 |
17 | private final boolean isInline;
18 | private final List types;
19 |
20 | private NullabilityDefinition(boolean isInline, TsType... types) {
21 | this.isInline = isInline;
22 | this.types = Arrays.asList(types);
23 | }
24 |
25 | public boolean isInline() {
26 | return isInline;
27 | }
28 |
29 | public List getTypes() {
30 | return types;
31 | }
32 |
33 | public boolean containsUndefined() {
34 | return types.contains(TsType.Undefined);
35 | }
36 |
37 | public boolean containsNull() {
38 | return types.contains(TsType.Null);
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/OptionalProperties.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 |
5 | public enum OptionalProperties {
6 | useSpecifiedAnnotations, useLibraryDefinition, all
7 | }
8 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/OptionalPropertiesDeclaration.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 |
5 | public enum OptionalPropertiesDeclaration {
6 | questionMark,
7 | questionMarkAndNullableType,
8 | nullableType,
9 | nullableAndUndefinableType,
10 | undefinableType,
11 | }
12 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/Output.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import java.io.File;
5 | import java.io.FileNotFoundException;
6 | import java.io.FileOutputStream;
7 | import java.io.OutputStream;
8 | import java.io.OutputStreamWriter;
9 | import java.io.Writer;
10 | import java.nio.charset.Charset;
11 |
12 |
13 | public class Output {
14 |
15 | private final Writer writer;
16 | private final String name;
17 | private final boolean closeWriter;
18 |
19 | private Output(Writer writer, String name, boolean closeWriter) {
20 | this.writer = writer;
21 | this.name = name;
22 | this.closeWriter = closeWriter;
23 | }
24 |
25 | public Writer getWriter() {
26 | return writer;
27 | }
28 |
29 | public String getName() {
30 | return name;
31 | }
32 |
33 | public boolean shouldCloseWriter() {
34 | return closeWriter;
35 | }
36 |
37 | public static Output to(File file) {
38 | try {
39 | file.getParentFile().mkdirs();
40 | return new Output(new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF-8")), file.toString(), true);
41 | } catch (FileNotFoundException e) {
42 | throw new RuntimeException(e);
43 | }
44 | }
45 |
46 | public static Output to(OutputStream outputStream) {
47 | return new Output(new OutputStreamWriter(outputStream, Charset.forName("UTF-8")), null, false);
48 | }
49 |
50 | public static Output to(Writer writer) {
51 | return new Output(writer, null, false);
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/RestNamespacing.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 |
5 | public enum RestNamespacing {
6 |
7 | singleObject, perResource, byAnnotation
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/StringQuotes.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 |
5 | public enum StringQuotes {
6 |
7 | doubleQuotes, singleQuotes;
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/TsParameter.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 |
5 | public class TsParameter {
6 |
7 | public final String name;
8 | public final TsType tsType;
9 |
10 | public TsParameter(String name, TsType tsType) {
11 | this.name = name;
12 | this.tsType = tsType;
13 | }
14 |
15 | public String getName() {
16 | return name;
17 | }
18 |
19 | public TsType getTsType() {
20 | return tsType;
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/TsProperty.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import cz.habarta.typescript.generator.emitter.Emitter;
5 |
6 |
7 | public class TsProperty {
8 |
9 | public final String name;
10 | public final TsType tsType;
11 |
12 | public TsProperty(String name, TsType tsType) {
13 | this.name = name;
14 | this.tsType = tsType;
15 | }
16 |
17 | public String getName() {
18 | return name;
19 | }
20 |
21 | public TsType getTsType() {
22 | return tsType;
23 | }
24 |
25 | public String format(Settings settings) {
26 | final String questionMark = (tsType instanceof TsType.OptionalType) ? "?" : "";
27 | return Emitter.quoteIfNeeded(name, settings) + questionMark + ": " + tsType.format(settings) + ";";
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/TypeScriptFileType.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 |
5 | public enum TypeScriptFileType {
6 |
7 | declarationFile, implementationFile
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/TypeScriptOutputKind.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 |
5 | public enum TypeScriptOutputKind {
6 |
7 | global, module, ambientModule
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/compiler/EnumKind.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.compiler;
3 |
4 |
5 | public enum EnumKind {
6 |
7 | StringBased, NumberBased
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/compiler/EnumMemberModel.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.compiler;
3 |
4 | import java.lang.reflect.Field;
5 | import java.util.List;
6 |
7 |
8 | public class EnumMemberModel {
9 |
10 | private final String propertyName;
11 | private final Object/*String|Number*/ enumValue;
12 | private final Field originalField;
13 | private final List comments;
14 |
15 | public EnumMemberModel(String propertyName, String enumValue, Field originalField, List comments) {
16 | this(propertyName, (Object)enumValue, originalField, comments);
17 | }
18 |
19 | public EnumMemberModel(String propertyName, Number enumValue, Field originalField, List comments) {
20 | this(propertyName, (Object)enumValue, originalField, comments);
21 | }
22 |
23 | private EnumMemberModel(String propertyName, Object enumValue, Field originalField, List comments) {
24 | this.propertyName = propertyName;
25 | this.enumValue = enumValue;
26 | this.originalField = originalField;
27 | this.comments = comments;
28 | }
29 |
30 | public String getPropertyName() {
31 | return propertyName;
32 | }
33 |
34 | public Object getEnumValue() {
35 | return enumValue;
36 | }
37 |
38 | public Field getOriginalField() {
39 | return originalField;
40 | }
41 |
42 | public List getComments() {
43 | return comments;
44 | }
45 |
46 | public EnumMemberModel withPropertyName(String propertyName) {
47 | return new EnumMemberModel(propertyName, enumValue, originalField, comments);
48 | }
49 |
50 | public EnumMemberModel withComments(List comments) {
51 | return new EnumMemberModel(propertyName, enumValue, originalField, comments);
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/compiler/ModelTransformer.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.compiler;
3 |
4 | import cz.habarta.typescript.generator.parser.Model;
5 |
6 |
7 | public interface ModelTransformer {
8 |
9 | public Model transformModel(SymbolTable symbolTable, Model model);
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/compiler/Symbol.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.compiler;
3 |
4 |
5 | public class Symbol {
6 |
7 | private String module;
8 | private String namespace;
9 | private String simpleName;
10 | private boolean isResolved = false;
11 |
12 | public Symbol(String temporaryName) {
13 | this.simpleName = temporaryName;
14 | }
15 |
16 | public String getModule() {
17 | return module;
18 | }
19 |
20 | public String getNamespace() {
21 | return namespace;
22 | }
23 |
24 | public String getSimpleName() {
25 | return simpleName;
26 | }
27 |
28 | public boolean isResolved() {
29 | return isResolved;
30 | }
31 |
32 | public String getFullName() {
33 | String fullName = simpleName;
34 | if (namespace != null) {
35 | fullName = namespace + "." + fullName;
36 | }
37 | if (module != null) {
38 | fullName = module + "." + fullName;
39 | }
40 | return fullName;
41 | }
42 |
43 | public void setFullName(String module, String namespacedName) {
44 | this.module = module;
45 | final int index = namespacedName.lastIndexOf('.');
46 | if (index == -1) {
47 | namespace = null;
48 | simpleName = namespacedName;
49 | } else {
50 | namespace = namespacedName.substring(0, index);
51 | simpleName = namespacedName.substring(index + 1);
52 | }
53 | this.isResolved = true;
54 | }
55 |
56 | void addSuffix(String suffix) {
57 | simpleName = simpleName + suffix;
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/compiler/TsModelTransformer.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.compiler;
3 |
4 | import cz.habarta.typescript.generator.emitter.TsBeanModel;
5 | import cz.habarta.typescript.generator.emitter.TsModel;
6 | import cz.habarta.typescript.generator.emitter.TsPropertyModel;
7 | import cz.habarta.typescript.generator.parser.BeanModel;
8 | import cz.habarta.typescript.generator.parser.Model;
9 | import cz.habarta.typescript.generator.parser.PropertyModel;
10 | import java.util.Objects;
11 |
12 |
13 | @FunctionalInterface
14 | public interface TsModelTransformer {
15 |
16 | public TsModel transformModel(Context context, TsModel model);
17 |
18 | public static class Context {
19 |
20 | private final SymbolTable symbolTable;
21 | private final Model model;
22 |
23 | public Context(SymbolTable symbolTable, Model model) {
24 | this.symbolTable = Objects.requireNonNull(symbolTable, "symbolTable");
25 | this.model = Objects.requireNonNull(model, "model");
26 | }
27 |
28 | public SymbolTable getSymbolTable() {
29 | return symbolTable;
30 | }
31 |
32 | public BeanModel getBeanModelOrigin(TsBeanModel tsBean) {
33 | final BeanModel bean = model.getBean(tsBean.getOrigin());
34 | return bean;
35 | }
36 |
37 | public PropertyModel getPropertyModelOrigin(TsBeanModel tsBean, TsPropertyModel tsProperty) {
38 | final BeanModel bean = getBeanModelOrigin(tsBean);
39 | if (bean == null) {
40 | return null;
41 | }
42 | final PropertyModel property = bean.getProperty(tsProperty.getName());
43 | return property;
44 | }
45 |
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/Emittable.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 |
6 |
7 | public interface Emittable {
8 |
9 | public String format(Settings settings);
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/EmitterExtension.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 |
6 |
7 | public abstract class EmitterExtension {
8 |
9 | public abstract EmitterExtensionFeatures getFeatures();
10 |
11 | public void emitElements(Writer writer, Settings settings, boolean exportKeyword, TsModel model) {
12 | }
13 |
14 | public static interface Writer {
15 | public void writeIndentedLine(String line);
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/EmitterExtensionFeatures.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import java.util.Map;
5 |
6 |
7 | public class EmitterExtensionFeatures {
8 |
9 | // declared abilities
10 | public boolean generatesRuntimeCode = false;
11 | public boolean generatesModuleCode = false;
12 | public boolean worksWithPackagesMappedToNamespaces = false;
13 | public boolean overridesStringEnums = false;
14 |
15 | // overridden settings
16 | public boolean generatesJaxrsApplicationClient = false;
17 | public String restResponseType = null;
18 | public String restOptionsType = null;
19 | public Map npmPackageDependencies = null;
20 | public Map npmDevDependencies = null;
21 | public Map npmPeerDependencies = null;
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/InfoJson.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import java.util.List;
5 |
6 |
7 | public class InfoJson {
8 |
9 | public List classes;
10 |
11 |
12 | public static class ClassInfo {
13 | public String javaClass;
14 | public String typeName;
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/InfoJsonEmitter.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import com.fasterxml.jackson.databind.ObjectMapper;
5 | import cz.habarta.typescript.generator.TypeScriptGenerator;
6 | import cz.habarta.typescript.generator.util.Utils;
7 | import java.io.IOException;
8 | import java.io.Writer;
9 | import java.util.ArrayList;
10 | import java.util.LinkedHashMap;
11 | import java.util.stream.Stream;
12 |
13 |
14 | public class InfoJsonEmitter {
15 |
16 | private Writer writer;
17 |
18 | public void emit(TsModel tsModel, Writer output, String outputName, boolean closeOutput) {
19 | this.writer = output;
20 | if (outputName != null) {
21 | TypeScriptGenerator.getLogger().info("Writing module info to: " + outputName);
22 | }
23 | emitTypeMappingJson(tsModel);
24 | if (closeOutput) {
25 | close();
26 | }
27 | }
28 |
29 | private void emitTypeMappingJson(TsModel tsModel) {
30 | try {
31 | final ObjectMapper objectMapper = Utils.getObjectMapper();
32 | final InfoJson infoJson = getInfoJson(tsModel);
33 | objectMapper.writeValue(writer, infoJson);
34 | } catch (IOException e) {
35 | throw new RuntimeException(e);
36 | }
37 | }
38 |
39 | private InfoJson getInfoJson(TsModel tsModel) {
40 | final LinkedHashMap map = new LinkedHashMap<>();
41 | Stream
42 | .of(
43 | tsModel.getBeans(),
44 | tsModel.getEnums(),
45 | tsModel.getTypeAliases()
46 | )
47 | .flatMap(s -> s.stream())
48 | .filter(declaration -> declaration.origin != null)
49 | .map(declaration -> {
50 | final InfoJson.ClassInfo typeMapping = new InfoJson.ClassInfo();
51 | typeMapping.javaClass = declaration.origin.getName();
52 | typeMapping.typeName = declaration.name.getFullName();
53 | return typeMapping;
54 | })
55 | .forEach(info -> {
56 | // remove duplicates, append new items to the end
57 | map.remove(info.javaClass);
58 | map.put(info.javaClass, info);
59 | });
60 |
61 | final InfoJson infoJson = new InfoJson();
62 | infoJson.classes = new ArrayList<>(map.values());
63 | return infoJson;
64 | }
65 |
66 | private void close() {
67 | try {
68 | writer.close();
69 | } catch (IOException e) {
70 | throw new RuntimeException(e);
71 | }
72 | }
73 |
74 | }
75 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/NpmPackageJson.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import java.util.Map;
5 |
6 |
7 | public class NpmPackageJson {
8 |
9 | public String name;
10 | public String version;
11 | public String types;
12 | public String main;
13 | public Map dependencies;
14 | public Map devDependencies;
15 | public Map peerDependencies;
16 | public Map scripts;
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/NpmPackageJsonEmitter.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import com.fasterxml.jackson.databind.ObjectMapper;
5 | import cz.habarta.typescript.generator.TypeScriptGenerator;
6 | import cz.habarta.typescript.generator.util.Utils;
7 | import java.io.IOException;
8 | import java.io.Writer;
9 |
10 |
11 | public class NpmPackageJsonEmitter {
12 |
13 | private Writer writer;
14 |
15 | public void emit(NpmPackageJson npmPackageJson, Writer output, String outputName, boolean closeOutput) {
16 | this.writer = output;
17 | if (outputName != null) {
18 | TypeScriptGenerator.getLogger().info("Writing NPM package to: " + outputName);
19 | }
20 | emitPackageJson(npmPackageJson);
21 | if (closeOutput) {
22 | close();
23 | }
24 | }
25 |
26 | private void emitPackageJson(NpmPackageJson npmPackageJson) {
27 | try {
28 | final ObjectMapper objectMapper = Utils.getObjectMapper();
29 | objectMapper.writeValue(writer, npmPackageJson);
30 | } catch (IOException e) {
31 | throw new RuntimeException(e);
32 | }
33 | }
34 |
35 | private void close() {
36 | try {
37 | writer.close();
38 | } catch (IOException e) {
39 | throw new RuntimeException(e);
40 | }
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsAccessibilityModifier.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 |
5 | public enum TsAccessibilityModifier {
6 |
7 | Public, Private, Protected;
8 |
9 | public String format() {
10 | return name().toLowerCase();
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsAliasModel.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.TsType;
5 | import cz.habarta.typescript.generator.compiler.Symbol;
6 | import java.util.Collections;
7 | import java.util.List;
8 |
9 |
10 | public class TsAliasModel extends TsDeclarationModel {
11 |
12 | private final List typeParameters;
13 | private final TsType definition;
14 |
15 | public TsAliasModel(Class> origin, Symbol name, List typeParameters, TsType definition, List comments) {
16 | super(origin, null, name, comments);
17 | this.typeParameters = typeParameters != null ? typeParameters : Collections.emptyList();
18 | this.definition = definition;
19 | }
20 |
21 | public List getTypeParameters() {
22 | return typeParameters;
23 | }
24 |
25 | public TsType getDefinition() {
26 | return definition;
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsArrowFunction.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 | import cz.habarta.typescript.generator.TsParameter;
6 | import java.util.List;
7 |
8 |
9 | public class TsArrowFunction extends TsExpression {
10 |
11 | private final List parameters;
12 |
13 | // ConciseBody = FunctionBody | Expression;
14 | private final TsExpression expression;
15 | // private final List body;
16 |
17 | public TsArrowFunction(List parameters, TsExpression expression) {
18 | this.parameters = parameters;
19 | this.expression = expression;
20 | }
21 |
22 | public List getParameters() {
23 | return parameters;
24 | }
25 |
26 | public TsExpression getExpression() {
27 | return expression;
28 | }
29 |
30 | @Override
31 | public String format(Settings settings) {
32 | return Emitter.formatParameterList(parameters) + " => " + expression.format(settings);
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsAssignmentExpression.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 | import java.util.Objects;
6 |
7 |
8 | public class TsAssignmentExpression extends TsExpression {
9 |
10 | private final TsExpression leftHandSideExpression;
11 | private final TsExpression assignmentExpression;
12 |
13 | public TsAssignmentExpression(TsExpression leftHandSideExpression, TsExpression assignmentExpression) {
14 | Objects.requireNonNull(leftHandSideExpression);
15 | Objects.requireNonNull(assignmentExpression);
16 | this.leftHandSideExpression = leftHandSideExpression;
17 | this.assignmentExpression = assignmentExpression;
18 | }
19 |
20 | public TsExpression getLeftHandSideExpression() {
21 | return leftHandSideExpression;
22 | }
23 |
24 | public TsExpression getAssignmentExpression() {
25 | return assignmentExpression;
26 | }
27 |
28 | @Override
29 | public String format(Settings settings) {
30 | return leftHandSideExpression.format(settings) + " = " + assignmentExpression.format(settings);
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsBeanCategory.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 |
5 | public enum TsBeanCategory {
6 |
7 | // order of these constants determines order of emitted declarations
8 | ServicePrerequisite,
9 | Service,
10 | Data,
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsBinaryExpression.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 |
6 |
7 | public class TsBinaryExpression extends TsExpression {
8 |
9 | private final TsExpression left;
10 | private final TsBinaryOperator operator;
11 | private final TsExpression right;
12 |
13 | public TsBinaryExpression(TsExpression left, TsBinaryOperator operator, TsExpression right) {
14 | this.left = left;
15 | this.operator = operator;
16 | this.right = right;
17 | }
18 |
19 | public TsExpression getLeft() {
20 | return left;
21 | }
22 |
23 | public TsBinaryOperator getOperator() {
24 | return operator;
25 | }
26 |
27 | public TsExpression getRight() {
28 | return right;
29 | }
30 |
31 | @Override
32 | public String format(Settings settings) {
33 | return left.format(settings) + " " + operator.format(settings) + " " + right.format(settings);
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsBinaryOperator.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 |
6 |
7 | public enum TsBinaryOperator implements Emittable {
8 |
9 | BarBar("||");
10 |
11 | private final String formatted;
12 |
13 | private TsBinaryOperator(String formatted) {
14 | this.formatted = formatted;
15 | }
16 |
17 | @Override
18 | public String format(Settings settings) {
19 | return formatted;
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsBooleanLiteral.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 |
6 |
7 | public class TsBooleanLiteral extends TsExpression {
8 |
9 | private final boolean literal;
10 |
11 | public TsBooleanLiteral(boolean literal) {
12 | this.literal = literal;
13 | }
14 |
15 | public boolean getLiteral() {
16 | return literal;
17 | }
18 |
19 | @Override
20 | public String format(Settings settings) {
21 | return String.valueOf(literal);
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsCallExpression.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 | import cz.habarta.typescript.generator.TsType;
6 | import java.util.Arrays;
7 | import java.util.Collections;
8 | import java.util.List;
9 |
10 |
11 | public class TsCallExpression extends TsExpression {
12 |
13 | private final TsExpression expression;
14 | private final List typeArguments;
15 | private final List arguments;
16 |
17 | public TsCallExpression(TsExpression expression, TsExpression... arguments) {
18 | this(expression, null, Arrays.asList(arguments));
19 | }
20 |
21 | public TsCallExpression(TsExpression expression, List typeArguments, List arguments) {
22 | this.expression = expression;
23 | this.typeArguments = typeArguments != null ? typeArguments : Collections.emptyList();
24 | this.arguments = arguments;
25 | }
26 |
27 | public TsExpression getExpression() {
28 | return expression;
29 | }
30 |
31 | public List getTypeArguments() {
32 | return typeArguments;
33 | }
34 |
35 | public List getArguments() {
36 | return arguments;
37 | }
38 |
39 | @Override
40 | public String format(Settings settings) {
41 | final String typeArgumentsString = typeArguments.isEmpty() ? "" : "<" + Emitter.formatList(settings, typeArguments) + ">";
42 | return expression.format(settings) + typeArgumentsString + "(" + Emitter.formatList(settings, arguments) + ")";
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsCallableModel.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.TsType;
5 | import java.util.Collections;
6 | import java.util.List;
7 |
8 |
9 | public class TsCallableModel {
10 |
11 | protected final String name;
12 | protected final TsModifierFlags modifiers;
13 | protected final List typeParameters;
14 | protected final List parameters;
15 | protected final TsType returnType;
16 | protected final List body;
17 | protected final List comments;
18 |
19 | public TsCallableModel(String name, TsModifierFlags modifiers, List typeParameters,
20 | List parameters, TsType returnType, List body, List comments) {
21 | this.name = name;
22 | this.modifiers = modifiers != null ? modifiers : TsModifierFlags.None;
23 | this.typeParameters = typeParameters != null ? typeParameters : Collections.emptyList();
24 | this.parameters = parameters;
25 | this.returnType = returnType;
26 | this.body = body;
27 | this.comments = comments;
28 | }
29 |
30 | public String getName() {
31 | return name;
32 | }
33 |
34 | public TsModifierFlags getModifiers() {
35 | return modifiers;
36 | }
37 |
38 | public List getTypeParameters() {
39 | return typeParameters;
40 | }
41 |
42 | public List getParameters() {
43 | return parameters;
44 | }
45 |
46 | public TsType getReturnType() {
47 | return returnType;
48 | }
49 |
50 | public List getBody() {
51 | return body;
52 | }
53 |
54 | public List getComments() {
55 | return comments;
56 | }
57 |
58 | }
59 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsConstructorModel.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import java.util.List;
5 |
6 |
7 | public class TsConstructorModel extends TsCallableModel {
8 |
9 | public TsConstructorModel(TsModifierFlags modifiers, List parameters, List body, List comments) {
10 | super("constructor", modifiers, null, parameters, null, body, comments);
11 | }
12 |
13 | public TsConstructorModel withParameters(List parameters) {
14 | return new TsConstructorModel(modifiers, parameters, body, comments);
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsDeclarationModel.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.compiler.Symbol;
5 | import java.util.List;
6 | import java.util.Objects;
7 |
8 |
9 | public class TsDeclarationModel implements Comparable {
10 |
11 | protected final Class> origin;
12 | protected final TsBeanCategory category;
13 | protected final Symbol name;
14 | protected final List comments;
15 |
16 | public TsDeclarationModel(Class> origin, TsBeanCategory category, Symbol name, List comments) {
17 | this.origin = origin;
18 | this.category = category;
19 | this.name = Objects.requireNonNull(name);
20 | this.comments = comments;
21 | }
22 |
23 | public Class> getOrigin() {
24 | return origin;
25 | }
26 |
27 | public TsBeanCategory getCategory() {
28 | return category;
29 | }
30 |
31 | public Symbol getName() {
32 | return name;
33 | }
34 |
35 | public List getComments() {
36 | return comments;
37 | }
38 |
39 | @Override
40 | public int compareTo(TsDeclarationModel o) {
41 | final int categoryResult = compare(this.category, o.category);
42 | if (categoryResult != 0) {
43 | return categoryResult;
44 | }
45 | final int nameResult = compare(this.name.getFullName(), o.name.getFullName());
46 | if (nameResult != 0) {
47 | return nameResult;
48 | }
49 | return 0;
50 | }
51 |
52 | /**
53 | * Natural order with null last.
54 | */
55 | private static > int compare(T o1, T o2) {
56 | if (o1 != null) {
57 | return o2 != null ? o1.compareTo(o2) : -1;
58 | } else {
59 | return o2 != null ? 1 : 0;
60 | }
61 | }
62 |
63 | @Override
64 | public String toString() {
65 | return String.format("Declaration `%s`", name);
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsDecorator.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import java.util.List;
5 | import java.util.Objects;
6 |
7 |
8 | public class TsDecorator {
9 |
10 | private final TsIdentifierReference identifierReference;
11 | private final List arguments;
12 |
13 | public TsDecorator(TsIdentifierReference identifierReference, List arguments) {
14 | this.identifierReference = Objects.requireNonNull(identifierReference);
15 | this.arguments = arguments;
16 | }
17 |
18 | public TsIdentifierReference getIdentifierReference() {
19 | return identifierReference;
20 | }
21 |
22 | public List getArguments() {
23 | return arguments;
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsEnumModel.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.compiler.EnumKind;
5 | import cz.habarta.typescript.generator.compiler.EnumMemberModel;
6 | import cz.habarta.typescript.generator.compiler.Symbol;
7 | import cz.habarta.typescript.generator.parser.EnumModel;
8 | import java.util.List;
9 | import java.util.Objects;
10 |
11 |
12 | public class TsEnumModel extends TsDeclarationModel {
13 |
14 | private final EnumKind kind;
15 | private final List members;
16 | private final boolean isNonConstEnum;
17 |
18 | public TsEnumModel(Class> origin, Symbol name, EnumKind kind, List members, List comments, boolean isNonConstEnum) {
19 | super(origin, null, name, comments);
20 | this.kind = Objects.requireNonNull(kind);
21 | this.members = Objects.requireNonNull(members);
22 | this.isNonConstEnum = isNonConstEnum;
23 | }
24 |
25 | public static TsEnumModel fromEnumModel(Symbol name, EnumModel enumModel, boolean isNonConstEnum) {
26 | return new TsEnumModel(enumModel.getOrigin(), name, enumModel.getKind(), enumModel.getMembers(), enumModel.getComments(), isNonConstEnum);
27 | }
28 |
29 | public EnumKind getKind() {
30 | return kind;
31 | }
32 |
33 | public List getMembers() {
34 | return members;
35 | }
36 |
37 | public boolean isNonConstEnum() {
38 | return isNonConstEnum;
39 | }
40 |
41 | public TsEnumModel withMembers(List members) {
42 | return new TsEnumModel(origin, name, kind, members, comments, isNonConstEnum);
43 | }
44 |
45 | public TsEnumModel withComments(List comments) {
46 | return new TsEnumModel(origin, name, kind, members, comments, isNonConstEnum);
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsExpression.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 |
6 |
7 | public abstract class TsExpression implements Emittable {
8 |
9 | @Override
10 | public abstract String format(Settings settings);
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsExpressionStatement.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import java.util.Objects;
5 |
6 |
7 | public class TsExpressionStatement extends TsStatement {
8 |
9 | private final TsExpression expression;
10 |
11 | public TsExpressionStatement(TsExpression expression) {
12 | Objects.requireNonNull(expression);
13 | this.expression = expression;
14 | }
15 |
16 | public TsExpression getExpression() {
17 | return expression;
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsHelper.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.util.Utils;
5 | import java.util.List;
6 |
7 |
8 | public class TsHelper {
9 |
10 | private final List lines;
11 |
12 | public TsHelper(List lines) {
13 | this.lines = lines;
14 | }
15 |
16 | public static TsHelper loadFromResource(String resourceName) {
17 | return new TsHelper(Utils.readLines(TsHelper.class.getResourceAsStream(resourceName)));
18 | }
19 |
20 | public List getLines() {
21 | return lines;
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsIdentifierReference.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 |
6 |
7 | public class TsIdentifierReference extends TsExpression {
8 |
9 | public static final TsIdentifierReference Undefined = new TsIdentifierReference("undefined");
10 |
11 | private final String identifier;
12 |
13 | public TsIdentifierReference(String identifier) {
14 | this.identifier = identifier;
15 | }
16 |
17 | public String getIdentifier() {
18 | return identifier;
19 | }
20 |
21 | @Override
22 | public String format(Settings settings) {
23 | return identifier;
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsIfStatement.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import java.util.List;
5 | import java.util.Objects;
6 |
7 |
8 | public class TsIfStatement extends TsStatement {
9 |
10 | private final TsExpression expression;
11 | private final List thenStatements;
12 | private final List elseStatements;
13 |
14 | public TsIfStatement(TsExpression expression, List thenStatements) {
15 | this(expression, thenStatements, null);
16 | }
17 |
18 | public TsIfStatement(TsExpression expression, List thenStatements, List elseStatements) {
19 | Objects.requireNonNull(expression);
20 | Objects.requireNonNull(thenStatements);
21 | this.expression = expression;
22 | this.thenStatements = thenStatements;
23 | this.elseStatements = elseStatements;
24 | }
25 |
26 | public TsExpression getExpression() {
27 | return expression;
28 | }
29 |
30 | public List getThenStatements() {
31 | return thenStatements;
32 | }
33 |
34 | public List getElseStatements() {
35 | return elseStatements;
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsMemberExpression.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 | import cz.habarta.typescript.generator.compiler.ModelCompiler;
6 |
7 |
8 | public class TsMemberExpression extends TsExpression {
9 |
10 | private final TsExpression expression;
11 | private final String identifierName;
12 |
13 | public TsMemberExpression(TsExpression expression, String identifierName) {
14 | this.expression = expression;
15 | this.identifierName = identifierName;
16 | }
17 |
18 | public TsExpression getExpression() {
19 | return expression;
20 | }
21 |
22 | public String getIdentifierName() {
23 | return identifierName;
24 | }
25 |
26 | @Override
27 | public String format(Settings settings) {
28 | if (ModelCompiler.isValidIdentifierName(identifierName)) {
29 | return expression.format(settings) + "." + identifierName;
30 | } else {
31 | return expression.format(settings) + "[" + Emitter.quote(identifierName, settings) + "]";
32 | }
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsMethodModel.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.TsType;
5 | import cz.habarta.typescript.generator.util.Utils;
6 | import java.util.List;
7 |
8 |
9 | public class TsMethodModel extends TsCallableModel {
10 |
11 | protected final List decorators;
12 |
13 | public TsMethodModel(String name, TsModifierFlags modifiers, List typeParameters, List parameters, TsType returnType, List body, List comments) {
14 | this(name, null, modifiers, typeParameters, parameters, returnType, body, comments);
15 | }
16 |
17 | private TsMethodModel(String name, List decorators, TsModifierFlags modifiers, List typeParameters, List parameters, TsType returnType, List body, List comments) {
18 | super(name, modifiers, typeParameters, parameters, returnType, body, comments);
19 | this.decorators = Utils.listFromNullable(decorators);
20 | }
21 |
22 | public List getDecorators() {
23 | return decorators;
24 | }
25 |
26 | public TsMethodModel withDecorators(List decorators) {
27 | return new TsMethodModel(name, decorators, modifiers, typeParameters, parameters, returnType, body, comments);
28 | }
29 |
30 | public TsMethodModel withParameters(List parameters) {
31 | return new TsMethodModel(name, decorators, modifiers, typeParameters, parameters, returnType, body, comments);
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsModifierFlags.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 |
5 | public class TsModifierFlags {
6 |
7 | public static final TsModifierFlags None = new TsModifierFlags(false, false);
8 |
9 | public final boolean isStatic;
10 | public final boolean isReadonly;
11 |
12 | private TsModifierFlags(boolean isStatic, boolean isReadonly) {
13 | this.isStatic = isStatic;
14 | this.isReadonly = isReadonly;
15 | }
16 |
17 | public TsModifierFlags setStatic() {
18 | return new TsModifierFlags(true, isReadonly);
19 | }
20 |
21 | public TsModifierFlags setStatic(boolean isStatic) {
22 | return new TsModifierFlags(isStatic, isReadonly);
23 | }
24 |
25 | public TsModifierFlags setReadonly() {
26 | return new TsModifierFlags(isStatic, true);
27 | }
28 |
29 | public TsModifierFlags setReadonly(boolean isReadonly) {
30 | return new TsModifierFlags(isStatic, isReadonly);
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsNewExpression.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 | import cz.habarta.typescript.generator.TsType;
6 | import java.util.ArrayList;
7 | import java.util.Collections;
8 | import java.util.List;
9 |
10 |
11 | public class TsNewExpression extends TsExpression {
12 |
13 | private final TsExpression expression;
14 | private final List typeArguments;
15 | private final List arguments;
16 |
17 | public TsNewExpression(TsExpression expression, List extends TsExpression> arguments) {
18 | this(expression, null, arguments);
19 | }
20 |
21 | public TsNewExpression(TsExpression expression, List extends TsType> typeArguments, List extends TsExpression> arguments) {
22 | this.expression = expression;
23 | this.typeArguments = typeArguments != null ? new ArrayList(typeArguments) : Collections.emptyList();
24 | this.arguments = arguments != null ? new ArrayList(arguments) : Collections.emptyList();
25 | }
26 |
27 | public TsExpression getExpression() {
28 | return expression;
29 | }
30 |
31 | public List getTypeArguments() {
32 | return typeArguments;
33 | }
34 |
35 | public List getArguments() {
36 | return arguments;
37 | }
38 |
39 | @Override
40 | public String format(Settings settings) {
41 | return "new "
42 | + expression.format(settings)
43 | + (typeArguments.isEmpty() ? "" : "<" + Emitter.formatList(settings, typeArguments) + ">")
44 | + "(" + Emitter.formatList(settings, arguments)
45 | + ")";
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsNumberLiteral.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 |
6 |
7 | public class TsNumberLiteral extends TsExpression {
8 |
9 | private final Number literal;
10 |
11 | public TsNumberLiteral(Number literal) {
12 | this.literal = literal;
13 | }
14 |
15 | public Number getLiteral() {
16 | return literal;
17 | }
18 |
19 | @Override
20 | public String format(Settings settings) {
21 | return literal.toString();
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsObjectLiteral.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 | import cz.habarta.typescript.generator.util.Utils;
6 | import java.util.ArrayList;
7 | import java.util.Arrays;
8 | import java.util.List;
9 |
10 |
11 | public class TsObjectLiteral extends TsExpression {
12 |
13 | private final List propertyDefinitions;
14 |
15 | public TsObjectLiteral(TsPropertyDefinition... propertyDefinitions) {
16 | this(Utils.removeNulls(Arrays.asList(propertyDefinitions)));
17 | }
18 |
19 | public TsObjectLiteral(List propertyDefinitions) {
20 | this.propertyDefinitions = propertyDefinitions;
21 | }
22 |
23 | public List getPropertyDefinitions() {
24 | return propertyDefinitions;
25 | }
26 |
27 | @Override
28 | public String format(Settings settings) {
29 | final List props = new ArrayList<>();
30 | for (TsPropertyDefinition property : propertyDefinitions) {
31 | props.add(property.format(settings));
32 | }
33 | if (props.isEmpty()) {
34 | return "{}";
35 | } else {
36 | return "{ " + String.join(", ", props) + " }";
37 | }
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsParameterModel.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.TsParameter;
5 | import cz.habarta.typescript.generator.TsType;
6 | import cz.habarta.typescript.generator.util.Utils;
7 | import java.util.List;
8 |
9 |
10 | public class TsParameterModel extends TsParameter {
11 |
12 | protected final List decorators;
13 | private final TsAccessibilityModifier accessibilityModifier;
14 |
15 | public TsParameterModel(String name, TsType tsType) {
16 | this(null, name, tsType);
17 | }
18 |
19 | public TsParameterModel(TsAccessibilityModifier accessibilityModifier, String name, TsType tsType) {
20 | this(null, accessibilityModifier, name, tsType);
21 | }
22 |
23 | private TsParameterModel(List decorators, TsAccessibilityModifier accessibilityModifier, String name, TsType tsType) {
24 | super(name, tsType);
25 | this.decorators = Utils.listFromNullable(decorators);
26 | this.accessibilityModifier = accessibilityModifier;
27 | }
28 |
29 | public List getDecorators() {
30 | return decorators;
31 | }
32 |
33 | public TsAccessibilityModifier getAccessibilityModifier() {
34 | return accessibilityModifier;
35 | }
36 |
37 | public TsParameterModel withTsType(TsType tsType) {
38 | return new TsParameterModel(decorators, accessibilityModifier, name, tsType);
39 | }
40 |
41 | public TsParameterModel withDecorators(List decorators) {
42 | return new TsParameterModel(decorators, accessibilityModifier, name, tsType);
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsPrefixUnaryExpression.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 |
6 |
7 | public class TsPrefixUnaryExpression extends TsExpression {
8 |
9 | private final TsUnaryOperator operator;
10 | private final TsExpression operand;
11 |
12 | public TsPrefixUnaryExpression(TsUnaryOperator operator, TsExpression operand) {
13 | this.operator = operator;
14 | this.operand = operand;
15 | }
16 |
17 | public TsUnaryOperator getOperator() {
18 | return operator;
19 | }
20 |
21 | public TsExpression getOperand() {
22 | return operand;
23 | }
24 |
25 | @Override
26 | public String format(Settings settings) {
27 | return operator.format(settings) + operand.format(settings);
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsPropertyDefinition.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 |
6 |
7 | public class TsPropertyDefinition {
8 |
9 | private final String propertyName;
10 | private final TsExpression expression;
11 |
12 | public TsPropertyDefinition(String propertyName, TsExpression expression) {
13 | this.propertyName = propertyName;
14 | this.expression = expression;
15 | }
16 |
17 | public String getPropertyName() {
18 | return propertyName;
19 | }
20 |
21 | public TsExpression getExpression() {
22 | return expression;
23 | }
24 |
25 | public String format(Settings settings) {
26 | return Emitter.quoteIfNeeded(propertyName, settings) + ": " + expression.format(settings);
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsPropertyModel.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.TsProperty;
5 | import cz.habarta.typescript.generator.TsType;
6 | import cz.habarta.typescript.generator.util.Utils;
7 | import java.util.List;
8 |
9 |
10 | public class TsPropertyModel extends TsProperty implements Comparable {
11 |
12 | public final List decorators;
13 | public final TsModifierFlags modifiers;
14 | public final boolean ownProperty; // property exists directly on the bean, should not be inherited
15 | public final TsExpression defaultValue;
16 | public final List comments;
17 |
18 | public TsPropertyModel(String name, TsType tsType, TsModifierFlags modifiers, boolean ownProperty, List comments) {
19 | this(name, tsType, /*decorators*/ null, modifiers, ownProperty, /*defaultValue*/ null, comments);
20 | }
21 |
22 | public TsPropertyModel(String name, TsType tsType, List decorators, TsModifierFlags modifiers, boolean ownProperty, TsExpression defaultValue, List comments) {
23 | super(name, tsType);
24 | this.decorators = Utils.listFromNullable(decorators);
25 | this.modifiers = modifiers != null ? modifiers : TsModifierFlags.None;
26 | this.comments = comments;
27 | this.defaultValue = defaultValue;
28 | this.ownProperty = ownProperty;
29 | }
30 |
31 | public List getDecorators() {
32 | return decorators;
33 | }
34 |
35 | public TsPropertyModel withDecorators(List decorators) {
36 | return new TsPropertyModel(getName(), tsType, decorators, modifiers, ownProperty, defaultValue, getComments());
37 | }
38 |
39 | public TsModifierFlags getModifiers() {
40 | return modifiers;
41 | }
42 |
43 | public boolean isOwnProperty() {
44 | return ownProperty;
45 | }
46 |
47 | public TsExpression getDefaultValue() {
48 | return defaultValue;
49 | }
50 |
51 | public TsPropertyModel withDefaultValue(TsExpression defaultValue) {
52 | return new TsPropertyModel(name, tsType, decorators, modifiers, ownProperty, defaultValue, comments);
53 | }
54 |
55 | public List getComments() {
56 | return comments;
57 | }
58 |
59 | public TsPropertyModel withTsType(TsType tsType) {
60 | return new TsPropertyModel(name, tsType, decorators, modifiers, ownProperty, defaultValue, comments);
61 | }
62 |
63 | @Override
64 | public int compareTo(TsProperty o) {
65 | return name.compareTo(o.getName());
66 | }
67 |
68 | @Override
69 | public String toString() {
70 | return "TsPropertyModel{" + "name=" + name + ", tsType=" + tsType + '}';
71 | }
72 |
73 | }
74 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsReturnStatement.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 |
5 | public class TsReturnStatement extends TsStatement {
6 |
7 | private final TsExpression expression;
8 |
9 | public TsReturnStatement() {
10 | this(null);
11 | }
12 |
13 | public TsReturnStatement(TsExpression expression) {
14 | this.expression = expression;
15 | }
16 |
17 | public TsExpression getExpression() {
18 | return expression;
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsStatement.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 |
5 | public abstract class TsStatement {
6 | }
7 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsStringLiteral.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 |
6 |
7 | public class TsStringLiteral extends TsExpression {
8 |
9 | private final String literal;
10 |
11 | public TsStringLiteral(String literal) {
12 | this.literal = literal;
13 | }
14 |
15 | public String getLiteral() {
16 | return literal;
17 | }
18 |
19 | @Override
20 | public String format(Settings settings) {
21 | return Emitter.quote(literal, settings);
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsSuperExpression.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 |
6 |
7 | public class TsSuperExpression extends TsExpression {
8 |
9 | @Override
10 | public String format(Settings settings) {
11 | return "super";
12 | }
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsSwitchCaseClause.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import java.util.List;
5 |
6 |
7 | public class TsSwitchCaseClause extends TsStatement {
8 |
9 | private final TsExpression expression;
10 | private final List statements;
11 |
12 | public TsSwitchCaseClause(TsExpression expression, List statements) {
13 | this.expression = expression;
14 | this.statements = statements;
15 | }
16 |
17 | public TsExpression getExpression() {
18 | return expression;
19 | }
20 |
21 | public List getStatements() {
22 | return statements;
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsSwitchStatement.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.util.Utils;
5 | import java.util.List;
6 |
7 |
8 | public class TsSwitchStatement extends TsStatement {
9 |
10 | private final TsExpression expression;
11 | private final List caseClauses;
12 | private final List defaultClause;
13 |
14 | public TsSwitchStatement(TsExpression expression, List caseClauses, List defaultClause) {
15 | this.expression = expression;
16 | this.caseClauses = Utils.listFromNullable(caseClauses);
17 | this.defaultClause = defaultClause;
18 | }
19 |
20 | public TsExpression getExpression() {
21 | return expression;
22 | }
23 |
24 | public List getCaseClauses() {
25 | return caseClauses;
26 | }
27 |
28 | public List getDefaultClause() {
29 | return defaultClause;
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsTaggedTemplateLiteral.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 | import java.util.List;
6 |
7 |
8 | public class TsTaggedTemplateLiteral extends TsTemplateLiteral {
9 |
10 | private final TsExpression tagFunction;
11 |
12 | public TsTaggedTemplateLiteral(TsExpression tagFunction, List spans) {
13 | super(spans);
14 | this.tagFunction = tagFunction;
15 | }
16 |
17 | public TsExpression getTagFunction() {
18 | return tagFunction;
19 | }
20 |
21 | @Override
22 | public String format(Settings settings) {
23 | return tagFunction.format(settings) + super.format(settings);
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsTemplateLiteral.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 | import java.util.List;
6 |
7 |
8 | public class TsTemplateLiteral extends TsExpression {
9 |
10 | private final List spans;
11 |
12 | public TsTemplateLiteral(List spans) {
13 | this.spans = spans;
14 | }
15 |
16 | public List getSpans() {
17 | return spans;
18 | }
19 |
20 | @Override
21 | public String format(Settings settings) {
22 | final StringBuilder sb = new StringBuilder();
23 | sb.append("`");
24 | for (TsExpression span : spans) {
25 | if (span instanceof TsStringLiteral) {
26 | final TsStringLiteral literal = (TsStringLiteral) span;
27 | sb.append(literal.getLiteral());
28 | } else {
29 | sb.append("${");
30 | sb.append(span.format(settings));
31 | sb.append("}");
32 | }
33 | }
34 | sb.append("`");
35 | return sb.toString();
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsThisExpression.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 |
6 |
7 | public class TsThisExpression extends TsExpression {
8 |
9 | @Override
10 | public String format(Settings settings) {
11 | return "this";
12 | }
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsTypeReferenceExpression.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 | import cz.habarta.typescript.generator.TsType;
6 |
7 |
8 | public class TsTypeReferenceExpression extends TsExpression {
9 |
10 | private final TsType.ReferenceType type;
11 |
12 | public TsTypeReferenceExpression(TsType.ReferenceType type) {
13 | this.type = type;
14 | }
15 |
16 | public TsType.ReferenceType getType() {
17 | return type;
18 | }
19 |
20 | @Override
21 | public String format(Settings settings) {
22 | return type.format(settings);
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsUnaryOperator.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 |
6 |
7 | public enum TsUnaryOperator implements Emittable {
8 |
9 | Exclamation("!");
10 |
11 | private final String formatted;
12 |
13 | private TsUnaryOperator(String formatted) {
14 | this.formatted = formatted;
15 | }
16 |
17 | @Override
18 | public String format(Settings settings) {
19 | return formatted;
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/emitter/TsVariableDeclarationStatement.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.emitter;
3 |
4 | import cz.habarta.typescript.generator.TsType;
5 | import java.util.Objects;
6 |
7 |
8 | public class TsVariableDeclarationStatement extends TsStatement {
9 |
10 | private final boolean isConst;
11 | private final String name;
12 | private final TsType type;
13 | private final TsExpression initializer;
14 |
15 | public TsVariableDeclarationStatement(boolean isConst, String name, TsType type, TsExpression initializer) {
16 | Objects.requireNonNull(name);
17 | this.isConst = isConst;
18 | this.name = name;
19 | this.type = type;
20 | this.initializer = initializer;
21 | }
22 |
23 | public boolean isConst() {
24 | return isConst;
25 | }
26 |
27 | public String getName() {
28 | return name;
29 | }
30 |
31 | public TsType getType() {
32 | return type;
33 | }
34 |
35 | public TsExpression getInitializer() {
36 | return initializer;
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/parser/DeclarationModel.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.parser;
3 |
4 | import java.util.List;
5 |
6 |
7 | public abstract class DeclarationModel {
8 |
9 | protected final Class> origin;
10 | protected final List comments;
11 |
12 | public DeclarationModel(Class> origin, List comments) {
13 | this.origin = origin;
14 | this.comments = comments;
15 | }
16 |
17 | public Class> getOrigin() {
18 | return origin;
19 | }
20 |
21 | public List getComments() {
22 | return comments;
23 | }
24 |
25 | public abstract DeclarationModel withComments(List comments);
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/parser/EnumModel.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.parser;
3 |
4 | import cz.habarta.typescript.generator.compiler.EnumKind;
5 | import cz.habarta.typescript.generator.compiler.EnumMemberModel;
6 | import java.util.List;
7 |
8 |
9 | public class EnumModel extends DeclarationModel {
10 |
11 | private final EnumKind kind;
12 | private final List members;
13 |
14 | public EnumModel(Class> origin, EnumKind kind, List members, List comments) {
15 | super (origin, comments);
16 | this.kind = kind;
17 | this.members = members;
18 | }
19 |
20 | public EnumKind getKind() {
21 | return kind;
22 | }
23 |
24 | public List getMembers() {
25 | return members;
26 | }
27 |
28 | public EnumModel withMembers(List members) {
29 | return new EnumModel(origin, kind, members, comments);
30 | }
31 |
32 | @Override
33 | public EnumModel withComments(List comments) {
34 | return new EnumModel(origin, kind, members, comments);
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/parser/MethodModel.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.parser;
3 |
4 | import java.lang.reflect.Method;
5 | import java.lang.reflect.Type;
6 | import java.util.Collections;
7 | import java.util.List;
8 |
9 |
10 | public class MethodModel {
11 |
12 | protected final Class> originClass;
13 | protected final String name;
14 | protected final List parameters;
15 | protected final Type returnType;
16 | protected final Method originalMethod;
17 | protected final List comments;
18 |
19 | public MethodModel(Class> originClass, String name, List parameters, Type returnType, Method originalMethod, List comments) {
20 | this.originClass = originClass;
21 | this.name = name;
22 | this.parameters = parameters != null ? parameters : Collections.emptyList();
23 | this.returnType = returnType;
24 | this.originalMethod = originalMethod;
25 | this.comments = comments;
26 | }
27 |
28 | public Class> getOriginClass() {
29 | return originClass;
30 | }
31 |
32 | public String getName() {
33 | return name;
34 | }
35 |
36 | public List getParameters() {
37 | return parameters;
38 | }
39 |
40 | public Type getReturnType() {
41 | return returnType;
42 | }
43 |
44 | public Method getOriginalMethod() {
45 | return originalMethod;
46 | }
47 |
48 | public List getComments() {
49 | return comments;
50 | }
51 |
52 | public MethodModel withComments(List comments) {
53 | return new MethodModel(originClass, name, parameters, returnType, originalMethod, comments);
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/parser/MethodParameterModel.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.parser;
3 |
4 | import java.lang.reflect.Type;
5 |
6 |
7 | public class MethodParameterModel {
8 |
9 | private final String name;
10 | private final Type type;
11 |
12 | public MethodParameterModel(String name, Type type) {
13 | this.name = name;
14 | this.type = type;
15 | }
16 |
17 | public String getName() {
18 | return name;
19 | }
20 |
21 | public Type getType() {
22 | return type;
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/parser/Model.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.parser;
3 |
4 | import java.util.List;
5 | import java.util.Objects;
6 |
7 |
8 | public class Model {
9 |
10 | private final List beans;
11 | private final List enums;
12 | private final List restApplications;
13 |
14 | public Model(List beans, List enums, List restApplications) {
15 | this.beans = Objects.requireNonNull(beans);
16 | this.enums = Objects.requireNonNull(enums);
17 | this.restApplications = restApplications;
18 | }
19 |
20 | public List getBeans() {
21 | return beans;
22 | }
23 |
24 | public BeanModel getBean(Class> beanClass) {
25 | for (BeanModel bean : beans) {
26 | if (bean.getOrigin().equals(beanClass)) {
27 | return bean;
28 | }
29 | }
30 | return null;
31 | }
32 |
33 | public List getEnums() {
34 | return enums;
35 | }
36 |
37 | public List getRestApplications() {
38 | return restApplications;
39 | }
40 |
41 | @Override
42 | public String toString() {
43 | final StringBuilder sb = new StringBuilder();
44 | sb.append("Model{");
45 | sb.append(String.format("%n"));
46 | for (BeanModel bean : beans) {
47 | sb.append(" ");
48 | sb.append(bean);
49 | sb.append(String.format("%n"));
50 | }
51 | for (EnumModel enumModel : enums) {
52 | sb.append(" ");
53 | sb.append(enumModel);
54 | sb.append(String.format("%n"));
55 | }
56 | sb.append('}');
57 | return sb.toString();
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/parser/PropertyAccess.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.parser;
3 |
4 |
5 | public enum PropertyAccess {
6 |
7 | ReadOnly,
8 | WriteOnly,
9 | ReadWrite,
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/parser/RestApplicationModel.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.parser;
3 |
4 | import java.util.ArrayList;
5 | import java.util.List;
6 | import java.util.Objects;
7 |
8 |
9 | public class RestApplicationModel {
10 |
11 | private final RestApplicationType type;
12 | private String applicationPath;
13 | private String applicationName;
14 | private final List methods;
15 |
16 | public RestApplicationModel(RestApplicationType type) {
17 | this.type = type;
18 | this.methods = new ArrayList<>();
19 | }
20 |
21 | public RestApplicationModel(RestApplicationType type, String applicationPath, String applicationName, List methods) {
22 | this.type = Objects.requireNonNull(type);
23 | this.applicationPath = applicationPath;
24 | this.applicationName = applicationName;
25 | this.methods = Objects.requireNonNull(methods);
26 | }
27 |
28 | public RestApplicationType getType() {
29 | return type;
30 | }
31 |
32 | public String getApplicationPath() {
33 | return applicationPath;
34 | }
35 |
36 | public void setApplicationPath(String applicationPath) {
37 | this.applicationPath = applicationPath;
38 | }
39 |
40 | public String getApplicationName() {
41 | return applicationName;
42 | }
43 |
44 | public void setApplicationName(String applicationName) {
45 | this.applicationName = applicationName;
46 | }
47 |
48 | public List getMethods() {
49 | return methods;
50 | }
51 |
52 | public RestApplicationModel withMethods(List methods) {
53 | return new RestApplicationModel(type, applicationPath, applicationName, methods);
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/parser/RestApplicationType.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.parser;
3 |
4 | import cz.habarta.typescript.generator.Settings;
5 | import java.util.function.Function;
6 |
7 |
8 | public enum RestApplicationType {
9 |
10 | Jaxrs(settings -> settings.generateJaxrsApplicationInterface, settings -> settings.generateJaxrsApplicationClient),
11 | Spring(settings -> settings.generateSpringApplicationInterface, settings -> settings.generateSpringApplicationClient);
12 |
13 | private RestApplicationType(Function generateInterface, Function generateClient) {
14 | this.generateInterface = generateInterface;
15 | this.generateClient = generateClient;
16 | }
17 |
18 | public final Function generateInterface;
19 | public final Function generateClient;
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/parser/RestMethodModel.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.parser;
3 |
4 | import java.lang.reflect.Method;
5 | import java.lang.reflect.Type;
6 | import java.util.List;
7 |
8 |
9 | public class RestMethodModel extends MethodModel {
10 |
11 | private final Class> rootResource;
12 | private final String httpMethod;
13 | private final String path;
14 | private final List pathParams;
15 | private final List queryParams;
16 | private final MethodParameterModel entityParam;
17 |
18 | public RestMethodModel(Class> originClass, String name, Type returnType, Method originalMethod,
19 | Class> rootResource, String httpMethod, String path, List pathParams, List queryParams, MethodParameterModel entityParam,
20 | List comments) {
21 | super(originClass, name, null, returnType, originalMethod, comments);
22 | this.rootResource = rootResource;
23 | this.httpMethod = httpMethod;
24 | this.path = path;
25 | this.pathParams = pathParams;
26 | this.queryParams = queryParams;
27 | this.entityParam = entityParam;
28 | }
29 |
30 | public Class> getRootResource() {
31 | return rootResource;
32 | }
33 |
34 | public String getHttpMethod() {
35 | return httpMethod;
36 | }
37 |
38 | public String getPath() {
39 | return path;
40 | }
41 |
42 | public List getPathParams() {
43 | return pathParams;
44 | }
45 |
46 | public List getQueryParams() {
47 | return queryParams;
48 | }
49 |
50 | public MethodParameterModel getEntityParam() {
51 | return entityParam;
52 | }
53 |
54 | @Override
55 | public RestMethodModel withComments(List comments) {
56 | return new RestMethodModel(originClass, name, returnType, originalMethod, rootResource, httpMethod, path, pathParams, queryParams, entityParam, comments);
57 | }
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/parser/RestQueryParam.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.parser;
3 |
4 |
5 | public abstract class RestQueryParam {
6 |
7 | public boolean required;
8 |
9 | RestQueryParam(boolean required) {
10 | this.required = required;
11 | }
12 |
13 | public static class Single extends RestQueryParam {
14 | private final MethodParameterModel queryParam;
15 |
16 | public Single(MethodParameterModel queryParam, boolean required) {
17 | super(required);
18 | this.queryParam = queryParam;
19 | }
20 |
21 | public MethodParameterModel getQueryParam() {
22 | return queryParam;
23 | }
24 | }
25 |
26 | public static class Bean extends RestQueryParam {
27 | private final BeanModel bean;
28 |
29 | // Only used in JAX-Rs, so optional
30 | public Bean(BeanModel bean) {
31 | super(false);
32 | this.bean = bean;
33 | }
34 |
35 | public BeanModel getBean() {
36 | return bean;
37 | }
38 | }
39 |
40 | public static class Map extends RestQueryParam {
41 | public Map(boolean required) {
42 | super(required);
43 | }
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/parser/SourceType.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.parser;
3 |
4 | import java.lang.reflect.Type;
5 |
6 |
7 | public class SourceType {
8 |
9 | public final T type;
10 | public final Class> usedInClass;
11 | public final String usedInMember;
12 |
13 | public SourceType(T type) {
14 | this (type, null, null);
15 | }
16 |
17 | public SourceType(T type, Class> usedInClass, String usedInMember) {
18 | this.type = type;
19 | this.usedInClass = usedInClass;
20 | this.usedInMember = usedInMember;
21 | }
22 |
23 | @SuppressWarnings("unchecked")
24 | public SourceType> asSourceClass() {
25 | Class.class.cast(this.type);
26 | return (SourceType>) this;
27 | }
28 |
29 | @Override
30 | public String toString() {
31 | return type.toString();
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/parser/SwaggerOperation.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.parser;
3 |
4 | import java.lang.reflect.Type;
5 | import java.util.List;
6 |
7 |
8 | public class SwaggerOperation {
9 | public Type responseType;
10 | public List possibleResponses;
11 | public boolean hidden;
12 | public String comment;
13 | }
14 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/parser/SwaggerResponse.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.parser;
3 |
4 | import java.lang.reflect.Type;
5 |
6 |
7 | public class SwaggerResponse {
8 | public String code;
9 | public String comment;
10 | public Type responseType;
11 | }
12 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/type/JGenericArrayType.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.type;
3 |
4 | import java.lang.reflect.GenericArrayType;
5 | import java.lang.reflect.Type;
6 | import java.util.Objects;
7 |
8 |
9 | public class JGenericArrayType implements GenericArrayType {
10 |
11 | private final Type genericComponentType;
12 |
13 | public JGenericArrayType(Type genericComponentType) {
14 | this.genericComponentType = Objects.requireNonNull(genericComponentType, "genericComponentType");
15 | }
16 |
17 | public static JGenericArrayType of(Class> arrayClass) {
18 | Objects.requireNonNull(arrayClass);
19 | if (!arrayClass.isArray()) {
20 | throw new IllegalArgumentException("Class is not array: " + arrayClass);
21 | }
22 | return new JGenericArrayType(arrayClass.getComponentType());
23 | }
24 |
25 | @Override
26 | public Type getGenericComponentType() {
27 | return genericComponentType;
28 | }
29 |
30 | @Override
31 | public int hashCode() {
32 | return Objects.hashCode(genericComponentType);
33 | }
34 |
35 | @Override
36 | public boolean equals(Object obj) {
37 | if (this == obj) {
38 | return true;
39 | }
40 | if (obj instanceof GenericArrayType) {
41 | final GenericArrayType that = (GenericArrayType) obj;
42 | return Objects.equals(genericComponentType, that.getGenericComponentType());
43 | } else {
44 | return false;
45 | }
46 | }
47 |
48 | @Override
49 | public String toString() {
50 | return getGenericComponentType().getTypeName() + "[]";
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/type/JParameterizedType.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.type;
3 |
4 | import java.lang.reflect.ParameterizedType;
5 | import java.lang.reflect.Type;
6 | import java.util.Arrays;
7 | import java.util.Objects;
8 | import java.util.stream.Collectors;
9 | import java.util.stream.Stream;
10 |
11 |
12 | public class JParameterizedType implements ParameterizedType {
13 |
14 | private final Type rawType;
15 | private final Type[] actualTypeArguments;
16 | private final Type ownerType;
17 |
18 | public JParameterizedType(Type rawType, Type[] actualTypeArguments, Type ownerType) {
19 | this.rawType = Objects.requireNonNull(rawType, "rawType");
20 | this.actualTypeArguments = actualTypeArguments != null ? actualTypeArguments : new Type[0];
21 | this.ownerType = ownerType;
22 | }
23 |
24 | @Override
25 | public Type[] getActualTypeArguments() {
26 | return actualTypeArguments;
27 | }
28 |
29 | @Override
30 | public Type getRawType() {
31 | return rawType;
32 | }
33 |
34 | @Override
35 | public Type getOwnerType() {
36 | return ownerType;
37 | }
38 |
39 | @Override
40 | public int hashCode() {
41 | return Objects.hash(ownerType, rawType, actualTypeArguments);
42 | }
43 |
44 | @Override
45 | public boolean equals(Object obj) {
46 | if (this == obj) {
47 | return true;
48 | }
49 | if (obj instanceof ParameterizedType) {
50 | final ParameterizedType that = (ParameterizedType) obj;
51 | return Objects.equals(ownerType, that.getOwnerType()) &&
52 | Objects.equals(rawType, that.getRawType()) &&
53 | Arrays.equals(actualTypeArguments, that.getActualTypeArguments());
54 | } else {
55 | return false;
56 | }
57 | }
58 |
59 | @Override
60 | public String toString() {
61 | return (rawType instanceof Class ? ((Class>)rawType).getName() : rawType.getTypeName())
62 | + "<"
63 | + Stream.of(actualTypeArguments)
64 | .map(type -> type.getTypeName())
65 | .collect(Collectors.joining(", "))
66 | + ">";
67 | }
68 |
69 | }
70 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/type/JTypeWithNullability.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.type;
3 |
4 | import cz.habarta.typescript.generator.util.Utils;
5 | import java.lang.reflect.Type;
6 | import java.util.Objects;
7 |
8 |
9 | public class JTypeWithNullability implements Type {
10 |
11 | private final Type type;
12 | private final boolean isNullable;
13 |
14 | public JTypeWithNullability(Type type, boolean isNullable) {
15 | this.type = Objects.requireNonNull(type, "type");
16 | this.isNullable = isNullable;
17 | }
18 |
19 | public Type getType() {
20 | return type;
21 | }
22 |
23 | public boolean isNullable() {
24 | return isNullable;
25 | }
26 |
27 | // shallow
28 | public static Type getPlainType(Type type) {
29 | if (type instanceof JTypeWithNullability) {
30 | final JTypeWithNullability typeWithNullability = (JTypeWithNullability) type;
31 | return typeWithNullability.getType();
32 | } else {
33 | return type;
34 | }
35 | }
36 |
37 | // deep
38 | public static Type removeNullability(Type type) {
39 | if (type instanceof JTypeWithNullability) {
40 | final JTypeWithNullability typeWithNullability = (JTypeWithNullability) type;
41 | return removeNullability(typeWithNullability.getType());
42 | }
43 | return Utils.transformContainedTypes(type, JTypeWithNullability::removeNullability);
44 | }
45 |
46 | @Override
47 | public String toString() {
48 | return type + (isNullable ? "?" : "!");
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/type/JUnionType.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.type;
3 |
4 | import java.lang.reflect.Type;
5 | import java.util.Arrays;
6 | import java.util.List;
7 | import java.util.stream.Collectors;
8 |
9 |
10 | public class JUnionType implements Type {
11 |
12 | private final List types;
13 |
14 | public JUnionType(Type... types) {
15 | this(Arrays.asList(types));
16 | }
17 |
18 | public JUnionType(List types) {
19 | this.types = types;
20 | }
21 |
22 | public List getTypes() {
23 | return types;
24 | }
25 |
26 | @Override
27 | public String toString() {
28 | return "(" +
29 | types.stream().map(Type::toString).collect(Collectors.joining(" | "))
30 | + ")";
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/type/JWildcardType.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.type;
3 |
4 |
5 | import java.lang.reflect.Type;
6 | import java.lang.reflect.WildcardType;
7 | import java.util.Arrays;
8 | import java.util.Objects;
9 | import java.util.stream.Collectors;
10 | import java.util.stream.Stream;
11 |
12 | public class JWildcardType implements WildcardType {
13 |
14 | private final Type[] upperBounds;
15 | private final Type[] lowerBounds;
16 |
17 | public JWildcardType() {
18 | this(null, null);
19 | }
20 |
21 | public JWildcardType(Type[] upperBounds, Type[] lowerBounds) {
22 | this.upperBounds = upperBounds != null ? upperBounds : new Type[0];
23 | this.lowerBounds = lowerBounds != null ? lowerBounds : new Type[0];
24 | }
25 |
26 | @Override
27 | public Type[] getUpperBounds() {
28 | return upperBounds;
29 | }
30 |
31 | @Override
32 | public Type[] getLowerBounds() {
33 | return lowerBounds;
34 | }
35 |
36 | @Override
37 | public int hashCode() {
38 | return Arrays.hashCode(lowerBounds) ^ Arrays.hashCode(upperBounds);
39 | }
40 |
41 | @Override
42 | public boolean equals(Object obj) {
43 | if (this == obj) {
44 | return true;
45 | }
46 | if (obj instanceof WildcardType) {
47 | final WildcardType that = (WildcardType) obj;
48 | return Arrays.equals(lowerBounds, that.getLowerBounds()) &&
49 | Arrays.equals(upperBounds, that.getUpperBounds());
50 | } else {
51 | return false;
52 | }
53 | }
54 |
55 | @Override
56 | public String toString() {
57 | final String upper = upperBounds.length > 0 && !Objects.equals(upperBounds[0], Object.class)
58 | ? " extends " + Stream.of(upperBounds).map(Type::getTypeName).collect(Collectors.joining(" & "))
59 | : "";
60 | final String lower = lowerBounds.length > 0
61 | ? " extends " + Stream.of(lowerBounds).map(Type::getTypeName).collect(Collectors.joining(" & "))
62 | : "";
63 | return "?" + upper + lower;
64 | }
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/util/AnnotationGetter.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.util;
3 |
4 | import java.lang.annotation.Annotation;
5 |
6 |
7 | @FunctionalInterface
8 | public interface AnnotationGetter {
9 | public A getAnnotation(Class annotationClass);
10 | }
11 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/util/DeprecationUtils.java:
--------------------------------------------------------------------------------
1 | package cz.habarta.typescript.generator.util;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public final class DeprecationUtils {
7 |
8 | public static final String DEPRECATED = "@deprecated";
9 |
10 | public static String convertToComment(Deprecated deprecated) {
11 | String since = deprecated.since();
12 | Boolean forRemoval = deprecated.forRemoval();
13 |
14 | List additional = new ArrayList<>();
15 | if (since != null && !since.isEmpty()) {
16 | additional.add("since " + since);
17 | }
18 | if (forRemoval != null && forRemoval) {
19 | additional.add("for removal");
20 | }
21 | return additional.isEmpty() ? DEPRECATED : (DEPRECATED + " " + String.join(", ", additional));
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/util/Pair.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.util;
3 |
4 | import java.util.Objects;
5 |
6 |
7 | public class Pair {
8 |
9 | private final T1 value1;
10 | private final T2 value2;
11 |
12 | private Pair(T1 value1, T2 value2) {
13 | this.value1 = value1;
14 | this.value2 = value2;
15 | }
16 |
17 | public static Pair of(T1 value1, T2 value2) {
18 | return new Pair<>(value1, value2);
19 | }
20 |
21 | public T1 getValue1() {
22 | return value1;
23 | }
24 |
25 | public T2 getValue2() {
26 | return value2;
27 | }
28 |
29 | @Override
30 | public int hashCode() {
31 | int hash = 5;
32 | hash = 53 * hash + Objects.hashCode(this.value1);
33 | hash = 53 * hash + Objects.hashCode(this.value2);
34 | return hash;
35 | }
36 |
37 | @Override
38 | public boolean equals(Object obj) {
39 | if (this == obj) {
40 | return true;
41 | }
42 | if (obj == null) {
43 | return false;
44 | }
45 | if (getClass() != obj.getClass()) {
46 | return false;
47 | }
48 | final Pair, ?> other = (Pair, ?>) obj;
49 | if (!Objects.equals(this.value1, other.value1)) {
50 | return false;
51 | }
52 | if (!Objects.equals(this.value2, other.value2)) {
53 | return false;
54 | }
55 | return true;
56 | }
57 |
58 | }
59 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/util/PropertyMember.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.util;
3 |
4 | import java.lang.annotation.Annotation;
5 | import java.lang.reflect.AnnotatedElement;
6 | import java.lang.reflect.AnnotatedType;
7 | import java.lang.reflect.Type;
8 | import java.util.Objects;
9 |
10 |
11 | public class PropertyMember {
12 |
13 | private final AnnotatedElement annotatedElement;
14 | private final Type type;
15 | private final AnnotatedType annotatedType;
16 | private final AnnotationGetter annotationGetter;
17 |
18 | public PropertyMember(AnnotatedElement annotatedElement, Type type, AnnotatedType annotatedType, AnnotationGetter annotationGetter) {
19 | this.annotatedElement = Objects.requireNonNull(annotatedElement);
20 | this.type = Objects.requireNonNull(type);
21 | this.annotatedType = Objects.requireNonNull(annotatedType);
22 | this.annotationGetter = annotationGetter;
23 | }
24 |
25 | public Type getType() {
26 | return type;
27 | }
28 |
29 | public A getAnnotation(Class annotationClass) {
30 | final A annotation = annotationGetter != null
31 | ? annotationGetter.getAnnotation(annotationClass)
32 | : annotatedElement.getAnnotation(annotationClass);
33 | return annotation != null
34 | ? annotation
35 | : annotatedType.getAnnotation(annotationClass);
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/util/StandardJsonPrettyPrinter.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.util;
3 |
4 | import com.fasterxml.jackson.core.JsonGenerator;
5 | import com.fasterxml.jackson.core.util.DefaultIndenter;
6 | import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
7 | import java.io.IOException;
8 |
9 |
10 | /**
11 | * Jackson2 PrettyPrinter implementation that produces JSON format similar to JSON.stringify() output.
12 | */
13 | public class StandardJsonPrettyPrinter extends DefaultPrettyPrinter {
14 | private static final long serialVersionUID = 1;
15 |
16 | private final String indent;
17 | private final String eol;
18 |
19 | public StandardJsonPrettyPrinter() {
20 | this(" ", String.format("%n"));
21 | }
22 |
23 | public StandardJsonPrettyPrinter(String indent, String eol) {
24 | this.indent = indent;
25 | this.eol = eol;
26 | final DefaultIndenter indenter = new DefaultIndenter(indent, eol);
27 | this._arrayIndenter = indenter;
28 | this._objectIndenter = indenter;
29 | }
30 |
31 | @Override
32 | public DefaultPrettyPrinter createInstance() {
33 | return new StandardJsonPrettyPrinter(indent, eol);
34 | }
35 |
36 | @Override
37 | public void writeObjectFieldValueSeparator(JsonGenerator jg) throws IOException {
38 | jg.writeRaw(": ");
39 | }
40 |
41 | @Override
42 | public void writeEndObject(JsonGenerator g, int nrOfEntries) throws IOException {
43 | if (!_objectIndenter.isInline()) {
44 | --_nesting;
45 | }
46 | if (nrOfEntries > 0) {
47 | _objectIndenter.writeIndentation(g, _nesting);
48 | }
49 | g.writeRaw('}');
50 | }
51 |
52 | @Override
53 | public void writeEndArray(JsonGenerator g, int nrOfValues) throws IOException {
54 | if (!_arrayIndenter.isInline()) {
55 | --_nesting;
56 | }
57 | if (nrOfValues > 0) {
58 | _arrayIndenter.writeIndentation(g, _nesting);
59 | }
60 | g.writeRaw(']');
61 | }
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/resources/cz/habarta/typescript/generator/ext/AxiosClientExtension-client.template.ts:
--------------------------------------------------------------------------------
1 |
2 | /*export*/ class $$AxiosRestApplicationClient$$ extends $$RestApplicationClientFullName$$ {
3 |
4 | constructor(baseURL: string, axiosInstance: Axios.AxiosInstance = axios.create()) {
5 | axiosInstance.defaults.baseURL = baseURL;
6 | super(new AxiosHttpClient(axiosInstance));
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/resources/cz/habarta/typescript/generator/ext/AxiosClientExtension-shared.template.ts:
--------------------------------------------------------------------------------
1 |
2 | import axios from "axios";
3 | import * as Axios from "axios";
4 |
5 | declare module "axios" {
6 | export interface GenericAxiosResponse extends Axios.AxiosResponse {
7 | data: R;
8 | }
9 | }
10 |
11 | class AxiosHttpClient implements HttpClient {
12 |
13 | constructor(private axios: Axios.AxiosInstance) {
14 | }
15 |
16 | request(requestConfig: { method: string; url: string; queryParams?: any; data?: any; copyFn?: (data: R) => R; options?: Axios.AxiosRequestConfig; }): RestResponse {
17 | function assign(target: any, source?: any) {
18 | if (source != undefined) {
19 | for (const key in source) {
20 | if (source.hasOwnProperty(key)) {
21 | target[key] = source[key];
22 | }
23 | }
24 | }
25 | return target;
26 | }
27 |
28 | const config: Axios.AxiosRequestConfig = {};
29 | config.method = requestConfig.method as typeof config.method; // `string` in axios 0.16.0, `Method` in axios 0.19.0
30 | config.url = requestConfig.url;
31 | config.params = requestConfig.queryParams;
32 | config.data = requestConfig.data;
33 | assign(config, requestConfig.options);
34 | const copyFn = requestConfig.copyFn;
35 |
36 | const axiosResponse = this.axios.request(config);
37 | return axiosResponse.then(axiosResponse => {
38 | if (copyFn && axiosResponse.data) {
39 | (axiosResponse as any).originalData = axiosResponse.data;
40 | axiosResponse.data = copyFn(axiosResponse.data);
41 | }
42 | return axiosResponse;
43 | });
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/resources/datalibrary/guava.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "./_schema.json",
3 | "info": {
4 | "source": "https://github.com/google/guava",
5 | "jacksonModule": "https://github.com/FasterXML/jackson-datatypes-collections/blob/master/guava/src/main/java/com/fasterxml/jackson/datatype/guava/GuavaModule.java"
6 | },
7 | "classMappings": [
8 | {
9 | "className": "com.google.common.base.Optional",
10 | "semanticType": "optional"
11 | },
12 | {
13 | "className": "com.google.common.collect.RangeSet",
14 | "customType": "GuavaRangeSet"
15 | },
16 | {
17 | "className": "com.google.common.collect.Range",
18 | "customType": "GuavaRange"
19 | },
20 | {
21 | "className": "com.google.common.collect.Table",
22 | "customType": "GuavaTable"
23 | },
24 | {
25 | "className": "com.google.common.net.HostAndPort",
26 | "semanticType": "string"
27 | },
28 | {
29 | "className": "com.google.common.net.InternetDomainName",
30 | "semanticType": "string"
31 | },
32 | {
33 | "className": "com.google.common.cache.CacheBuilderSpec",
34 | "semanticType": "string"
35 | },
36 | {
37 | "className": "com.google.common.cache.CacheBuilder",
38 | "customType": "string"
39 | },
40 | {
41 | "className": "com.google.common.hash.HashCode",
42 | "semanticType": "string"
43 | },
44 | {
45 | "className": "com.google.common.collect.FluentIterable",
46 | "semanticType": "list"
47 | },
48 | {
49 | "className": "com.google.common.collect.Multimap",
50 | "customType": "GuavaMultimap"
51 | }
52 | ],
53 | "typeAliases": [
54 | {
55 | "name": "GuavaRangeSet",
56 | "definition": "GuavaRange[]"
57 | },
58 | {
59 | "name": "GuavaRange",
60 | "definition": "{ lowerEndpoint: C, lowerBoundType: 'OPEN' | 'CLOSED', upperEndpoint: C, upperBoundType: 'OPEN' | 'CLOSED' }"
61 | },
62 | {
63 | "name": "GuavaTable",
64 | "definition": "{ [index: string]: { [index: string]: V } }"
65 | },
66 | {
67 | "name": "GuavaMultimap",
68 | "definition": "{ [index: string]: V[] }"
69 | }
70 | ]
71 | }
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/resources/datalibrary/joda.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "./_schema.json",
3 | "info": {
4 | "source": "https://github.com/JodaOrg/joda-time",
5 | "jacksonModule": "https://github.com/FasterXML/jackson-datatype-joda/blob/master/src/main/java/com/fasterxml/jackson/datatype/joda/JodaModule.java"
6 | },
7 | "classMappings": [
8 | {
9 | "className": "org.joda.time.DateTime",
10 | "semanticType": "date"
11 | },
12 | {
13 | "className": "org.joda.time.DateTimeZone",
14 | "semanticType": "string"
15 | },
16 | {
17 | "className": "org.joda.time.Duration",
18 | "semanticType": "number"
19 | },
20 | {
21 | "className": "org.joda.time.Instant",
22 | "semanticType": "date"
23 | },
24 | {
25 | "className": "org.joda.time.LocalDateTime",
26 | "semanticType": "date"
27 | },
28 | {
29 | "className": "org.joda.time.LocalDate",
30 | "semanticType": "date"
31 | },
32 | {
33 | "className": "org.joda.time.LocalTime",
34 | "semanticType": "date"
35 | },
36 | {
37 | "className": "org.joda.time.Period",
38 | "semanticType": "string"
39 | },
40 | {
41 | "className": "org.joda.time.Interval",
42 | "semanticType": "string"
43 | },
44 | {
45 | "className": "org.joda.time.MonthDay",
46 | "semanticType": "string"
47 | },
48 | {
49 | "className": "org.joda.time.YearMonth",
50 | "semanticType": "string"
51 | },
52 | {
53 | "className": "org.joda.time.DateMidnight",
54 | "semanticType": "date"
55 | }
56 | ]
57 | }
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/resources/datalibrary/vavr.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "./_schema.json",
3 | "info": {
4 | "source": "https://github.com/vavr-io/vavr",
5 | "jacksonModule": "https://github.com/vavr-io/vavr-jackson/blob/master/src/main/java/io/vavr/jackson/datatype/VavrModule.java"
6 | },
7 | "classMappings": [
8 | {
9 | "className": "io.vavr.Lazy",
10 | "semanticType": "wrapper"
11 | },
12 | {
13 | "className": "io.vavr.control.Option",
14 | "semanticType": "optional"
15 | },
16 | {
17 | "className": "io.vavr.collection.CharSeq",
18 | "semanticType": "string"
19 | },
20 | {
21 | "className": "io.vavr.collection.Seq",
22 | "semanticType": "list"
23 | },
24 | {
25 | "className": "io.vavr.collection.Set",
26 | "semanticType": "list"
27 | },
28 | {
29 | "className": "io.vavr.collection.PriorityQueue",
30 | "semanticType": "list"
31 | },
32 | {
33 | "className": "io.vavr.collection.Map",
34 | "semanticType": "map"
35 | },
36 | {
37 | "className": "io.vavr.collection.Multimap",
38 | "customType": "VavrMultimap"
39 | }
40 | ],
41 | "typeAliases": [
42 | {
43 | "name": "VavrMultimap",
44 | "definition": "{ [index: string]: V[] }"
45 | }
46 | ]
47 | }
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/resources/helpers/jsonDeserialization.ts:
--------------------------------------------------------------------------------
1 | function __getCopyArrayFn(itemCopyFn: (item: T) => T): (array: T[]) => T[] {
2 | return (array: T[]) => __copyArray(array, itemCopyFn);
3 | }
4 |
5 | function __copyArray(array: T[], itemCopyFn: (item: T) => T): T[] {
6 | return array && array.map(item => item && itemCopyFn(item));
7 | }
8 |
9 | function __getCopyObjectFn(itemCopyFn: (item: T) => T): (object: { [index: string]: T }) => { [index: string]: T } {
10 | return (object: { [index: string]: T }) => __copyObject(object, itemCopyFn);
11 | }
12 |
13 | function __copyObject(object: { [index: string]: T }, itemCopyFn: (item: T) => T): { [index: string]: T } {
14 | if (!object) {
15 | return object;
16 | }
17 | const result: any = {};
18 | for (const key in object) {
19 | if (object.hasOwnProperty(key)) {
20 | const value = object[key];
21 | result[key] = value && itemCopyFn(value);
22 | }
23 | }
24 | return result;
25 | }
26 |
27 | function __identity(): (value: T) => T {
28 | return value => value;
29 | }
30 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/main/resources/helpers/uriEncoding.ts:
--------------------------------------------------------------------------------
1 | function uriEncoding(template: TemplateStringsArray, ...substitutions: any[]): string {
2 | let result = "";
3 | for (let i = 0; i < substitutions.length; i++) {
4 | result += template[i];
5 | result += encodeURIComponent(substitutions[i]);
6 | }
7 | result += template[template.length - 1];
8 | return result;
9 | }
10 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/CovariantPropertiesTest.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import java.util.List;
5 | import org.junit.jupiter.api.Assertions;
6 | import org.junit.jupiter.api.Test;
7 |
8 |
9 | public class CovariantPropertiesTest {
10 |
11 | @Test
12 | public void test() {
13 | final Settings settings = TestUtils.settings();
14 | settings.sortDeclarations = true;
15 | final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(Dog.class));
16 | final String expected =
17 | "interface Animal {\n" +
18 | " allFood: Food[];\n" +
19 | " todaysFood: Food;\n" +
20 | "}\n" +
21 | "\n" +
22 | "interface Dog extends Animal {\n" +
23 | " allFood: DogFood[];\n" +
24 | " todaysFood: DogFood;\n" +
25 | "}\n" +
26 | "\n" +
27 | "interface DogFood extends Food {\n" +
28 | "}\n" +
29 | "\n" +
30 | "interface Food {\n" +
31 | "}";
32 | Assertions.assertEquals(expected.replace('\'', '"'), output.trim());
33 | }
34 |
35 | private static abstract class Animal {
36 | public abstract Food getTodaysFood();
37 | public abstract List extends Food> getAllFood();
38 | }
39 |
40 | private static abstract class Dog extends Animal {
41 | @Override
42 | public abstract DogFood getTodaysFood();
43 | @Override
44 | public abstract List extends DogFood> getAllFood();
45 | }
46 |
47 | private static abstract class Food {
48 | }
49 |
50 | private static abstract class DogFood extends Food {
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/CustomTypeAliasesTest.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import java.util.Collections;
5 | import org.junit.jupiter.api.Assertions;
6 | import org.junit.jupiter.api.Test;
7 |
8 |
9 | @SuppressWarnings("unused")
10 | public class CustomTypeAliasesTest {
11 |
12 | @Test
13 | public void testGeneric() {
14 | final Settings settings = TestUtils.settings();
15 | settings.outputKind = TypeScriptOutputKind.module;
16 | settings.customTypeAliases = Collections.singletonMap("Id", "string");
17 | settings.customTypeMappings = Collections.singletonMap("cz.habarta.typescript.generator.CustomTypeAliasesTest$IdRepresentation", "Id");
18 | final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(MyEntityRepresentation.class));
19 | Assertions.assertTrue(output.contains("id: Id"));
20 | Assertions.assertTrue(output.contains("export type Id = string"));
21 | }
22 |
23 | private static class MyEntityRepresentation {
24 | public IdRepresentation id;
25 | }
26 |
27 | private static class IdRepresentation {
28 | public String id;
29 | }
30 |
31 | @Test
32 | public void testNonGeneric() {
33 | final Settings settings = TestUtils.settings();
34 | settings.customTypeAliases = Collections.singletonMap("Id", "string");
35 | final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from());
36 | Assertions.assertTrue(output.contains("type Id = string"));
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/DeprecationUtilsTest.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import cz.habarta.typescript.generator.util.DeprecationUtils;
5 | import org.junit.jupiter.api.Assertions;
6 | import org.junit.jupiter.api.Test;
7 |
8 |
9 | public class DeprecationUtilsTest {
10 |
11 | @Deprecated
12 | private String a;
13 |
14 | @Deprecated(since = "2.28")
15 | private String b;
16 |
17 | @Deprecated(forRemoval = true)
18 | private String c;
19 |
20 | @Deprecated(since = "2.28", forRemoval = true)
21 | private String d;
22 |
23 | @Test
24 | public void test() {
25 | Assertions.assertEquals("@deprecated", getDeprecationText("a"));
26 | Assertions.assertEquals("@deprecated since 2.28", getDeprecationText("b"));
27 | Assertions.assertEquals("@deprecated for removal", getDeprecationText("c"));
28 | Assertions.assertEquals("@deprecated since 2.28, for removal", getDeprecationText("d"));
29 | }
30 |
31 | private static String getDeprecationText(String fieldName) {
32 | try {
33 | final Deprecated deprecated = DeprecationUtilsTest.class.getDeclaredField(fieldName).getAnnotation(Deprecated.class);
34 | return DeprecationUtils.convertToComment(deprecated);
35 | } catch (ReflectiveOperationException e) {
36 | throw new RuntimeException(e);
37 | }
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/DummyBean.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import java.util.ArrayList;
5 | import java.util.Date;
6 | import java.util.List;
7 | import java.util.Map;
8 |
9 |
10 | @SuppressWarnings("rawtypes")
11 | public class DummyBean {
12 |
13 | public String firstProperty;
14 | public int intProperty;
15 | public Integer integerProperty;
16 | public boolean booleanProperty;
17 | public Date dateProperty;
18 | public String[] stringArrayProperty;
19 | public List stringListProperty;
20 | public ArrayList stringArrayListProperty;
21 | public DummyEnum dummyEnumProperty;
22 | public Map stringMapProperty;
23 | public List> listOfListOfIntegerProperty;
24 | public Map mapOfDummyBeanProperty;
25 | public List rawListProperty;
26 | public Map rawMapProperty;
27 | public List listOfDummyEnumProperty;
28 | public Map mapOfDummyEnumProperty;
29 | public Map>> mapOfListOfMapOfDummyEnumProperty;
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/DummyClassEnum.java:
--------------------------------------------------------------------------------
1 | package cz.habarta.typescript.generator;
2 |
3 | import com.fasterxml.jackson.annotation.JsonCreator;
4 | import com.fasterxml.jackson.annotation.JsonValue;
5 | import java.util.Objects;
6 |
7 | public class DummyClassEnum {
8 |
9 | public static final DummyClassEnum ATYPE = new DummyClassEnum("ATYPE");
10 | public static final DummyClassEnum BTYPE = new DummyClassEnum("BTYPE");
11 | public static final DummyClassEnum CTYPE = new DummyClassEnum("CTYPE");
12 |
13 | private final String value;
14 |
15 | @JsonCreator
16 | public DummyClassEnum(String value) {
17 | this.value = Objects.requireNonNull(value);
18 | }
19 |
20 | @JsonValue
21 | public String getValue() { return value; }
22 |
23 | @Override
24 | public String toString() { return value; }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/DummyEnum.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 |
5 | /**
6 | * Documentation for DummyEnum.
7 | */
8 | public enum DummyEnum {
9 |
10 | /**
11 | * ff0000
12 | */
13 | Red,
14 |
15 | /**
16 | * 00ff00
17 | */
18 | Green,
19 |
20 | /**
21 | * 0000ff
22 | */
23 | Blue;
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/DummyMixedCaseEnum.java:
--------------------------------------------------------------------------------
1 | package cz.habarta.typescript.generator;
2 |
3 | public enum DummyMixedCaseEnum {
4 | camelCaseType,
5 | PascalCaseType,
6 | UPPER_CASE_TYPE
7 | }
8 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/DuplicatePropertyTest.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import com.fasterxml.jackson.annotation.JsonSubTypes;
5 | import com.fasterxml.jackson.annotation.JsonTypeInfo;
6 | import com.fasterxml.jackson.core.JsonProcessingException;
7 | import com.fasterxml.jackson.databind.ObjectMapper;
8 | import org.junit.jupiter.api.Assertions;
9 | import org.junit.jupiter.api.Test;
10 |
11 |
12 | public class DuplicatePropertyTest {
13 |
14 | public static class DuplicateKindUsage {
15 | public DuplicateKind duplicateKind;
16 | }
17 |
18 | @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "kind", include = JsonTypeInfo.As.PROPERTY)
19 | @JsonSubTypes({
20 | @JsonSubTypes.Type(value = DuplicateKind1.class, name = "kind_1"),
21 | @JsonSubTypes.Type(value = DuplicateKind2.class, name = "kind_2"),
22 | })
23 | public static abstract class DuplicateKind {
24 | // public String kind;
25 | }
26 |
27 | public static class DuplicateKind1 extends DuplicateKind {
28 | public String kind;
29 | }
30 |
31 | public static class DuplicateKind2 extends DuplicateKind {
32 | }
33 |
34 | @Test
35 | public void testJacksonDuplicateProperty() throws JsonProcessingException {
36 | final DuplicateKind1 object = new DuplicateKind1();
37 | object.kind = "kind_invalid";
38 | final String json = new ObjectMapper().writeValueAsString(object);
39 | // {"kind":"kind_1","kind":"kind_invalid"}
40 | Assertions.assertTrue(json.contains("\"kind\":\"kind_1\""));
41 | Assertions.assertTrue(json.contains("\"kind\":\"kind_invalid\""));
42 | }
43 |
44 | @Test
45 | public void testDuplicateProperty() throws JsonProcessingException {
46 | final Settings settings = TestUtils.settings();
47 | settings.outputKind = TypeScriptOutputKind.module;
48 | settings.outputFileType = TypeScriptFileType.implementationFile;
49 | settings.mapClasses = ClassMapping.asClasses;
50 | final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(DuplicateKindUsage.class));
51 | Assertions.assertTrue(!output.contains("DuplicateKindUnion"));
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/InterfaceTest.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import org.junit.jupiter.api.Assertions;
5 | import org.junit.jupiter.api.Test;
6 |
7 |
8 | public class InterfaceTest {
9 |
10 | @Test
11 | public void test() {
12 | final Settings settings = TestUtils.settings();
13 | final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(Book.class));
14 | Assertions.assertTrue(output.contains("interface Book"));
15 | Assertions.assertTrue(output.contains("title: string;"));
16 | Assertions.assertTrue(output.contains("interface Author"));
17 | }
18 |
19 | @Test
20 | public void testReadOnlyProperties() {
21 | final Settings settings = TestUtils.settings();
22 | settings.declarePropertiesAsReadOnly = true;
23 | final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(Book.class));
24 | Assertions.assertTrue(output.contains("readonly author: Author;"));
25 | Assertions.assertTrue(output.contains("readonly title: string;"));
26 | Assertions.assertTrue(output.contains("readonly name: string;"));
27 | }
28 |
29 | static interface Book {
30 | Author getAuthor();
31 | String getTitle();
32 | }
33 |
34 | static interface Author {
35 | String getName();
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/Jackson2ConfigurationResolvedTest.java:
--------------------------------------------------------------------------------
1 | package cz.habarta.typescript.generator;
2 |
3 | import java.util.Arrays;
4 | import org.junit.jupiter.api.Assertions;
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class Jackson2ConfigurationResolvedTest {
8 |
9 | @Test
10 | public void test() {
11 | final Jackson2Configuration configuration = new Jackson2Configuration();
12 | configuration.serializerTypeMappings = Arrays.asList(Jackson2ParserTest.IdSerializer.class.getName() + ":" + "string");
13 | final Jackson2ConfigurationResolved resolved = Jackson2ConfigurationResolved.from(configuration, Thread.currentThread().getContextClassLoader());
14 | Assertions.assertEquals("string", resolved.serializerTypeMappings.get(Jackson2ParserTest.IdSerializer.class));
15 | }
16 |
17 | }
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/Jackson2DeserializableRootType.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import com.fasterxml.jackson.annotation.JsonSubTypes;
5 | import com.fasterxml.jackson.annotation.JsonTypeInfo;
6 | import com.fasterxml.jackson.annotation.JsonTypeName;
7 | import com.fasterxml.jackson.core.JsonProcessingException;
8 | import com.fasterxml.jackson.databind.ObjectMapper;
9 | import org.junit.jupiter.api.Assertions;
10 | import org.junit.jupiter.api.Test;
11 |
12 | /**
13 | * Test that root type name in a hirarchy is included iff root type itself is not abstract
14 | */
15 | public class Jackson2DeserializableRootType {
16 |
17 | @Test
18 | public void testHowJacksonDeserializes() throws JsonProcessingException {
19 | NonAbstractRoot nar = new ObjectMapper()
20 | .readValue("{\"type\": \"rootType\"}",
21 | NonAbstractRoot.class);
22 | NonAbstractRoot nars = new ObjectMapper()
23 | .readValue("{\"type\": \"subType\"}",
24 | NonAbstractRoot.class);
25 |
26 | Assertions.assertSame(NonAbstractRoot.class, nar.getClass());
27 | Assertions.assertSame(NonAbstractRootSub.class, nars.getClass());
28 | }
29 |
30 | @Test
31 | public void testRootTypeIncludedIfNotAbstract() {
32 | final String output = new TypeScriptGenerator(TestUtils.settings()).generateTypeScript(Input.from(NonAbstractRoot.class));
33 | Assertions.assertTrue(output.contains("\"rootType\""));
34 | }
35 |
36 | @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
37 | @JsonSubTypes(@JsonSubTypes.Type(NonAbstractRootSub.class))
38 | @JsonTypeName("rootType")
39 | public static class NonAbstractRoot {
40 | }
41 |
42 | @JsonTypeName("subType")
43 | public static class NonAbstractRootSub extends NonAbstractRoot {
44 | }
45 |
46 | @Test
47 | public void testRootTypeNotIncludedIfAbstract() {
48 | final String output = new TypeScriptGenerator(TestUtils.settings()).generateTypeScript(Input.from(AbstractRoot.class));
49 | // Root type is abstract and therefore ignored in the type list
50 | Assertions.assertFalse(output.contains("\"rootType\""));
51 | }
52 |
53 | @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
54 | @JsonSubTypes(@JsonSubTypes.Type(AbstractRootSub.class))
55 | @JsonTypeName("rootType")
56 | public static abstract class AbstractRoot {
57 | }
58 |
59 | @JsonTypeName("subType")
60 | public static class AbstractRootSub extends AbstractRoot {
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/Jackson2PolymorphismTest.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import com.fasterxml.jackson.annotation.JsonSubTypes;
5 | import com.fasterxml.jackson.annotation.JsonTypeInfo;
6 | import org.junit.jupiter.api.Assertions;
7 | import org.junit.jupiter.api.Test;
8 |
9 |
10 | public class Jackson2PolymorphismTest {
11 |
12 | @Test
13 | public void testPropertyNameQuoting() {
14 | final String output = new TypeScriptGenerator(TestUtils.settings()).generateTypeScript(Input.from(BadFieldClass.class));
15 | Assertions.assertTrue(output.contains("\"@class\""));
16 | }
17 |
18 | @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
19 | public static interface BadFieldClass {
20 | }
21 |
22 | @Test
23 | public void testInterfaceOrder() {
24 | final String output = new TypeScriptGenerator(TestUtils.settings()).generateTypeScript(Input.from(Z.class));
25 | final int x = output.indexOf("interface X");
26 | final int y = output.indexOf("interface Y");
27 | final int z = output.indexOf("interface Z");
28 | Assertions.assertTrue(z < x);
29 | Assertions.assertTrue(z < y);
30 | }
31 |
32 | @JsonSubTypes({
33 | @JsonSubTypes.Type(Y.class),
34 | @JsonSubTypes.Type(X.class)
35 | })
36 | public static class Z {
37 | }
38 |
39 | public static class Y extends Z {
40 | }
41 |
42 | public static class X extends Z {
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/JaxbTest.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import javax.xml.bind.JAXBElement;
5 | import javax.xml.bind.annotation.XmlElement;
6 | import javax.xml.bind.annotation.XmlElementRef;
7 | import javax.xml.bind.annotation.XmlRootElement;
8 | import javax.xml.bind.annotation.XmlTransient;
9 | import org.junit.jupiter.api.Assertions;
10 | import org.junit.jupiter.api.Test;
11 |
12 |
13 | public class JaxbTest {
14 |
15 | @Test
16 | public void test() {
17 | final Settings settings = TestUtils.settings();
18 | settings.jsonLibrary = JsonLibrary.jaxb;
19 | final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(MyJaxbBean.class));
20 | Assertions.assertTrue(output.contains("king"));
21 | Assertions.assertFalse(output.contains("age"));
22 | }
23 |
24 | @XmlRootElement
25 | private static class MyJaxbBean {
26 |
27 | @XmlElement(name = "king")
28 | public String name;
29 |
30 | @XmlTransient
31 | public int age;
32 |
33 | }
34 |
35 | @Test
36 | public void testJAXBElement() {
37 | final Settings settings = TestUtils.settings();
38 | settings.jsonLibrary = JsonLibrary.jaxb;
39 | final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(ClassWithJAXBElements.class));
40 | Assertions.assertTrue(output.contains("ExternalReference: string"));
41 | Assertions.assertTrue(output.contains("UserInformation: UserType"));
42 | Assertions.assertTrue(output.contains("Source: EndPointType"));
43 | Assertions.assertTrue(output.contains("AdditionalContextInfo: AdditionalContextType"));
44 | }
45 |
46 | @XmlRootElement
47 | private static class ClassWithJAXBElements {
48 | @XmlElement(name = "ExternalReference")
49 | protected String externalReference;
50 | @XmlElementRef(name = "UserInformation", type = JAXBElement.class, required = false)
51 | protected JAXBElement userInformation;
52 | @XmlElementRef(name = "Source", type = JAXBElement.class, required = false)
53 | protected JAXBElement source;
54 | @XmlElementRef(name = "AdditionalContextInfo", type = JAXBElement.class, required = false)
55 | protected JAXBElement additionalContextInfo;
56 | }
57 |
58 | private static class UserType {
59 | }
60 |
61 | private static class EndPointType {
62 | }
63 |
64 | private static class AdditionalContextType {
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/JaxbV3Test.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import jakarta.xml.bind.JAXBElement;
5 | import jakarta.xml.bind.annotation.XmlElement;
6 | import jakarta.xml.bind.annotation.XmlElementRef;
7 | import jakarta.xml.bind.annotation.XmlRootElement;
8 | import jakarta.xml.bind.annotation.XmlTransient;
9 | import org.junit.jupiter.api.Assertions;
10 | import org.junit.jupiter.api.Test;
11 |
12 |
13 | public class JaxbV3Test {
14 |
15 | @Test
16 | public void test() {
17 | final Settings settings = TestUtils.settings();
18 | settings.jsonLibrary = JsonLibrary.jaxb;
19 | final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(MyJaxbBean.class));
20 | Assertions.assertTrue(output.contains("king"));
21 | Assertions.assertFalse(output.contains("age"));
22 | }
23 |
24 | @XmlRootElement
25 | private static class MyJaxbBean {
26 |
27 | @XmlElement(name = "king")
28 | public String name;
29 |
30 | @XmlTransient
31 | public int age;
32 |
33 | }
34 |
35 | @Test
36 | public void testJAXBElement() {
37 | final Settings settings = TestUtils.settings();
38 | settings.jsonLibrary = JsonLibrary.jaxb;
39 | final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(ClassWithJAXBElements.class));
40 | Assertions.assertTrue(output.contains("ExternalReference: string"));
41 | Assertions.assertTrue(output.contains("UserInformation: UserType"));
42 | Assertions.assertTrue(output.contains("Source: EndPointType"));
43 | Assertions.assertTrue(output.contains("AdditionalContextInfo: AdditionalContextType"));
44 | }
45 |
46 | @XmlRootElement
47 | private static class ClassWithJAXBElements {
48 | @XmlElement(name = "ExternalReference")
49 | protected String externalReference;
50 | @XmlElementRef(name = "UserInformation", type = JAXBElement.class, required = false)
51 | protected JAXBElement userInformation;
52 | @XmlElementRef(name = "Source", type = JAXBElement.class, required = false)
53 | protected JAXBElement source;
54 | @XmlElementRef(name = "AdditionalContextInfo", type = JAXBElement.class, required = false)
55 | protected JAXBElement additionalContextInfo;
56 | }
57 |
58 | private static class UserType {
59 | }
60 |
61 | private static class EndPointType {
62 | }
63 |
64 | private static class AdditionalContextType {
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/MapTest.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import java.util.Map;
5 | import org.junit.jupiter.api.Assertions;
6 | import org.junit.jupiter.api.Test;
7 |
8 |
9 | public class MapTest {
10 |
11 | public static class ClassWithMap {
12 | public Map people;
13 | }
14 |
15 | @Test
16 | public void testDefault() {
17 | final Settings settings = TestUtils.settings();
18 | final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(ClassWithMap.class));
19 | Assertions.assertTrue(output.contains("people: { [index: string]: Person }"));
20 | }
21 |
22 | @Test
23 | public void testIndexedArray() {
24 | final Settings settings = TestUtils.settings();
25 | settings.mapMap = MapMapping.asIndexedArray;
26 | final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(ClassWithMap.class));
27 | Assertions.assertTrue(output.contains("people: { [index: string]: Person }"));
28 | }
29 |
30 | @Test
31 | public void testRecord() {
32 | final Settings settings = TestUtils.settings();
33 | settings.mapMap = MapMapping.asRecord;
34 | final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(ClassWithMap.class));
35 | Assertions.assertTrue(output.contains("people: Record"));
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/PathTemplateTest.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import cz.habarta.typescript.generator.parser.PathTemplate;
5 | import org.junit.jupiter.api.Assertions;
6 | import org.junit.jupiter.api.Test;
7 |
8 |
9 | public class PathTemplateTest {
10 |
11 | @Test
12 | public void test() {
13 | Assertions.assertEquals(0, PathTemplate.parse("").getParts().size());
14 | Assertions.assertEquals(1, PathTemplate.parse("a").getParts().size());
15 | Assertions.assertEquals(1, PathTemplate.parse("{x}").getParts().size());
16 | Assertions.assertEquals(1, PathTemplate.parse("{x:.+}").getParts().size());
17 | Assertions.assertEquals(1, PathTemplate.parse("{ x : .+ }").getParts().size());
18 | Assertions.assertEquals(2, PathTemplate.parse("a{x}").getParts().size());
19 | Assertions.assertEquals(2, PathTemplate.parse("{x}a").getParts().size());
20 | Assertions.assertEquals(2, PathTemplate.parse("{x}{y}").getParts().size());
21 | Assertions.assertEquals(3, PathTemplate.parse("a{x}a").getParts().size());
22 | Assertions.assertEquals(3, PathTemplate.parse("{x}a{y}").getParts().size());
23 |
24 | Assertions.assertEquals("${x}a${y}", PathTemplate.parse("{ x : .+ }a{y}").format("${", "}", false));
25 | Assertions.assertEquals("{x:.+}a{y}", PathTemplate.parse("{ x : .+ }a{y}").format("{", "}", true));
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/Person.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import java.util.List;
5 | import java.util.Map;
6 |
7 |
8 | public class Person {
9 |
10 | public String name;
11 | public int age;
12 | public boolean hasChildren;
13 | public List tags;
14 | public Map emails;
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/PersonTest.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import java.io.File;
5 | import org.junit.jupiter.api.Test;
6 |
7 |
8 | public class PersonTest {
9 |
10 | @Test
11 | public void test() {
12 | new TypeScriptGenerator(TestUtils.settings()).generateTypeScript(Input.from(Person.class), Output.to(new File("target/person.d.ts")));
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/RecordTest.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import java.util.List;
5 | import org.junit.jupiter.api.Assertions;
6 | import org.junit.jupiter.api.Test;
7 |
8 |
9 | public class RecordTest {
10 |
11 | // public record Account(Long id, String name) {}
12 |
13 | // @Test
14 | // public void test() {
15 | // final Settings settings = TestUtils.settings();
16 | // final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(Account.class));
17 | // Assertions.assertTrue(!output.contains("interface Record"));
18 | // }
19 |
20 | // @Test
21 | // public void testConstructor() {
22 | // final Settings settings = TestUtils.settings();
23 | // settings.outputFileType = TypeScriptFileType.implementationFile;
24 | // settings.mapClasses = ClassMapping.asClasses;
25 | // settings.generateConstructors = true;
26 | // final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(Account.class));
27 | // System.out.println(output);
28 | // Assertions.assertTrue(!output.contains("interface Record"));
29 | // }
30 |
31 | private static class Base {
32 | }
33 |
34 | private static class Derived extends Base {
35 | public String name;
36 | }
37 |
38 | @Test
39 | public void testConstructorWithExclusion() {
40 | final Settings settings = TestUtils.settings();
41 | settings.outputFileType = TypeScriptFileType.implementationFile;
42 | settings.mapClasses = ClassMapping.asClasses;
43 | settings.generateConstructors = true;
44 | settings.setExcludeFilter(List.of(Base.class.getName()), null);
45 | final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(Derived.class));
46 | Assertions.assertTrue(!output.contains("interface Record"));
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/SettingsTest.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import java.lang.reflect.Modifier;
5 | import org.junit.jupiter.api.Assertions;
6 | import org.junit.jupiter.api.Test;
7 |
8 |
9 | public class SettingsTest {
10 |
11 | @Test
12 | public void testParseModifiers() {
13 | Assertions.assertEquals(0, Settings.parseModifiers("", Modifier.fieldModifiers()));
14 | Assertions.assertEquals(Modifier.STATIC, Settings.parseModifiers("static", Modifier.fieldModifiers()));
15 | Assertions.assertEquals(Modifier.STATIC | Modifier.TRANSIENT, Settings.parseModifiers("static | transient", Modifier.fieldModifiers()));
16 | }
17 |
18 | @Test
19 | public void testNpmDependenciesValidation() {
20 | String exceptionMessage = "'npmDependencies', 'npmDevDependencies' and 'npmPeerDependencies' parameters are only applicable when generating NPM 'package.json'.";
21 |
22 | {
23 | Settings settings = new Settings();
24 | settings.outputKind = TypeScriptOutputKind.module;
25 | settings.jsonLibrary = JsonLibrary.jackson2;
26 | settings.generateNpmPackageJson = false;
27 | settings.npmPackageDependencies.put("dependencies", "version");
28 |
29 | RuntimeException exception = Assertions.assertThrows(RuntimeException.class, () -> settings.validate());
30 | Assertions.assertEquals(exceptionMessage, exception.getMessage());
31 | }
32 |
33 | {
34 | Settings settings = new Settings();
35 | settings.outputKind = TypeScriptOutputKind.module;
36 | settings.jsonLibrary = JsonLibrary.jackson2;
37 | settings.generateNpmPackageJson = false;
38 | settings.npmDevDependencies.put("dependencies", "version");
39 |
40 | RuntimeException exception = Assertions.assertThrows(RuntimeException.class, () -> settings.validate());
41 | Assertions.assertEquals(exceptionMessage, exception.getMessage());
42 | }
43 |
44 | {
45 | Settings settings = new Settings();
46 | settings.outputKind = TypeScriptOutputKind.module;
47 | settings.jsonLibrary = JsonLibrary.jackson2;
48 | settings.generateNpmPackageJson = false;
49 | settings.npmPeerDependencies.put("dependencies", "version");
50 |
51 | RuntimeException exception = Assertions.assertThrows(RuntimeException.class, () -> settings.validate());
52 | Assertions.assertEquals(exceptionMessage, exception.getMessage());
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/SortedTypesTest.java:
--------------------------------------------------------------------------------
1 | package cz.habarta.typescript.generator;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import org.junit.jupiter.api.Test;
5 |
6 | public class SortedTypesTest {
7 |
8 | @Test
9 | public void testOrder1() {
10 | assertCorrectOrder(A.class, B.class);
11 | }
12 |
13 | @Test
14 | public void testOrder2() {
15 | assertCorrectOrder(B.class, A.class);
16 | }
17 |
18 | public void assertCorrectOrder(Class>... classes) {
19 | final Settings settings = TestUtils.settings();
20 | settings.sortDeclarations = true;
21 | String expected = "" +
22 | "" + settings.newline +
23 | "interface A {" + settings.newline +
24 | " x: number;" + settings.newline +
25 | " yyy: number;" + settings.newline +
26 | "}" + settings.newline +
27 | "" + settings.newline +
28 | "interface B {" + settings.newline +
29 | " x: number;" + settings.newline +
30 | "}" + settings.newline +
31 | "";
32 | final String actual = new TypeScriptGenerator(settings).generateTypeScript(Input.from(classes));
33 |
34 | assertEquals(expected, actual);
35 | }
36 |
37 | public static class A {
38 | public int getYYY() {
39 | return -1;
40 | }
41 | public int getX() {
42 | return -1;
43 | }
44 | }
45 |
46 | public static class B {
47 | public int getX() {
48 | return -1;
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/StyleConfigurationTest.java:
--------------------------------------------------------------------------------
1 | package cz.habarta.typescript.generator;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import org.junit.jupiter.api.Test;
5 |
6 | public class StyleConfigurationTest {
7 |
8 | public static class A {
9 | public int getX() {
10 | return -1;
11 | }
12 | public B getB() {
13 | return null;
14 | }
15 | }
16 |
17 | public static class B {
18 | public String getS() {
19 | return null;
20 | }
21 | }
22 |
23 | @Test
24 | public void testTypeNameCustomizations() {
25 | final Settings settings = TestUtils.settings();
26 | settings.removeTypeNamePrefix = "Json";
27 | settings.removeTypeNameSuffix = "Class";
28 | settings.addTypeNamePrefix = "I";
29 | settings.addTypeNameSuffix = "JSON";
30 |
31 | final TsType tsType = TestUtils.compileType(settings, JsonTestClass.class);
32 | assertEquals("ITestJSON", tsType.toString());
33 | }
34 |
35 | private static class JsonTestClass {
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/TestEnums.java:
--------------------------------------------------------------------------------
1 | package cz.habarta.typescript.generator;
2 |
3 | import com.fasterxml.jackson.annotation.JsonProperty;
4 | import com.fasterxml.jackson.annotation.JsonValue;
5 |
6 | public class TestEnums {
7 | public enum StandardEnum {
8 | A, B, C
9 | }
10 |
11 | public enum GeneralMethodValuedEnum {
12 | A, B, C;
13 |
14 | @JsonValue
15 | public String getValue() {
16 | return "_" + name();
17 | }
18 | }
19 |
20 | public enum NumberFieldValuedEnum {
21 | A(1), B(2), C(3);
22 |
23 | @JsonValue
24 | private int value;
25 |
26 | NumberFieldValuedEnum(int value) {
27 | this.value = value;
28 | }
29 | }
30 |
31 | public enum NumberMethodValuedEnum {
32 | A(1), B(2), C(3);
33 |
34 | private int value;
35 |
36 | NumberMethodValuedEnum(int value) {
37 | this.value = value;
38 | }
39 |
40 | @JsonValue
41 | public int getValue() {
42 | return value;
43 | }
44 | }
45 |
46 | public enum ToStringValuedEnum {
47 | A, B, C;
48 |
49 | @JsonValue
50 | @Override
51 | public String toString() {
52 | return "_" + name();
53 | }
54 | }
55 |
56 | public enum StringPropertyValuedEnum {
57 | A, B, C;
58 |
59 | @JsonValue
60 | private final String value = "_" + name();
61 | }
62 |
63 | public enum NumberPropertyValuedEnum {
64 | A, B, C;
65 |
66 | @JsonValue
67 | private final Integer value = ordinal();
68 | }
69 |
70 | public enum JsonPropertyValuedEnum {
71 | @JsonProperty("_A") A,
72 | @JsonProperty("_B") B,
73 | @JsonProperty("_C") C
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/TestUtils.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator;
3 |
4 | import cz.habarta.typescript.generator.compiler.ModelCompiler;
5 | import java.io.IOException;
6 | import java.lang.reflect.Type;
7 | import java.nio.file.Files;
8 | import java.nio.file.Paths;
9 |
10 |
11 | public class TestUtils {
12 |
13 | private TestUtils() {
14 | }
15 |
16 | public static Settings settings() {
17 | final Settings settings = new Settings();
18 | settings.outputKind = TypeScriptOutputKind.global;
19 | settings.jsonLibrary = JsonLibrary.jackson2;
20 | settings.noFileComment = true;
21 | settings.noTslintDisable = true;
22 | settings.noEslintDisable = true;
23 | settings.newline = "\n";
24 | settings.classLoader = Thread.currentThread().getContextClassLoader();
25 | return settings;
26 | }
27 |
28 | public static TsType compileType(Settings settings, Type type) {
29 | final ModelCompiler modelCompiler = new TypeScriptGenerator(settings).getModelCompiler();
30 | return modelCompiler.javaToTypeScript(type);
31 | }
32 |
33 | public static String readFile(String file) {
34 | try {
35 | return String.join("\n", Files.readAllLines(Paths.get(file)));
36 | } catch (IOException e) {
37 | throw new RuntimeException(e);
38 | }
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/TsTypeTest.java:
--------------------------------------------------------------------------------
1 | package cz.habarta.typescript.generator;
2 |
3 | import cz.habarta.typescript.generator.TsType.BasicArrayType;
4 | import cz.habarta.typescript.generator.TsType.IndexedArrayType;
5 | import static cz.habarta.typescript.generator.TsType.Number;
6 | import cz.habarta.typescript.generator.TsType.ObjectType;
7 | import static cz.habarta.typescript.generator.TsType.String;
8 | import cz.habarta.typescript.generator.TsType.UnionType;
9 | import cz.habarta.typescript.generator.compiler.Symbol;
10 | import java.util.Arrays;
11 | import static org.junit.jupiter.api.Assertions.assertEquals;
12 | import static org.junit.jupiter.api.Assertions.assertNotEquals;
13 | import org.junit.jupiter.api.Test;
14 |
15 | public class TsTypeTest {
16 |
17 | @Test
18 | public void testEquals() {
19 | assertEquals(new TsType.ReferenceType(new Symbol(new String("Foo"))), new TsType.ReferenceType(new Symbol("Foo")));
20 | }
21 |
22 | @Test
23 | public void testNotEquals() {
24 | assertNotEquals(new TsType.ReferenceType(new Symbol("Foo")), new TsType.ReferenceType(new Symbol("Bar")));
25 | }
26 |
27 | @Test
28 | public void testNotEqualsNull() {
29 | assertNotEquals(new TsType.ReferenceType(new Symbol("Foo")), null);
30 | }
31 |
32 | @Test
33 | public void testTypeParentheses() {
34 | final Settings settings = TestUtils.settings();
35 | assertEquals("string | number", new UnionType(Arrays.asList(String, Number)).format(settings));
36 | assertEquals("string | number[]", new UnionType(Arrays.asList(String, new BasicArrayType(Number))).format(settings));
37 | assertEquals("(string | number)[]", new BasicArrayType(new UnionType(Arrays.asList(String, Number))).format(settings));
38 | assertEquals("(string | number)[][]", new BasicArrayType(new BasicArrayType(new UnionType(Arrays.asList(String, Number)))).format(settings));
39 | assertEquals("{ [index: string]: string | number }", new IndexedArrayType(String, new UnionType(Arrays.asList(String, Number))).format(settings));
40 | }
41 |
42 | @Test
43 | public void testObjectType() {
44 | final Settings settings = TestUtils.settings();
45 | assertEquals("{ a: string; b: string | number; c: {}; d: { x: string; }; }", new TsType.ObjectType(Arrays.asList(
46 | new TsProperty("a", String),
47 | new TsProperty("b", new UnionType(Arrays.asList(String, Number))),
48 | new TsProperty("c", new ObjectType(Arrays.asList())),
49 | new TsProperty("d", new ObjectType(Arrays.asList(
50 | new TsProperty("x", String)
51 | )))
52 | )).format(settings));
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/compiler/ModelCompilerUtilsTest.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.compiler;
3 |
4 | import java.util.stream.Collectors;
5 | import org.junit.jupiter.api.Assertions;
6 | import org.junit.jupiter.api.Test;
7 |
8 |
9 | public class ModelCompilerUtilsTest {
10 |
11 | @Test
12 | public void testSplitIdentifierIntoWords() {
13 | Assertions.assertEquals("Red", splitIdentifierIntoWords("Red"));
14 | Assertions.assertEquals("ATYPE", splitIdentifierIntoWords("ATYPE"));
15 | Assertions.assertEquals("camel Case Type", splitIdentifierIntoWords("camelCaseType"));
16 | Assertions.assertEquals("Pascal Case Type", splitIdentifierIntoWords("PascalCaseType"));
17 | Assertions.assertEquals("UPPER CASE TYPE", splitIdentifierIntoWords("UPPER_CASE_TYPE"));
18 | Assertions.assertEquals("XML Http Request", splitIdentifierIntoWords("XMLHttpRequest"));
19 | Assertions.assertEquals("HÁČKY A ČÁRKY", splitIdentifierIntoWords("HÁČKY_A_ČÁRKY"));
20 | Assertions.assertEquals("Háčky A Čárky", splitIdentifierIntoWords("HáčkyAČárky"));
21 | Assertions.assertEquals("String 2 Json", splitIdentifierIntoWords("String2Json"));
22 | Assertions.assertEquals("string 2 json", splitIdentifierIntoWords("string2json"));
23 | Assertions.assertEquals("version 42 final", splitIdentifierIntoWords("version42final"));
24 | }
25 |
26 | private static String splitIdentifierIntoWords(String identifier) {
27 | return ModelCompiler.splitIdentifierIntoWords(identifier).stream().collect(Collectors.joining(" "));
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/ext/BeanPropertyPathExtensionTest.java:
--------------------------------------------------------------------------------
1 | package cz.habarta.typescript.generator.ext;
2 |
3 | import cz.habarta.typescript.generator.DefaultTypeProcessor;
4 | import cz.habarta.typescript.generator.Settings;
5 | import cz.habarta.typescript.generator.TypeProcessor;
6 | import cz.habarta.typescript.generator.compiler.ModelCompiler;
7 | import cz.habarta.typescript.generator.emitter.EmitterExtension;
8 | import cz.habarta.typescript.generator.emitter.TsModel;
9 | import cz.habarta.typescript.generator.parser.Jackson2Parser;
10 | import cz.habarta.typescript.generator.parser.Model;
11 | import cz.habarta.typescript.generator.util.Utils;
12 | import org.junit.jupiter.api.Assertions;
13 | import org.junit.jupiter.api.Test;
14 |
15 | public class BeanPropertyPathExtensionTest {
16 |
17 | static class ClassA {
18 | public String field1;
19 | public ClassB field2;
20 | public ClassC field3;
21 | }
22 |
23 | static class ClassB {
24 | public int field1;
25 | }
26 |
27 | static class ClassC extends ClassB {
28 | public int field4;
29 | }
30 |
31 | @Test
32 | public void basicTest() throws Exception {
33 | final StringBuilder data = new StringBuilder();
34 | final EmitterExtension.Writer writer = new EmitterExtension.Writer() {
35 | @Override
36 | public void writeIndentedLine(String line) {
37 | data.append(line + "\n");
38 | }
39 | };
40 | final Settings settings = new Settings();
41 | settings.sortDeclarations = true;
42 | final TypeProcessor typeProcessor = new DefaultTypeProcessor();
43 | final Model model = new Jackson2Parser(settings, typeProcessor).parseModel(ClassA.class);
44 | final TsModel tsModel = new ModelCompiler(settings, typeProcessor).javaToTypeScript(model);
45 | new BeanPropertyPathExtension().emitElements(writer, settings, false, tsModel);
46 | String dataStr = data.toString();
47 | final String expected = Utils.readString(getClass().getResourceAsStream("/ext/expected.ts"), "\n");
48 | Assertions.assertEquals(expected.trim(), dataStr.trim());
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/ext/DefaultsFromInstanceExtensionTest.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.ext;
3 |
4 | import cz.habarta.typescript.generator.ClassMapping;
5 | import cz.habarta.typescript.generator.Input;
6 | import cz.habarta.typescript.generator.Settings;
7 | import cz.habarta.typescript.generator.TestUtils;
8 | import cz.habarta.typescript.generator.TypeScriptFileType;
9 | import cz.habarta.typescript.generator.TypeScriptGenerator;
10 | import java.util.Arrays;
11 | import java.util.List;
12 | import org.junit.jupiter.api.Assertions;
13 | import org.junit.jupiter.api.Test;
14 |
15 |
16 | public class DefaultsFromInstanceExtensionTest {
17 |
18 | @Test
19 | public void test() {
20 | final Settings settings = TestUtils.settings();
21 | settings.quotes = "'";
22 | settings.outputFileType = TypeScriptFileType.implementationFile;
23 | settings.mapClasses = ClassMapping.asClasses;
24 | settings.extensions.add(new DefaultsFromInstanceExtension());
25 | final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(A.class));
26 | Assertions.assertTrue(output.contains("text0: string;"));
27 | Assertions.assertTrue(output.contains("text1: string = 'hello';"));
28 | Assertions.assertTrue(output.contains("number0: number;"));
29 | Assertions.assertTrue(output.contains("number1: number = 42;"));
30 | Assertions.assertTrue(output.contains("number2: number = 42;"));
31 | Assertions.assertTrue(output.contains("list: string[];"));
32 | Assertions.assertTrue(output.contains("text2: string = 'hello2';"));
33 | }
34 |
35 | public static class A {
36 |
37 | public String text0 = null;
38 | public String text1 = "hello";
39 | public Long number0 = null;
40 | public Long number1 = 42L;
41 | public long number2 = 42L;
42 | public List list = Arrays.asList("a", "b");
43 |
44 | public String getText2() {
45 | return "hello2";
46 | }
47 |
48 | }
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/p1/A.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.p1;
3 |
4 |
5 | public class A {
6 |
7 | public String sa;
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/p1/C.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.p1;
3 |
4 | import cz.habarta.typescript.generator.p2.B;
5 |
6 |
7 | public class C extends B {
8 |
9 | public String sc;
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/p1/E.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.p1;
3 |
4 | public enum E {
5 | Left, Right
6 | }
7 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/p2/B.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.p2;
3 |
4 | import cz.habarta.typescript.generator.p1.A;
5 |
6 |
7 | public class B extends A {
8 |
9 | public String sb;
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/p2/D.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.p2;
3 |
4 | import cz.habarta.typescript.generator.p1.A;
5 | import cz.habarta.typescript.generator.p1.C;
6 | import cz.habarta.typescript.generator.p1.E;
7 |
8 |
9 | public class D {
10 |
11 | public A a;
12 | public B b;
13 | public C c;
14 | public E e;
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/parser/JaxrsApplicationParserTest.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.parser;
3 |
4 | import jakarta.ws.rs.ApplicationPath;
5 | import org.junit.jupiter.api.Assertions;
6 | import org.junit.jupiter.api.Test;
7 |
8 |
9 | public class JaxrsApplicationParserTest {
10 |
11 | @jakarta.ws.rs.ApplicationPath("testJakarta")
12 | private static class JakartaRsClass {}
13 |
14 | @javax.ws.rs.ApplicationPath("testJavax")
15 | private static class JavaxRsClass {}
16 |
17 | @Test
18 | public void testJakartaAnnotation() {
19 | final ApplicationPath annotation = JaxrsApplicationParser.getRsAnnotation(JakartaRsClass.class, jakarta.ws.rs.ApplicationPath.class);
20 | Assertions.assertNotNull(annotation);
21 | Assertions.assertEquals("testJakarta", annotation.value());
22 | }
23 |
24 | @Test
25 | public void testJavaxAnnotation() {
26 | final ApplicationPath annotation = JaxrsApplicationParser.getRsAnnotation(JavaxRsClass.class, jakarta.ws.rs.ApplicationPath.class);
27 | Assertions.assertNotNull(annotation);
28 | Assertions.assertEquals("testJavax", annotation.value());
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/java/cz/habarta/typescript/generator/yield/KeywordInPackage.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.yield;
3 |
4 |
5 | public class KeywordInPackage {
6 | }
7 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/resources/ext/OnePossiblePropertyValueAssigningExtensionTest-all.ts:
--------------------------------------------------------------------------------
1 |
2 | export class BaseClass {
3 | discriminator: "OnePossiblePropertyValueAssigningExtensionTest$SubClass" | "OnePossiblePropertyValueAssigningExtensionTest$OtherSubClass";
4 | field1: number;
5 | readonly field2: OneValueEnum;
6 |
7 | constructor() {
8 | this.field2 = "MY_VALUE";
9 | }
10 | }
11 |
12 | export class OtherSubClass extends BaseClass {
13 | readonly discriminator: "OnePossiblePropertyValueAssigningExtensionTest$OtherSubClass";
14 | readonly enumField1: OneValueEnum;
15 | enumField2: TwoValueEnum;
16 | testField2: string;
17 |
18 | constructor() {
19 | super();
20 | this.discriminator = "OnePossiblePropertyValueAssigningExtensionTest$OtherSubClass";
21 | this.enumField1 = "MY_VALUE";
22 | }
23 | }
24 |
25 | export class SubClass extends BaseClass {
26 | readonly discriminator: "OnePossiblePropertyValueAssigningExtensionTest$SubClass";
27 | testField1: string;
28 |
29 | constructor() {
30 | super();
31 | this.discriminator = "OnePossiblePropertyValueAssigningExtensionTest$SubClass";
32 | }
33 | }
34 |
35 | export type OneValueEnum = "MY_VALUE";
36 |
37 | export type TwoValueEnum = "ONE" | "TWO";
38 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/resources/ext/RequiredPropertyConstructorExtensionTest-basicWithConfiguration.ts:
--------------------------------------------------------------------------------
1 | /* tslint:disable */
2 |
3 | export class OtherClass {
4 | readonly field2: string;
5 |
6 | constructor(field2: string) {
7 | this.field2 = field2;
8 | }
9 | }
10 |
11 | export class PolymorphicClass implements SuperInterface {
12 | readonly discriminator: "class-b";
13 | readonly field1: number;
14 | }
15 |
16 | export class SimpleClass {
17 | readonly field1: string;
18 | readonly field2: PolymorphicClass;
19 |
20 | constructor(field1: string, field2: PolymorphicClass) {
21 | this.field1 = field1;
22 | this.field2 = field2;
23 | }
24 | }
25 |
26 | export interface SuperInterface {
27 | readonly discriminator: "class-b";
28 | }
29 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/resources/ext/RequiredPropertyConstructorExtensionTest-basicWithReadOnly.ts:
--------------------------------------------------------------------------------
1 | /* tslint:disable */
2 |
3 | export class PolymorphicClass implements SuperInterface {
4 | readonly discriminator: "class-b";
5 | readonly field1: number;
6 |
7 | constructor(field1: number) {
8 | this.discriminator = "class-b";
9 | this.field1 = field1;
10 | }
11 | }
12 |
13 | export class SimpleClass {
14 | readonly field1: string;
15 | readonly field2: PolymorphicClass;
16 |
17 | constructor(field1: string, field2: PolymorphicClass) {
18 | this.field1 = field1;
19 | this.field2 = field2;
20 | }
21 | }
22 |
23 | export interface SuperInterface {
24 | readonly discriminator: "class-b";
25 | }
26 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/resources/ext/RequiredPropertyConstructorExtensionTest-basicWithoutReadOnly.ts:
--------------------------------------------------------------------------------
1 | /* tslint:disable */
2 |
3 | export class PolymorphicClass implements SuperInterface {
4 | discriminator: "class-b";
5 | field1: number;
6 | }
7 |
8 | export class SimpleClass {
9 | field1: string;
10 | field2: PolymorphicClass;
11 | }
12 |
13 | export interface SuperInterface {
14 | discriminator: "class-b";
15 | }
16 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/resources/ext/RequiredPropertyConstructorExtensionTest-enums.ts:
--------------------------------------------------------------------------------
1 | /* tslint:disable */
2 |
3 | export class MultipleEnumContainerClass {
4 | readonly multiple: MultipleEntryEnum;
5 |
6 | constructor(multiple: MultipleEntryEnum) {
7 | this.multiple = multiple;
8 | }
9 | }
10 |
11 | export class SingleEnumContainerClass {
12 | readonly single: SingleEntryEnum;
13 |
14 | constructor() {
15 | this.single = "ENTRY_1";
16 | }
17 | }
18 |
19 | export type MultipleEntryEnum = "ENTRY_1" | "ENTRY_2" | "ENTRY_3";
20 |
21 | export type SingleEntryEnum = "ENTRY_1";
22 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/resources/ext/RequiredPropertyConstructorExtensionTest-inheritance.ts:
--------------------------------------------------------------------------------
1 | /* tslint:disable */
2 |
3 | export class PolymorphicClass implements SuperInterface {
4 | readonly discriminator: "class-b";
5 | readonly field1: number;
6 |
7 | constructor(field1: number) {
8 | this.discriminator = "class-b";
9 | this.field1 = field1;
10 | }
11 | }
12 |
13 | export class SimpleClass {
14 | readonly field1: string;
15 | readonly field2: PolymorphicClass;
16 |
17 | constructor(field1: string, field2: PolymorphicClass) {
18 | this.field1 = field1;
19 | this.field2 = field2;
20 | }
21 | }
22 |
23 | export class SecondClass extends SimpleClass {
24 | readonly field3: number;
25 |
26 | constructor(field1: string, field2: PolymorphicClass, field3: number) {
27 | super(field1, field2);
28 | this.field3 = field3;
29 | }
30 | }
31 |
32 | export interface SuperInterface {
33 | readonly discriminator: "class-b";
34 | }
35 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/resources/ext/RequiredPropertyConstructorExtensionTest-optionalParameters.ts:
--------------------------------------------------------------------------------
1 | /* tslint:disable */
2 |
3 | export class SimpleOptionalClass {
4 | readonly field1: string;
5 | readonly field2?: number;
6 |
7 | constructor(field1: string, field2?: number) {
8 | this.field1 = field1;
9 | this.field2 = field2;
10 | }
11 | }
12 |
13 | export class SecondOptionalClass extends SimpleOptionalClass {
14 | readonly field3: string;
15 |
16 | constructor(field1: string, field3: string, field2?: number) {
17 | super(field1, field2);
18 | this.field3 = field3;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/resources/ext/expected.ts:
--------------------------------------------------------------------------------
1 |
2 | export class Fields {
3 | protected $$parent: Fields | undefined;
4 | protected $$name: string;
5 | constructor(parent?: Fields, name?: string) {
6 | this.$$parent = parent;
7 | this.$$name = name || '';
8 | };
9 | get(): string {
10 | if (this.$$parent && this.$$parent.get().length > 0) {
11 | return this.$$parent.get() + "." + this.$$name;
12 | } else {
13 | return this.$$name;
14 | }
15 | }
16 | }
17 |
18 | class ClassAFields extends Fields {
19 | constructor(parent?: Fields, name?: string) { super(parent, name); }
20 | field1 = new Fields(this, "field1");
21 | field2 = new ClassBFields(this, "field2");
22 | field3 = new ClassCFields(this, "field3");
23 | }
24 |
25 | class ClassBFields extends Fields {
26 | constructor(parent?: Fields, name?: string) { super(parent, name); }
27 | field1 = new Fields(this, "field1");
28 | }
29 |
30 | class ClassCFields extends ClassBFields {
31 | constructor(parent?: Fields, name?: string) { super(parent, name); }
32 | field4 = new Fields(this, "field4");
33 | }
34 | const ClassA = new ClassAFields();
35 | const ClassB = new ClassBFields();
36 | const ClassC = new ClassCFields();
37 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/ts/JsonDeserializationTest/JsonDeserializationTest-expected-test-data.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "name1",
3 | "authentication": "Password",
4 | "childAccount": true,
5 | "age": 42,
6 | "address": {
7 | "street": "street1",
8 | "city": "city1"
9 | },
10 | "addresses": [
11 | {
12 | "street": "street2",
13 | "city": "city2"
14 | }
15 | ],
16 | "taggedAddresses": {
17 | "address3": {
18 | "street": "street3",
19 | "city": "city3"
20 | }
21 | },
22 | "groupedAddresses": {
23 | "addresses4": [
24 | {
25 | "street": "street5",
26 | "city": "city5"
27 | }
28 | ]
29 | },
30 | "listOfTaggedAddresses": [
31 | {
32 | "address6": {
33 | "street": "street6",
34 | "city": "city6"
35 | }
36 | }
37 | ],
38 | "tags": [
39 | "item"
40 | ],
41 | "mapping": {
42 | "key": "value"
43 | },
44 | "listOfListOfString": [
45 | [
46 | "string"
47 | ]
48 | ],
49 | "orders": {
50 | "page": 7,
51 | "items": [
52 | {
53 | "id": "id7"
54 | }
55 | ],
56 | "additionalInfo": "Token"
57 | },
58 | "allOrders": [
59 | {
60 | "page": 8,
61 | "items": [
62 | {
63 | "id": "id8"
64 | }
65 | ],
66 | "additionalInfo": "Fingerprint"
67 | }
68 | ],
69 | "shape": {
70 | "kind": "square",
71 | "metadata": {
72 | "group": "group9"
73 | },
74 | "size": 9
75 | },
76 | "shapes": [
77 | {
78 | "kind": "rectangle",
79 | "metadata": {
80 | "group": "group10"
81 | },
82 | "width": 10,
83 | "height": 10
84 | }
85 | ]
86 | }
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/ts/JsonDeserializationTest/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "module": "commonjs",
4 | "target": "es5",
5 | "noImplicitAny": true,
6 | "sourceMap": true,
7 | "strict": true,
8 | "strictPropertyInitialization": false
9 | }
10 | }
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/ts/module-usage.ts:
--------------------------------------------------------------------------------
1 |
2 | ///
3 | ///
4 | ///
5 | ///
6 | ///
7 | ///
8 |
9 | // declaration files
10 |
11 | var a1: Test1Data;
12 | var e1: Test1Direction;
13 | var ne1: Test1Align;
14 |
15 | var a2: NS2.Test2Data;
16 | var e2: NS2.Test2Direction;
17 | var ne2: NS2.Test2Align;
18 |
19 | import * as mod3a from "mod3a";
20 | var a3a: mod3a.Test3aData;
21 | var e3a: mod3a.Test3aDirection;
22 | var ne3a: mod3a.Test3aAlign;
23 |
24 | import * as mod3b from "../../../target/test-ts-modules/test-mn3b";
25 | var a3b: mod3b.Test3bData;
26 | var e3b: mod3b.Test3bDirection;
27 | var ne3b: mod3b.Test3bAlign;
28 |
29 | import * as mod4a from "mod4a";
30 | var a4a: mod4a.NS4a.Test4aData;
31 | var e4a: mod4a.NS4a.Test4aDirection;
32 | var ne4a: mod4a.NS4a.Test4aAlign;
33 |
34 | import * as mod4b from "../../../target/test-ts-modules/test-mn4b";
35 | var a4b: mod4b.NS4b.Test4bData;
36 | var e4b: mod4b.NS4b.Test4bDirection;
37 | var ne4b: mod4b.NS4b.Test4bAlign;
38 |
39 |
40 | // implementation files
41 |
42 | var a5: Test5Data;
43 | var e5: Test5Direction;
44 | var ne5: Test5Align;
45 | test();
46 |
47 | var a6: NS6.Test6Data;
48 | var e6: NS6.Test6Direction;
49 | var ne6: NS6.Test6Align;
50 | NS6.test();
51 |
52 | import * as mod7 from "../../../target/test-ts-modules/test-mn7";
53 | var a7: mod7.Test7Data;
54 | var e7: mod7.Test7Direction;
55 | var ne7: mod7.Test7Align;
56 | mod7.test();
57 |
58 | import * as mod8 from "../../../target/test-ts-modules/test-mn8";
59 | var a8: mod8.NS8.Test8Data;
60 | var e8: mod8.NS8.Test8Direction;
61 | var ne8: mod8.NS8.Test8Align;
62 | mod8.NS8.test();
63 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/ts/my-custom-types.d.ts:
--------------------------------------------------------------------------------
1 | // used in CustomTypeMappingTest
2 |
3 | type MyDate = string;
4 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/ts/my-module.d.ts:
--------------------------------------------------------------------------------
1 | // used in CustomTypeMappingTest
2 |
3 | export type MyCalendar = string;
4 |
--------------------------------------------------------------------------------
/typescript-generator-core/src/test/ts/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "module": "commonjs",
4 | "target": "es5",
5 | "noImplicitAny": true,
6 | "sourceMap": true,
7 | "noEmit": true
8 | },
9 | "files": [
10 | "module-usage.ts",
11 | // "../../../target/test-ts-modules/test-mn1.d.ts",
12 | // "../../../target/test-ts-modules/test-mn2.d.ts",
13 | // "../../../target/test-ts-modules/test-mn3a.d.ts",
14 | // "../../../target/test-ts-modules/test-mn3b.d.ts",
15 | // "../../../target/test-ts-modules/test-mn4a.d.ts",
16 | // "../../../target/test-ts-modules/test-mn4b.d.ts",
17 | // "../../../target/test-ts-modules/test-mn5.ts",
18 | // "../../../target/test-ts-modules/test-mn6.ts",
19 | // "../../../target/test-ts-modules/test-mn7.ts",
20 | // "../../../target/test-ts-modules/test-mn8.ts",
21 | "module-usage-pkg.ts"
22 | // "../../../target/test-ts-modules-pkg/test-mn1.d.ts",
23 | // "../../../target/test-ts-modules-pkg/test-mn2.d.ts",
24 | // "../../../target/test-ts-modules-pkg/test-mn3a.d.ts",
25 | // "../../../target/test-ts-modules-pkg/test-mn3b.d.ts",
26 | // "../../../target/test-ts-modules-pkg/test-mn4a.d.ts",
27 | // "../../../target/test-ts-modules-pkg/test-mn4b.d.ts",
28 | // "../../../target/test-ts-modules-pkg/test-mn5.ts",
29 | // "../../../target/test-ts-modules-pkg/test-mn6.ts",
30 | // "../../../target/test-ts-modules-pkg/test-mn7.ts",
31 | // "../../../target/test-ts-modules-pkg/test-mn8.ts"
32 | ]
33 | }
--------------------------------------------------------------------------------
/typescript-generator-gradle-plugin/src/main/java/cz/habarta/typescript/generator/gradle/TypeScriptGeneratorPlugin.java:
--------------------------------------------------------------------------------
1 |
2 | package cz.habarta.typescript.generator.gradle;
3 |
4 | import java.util.Collections;
5 | import org.gradle.api.Plugin;
6 | import org.gradle.api.Project;
7 | import org.gradle.api.Task;
8 |
9 |
10 | public class TypeScriptGeneratorPlugin implements Plugin {
11 |
12 | @Override
13 | public void apply(Project project) {
14 | final Task generateTsTask = project.task(Collections.singletonMap(Task.TASK_TYPE, GenerateTask.class), "generateTypeScript");
15 |
16 | for (Task task : project.getTasks()) {
17 | if (task.getName().startsWith("compile") && !task.getName().startsWith("compileTest")) {
18 | generateTsTask.dependsOn(task.getName());
19 | generateTsTask.getInputs().files(task);
20 | }
21 | }
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/typescript-generator-gradle-plugin/src/main/resources/META-INF/gradle-plugins/cz.habarta.typescript-generator.properties:
--------------------------------------------------------------------------------
1 | implementation-class=cz.habarta.typescript.generator.gradle.TypeScriptGeneratorPlugin
2 |
--------------------------------------------------------------------------------
/typescript-generator-maven-plugin/src/site/markdown/index.md:
--------------------------------------------------------------------------------
1 | ## About
2 |
3 | The _typescript-generator-maven-plugin_ let you generate TypeScript declaration file from specified Java classes.
4 |
5 | The plugin has a [generate](generate-mojo.html) goal.
6 |
7 | You can find detailed description how it works on GitHub [typescript-generator](https://github.com/vojtechhabarta/typescript-generator) project.
8 |
--------------------------------------------------------------------------------
/typescript-generator-maven-plugin/src/site/site.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 | org.apache.maven.skins
10 | maven-fluido-skin
11 | 1.6
12 |
13 |
14 |
15 | false
16 | true
17 |
18 |