Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bbd8f76f08 | ||
|
|
5780337b08 | ||
|
|
fc87ef4834 | ||
|
|
82672e97bf | ||
|
|
9a288d7728 | ||
|
|
21556018c8 | ||
|
|
22a8761f14 | ||
|
|
db6f311bfb | ||
|
|
6ab2e4082e | ||
|
|
e23373f73b | ||
|
|
0194b262c7 |
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:
|
||||
@@ -34,18 +37,6 @@ jobs:
|
||||
working-directory: ${{ github.workspace }}
|
||||
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
|
||||
run: ./gradlew wrapper
|
||||
|
||||
|
||||
+27
-16
@@ -1,33 +1,48 @@
|
||||
plugins {
|
||||
kotlin("jvm") version "2.3.21"
|
||||
kotlin("jvm") version "2.2.21"
|
||||
id("maven-publish")
|
||||
`java-gradle-plugin`
|
||||
`kotlin-dsl`
|
||||
}
|
||||
|
||||
group = "no.iktdev"
|
||||
version = "1.0-SNAPSHOT"
|
||||
val named = "ts-gen"
|
||||
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") ?: ""
|
||||
|
||||
val dynamicVersion = providers.provider {
|
||||
val ref = System.getenv("GITHUB_REF") ?: ""
|
||||
val isSnapshot = ref.endsWith("/master") || ref.endsWith("/main")
|
||||
// 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 {
|
||||
// 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.getOrElse("0.0.0").trim().removePrefix("v")
|
||||
}.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[0]}.${parts[1]}" else latestTag
|
||||
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.getOrElse("0").trim().toIntOrNull() ?: 0
|
||||
}.standardOutput.asText.get().trim().toIntOrNull() ?: 0
|
||||
|
||||
"$base.$patch-SNAPSHOT-$buildNumber"
|
||||
} else {
|
||||
latestTag
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
"0.0.1-SNAPSHOT"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
group = "no.iktdev"
|
||||
version = dynamicVersion
|
||||
val named = "ts-gen"
|
||||
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
@@ -66,11 +81,7 @@ tasks.jar {
|
||||
manifest {
|
||||
attributes(
|
||||
"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 provider {
|
||||
// Hvis du har definert dynamicVersion som en lokal val, kan du kalle .get() på den her:
|
||||
dynamicVersion.get()
|
||||
}
|
||||
"Implementation-Version" to project.version
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -96,7 +107,7 @@ publishing {
|
||||
if (name == "pluginMaven") {
|
||||
groupId = "no.iktdev"
|
||||
artifactId = "ts-gen"
|
||||
version = dynamicVersion.get()
|
||||
version = project.version.toString()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,4 +38,13 @@ class ClassScanner {
|
||||
|
||||
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
|
||||
|
||||
object TsGenerator {
|
||||
var consumerAppVersionInfo: String = "unknown"
|
||||
var versionInfo: String = TsGenerator::class.java.getPackage()?.implementationVersion
|
||||
?: TsGenerator::class.java.getResource("/META-INF/MANIFEST.MF")?.let {
|
||||
// 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 versionInfo: String = System.getProperty("tsgenerator.version")
|
||||
?: TsGenerator::class.java.getPackage()?.implementationVersion
|
||||
?: "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,
|
||||
includeSealed: Boolean = true,
|
||||
includeInterface: Boolean = true
|
||||
writeSealedStrategy: SealedStrategy,
|
||||
) = 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")
|
||||
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")
|
||||
classes.forEach { println(" - ${it.qualifiedName}") }
|
||||
@@ -33,43 +35,51 @@ object TsGenerator {
|
||||
val ts = buildString {
|
||||
appendLine("// AUTO-GENERATED. DO NOT EDIT.")
|
||||
appendLine("// TSGenerator Version: $versionInfo")
|
||||
appendLine("// Consumer App Version: $consumerAppVersionInfo")
|
||||
appendLine("// Time: $buildTime")
|
||||
appendLine("// Source: $packageName")
|
||||
appendLine("// package: $packageName")
|
||||
if (includeClasses.isNotEmpty()) {
|
||||
appendLine("// includeClasses:")
|
||||
includeClasses
|
||||
.filter { it.isNotBlank() }
|
||||
.distinct()
|
||||
.forEach { appendLine("//\t$it") }
|
||||
}
|
||||
|
||||
appendLine()
|
||||
|
||||
classes.forEach { cls ->
|
||||
when {
|
||||
// ----------------------------------------------------
|
||||
// 1) Sealed interface → union type alias
|
||||
// 1) Sealed interface → union type alias + evt. base interface
|
||||
// ----------------------------------------------------
|
||||
cls.isSealed && cls.java.isInterface -> {
|
||||
val subTypes = cls.sealedSubclasses
|
||||
.mapNotNull { it.simpleName }
|
||||
.joinToString(" | ")
|
||||
|
||||
println("Generating union type for sealed interface: ${cls.simpleName} = $subTypes")
|
||||
appendLine("export type ${cls.simpleName} = $subTypes")
|
||||
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 -> {
|
||||
val subTypes = cls.sealedSubclasses
|
||||
.mapNotNull { it.simpleName }
|
||||
.joinToString(" | ")
|
||||
|
||||
println("Generating union type for sealed class: ${cls.simpleName} = $subTypes")
|
||||
appendLine("export type ${cls.simpleName} = $subTypes")
|
||||
println("Generating sealed class: ${cls.simpleName}")
|
||||
append(tmr.sealedUnionToTs(cls, writeSealedStrategy))
|
||||
}
|
||||
|
||||
|
||||
// ----------------------------------------------------
|
||||
// 1b) Sealed subtype (data object / data class)
|
||||
// → generer interface selv uten properties
|
||||
// Sjekker strategien for type-felt og extends-base
|
||||
// ----------------------------------------------------
|
||||
cls.isSealedSubtype() -> {
|
||||
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 +91,11 @@ object TsGenerator {
|
||||
}
|
||||
|
||||
// ----------------------------------------------------
|
||||
// 3) Data class → interface
|
||||
// 3) Data class → interface (vanlige klasser)
|
||||
// ----------------------------------------------------
|
||||
cls.hasProperties() && !cls.isSealed -> {
|
||||
println("Generating interface: ${cls.simpleName}")
|
||||
append(tmr.dataClassToTs(cls, ttm, includeInterface))
|
||||
append(tmr.dataClassToTs(cls))
|
||||
}
|
||||
|
||||
else -> {
|
||||
@@ -101,5 +111,4 @@ object TsGenerator {
|
||||
|
||||
println("TsGenerator: wrote file to ${output.absolutePath}")
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package no.iktdev.ts
|
||||
|
||||
import no.iktdev.ts.anno.TsMapStrategy
|
||||
import kotlin.reflect.KClass
|
||||
import kotlin.reflect.full.findAnnotation
|
||||
import kotlin.reflect.full.memberProperties
|
||||
import kotlin.reflect.full.primaryConstructor
|
||||
|
||||
@@ -13,14 +15,66 @@ class TsModelRenderer {
|
||||
return "export type ${cls.simpleName} = $values\n"
|
||||
}
|
||||
|
||||
fun sealedSubtypeToTs(cls: KClass<*>, ttm: TsTypeMapper, includeTypeDiscriminator: Boolean): String {
|
||||
return dataClassToTs(cls, ttm, includeTypeDiscriminator)
|
||||
// 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(" | ")
|
||||
|
||||
if (strategy == SealedStrategy.ONLY_TYPED) {
|
||||
return "export type ${cls.simpleName} = $subTypes\n"
|
||||
}
|
||||
|
||||
fun dataClassToTs(cls: KClass<*>, ttm: TsTypeMapper, includeTypeDiscriminator: Boolean): String {
|
||||
val typeParams = cls.typeParameters.map { it.name }
|
||||
val generic = if (typeParams.isNotEmpty()) "<" + typeParams.joinToString(", ") + ">" else ""
|
||||
// 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}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 superClass = cls.java.superclass?.kotlin
|
||||
if (superClass != null && superClass != Any::class) {
|
||||
@@ -32,36 +86,71 @@ 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()
|
||||
|
||||
// Sjekk om klassen har et 'type'-felt, og tving det til klassens navn hvis flagget er satt
|
||||
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 ->
|
||||
val tsType = if (prop.name == "type" && includeTypeDiscriminator) {
|
||||
// Tving type-feltet til å bli en string literal basert på klassens navn (f.eks. "FileCopyProgress")
|
||||
"\"${cls.simpleName}\""
|
||||
val mapStrategy = prop.findAnnotation<TsMapStrategy>()?.value
|
||||
?: MapStrategy.MapAsRecord
|
||||
|
||||
val tsType = if (prop.name == "type" && defaultTypeLiteral != null) {
|
||||
"\"$defaultTypeLiteral\""
|
||||
} else {
|
||||
ttm.kotlinToTsType(prop.returnType.toString(), typeParams)
|
||||
TsTypeMapper.kotlinToTsType(
|
||||
prop.returnType.toString(),
|
||||
typeParams,
|
||||
mapStrategy
|
||||
)
|
||||
}
|
||||
" ${prop.name}: $tsType;"
|
||||
}
|
||||
|
||||
val propsBlock = if (props.isBlank()) "" else "\n$props"
|
||||
|
||||
return buildString {
|
||||
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 (includeTypeDiscriminator && !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,9 +1,19 @@
|
||||
package no.iktdev.ts
|
||||
|
||||
class TsTypeMapper {
|
||||
fun kotlinToTsType(kotlinType: String, genericParams: List<String> = emptyList()): String {
|
||||
object TsTypeMapper {
|
||||
fun kotlinToTsType(
|
||||
kotlinType: String,
|
||||
genericParams: List<String> = emptyList(),
|
||||
mapStrategy: MapStrategy = MapStrategy.MapAsRecord,
|
||||
): String {
|
||||
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
|
||||
if (clean == "java.util.UUID") {
|
||||
@@ -20,7 +30,7 @@ class TsTypeMapper {
|
||||
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") ||
|
||||
clean.startsWith("kotlin.collections.MutableMap")) {
|
||||
|
||||
@@ -30,7 +40,13 @@ class TsTypeMapper {
|
||||
val tsKey = kotlinToTsType(key, 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
|
||||
}
|
||||
|
||||
@@ -66,7 +82,7 @@ class TsTypeMapper {
|
||||
return if (isNullable) "$base | null" else base
|
||||
}
|
||||
|
||||
// Primitive mappings
|
||||
// Primitive mappings / Klasser
|
||||
val base = when (clean) {
|
||||
"kotlin.String" -> "string"
|
||||
"kotlin.Int",
|
||||
@@ -76,8 +92,8 @@ class TsTypeMapper {
|
||||
"kotlin.Boolean" -> "boolean"
|
||||
"kotlin.Any" -> "any"
|
||||
else -> {
|
||||
if (clean.contains(".")) clean.substringAfterLast(".")
|
||||
else "any"
|
||||
// Stripper vekk alt av pakkenavn og eventuelle lokale test-referanser med $
|
||||
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
|
||||
|
||||
import no.iktdev.ts.SealedStrategy
|
||||
import no.iktdev.ts.TsGenerator
|
||||
import org.gradle.api.Plugin
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.api.plugins.JavaPluginExtension
|
||||
import org.gradle.api.provider.Property
|
||||
import org.gradle.api.provider.ListProperty
|
||||
import java.io.File
|
||||
import java.net.URLClassLoader
|
||||
|
||||
interface TsGeneratorExtension {
|
||||
val packageName: Property<String>
|
||||
val includeClasses: ListProperty<String>
|
||||
val outputFile: Property<File>
|
||||
|
||||
val includeSealed: Property<Boolean>
|
||||
val includeInterface: 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 {
|
||||
includeSealed.convention(true)
|
||||
includeInterface.convention(true)
|
||||
sealedStrategy.convention(SealedStrategy.AS_INTERFACE_WITH_TYPE)
|
||||
includeClasses.convention(emptyList())
|
||||
}
|
||||
|
||||
project.tasks.register("generateTs") {
|
||||
group = "typescript"
|
||||
dependsOn("compileKotlin")
|
||||
|
||||
doLast {
|
||||
TsGenerator.versionInfo = project.version.toString()
|
||||
TsGenerator.buildTime = java.time.Instant.now().toString()
|
||||
|
||||
val pkg = extension.packageName.get()
|
||||
val includedClasses = extension.includeClasses.get()
|
||||
val out = extension.outputFile.get()
|
||||
val includeSealed = extension.includeSealed.get()
|
||||
val includeInterface = extension.includeInterface.get()
|
||||
val writeSealedStrategy = extension.sealedStrategy.get()
|
||||
|
||||
// Hent classpath for å lage ClassLoaderen
|
||||
val mainSourceSet = project.extensions.getByType(JavaPluginExtension::class.java)
|
||||
@@ -44,7 +44,7 @@ class TsGeneratorPlugin : Plugin<Project> {
|
||||
val cl = URLClassLoader(urls, TsGenerator::class.java.classLoader)
|
||||
|
||||
// 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 {
|
||||
|
||||
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;")
|
||||
@@ -40,22 +39,114 @@ class TsModelRendererTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sealed subtype test - verifiser type discriminator`() {
|
||||
data class Sensor(val type: String = "TEMP_SENSOR", val value: Double)
|
||||
fun `should handle generic classes correctly`() {
|
||||
data class Wrapper<T>(val data: T, val message: String?)
|
||||
|
||||
// Send med true for å inkludere type-diskriminatoren i testen
|
||||
val sensorTs = renderer.sealedSubtypeToTs(Sensor::class, ttm, includeTypeDiscriminator = 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;")
|
||||
}
|
||||
|
||||
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("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
|
||||
fun `sealed subtype test - no type when off`() {
|
||||
data class Sensor(val type: String = "TEMP_SENSOR", val value: Double)
|
||||
|
||||
// Send med true for å inkludere type-diskriminatoren i testen
|
||||
val sensorTs = renderer.sealedSubtypeToTs(Sensor::class, ttm, includeTypeDiscriminator = false)
|
||||
// Tester med false for å verifisere at type-lappen utelates
|
||||
val sensorTs = renderer.dataClassToTs(Sensor::class)
|
||||
|
||||
assertThat(sensorTs).doesNotContain("type: \"Sensor\";")
|
||||
assertThat(sensorTs).contains("value: number;")
|
||||
@@ -64,18 +155,16 @@ 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")
|
||||
|
||||
// 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("interfaceName: string;")
|
||||
|
||||
// 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[];")
|
||||
|
||||
// 5. Sjekk at klassenavnet er riktig
|
||||
|
||||
@@ -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