├── gradle.properties ├── .github ├── FUNDING.yml └── workflows │ ├── junie.yml │ └── tests.yml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── zodable-ksp-processor ├── src │ └── main │ │ ├── resources │ │ └── META-INF │ │ │ └── services │ │ │ └── com.google.devtools.ksp.processing.SymbolProcessorProvider │ │ └── kotlin │ │ └── digital │ │ └── guimauve │ │ └── zodable │ │ ├── config │ │ ├── Export.kt │ │ ├── Import.kt │ │ └── GeneratorConfig.kt │ │ ├── ZodableProcessorProvider.kt │ │ ├── ZodableProcessor.kt │ │ └── generators │ │ ├── PythonGenerator.kt │ │ ├── TypescriptGenerator.kt │ │ └── ZodableGenerator.kt └── build.gradle.kts ├── sample-package ├── src │ └── main │ │ └── kotlin │ │ └── digital │ │ └── guimauve │ │ └── example │ │ ├── Message.kt │ │ ├── Country.kt │ │ ├── Street.kt │ │ ├── Address.kt │ │ ├── MyModel.kt │ │ ├── Payload.kt │ │ ├── Custom.kt │ │ └── User.kt └── build.gradle.kts ├── zodable-annotations ├── src │ └── commonMain │ │ └── kotlin │ │ └── digital │ │ └── guimauve │ │ └── zodable │ │ ├── Zodable.kt │ │ ├── ZodIgnore.kt │ │ ├── ZodType.kt │ │ ├── ZodOverrideSchema.kt │ │ └── ZodImport.kt └── build.gradle.kts ├── zodable-gradle-plugin ├── src │ └── main │ │ └── kotlin │ │ └── digital │ │ └── guimauve │ │ └── zodable │ │ ├── ExecCommand.kt │ │ ├── KspConfig.kt │ │ ├── Optionals.kt │ │ ├── extensions │ │ └── ZodableExtension.kt │ │ ├── Files.kt │ │ └── ZodablePlugin.kt └── build.gradle.kts ├── sample-package-multiplatform ├── src │ └── commonMain │ │ └── kotlin │ │ └── digital │ │ └── guimauve │ │ └── example │ │ ├── MultiplatformType.kt │ │ └── MultiplatformUser.kt └── build.gradle.kts ├── .devcontainer └── devcontainer.json ├── settings.gradle.kts ├── .gitignore ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official 2 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [ guimauvedigital, nathanfallet ] 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guimauvedigital/zodable/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /zodable-ksp-processor/src/main/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider: -------------------------------------------------------------------------------- 1 | digital.guimauve.zodable.ZodableProcessorProvider 2 | -------------------------------------------------------------------------------- /zodable-ksp-processor/src/main/kotlin/digital/guimauve/zodable/config/Export.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.zodable.config 2 | 3 | data class Export( 4 | val name: String, 5 | val packageName: String, 6 | ) 7 | -------------------------------------------------------------------------------- /sample-package/src/main/kotlin/digital/guimauve/example/Message.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.example 2 | 3 | import digital.guimauve.zodable.Zodable 4 | 5 | @Zodable 6 | data class Message( 7 | val content: T, 8 | ) 9 | -------------------------------------------------------------------------------- /zodable-annotations/src/commonMain/kotlin/digital/guimauve/zodable/Zodable.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.zodable 2 | 3 | @Target(AnnotationTarget.CLASS) 4 | @Retention(AnnotationRetention.RUNTIME) 5 | annotation class Zodable 6 | -------------------------------------------------------------------------------- /zodable-gradle-plugin/src/main/kotlin/digital/guimauve/zodable/ExecCommand.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.zodable 2 | 3 | data class ExecCommand( 4 | val commandLine: List, 5 | val standardInput: String? = null, 6 | ) 7 | -------------------------------------------------------------------------------- /sample-package/src/main/kotlin/digital/guimauve/example/Country.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.example 2 | 3 | import digital.guimauve.zodable.Zodable 4 | 5 | @Zodable 6 | enum class Country { 7 | 8 | FRANCE, US 9 | 10 | } 11 | -------------------------------------------------------------------------------- /sample-package/src/main/kotlin/digital/guimauve/example/Street.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.example 2 | 3 | // value classes do not need to be annotated with Zodable if valueClassUnwrap = true 4 | @JvmInline 5 | value class Street(val name: String) 6 | -------------------------------------------------------------------------------- /zodable-gradle-plugin/src/main/kotlin/digital/guimauve/zodable/KspConfig.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.zodable 2 | 3 | data class KspConfig( 4 | val apiConfigurationName: String, 5 | val kspConfigurationName: String, 6 | val taskName: String, 7 | ) 8 | -------------------------------------------------------------------------------- /sample-package-multiplatform/src/commonMain/kotlin/digital/guimauve/example/MultiplatformType.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.example 2 | 3 | import digital.guimauve.zodable.Zodable 4 | 5 | @Zodable 6 | enum class MultiplatformType { 7 | 8 | JVM, NATIVE, JS 9 | 10 | } 11 | -------------------------------------------------------------------------------- /zodable-gradle-plugin/src/main/kotlin/digital/guimauve/zodable/Optionals.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.zodable 2 | 3 | enum class Optionals( 4 | val zodType: String, 5 | ) { 6 | 7 | NULLABLE(".nullable()"), NULLISH(".nullish()"), OPTIONAL(".optional()"); 8 | 9 | } 10 | -------------------------------------------------------------------------------- /zodable-annotations/src/commonMain/kotlin/digital/guimauve/zodable/ZodIgnore.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.zodable 2 | 3 | @Target(AnnotationTarget.PROPERTY) 4 | @Retention(AnnotationRetention.RUNTIME) 5 | @Repeatable 6 | annotation class ZodIgnore( 7 | val filter: String = "*", 8 | ) 9 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sat Mar 30 15:02:52 CET 2024 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /sample-package/src/main/kotlin/digital/guimauve/example/Address.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.example 2 | 3 | import digital.guimauve.zodable.Zodable 4 | 5 | @Zodable 6 | data class Address( 7 | val street: Street, 8 | val city: String, 9 | val country: Country, 10 | ) 11 | -------------------------------------------------------------------------------- /zodable-annotations/src/commonMain/kotlin/digital/guimauve/zodable/ZodType.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.zodable 2 | 3 | @Target(AnnotationTarget.PROPERTY) 4 | @Retention(AnnotationRetention.RUNTIME) 5 | @Repeatable 6 | annotation class ZodType( 7 | val value: String, 8 | val filter: String = "*", 9 | ) 10 | -------------------------------------------------------------------------------- /zodable-annotations/src/commonMain/kotlin/digital/guimauve/zodable/ZodOverrideSchema.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.zodable 2 | 3 | @Target(AnnotationTarget.CLASS) 4 | @Retention(AnnotationRetention.RUNTIME) 5 | @Repeatable 6 | annotation class ZodOverrideSchema( 7 | val content: String, 8 | val filter: String = "*", 9 | ) 10 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Java", 3 | "image": "mcr.microsoft.com/devcontainers/java:1-21", 4 | "features": { 5 | "ghcr.io/devcontainers/features/java:1": { 6 | "version": "none", 7 | "installMaven": "true", 8 | "mavenVersion": "3.8.6", 9 | "installGradle": "true" 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /sample-package/src/main/kotlin/digital/guimauve/example/MyModel.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.example 2 | 3 | import digital.guimauve.zodable.Zodable 4 | import kotlin.uuid.ExperimentalUuidApi 5 | import kotlin.uuid.Uuid 6 | 7 | @OptIn(ExperimentalUuidApi::class) 8 | @Zodable 9 | data class MyModel( 10 | val id: Uuid, 11 | val name: String, 12 | ) 13 | -------------------------------------------------------------------------------- /zodable-annotations/src/commonMain/kotlin/digital/guimauve/zodable/ZodImport.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.zodable 2 | 3 | @Target(AnnotationTarget.CLASS) 4 | @Retention(AnnotationRetention.RUNTIME) 5 | @Repeatable 6 | annotation class ZodImport( 7 | val name: String, 8 | val source: String, 9 | val filter: String = "*", 10 | val isInvariable: Boolean = false, 11 | ) 12 | -------------------------------------------------------------------------------- /zodable-ksp-processor/src/main/kotlin/digital/guimauve/zodable/config/Import.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.zodable.config 2 | 3 | data class Import( 4 | val name: String, 5 | val source: String, 6 | val isExternal: Boolean = false, 7 | val isInvariable: Boolean = false, 8 | val isDependency: Boolean = true, 9 | val dependencyVersion: String? = null, 10 | ) 11 | -------------------------------------------------------------------------------- /sample-package-multiplatform/src/commonMain/kotlin/digital/guimauve/example/MultiplatformUser.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.example 2 | 3 | import digital.guimauve.zodable.Zodable 4 | import kotlin.uuid.ExperimentalUuidApi 5 | import kotlin.uuid.Uuid 6 | 7 | @OptIn(ExperimentalUuidApi::class) 8 | @Zodable 9 | data class MultiplatformUser( 10 | val id: Uuid, 11 | val type: MultiplatformType, 12 | ) 13 | -------------------------------------------------------------------------------- /zodable-ksp-processor/src/main/kotlin/digital/guimauve/zodable/config/GeneratorConfig.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.zodable.config 2 | 3 | import java.io.File 4 | 5 | data class GeneratorConfig( 6 | val packageName: String, 7 | val outputPath: File, 8 | val inferTypes: Boolean, 9 | val coerceMapKeys: Boolean, 10 | val optionals: String, 11 | val valueClassUnwrap: Boolean, 12 | ) 13 | -------------------------------------------------------------------------------- /sample-package/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | kotlin("jvm") 3 | id("digital.guimauve.zodable") 4 | id("com.google.devtools.ksp") 5 | } 6 | 7 | dependencies { 8 | api(project(":sample-package-multiplatform")) 9 | api("org.jetbrains.kotlinx:kotlinx-datetime:0.7.1") 10 | } 11 | 12 | zodable { 13 | packageName = "zodable-sample-package" 14 | enablePython = true // Default is false 15 | valueClassUnwrap = true 16 | } 17 | -------------------------------------------------------------------------------- /sample-package/src/main/kotlin/digital/guimauve/example/Payload.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.example 2 | 3 | import digital.guimauve.zodable.Zodable 4 | import kotlinx.serialization.SerialName 5 | 6 | @Zodable 7 | sealed class Payload { 8 | 9 | @SerialName("EMPTY") 10 | data object EmptyPayload : Payload() 11 | 12 | @SerialName("TEXT") 13 | data class TextPayload( 14 | val text: String, 15 | ) : Payload() 16 | 17 | } 18 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | mavenCentral() 4 | gradlePluginPortal() 5 | } 6 | } 7 | 8 | plugins { 9 | id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0" 10 | } 11 | 12 | rootProject.name = "zodable" 13 | includeBuild("zodable-gradle-plugin") 14 | include(":zodable-annotations") 15 | include(":zodable-ksp-processor") 16 | 17 | include(":sample-package") 18 | include(":sample-package-multiplatform") 19 | -------------------------------------------------------------------------------- /zodable-ksp-processor/src/main/kotlin/digital/guimauve/zodable/ZodableProcessorProvider.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.zodable 2 | 3 | import com.google.devtools.ksp.processing.SymbolProcessor 4 | import com.google.devtools.ksp.processing.SymbolProcessorEnvironment 5 | import com.google.devtools.ksp.processing.SymbolProcessorProvider 6 | 7 | class ZodableProcessorProvider : SymbolProcessorProvider { 8 | 9 | override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor { 10 | return ZodableProcessor(environment) 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /.github/workflows/junie.yml: -------------------------------------------------------------------------------- 1 | name: Junie 2 | run-name: Junie run ${{ inputs.run_id }} 3 | 4 | permissions: 5 | contents: write 6 | pull-requests: write 7 | 8 | on: 9 | workflow_dispatch: 10 | inputs: 11 | run_id: 12 | description: "id of workflow process" 13 | required: true 14 | workflow_params: 15 | description: "stringified params" 16 | required: true 17 | 18 | jobs: 19 | call-workflow-passing-data: 20 | uses: jetbrains-junie/junie-workflows/.github/workflows/ej-issue.yml@main 21 | with: 22 | workflow_params: ${{ inputs.workflow_params }} 23 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Run tests 2 | on: 3 | push: 4 | branches: [ main ] 5 | pull_request: 6 | branches: [ main ] 7 | 8 | jobs: 9 | test: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout 13 | uses: actions/checkout@v3 14 | - name: Set up Java 15 | uses: actions/setup-java@v3 16 | with: 17 | distribution: temurin 18 | java-version: 21 19 | - name: Build project 20 | run: ./gradlew build allTest 21 | - name: Get report 22 | run: ./gradlew koverXmlReport 23 | - name: Upload coverage reports to Codecov 24 | uses: codecov/codecov-action@v5 25 | with: 26 | token: ${{ secrets.CODECOV_TOKEN }} 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | .kotlin 3 | .idea 4 | .fleet 5 | build/ 6 | !gradle/wrapper/gradle-wrapper.jar 7 | !**/src/main/**/build/ 8 | !**/src/test/**/build/ 9 | local.properties 10 | 11 | ### IntelliJ IDEA ### 12 | .idea/modules.xml 13 | .idea/jarRepositories.xml 14 | .idea/compiler.xml 15 | .idea/libraries/ 16 | *.iws 17 | *.iml 18 | *.ipr 19 | out/ 20 | !**/src/main/**/out/ 21 | !**/src/test/**/out/ 22 | 23 | ### Eclipse ### 24 | .apt_generated 25 | .classpath 26 | .factorypath 27 | .project 28 | .settings 29 | .springBeans 30 | .sts4-cache 31 | bin/ 32 | !**/src/main/**/bin/ 33 | !**/src/test/**/bin/ 34 | 35 | ### NetBeans ### 36 | /nbproject/private/ 37 | /nbbuild/ 38 | /dist/ 39 | /nbdist/ 40 | /.nb-gradle/ 41 | 42 | ### VS Code ### 43 | .vscode/ 44 | 45 | ### Mac OS ### 46 | .DS_Store 47 | 48 | ### JS ### 49 | yarn.lock 50 | -------------------------------------------------------------------------------- /sample-package/src/main/kotlin/digital/guimauve/example/Custom.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.example 2 | 3 | import digital.guimauve.zodable.ZodOverrideSchema 4 | import digital.guimauve.zodable.Zodable 5 | 6 | @Zodable 7 | @ZodOverrideSchema( 8 | content = """ 9 | export const CustomSchema = z.object({ 10 | name: z.string(), 11 | age: z.number().int(), 12 | isActive: z.boolean(), 13 | tags: z.array(z.string()), 14 | }) 15 | export type Custom = z.infer 16 | """, 17 | filter = "ts" 18 | ) 19 | @ZodOverrideSchema( 20 | content = """ 21 | from typing import List 22 | 23 | class Custom(BaseModel): 24 | name: str 25 | age: int 26 | is_active: bool 27 | tags: List[str] 28 | """, 29 | filter = "py" 30 | ) 31 | interface Custom 32 | -------------------------------------------------------------------------------- /zodable-gradle-plugin/src/main/kotlin/digital/guimauve/zodable/extensions/ZodableExtension.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.zodable.extensions 2 | 3 | import digital.guimauve.zodable.Optionals 4 | import org.gradle.api.provider.ListProperty 5 | import org.gradle.api.provider.MapProperty 6 | import org.gradle.api.provider.Property 7 | 8 | interface ZodableExtension { 9 | 10 | val enableTypescript: Property 11 | val enablePython: Property 12 | val inferTypes: Property 13 | val coerceMapKeys: Property 14 | val optionals: Property 15 | val packageName: Property 16 | val packageVersion: Property 17 | val additionalNpmCommands: ListProperty> 18 | val externalPackageInstallCommands: MapProperty> 19 | val externalPackageLocations: MapProperty 20 | val valueClassUnwrap: Property 21 | 22 | } 23 | -------------------------------------------------------------------------------- /zodable-gradle-plugin/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | `kotlin-dsl` 3 | id("com.gradle.plugin-publish") version "1.2.1" 4 | id("com.google.devtools.ksp") version "2.2.20-2.0.4" 5 | } 6 | 7 | repositories { 8 | gradlePluginPortal() 9 | mavenCentral() 10 | } 11 | 12 | kotlin { 13 | dependencies { 14 | implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:2.2.20") 15 | implementation("com.google.devtools.ksp:com.google.devtools.ksp.gradle.plugin:2.2.20-2.0.4") 16 | } 17 | } 18 | 19 | group = "digital.guimauve.zodable" 20 | version = "1.7.2" 21 | 22 | gradlePlugin { 23 | website = "https://github.com/guimauvedigital/zodable" 24 | vcsUrl = "https://github.com/guimauvedigital/zodable.git" 25 | 26 | plugins { 27 | create("zodable-gradle-plugin") { 28 | id = "digital.guimauve.zodable" 29 | implementationClass = "digital.guimauve.zodable.ZodablePlugin" 30 | displayName = "Zodable" 31 | description = "Generate zod schemas from Kotlin data classes." 32 | tags = listOf("zod", "ts", "ksp") 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /sample-package-multiplatform/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | kotlin("multiplatform") 3 | id("digital.guimauve.zodable") 4 | id("com.google.devtools.ksp") 5 | } 6 | 7 | kotlin { 8 | // Tiers are in accordance with 9 | // Tier 1 10 | macosX64() 11 | macosArm64() 12 | iosSimulatorArm64() 13 | iosX64() 14 | 15 | // Tier 2 16 | linuxX64() 17 | linuxArm64() 18 | watchosSimulatorArm64() 19 | watchosX64() 20 | watchosArm32() 21 | watchosArm64() 22 | tvosSimulatorArm64() 23 | tvosX64() 24 | tvosArm64() 25 | iosArm64() 26 | 27 | // Tier 3 28 | mingwX64() 29 | watchosDeviceArm64() 30 | 31 | // jvm & js 32 | jvmToolchain(21) 33 | jvm { 34 | testRuns.named("test") { 35 | executionTask.configure { 36 | useJUnitPlatform() 37 | } 38 | } 39 | } 40 | js { 41 | generateTypeScriptDefinitions() 42 | binaries.library() 43 | nodejs() 44 | browser() 45 | } 46 | 47 | applyDefaultHierarchyTemplate() 48 | sourceSets { 49 | val commonMain by getting { 50 | dependencies { 51 | 52 | } 53 | } 54 | } 55 | } 56 | 57 | zodable { 58 | packageName = "zodable-sample-package-multiplatform" 59 | enablePython = true // Default is false 60 | } 61 | -------------------------------------------------------------------------------- /zodable-ksp-processor/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | kotlin("jvm") 3 | kotlin("plugin.serialization") 4 | id("org.jetbrains.kotlinx.kover") 5 | id("com.google.devtools.ksp") 6 | id("com.vanniktech.maven.publish") 7 | } 8 | 9 | mavenPublishing { 10 | publishToMavenCentral(com.vanniktech.maven.publish.SonatypeHost.CENTRAL_PORTAL) 11 | signAllPublications() 12 | pom { 13 | name.set("zodable-ksp-processor") 14 | description.set("KSP processor for Zodable Gradle plugin.") 15 | url.set(project.ext.get("url")?.toString()) 16 | licenses { 17 | license { 18 | name.set(project.ext.get("license.name")?.toString()) 19 | url.set(project.ext.get("license.url")?.toString()) 20 | } 21 | } 22 | developers { 23 | developer { 24 | id.set(project.ext.get("developer.id")?.toString()) 25 | name.set(project.ext.get("developer.name")?.toString()) 26 | email.set(project.ext.get("developer.email")?.toString()) 27 | url.set(project.ext.get("developer.url")?.toString()) 28 | } 29 | } 30 | scm { 31 | url.set(project.ext.get("scm.url")?.toString()) 32 | } 33 | } 34 | } 35 | 36 | dependencies { 37 | api("com.google.devtools.ksp:symbol-processing-api:2.2.20-2.0.4") 38 | api(project(":zodable-annotations")) 39 | } 40 | -------------------------------------------------------------------------------- /zodable-gradle-plugin/src/main/kotlin/digital/guimauve/zodable/Files.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.zodable 2 | 3 | object Files { 4 | 5 | fun String.pythonCompatible() = this.replace("-", "_") 6 | 7 | const val ZOD_DESCRIPTION = "Auto-generated zod project from Kotlin using guimauvedigital/zodable" 8 | 9 | fun generatePyProjectToml( 10 | name: String, 11 | version: String, 12 | ): String = 13 | """ 14 | import sys 15 | import toml 16 | import subprocess 17 | 18 | project = { 19 | "name": "$name", 20 | "version": "$version", 21 | "description": "Auto-generated Pydantic project from Kotlin using guimauvedigital/zodable", 22 | "dependencies": [], 23 | "requires-python": ">=3.9" 24 | } 25 | 26 | with open("requirements.txt", "r") as f: 27 | deps = [line.strip() for line in f if line.strip() and not line.startswith("#")] 28 | project["dependencies"] = [dep.replace("==", ">=") for dep in deps] 29 | 30 | pyproject = { 31 | "project": project, 32 | "build-system": { 33 | "requires": ["setuptools", "wheel"], 34 | "build-backend": "setuptools.build_meta" 35 | }, 36 | "tool": { 37 | "setuptools": { 38 | "package-data": { 39 | "${name.pythonCompatible()}": ["py.typed"] 40 | } 41 | }, 42 | "mypy": { 43 | "strict": True 44 | } 45 | } 46 | } 47 | 48 | with open("pyproject.toml", "w") as f: 49 | toml.dump(pyproject, f) 50 | """.trimIndent() 51 | 52 | } 53 | -------------------------------------------------------------------------------- /sample-package/src/main/kotlin/digital/guimauve/example/User.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.example 2 | 3 | import digital.guimauve.zodable.ZodIgnore 4 | import digital.guimauve.zodable.ZodImport 5 | import digital.guimauve.zodable.ZodType 6 | import digital.guimauve.zodable.Zodable 7 | import kotlinx.datetime.LocalDate 8 | import kotlinx.datetime.LocalDateTime 9 | import kotlinx.serialization.SerialName 10 | import kotlin.time.ExperimentalTime 11 | import kotlin.time.Instant 12 | import kotlin.uuid.ExperimentalUuidApi 13 | import kotlin.uuid.Uuid 14 | 15 | @ZodImport("IdSchema", "zodable-idschema", isInvariable = true) 16 | @ZodImport("MultiplatformUser", "zodable-sample-package-multiplatform") 17 | 18 | @OptIn(ExperimentalUuidApi::class, ExperimentalTime::class) 19 | @Zodable 20 | data class User( 21 | val id: Uuid, 22 | val name: String, 23 | val email: String?, 24 | val followers: Int, 25 | val addresses: List
, // List of another annotated class 26 | val tags: List, // List of primitive type 27 | val settings: Map, // Map of primitive types 28 | val eventsByYear: Map>, // Map of primitive types, with non-string key 29 | val contactGroups: Map>, // Nested generics 30 | val coordinates: Pair, // Pair of primitive types 31 | val createdAt: Instant, 32 | val day: LocalDate, 33 | val daytime: LocalDateTime, 34 | val externalUser: MultiplatformUser, 35 | @ZodType("z.date()", "ts") @ZodType("datetime", "py") val birthDate: String, // Custom mapping 36 | @ZodType("IdSchema") val otherId: Uuid, 37 | @ZodIgnore val ignored: String, // Ignored property 38 | @SerialName("custom_name") val customName: String, // Custom serialization name 39 | val message: Message, 40 | ) { 41 | 42 | val notIncluded: Boolean 43 | get() = true 44 | 45 | } 46 | -------------------------------------------------------------------------------- /zodable-annotations/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | kotlin("multiplatform") 3 | kotlin("plugin.serialization") 4 | id("com.vanniktech.maven.publish") 5 | } 6 | 7 | mavenPublishing { 8 | publishToMavenCentral(com.vanniktech.maven.publish.SonatypeHost.CENTRAL_PORTAL) 9 | signAllPublications() 10 | pom { 11 | name.set("zodable-annotations") 12 | description.set("Annotations for Zodable Gradle plugin.") 13 | url.set(project.ext.get("url")?.toString()) 14 | licenses { 15 | license { 16 | name.set(project.ext.get("license.name")?.toString()) 17 | url.set(project.ext.get("license.url")?.toString()) 18 | } 19 | } 20 | developers { 21 | developer { 22 | id.set(project.ext.get("developer.id")?.toString()) 23 | name.set(project.ext.get("developer.name")?.toString()) 24 | email.set(project.ext.get("developer.email")?.toString()) 25 | url.set(project.ext.get("developer.url")?.toString()) 26 | } 27 | } 28 | scm { 29 | url.set(project.ext.get("scm.url")?.toString()) 30 | } 31 | } 32 | } 33 | 34 | kotlin { 35 | // Tiers are in accordance with 36 | // Tier 1 37 | macosX64() 38 | macosArm64() 39 | iosSimulatorArm64() 40 | iosX64() 41 | 42 | // Tier 2 43 | linuxX64() 44 | linuxArm64() 45 | watchosSimulatorArm64() 46 | watchosX64() 47 | watchosArm32() 48 | watchosArm64() 49 | tvosSimulatorArm64() 50 | tvosX64() 51 | tvosArm64() 52 | iosArm64() 53 | 54 | // Tier 3 55 | mingwX64() 56 | watchosDeviceArm64() 57 | 58 | // jvm & js 59 | jvmToolchain(21) 60 | jvm { 61 | testRuns.named("test") { 62 | executionTask.configure { 63 | useJUnitPlatform() 64 | } 65 | } 66 | } 67 | js { 68 | generateTypeScriptDefinitions() 69 | binaries.library() 70 | nodejs() 71 | browser() 72 | } 73 | 74 | applyDefaultHierarchyTemplate() 75 | sourceSets { 76 | val commonMain by getting { 77 | dependencies { 78 | api("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0") 79 | } 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /zodable-ksp-processor/src/main/kotlin/digital/guimauve/zodable/ZodableProcessor.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.zodable 2 | 3 | import com.google.devtools.ksp.processing.Resolver 4 | import com.google.devtools.ksp.processing.SymbolProcessor 5 | import com.google.devtools.ksp.processing.SymbolProcessorEnvironment 6 | import com.google.devtools.ksp.symbol.KSAnnotated 7 | import com.google.devtools.ksp.symbol.KSClassDeclaration 8 | import digital.guimauve.zodable.config.GeneratorConfig 9 | import digital.guimauve.zodable.generators.PythonGenerator 10 | import digital.guimauve.zodable.generators.TypescriptGenerator 11 | import java.io.File 12 | import java.nio.file.Paths 13 | 14 | class ZodableProcessor( 15 | private val env: SymbolProcessorEnvironment, 16 | ) : SymbolProcessor { 17 | 18 | val enableTypescript = env.options["zodableEnableTypescript"].equals("true") 19 | val enablePython = env.options["zodableEnablePython"].equals("true") 20 | val packageName = env.options["zodablePackageName"] ?: "zodable" 21 | val outputPath = env.options["zodableOutputPath"] ?: "" 22 | val inferTypes = env.options["zodableInferTypes"].equals("true") 23 | val coerceMapKeys = env.options["zodableCoerceMapKeys"].equals("true") 24 | val optionals = env.options["zodableOptionals"] ?: "" 25 | val valueClassUnwrap = env.options["zodableValueClassUnwrap"].equals("true") 26 | 27 | val outputPathFile: File by lazy { Paths.get(outputPath).toFile().also { it.mkdirs() } } 28 | val config by lazy { GeneratorConfig(packageName, outputPathFile, inferTypes, coerceMapKeys, optionals, valueClassUnwrap) } 29 | val typescriptGenerator by lazy { TypescriptGenerator(env, config) } 30 | val pythonGenerator by lazy { 31 | val pythonOutputPath = outputPathFile.parentFile.resolve("pydantable").also { it.mkdirs() } 32 | PythonGenerator(env, config.copy(outputPath = pythonOutputPath)) 33 | } 34 | 35 | override fun process(resolver: Resolver): List { 36 | val annotatedClasses = resolver.getSymbolsWithAnnotation(Zodable::class.qualifiedName!!) 37 | .filterIsInstance() 38 | 39 | if (enableTypescript) { 40 | typescriptGenerator.generateFiles(annotatedClasses) 41 | } 42 | if (enablePython) { 43 | pythonGenerator.generateFiles(annotatedClasses) 44 | } 45 | 46 | return emptyList() 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # zodable 2 | 3 | Generate zod schemas from Kotlin data classes. 4 | 5 | ## Install the plugin 6 | 7 | Add the following to your `build.gradle.kts`: 8 | 9 | ```kotlin 10 | plugins { 11 | id("digital.guimauve.zodable") version "1.7.2" 12 | id("com.google.devtools.ksp") version "2.2.20-2.0.4" // Adjust version as needed 13 | } 14 | ``` 15 | 16 | Or if you are using KSP 1: 17 | 18 | ```kotlin 19 | plugins { 20 | id("digital.guimauve.zodable") version "1.7.0-ksp1" 21 | id("com.google.devtools.ksp") version "2.1.10-1.0.30" 22 | } 23 | ``` 24 | 25 | And that's all! The plugin is ready to use. 26 | 27 | ## Usage 28 | 29 | Add the `@Zodable` annotation to your data classes. The plugin will generate a zod schema for each annotated class. 30 | 31 | ```kotlin 32 | @Zodable 33 | data class User( 34 | val id: Int, 35 | val name: String 36 | ) 37 | ``` 38 | 39 | Build the schema with `./gradlew build`, like you would with any other gradle project. 40 | 41 | The generated schema will look like this: 42 | 43 | ```typescript 44 | import {z} from "zod" 45 | 46 | export const UserSchema = z.object({ 47 | id: z.number().int(), 48 | name: z.string() 49 | }) 50 | export type User = z.infer 51 | ``` 52 | 53 | Generated schemas can be found in `build/zodable`. It is a ready to use npm package. 54 | 55 | Pydantic schema generation is also available, by setting `enablePython` to `true` in the gradle configuration (see 56 | configuration options below). The generated schema will look like this: 57 | 58 | ```python 59 | from pydantic import BaseModel 60 | 61 | class User(BaseModel): 62 | id: int 63 | name: str 64 | ``` 65 | 66 | Generated schemas can be found in `build/pydantable`. It is a ready to use pip package. 67 | 68 | ## Customizing the generated schema with annotations 69 | 70 | You can customize the generated schema with annotations: 71 | 72 | ### `@ZodIgnore` 73 | 74 | You can ignore a field with the `@ZodIgnore` annotation: 75 | 76 | ```kotlin 77 | data class User( 78 | @ZodIgnore 79 | val password: String // Will not be included in the generated schema 80 | ) 81 | ``` 82 | 83 | ### `@ZodImport` 84 | 85 | If you are consuming another package/dependency in your schema, you can import it with the `@ZodImport` annotation: 86 | 87 | ```kotlin 88 | @ZodImport("Pokemon", "my-pokemon-package") // Will generate import and package dependencies 89 | 90 | data class User( 91 | val favoritePokemon: Pokemon // Pokemon is defined in another gradle module/package 92 | ) 93 | ``` 94 | 95 | ### `@ZodType` 96 | 97 | You can specify the zod type for a field with the `@ZodType` annotation: 98 | 99 | ```kotlin 100 | data class User( 101 | @ZodType("IdSchema") 102 | val id: UUID, 103 | @ZodType("z.date()", "ts") 104 | @ZodType("datetime", "py") 105 | val birthDate: String, 106 | ) 107 | ``` 108 | 109 | The first argument is the zod type, the second argument is a filter for the target language. If you defined a custom 110 | schema in another package or are only enabling one language, you can omit the filter. 111 | 112 | ### `@ZodOverrideSchema` 113 | 114 | Need the maximum flexibility? You can override the entire schema for a type with the `@ZodOverrideSchema` annotation: 115 | 116 | ```kotlin 117 | @Zodable 118 | @ZodOverrideSchema( 119 | content = """ 120 | export const CustomSchema = z.object({ 121 | name: z.string(), 122 | age: z.number().int(), 123 | isActive: z.boolean(), 124 | tags: z.array(z.string()), 125 | }) 126 | export type Custom = z.infer 127 | """, 128 | filter = "ts" 129 | ) 130 | @ZodOverrideSchema( 131 | content = """ 132 | from typing import List 133 | 134 | class Custom(BaseModel): 135 | name: str 136 | age: int 137 | is_active: bool 138 | tags: List[str] 139 | """, 140 | filter = "py" 141 | ) 142 | interface Custom 143 | ``` 144 | 145 | ## Configuration options 146 | 147 | You can configure a few things in your `build.gradle.kts`: 148 | 149 | ```kotlin 150 | zodable { 151 | inferTypes = true // Generate `export type X = z.infer`, default is true 152 | optionals = digital.guimauve.zodable.Optionals.NULLISH // How to handle optional fields, default is NULLISH 153 | packageName = "my-package" // npm package name, default is the gradle project name 154 | packageVersion = "1.0.0" // npm package version, default is the gradle project version 155 | // additional npm commands to be executed to affect the generated zodable package 156 | additionalNpmCommands = listOf(listOf("npm", "pkg", "set", "files[1]=.yalc/**/*")) 157 | // mapping of @ZodImport package names to install commands 158 | externalPackageInstallCommands = mapOf("package-name" to listOf("yalc", "add")) 159 | // mapping of @ZodImport package names to locations 160 | externalPackageLocations = mapOf("package-name" to "file:/path/to/package-name") 161 | valueClassUnwrap = true // whether to unwrap properties with value class types, default is true 162 | enableTypescript = true // Generate typescript schemas, default is true 163 | enablePython = false // Generate pydantic schemas, default is false 164 | } 165 | ``` 166 | -------------------------------------------------------------------------------- /zodable-ksp-processor/src/main/kotlin/digital/guimauve/zodable/generators/PythonGenerator.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.zodable.generators 2 | 3 | import com.google.devtools.ksp.processing.SymbolProcessorEnvironment 4 | import com.google.devtools.ksp.symbol.ClassKind 5 | import com.google.devtools.ksp.symbol.KSClassDeclaration 6 | import digital.guimauve.zodable.config.Export 7 | import digital.guimauve.zodable.config.GeneratorConfig 8 | import digital.guimauve.zodable.config.Import 9 | import java.io.File 10 | 11 | class PythonGenerator( 12 | env: SymbolProcessorEnvironment, 13 | config: GeneratorConfig, 14 | ) : ZodableGenerator(env, config) { 15 | 16 | fun String.pythonCompatible() = this.replace("-", "_") 17 | 18 | override fun shouldKeepAnnotation(annotation: String, filter: String): Boolean { 19 | return listOf("*", "pydantic", "py", "python").contains(filter) 20 | } 21 | 22 | override fun resolveSourceFolder(): File { 23 | return config.outputPath.resolve(config.packageName.pythonCompatible()) 24 | } 25 | 26 | override fun resolveDependenciesFile(): File { 27 | return config.outputPath.resolve("requirements.txt") 28 | } 29 | 30 | override fun resolveIndexFile(sourceFolder: File): File { 31 | return sourceFolder.resolve("__init__.py") 32 | } 33 | 34 | override fun resolveClassFile(sourceFolder: File, packageName: String, name: String): File { 35 | return sourceFolder.resolve("$packageName/$name.py") 36 | } 37 | 38 | override fun resolveInstallName(source: String, version: String?): String { 39 | return source + (version ?: "") 40 | } 41 | 42 | override fun resolveDefaultImports(classDeclaration: KSClassDeclaration): Set { 43 | val sealedSubclasses = try { 44 | classDeclaration.getSealedSubclasses().toList() 45 | } catch (_: Exception) { 46 | emptyList() 47 | } 48 | 49 | return when (classDeclaration.classKind) { 50 | ClassKind.ENUM_CLASS -> setOf( 51 | Import("Enum", "enum", isExternal = true, isInvariable = true, isDependency = false) 52 | ) 53 | 54 | else -> setOf( 55 | Import("BaseModel", "pydantic", isExternal = true, isInvariable = true) 56 | ) 57 | }.let { 58 | if (classDeclaration.typeParameters.isNotEmpty()) it + setOf( 59 | Import("Generic", "typing", isExternal = true, isInvariable = true), 60 | Import("TypeVar", "typing", isExternal = true, isInvariable = true) 61 | ) else it 62 | }.let { 63 | if (sealedSubclasses.isNotEmpty()) it + setOf( 64 | Import("Union", "typing", isExternal = true, isInvariable = true), 65 | ) else it 66 | } 67 | } 68 | 69 | override fun generateImports(sourceFolder: File, currentFile: File, imports: Set): String { 70 | return imports.joinToString("\n") { import -> 71 | val source = 72 | if (import.isExternal) import.source.pythonCompatible() 73 | else sourceFolder.resolve(import.source) 74 | .relativeTo(config.outputPath) 75 | .path.replace("/", ".") 76 | "from $source import ${import.name}" 77 | } 78 | } 79 | 80 | override fun generateIndexExport(exports: Sequence): String { 81 | return exports.joinToString("\n") { 82 | val source = "${config.packageName.pythonCompatible()}.${it.packageName.replace("/", ".")}.${it.name}" 83 | "from $source import ${it.name}" 84 | } + "\n__all__ = [" + exports.joinToString(", ") { "\"${it.name}\"" } + "]" 85 | } 86 | 87 | override fun generateClassSchema( 88 | name: String, 89 | arguments: List, 90 | properties: Set>, 91 | ): String { 92 | val typeVar = if (arguments.isNotEmpty()) arguments.joinToString("\n", postfix = "\n") { 93 | "$it = TypeVar('$it')" 94 | } else "" 95 | val generics = if (arguments.isNotEmpty()) ", Generic[${arguments.joinToString(", ")}]" else "" 96 | val body = properties.joinToString("\n") { (name, type) -> " $name: $type" } 97 | return "${typeVar}class ${name}(BaseModel$generics):\n" + body.ifEmpty { " pass" } 98 | } 99 | 100 | override fun generateEnumSchema(name: String, arguments: List, values: Set): String { 101 | return "class ${name}(str, Enum):\n" + values.joinToString("\n") { name -> " $name = '$name'" } 102 | } 103 | 104 | override fun generateUnionSchema(name: String, arguments: List, values: Set): String { 105 | return "$name = Union[${values.joinToString(", ")}]" 106 | } 107 | 108 | override fun resolvePrimitiveType(kotlinType: String): Pair>? { 109 | return when (kotlinType) { 110 | "kotlin.String" -> "str" to emptyList() 111 | "kotlin.Int", "kotlin.Long" -> "int" to emptyList() 112 | "kotlin.Double", "kotlin.Float" -> "float" to emptyList() 113 | "kotlin.Boolean" -> "bool" to emptyList() 114 | "kotlin.Pair" -> "KotlinPair[]" to listOf( 115 | Import("KotlinPair", "zodable-kotlin-primitives", isExternal = true, isInvariable = true) 116 | ) 117 | 118 | "kotlin.time.Instant", 119 | "kotlinx.datetime.Instant", 120 | "kotlinx.datetime.LocalDateTime", 121 | "kotlinx.datetime.LocalDate" -> "datetime" to listOf( 122 | Import("datetime", "datetime", isExternal = true, isInvariable = true) 123 | ) 124 | 125 | "dev.kaccelero.models.UUID", 126 | "kotlin.uuid.Uuid" -> "UUID" to listOf( 127 | Import("UUID", "uuid", isExternal = true, isInvariable = true) 128 | ) 129 | 130 | "kotlin.collections.List" -> "list[]" to emptyList() 131 | "kotlin.collections.Map" -> "dict[]" to emptyList() 132 | else -> null 133 | } 134 | } 135 | 136 | override fun resolveZodableType(name: String, isGeneric: Boolean): Pair> { 137 | return "${name}${if (isGeneric) "[]" else ""}" to emptyList() 138 | } 139 | 140 | override fun resolveLiteralType(name: String): Pair> { 141 | return "Literal[\"$name\"]" to listOf( 142 | Import("Literal", "typing", isExternal = true, isInvariable = true) 143 | ) 144 | } 145 | 146 | override fun resolveGenericArgument(name: String): Pair> { 147 | return name to emptyList() 148 | } 149 | 150 | override fun resolveUnknownType(): Pair> { 151 | return "Any" to listOf(Import("Any", "typing", isExternal = true, isInvariable = true)) 152 | } 153 | 154 | override fun addGenericArguments(type: String, arguments: List): Pair> { 155 | if (!type.endsWith("[]")) return type to emptyList() 156 | return type.substring(0, type.length - 2) + "[${arguments.joinToString(", ")}]" to emptyList() 157 | } 158 | 159 | override fun markAsNullable(type: String): Pair> { 160 | return "Optional[$type] = None" to listOf(Import("Optional", "typing", isExternal = true, isInvariable = true)) 161 | } 162 | 163 | override fun extensionName(): String = "py" 164 | } 165 | -------------------------------------------------------------------------------- /zodable-ksp-processor/src/main/kotlin/digital/guimauve/zodable/generators/TypescriptGenerator.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.zodable.generators 2 | 3 | import com.google.devtools.ksp.processing.SymbolProcessorEnvironment 4 | import com.google.devtools.ksp.symbol.KSClassDeclaration 5 | import digital.guimauve.zodable.config.Export 6 | import digital.guimauve.zodable.config.GeneratorConfig 7 | import digital.guimauve.zodable.config.Import 8 | import java.io.File 9 | 10 | class TypescriptGenerator( 11 | env: SymbolProcessorEnvironment, 12 | config: GeneratorConfig, 13 | ) : ZodableGenerator(env, config) { 14 | 15 | override fun shouldKeepAnnotation(annotation: String, filter: String): Boolean { 16 | return listOf("*", "zod", "ts", "typescript").contains(filter) 17 | } 18 | 19 | override fun resolveSourceFolder(): File { 20 | return config.outputPath.resolve("src") 21 | } 22 | 23 | override fun resolveDependenciesFile(): File { 24 | return config.outputPath.resolve("dependencies.txt") 25 | } 26 | 27 | override fun resolveIndexFile(sourceFolder: File): File { 28 | return sourceFolder.resolve("index.ts") 29 | } 30 | 31 | override fun resolveClassFile(sourceFolder: File, packageName: String, name: String): File { 32 | return sourceFolder.resolve("$packageName/$name.ts") 33 | } 34 | 35 | override fun resolveInstallName(source: String, version: String?): String { 36 | return source + (version?.let { "@$it" } ?: "") 37 | } 38 | 39 | override fun resolveDefaultImports(classDeclaration: KSClassDeclaration): Set { 40 | return setOf( 41 | // Don't support Zod 4 yet (currently breaking) 42 | Import("z", "zod", isExternal = true, isInvariable = true, dependencyVersion = "^3.0.0") 43 | ) 44 | } 45 | 46 | override fun generateImports(sourceFolder: File, currentFile: File, imports: Set): String { 47 | return imports.joinToString("\n") { import -> 48 | val source = 49 | if (import.isExternal) import.source 50 | else sourceFolder.resolve(import.source) 51 | .relativeTo(currentFile.parentFile) // Folder containing current file 52 | .path.let { if (!it.startsWith(".")) "./$it" else it } 53 | "import {${import.name}${if (!import.isInvariable) "Schema" else ""}} from \"$source\"" 54 | } 55 | } 56 | 57 | override fun generateIndexExport(exports: Sequence): String { 58 | return exports.joinToString("\n") { 59 | val namesToExport = listOfNotNull( 60 | "${it.name}Schema", 61 | if (config.inferTypes) it.name else null 62 | ).joinToString(prefix = "{", postfix = "}", separator = ", ") 63 | "export $namesToExport from \"./${it.packageName}/${it.name}\"" 64 | } 65 | } 66 | 67 | override fun generateClassSchema( 68 | name: String, 69 | arguments: List, 70 | properties: Set>, 71 | ): String { 72 | val body = properties.joinToString(",\n ") { (name, type) -> "$name: $type" } 73 | val genericPrefix = generateGenericPrefixType(arguments) + generateGenericPrefixParams(arguments) 74 | return "export const ${name}Schema = ${genericPrefix}z.object({\n $body\n})" + 75 | generateInferType(name, arguments) 76 | } 77 | 78 | override fun generateEnumSchema(name: String, arguments: List, values: Set): String { 79 | val body = values.joinToString(", ") { "\"$it\"" } 80 | val genericPrefix = generateGenericPrefixType(arguments) + generateGenericPrefixParams(arguments) 81 | return "export const ${name}Schema = ${genericPrefix}z.enum([\n $body\n])" + 82 | generateInferType(name, arguments) 83 | } 84 | 85 | override fun generateUnionSchema(name: String, arguments: List, values: Set): String { 86 | val joinedValues = values.joinToString(",\n") { " ${it}Schema" } 87 | val body = 88 | if (joinedValues.isEmpty()) "z.never()" 89 | else "z.discriminatedUnion(\"type\", [\n$joinedValues\n])" 90 | val genericPrefix = generateGenericPrefixType(arguments) + generateGenericPrefixParams(arguments) 91 | return "export const ${name}Schema = $genericPrefix$body" + generateInferType(name, arguments) 92 | } 93 | 94 | fun generateGenericPrefixType(arguments: List, schema: Boolean = true, extends: Boolean = true): String { 95 | if (arguments.isEmpty()) return "" 96 | return arguments.joinToString(", ", prefix = "<", postfix = ">") { 97 | "${it}${if (schema) "Schema" else ""}${if (extends) " extends z.ZodTypeAny" else ""}" 98 | } 99 | } 100 | 101 | fun generateGenericPrefixParams(arguments: List): String { 102 | if (arguments.isEmpty()) return "" 103 | return arguments.joinToString(", ", prefix = " (", postfix = ") => ") { argument -> 104 | "${argument.replaceFirstChar { it.lowercaseChar() }}Schema: ${argument}Schema" 105 | } 106 | } 107 | 108 | fun generateInferType(name: String, arguments: List): String { 109 | if (!config.inferTypes) return "" 110 | val genericPrefix = generateGenericPrefixType(arguments, schema = false, extends = false) 111 | val typeOf = "typeof ${name}Schema".let { rawTypeOf -> 112 | if (arguments.isNotEmpty()) { 113 | val genericCall = arguments.joinToString(", ", prefix = "<", postfix = ">") { 114 | "z.ZodType<${it}, any, any>" 115 | } 116 | "ReturnType<$rawTypeOf$genericCall>" 117 | } else rawTypeOf 118 | } 119 | return "\nexport type $name$genericPrefix = z.infer<$typeOf>" 120 | } 121 | 122 | override fun resolvePrimitiveType(kotlinType: String): Pair>? { 123 | return when (kotlinType) { 124 | "kotlin.String" -> "z.string()" to emptyList() 125 | "kotlin.Int" -> "z.number().int()" to emptyList() 126 | "kotlin.Long", "kotlin.Double", "kotlin.Float" -> "z.number()" to emptyList() 127 | "kotlin.Boolean" -> "z.boolean()" to emptyList() 128 | "kotlin.Pair" -> "KotlinPairSchema()" to listOf( 129 | Import("KotlinPairSchema", "zodable-kotlin-primitives", isExternal = true, isInvariable = true) 130 | ) 131 | 132 | "kotlin.time.Instant", 133 | "kotlinx.datetime.Instant", 134 | "kotlinx.datetime.LocalDateTime", 135 | "kotlinx.datetime.LocalDate" -> "z.coerce.date()" to emptyList() 136 | 137 | "dev.kaccelero.models.UUID", 138 | "kotlin.uuid.Uuid" -> "z.string().uuid()" to emptyList() 139 | 140 | "kotlin.collections.List" -> "z.array()" to emptyList() 141 | "kotlin.collections.Map" -> "z.record()" to emptyList() 142 | else -> null 143 | } 144 | } 145 | 146 | override fun resolveZodableType(name: String, isGeneric: Boolean): Pair> { 147 | return "${name}Schema${if (isGeneric) "()" else ""}" to emptyList() 148 | } 149 | 150 | override fun resolveLiteralType(name: String): Pair> { 151 | return "z.literal(\"$name\")" to emptyList() 152 | } 153 | 154 | override fun resolveGenericArgument(name: String): Pair> { 155 | return "${name.replaceFirstChar { it.lowercaseChar() }}Schema" to emptyList() 156 | } 157 | 158 | override fun resolveUnknownType(): Pair> { 159 | return "z.unknown()" to emptyList() 160 | } 161 | 162 | override fun addGenericArguments(type: String, arguments: List): Pair> { 163 | if (!type.endsWith("()")) return type to emptyList() 164 | 165 | // Coerce arguments if needed 166 | val coercedArguments = when (type) { 167 | // For map, we need to coerce the key type (always from string inside json) 168 | "z.record()" -> { 169 | val firstArgument = arguments.first() 170 | val coercedFirstArgument = 171 | if (config.coerceMapKeys && firstArgument.startsWith("z.")) 172 | firstArgument.replaceFirst("z.", "z.coerce.") 173 | else firstArgument 174 | listOf(coercedFirstArgument) + arguments.drop(1) 175 | } 176 | 177 | else -> arguments 178 | } 179 | return type.substring(0, type.length - 2) + "(${coercedArguments.joinToString(", ")})" to emptyList() 180 | } 181 | 182 | override fun markAsNullable(type: String): Pair> { 183 | return "$type${config.optionals}" to emptyList() 184 | } 185 | 186 | override fun extensionName(): String = "ts" 187 | } 188 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /zodable-gradle-plugin/src/main/kotlin/digital/guimauve/zodable/ZodablePlugin.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.zodable 2 | 3 | import com.google.devtools.ksp.gradle.KspExtension 4 | import digital.guimauve.zodable.Files.pythonCompatible 5 | import digital.guimauve.zodable.extensions.ZodableExtension 6 | import org.gradle.api.Plugin 7 | import org.gradle.api.Project 8 | import org.gradle.api.tasks.Exec 9 | import org.gradle.kotlin.dsl.create 10 | import org.gradle.kotlin.dsl.dependencies 11 | import org.gradle.kotlin.dsl.getByType 12 | import org.gradle.kotlin.dsl.register 13 | import java.io.File 14 | 15 | abstract class ZodablePlugin : Plugin { 16 | 17 | private val zodableVersion = "1.7.2" 18 | 19 | override fun apply(project: Project) { 20 | val outputPath = project.file("build/zodable") 21 | 22 | project.pluginManager.apply("com.google.devtools.ksp") 23 | project.configureExtensions() 24 | project.configureKspProcessor() 25 | project.afterEvaluate { 26 | project.configureKspArgs(outputPath) 27 | project.configureTasks(outputPath) 28 | } 29 | } 30 | 31 | private fun Project.configureExtensions() { 32 | val extension = extensions.create("zodable") 33 | extension.enableTypescript.convention(true) 34 | extension.enablePython.convention(false) 35 | extension.inferTypes.convention(true) 36 | extension.coerceMapKeys.convention(true) 37 | extension.optionals.convention(Optionals.NULLISH) 38 | extension.packageName.convention(project.name) 39 | extension.packageVersion.convention(project.version.toString()) 40 | extension.additionalNpmCommands.convention(emptyList()) 41 | extension.externalPackageInstallCommands.convention(emptyMap()) 42 | extension.externalPackageLocations.convention(emptyMap()) 43 | extension.valueClassUnwrap.convention(true) 44 | } 45 | 46 | private fun Project.getKspConfig(): KspConfig { 47 | return if (plugins.hasPlugin("org.jetbrains.kotlin.multiplatform")) KspConfig( 48 | apiConfigurationName = "commonMainApi", 49 | kspConfigurationName = "kspCommonMainMetadata", 50 | taskName = "kspCommonMainKotlinMetadata" 51 | ) else KspConfig( 52 | apiConfigurationName = "api", 53 | kspConfigurationName = "ksp", 54 | taskName = "kspKotlin" 55 | ) 56 | } 57 | 58 | private fun Project.configureKspProcessor() { 59 | val kspConfig = getKspConfig() 60 | 61 | dependencies { 62 | if (project.group == "digital.guimauve.zodable") { 63 | add(kspConfig.apiConfigurationName, project(":zodable-annotations")) 64 | add(kspConfig.kspConfigurationName, project(":zodable-ksp-processor")) 65 | } else { 66 | add(kspConfig.apiConfigurationName, "digital.guimauve.zodable:zodable-annotations:$zodableVersion") 67 | add(kspConfig.kspConfigurationName, "digital.guimauve.zodable:zodable-ksp-processor:$zodableVersion") 68 | } 69 | } 70 | } 71 | 72 | private fun Project.configureKspArgs(outputPath: File) { 73 | val extension = extensions.getByType() 74 | 75 | plugins.withId("com.google.devtools.ksp") { 76 | extensions.getByType().apply { 77 | arg("zodableEnableTypescript", extension.enableTypescript.get().toString()) 78 | arg("zodableEnablePython", extension.enablePython.get().toString()) 79 | arg("zodablePackageName", extension.packageName.get()) 80 | arg("zodableOutputPath", outputPath.absolutePath) 81 | arg("zodableInferTypes", extension.inferTypes.get().toString()) 82 | arg("zodableCoerceMapKeys", extension.coerceMapKeys.get().toString()) 83 | arg("zodableOptionals", extension.optionals.get().zodType) 84 | arg("zodableValueClassUnwrap", extension.valueClassUnwrap.get().toString()) 85 | } 86 | } 87 | } 88 | 89 | private fun Project.configureTasks(outputPath: File) { 90 | val extension = extensions.getByType() 91 | val kspConfig = getKspConfig() 92 | 93 | // typescript 94 | val srcDir = outputPath.resolve("src") 95 | val dependenciesFile = outputPath.resolve("dependencies.txt") 96 | 97 | // python 98 | val pythonOutputPath = outputPath.parentFile.resolve("pydantable") 99 | val pythonSrcDir = extension.packageName.get().pythonCompatible() 100 | val resolvedPythonSrcDir = pythonOutputPath.resolve(pythonSrcDir) 101 | val requirementsFile = pythonOutputPath.resolve("requirements.txt") 102 | 103 | // ensure we set the src dir and dependencies file as outputs of the ksp task for proper ordering 104 | // and gradle output tracking 105 | tasks.configureEach { 106 | if (name == kspConfig.taskName) { 107 | outputs.dir(srcDir) 108 | outputs.dir(resolvedPythonSrcDir) 109 | outputs.file(dependenciesFile) 110 | outputs.file(requirementsFile) 111 | } 112 | } 113 | 114 | val setupZodablePackage = tasks.register("setupZodablePackage") { 115 | group = "build" 116 | description = "Setup zodable npm package" 117 | 118 | workingDir = outputPath 119 | 120 | // define the gradle plugin input and output dependencies 121 | inputs.dir(srcDir) 122 | inputs.file(dependenciesFile) 123 | outputs.file(outputPath.resolve("package.json")) 124 | outputs.dir(outputPath.resolve("node_modules")) 125 | outputs.file(outputPath.resolve("package-lock.json")) 126 | outputs.file(outputPath.resolve("tsconfig.json")) 127 | 128 | commandLine = listOf("npm", "init", "-y") 129 | 130 | dependsOn(kspConfig.taskName) 131 | 132 | doLast { 133 | buildList { 134 | add(ExecCommand(listOf("npm", "pkg", "set", "name=${extension.packageName.get()}"))) 135 | add(ExecCommand(listOf("npm", "pkg", "set", "version=${extension.packageVersion.get()}"))) 136 | add(ExecCommand(listOf("npm", "pkg", "set", "description=${Files.ZOD_DESCRIPTION}"))) 137 | add(ExecCommand(listOf("npm", "pkg", "set", "type=module"))) 138 | add(ExecCommand(listOf("npm", "pkg", "set", "main=src/index.js"))) 139 | add(ExecCommand(listOf("npm", "pkg", "set", "types=src/index.d.ts"))) 140 | add(ExecCommand(listOf("npm", "pkg", "set", "files[0]=src/**/*"))) 141 | add(ExecCommand(listOf("npm", "install", "typescript", "--save-dev"))) 142 | File(outputPath, "dependencies.txt").readLines().forEach { dep -> 143 | val npmPackage = extension.externalPackageLocations.get()[dep] ?: dep 144 | val installCommand = 145 | extension.externalPackageInstallCommands.get()[dep] ?: listOf("npm", "install", npmPackage) 146 | add(ExecCommand(installCommand)) 147 | } 148 | extension.additionalNpmCommands.get()?.forEach { cmd -> 149 | add(ExecCommand(cmd)) 150 | } 151 | add( 152 | ExecCommand( 153 | listOf( 154 | "npx", "tsc", "--init", 155 | "-d", 156 | "--module", "esnext", 157 | "--moduleResolution", "bundler", 158 | "--baseUrl", "./", 159 | "--isolatedModules", "false", 160 | "--verbatimModuleSyntax", "false" 161 | ) 162 | ) 163 | ) 164 | add(ExecCommand(listOf("npx", "tsc"))) 165 | }.forEach { command -> 166 | exec { 167 | workingDir = outputPath 168 | commandLine = command.commandLine 169 | command.standardInput?.let { 170 | standardInput = outputPath.resolve(it).inputStream() 171 | } 172 | } 173 | } 174 | } 175 | } 176 | val setupPydantablePackage = tasks.register("setupPydantablePackage") { 177 | val venvPath = pythonOutputPath.resolve(".venv") 178 | val pythonExec = venvPath.resolve("bin/python").absolutePath 179 | val pipExec = venvPath.resolve("bin/pip").absolutePath 180 | 181 | group = "build" 182 | description = "Setup zodable pypi package" 183 | 184 | workingDir = pythonOutputPath 185 | 186 | // define the gradle plugin input and output dependencies 187 | inputs.dir(resolvedPythonSrcDir) 188 | inputs.file(requirementsFile) 189 | outputs.dir(pythonOutputPath.resolve("dist")) 190 | outputs.dir(pythonOutputPath.resolve(".venv")) 191 | outputs.file(pythonOutputPath.resolve("pyproject.toml")) 192 | outputs.file(pythonOutputPath.resolve("$pythonSrcDir.egg-info")) 193 | 194 | commandLine = listOf("python3", "-m", "venv", ".venv") 195 | 196 | dependsOn(kspConfig.taskName) 197 | 198 | doLast { 199 | listOf( 200 | ExecCommand(listOf(pipExec, "install", "-r", "requirements.txt")), 201 | ExecCommand(listOf(pipExec, "install", "toml")), 202 | ExecCommand( 203 | listOf( 204 | pythonExec, "-c", Files.generatePyProjectToml( 205 | extension.packageName.get(), 206 | extension.packageVersion.get(), 207 | ) 208 | ) 209 | ), 210 | ExecCommand(listOf("touch", "$pythonSrcDir/py.typed")), 211 | ExecCommand(listOf(pipExec, "install", "mypy", "build", "twine")), 212 | ExecCommand(listOf(pythonExec, "-m", "mypy", pythonSrcDir)), 213 | ExecCommand(listOf(pythonExec, "-m", "build")), 214 | ).forEach { command -> 215 | exec { 216 | workingDir = pythonOutputPath 217 | commandLine = command.commandLine 218 | } 219 | } 220 | } 221 | } 222 | tasks.named("build").configure { 223 | if (extension.enableTypescript.get()) dependsOn(setupZodablePackage) 224 | if (extension.enablePython.get()) dependsOn(setupPydantablePackage) 225 | } 226 | } 227 | 228 | } 229 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /zodable-ksp-processor/src/main/kotlin/digital/guimauve/zodable/generators/ZodableGenerator.kt: -------------------------------------------------------------------------------- 1 | package digital.guimauve.zodable.generators 2 | 3 | import com.google.devtools.ksp.processing.SymbolProcessorEnvironment 4 | import com.google.devtools.ksp.symbol.* 5 | import digital.guimauve.zodable.* 6 | import digital.guimauve.zodable.config.Export 7 | import digital.guimauve.zodable.config.GeneratorConfig 8 | import digital.guimauve.zodable.config.Import 9 | import kotlinx.serialization.SerialName 10 | import java.io.File 11 | import java.io.FileOutputStream 12 | import java.io.OutputStreamWriter 13 | 14 | abstract class ZodableGenerator( 15 | protected val env: SymbolProcessorEnvironment, 16 | protected val config: GeneratorConfig, 17 | ) { 18 | var round = 0 19 | 20 | fun generateFiles(annotatedClasses: Sequence) { 21 | val append = round++ > 0 22 | val sourceFolder = resolveSourceFolder().also { it.mkdirs() } 23 | val importedPackages = mutableSetOf() 24 | 25 | val exports = annotatedClasses.map { classDeclaration -> 26 | val name = classDeclaration.simpleName.asString() 27 | val packageName = classDeclaration.packageName.asString().replace(".", "/") 28 | val arguments = classDeclaration.typeParameters.map { it.name.asString() } 29 | val classFile = resolveClassFile(sourceFolder, packageName, name) 30 | classFile.parentFile.mkdirs() 31 | 32 | env.codeGenerator.associateByPath(listOf(classDeclaration.containingFile!!), classFile.path, extensionName()) 33 | 34 | OutputStreamWriter(classFile.outputStream(), Charsets.UTF_8).use { schemaWriter -> 35 | val imports = generateImports(classDeclaration).toMutableSet() 36 | 37 | val overriddenSchema = classDeclaration.annotations.firstNotNullOfOrNull { annotation -> 38 | if (annotation.shortName.asString() != ZodOverrideSchema::class.simpleName) return@firstNotNullOfOrNull null 39 | val zodOverride = annotation.toZodOverrideSchema() 40 | if (!shouldKeepAnnotation("ZodOverrideSchema", zodOverride.filter)) return@firstNotNullOfOrNull null 41 | zodOverride.content.trimIndent() 42 | } 43 | 44 | val sealedSubclasses = try { 45 | classDeclaration.getSealedSubclasses().toList() 46 | } catch (_: Exception) { 47 | emptyList() 48 | } 49 | 50 | val generatedBody = overriddenSchema ?: if (sealedSubclasses.isNotEmpty()) { 51 | processSealedClass(name, arguments, sealedSubclasses, imports) 52 | } else when (classDeclaration.classKind) { 53 | ClassKind.ENUM_CLASS -> processEnumClass(name, arguments, classDeclaration) 54 | else -> processClass(name, arguments, classDeclaration, imports) 55 | } 56 | val generatedImports = generateImports(sourceFolder, classFile, imports) + "\n" 57 | 58 | schemaWriter.write(generatedImports + "\n") 59 | schemaWriter.write(generatedBody + "\n") 60 | 61 | importedPackages.addAll( 62 | imports 63 | .filter { it.isExternal && it.isDependency } 64 | .map { resolveInstallName(it.source, it.dependencyVersion) } 65 | ) 66 | } 67 | Export(name, packageName) 68 | } 69 | 70 | val indexFile = resolveIndexFile(sourceFolder) 71 | env.codeGenerator.associateWithClasses(annotatedClasses.toList(), "", indexFile.name, extensionName()) 72 | OutputStreamWriter(FileOutputStream(indexFile, append), Charsets.UTF_8).use { indexWriter -> 73 | indexWriter.write(generateIndexExport(exports) + "\n") 74 | } 75 | 76 | val dependenciesFile = resolveDependenciesFile() 77 | env.codeGenerator.associateWithClasses(annotatedClasses.toList(), "", dependenciesFile.name, "txt") 78 | OutputStreamWriter(FileOutputStream(dependenciesFile, append), Charsets.UTF_8).use { depWriter -> 79 | importedPackages.forEach { depWriter.write("$it\n") } 80 | } 81 | } 82 | 83 | private fun processEnumClass(name: String, arguments: List, classDeclaration: KSClassDeclaration): String { 84 | val values = classDeclaration.declarations.filterIsInstance() 85 | .map { it.simpleName.asString() } 86 | .toSet() 87 | return generateEnumSchema(name, arguments, values) 88 | } 89 | 90 | private fun processSealedClass( 91 | name: String, 92 | arguments: List, 93 | subclasses: List, 94 | imports: MutableSet, 95 | ): String { 96 | val variants = subclasses.associate { subclass -> 97 | // Get the SerialName annotation value to use as the discriminator value 98 | val subclassName = subclass.simpleName.asString() 99 | val serialName = subclass.annotations.firstNotNullOfOrNull { annotation -> 100 | if (annotation.shortName.asString() != "SerialName") return@firstNotNullOfOrNull null 101 | val args = annotation.arguments.associateBy { it.name?.asString() } 102 | args["value"]?.value as? String 103 | } ?: subclass.simpleName.asString() 104 | val subclassArguments = subclass.typeParameters.map { it.name.asString() } 105 | val (literalType, literalImports) = resolveLiteralType(serialName) 106 | imports.addAll(literalImports) 107 | 108 | subclassName to processClass( 109 | name = subclassName, 110 | arguments = subclassArguments, 111 | classDeclaration = subclass, 112 | imports = imports, 113 | additionalProperties = setOf("type" to literalType), 114 | ) 115 | } 116 | val union = generateUnionSchema(name, arguments, variants.keys) 117 | 118 | return variants.values.joinToString("\n\n") + "\n\n" + union 119 | } 120 | 121 | private fun processClass( 122 | name: String, 123 | arguments: List, 124 | classDeclaration: KSClassDeclaration, 125 | imports: MutableSet, 126 | additionalProperties: Set> = emptySet(), 127 | ): String { 128 | val properties = classDeclaration.getAllProperties() 129 | .filter { it.hasBackingField } 130 | .mapNotNull { prop -> 131 | val name = prop.annotations.firstNotNullOfOrNull { annotation -> 132 | if (annotation.shortName.asString() != SerialName::class.simpleName) return@firstNotNullOfOrNull null 133 | annotation.toSerialName().value 134 | } ?: prop.simpleName.asString() 135 | val (type, localImports) = resolveZodType(prop, classDeclaration) 136 | ?: return@mapNotNull null 137 | localImports.forEach { import -> 138 | if (imports.none { it.name == import.name }) imports.add(import) 139 | } 140 | name to type 141 | } 142 | .toSet() 143 | return generateClassSchema(name, arguments, properties + additionalProperties) 144 | } 145 | 146 | private fun generateImports(classDeclaration: KSClassDeclaration): Set = 147 | resolveDefaultImports(classDeclaration) + classDeclaration.annotations.mapNotNull { annotation -> 148 | if (annotation.shortName.asString() != ZodImport::class.simpleName) return@mapNotNull null 149 | val zodImport = annotation.toZodImport() 150 | if (!shouldKeepAnnotation("ZodImport", zodImport.filter)) return@mapNotNull null 151 | Import(zodImport.name, zodImport.source, true, zodImport.isInvariable) 152 | }.toSet() 153 | 154 | private fun resolveZodType( 155 | prop: KSPropertyDeclaration, 156 | classDeclaration: KSClassDeclaration, 157 | ): Pair>? { 158 | prop.annotations.forEach { annotation -> 159 | if (annotation.shortName.asString() != ZodIgnore::class.simpleName) return@forEach 160 | val zodIgnore = annotation.toZodIgnore() 161 | if (!shouldKeepAnnotation("ZodIgnore", zodIgnore.filter)) return@forEach 162 | return@resolveZodType null 163 | } 164 | val customZodType = prop.annotations.firstNotNullOfOrNull { annotation -> 165 | if (annotation.shortName.asString() != ZodType::class.simpleName) return@firstNotNullOfOrNull null 166 | val zodType = annotation.toZodType() 167 | if (!shouldKeepAnnotation("ZodType", zodType.filter)) return@firstNotNullOfOrNull null 168 | zodType.value 169 | } 170 | if (customZodType != null) return Pair(customZodType, emptyList()) 171 | return resolveZodType(prop.type.resolve(), classDeclaration) 172 | } 173 | 174 | private fun resolveZodType(type: KSType, classDeclaration: KSClassDeclaration): Pair> { 175 | val isNullable = type.isMarkedNullable 176 | val imports = mutableListOf() 177 | 178 | // Check if this is a value class and resolve to its underlying type 179 | val typeDeclaration = type.declaration as? KSClassDeclaration 180 | if (typeDeclaration != null && typeDeclaration.isValueClass() && config.valueClassUnwrap) { 181 | val valueClassProperty = typeDeclaration.getAllProperties() 182 | .firstOrNull { it.hasBackingField } 183 | 184 | if (valueClassProperty != null) { 185 | val underlyingType = valueClassProperty.type.resolve() 186 | // Recursively resolve the underlying type, preserving nullability 187 | val (resolvedType, resolvedImports) = resolveZodType(underlyingType, classDeclaration) 188 | return if (isNullable) { 189 | val (nullableType, nullableImports) = markAsNullable(resolvedType) 190 | nullableType to (resolvedImports + nullableImports) 191 | } else { 192 | resolvedType to resolvedImports 193 | } 194 | } 195 | } 196 | 197 | val (arguments, argumentImports) = type.arguments.map { 198 | val argument = it.type?.resolve() ?: return@map resolveUnknownType() 199 | resolveZodType(argument, classDeclaration) 200 | }.unzip().let { it.first to it.second.flatten() } 201 | 202 | val (resolvedType, resolvedImports) = resolvePrimitiveType( 203 | type.declaration.qualifiedName?.asString() ?: "kotlin.Any" 204 | ) ?: { 205 | val typeDeclaration = type.declaration as? KSClassDeclaration 206 | if (typeDeclaration != null && typeDeclaration.annotations.any { it.shortName.asString() == Zodable::class.simpleName }) { 207 | val import = typeDeclaration.packageName.asString() 208 | .replace(".", "/") + "/" + typeDeclaration.simpleName.asString() 209 | imports += Import(import.split("/").last(), import) 210 | resolveZodableType(typeDeclaration.simpleName.asString(), typeDeclaration.typeParameters.isNotEmpty()) 211 | } else if (classDeclaration.typeParameters.any { it.name.asString() == type.declaration.simpleName.asString() }) { 212 | resolveGenericArgument(type.declaration.simpleName.asString()) 213 | } else { 214 | val unknownType = resolveUnknownType() 215 | env.logger.warn("Unsupported type ${type.declaration.simpleName.asString()} in class ${classDeclaration.qualifiedName?.asString()}, using ${unknownType.first}") 216 | unknownType 217 | } 218 | }() 219 | 220 | val allImports = imports + argumentImports + resolvedImports 221 | return (resolvedType to allImports) 222 | .let { 223 | if (arguments.isNotEmpty()) { 224 | val (newType, newImports) = addGenericArguments(it.first, arguments) 225 | newType to (it.second + newImports) 226 | } else it 227 | } 228 | .let { 229 | if (isNullable) { 230 | val (newType, newImports) = markAsNullable(it.first) 231 | newType to (it.second + newImports) 232 | } else it 233 | } 234 | } 235 | 236 | private fun KSAnnotation.toZodOverrideSchema(): ZodOverrideSchema { 237 | val args = arguments.associateBy { it.name?.asString() } 238 | return ZodOverrideSchema( 239 | content = args["content"]?.value as? String ?: error("Missing 'content'"), 240 | filter = args["filter"]?.value as? String ?: "*", 241 | ) 242 | } 243 | 244 | private fun KSAnnotation.toZodImport(): ZodImport { 245 | val args = arguments.associateBy { it.name?.asString() } 246 | return ZodImport( 247 | name = args["name"]?.value as? String ?: error("Missing 'name'"), 248 | source = args["source"]?.value as? String ?: error("Missing 'source'"), 249 | filter = args["filter"]?.value as? String ?: "*", 250 | isInvariable = args["isInvariable"]?.value as? Boolean == true 251 | ) 252 | } 253 | 254 | private fun KSAnnotation.toZodIgnore(): ZodIgnore { 255 | val args = arguments.associateBy { it.name?.asString() } 256 | return ZodIgnore( 257 | filter = args["filter"]?.value as? String ?: "*", 258 | ) 259 | } 260 | 261 | private fun KSAnnotation.toZodType(): ZodType { 262 | val args = arguments.associateBy { it.name?.asString() } 263 | return ZodType( 264 | value = args["value"]?.value as? String ?: error("Missing 'type'"), 265 | filter = args["filter"]?.value as? String ?: "*", 266 | ) 267 | } 268 | 269 | private fun KSAnnotation.toSerialName(): SerialName { 270 | val args = arguments.associateBy { it.name?.asString() } 271 | return SerialName( 272 | value = args["value"]?.value as? String ?: "*", 273 | ) 274 | } 275 | 276 | private fun KSClassDeclaration.isValueClass(): Boolean { 277 | // when ksp runs against a compiled lib, it sees it as INLINE, not VALUE because of the JVM bytecode representation 278 | return modifiers.contains(Modifier.VALUE) || modifiers.contains(Modifier.INLINE) 279 | } 280 | 281 | abstract fun shouldKeepAnnotation(annotation: String, filter: String): Boolean 282 | abstract fun resolveSourceFolder(): File 283 | abstract fun resolveDependenciesFile(): File 284 | abstract fun resolveIndexFile(sourceFolder: File): File 285 | abstract fun resolveClassFile(sourceFolder: File, packageName: String, name: String): File 286 | abstract fun resolveInstallName(source: String, version: String?): String 287 | abstract fun resolveDefaultImports(classDeclaration: KSClassDeclaration): Set 288 | abstract fun generateImports(sourceFolder: File, currentFile: File, imports: Set): String 289 | abstract fun generateIndexExport(exports: Sequence): String 290 | abstract fun generateClassSchema( 291 | name: String, 292 | arguments: List, 293 | properties: Set>, 294 | ): String 295 | 296 | abstract fun generateEnumSchema(name: String, arguments: List, values: Set): String 297 | abstract fun generateUnionSchema(name: String, arguments: List, values: Set): String 298 | abstract fun resolvePrimitiveType(kotlinType: String): Pair>? 299 | abstract fun resolveZodableType(name: String, isGeneric: Boolean): Pair> 300 | abstract fun resolveLiteralType(name: String): Pair> 301 | abstract fun resolveGenericArgument(name: String): Pair> 302 | abstract fun resolveUnknownType(): Pair> 303 | abstract fun addGenericArguments(type: String, arguments: List): Pair> 304 | abstract fun markAsNullable(type: String): Pair> 305 | abstract fun extensionName(): String 306 | 307 | } 308 | --------------------------------------------------------------------------------