Compare commits
10
Commits
48b8538527
...
v1.0-rc11
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5780337b08 | ||
|
|
fc87ef4834 | ||
|
|
82672e97bf | ||
|
|
9a288d7728 | ||
|
|
21556018c8 | ||
|
|
22a8761f14 | ||
|
|
db6f311bfb | ||
|
|
6ab2e4082e | ||
|
|
e23373f73b | ||
|
|
0194b262c7 |
No files matched your search
@@ -17,7 +17,10 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
fetch-tags: true
|
||||||
- name: Set up JDK 21
|
- name: Set up JDK 21
|
||||||
uses: actions/setup-java@v3
|
uses: actions/setup-java@v3
|
||||||
with:
|
with:
|
||||||
@@ -34,18 +37,6 @@ jobs:
|
|||||||
working-directory: ${{ github.workspace }}
|
working-directory: ${{ github.workspace }}
|
||||||
run: ls -la
|
run: ls -la
|
||||||
|
|
||||||
- name: Set library version
|
|
||||||
working-directory: ${{ github.workspace }}
|
|
||||||
run: |
|
|
||||||
if [ -n "${{ github.event.release.tag_name }}" ]; then
|
|
||||||
version=$(echo ${{ github.event.release.tag_name }} | sed 's/^v//')
|
|
||||||
sed -i "s/version = \".*\"/version = \"$version\"/g" build.gradle.kts
|
|
||||||
grep -o "version = \"$version\"" build.gradle.kts
|
|
||||||
else
|
|
||||||
echo "No release tag found. Skipping library version update."
|
|
||||||
fi
|
|
||||||
|
|
||||||
|
|
||||||
- name: Initialize Gradle wrapper
|
- name: Initialize Gradle wrapper
|
||||||
run: ./gradlew wrapper
|
run: ./gradlew wrapper
|
||||||
|
|
||||||
|
|||||||
+27
-16
@@ -1,34 +1,49 @@
|
|||||||
plugins {
|
plugins {
|
||||||
kotlin("jvm") version "2.3.21"
|
kotlin("jvm") version "2.2.21"
|
||||||
id("maven-publish")
|
id("maven-publish")
|
||||||
`java-gradle-plugin`
|
`java-gradle-plugin`
|
||||||
`kotlin-dsl`
|
`kotlin-dsl`
|
||||||
}
|
}
|
||||||
|
|
||||||
group = "no.iktdev"
|
val dynamicVersion: String by lazy {
|
||||||
version = "1.0-SNAPSHOT"
|
val githubRef = System.getenv("GITHUB_REF") ?: ""
|
||||||
val named = "ts-gen"
|
val releaseTag = System.getenv("GITHUB_REF_NAME") ?: ""
|
||||||
|
val eventName = System.getenv("GITHUB_EVENT_NAME") ?: ""
|
||||||
|
|
||||||
val dynamicVersion = providers.provider {
|
// Hvis det er en release eller tag-push i GitHub Actions, bruk taggen direkte
|
||||||
val ref = System.getenv("GITHUB_REF") ?: ""
|
if ((eventName == "release" || githubRef.startsWith("refs/tags/")) && releaseTag.isNotBlank()) {
|
||||||
val isSnapshot = ref.endsWith("/master") || ref.endsWith("/main")
|
releaseTag.removePrefix("v")
|
||||||
|
} else {
|
||||||
|
// Lokalt eller ved vanlig push til main/master: Beregn dynamisk SNAPSHOT via git
|
||||||
|
try {
|
||||||
|
val isSnapshot = githubRef.endsWith("/master") || githubRef.endsWith("/main") || githubRef.isEmpty()
|
||||||
val latestTag = providers.exec {
|
val latestTag = providers.exec {
|
||||||
commandLine("git", "describe", "--tags", "--abbrev=0")
|
commandLine("git", "describe", "--tags", "--abbrev=0")
|
||||||
}.standardOutput.asText.getOrElse("0.0.0").trim().removePrefix("v")
|
}.standardOutput.asText.get().trim().removePrefix("v")
|
||||||
|
|
||||||
if (isSnapshot) {
|
if (isSnapshot) {
|
||||||
val parts = latestTag.split(".")
|
val parts = latestTag.split(".")
|
||||||
val patch = parts.lastOrNull()?.toIntOrNull()?.plus(1) ?: 1
|
val patch = parts.lastOrNull()?.toIntOrNull()?.plus(1) ?: 1
|
||||||
val base = if (parts.size >= 2) "${parts[0]}.${parts[1]}" else latestTag
|
val base = if (parts.size >= 2) "${parts.first()}.${parts[1]}" else latestTag
|
||||||
val buildNumber = providers.exec {
|
val buildNumber = providers.exec {
|
||||||
commandLine("git", "rev-list", "v$latestTag..HEAD", "--count")
|
commandLine("git", "rev-list", "v$latestTag..HEAD", "--count")
|
||||||
}.standardOutput.asText.getOrElse("0").trim().toIntOrNull() ?: 0
|
}.standardOutput.asText.get().trim().toIntOrNull() ?: 0
|
||||||
|
|
||||||
"$base.$patch-SNAPSHOT-$buildNumber"
|
"$base.$patch-SNAPSHOT-$buildNumber"
|
||||||
} else {
|
} else {
|
||||||
latestTag
|
latestTag
|
||||||
}
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
"0.0.1-SNAPSHOT"
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
group = "no.iktdev"
|
||||||
|
version = dynamicVersion
|
||||||
|
val named = "ts-gen"
|
||||||
|
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
}
|
}
|
||||||
@@ -66,11 +81,7 @@ tasks.jar {
|
|||||||
manifest {
|
manifest {
|
||||||
attributes(
|
attributes(
|
||||||
"Implementation-Title" to project.name,
|
"Implementation-Title" to project.name,
|
||||||
// Bruk en provider for å hente dynamisk versjon, slik at den ikke blir fastlåst til "1.0-SNAPSHOT"
|
"Implementation-Version" to project.version
|
||||||
"Implementation-Version" to provider {
|
|
||||||
// Hvis du har definert dynamicVersion som en lokal val, kan du kalle .get() på den her:
|
|
||||||
dynamicVersion.get()
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -96,7 +107,7 @@ publishing {
|
|||||||
if (name == "pluginMaven") {
|
if (name == "pluginMaven") {
|
||||||
groupId = "no.iktdev"
|
groupId = "no.iktdev"
|
||||||
artifactId = "ts-gen"
|
artifactId = "ts-gen"
|
||||||
version = dynamicVersion.get()
|
version = project.version.toString()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,4 +38,13 @@ class ClassScanner {
|
|||||||
|
|
||||||
return classes
|
return classes
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun scan(packageName: String, includeClasses: Collection<String>, classLoader: ClassLoader): List<KClass<*>> =
|
||||||
|
(scan(packageName, classLoader) + includeClasses.map { className ->
|
||||||
|
try {
|
||||||
|
Class.forName(className, false, classLoader).kotlin
|
||||||
|
} catch (e: ClassNotFoundException) {
|
||||||
|
throw IllegalArgumentException("Included class '$className' was not found", e)
|
||||||
|
}
|
||||||
|
}).distinctBy { it.qualifiedName }
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package no.iktdev.ts
|
||||||
|
|
||||||
|
enum class MapStrategy {
|
||||||
|
MapAsPartialRecord,
|
||||||
|
MapAsRecord
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package no.iktdev.ts
|
||||||
|
|
||||||
|
enum class SealedStrategy {
|
||||||
|
AS_INTERFACE, // Lager kun interfacet (og eventuelt union) uten automatisk type-felt
|
||||||
|
AS_INTERFACE_WITH_TYPE,// Lager interface + union + automatisk type-felt på subtypene
|
||||||
|
ONLY_TYPED // Lager kun unionen/typene uten base-interface
|
||||||
|
}
|
||||||
@@ -3,29 +3,31 @@ package no.iktdev.ts
|
|||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
||||||
object TsGenerator {
|
object TsGenerator {
|
||||||
var consumerAppVersionInfo: String = "unknown"
|
var versionInfo: String = System.getProperty("tsgenerator.version")
|
||||||
var versionInfo: String = TsGenerator::class.java.getPackage()?.implementationVersion
|
?: TsGenerator::class.java.getPackage()?.implementationVersion
|
||||||
?: TsGenerator::class.java.getResource("/META-INF/MANIFEST.MF")?.let {
|
?: "any"
|
||||||
// Alternativ fallback hvis du vil lese manifest-streamen direkte,
|
|
||||||
// men pakke-sjekken under dekker de fleste tilfeller når den er bygget.
|
|
||||||
null
|
|
||||||
}
|
|
||||||
?: "1.0.0" // Hardkodet fallback eller "unknown"
|
|
||||||
var buildTime: String = java.time.Instant.now().toString()
|
var buildTime: String = java.time.Instant.now().toString()
|
||||||
|
|
||||||
val ttm = TsTypeMapper()
|
|
||||||
val tmr = TsModelRenderer()
|
val tmr = TsModelRenderer()
|
||||||
|
|
||||||
fun generate(
|
fun generate(
|
||||||
packageName: String,
|
packageName: String,
|
||||||
output: File,
|
output: File,
|
||||||
classLoader: ClassLoader = Thread.currentThread().contextClassLoader,
|
classLoader: ClassLoader = Thread.currentThread().contextClassLoader,
|
||||||
includeSealed: Boolean = true,
|
writeSealedStrategy: SealedStrategy,
|
||||||
includeInterface: Boolean = true
|
) = generate(packageName, emptyList(), output, classLoader, writeSealedStrategy)
|
||||||
|
|
||||||
|
fun generate(
|
||||||
|
packageName: String,
|
||||||
|
includeClasses: Collection<String>,
|
||||||
|
output: File,
|
||||||
|
classLoader: ClassLoader = Thread.currentThread().contextClassLoader,
|
||||||
|
writeSealedStrategy: SealedStrategy,
|
||||||
) {
|
) {
|
||||||
println("TsGenerator: scanning package: $packageName")
|
println("TsGenerator: scanning package: $packageName")
|
||||||
|
if (includeClasses.isNotEmpty()) println("TsGenerator: including classes: ${includeClasses.joinToString()}")
|
||||||
|
|
||||||
val classes = ClassScanner().scan(packageName, classLoader)
|
val classes = ClassScanner().scan(packageName, includeClasses, classLoader)
|
||||||
|
|
||||||
println("TsGenerator: found ${classes.size} classes total")
|
println("TsGenerator: found ${classes.size} classes total")
|
||||||
classes.forEach { println(" - ${it.qualifiedName}") }
|
classes.forEach { println(" - ${it.qualifiedName}") }
|
||||||
@@ -33,43 +35,48 @@ object TsGenerator {
|
|||||||
val ts = buildString {
|
val ts = buildString {
|
||||||
appendLine("// AUTO-GENERATED. DO NOT EDIT.")
|
appendLine("// AUTO-GENERATED. DO NOT EDIT.")
|
||||||
appendLine("// TSGenerator Version: $versionInfo")
|
appendLine("// TSGenerator Version: $versionInfo")
|
||||||
appendLine("// Consumer App Version: $consumerAppVersionInfo")
|
appendLine("// package: $packageName")
|
||||||
appendLine("// Time: $buildTime")
|
appendLine("// includeClasses:")
|
||||||
appendLine("// Source: $packageName")
|
includeClasses
|
||||||
|
.filter { it.isNotBlank() }
|
||||||
|
.distinct()
|
||||||
|
.forEach { appendLine("//\t$it") }
|
||||||
appendLine()
|
appendLine()
|
||||||
|
|
||||||
classes.forEach { cls ->
|
classes.forEach { cls ->
|
||||||
when {
|
when {
|
||||||
// ----------------------------------------------------
|
// ----------------------------------------------------
|
||||||
// 1) Sealed interface → union type alias
|
// 1) Sealed interface → union type alias + evt. base interface
|
||||||
// ----------------------------------------------------
|
// ----------------------------------------------------
|
||||||
cls.isSealed && cls.java.isInterface -> {
|
cls.isSealed && cls.java.isInterface -> {
|
||||||
val subTypes = cls.sealedSubclasses
|
println("Generating sealed interface: ${cls.simpleName}")
|
||||||
.mapNotNull { it.simpleName }
|
append(tmr.sealedUnionToTs(cls, writeSealedStrategy))
|
||||||
.joinToString(" | ")
|
|
||||||
|
|
||||||
println("Generating union type for sealed interface: ${cls.simpleName} = $subTypes")
|
|
||||||
appendLine("export type ${cls.simpleName} = $subTypes")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 1a) Sealed class → union type alias
|
// ----------------------------------------------------
|
||||||
|
// 1a) Sealed class → union type alias + evt. base interface
|
||||||
|
// ----------------------------------------------------
|
||||||
cls.isSealed && !cls.java.isInterface -> {
|
cls.isSealed && !cls.java.isInterface -> {
|
||||||
val subTypes = cls.sealedSubclasses
|
println("Generating sealed class: ${cls.simpleName}")
|
||||||
.mapNotNull { it.simpleName }
|
append(tmr.sealedUnionToTs(cls, writeSealedStrategy))
|
||||||
.joinToString(" | ")
|
|
||||||
|
|
||||||
println("Generating union type for sealed class: ${cls.simpleName} = $subTypes")
|
|
||||||
appendLine("export type ${cls.simpleName} = $subTypes")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// ----------------------------------------------------
|
// ----------------------------------------------------
|
||||||
// 1b) Sealed subtype (data object / data class)
|
// 1b) Sealed subtype (data object / data class)
|
||||||
// → generer interface selv uten properties
|
// Sjekker strategien for type-felt og extends-base
|
||||||
// ----------------------------------------------------
|
// ----------------------------------------------------
|
||||||
cls.isSealedSubtype() -> {
|
cls.isSealedSubtype() -> {
|
||||||
println("Generating sealed subtype interface: ${cls.simpleName}")
|
println("Generating sealed subtype interface: ${cls.simpleName}")
|
||||||
append(tmr.sealedSubtypeToTs(cls, ttm, includeSealed))
|
|
||||||
|
// Finn baseklassen/interfacet hvis strategien tillater det
|
||||||
|
val baseName = if (writeSealedStrategy != SealedStrategy.ONLY_TYPED) {
|
||||||
|
cls.java.superclass?.kotlin?.takeIf { it.isSealed }?.simpleName
|
||||||
|
?: cls.java.interfaces.map { it.kotlin }.firstOrNull { it.isSealed }?.simpleName
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
append(tmr.sealedSubtypeToTs(cls, writeSealedStrategy, baseName))
|
||||||
}
|
}
|
||||||
|
|
||||||
// ----------------------------------------------------
|
// ----------------------------------------------------
|
||||||
@@ -81,11 +88,11 @@ object TsGenerator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ----------------------------------------------------
|
// ----------------------------------------------------
|
||||||
// 3) Data class → interface
|
// 3) Data class → interface (vanlige klasser)
|
||||||
// ----------------------------------------------------
|
// ----------------------------------------------------
|
||||||
cls.hasProperties() && !cls.isSealed -> {
|
cls.hasProperties() && !cls.isSealed -> {
|
||||||
println("Generating interface: ${cls.simpleName}")
|
println("Generating interface: ${cls.simpleName}")
|
||||||
append(tmr.dataClassToTs(cls, ttm, includeInterface))
|
append(tmr.dataClassToTs(cls))
|
||||||
}
|
}
|
||||||
|
|
||||||
else -> {
|
else -> {
|
||||||
@@ -101,5 +108,4 @@ object TsGenerator {
|
|||||||
|
|
||||||
println("TsGenerator: wrote file to ${output.absolutePath}")
|
println("TsGenerator: wrote file to ${output.absolutePath}")
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
package no.iktdev.ts
|
package no.iktdev.ts
|
||||||
|
|
||||||
|
import no.iktdev.ts.anno.TsMapStrategy
|
||||||
import kotlin.reflect.KClass
|
import kotlin.reflect.KClass
|
||||||
|
import kotlin.reflect.full.findAnnotation
|
||||||
import kotlin.reflect.full.memberProperties
|
import kotlin.reflect.full.memberProperties
|
||||||
import kotlin.reflect.full.primaryConstructor
|
import kotlin.reflect.full.primaryConstructor
|
||||||
|
|
||||||
@@ -13,14 +15,66 @@ class TsModelRenderer {
|
|||||||
return "export type ${cls.simpleName} = $values\n"
|
return "export type ${cls.simpleName} = $values\n"
|
||||||
}
|
}
|
||||||
|
|
||||||
fun sealedSubtypeToTs(cls: KClass<*>, ttm: TsTypeMapper, includeTypeDiscriminator: Boolean): String {
|
// Genererer base-interface (hvis ikke ONLY_TYPED) og union-typen
|
||||||
return dataClassToTs(cls, ttm, includeTypeDiscriminator)
|
fun sealedUnionToTs(
|
||||||
|
cls: KClass<*>,
|
||||||
|
strategy: SealedStrategy
|
||||||
|
): String {
|
||||||
|
val subTypes = cls.sealedSubclasses
|
||||||
|
.mapNotNull { it.simpleName }
|
||||||
|
.joinToString(" | ")
|
||||||
|
|
||||||
|
if (strategy == SealedStrategy.ONLY_TYPED) {
|
||||||
|
return "export type ${cls.simpleName} = $subTypes\n"
|
||||||
}
|
}
|
||||||
|
|
||||||
fun dataClassToTs(cls: KClass<*>, ttm: TsTypeMapper, includeTypeDiscriminator: Boolean): String {
|
// AS_INTERFACE og AS_INTERFACE_WITH_TYPE lager base-interfacet for sealed-klassen
|
||||||
val typeParams = cls.typeParameters.map { it.name }
|
val superClasses = getSuperClasses(cls)
|
||||||
val generic = if (typeParams.isNotEmpty()) "<" + typeParams.joinToString(", ") + ">" else ""
|
val extendsClause = getExtendsClause(superClasses, null)
|
||||||
|
val inheritedPropNames = superClasses.flatMap { it.memberProperties }.map { it.name }.toSet()
|
||||||
|
|
||||||
|
val baseInterface = buildInterfaceString(cls, inheritedPropNames, extendsClause, null)
|
||||||
|
val unionType = "export type ${cls.simpleName}Ref = $subTypes\n"
|
||||||
|
|
||||||
|
return listOf(baseInterface, unionType).filter { it.isNotBlank() }.joinToString("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sealed subtype renderer som respekterer om vi skal ha type-felt eller ikke
|
||||||
|
fun sealedSubtypeToTs(
|
||||||
|
cls: KClass<*>,
|
||||||
|
strategy: SealedStrategy,
|
||||||
|
extendsBaseName: String?
|
||||||
|
): String {
|
||||||
|
// Hvis ONLY_TYPED, skal den ikke arve fra eller filtrere ut felter fra baseklassen
|
||||||
|
val superClasses = if (strategy == SealedStrategy.ONLY_TYPED) emptyList() else getSuperClasses(cls)
|
||||||
|
|
||||||
|
// Kun AS_INTERFACE_WITH_TYPE og AS_INTERFACE skal arve fra baseklassen
|
||||||
|
val extraExtends = if (strategy != SealedStrategy.ONLY_TYPED) extendsBaseName else null
|
||||||
|
val extendsClause = getExtendsClause(superClasses, extraExtends)
|
||||||
|
val inheritedPropNames = if (strategy == SealedStrategy.ONLY_TYPED) emptySet() else superClasses.flatMap { it.memberProperties }.map { it.name }.toSet()
|
||||||
|
|
||||||
|
// Type-literalen tvinges KUN på hvis strategien er AS_INTERFACE_WITH_TYPE
|
||||||
|
val typeLiteral = if (strategy == SealedStrategy.AS_INTERFACE_WITH_TYPE) {
|
||||||
|
getDefaultTypeLiteral(cls) ?: cls.simpleName
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
return buildInterfaceString(cls, inheritedPropNames, extendsClause, typeLiteral)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ordinær data-klasse / interface renderer
|
||||||
|
fun dataClassToTs(cls: KClass<*>): String {
|
||||||
|
val superClasses = getSuperClasses(cls)
|
||||||
|
val extendsClause = getExtendsClause(superClasses, null)
|
||||||
|
val inheritedPropNames = superClasses.flatMap { it.memberProperties }.map { it.name }.toSet()
|
||||||
|
|
||||||
|
return buildInterfaceString(cls, inheritedPropNames, extendsClause, null)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Felles hjelpemetoder ---
|
||||||
|
|
||||||
|
private fun getSuperClasses(cls: KClass<*>): List<KClass<*>> {
|
||||||
val superClasses = mutableListOf<KClass<*>>()
|
val superClasses = mutableListOf<KClass<*>>()
|
||||||
val superClass = cls.java.superclass?.kotlin
|
val superClass = cls.java.superclass?.kotlin
|
||||||
if (superClass != null && superClass != Any::class) {
|
if (superClass != null && superClass != Any::class) {
|
||||||
@@ -32,36 +86,71 @@ class TsModelRenderer {
|
|||||||
.filter { it.simpleName != "Any" && it.simpleName != "Serializable" }
|
.filter { it.simpleName != "Any" && it.simpleName != "Serializable" }
|
||||||
|
|
||||||
superClasses.addAll(superInterfaces)
|
superClasses.addAll(superInterfaces)
|
||||||
|
return superClasses
|
||||||
|
}
|
||||||
|
|
||||||
val extendsClause = if (superClasses.isNotEmpty()) {
|
private fun getExtendsClause(superClasses: List<KClass<*>>, extraExtends: String?): String {
|
||||||
" extends ${superClasses.joinToString(", ") { it.simpleName!! }}"
|
val names = superClasses.map { it.simpleName!! }.toMutableList()
|
||||||
|
if (extraExtends != null && extraExtends !in names) {
|
||||||
|
names.add(extraExtends)
|
||||||
|
}
|
||||||
|
return if (names.isNotEmpty()) {
|
||||||
|
" extends ${names.distinct().joinToString(", ")}"
|
||||||
} else ""
|
} else ""
|
||||||
|
}
|
||||||
|
|
||||||
val inheritedPropNames = superClasses.flatMap { it.memberProperties }.map { it.name }.toSet()
|
private fun buildInterfaceString(
|
||||||
|
cls: KClass<*>,
|
||||||
// Sjekk om klassen har et 'type'-felt, og tving det til klassens navn hvis flagget er satt
|
inheritedPropNames: Set<String>,
|
||||||
val hasTypeProp = cls.memberProperties.any { it.name == "type" }
|
extendsClause: String?,
|
||||||
|
forcedTypeLiteral: String?
|
||||||
|
): String {
|
||||||
|
val typeParams = cls.typeParameters.map { it.name }
|
||||||
|
val generic = if (typeParams.isNotEmpty()) "<" + typeParams.joinToString(", ") + ">" else ""
|
||||||
|
val defaultTypeLiteral = getDefaultTypeLiteral(cls)
|
||||||
|
|
||||||
val props = cls.memberProperties
|
val props = cls.memberProperties
|
||||||
.filter { it.name !in inheritedPropNames }
|
.filter { it.name !in inheritedPropNames }
|
||||||
|
.filter { forcedTypeLiteral == null || it.name != "type" }
|
||||||
.joinToString("\n") { prop ->
|
.joinToString("\n") { prop ->
|
||||||
val tsType = if (prop.name == "type" && includeTypeDiscriminator) {
|
val mapStrategy = prop.findAnnotation<TsMapStrategy>()?.value
|
||||||
// Tving type-feltet til å bli en string literal basert på klassens navn (f.eks. "FileCopyProgress")
|
?: MapStrategy.MapAsRecord
|
||||||
"\"${cls.simpleName}\""
|
|
||||||
|
val tsType = if (prop.name == "type" && defaultTypeLiteral != null) {
|
||||||
|
"\"$defaultTypeLiteral\""
|
||||||
} else {
|
} else {
|
||||||
ttm.kotlinToTsType(prop.returnType.toString(), typeParams)
|
TsTypeMapper.kotlinToTsType(
|
||||||
|
prop.returnType.toString(),
|
||||||
|
typeParams,
|
||||||
|
mapStrategy
|
||||||
|
)
|
||||||
}
|
}
|
||||||
" ${prop.name}: $tsType;"
|
" ${prop.name}: $tsType;"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val propsBlock = if (props.isBlank()) "" else "\n$props"
|
||||||
|
|
||||||
return buildString {
|
return buildString {
|
||||||
appendLine("export interface ${cls.simpleName}$generic$extendsClause {")
|
appendLine("export interface ${cls.simpleName}$generic${extendsClause ?: ""} {")
|
||||||
// Hvis klassen ikke har 'type'-felt i det hele tatt, men skal ha diskriminator, legg til den
|
if (forcedTypeLiteral != null) {
|
||||||
if (includeTypeDiscriminator && !hasTypeProp && "type" !in inheritedPropNames) {
|
appendLine(" type: \"$forcedTypeLiteral\";$propsBlock")
|
||||||
appendLine(" type: \"${cls.simpleName}\";")
|
} else if (props.isNotBlank()) {
|
||||||
|
appendLine(props)
|
||||||
}
|
}
|
||||||
if (props.isNotBlank()) appendLine(props)
|
|
||||||
appendLine("}")
|
appendLine("}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun getDefaultTypeLiteral(cls: KClass<*>): String? {
|
||||||
|
val ctor = cls.primaryConstructor ?: return null
|
||||||
|
ctor.parameters.find { it.name == "type" } ?: return null
|
||||||
|
|
||||||
|
return try {
|
||||||
|
val instance = ctor.callBy(emptyMap())
|
||||||
|
val prop = cls.memberProperties.find { it.name == "type" }
|
||||||
|
prop?.getter?.call(instance)?.toString()
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,19 @@
|
|||||||
package no.iktdev.ts
|
package no.iktdev.ts
|
||||||
|
|
||||||
class TsTypeMapper {
|
object TsTypeMapper {
|
||||||
fun kotlinToTsType(kotlinType: String, genericParams: List<String> = emptyList()): String {
|
fun kotlinToTsType(
|
||||||
|
kotlinType: String,
|
||||||
|
genericParams: List<String> = emptyList(),
|
||||||
|
mapStrategy: MapStrategy = MapStrategy.MapAsRecord,
|
||||||
|
): String {
|
||||||
val isNullable = kotlinType.endsWith("?")
|
val isNullable = kotlinType.endsWith("?")
|
||||||
val clean = kotlinType.removeSuffix("?")
|
// Fjerner eventuelle backticks som Kotlin legger rundt lokale/test-klasser, og trimmet
|
||||||
|
val clean = kotlinType.removeSuffix("?").replace("`", "").trim()
|
||||||
|
|
||||||
|
// Sjekk om typen er en generisk parameter (f.eks. "T")
|
||||||
|
if (genericParams.contains(clean)) {
|
||||||
|
return if (isNullable) "$clean | null" else clean
|
||||||
|
}
|
||||||
|
|
||||||
// UUID → string
|
// UUID → string
|
||||||
if (clean == "java.util.UUID") {
|
if (clean == "java.util.UUID") {
|
||||||
@@ -20,7 +30,7 @@ class TsTypeMapper {
|
|||||||
return if (isNullable) "string | null" else "string"
|
return if (isNullable) "string | null" else "string"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Map<K, V> → Record<K, V>
|
// Map<K, V> → Record<K, V> / Partial<Record<K, V>>
|
||||||
if (clean.startsWith("kotlin.collections.Map") ||
|
if (clean.startsWith("kotlin.collections.Map") ||
|
||||||
clean.startsWith("kotlin.collections.MutableMap")) {
|
clean.startsWith("kotlin.collections.MutableMap")) {
|
||||||
|
|
||||||
@@ -30,7 +40,13 @@ class TsTypeMapper {
|
|||||||
val tsKey = kotlinToTsType(key, genericParams)
|
val tsKey = kotlinToTsType(key, genericParams)
|
||||||
val tsValue = kotlinToTsType(value, genericParams)
|
val tsValue = kotlinToTsType(value, genericParams)
|
||||||
|
|
||||||
val base = "Record<$tsKey, $tsValue>"
|
val record = "Record<$tsKey, $tsValue>"
|
||||||
|
|
||||||
|
val base = when (mapStrategy) {
|
||||||
|
MapStrategy.MapAsRecord -> record
|
||||||
|
MapStrategy.MapAsPartialRecord -> "Partial<$record>"
|
||||||
|
}
|
||||||
|
|
||||||
return if (isNullable) "$base | null" else base
|
return if (isNullable) "$base | null" else base
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,7 +82,7 @@ class TsTypeMapper {
|
|||||||
return if (isNullable) "$base | null" else base
|
return if (isNullable) "$base | null" else base
|
||||||
}
|
}
|
||||||
|
|
||||||
// Primitive mappings
|
// Primitive mappings / Klasser
|
||||||
val base = when (clean) {
|
val base = when (clean) {
|
||||||
"kotlin.String" -> "string"
|
"kotlin.String" -> "string"
|
||||||
"kotlin.Int",
|
"kotlin.Int",
|
||||||
@@ -76,8 +92,8 @@ class TsTypeMapper {
|
|||||||
"kotlin.Boolean" -> "boolean"
|
"kotlin.Boolean" -> "boolean"
|
||||||
"kotlin.Any" -> "any"
|
"kotlin.Any" -> "any"
|
||||||
else -> {
|
else -> {
|
||||||
if (clean.contains(".")) clean.substringAfterLast(".")
|
// Stripper vekk alt av pakkenavn og eventuelle lokale test-referanser med $
|
||||||
else "any"
|
clean.substringAfterLast(".").substringAfterLast("$")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package no.iktdev.ts.anno
|
||||||
|
|
||||||
|
import no.iktdev.ts.MapStrategy
|
||||||
|
|
||||||
|
@Target(AnnotationTarget.PROPERTY)
|
||||||
|
@Retention(AnnotationRetention.RUNTIME)
|
||||||
|
annotation class TsMapStrategy(
|
||||||
|
val value: MapStrategy
|
||||||
|
)
|
||||||
@@ -1,40 +1,40 @@
|
|||||||
package no.iktdev.tsgen
|
package no.iktdev.tsgen
|
||||||
|
|
||||||
|
import no.iktdev.ts.SealedStrategy
|
||||||
import no.iktdev.ts.TsGenerator
|
import no.iktdev.ts.TsGenerator
|
||||||
import org.gradle.api.Plugin
|
import org.gradle.api.Plugin
|
||||||
import org.gradle.api.Project
|
import org.gradle.api.Project
|
||||||
import org.gradle.api.plugins.JavaPluginExtension
|
import org.gradle.api.plugins.JavaPluginExtension
|
||||||
import org.gradle.api.provider.Property
|
import org.gradle.api.provider.Property
|
||||||
|
import org.gradle.api.provider.ListProperty
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.net.URLClassLoader
|
import java.net.URLClassLoader
|
||||||
|
|
||||||
interface TsGeneratorExtension {
|
interface TsGeneratorExtension {
|
||||||
val packageName: Property<String>
|
val packageName: Property<String>
|
||||||
|
val includeClasses: ListProperty<String>
|
||||||
val outputFile: Property<File>
|
val outputFile: Property<File>
|
||||||
|
|
||||||
val includeSealed: Property<Boolean>
|
val sealedStrategy: Property<SealedStrategy>
|
||||||
val includeInterface: Property<Boolean>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class TsGeneratorPlugin : Plugin<Project> {
|
class TsGeneratorPlugin : Plugin<Project> {
|
||||||
override fun apply(project: Project) {
|
override fun apply(project: Project) {
|
||||||
val extension = project.extensions.create("tsGenerator", TsGeneratorExtension::class.java).apply {
|
val extension = project.extensions.create("tsGenerator", TsGeneratorExtension::class.java).apply {
|
||||||
includeSealed.convention(true)
|
sealedStrategy.convention(SealedStrategy.AS_INTERFACE_WITH_TYPE)
|
||||||
includeInterface.convention(true)
|
includeClasses.convention(emptyList())
|
||||||
}
|
}
|
||||||
|
|
||||||
project.tasks.register("generateTs") {
|
project.tasks.register("generateTs") {
|
||||||
group = "typescript"
|
group = "typescript"
|
||||||
dependsOn("compileKotlin")
|
dependsOn("compileKotlin")
|
||||||
|
|
||||||
doLast {
|
doLast {
|
||||||
TsGenerator.versionInfo = project.version.toString()
|
|
||||||
TsGenerator.buildTime = java.time.Instant.now().toString()
|
TsGenerator.buildTime = java.time.Instant.now().toString()
|
||||||
|
|
||||||
val pkg = extension.packageName.get()
|
val pkg = extension.packageName.get()
|
||||||
|
val includedClasses = extension.includeClasses.get()
|
||||||
val out = extension.outputFile.get()
|
val out = extension.outputFile.get()
|
||||||
val includeSealed = extension.includeSealed.get()
|
val writeSealedStrategy = extension.sealedStrategy.get()
|
||||||
val includeInterface = extension.includeInterface.get()
|
|
||||||
|
|
||||||
// Hent classpath for å lage ClassLoaderen
|
// Hent classpath for å lage ClassLoaderen
|
||||||
val mainSourceSet = project.extensions.getByType(JavaPluginExtension::class.java)
|
val mainSourceSet = project.extensions.getByType(JavaPluginExtension::class.java)
|
||||||
@@ -44,7 +44,7 @@ class TsGeneratorPlugin : Plugin<Project> {
|
|||||||
val cl = URLClassLoader(urls, TsGenerator::class.java.classLoader)
|
val cl = URLClassLoader(urls, TsGenerator::class.java.classLoader)
|
||||||
|
|
||||||
// Kall generatoren med det nye flagget
|
// Kall generatoren med det nye flagget
|
||||||
TsGenerator.generate(pkg, out, cl, includeSealed, includeInterface)
|
TsGenerator.generate(pkg, includedClasses, out, cl, writeSealedStrategy)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,11 +11,10 @@ import org.junit.jupiter.api.Test
|
|||||||
class TsModelRendererTest {
|
class TsModelRendererTest {
|
||||||
|
|
||||||
private val renderer = TsModelRenderer()
|
private val renderer = TsModelRenderer()
|
||||||
private val ttm = TsTypeMapper()
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `should maintain exact property names without renaming`() {
|
fun `should maintain exact property names without renaming`() {
|
||||||
val result = renderer.dataClassToTs(Fancy::class, ttm, true)
|
val result = renderer.dataClassToTs(Fancy::class)
|
||||||
|
|
||||||
// Sjekk at "isFancy" ikke ble endret til "fancy"
|
// Sjekk at "isFancy" ikke ble endret til "fancy"
|
||||||
assertThat(result).contains("isFancy: boolean;")
|
assertThat(result).contains("isFancy: boolean;")
|
||||||
@@ -28,7 +27,7 @@ class TsModelRendererTest {
|
|||||||
@Test
|
@Test
|
||||||
fun `full test - verifiser arv, typer og union`() {
|
fun `full test - verifiser arv, typer og union`() {
|
||||||
// 1. Test Interface Arv
|
// 1. Test Interface Arv
|
||||||
val cameraTs = renderer.dataClassToTs(Camera::class, ttm, true)
|
val cameraTs = renderer.dataClassToTs(Camera::class)
|
||||||
|
|
||||||
assertThat(cameraTs).contains("interface Camera extends BaseDevice")
|
assertThat(cameraTs).contains("interface Camera extends BaseDevice")
|
||||||
assertThat(cameraTs).contains("resolution: number;")
|
assertThat(cameraTs).contains("resolution: number;")
|
||||||
@@ -40,22 +39,114 @@ class TsModelRendererTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `sealed subtype test - verifiser type discriminator`() {
|
fun `should handle generic classes correctly`() {
|
||||||
data class Sensor(val type: String = "TEMP_SENSOR", val value: Double)
|
data class Wrapper<T>(val data: T, val message: String?)
|
||||||
|
|
||||||
// Send med true for å inkludere type-diskriminatoren i testen
|
val result = renderer.dataClassToTs(Wrapper::class)
|
||||||
val sensorTs = renderer.sealedSubtypeToTs(Sensor::class, ttm, includeTypeDiscriminator = true)
|
|
||||||
|
|
||||||
|
assertThat(result).contains("export interface Wrapper<T>")
|
||||||
|
assertThat(result).contains("data: T;")
|
||||||
|
assertThat(result).contains("message: string | null;")
|
||||||
|
}
|
||||||
|
|
||||||
|
class TsModelRendererTest {
|
||||||
|
private val renderer = TsModelRenderer()
|
||||||
|
|
||||||
|
sealed class ASealedDevice
|
||||||
|
data class Sensor(val value: Double) : ASealedDevice()
|
||||||
|
data class Actuator(val active: Boolean) : ASealedDevice()
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `sealed union and subtypes - AS_INTERFACE_WITH_TYPE`() {
|
||||||
|
// 1. Verifiser at hovedklassen blir et interface + union-type
|
||||||
|
val unionTs = renderer.sealedUnionToTs(ASealedDevice::class, SealedStrategy.AS_INTERFACE_WITH_TYPE)
|
||||||
|
assertThat(unionTs).contains("export interface ASealedDevice")
|
||||||
|
assertThat(unionTs).contains("export type ASealedDeviceRef = Actuator | Sensor")
|
||||||
|
|
||||||
|
// 2. Verifiser at subtypen får type-discriminator og arver baseklassen
|
||||||
|
val sensorTs = renderer.sealedSubtypeToTs(Sensor::class, SealedStrategy.AS_INTERFACE_WITH_TYPE, "ASealedDevice")
|
||||||
|
assertThat(sensorTs).contains("export interface Sensor extends ASealedDevice")
|
||||||
assertThat(sensorTs).contains("type: \"Sensor\";")
|
assertThat(sensorTs).contains("type: \"Sensor\";")
|
||||||
assertThat(sensorTs).contains("value: number;")
|
assertThat(sensorTs).contains("value: number;")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `sealed union and subtypes - ONLY_TYPED`() {
|
||||||
|
// 1. Verifiser at ONLY_TYPED kun lager en ren union-type for hovedklassen
|
||||||
|
val unionTs = renderer.sealedUnionToTs(ASealedDevice::class, SealedStrategy.ONLY_TYPED)
|
||||||
|
assertThat(unionTs).isEqualTo("export type ASealedDevice = Actuator | Sensor\n")
|
||||||
|
|
||||||
|
// 2. Verifiser at subtypen IKKE får type-discriminator eller extends-klausul når baseName er null
|
||||||
|
val sensorTs = renderer.sealedSubtypeToTs(Sensor::class, SealedStrategy.ONLY_TYPED, null)
|
||||||
|
assertThat(sensorTs).doesNotContain("type:")
|
||||||
|
assertThat(sensorTs).doesNotContain("extends")
|
||||||
|
assertThat(sensorTs).contains("export interface Sensor {")
|
||||||
|
assertThat(sensorTs).contains("value: number;")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `sealed union and subtypes - AS_INTERFACE`() {
|
||||||
|
// 1. Verifiser at AS_INTERFACE lager base-interface og union-type
|
||||||
|
val unionTs = renderer.sealedUnionToTs(ASealedDevice::class, SealedStrategy.AS_INTERFACE)
|
||||||
|
assertThat(unionTs).contains("export interface ASealedDevice")
|
||||||
|
assertThat(unionTs).contains("export type ASealedDeviceRef = Actuator | Sensor")
|
||||||
|
|
||||||
|
// 2. Verifiser at subtypen arver baseklassen, men IKKE har automatisk type-discriminator
|
||||||
|
val sensorTs = renderer.sealedSubtypeToTs(Sensor::class, SealedStrategy.AS_INTERFACE, "ASealedDevice")
|
||||||
|
assertThat(sensorTs).contains("export interface Sensor extends ASealedDevice")
|
||||||
|
assertThat(sensorTs).doesNotContain("type:")
|
||||||
|
assertThat(sensorTs).contains("value: number;")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
fun `should generate string literal union for enums`() {
|
||||||
|
val result = renderer.enumToTs(DeviceStatus::class)
|
||||||
|
|
||||||
|
assertThat(result).isEqualTo("export type DeviceStatus = \"ONLINE\" | \"OFFLINE\"\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `should handle classes with no unique properties gracefully`() {
|
||||||
|
open class Base(val id: String)
|
||||||
|
data class EmptySub(val type: String = "EmptySub") : Base("123")
|
||||||
|
|
||||||
|
val result = renderer.dataClassToTs(EmptySub::class)
|
||||||
|
|
||||||
|
assertThat(result).contains("export interface EmptySub extends Base")
|
||||||
|
assertThat(result).contains("type: \"EmptySub\";")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `should map list of complex objects correctly`() {
|
||||||
|
data class SubItem(val code: String)
|
||||||
|
data class Container(val items: List<SubItem>)
|
||||||
|
|
||||||
|
val result = renderer.dataClassToTs(Container::class)
|
||||||
|
|
||||||
|
assertThat(result).contains("items: SubItem[];")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `should correctly inherit properties from parent data class`() {
|
||||||
|
open class Parent(val id: String, val createdAt: String)
|
||||||
|
data class Child(val name: String, val age: Int) : Parent("default-id", "now")
|
||||||
|
|
||||||
|
val result = renderer.dataClassToTs(Child::class)
|
||||||
|
|
||||||
|
assertThat(result).contains("extends Parent")
|
||||||
|
assertThat(result).contains("name: string;")
|
||||||
|
assertThat(result).contains("age: number;")
|
||||||
|
// Felt fra Parent skal være filtrert bort fra Child-interfacet
|
||||||
|
assertThat(result).doesNotContain("id: string;")
|
||||||
|
assertThat(result).doesNotContain("createdAt: string;")
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `sealed subtype test - no type when off`() {
|
fun `sealed subtype test - no type when off`() {
|
||||||
data class Sensor(val type: String = "TEMP_SENSOR", val value: Double)
|
data class Sensor(val type: String = "TEMP_SENSOR", val value: Double)
|
||||||
|
|
||||||
// Send med true for å inkludere type-diskriminatoren i testen
|
// Tester med false for å verifisere at type-lappen utelates
|
||||||
val sensorTs = renderer.sealedSubtypeToTs(Sensor::class, ttm, includeTypeDiscriminator = false)
|
val sensorTs = renderer.dataClassToTs(Sensor::class)
|
||||||
|
|
||||||
assertThat(sensorTs).doesNotContain("type: \"Sensor\";")
|
assertThat(sensorTs).doesNotContain("type: \"Sensor\";")
|
||||||
assertThat(sensorTs).contains("value: number;")
|
assertThat(sensorTs).contains("value: number;")
|
||||||
@@ -64,18 +155,16 @@ class TsModelRendererTest {
|
|||||||
@Test
|
@Test
|
||||||
fun `should correctly extend abstract class and avoid duplicated properties`() {
|
fun `should correctly extend abstract class and avoid duplicated properties`() {
|
||||||
// 1. Generer TypeScript fra dummy-klassen
|
// 1. Generer TypeScript fra dummy-klassen
|
||||||
val result = renderer.dataClassToTs(AChild::class, ttm, true)
|
val result = renderer.dataClassToTs(AChild::class)
|
||||||
|
|
||||||
// 2. Verifiser at den utvider den abstrakte klassen
|
// 2. Verifiser at den utvider den abstrakte klassen
|
||||||
assertThat(result).contains("extends AParent")
|
assertThat(result).contains("extends AParent")
|
||||||
|
|
||||||
// 3. Verifiser at felt som finnes i AParent IKKE er duplisert i AChild
|
// 3. Verifiser at felt som finnes i AParent IKKE er duplisert i AChild
|
||||||
// Dette bekrefter at filtreringen mot superclass fungerer
|
|
||||||
assertThat(result).doesNotContain("macAdress: string;")
|
assertThat(result).doesNotContain("macAdress: string;")
|
||||||
assertThat(result).doesNotContain("interfaceName: string;")
|
assertThat(result).doesNotContain("interfaceName: string;")
|
||||||
|
|
||||||
// 4. Verifiser at unike felt for sub-klassen er med
|
// 4. Verifiser at unike felt for sub-klassen er med
|
||||||
// (Merk: ttm mapper List til string[] i din originale kode)
|
|
||||||
assertThat(result).contains("caps: string[];")
|
assertThat(result).contains("caps: string[];")
|
||||||
|
|
||||||
// 5. Sjekk at klassenavnet er riktig
|
// 5. Sjekk at klassenavnet er riktig
|
||||||
|
|||||||
@@ -6,49 +6,47 @@ import org.junit.jupiter.api.Test
|
|||||||
|
|
||||||
class TsTypeMapperTest {
|
class TsTypeMapperTest {
|
||||||
|
|
||||||
private val mapper = TsTypeMapper()
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `should map primitives correctly`() {
|
fun `should map primitives correctly`() {
|
||||||
assertEquals("string", mapper.kotlinToTsType("kotlin.String"))
|
assertEquals("string", TsTypeMapper.kotlinToTsType("kotlin.String"))
|
||||||
assertEquals("number", mapper.kotlinToTsType("kotlin.Int"))
|
assertEquals("number", TsTypeMapper.kotlinToTsType("kotlin.Int"))
|
||||||
assertEquals("number", mapper.kotlinToTsType("kotlin.Double"))
|
assertEquals("number", TsTypeMapper.kotlinToTsType("kotlin.Double"))
|
||||||
assertEquals("boolean", mapper.kotlinToTsType("kotlin.Boolean"))
|
assertEquals("boolean", TsTypeMapper.kotlinToTsType("kotlin.Boolean"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `should map java types to string`() {
|
fun `should map java types to string`() {
|
||||||
assertEquals("string", mapper.kotlinToTsType("java.util.UUID"))
|
assertEquals("string", TsTypeMapper.kotlinToTsType("java.util.UUID"))
|
||||||
assertEquals("string", mapper.kotlinToTsType("java.time.Instant"))
|
assertEquals("string", TsTypeMapper.kotlinToTsType("java.time.Instant"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `should handle nullability`() {
|
fun `should handle nullability`() {
|
||||||
assertEquals("string | null", mapper.kotlinToTsType("kotlin.String?"))
|
assertEquals("string | null", TsTypeMapper.kotlinToTsType("kotlin.String?"))
|
||||||
assertEquals("number | null", mapper.kotlinToTsType("kotlin.Int?"))
|
assertEquals("number | null", TsTypeMapper.kotlinToTsType("kotlin.Int?"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `should map List and Set to arrays`() {
|
fun `should map List and Set to arrays`() {
|
||||||
assertEquals("string[]", mapper.kotlinToTsType("kotlin.collections.List<kotlin.String>"))
|
assertEquals("string[]", TsTypeMapper.kotlinToTsType("kotlin.collections.List<kotlin.String>"))
|
||||||
assertEquals("number[]", mapper.kotlinToTsType("kotlin.collections.MutableSet<kotlin.Int>"))
|
assertEquals("number[]", TsTypeMapper.kotlinToTsType("kotlin.collections.MutableSet<kotlin.Int>"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `should handle nested Map`() {
|
fun `should handle nested Map`() {
|
||||||
val input = "kotlin.collections.Map<kotlin.String, kotlin.Int>"
|
val input = "kotlin.collections.Map<kotlin.String, kotlin.Int>"
|
||||||
assertEquals("Record<string, number>", mapper.kotlinToTsType(input))
|
assertEquals("Record<string, number>", TsTypeMapper.kotlinToTsType(input))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `should handle generic parameters`() {
|
fun `should handle generic parameters`() {
|
||||||
// Antar at "T" er definert i genericParams
|
// Antar at "T" er definert i genericParams
|
||||||
val generics = listOf("T")
|
val generics = listOf("T")
|
||||||
assertEquals("T[]", mapper.kotlinToTsType("kotlin.collections.List<T>", generics))
|
assertEquals("T[]", TsTypeMapper.kotlinToTsType("kotlin.collections.List<T>", generics))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `should handle unknown types by taking simple name`() {
|
fun `should handle unknown types by taking simple name`() {
|
||||||
assertEquals("MyCustomClass", mapper.kotlinToTsType("no.iktdev.models.MyCustomClass"))
|
assertEquals("MyCustomClass", TsTypeMapper.kotlinToTsType("no.iktdev.models.MyCustomClass"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user