Changes
This commit is contained in:
1 parent
e23373f73b
commit
6ab2e4082e
9 files changed
+240
-99
No files matched your search
@@ -17,7 +17,10 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
fetch-tags: true
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@v3
|
||||
with:
|
||||
|
||||
+40
-18
@@ -1,32 +1,46 @@
|
||||
plugins {
|
||||
kotlin("jvm") version "2.3.21"
|
||||
kotlin("jvm") version "2.2.21"
|
||||
id("maven-publish")
|
||||
`java-gradle-plugin`
|
||||
`kotlin-dsl`
|
||||
}
|
||||
|
||||
val dynamicVersion = providers.provider {
|
||||
val ref = System.getenv("GITHUB_REF") ?: ""
|
||||
val isSnapshot = ref.endsWith("/master") || ref.endsWith("/main")
|
||||
val latestTag = providers.exec {
|
||||
commandLine("git", "describe", "--tags", "--abbrev=0")
|
||||
}.standardOutput.asText.getOrElse("0.0.0").trim().removePrefix("v")
|
||||
val dynamicVersion: String by lazy {
|
||||
val githubRef = System.getenv("GITHUB_REF") ?: ""
|
||||
val releaseTag = System.getenv("GITHUB_REF_NAME") ?: ""
|
||||
val eventName = System.getenv("GITHUB_EVENT_NAME") ?: ""
|
||||
|
||||
if (isSnapshot) {
|
||||
val parts = latestTag.split(".")
|
||||
val patch = parts.lastOrNull()?.toIntOrNull()?.plus(1) ?: 1
|
||||
val base = if (parts.size >= 2) "${parts[0]}.${parts[1]}" else latestTag
|
||||
val buildNumber = providers.exec {
|
||||
commandLine("git", "rev-list", "v$latestTag..HEAD", "--count")
|
||||
}.standardOutput.asText.getOrElse("0").trim().toIntOrNull() ?: 0
|
||||
"$base.$patch-SNAPSHOT-$buildNumber"
|
||||
// Hvis det er en release eller tag-push i GitHub Actions, bruk taggen direkte
|
||||
if ((eventName == "release" || githubRef.startsWith("refs/tags/")) && releaseTag.isNotBlank()) {
|
||||
releaseTag.removePrefix("v")
|
||||
} else {
|
||||
latestTag
|
||||
// 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 {
|
||||
commandLine("git", "describe", "--tags", "--abbrev=0")
|
||||
}.standardOutput.asText.get().trim().removePrefix("v")
|
||||
|
||||
if (isSnapshot) {
|
||||
val parts = latestTag.split(".")
|
||||
val patch = parts.lastOrNull()?.toIntOrNull()?.plus(1) ?: 1
|
||||
val base = if (parts.size >= 2) "${parts.first()}.${parts[1]}" else latestTag
|
||||
val buildNumber = providers.exec {
|
||||
commandLine("git", "rev-list", "v$latestTag..HEAD", "--count")
|
||||
}.standardOutput.asText.get().trim().toIntOrNull() ?: 0
|
||||
|
||||
"$base.$patch-SNAPSHOT-$buildNumber"
|
||||
} else {
|
||||
latestTag
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
"0.0.1-SNAPSHOT"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
group = "no.iktdev"
|
||||
version = dynamicVersion.get()
|
||||
version = dynamicVersion
|
||||
val named = "ts-gen"
|
||||
|
||||
|
||||
@@ -63,6 +77,14 @@ dependencies {
|
||||
|
||||
}
|
||||
|
||||
tasks.jar {
|
||||
manifest {
|
||||
attributes(
|
||||
"Implementation-Title" to project.name,
|
||||
"Implementation-Version" to project.version
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
useJUnitPlatform()
|
||||
@@ -85,7 +107,7 @@ publishing {
|
||||
if (name == "pluginMaven") {
|
||||
groupId = "no.iktdev"
|
||||
artifactId = "ts-gen"
|
||||
version = dynamicVersion.get()
|
||||
version = dynamicVersion
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -5,18 +5,16 @@ import java.io.File
|
||||
object TsGenerator {
|
||||
var versionInfo: String = System.getProperty("tsgenerator.version")
|
||||
?: TsGenerator::class.java.getPackage()?.implementationVersion
|
||||
?: "dev"
|
||||
?: "any"
|
||||
var buildTime: String = java.time.Instant.now().toString()
|
||||
|
||||
val ttm = TsTypeMapper()
|
||||
val tmr = TsModelRenderer()
|
||||
|
||||
fun generate(
|
||||
packageName: String,
|
||||
output: File,
|
||||
classLoader: ClassLoader = Thread.currentThread().contextClassLoader,
|
||||
includeTypedSealed: Boolean = true,
|
||||
includeTypedInterface: Boolean = true
|
||||
writeSealedStrategy: SealedStrategy,
|
||||
) {
|
||||
println("TsGenerator: scanning package: $packageName")
|
||||
|
||||
@@ -35,28 +33,37 @@ object TsGenerator {
|
||||
classes.forEach { cls ->
|
||||
when {
|
||||
// ----------------------------------------------------
|
||||
// 1) Sealed interface → union type alias
|
||||
// 1) Sealed interface → union type alias + evt. base interface
|
||||
// ----------------------------------------------------
|
||||
cls.isSealed && cls.java.isInterface -> {
|
||||
println("Generating union type for sealed interface: ${cls.simpleName}")
|
||||
append(tmr.sealedUnionToTs(cls))
|
||||
println("Generating sealed interface: ${cls.simpleName}")
|
||||
append(tmr.sealedUnionToTs(cls, writeSealedStrategy))
|
||||
}
|
||||
|
||||
// ----------------------------------------------------
|
||||
// 1a) Sealed class → union type alias
|
||||
// 1a) Sealed class → union type alias + evt. base interface
|
||||
// ----------------------------------------------------
|
||||
cls.isSealed && !cls.java.isInterface -> {
|
||||
println("Generating union type for sealed class: ${cls.simpleName}")
|
||||
append(tmr.sealedUnionToTs(cls))
|
||||
println("Generating sealed class: ${cls.simpleName}")
|
||||
append(tmr.sealedUnionToTs(cls, writeSealedStrategy))
|
||||
}
|
||||
|
||||
// ----------------------------------------------------
|
||||
// 1b) Sealed subtype (data object / data class)
|
||||
// → Bruker includeTypedSealed for type-lappen
|
||||
// Sjekker strategien for type-felt og extends-base
|
||||
// ----------------------------------------------------
|
||||
cls.isSealedSubtype() -> {
|
||||
println("Generating sealed subtype interface: ${cls.simpleName}")
|
||||
append(tmr.dataClassToTs(cls, ttm, includeTypedSealed))
|
||||
|
||||
// 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))
|
||||
}
|
||||
|
||||
// ----------------------------------------------------
|
||||
@@ -68,12 +75,11 @@ object TsGenerator {
|
||||
}
|
||||
|
||||
// ----------------------------------------------------
|
||||
// 3) Data class → interface
|
||||
// → Bruker includeTypedInterface for type-lappen
|
||||
// 3) Data class → interface (vanlige klasser)
|
||||
// ----------------------------------------------------
|
||||
cls.hasProperties() && !cls.isSealed -> {
|
||||
println("Generating interface: ${cls.simpleName}")
|
||||
append(tmr.dataClassToTs(cls, ttm, includeTypedInterface))
|
||||
append(tmr.dataClassToTs(cls))
|
||||
}
|
||||
|
||||
else -> {
|
||||
|
||||
@@ -2,6 +2,7 @@ package no.iktdev.ts
|
||||
|
||||
import kotlin.reflect.KClass
|
||||
import kotlin.reflect.full.memberProperties
|
||||
import kotlin.reflect.full.primaryConstructor
|
||||
|
||||
class TsModelRenderer {
|
||||
|
||||
@@ -12,24 +13,66 @@ class TsModelRenderer {
|
||||
return "export type ${cls.simpleName} = $values\n"
|
||||
}
|
||||
|
||||
// Genererer union-typen for sealed klasser (f.eks. export type Progress = A | B | C)
|
||||
fun sealedUnionToTs(cls: KClass<*>): String {
|
||||
// Genererer base-interface (hvis ikke ONLY_TYPED) og union-typen
|
||||
fun sealedUnionToTs(
|
||||
cls: KClass<*>,
|
||||
strategy: SealedStrategy
|
||||
): String {
|
||||
val subTypes = cls.sealedSubclasses
|
||||
.mapNotNull { it.simpleName }
|
||||
.joinToString(" | ")
|
||||
|
||||
return "export type ${cls.simpleName} = $subTypes\n"
|
||||
if (strategy == SealedStrategy.ONLY_TYPED) {
|
||||
return "export type ${cls.simpleName} = $subTypes\n"
|
||||
}
|
||||
|
||||
// AS_INTERFACE og AS_INTERFACE_WITH_TYPE lager base-interfacet for sealed-klassen
|
||||
val superClasses = getSuperClasses(cls)
|
||||
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}Type = $subTypes\n"
|
||||
|
||||
return listOf(baseInterface, unionType).filter { it.isNotBlank() }.joinToString("\n")
|
||||
}
|
||||
|
||||
// Genererer standard interface for klasser/subtyper
|
||||
fun dataClassToTs(
|
||||
// Sealed subtype renderer som respekterer om vi skal ha type-felt eller ikke
|
||||
fun sealedSubtypeToTs(
|
||||
cls: KClass<*>,
|
||||
ttm: TsTypeMapper,
|
||||
includeTypedInterface: Boolean
|
||||
strategy: SealedStrategy,
|
||||
extendsBaseName: String?
|
||||
): String {
|
||||
val typeParams = cls.typeParameters.map { it.name }
|
||||
val generic = if (typeParams.isNotEmpty()) "<" + typeParams.joinToString(", ") + ">" else ""
|
||||
// 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 superClass = cls.java.superclass?.kotlin
|
||||
if (superClass != null && superClass != Any::class) {
|
||||
@@ -41,37 +84,64 @@ class TsModelRenderer {
|
||||
.filter { it.simpleName != "Any" && it.simpleName != "Serializable" }
|
||||
|
||||
superClasses.addAll(superInterfaces)
|
||||
return superClasses
|
||||
}
|
||||
|
||||
val extendsClause = if (superClasses.isNotEmpty()) {
|
||||
" extends " + superClasses.joinToString(", ") { it.simpleName!! }
|
||||
private fun getExtendsClause(superClasses: List<KClass<*>>, extraExtends: String?): String {
|
||||
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 ""
|
||||
}
|
||||
|
||||
val inheritedPropNames = superClasses.flatMap { it.memberProperties }.map { it.name }.toSet()
|
||||
val hasTypeProp = cls.memberProperties.any { it.name == "type" }
|
||||
private fun buildInterfaceString(
|
||||
cls: KClass<*>,
|
||||
inheritedPropNames: Set<String>,
|
||||
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
|
||||
.filter { it.name !in inheritedPropNames }
|
||||
.filter { forcedTypeLiteral == null || it.name != "type" }
|
||||
.joinToString("\n") { prop ->
|
||||
// HVIS feltet heter "type" og vi har slått på includeTypedInterface,
|
||||
// tvinger vi type-definisjonen til å bli klassens navn som en string-literal!
|
||||
val tsType = if (prop.name == "type" && includeTypedInterface) {
|
||||
"\"${cls.simpleName}\""
|
||||
val tsType = if (prop.name == "type" && defaultTypeLiteral != null) {
|
||||
"\"$defaultTypeLiteral\""
|
||||
} else {
|
||||
ttm.kotlinToTsType(prop.returnType.toString(), typeParams)
|
||||
TsTypeMapper.kotlinToTsType(prop.returnType.toString(), typeParams)
|
||||
}
|
||||
" ${prop.name}: $tsType;"
|
||||
}
|
||||
|
||||
val propsBlock = if (props.isBlank()) "" else "\n$props"
|
||||
|
||||
return buildString {
|
||||
appendLine("export interface ${cls.simpleName}$generic$extendsClause {")
|
||||
|
||||
// Hvis klassen IKKE hadde "type"-felt fra før, men flagget er på, legger vi til lappen her
|
||||
if (includeTypedInterface && !hasTypeProp && "type" !in inheritedPropNames) {
|
||||
appendLine(" type: \"${cls.simpleName}\";")
|
||||
appendLine("export interface ${cls.simpleName}$generic${extendsClause ?: ""} {")
|
||||
if (forcedTypeLiteral != null) {
|
||||
appendLine(" type: \"$forcedTypeLiteral\";$propsBlock")
|
||||
} else if (props.isNotBlank()) {
|
||||
appendLine(props)
|
||||
}
|
||||
|
||||
if (props.isNotBlank()) appendLine(props)
|
||||
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,6 +1,6 @@
|
||||
package no.iktdev.ts
|
||||
|
||||
class TsTypeMapper {
|
||||
object TsTypeMapper {
|
||||
fun kotlinToTsType(kotlinType: String, genericParams: List<String> = emptyList()): String {
|
||||
val isNullable = kotlinType.endsWith("?")
|
||||
// Fjerner eventuelle backticks som Kotlin legger rundt lokale/test-klasser, og trimmet
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package no.iktdev.tsgen
|
||||
|
||||
import no.iktdev.ts.SealedStrategy
|
||||
import no.iktdev.ts.TsGenerator
|
||||
import org.gradle.api.Plugin
|
||||
import org.gradle.api.Project
|
||||
@@ -12,15 +13,13 @@ interface TsGeneratorExtension {
|
||||
val packageName: Property<String>
|
||||
val outputFile: Property<File>
|
||||
|
||||
val includeTypedSealed: Property<Boolean>
|
||||
val includeTypedInterface: Property<Boolean>
|
||||
val sealedStrategy: Property<SealedStrategy>
|
||||
}
|
||||
|
||||
class TsGeneratorPlugin : Plugin<Project> {
|
||||
override fun apply(project: Project) {
|
||||
val extension = project.extensions.create("tsGenerator", TsGeneratorExtension::class.java).apply {
|
||||
includeTypedSealed.convention(false)
|
||||
includeTypedInterface.convention(false)
|
||||
sealedStrategy.convention(SealedStrategy.AS_INTERFACE_WITH_TYPE)
|
||||
}
|
||||
|
||||
project.tasks.register("generateTs") {
|
||||
@@ -32,8 +31,7 @@ class TsGeneratorPlugin : Plugin<Project> {
|
||||
|
||||
val pkg = extension.packageName.get()
|
||||
val out = extension.outputFile.get()
|
||||
val includeTypedSealed = extension.includeTypedSealed.get()
|
||||
val includeTypedInterface = extension.includeTypedInterface.get()
|
||||
val writeSealedStrategy = extension.sealedStrategy.get()
|
||||
|
||||
// Hent classpath for å lage ClassLoaderen
|
||||
val mainSourceSet = project.extensions.getByType(JavaPluginExtension::class.java)
|
||||
@@ -43,7 +41,7 @@ class TsGeneratorPlugin : Plugin<Project> {
|
||||
val cl = URLClassLoader(urls, TsGenerator::class.java.classLoader)
|
||||
|
||||
// Kall generatoren med det nye flagget
|
||||
TsGenerator.generate(pkg, out, cl, includeTypedSealed, includeTypedInterface)
|
||||
TsGenerator.generate(pkg, out, cl, writeSealedStrategy)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,11 +11,10 @@ import org.junit.jupiter.api.Test
|
||||
class TsModelRendererTest {
|
||||
|
||||
private val renderer = TsModelRenderer()
|
||||
private val ttm = TsTypeMapper()
|
||||
|
||||
@Test
|
||||
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"
|
||||
assertThat(result).contains("isFancy: boolean;")
|
||||
@@ -28,7 +27,7 @@ class TsModelRendererTest {
|
||||
@Test
|
||||
fun `full test - verifiser arv, typer og union`() {
|
||||
// 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("resolution: number;")
|
||||
@@ -43,24 +42,62 @@ class TsModelRendererTest {
|
||||
fun `should handle generic classes correctly`() {
|
||||
data class Wrapper<T>(val data: T, val message: String?)
|
||||
|
||||
val result = renderer.dataClassToTs(Wrapper::class, ttm, true)
|
||||
val result = renderer.dataClassToTs(Wrapper::class)
|
||||
|
||||
assertThat(result).contains("export interface Wrapper<T>")
|
||||
assertThat(result).contains("data: T;")
|
||||
assertThat(result).contains("message: string | null;")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sealed subtype test - verifiser type discriminator`() {
|
||||
data class Sensor(val type: String = "TEMP_SENSOR", val value: Double)
|
||||
class TsModelRendererTest {
|
||||
private val renderer = TsModelRenderer()
|
||||
|
||||
// Bruker dataClassToTs direkte ettersom sealed subtyper nå bruker denne metoden
|
||||
val sensorTs = renderer.dataClassToTs(Sensor::class, ttm, includeTypedInterface = true)
|
||||
sealed class ASealedDevice
|
||||
data class Sensor(val value: Double) : ASealedDevice()
|
||||
data class Actuator(val active: Boolean) : ASealedDevice()
|
||||
|
||||
assertThat(sensorTs).contains("type: \"Sensor\";")
|
||||
assertThat(sensorTs).contains("value: number;")
|
||||
@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 ASealedDeviceType = 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("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 ASealedDeviceType = 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)
|
||||
@@ -73,7 +110,7 @@ class TsModelRendererTest {
|
||||
open class Base(val id: String)
|
||||
data class EmptySub(val type: String = "EmptySub") : Base("123")
|
||||
|
||||
val result = renderer.dataClassToTs(EmptySub::class, ttm, true)
|
||||
val result = renderer.dataClassToTs(EmptySub::class)
|
||||
|
||||
assertThat(result).contains("export interface EmptySub extends Base")
|
||||
assertThat(result).contains("type: \"EmptySub\";")
|
||||
@@ -84,7 +121,7 @@ class TsModelRendererTest {
|
||||
data class SubItem(val code: String)
|
||||
data class Container(val items: List<SubItem>)
|
||||
|
||||
val result = renderer.dataClassToTs(Container::class, ttm, false)
|
||||
val result = renderer.dataClassToTs(Container::class)
|
||||
|
||||
assertThat(result).contains("items: SubItem[];")
|
||||
}
|
||||
@@ -94,7 +131,7 @@ class TsModelRendererTest {
|
||||
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, ttm, false)
|
||||
val result = renderer.dataClassToTs(Child::class)
|
||||
|
||||
assertThat(result).contains("extends Parent")
|
||||
assertThat(result).contains("name: string;")
|
||||
@@ -109,7 +146,7 @@ class TsModelRendererTest {
|
||||
data class Sensor(val type: String = "TEMP_SENSOR", val value: Double)
|
||||
|
||||
// Tester med false for å verifisere at type-lappen utelates
|
||||
val sensorTs = renderer.dataClassToTs(Sensor::class, ttm, includeTypedInterface = false)
|
||||
val sensorTs = renderer.dataClassToTs(Sensor::class)
|
||||
|
||||
assertThat(sensorTs).doesNotContain("type: \"Sensor\";")
|
||||
assertThat(sensorTs).contains("value: number;")
|
||||
@@ -118,7 +155,7 @@ class TsModelRendererTest {
|
||||
@Test
|
||||
fun `should correctly extend abstract class and avoid duplicated properties`() {
|
||||
// 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
|
||||
assertThat(result).contains("extends AParent")
|
||||
|
||||
@@ -6,49 +6,47 @@ import org.junit.jupiter.api.Test
|
||||
|
||||
class TsTypeMapperTest {
|
||||
|
||||
private val mapper = TsTypeMapper()
|
||||
|
||||
@Test
|
||||
fun `should map primitives correctly`() {
|
||||
assertEquals("string", mapper.kotlinToTsType("kotlin.String"))
|
||||
assertEquals("number", mapper.kotlinToTsType("kotlin.Int"))
|
||||
assertEquals("number", mapper.kotlinToTsType("kotlin.Double"))
|
||||
assertEquals("boolean", mapper.kotlinToTsType("kotlin.Boolean"))
|
||||
assertEquals("string", TsTypeMapper.kotlinToTsType("kotlin.String"))
|
||||
assertEquals("number", TsTypeMapper.kotlinToTsType("kotlin.Int"))
|
||||
assertEquals("number", TsTypeMapper.kotlinToTsType("kotlin.Double"))
|
||||
assertEquals("boolean", TsTypeMapper.kotlinToTsType("kotlin.Boolean"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should map java types to string`() {
|
||||
assertEquals("string", mapper.kotlinToTsType("java.util.UUID"))
|
||||
assertEquals("string", mapper.kotlinToTsType("java.time.Instant"))
|
||||
assertEquals("string", TsTypeMapper.kotlinToTsType("java.util.UUID"))
|
||||
assertEquals("string", TsTypeMapper.kotlinToTsType("java.time.Instant"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should handle nullability`() {
|
||||
assertEquals("string | null", mapper.kotlinToTsType("kotlin.String?"))
|
||||
assertEquals("number | null", mapper.kotlinToTsType("kotlin.Int?"))
|
||||
assertEquals("string | null", TsTypeMapper.kotlinToTsType("kotlin.String?"))
|
||||
assertEquals("number | null", TsTypeMapper.kotlinToTsType("kotlin.Int?"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should map List and Set to arrays`() {
|
||||
assertEquals("string[]", mapper.kotlinToTsType("kotlin.collections.List<kotlin.String>"))
|
||||
assertEquals("number[]", mapper.kotlinToTsType("kotlin.collections.MutableSet<kotlin.Int>"))
|
||||
assertEquals("string[]", TsTypeMapper.kotlinToTsType("kotlin.collections.List<kotlin.String>"))
|
||||
assertEquals("number[]", TsTypeMapper.kotlinToTsType("kotlin.collections.MutableSet<kotlin.Int>"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should handle nested Map`() {
|
||||
val input = "kotlin.collections.Map<kotlin.String, kotlin.Int>"
|
||||
assertEquals("Record<string, number>", mapper.kotlinToTsType(input))
|
||||
assertEquals("Record<string, number>", TsTypeMapper.kotlinToTsType(input))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should handle generic parameters`() {
|
||||
// Antar at "T" er definert i genericParams
|
||||
val generics = listOf("T")
|
||||
assertEquals("T[]", mapper.kotlinToTsType("kotlin.collections.List<T>", generics))
|
||||
assertEquals("T[]", TsTypeMapper.kotlinToTsType("kotlin.collections.List<T>", generics))
|
||||
}
|
||||
|
||||
@Test
|
||||
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