From 6be9e337996b6d0c840916f7068b62183ca9e689 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Sowa?= Date: Sat, 21 Nov 2026 10:18:57 +0000 Subject: [PATCH 01/10] Add kebs 3 design doc and implementation plans Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFD5QTj91bQhcjiNo9n48K --- design/2026-11-21-kebs-3-design.md | 404 ++++++++++++++++++ .../plans/2026-11-21-plan-0-release-2.3.0.md | 106 +++++ .../2026-11-21-plan-1-build-core-testkit.md | 345 +++++++++++++++ 3 files changed, 855 insertions(+) create mode 100644 design/2026-11-21-kebs-3-design.md create mode 100644 design/plans/2026-11-21-plan-0-release-2.3.0.md create mode 100644 design/plans/2026-11-21-plan-1-build-core-testkit.md diff --git a/design/2026-11-21-kebs-3-design.md b/design/2026-11-21-kebs-3-design.md new file mode 100644 index 00000000..da655f1f --- /dev/null +++ b/design/2026-11-21-kebs-3-design.md @@ -0,0 +1,404 @@ +# kebs 3 — design + +Status: draft for maintainer review · 2026-11-21 + +## 1. Intent + +Rewrite kebs' macros on [hearth](https://github.com/kubuszok/hearth) — or delegate to +[kindlings](https://github.com/kubuszok/kindlings) where a kindlings module already does the job — so that: + +- **macros are faster** to compile (no inline/`Mirror` recursion, no implicit-search chains) and the generated code is + faster at runtime (no `productIterator` zipping, no `Tuple` allocation, no per-site anonymous classes — issue #417); +- **there is one implementation per macro** shared by Scala 2.13 and Scala 3, instead of two that drift apart; +- **behaviour is the same on both Scala versions** (today it is not — see §4.2). + +While the macros are being rewritten, kebs 3 also closes cheap feature gaps, unifies how JSON modules name fields and +enum values, and adds ADT support to the JSON modules. Because the Scala 3 floor moves (see §3), this is a major +release: **kebs 3.0**. + +Before kebs 3 work lands on master, kebs **2.3.0** is cut with dependency bumps only, as the (likely) last 2.x minor. + +## 2. Goals, non-goals, anti-goals + +**Goals** + +1. Every macro kebs owns is written once on hearth, cross-compiled for 2.13 and 3. +2. circe and scalacheck derivation delegate to kindlings; a new `kebs-jsoniter` module is built on kindlings. +3. The current test suites keep passing on both Scala versions; they are the behavioural spec (see §6). +4. Scala 2 vs Scala 3 inconsistencies listed in §4.2 are removed. +5. The gaps listed in §4.3 are filled. +6. One naming vocabulary for field names and enum values across all modules (§5.3). +7. JSON modules (circe, spray-json, play-json, jsoniter) derive case classes **and** sealed hierarchies the same way, + configured the same way (§5.4). + +**Non-goals** + +- tagged-meta (Scala 2 macro annotation) and jsonschema (scala-jsonschema is Scala 2 only) are not rewritten; they stay + Scala 2 only, unchanged apart from build changes. +- slick-pg issues (#4, #5, #6, #276) are not addressed. +- PATCH semantics (distinguishing absent vs `null` fields) are not exposed by kebs. +- No changes to `instances`, `opaque`, `tagged`, `slick`, `baklava` beyond what build/dependency/enum-naming changes + require. + +**Anti-goals** (a release that does these is a failure even if it compiles) + +- **Silent wire-format changes.** A kebs 2 user upgrading to kebs 3 must get the same JSON (and the same DB/HTTP enum + strings) unless the change is deliberate and listed in the migration guide. Defaults are chosen to preserve today's + output per module. +- Users having to rewrite call sites for things that did not change conceptually: the existing entry points + (`KebsCirce`, `circe.snakified`, `sprayjson.capitalized`, `enums.uppercase`, `KebsArbitrarySupport`, + `CaseClass1ToValueClass`, …) keep their names and roles. +- Worse error messages than today for a missing instance. + +## 3. Constraints + +- **Scala versions: 2.13.18 and 3.9.0 (LTS).** kindlings 0.4.0's Scala 3 artifacts are built with 3.8.4, so the kebs + Scala 3 floor rises from 3.3 to 3.9. Verified: kindlings-circe-derivation 0.4.0 compiles and runs from a 3.9.0 build. +- **JDK 17+.** Scala 3.8+ requires it. CI moves from JDK 11+17 to JDK 17+21. +- **hearth 0.4.5, kindlings 0.4.0.** kindlings 0.4.0 depends on hearth 0.4.5; kebs must depend on exactly the hearth + version its kindlings version uses (they run inside the compiler, an evicted mismatch can break macro expansion). + Policy: bump hearth and kindlings together. +- hearth is pre-1.0 and becomes a transitive dependency of every kebs user (via kebs-core). +- Cross-compiled hearth macros still need a small per-version entry file (`scala-2/` macro bundle, `scala-3/` + `inline … = ${…}`), and the `hearth-cross-quotes` compiler plugin on Scala 3. The macro logic is shared. +- Platforms stay as today (core/circe/http4s/… on JVM+JS+Native, play-json JVM+JS, others JVM). hearth and the used + kindlings modules are published for all three platforms. +- Binary compatibility: kebs 3.0 breaks it deliberately; MiMa is disabled for 3.0.0 and re-enabled with + `tlMimaPreviousVersions := Set("3.0.0")` afterwards. +- Generated docs (`docs/*.md`) are compiled by mdoc into the website; `ci.yml` is generated by sbt-github-actions + (never hand-edit; regenerate from build.sbt). The website workflow only runs on master. + +## 4. Scope + +### 4.1 Macro inventory and where each goes + +| Module | Today (2.13 / 3) | kebs 3 | +|---|---|---| +| core `ValueClassLike` (`CaseClass1ToValueClass`) | whitebox macro / `Mirror.ProductOf` + `productElement(0).asInstanceOf` | hearth macro | +| enum | `Enumeration` only / Scala 3 `enum` only; `KebsValueEnum` Scala 3 only | hearth macro (`Enum` view) | +| enumeratum | `Companion.values` / `Mirror` inline recursion | hearth macro, `Companion.values` on both | +| spray-json | own macro (spray `jsonFormat` ≤22, hand-rolled >22) / `Mirror` + runtime zip | hearth macro | +| play-json | none (flat/enum/instance formats only) | **new** hearth macro (issue #384) | +| circe | own macro + circe-generic `AutoDerivation` + generic-extras >22 / circe `ConfiguredDecoder` | kindlings-circe-derivation | +| jsoniter | — | **new** module on kindlings-jsoniter-derivation (issue #255) | +| scalacheck | magnolify / scalacheck-derived | kindlings-scalacheck-derivation | +| jsonschema, tagged-meta | Scala 2 only | unchanged | +| akka-http | Scala 2 only, Akka 2.6 | **dropped** (pekko-http replaces it) | + +### 4.2 Inconsistencies to remove + +1. `ValueClassLike` on Scala 3 constructs via `Mirror.fromProduct` (the constructor), bypassing a validating + companion `apply`; Scala 2 calls `apply`. → Both call the companion `apply` (verify a test exists; add one). +2. enum: Scala 2 handles only `scala.Enumeration`, Scala 3 only `scala.reflect.Enum`; value enums only on Scala 3. → + `KebsEnum` handles `Enumeration` on both versions and `enum` on Scala 3; `KebsValueEnum` on both versions for + sealed hierarchies / enums extending `ValueEnumLikeEntry` (today's Scala 3 bound, now also on 2.13). + **Plain sealed hierarchies of case objects do not get an `EnumLike` automatically** (decided 2026-11-21 after + review): enumeratum entries are such hierarchies too (the two implicits would compete), and it would silently turn + `{"Red":{}}` into `"Red"` for circe users. They stay ADTs; users who want enum strings use enumeratum, `Enumeration`, + a Scala 3 `enum`, or the ADT's `constructorNaming` with case objects. +3. enumeratum on Scala 3 ignores the user's `values` and fails on nested sealed hierarchies. → `Companion.values` on + both. +4. circe: Scala 2 auto-derives sealed traits, Scala 3 only case classes; snake_case comes from kebs' `snakify` on 2 and + circe's renaming on 3. → kindlings on both, given kebs' naming functions. +5. spray-json: `jsonFormatRec` is a real lazy format on 2, an alias on 3; >22 fields hand-rolled on 2 (and there it + drops *any* `JsNull` field, not only `None`); Scala 3 zips lists at runtime. → One hearth macro; recursion handled + inside the macro (`jsonFormatRec` kept as a deprecated alias of `jsonFormatN`). +6. scalacheck: different generators per version. → kindlings on both. +7. Tests: enum-related tests use enumeratum on Scala 2 and native enums on Scala 3. → Shared tests (`src/test/scala`) + exercising sealed-trait enums and enumeratum on both versions; Scala 3 `enum` tests stay in `scala-3/`. + +### 4.3 Gaps to fill + +- play-json auto-derivation (#384) — §5.4. +- jsoniter-scala module (#255) on kindlings. Contributor PR #531 (built on jsoniter's own macros) is closed with + thanks and credit in the release notes; its tests are reused where they fit. +- http4s: value-enum path matchers and `QueryParamDecoder` (parity with http4s-stir/pekko-http). +- pureconfig: `EnumLike`, `ValueEnumLike` and `InstanceConverter` readers/writers. +- scalacheck: `Arbitrary` for `EnumLike`, `ValueEnumLike` and `InstanceConverter` types. +- `EnumLike` lookups (`withNameInsensitiveOption`, upper/lower variants) use precomputed maps instead of linear scans. +- #417 is closed by the rewrite (no anonymous classes duplicated per inline site). +- #410 (sbt-typelevel) is already done — close it. + +## 5. Design + +### 5.1 Delivery + +**Approaches considered** + +- **A. One module per PR, straight into master** (picked). First PR switches the build and ports core; master + becomes 3.0-SNAPSHOT; 2.x fixes come from `series/2.x` cut at v2.3.0. Small reviewable PRs, both Scala versions + green at every step. +- B. Same PRs into a long-lived `kebs-3` branch merged at the end. Keeps master releasable as 2.x but needs rebasing. +- C. One big PR. Fast to start, hard to review and to bisect. + +**Order** + +0. **2.3.0 release** (on master, before any kebs 3 change): merge open Steward PRs except doobie RC13/RC14 (#556, + #611 — package relocation, breaking) and scala-library 3.10 (#604 — 2.x stays on 3.3 LTS). Set + `tlBaseVersion := "2.3"`, `tlMimaPreviousVersions := Set("2.2.2")`, README versions; maintainer confirms before + merges and before pushing tag `v2.3.0`. Cut `series/2.x` from the tag. +1. **Spike** (throwaway, worktree): see §7. +2. **PR: build + core** — Scala 3.9.0, JDK 17/21, `tlBaseVersion := "3.0"`, MiMa off, hearth + cross-quotes plugin + wiring, drop akka-http, doobie RC14 migration (`org.typelevel.doobie`), core `ValueClassLike` on hearth. +3. **PR: enum + enumeratum** on hearth; `EnumLike` map-based lookups; shared enum tests. +4. **PR: naming** — `Naming`, `EnumNaming`, `JsonConfig` in core (§5.3); enum codecs in every module (circe, spray, + play, doobie, baklava, pekko-http, http4s, http4s-stir, slick) moved onto `EnumNaming`. +5. **PR: spray-json** hearth macro (§5.4). +6. **PR: play-json** auto-derivation (§5.4). +7. **PR: circe** on kindlings (§5.4). +8. **PR: jsoniter** new module (§5.4). +9. **PR: scalacheck** on kindlings + enum/`InstanceConverter` arbitraries. +10. **PR: small gaps** — http4s value enums, pureconfig enum/`InstanceConverter`. +11. **Release** — docs for every module, a "Migrating to kebs 3" page, README; `v3.0.0-RC1`, then `v3.0.0`. + +Each PR keeps every existing test green on 2.13 and 3.9 (JVM; JS/Native where the module has them). + +### 5.2 Build + +- `scala_3 = "3.9.0"`; drop `-Xmax-inlines 64`/`-Yretain-trees` if no longer needed once inline derivation is gone. +- Modules containing hearth macros (core, enum, enumeratum, spray-json, play-json) get `"com.kubuszok" %%% "hearth"` and, + on Scala 3, `compilerPlugin("com.kubuszok" % "hearth-cross-quotes_3" % hearthV)`; on 2.13 they keep + `scala-reflect`/`scala-compiler % provided`. +- Layout per hearth macro: shared logic in `src/main/scala/.../internal/compiletime/*MacrosImpl.scala` + (`trait … { this: MacroCommons => … }`), entry points in `src/main/scala-2/…Compat.scala` and + `src/main/scala-3/…Compat.scala`. +- `disableScala(List("3"))` stays for jsonschema and tagged-meta; examples stay 2.13-only. + +### 5.3 Naming (core) + +A single vocabulary used for JSON field names, ADT case names and enum values, in `pl.iterators.kebs.core.naming`: + +```scala +final case class Naming(apply: String => String) { def andThen(that: Naming): Naming } +object Naming { + val identity, snakeCase, screamingSnakeCase, kebabCase, camelCase, pascalCase, lowercase, uppercase: Naming + def custom(f: String => String): Naming +} +``` + +- Word splitting lives in one place and reproduces today's `SnakifyVariant.snakify` exactly (so snake_case output does + not change for Scala 2 users); `capitalize` ≡ `pascalCase`. `SnakifyVariant`/`CapitalizeVariant` become deprecated + forwarders. +- **Enum values:** `final case class EnumNaming(naming: Naming, caseInsensitive: Boolean = true)`. Every enum codec in + every module takes an implicit `EnumNaming`; the companion holds the default (`identity`, case-insensitive), so a + user's implicit in lexical scope wins. Encoding writes `naming(name)`; decoding matches the mapped name (case- + insensitively by default — today the identity decoder is case-insensitive and upper/lower are strict; making all + lenient only accepts more input). The existing `enums.uppercase` / `enums.lowercase` objects become presets; new + presets for `snakeCase`, `screamingSnakeCase`, `kebabCase`. +- **JSON config:** one case class shared by all JSON modules: + + ```scala + final case class JsonConfig( + fieldNaming: Naming, + constructorNaming: Naming, // ADT case names + noneHandling: NoneHandling, // WriteNull | Omit + useDefaults: Boolean, // fill missing fields from case-class defaults + discriminator: Option[String] // None = wrapper object {"Case": {...}} + ) + ``` + + Each JSON protocol trait exposes an overridable `implicit def kebsJsonConfig: JsonConfig` with that module's default; + the presets (`snakified`, `capitalized`) override it. Users customise by overriding it in their protocol object, or + per type by passing a config to an explicit derivation method. (This replaces the separate `FieldNaming` / + `NoneHandling` implicits floated during discussion — one implicit is simpler to resolve unambiguously on 2.13.) +- **Module defaults preserve today's output:** + + | | fieldNaming | noneHandling | ADTs | + |---|---|---|---| + | circe | identity | WriteNull | wrapper (as circe-generic on 2.13 today) | + | spray-json | identity | Omit (`NullOptions` → WriteNull) | wrapper | + | play-json | identity | Omit (Play's convention) | wrapper | + | jsoniter (new) | identity | WriteNull (kindlings default, same as circe) | wrapper | + + `constructorNaming = identity`, `useDefaults = false`, `discriminator = None` everywhere. + +### 5.4 JSON modules + +Common rules for all four: + +- **Flatness is owned by kebs.** A single-field case class is encoded as its field only when a `ValueClassLike` is in + scope (`CaseClass1ToValueClass` mixed in), exactly as today. kindlings' own `AnyVal` unwrapping is turned off + (`unwrapValueClasses = false`) so `AnyVal` case classes without `CaseClass1ToValueClass` still encode as objects. +- **Existing instances win over kebs' auto-derivation — for the root type and for every field type.** That covers + user instances in companions (`Json.format`, circe `deriveEncoder`, Scala 3 `derives`, enumeratum's `CirceEnum` / + `PlayJsonEnum`, …), instances in lexical scope, and kebs' own flat / `InstanceConverter` / enum codecs. Mechanism: + - circe: auto entry points return `Exported[…]` (circe's low-priority hook; verified in the spike, §7.2). + - spray-json, play-json, jsoniter (no such hook): the auto entry point's macro first summons the type class for the + root type **ignoring its own entry point**; if something is found it returns that instance, otherwise it derives. + Because kindlings and our macros look up field instances through ordinary implicit search, which lands on kebs' + entry point, the same check makes companion instances win for fields too. + - Golden tests cover companion codecs, enumeratum `CirceEnum`/`PlayJsonEnum` and Scala 3 `derives`. + - Behaviour change to list in the migration guide: on **Scala 3**, kebs 2's circe auto-derivation beat companion + codecs (it sat in lexical scope); in kebs 3 companion codecs win, as they already did on Scala 2. +- Derivation is sanely-automatic where we own the macro (spray, play): the macro tries an implicit first (excluding + its own entry point), and derives otherwise, recursing internally — recursive types need no `lazy` tricks. +- **Per-field annotations are module-local, with consistent names**: each module has + `pl.iterators.kebs..annotations.{fieldName, transientField}`. + - circe and jsoniter: type aliases to kindlings' annotations (verified: aliased annotations are honoured by + kindlings on 2.13 and 3.9). jsoniter additionally aliases `named` and `stringified`. + - spray-json and play-json: one real pair of classes defined in core (`pl.iterators.kebs.core.annotations`) read by + our macros, aliased into both modules. +- ADT naming of cases uses `constructorNaming`; nested sealed hierarchies are flattened to their leaves (kindlings/ + circe semantics), in all four modules. + +Per module: + +- **circe** — `KebsCirce` keeps flat/`InstanceConverter` codecs and provides the auto entry point (implicit + `Exported[Encoder[A]]`/`Exported[Decoder[A]]` for case classes and sealed traits, see §7.2) backed by + `KindlingsEncoder`/`KindlingsDecoder.derived`, + with `JsonConfig` translated to kindlings' `Configuration` (`transformMemberNames`, `transformConstructorNames`, + `useDefaults`, `discriminator`, `unwrapValueClasses = false`). Drops the circe-generic and circe-generic-extras + dependencies. `NoneHandling.Omit` requires an upstream kindlings change (circe `transientNone`, which its jsoniter + module already has); until it is available, circe supports only `WriteNull` (today's behaviour) and `Omit` is a + compile-time error with a clear message. +- **spray-json** — hearth macro generating a `RootJsonFormat[T]` per case class (field-by-field `read`/`write`, no + 22-field limit, no runtime reflection) and per sealed hierarchy. Honors `JsonConfig` and the annotations. Missing + non-`Option` field without default → `DeserializationException` naming the field (same as spray's `fromField`). +- **play-json** — same macro shape producing `Reads`/`Writes`/`OFormat`; entry points `KebsPlayJson` (identity) plus + `snakified`/`capitalized` objects like the other JSON modules. Auto-derivation comes with the existing + `import pl.iterators.kebs.playjson._` / `KebsPlayJson` (decided 2026-11-21, for consistency with circe and spray); + existing `Json.format` / `PlayJsonEnum` instances keep winning (rule above), covered by golden tests, and the + migration guide calls out the new behaviour. +- **jsoniter** — `KebsJsoniter` provides flat/`InstanceConverter`/enum `JsonValueCodec`s and an auto entry point backed + by kindlings' jsoniter derivation, `JsonConfig` translated to `JsoniterConfig` (`withFieldNameMapper`, + `withAdtLeafClassNameMapper`, `withTransientNone` for `Omit`, discriminator/wrapper, defaults). Platforms JVM+JS+ + Native. + +### 5.5 Other modules + +- **core `ValueClassLike`** — hearth macro: for a case class with exactly one field, generates + `new ValueClassLike[T, F](v => T.apply(v), _.field)` (companion `apply`, direct accessor; no casts, no `Tuple1`). + The field type `F` must be inferred from `T` during implicit search on both versions (whitebox on 2.13; on Scala 3 a + transparent macro or retaining the `Mirror`-based type evidence while the body is macro-generated — the spike picks). + Non-case-classes and arity ≠ 1 fail fast and silently (they are implicit candidates in every flat-format search). +- **enum / enumeratum** — `EnumLike`/`ValueEnumLike` instances built from a static list of the cases (enumeratum: + `Companion.values`; `Enumeration`: `Obj.values.toList`; Scala 3 enums and `ValueEnumLikeEntry` hierarchies: the + cases in declaration order); + the name is `entryName` (enumeratum) or the case's simple name. Existing type bounds on the implicits stay, so the + enum and enumeratum implicits never compete. +- **scalacheck** — `ScalacheckInstancesSupport.arb[T]` delegates to kindlings' `Arbitrary` derivation; + `KebsArbitrarySupport` keeps its predefined instances and adds enum/`InstanceConverter` ones. +- **doobie** — migrated to doobie 1.0.0-RC14 (`org.typelevel` organisation, `org.typelevel.doobie` package). + +## 6. Behavioural spec and testing + +- Existing tests are the spec. They move from `scala-2/`/`scala-3/` into shared `src/test/scala` wherever the only + reason for the split was the macro implementation. Scala-3-only syntax (enums, opaque types) stays in `scala-3/`. +- New tests for every item in §4.2–§4.3 and §5.3–§5.4: naming presets and custom naming, annotations, `NoneHandling`, + `useDefaults`, ADTs (wrapper and discriminator, nested hierarchies, case objects), recursive types, >22 fields, + validating `apply` in `ValueClassLike`. +- **Wire-format golden tests**: for circe and spray-json, a fixed set of models encoded with kebs 2.3.0 output is + checked in as expected JSON; kebs 3 must produce identical JSON with default config. Any deliberate difference goes to + the migration guide. +- Compile-time regression check: a small benchmark (an existing test module's `Test/compile` time) recorded before and + after the circe and spray-json PRs, reported in the PR description. No hard threshold. + +### 6.1 Raising test coverage (requested 2026-11-21) + +- **`kebs-testkit`** — a test-only, unpublished cross-project (JVM/JS/Native) holding shared models and abstract + contract suites; modules depend on it `% "test->test"`. Created in the build + core PR. +- **Characterisation tests first** — golden JSON (circe, spray-json), enum strings (all enum-aware modules) and flat + formats are captured from current behaviour in the build + core PR, before any macro is swapped. +- **Contract suites** (each module plugs in its encode/decode or read/write functions): + - JSON (circe, spray-json, play-json, jsoniter): naming presets + custom, annotations, `NoneHandling`, `useDefaults`, + ADTs (wrapper, discriminator, nested, case objects), recursion (direct, mutual, generic, through `Option`/`Map`), + >22 and ~100 fields, flat value classes, `InstanceConverter`, enums, existing instances winning. + - Enums (circe, spray-json, play-json, jsoniter, doobie, slick, baklava, pekko-http, http4s, http4s-stir, + pureconfig, scalacheck): `EnumNaming` presets + custom, case-insensitive decoding, unknown values, for enumeratum, + `Enumeration`, Scala 3 `enum` and value enums. + - `ValueClassLike` / `InstanceConverter` across all integration modules. +- **Corner cases** (from hearth's derivation checklist): generic types, fixtures from another compilation unit, + private constructors and validating `apply`, zero-field classes, a user instance in the middle of a recursive + cycle, derivation inside generic functions. +- **Compile-time tests**: what must not compile, with the error message asserted (missing instance names the type and + field; no `ValueClassLike` for 2-field classes); stress — 100-field class and 100-case enum compile, no generated + method exceeds 8000 bytes (class-file `Code` attribute check). +- **Property-based round-trips** (encode→decode = identity) with generators from kebs-scalacheck. +- **Platforms**: shared suites also run on JS/Native for modules published there. +- **Line coverage**: sbt-scoverage, a CI coverage job on JVM for 2.13 and 3.9, reported per module; after 3.0 each + module's `coverageMinimumStmtTotal` is set just below what it reached (a ratchet). Line coverage cannot see macro + implementations (they run inside the compiler); for those, the contract suites and corner-case matrix are the + coverage. +- **doobie / slick value round-trips** against in-memory H2 (no Docker): today's doobie tests only assert that + `Get`/`Put` instances resolve (0% statement coverage) and slick's mostly that column types resolve (15%), so no + value is ever actually mapped. Postgres-specific types (slick-pg, doobie-postgres arrays) stay compile-level. +- Out of scope: Testcontainers / a real Postgres. + +**Baseline (master @ v2.2.2, Scala 2.13, JVM, scoverage statement / branch):** + +| Module | stmt | branch | Module | stmt | branch | +|---|---|---|---|---|---| +| core | 56% | 82% | http4s | 64% | 50% | +| instances | 84% | 100% | http4s-stir | 82% | 100% | +| enum | 100% (no runtime code) | – | pekko-http | 82% | 100% | +| enumeratum | 57% | 50% | akka-http | 86% | 100% | +| circe | 97% | 100% | slick | 15% | 0% | +| spray-json | 100% | 100% | doobie | 0% | 0% | +| play-json | 96% | 100% | baklava | 100% | 100% | +| scalacheck | 58% | 27% | pureconfig | 100% | 100% | +| jsonschema | 0% | 0% | tagged | 5% | 100% | +| tagged-meta | 93% | 82% | | | | + +High numbers in the JSON modules mostly reflect how little runtime code they have; their real logic is macro code, +which line coverage cannot see. + +## 7. Spike results (2026-11-21) + +Throwaway sbt project (2.13.18 + 3.9.0, hearth 0.4.5, kindlings-circe 0.4.0); all 9 tests green on both versions. + +1. **`ValueClassLike` with inferred `F`: works.** Shared hearth macro (`CaseClass.parse`, single primary-constructor + parameter, `Expr.quote { new ValueClassLike[T, F](…) }`). Entry points: + - 2.13: `implicit def repFromCaseClass[T <: Product, F1]: ValueClassLike[T, F1] = macro …` with a **whitebox** + bundle extending `hearth.MacroCommonsScala2`. + - 3.9: keep the `Mirror` evidence for inference and candidate filtering, body is the macro: + `inline implicit def repFromCaseClass[T <: Product, F1](using m: Mirror.ProductOf[T], teq: m.MirroredElemTypes =:= F1 *: EmptyTuple.type): ValueClassLike[T, F1] = ${ … }`. + A non-transparent inline given is expanded *after* it is selected, so the `Mirror` guard is what keeps non- + matching types from reaching the macro (a macro abort there would be a hard error, not a skipped candidate). + - Works through an outer implicit with unknown `A` (`find[T, A](implicit rep: ValueClassLike[T, A])`) and for + `ValueClassLike[T, ?]`; 2-field case classes get no instance. + - Cross-quotes gotcha on 2.13: `import field.tpe.Underlying as F` (nested path) breaks `Type.of[…F…]`; bind the + path first: `val fieldType: ?? = field.tpe; import fieldType.Underlying as F`. + - The spike constructs with `new T(…)`; the real implementation must call the companion `apply` (§4.2.1). +2. **kindlings circe inside a kebs trait: works, with one required design choice.** kebs' auto entry points must + return circe's `io.circe.export.Exported[Encoder[A]]` / `Exported[Decoder[A]]` (picked up by circe's low-priority + `importedEncoder`/`importedDecoder`), exactly like circe-generic's auto derivation. With a plain lexical implicit, + the imported kebs auto-derivation beats a user's instance in the type's companion. With `Exported`: + - companion instances win, at the top level and for fields; + - kebs' flat formats are used for fields (kindlings summons field instances first); + - recursive types, >22 fields, sealed traits (wrapper) work; + - entry-point guard: 2.13 macro aborts unless the type is a case class or sealed (candidate skipped); 3.9 uses + `inline m: Mirror.Of[A]`. + - **Semantics to keep and document:** with `CaseClass1ToValueClass` in scope, single-field ADT children are flat + too (`{"Dot":2.0}`), consistent with "every single-field case class is a value class". + - Nested derived types are expanded through kebs' entry point (one expansion per type, as in classic auto + derivation) because kindlings ignores only its own implicits. Acceptable; optional upstream improvement in §8. +3. **Aliased kindlings annotations: work** on 2.13.18 and 3.9.0 (`type fieldName = …circederivation.annotations.fieldName`). +4. **kindlings' 3.8.4-built artifacts from 3.9.0: work.** + +Consequence for spray-json, play-json and jsoniter: neither library has circe's `Exported` hook, so the auto entry +point's macro summons the root type class ignoring itself and returns what it finds, deriving only when nothing is +found (§5.4). No failure during implicit search is needed, so a plain `inline` entry point with a `Mirror.Of` guard +works on Scala 3. Verify with a spray-json test first in its PR. + +## 8. Upstream (kindlings) + +- Request: `transientNone`-style option for circe derivation (drop `None` fields when encoding). Needed for + `NoneHandling.Omit` in kebs-circe; not blocking the release. +- Optional request: a way for a wrapping library to add its own entry points to the implicits kindlings ignores when + summoning field instances (e.g. a `-Xmacro-settings` key or an annotation), so nested types are derived inside one + expansion instead of through kebs' entry point. Performance only; not blocking. +- Request: an `unwrapValueClasses`-style switch in kindlings' jsoniter derivation (0.4.0 always encodes `AnyVal` case + classes as their bare field). Until then kebs-jsoniter documents the exception: `AnyVal` case classes are flat in + jsoniter even without `CaseClass1ToValueClass`. New module, so no wire-compatibility impact. + +**Policy:** kebs 3.0 takes newer kindlings/hearth releases if they land before the release (hearth and kindlings +bumped together, all kebs hearth macros re-tested). Upstream requests never block 3.0: the fallback is a documented +per-module exception, not our own circe/jsoniter macros (writing those would defeat the "less code" goal). + +## 9. Left to the builder + +- Internal structure of the hearth macros (rules, caching), within the layout in §5.2. +- Exact names of explicit per-type derivation methods (e.g. `deriveEncoder[T](config)`), as long as they are consistent + across the four JSON modules. +- Whether `-Xmax-inlines`/`-Yretain-trees` can be dropped. +- Error message wording, as long as it names the type and the missing instance. diff --git a/design/plans/2026-11-21-plan-0-release-2.3.0.md b/design/plans/2026-11-21-plan-0-release-2.3.0.md new file mode 100644 index 00000000..68a95e19 --- /dev/null +++ b/design/plans/2026-11-21-plan-0-release-2.3.0.md @@ -0,0 +1,106 @@ +# Plan 0 — kebs 2.3.0 release (dependency bumps) Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Release kebs 2.3.0 from master with the pending dependency updates, then cut `series/2.x` so master can become 3.0-SNAPSHOT. + +**Architecture:** Operational plan — merge Scala Steward PRs, verify, prepare the release commit, tag, publish the drafted GitHub release, branch. No library code changes. + +**Tech Stack:** sbt 1.12.13, sbt-typelevel 0.8.7 (`tlBaseVersion`, `tlMimaPreviousVersions`, tag-triggered publishing), `gh` CLI. + +**Spec:** `design/2026-11-21-kebs-3-design.md` §5.1 step 0. + +## Global Constraints + +- 2.x stays on Scala 3.3 LTS (`scala_3 = "3.3.x"`) and Scala 2.13.18; JDK 11 + 17 in CI. +- Repo convention: squash merges titled ` (#N)`. +- **Every merge, every push to master, the tag push and the release publish need the maintainer's explicit go-ahead in the session** (outward-facing, hard to reverse). +- `ci.yml` is generated (sbt-github-actions); never hand-edit. The local `gh` token lacks the `workflow` scope: merging a PR that touches `.github/workflows/` fails — ask the maintainer to run `! gh auth refresh -h github.com -s workflow`. None of the PRs below touch workflows. +- Release process (from the 2.2.0 release): prep commit on master bumping `tlBaseVersion`, `tlMimaPreviousVersions`, README install-snippet versions; run `sbt +mimaReportBinaryIssues` locally before tagging; push tag `vX.Y.Z` (CI publishes to Maven Central); publish the Release Drafter draft with `gh release edit --tag vX.Y.Z --title "vX.Y.Z 🥙" --draft=false --latest`. + +## Review Focus + +- A Steward PR built against a newer Scala 3 (TASTy too new for 3.3) — CI fails with "TASTy signature has wrong version". Expected: not merged into 2.x (this is why #610 scala-java-time 2.11.0 is excluded). Re-check after each merge that master CI stays green. +- Two PRs editing adjacent lines of `build.sbt` — the second merge conflicts. Expected: resolve on the Steward branch (`gh pr checkout N`, rebase on master, push over SSH) or ask Steward to rebase; never push the PR content straight to master. +- MiMa against 2.2.2 reports a binary break caused by a dependency bump (e.g. http4s-stir 0.5 → 0.7 is early-semver-major for that library). Expected: kebs' own API unchanged → no MiMa problems in kebs artifacts; if MiMa does flag kebs classes, stop and report to the maintainer before tagging. +- The tag CI run fails mid-publish. Expected: do not re-tag blindly; report and investigate (Sonatype staging state). +- `series/2.x` branch name already exists on the remote. Expected: check first (`git ls-remote --heads origin series/2.x`), and ask if it exists. + +--- + +### Task 1: Merge the dependency PRs + +**PRs to merge (all CI-green or infra-flake only, as of 2026-11-21):** #607 (Scala 3.3.9), #596 (circe 0.14.17), #595 (pekko 1.7.1), #600 (pekko-http 1.4.2), #603 (pureconfig 0.17.11), #613 (http4s-dsl 0.23.39), #605 (http4s-stir 0.7.1), #612 (baklava-core 2.4.0), #602 (scalacheck-derived 0.11.0), #592 (magnolify-scalacheck 0.9.8), #614 (sbt-scalajs 1.23.0), #615 (sbt-jmh 0.4.9). + +**Not merged (left open for kebs 3):** #610 scala-java-time 2.11.0 (built with Scala 3.9), #611 / #556 doobie RC14 / RC13 (package relocation, breaking), #604 scala-library 3.10.0, #531 jsoniter (contributor PR, superseded by the kebs 3 jsoniter module — closed in the kebs 3 jsoniter plan with credit). + +- [ ] **Step 1: Re-run the failed "Validate Steward Config" check on #612** + +Run: `gh run rerun 44217261099 --failed` +Expected: the job passes (the failure was a coursier download error, not a code problem). Check with `gh pr checks 612`. + +- [ ] **Step 2: Get the maintainer's go-ahead to merge the 12 PRs listed above** + +- [ ] **Step 3: Merge each PR, one at a time, re-checking mergeability between merges** + +Run, per PR: `gh pr view N --json mergeable --jq .mergeable` → expect `MERGEABLE`; then +`gh pr merge N --squash --subject " (#N)"`. +If a PR becomes `CONFLICTING`, resolve as described in Review Focus, wait for its CI, then merge. + +- [ ] **Step 4: Verify master locally on both Scala versions** + +Run: `git checkout master && git pull --ff-only && sbt +test` +Expected: all tests pass on 2.13.18 and 3.3.9. + +- [ ] **Step 5: Verify master CI** + +Run: `gh run list --branch master --limit 3` +Expected: the latest CI run on master is `success`. + +### Task 2: Release commit, tag, GitHub release + +- [ ] **Step 1: Check binary compatibility against 2.2.2 before bumping** + +Run: `sbt +mimaReportBinaryIssues` +Expected: no binary incompatibilities reported for kebs modules. + +- [ ] **Step 2: Prepare the release commit** + +In `build.sbt`: `ThisBuild / tlBaseVersion := "2.3"` and `ThisBuild / tlMimaPreviousVersions := Set("2.2.2")`. +In `README.md`: install-snippet versions → `2.3.0`. +Commit message: `Update version to 2.3.0, bump MiMa previous to 2.2.2`. + +- [ ] **Step 3: Re-run MiMa with the new settings** + +Run: `sbt +mimaReportBinaryIssues` +Expected: no issues. + +- [ ] **Step 4: Get the maintainer's go-ahead, then push the commit and the tag** + +Run: `git push origin master && git tag v2.3.0 && git push origin v2.3.0` + +- [ ] **Step 5: Watch the tag's CI run until publishing finishes** + +Run: `gh run list --branch v2.3.0 --limit 1` then `gh run watch ` +Expected: `success`; artifacts appear under `https://repo1.maven.org/maven2/pl/iterators/kebs-core_3/2.3.0/` (may take up to ~30 min to sync). + +- [ ] **Step 6: Publish the drafted release** + +Run: `gh release list --limit 3` (find the Release Drafter draft), then +`gh release edit --tag v2.3.0 --title "v2.3.0 🥙" --draft=false --latest` +Expected: `gh release view v2.3.0` shows a published release with the changelog. + +### Task 3: Cut `series/2.x` and tidy the issue tracker + +- [ ] **Step 1: Check the branch name is free** + +Run: `git ls-remote --heads origin series/2.x` +Expected: no output. + +- [ ] **Step 2: Create and push `series/2.x` from the tag (maintainer go-ahead)** + +Run: `git branch series/2.x v2.3.0 && git push origin series/2.x` + +- [ ] **Step 3: Close #410 (sbt-typelevel migration — already done) with a short comment (maintainer go-ahead)** + +Run: `gh issue close 410 --comment "Done — kebs builds with sbt-typelevel (sbt-typelevel-ci-release 0.8.7)."` diff --git a/design/plans/2026-11-21-plan-1-build-core-testkit.md b/design/plans/2026-11-21-plan-1-build-core-testkit.md new file mode 100644 index 00000000..f3969605 --- /dev/null +++ b/design/plans/2026-11-21-plan-1-build-core-testkit.md @@ -0,0 +1,345 @@ +# Plan 1 — kebs 3: build switch, core `ValueClassLike` on hearth, testkit + golden tests — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Turn master into kebs 3.0-SNAPSHOT on Scala 2.13.18 + 3.9.0 / JDK 17+, port core's `ValueClassLike` macro to hearth, drop akka-http, migrate doobie to RC14, and pin today's JSON wire format with golden tests before any other macro is rewritten. + +**Architecture:** One PR ("kebs 3: build + core"). Build changes first, then the first hearth macro (shared logic in `src/main/scala`, thin `scala-2`/`scala-3` entry points), then a test-only `kebs-testkit` cross-project with shared models, and golden tests that capture current circe / spray-json / play-json output. + +**Tech Stack:** sbt 1.12.13, sbt-typelevel 0.8.7, Scala 2.13.18 / 3.9.0, hearth 0.4.5 (+ `hearth-cross-quotes_3` compiler plugin), scalatest 3.2.20, doobie 1.0.0-RC14. + +**Spec:** `design/2026-11-21-kebs-3-design.md` (§3 constraints, §4.2.1, §5.1 step 2, §5.2, §5.5 core, §6, §6.1, §7.1). + +**Prerequisite:** Plan 0 done (v2.3.0 tagged, `series/2.x` cut). Work on branch `kebs-3/build-core` from master. + +## Global Constraints + +- Scala versions: `scala_2_13 = "2.13.18"`, `scala_3 = "3.9.0"`. JDK 17 and 21 in CI. +- `tlBaseVersion := "3.0"`; MiMa off for 3.0.0 (`tlMimaPreviousVersions := Set.empty`). +- hearth `0.4.5` exactly (kindlings 0.4.0 depends on it; later plans add kindlings at the same hearth version). +- Every existing test stays green on 2.13 and 3.9 (JVM; JS/Native for modules that have them). +- Golden tests capture **current** behaviour. If current output differs from a literal in this plan, stop and report it — never adjust a literal to make a golden test pass without the maintainer's decision. +- `ci.yml` is generated: change `build.sbt`, run `sbt githubWorkflowGenerate`, commit the result. Pushing/merging changes to `.github/workflows/` needs the `workflow` token scope — ask the maintainer to run `! gh auth refresh -h github.com -s workflow` before opening the PR. +- Do not put planning/design files under `docs/` (mdoc publishes everything there). +- Scalafmt runs on compile; commit formatted code. + +## Review Focus + +- **Case class with a validating or normalising companion `apply`** (e.g. `object Email { def apply(v: String) = new Email(v.toLowerCase) }`). Expected: `ValueClassLike.apply` goes through it on both Scala versions (Scala 3 used to bypass it). Pinned in Task 3. +- **Generic single-field case class** (`Box[A](a: A)`) and one **defined in another compilation unit** (testkit). Expected: `ValueClassLike[Box[Int], Int]` and `ValueClassLike[testkit.Id, String]` resolve. Pinned in Task 3 (`Box`) and Task 4 (`person flat` resolves `ValueClassLike` for `testkit.model.Id`, compiled in another module; core's own tests cannot depend on testkit without a cycle). +- **Flat-format search over every type** — `flatDecoder[T, A](implicit rep: ValueClassLike[T, A], …)` is tried for `Int`, `List[X]`, 2-field case classes, sealed traits. Expected: no instance and no compile error for those (the existing JSON/HTTP test suites exercise this heavily; they must stay green). Pinned by Task 3's `assertDoesNotCompile` cases plus the full `+test` run. +- **A field the goldens don't cover changes encoding after Scala 3.9** (e.g. `Option` inside a flat value class). Expected: same JSON as 2.3.0. Goldens include `Option` fields, flat value classes, enums, >22 fields and an `InstanceConverter` type (Tasks 4–6). +- **JS/Native builds** of core with the hearth dependency. Expected: `coreJS/test` and `coreNative/test` pass (hearth is published for both). Pinned in Task 3 Step 6. + +--- + +### Task 1: Scala 3.9, JDK 17/21, version 3.0, doobie RC14, scala-java-time 2.11 + +**Files:** +- Modify: `build.sbt` (`scala_3`, `tlBaseVersion`, `tlMimaPreviousVersions`, `githubWorkflowJavaVersions`, doobie and scala-java-time coordinates, Scala 3 `-Ykind-projector` → `-Xkind-projector` in `commonSettings`) +- Modify: `doobie/src/main/scala/pl/iterators/kebs/doobie/KebsDoobie.scala`, `doobie/src/main/scala/pl/iterators/kebs/doobie/enums/KebsDoobieEnums.scala`, and the doobie test sources (6 `import doobie…` lines in total) +- Modify: `.github/workflows/ci.yml` (regenerated) + +- [ ] **Step 1: Apply the build changes** + +`val scala_3 = "3.9.0"`; `ThisBuild / tlBaseVersion := "3.0"`; `ThisBuild / tlMimaPreviousVersions := Set.empty`; +`ThisBuild / githubWorkflowJavaVersions := Seq(JavaSpec.temurin("17"), JavaSpec.temurin("21"))`; +`val doobie = "org.typelevel" %% "doobie-core" % "1.0.0-RC14"`, `val doobiePg = "org.typelevel" %% "doobie-postgres" % "1.0.0-RC14"`; +`scalaJavaTime` → `"2.11.0"`. + +- [ ] **Step 2: Run the doobie module to see the expected failure** + +Run: `sbt "++3.9.0" doobieSupport/Test/compile` +Expected: FAIL — `Not found: doobie` in `KebsDoobie.scala:3` and `KebsDoobieEnums.scala:3`. + +- [ ] **Step 3: Move doobie imports to the relocated package** + +Every `import doobie.X` / `import doobie._` / `import doobie.implicits._` / `import doobie.postgres._` becomes `import org.typelevel.doobie.X` / `org.typelevel.doobie._` / `org.typelevel.doobie.implicits._` / `org.typelevel.doobie.postgres._` (package verified in the RC14 jar: `org/typelevel/doobie/**`). + +- [ ] **Step 4: Run all tests on both Scala versions (JVM)** + +Run: `sbt +test` +Expected: PASS on 2.13.18 and 3.9.0. New Scala 3.9 deprecation warnings (`_` wildcard in types, `with` type operator, implicit args without `using`) are acceptable in this task. + +- [ ] **Step 5: Regenerate CI and commit** + +Run: `sbt githubWorkflowGenerate` +```bash +git add build.sbt doobie .github/workflows/ci.yml +git commit -m "kebs 3: Scala 3.9.0, JDK 17/21, version 3.0, doobie 1.0.0-RC14" +``` + +### Task 2: Drop akka-http + +**Files:** +- Delete: `akka-http/` +- Modify: `build.sbt` (remove `akkaHttpSupport`, `akkaHttpSettings`, `akkaVersion`, `akkaHttpVersion`, `akkaStream`, `akkaStreamTestkit`, `akkaHttp`, `akkaHttpTestkit`, `akkaHttpInExamples`, and `akkaHttpSupport` from the root `aggregate`) +- Rename: `docs/akka-http.md` → `docs/pekko-http.md` (title `Pekko HTTP`, heading `# kebs-pekko-http`, remove the Akka setup line and "Akka" wording) +- Modify: `docs/http4s.md` (link `akka-http.md#path-matchers` → `pekko-http.md#path-matchers`, "Akka/Pekko HTTP matchers" → "Pekko HTTP matchers"; keep "Akka HTTP-style directives" — that describes http4s-stir's style), `docs/core-concepts.md` ("circe, slick, akka-http, etc." → "circe, slick, pekko-http, etc."), `README.md` (remove the `kebs-akka-http` row) +- Modify: `.github/workflows/ci.yml` (regenerated) + +- [ ] **Step 1: Remove the module, its build definitions and docs references as listed above** + +- [ ] **Step 2: Verify nothing references akka any more** + +Run: `grep -rni "akka" --include=*.sbt --include=*.scala --include=*.md . | grep -v "/target/" | grep -vi "akka http-style"` +Expected: no output. + +- [ ] **Step 3: Verify the build and docs** + +Run: `sbt projects +compile docs/mdoc` +Expected: no `akkaHttpSupport` in the project list; compile and mdoc succeed. + +- [ ] **Step 4: Regenerate CI and commit** + +Run: `sbt githubWorkflowGenerate` +```bash +git add -A build.sbt akka-http docs README.md .github/workflows/ci.yml +git commit -m "kebs 3: drop kebs-akka-http (use kebs-pekko-http)" +``` + +### Task 3: hearth wiring + `ValueClassLike` on hearth + +**Files:** +- Modify: `build.sbt` — `coreSettings`: add `libraryDependencies += "com.kubuszok" %%% "hearth" % hearthV` (`val hearthV = "0.4.5"`), on Scala 3 `compilerPlugin("com.kubuszok" % "hearth-cross-quotes_3" % hearthV)`, `scalaTest.value % "test"`; `baseSettings` on 2.13: add `"-Xsource:3"` and `"-Wconf:cat=scala3-migration:s"` +- Create: `core/src/main/scala/pl/iterators/kebs/core/macros/ValueClassLike.scala` +- Create: `core/src/main/scala/pl/iterators/kebs/core/macros/internal/ValueClassLikeMacrosImpl.scala` +- Create: `core/src/main/scala-2/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala` +- Create: `core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala` +- Delete: `core/src/main/scala-2/pl/iterators/kebs/core/macros/ValueClassReps.scala`, `core/src/main/scala-3/pl/iterators/kebs/core/macros/ValueClassReps.scala` +- Keep: `core/src/main/scala-2/pl/iterators/kebs/core/macros/MacroUtils.scala` (still used by the Scala 2 circe/spray/enumeratum/jsonschema macros until their plans) +- Test: `core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeTests.scala` + +**Interfaces:** +- Produces (public, unchanged names): `final class ValueClassLike[VC, F1](val apply: F1 => VC, val unapply: VC => F1)`; `trait CaseClass1ToValueClass { implicit def repFromCaseClass[VC <: Product, F1]: ValueClassLike[VC, F1] }` (Scala 2 signature) / `inline implicit def repFromCaseClass[T <: Product, F1](using m: Mirror.ProductOf[T], teq: m.MirroredElemTypes =:= F1 *: EmptyTuple.type): ValueClassLike[T, F1]` (Scala 3); `object CaseClass1ToValueClass extends CaseClass1ToValueClass`. +- Produces (internal, reused by later plans as the pattern): `private[kebs] trait ValueClassLikeMacrosImpl { this: hearth.MacroCommons => def deriveValueClassLike[T: Type]: Expr_?? }` returning an existential `Expr[ValueClassLike[T, F]]`. + +- [ ] **Step 1: Write the failing tests** + +```scala +package pl.iterators.kebs.core + +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import pl.iterators.kebs.core.macros.{CaseClass1ToValueClass, ValueClassLike} + +object ValueClassLikeTestDomain { + final case class Plain(value: String) + final case class Box[A](a: A) + final case class Positive(value: Int) + object Positive { def apply(value: Int): Positive = { require(value > 0, "must be positive"); new Positive(value) } } + final case class Email(value: String) + object Email { def apply(value: String): Email = new Email(value.toLowerCase) } + final case class Two(a: Int, b: Int) + final class NotCase(val value: Int) +} + +class ValueClassLikeTests extends AnyFunSuite with Matchers with CaseClass1ToValueClass { + import ValueClassLikeTestDomain._ + + test("derives apply/unapply for a single-field case class") { + val rep = implicitly[ValueClassLike[Plain, String]] + rep.apply("a") shouldBe Plain("a") + rep.unapply(Plain("b")) shouldBe "b" + } + test("infers the field type through an outer implicit") { + def find[T, A](implicit rep: ValueClassLike[T, A]): ValueClassLike[T, A] = rep + find[Plain, String].unapply(Plain("c")) shouldBe "c" + } + test("generic case class") { + implicitly[ValueClassLike[Box[Int], Int]].apply(1) shouldBe Box(1) + } + test("uses the companion apply (validation)") { + val rep = implicitly[ValueClassLike[Positive, Int]] + an[IllegalArgumentException] should be thrownBy rep.apply(-1) + } + test("uses the companion apply (normalisation)") { + implicitly[ValueClassLike[Email, String]].apply("A@B.PL").value shouldBe "a@b.pl" + } + test("no instance for a 2-field case class or a non-case class") { + assertDoesNotCompile("implicitly[ValueClassLike[Two, Int]]") + assertDoesNotCompile("implicitly[ValueClassLike[NotCase, Int]]") + } +} +``` + +- [ ] **Step 2: Run them to see the expected failure** + +Run: `sbt "++3.9.0" core/testOnly pl.iterators.kebs.core.ValueClassLikeTests` +Expected: FAIL — "uses the companion apply (validation)" and "(normalisation)" fail on Scala 3 (today's `Mirror.fromProduct` bypasses `apply`). (On 2.13 they already pass.) + +- [ ] **Step 3: Wire hearth into the build** (the `build.sbt` changes listed under Files) + +- [ ] **Step 4: Implement the shared macro and both entry points** + +`ValueClassLikeMacrosImpl.deriveValueClassLike[T]` (see design §7.1 for the shape proven in the spike): +1. `CaseClass.parse[T]`; not a case class → `Environment.reportErrorAndAbort` naming the type. +2. Exactly one parameter across the primary constructor's parameter lists, else abort. +3. Bind the field type without a nested path (`val fieldType: ?? = field.tpe; import fieldType.Underlying as F` — `import field.tpe.Underlying as F` breaks cross-quotes on 2.13). +4. Construct via the companion's `apply` taking exactly one parameter of type `F` (`Type[T].unsortedMethodsNamed("apply")`, then `Method.ApplyValues#apply(Map(name -> arg.as_??))` / `build()`), applying `T`'s type arguments for generic case classes; fall back to `CaseClass.construct` only when no such `apply` is callable at the call site. +5. Read the field with `caseClass.caseFieldValuesAt(t)`. +6. Return `Expr.quote { new ValueClassLike[T, F]((f: F) => …, (t: T) => …) }.as_??`. + +Scala 2 entry point: `implicit def repFromCaseClass[VC <: Product, F1]: ValueClassLike[VC, F1] = macro ValueClassRepMacros.materializeValueClassRep[VC, F1]` with `class ValueClassRepMacros(val c: whitebox.Context) extends hearth.MacroCommonsScala2 with ValueClassLikeMacrosImpl` (**whitebox** is required so `F1` is inferred). +Scala 3 entry point: the `inline implicit def` from Interfaces, body `${ ValueClassLikeMacros.materialize[T, F1] }` with `class ValueClassLikeMacros(q: Quotes) extends hearth.MacroCommonsScala3(using q), ValueClassLikeMacrosImpl`. The `Mirror` evidence stays: it drives inference of `F1` and keeps non-matching types from reaching the macro. + +- [ ] **Step 5: Run the new tests and the whole build on both versions** + +Run: `sbt core/testOnly pl.iterators.kebs.core.ValueClassLikeTests "++3.9.0" core/testOnly pl.iterators.kebs.core.ValueClassLikeTests` then `sbt +test` +Expected: PASS everywhere. + +- [ ] **Step 6: Run core on JS and Native** + +Run: `sbt +coreJS/test +coreNative/test` +Expected: PASS. + +- [ ] **Step 7: Commit** + +```bash +git add build.sbt core +git commit -m "kebs 3: ValueClassLike on hearth (companion apply on both Scala versions)" +``` + +### Task 4: `kebs-testkit` + circe golden tests + +**Files:** +- Modify: `build.sbt` — new `lazy val testkit = crossProject(JSPlatform, NativePlatform, JVMPlatform).withoutSuffixFor(JVMPlatform).crossType(CrossType.Pure).in(file("testkit")).dependsOn(core).settings(commonSettings *).settings(noPublishSettings *).settings(name := "testkit", moduleName := "kebs-testkit", libraryDependencies += enumeratum.value)` with `crossScalaVersions := supportedScalaVersions`; add `testkit` to the root `aggregate`; `circeSupport` gets `.dependsOn(testkit % "test->compile")` +- Create: `testkit/src/main/scala/pl/iterators/kebs/testkit/model.scala` +- Create: `circe/src/test/scala/pl/iterators/kebs/circe/golden/CirceGoldenTests.scala` +- Create: `circe/src/test/scala-2/pl/iterators/kebs/circe/golden/CirceAdtGoldenTests.scala` + +**Interfaces:** +- Produces (`pl.iterators.kebs.testkit.model`, used by Tasks 5–6 and later plans): + - `final case class Id(value: String)` + - `final case class Person(id: Id, name: String, age: Int, nickname: Option[String])` + - `final case class Naming(someField: Int, anotherFieldName: String, field1Name: Int, httpURL: String)` + - `final case class Event(id: Id, at: java.time.Instant)` + - `final case class Wide(f1: Int, …, f22: Int, f23: Option[String])` (23 fields `f1`..`f22: Int`, `f23: Option[String]`) + - `sealed abstract class Color extends enumeratum.EnumEntry; object Color extends enumeratum.Enum[Color] { case object Red; case object DarkBlue; val values = findValues }` + - `sealed abstract class Level(val value: Int) extends enumeratum.values.IntEnumEntry with pl.iterators.kebs.core.enums.ValueEnumLikeEntry[Int]; object Level extends enumeratum.values.IntEnum[Level] { case object Low extends Level(1); case object High extends Level(2); val values = findValues }` + - `final case class Paint(color: Color, level: Level)` + - `sealed trait Shape; final case class Circle(r: Double, label: String) extends Shape; case object Empty extends Shape` + +- [ ] **Step 1: Write the golden tests** (expected JSON parsed and compared as `Json` values; decode must round-trip) + +Protocols: `object Default extends KebsCirce`, `object Flat extends KebsCirce with CaseClass1ToValueClass`, `pl.iterators.kebs.circe.snakified`, `pl.iterators.kebs.circe.capitalized`; enums via `KebsEnumeratum`/`KebsValueEnumeratum` with `pl.iterators.kebs.circe.enums._`, plus `enums.uppercase` and `enums.lowercase`; `Instant` via `pl.iterators.kebs.instances.KebsInstances`. + +| Test name | Protocol | Value | Expected JSON | +|---|---|---|---| +| `person default` | Default | `Person(Id("x"), "Ann", 30, None)` | `{"id":{"value":"x"},"name":"Ann","age":30,"nickname":null}` | +| `person flat` | Flat | `Person(Id("x"), "Ann", 30, Some("A"))` | `{"id":"x","name":"Ann","age":30,"nickname":"A"}` | +| `naming snakified` | snakified | `Naming(1, "a", 2, "u")` | `{"some_field":1,"another_field_name":"a","field1_name":2,"http_url":"u"}` | +| `naming capitalized` | capitalized | `Naming(1, "a", 2, "u")` | `{"SomeField":1,"AnotherFieldName":"a","Field1Name":2,"HttpURL":"u"}` | +| `enums` | Flat + enums | `Paint(Color.DarkBlue, Level.High)` | `{"color":"DarkBlue","level":2}` | +| `enums uppercase` | Flat + enums.uppercase | `Paint(Color.DarkBlue, Level.High)` | `{"color":"DARKBLUE","level":2}` | +| `enums lowercase` | Flat + enums.lowercase | `Paint(Color.DarkBlue, Level.High)` | `{"color":"darkblue","level":2}` | +| `instance converter` | Flat + KebsInstances | `Event(Id("e"), Instant.parse("2026-01-02T03:04:05Z"))` | `{"id":"e","at":"2026-01-02T03:04:05Z"}` | +| `wide (>22 fields)` | Default | `Wide(1, 2, …, 22, None)` | `{"f1":1,…,"f22":22,"f23":null}` | + +Also assert case-insensitive decoding of the default enum decoder: decoding `{"color":"darkblue","level":2}` with the default protocol gives `Paint(Color.DarkBlue, Level.High)`. + +`CirceAdtGoldenTests` (Scala 2 only — Scala 3 kebs 2 does not derive sealed traits; the circe plan moves it to shared), using the `Default` protocol (with `Flat`, single-field children would be flat): +`Circle(1.0, "c"): Shape` → `{"Circle":{"r":1.0,"label":"c"}}`; `Empty: Shape` → `{"Empty":{}}`. + +- [ ] **Step 2: Run them against the current implementation** + +Run: `sbt +circeSupport/testOnly "pl.iterators.kebs.circe.golden.*"` +Expected: PASS on both versions. Any mismatch → stop and report it with the actual output (see Global Constraints). + +- [ ] **Step 3: Commit** + +```bash +git add build.sbt testkit circe/src/test +git commit -m "kebs 3: kebs-testkit module and circe golden tests (2.x wire format)" +``` + +### Task 5: spray-json golden tests + +**Files:** +- Modify: `build.sbt` — `sprayJsonSupport` gets `.dependsOn(testkit.jvm % "test->compile")` +- Create: `spray-json/src/test/scala/pl/iterators/kebs/sprayjson/golden/SprayGoldenTests.scala` + +**Interfaces:** +- Consumes: `pl.iterators.kebs.testkit.model._` (Task 4). + +- [ ] **Step 1: Write the golden tests** (expected parsed with `JsonParser`, compared as `JsValue`; read must round-trip) + +Protocols: `object Default extends DefaultJsonProtocol with KebsSprayJson`, `object Flat extends DefaultJsonProtocol with KebsSprayJson with CaseClass1ToValueClass`, `object FlatNulls extends DefaultJsonProtocol with KebsSprayJson with CaseClass1ToValueClass with NullOptions`, `pl.iterators.kebs.sprayjson.snakified`, `pl.iterators.kebs.sprayjson.capitalized`; enums via `pl.iterators.kebs.sprayjson.enums._` (+ `uppercase`, `lowercase`); `KebsInstances` for `Instant`. + +| Test name | Protocol | Value | Expected JSON | +|---|---|---|---| +| `person default` | Default | `Person(Id("x"), "Ann", 30, None)` | `{"id":{"value":"x"},"name":"Ann","age":30}` | +| `person flat` | Flat | `Person(Id("x"), "Ann", 30, Some("A"))` | `{"id":"x","name":"Ann","age":30,"nickname":"A"}` | +| `person NullOptions` | FlatNulls | `Person(Id("x"), "Ann", 30, None)` | `{"id":"x","name":"Ann","age":30,"nickname":null}` | +| `naming snakified` | snakified | `Naming(1, "a", 2, "u")` | `{"some_field":1,"another_field_name":"a","field1_name":2,"http_url":"u"}` | +| `naming capitalized` | capitalized | `Naming(1, "a", 2, "u")` | `{"SomeField":1,"AnotherFieldName":"a","Field1Name":2,"HttpURL":"u"}` | +| `enums` / `enums uppercase` / `enums lowercase` | Flat + enums variants | `Paint(Color.DarkBlue, Level.High)` | `{"color":"DarkBlue","level":2}` / `"DARKBLUE"` / `"darkblue"` | +| `instance converter` | Flat + KebsInstances | `Event(Id("e"), Instant.parse("2026-01-02T03:04:05Z"))` | `{"id":"e","at":"2026-01-02T03:04:05Z"}` | +| `wide (>22 fields)` | Default | `Wide(1, …, 22, None)` | `{"f1":1,…,"f22":22}` | +| `wide NullOptions` | FlatNulls | `Wide(1, …, 22, None)` | `{"f1":1,…,"f22":22,"f23":null}` | + +- [ ] **Step 2: Run them against the current implementation** + +Run: `sbt +sprayJsonSupport/testOnly "pl.iterators.kebs.sprayjson.golden.*"` +Expected: PASS on both versions; any mismatch → stop and report. + +- [ ] **Step 3: Commit** + +```bash +git add build.sbt spray-json/src/test +git commit -m "kebs 3: spray-json golden tests (2.x wire format)" +``` + +### Task 6: play-json golden tests + +**Files:** +- Modify: `build.sbt` — `playJsonSupport` gets `.dependsOn(testkit % "test->compile")` +- Create: `play-json/src/test/scala/pl/iterators/kebs/playjson/golden/PlayJsonGoldenTests.scala` + +**Interfaces:** +- Consumes: `pl.iterators.kebs.testkit.model._` (Task 4). + +- [ ] **Step 1: Write the golden tests** — kebs 2 has no case-class derivation for play-json, so the goldens pin what kebs does provide, with user-written `Json.format` for case classes (this is also the coexistence the play-json plan must preserve): + +Protocol: `object Flat extends KebsPlayJson with CaseClass1ToValueClass`, `pl.iterators.kebs.playjson.enums._` (+ `uppercase`, `lowercase`), `KebsInstances`; in the test: `implicit val personFormat: OFormat[Person] = Json.format[Person]`, same for `Paint` and `Event`. + +| Test name | Value | Expected JSON | +|---|---|---| +| `flat value class` | `Id("x")` | `"x"` | +| `user Json.format with kebs field formats` | `Person(Id("x"), "Ann", 30, None)` | `{"id":"x","name":"Ann","age":30}` | +| `enums` / `uppercase` / `lowercase` | `Paint(Color.DarkBlue, Level.High)` | `{"color":"DarkBlue","level":2}` / `"DARKBLUE"` / `"darkblue"` | +| `instance converter` | `Event(Id("e"), Instant.parse("2026-01-02T03:04:05Z"))` | `{"id":"e","at":"2026-01-02T03:04:05Z"}` | + +- [ ] **Step 2: Run them against the current implementation (JVM and JS)** + +Run: `sbt +playJsonSupport/testOnly "pl.iterators.kebs.playjson.golden.*" +playJsonSupportJS/testOnly "pl.iterators.kebs.playjson.golden.*"` +Expected: PASS; any mismatch → stop and report. + +- [ ] **Step 3: Commit** + +```bash +git add build.sbt play-json/src/test +git commit -m "kebs 3: play-json golden tests (2.x wire format)" +``` + +### Task 7: Open the PR + +- [ ] **Step 1: Full verification** + +Run: `sbt +test +coreJS/test +coreNative/test docs/mdoc` +Expected: all green. + +- [ ] **Step 2: Push and open the PR (maintainer go-ahead; `workflow` scope needed for `ci.yml`)** + +```bash +git push -u origin kebs-3/build-core +gh pr create --base master --title "kebs 3: Scala 3.9, ValueClassLike on hearth, testkit + golden tests" --body-file <(…summary of Tasks 1–6, link to design/2026-11-21-kebs-3-design.md…) +``` +Expected: CI green on JDK 17 and 21. + +--- + +## Notes for later plans (not tasks here) + +- Enum-string goldens for the non-JSON modules (doobie, slick, baklava, pekko-http, http4s, http4s-stir) and the H2 value round-trips for doobie/slick are written at the start of the naming plan, before its enum-codec refactor (same "capture before change" rule). +- `MacroUtils` (Scala 2) is deleted once circe, spray-json and enumeratum no longer use it; jsonschema then gets its own copy of the two helpers it needs. From 8f6307ac88463dc438033894b2195e567f4cba89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Sowa?= Date: Sat, 21 Nov 2026 10:18:57 +0000 Subject: [PATCH 02/10] kebs 3: Scala 3.9.0, JDK 17/21, version 3.0, doobie 1.0.0-RC14 Also scala-java-time 2.11.0 (built with Scala 3.9) and -Xkind-projector (-Ykind-projector is deprecated on Scala 3.9). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFD5QTj91bQhcjiNo9n48K --- .github/workflows/ci.yml | 70 +++++++++---------- build.sbt | 16 ++--- .../pl/iterators/kebs/doobie/KebsDoobie.scala | 2 +- .../kebs/doobie/enums/KebsDoobieEnums.scala | 2 +- .../kebs/doobie/ComplexTypesTests.scala | 8 +-- 5 files changed, 49 insertions(+), 49 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9724dd05..abbc8e57 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,7 +29,7 @@ jobs: matrix: os: [ubuntu-22.04] scala: [2.13, 3] - java: [temurin@11, temurin@17] + java: [temurin@17, temurin@21] runs-on: ${{ matrix.os }} timeout-minutes: 60 steps: @@ -41,30 +41,30 @@ jobs: - name: Setup sbt uses: sbt/setup-sbt@v1 - - name: Setup Java (temurin@11) - id: setup-java-temurin-11 - if: matrix.java == 'temurin@11' + - name: Setup Java (temurin@17) + id: setup-java-temurin-17 + if: matrix.java == 'temurin@17' uses: actions/setup-java@v5 with: distribution: temurin - java-version: 11 + java-version: 17 cache: sbt - name: sbt update - if: matrix.java == 'temurin@11' && steps.setup-java-temurin-11.outputs.cache-hit == 'false' + if: matrix.java == 'temurin@17' && steps.setup-java-temurin-17.outputs.cache-hit == 'false' run: sbt +update - - name: Setup Java (temurin@17) - id: setup-java-temurin-17 - if: matrix.java == 'temurin@17' + - name: Setup Java (temurin@21) + id: setup-java-temurin-21 + if: matrix.java == 'temurin@21' uses: actions/setup-java@v5 with: distribution: temurin - java-version: 17 + java-version: 21 cache: sbt - name: sbt update - if: matrix.java == 'temurin@17' && steps.setup-java-temurin-17.outputs.cache-hit == 'false' + if: matrix.java == 'temurin@21' && steps.setup-java-temurin-21.outputs.cache-hit == 'false' run: sbt +update - name: Check that workflows are up to date @@ -74,11 +74,11 @@ jobs: run: sbt '++ ${{ matrix.scala }}' test - name: Check binary compatibility - if: matrix.java == 'temurin@11' && matrix.os == 'ubuntu-22.04' + if: matrix.java == 'temurin@17' && matrix.os == 'ubuntu-22.04' run: sbt '++ ${{ matrix.scala }}' mimaReportBinaryIssues - name: Generate API documentation - if: matrix.java == 'temurin@11' && matrix.os == 'ubuntu-22.04' + if: matrix.java == 'temurin@17' && matrix.os == 'ubuntu-22.04' run: sbt '++ ${{ matrix.scala }}' doc - name: Make target directories @@ -103,7 +103,7 @@ jobs: strategy: matrix: os: [ubuntu-22.04] - java: [temurin@11] + java: [temurin@17] runs-on: ${{ matrix.os }} steps: - name: Checkout current branch (full) @@ -114,30 +114,30 @@ jobs: - name: Setup sbt uses: sbt/setup-sbt@v1 - - name: Setup Java (temurin@11) - id: setup-java-temurin-11 - if: matrix.java == 'temurin@11' + - name: Setup Java (temurin@17) + id: setup-java-temurin-17 + if: matrix.java == 'temurin@17' uses: actions/setup-java@v5 with: distribution: temurin - java-version: 11 + java-version: 17 cache: sbt - name: sbt update - if: matrix.java == 'temurin@11' && steps.setup-java-temurin-11.outputs.cache-hit == 'false' + if: matrix.java == 'temurin@17' && steps.setup-java-temurin-17.outputs.cache-hit == 'false' run: sbt +update - - name: Setup Java (temurin@17) - id: setup-java-temurin-17 - if: matrix.java == 'temurin@17' + - name: Setup Java (temurin@21) + id: setup-java-temurin-21 + if: matrix.java == 'temurin@21' uses: actions/setup-java@v5 with: distribution: temurin - java-version: 17 + java-version: 21 cache: sbt - name: sbt update - if: matrix.java == 'temurin@17' && steps.setup-java-temurin-17.outputs.cache-hit == 'false' + if: matrix.java == 'temurin@21' && steps.setup-java-temurin-21.outputs.cache-hit == 'false' run: sbt +update - name: Download target directories (2.13) @@ -190,7 +190,7 @@ jobs: strategy: matrix: os: [ubuntu-22.04] - java: [temurin@11] + java: [temurin@17] runs-on: ${{ matrix.os }} steps: - name: Checkout current branch (full) @@ -201,30 +201,30 @@ jobs: - name: Setup sbt uses: sbt/setup-sbt@v1 - - name: Setup Java (temurin@11) - id: setup-java-temurin-11 - if: matrix.java == 'temurin@11' + - name: Setup Java (temurin@17) + id: setup-java-temurin-17 + if: matrix.java == 'temurin@17' uses: actions/setup-java@v5 with: distribution: temurin - java-version: 11 + java-version: 17 cache: sbt - name: sbt update - if: matrix.java == 'temurin@11' && steps.setup-java-temurin-11.outputs.cache-hit == 'false' + if: matrix.java == 'temurin@17' && steps.setup-java-temurin-17.outputs.cache-hit == 'false' run: sbt +update - - name: Setup Java (temurin@17) - id: setup-java-temurin-17 - if: matrix.java == 'temurin@17' + - name: Setup Java (temurin@21) + id: setup-java-temurin-21 + if: matrix.java == 'temurin@21' uses: actions/setup-java@v5 with: distribution: temurin - java-version: 17 + java-version: 21 cache: sbt - name: sbt update - if: matrix.java == 'temurin@17' && steps.setup-java-temurin-17.outputs.cache-hit == 'false' + if: matrix.java == 'temurin@21' && steps.setup-java-temurin-21.outputs.cache-hit == 'false' run: sbt +update - name: Submit Dependencies diff --git a/build.sbt b/build.sbt index 0ef9d17c..70afc74b 100644 --- a/build.sbt +++ b/build.sbt @@ -1,7 +1,7 @@ import sbt.librarymanagement.ConflictWarning val scala_2_13 = "2.13.18" -val scala_3 = "3.3.9" +val scala_3 = "3.9.0" val mainScalaVersion = scala_3 val supportedScalaVersions = Seq(scala_2_13, scala_3) @@ -17,10 +17,10 @@ ThisBuild / publishTo := { else localStaging.value } -ThisBuild / tlBaseVersion := "2.3" +ThisBuild / tlBaseVersion := "3.0" ThisBuild / tlCiHeaderCheck := false -ThisBuild / tlMimaPreviousVersions := Set("2.2.2") -ThisBuild / githubWorkflowJavaVersions := Seq(JavaSpec.temurin("11"), JavaSpec.temurin("17")) +ThisBuild / tlMimaPreviousVersions := Set.empty +ThisBuild / githubWorkflowJavaVersions := Seq(JavaSpec.temurin("17"), JavaSpec.temurin("21")) ThisBuild / githubWorkflowPublishTargetBranches := Seq(RefPredicate.StartsWith(Ref.Tag("v")), RefPredicate.Equals(Ref.Branch("master"))) lazy val baseSettings = Seq( @@ -118,8 +118,8 @@ val slick = "com.typesafe.slick" %% "slick" % "3.6.1" val optionalSlick = optional(slick) val playJson = Def.setting("org.playframework" %%% "play-json" % "3.0.6") val slickPg = "com.github.tminglei" %% "slick-pg" % "0.23.1" -val doobie = "org.tpolecat" %% "doobie-core" % "1.0.0-RC12" -val doobiePg = "org.tpolecat" %% "doobie-postgres" % "1.0.0-RC12" +val doobie = "org.typelevel" %% "doobie-core" % "1.0.0-RC14" +val doobiePg = "org.typelevel" %% "doobie-postgres" % "1.0.0-RC14" val sprayJson = "io.spray" %% "spray-json" % "1.3.6" val circeV = "0.14.17" val circe = Def.setting("io.circe" %%% "circe-core" % circeV) @@ -184,12 +184,12 @@ val pureConfig = "com.github.pureconfig" %% "pureconfig-core" val pureConfigGeneric = "com.github.pureconfig" %% "pureconfig-generic" % pureConfigVersion val pureConfigGenericScala3 = "com.github.pureconfig" %% "pureconfig-generic-scala3" % pureConfigVersion -val scalaJavaTime = Def.setting("io.github.cquiroz" %%% "scala-java-time" % "2.7.0") +val scalaJavaTime = Def.setting("io.github.cquiroz" %%% "scala-java-time" % "2.11.0") lazy val commonSettings = baseSettings ++ Seq( scalacOptions ++= (if (scalaVersion.value.startsWith("3")) - Seq("-language:implicitConversions", "-Ykind-projector", "-Xignore-scala2-macros") + Seq("-language:implicitConversions", "-Xkind-projector", "-Xignore-scala2-macros") else Seq("-language:implicitConversions", "-language:experimental.macros")), // (scalacOptions in Test) ++= Seq("-Ymacro-debug-lite" /*, "-Xlog-implicits"*/ ), libraryDependencies += scalaTest.value % "test" diff --git a/doobie/src/main/scala/pl/iterators/kebs/doobie/KebsDoobie.scala b/doobie/src/main/scala/pl/iterators/kebs/doobie/KebsDoobie.scala index 453858a4..a0ae7133 100644 --- a/doobie/src/main/scala/pl/iterators/kebs/doobie/KebsDoobie.scala +++ b/doobie/src/main/scala/pl/iterators/kebs/doobie/KebsDoobie.scala @@ -1,6 +1,6 @@ package pl.iterators.kebs.doobie -import doobie.Meta +import org.typelevel.doobie.Meta import pl.iterators.kebs.core.instances.InstanceConverter import pl.iterators.kebs.core.macros.ValueClassLike diff --git a/doobie/src/main/scala/pl/iterators/kebs/doobie/enums/KebsDoobieEnums.scala b/doobie/src/main/scala/pl/iterators/kebs/doobie/enums/KebsDoobieEnums.scala index 3c56bb5d..af5eeef3 100644 --- a/doobie/src/main/scala/pl/iterators/kebs/doobie/enums/KebsDoobieEnums.scala +++ b/doobie/src/main/scala/pl/iterators/kebs/doobie/enums/KebsDoobieEnums.scala @@ -1,6 +1,6 @@ package pl.iterators.kebs.doobie.enums -import doobie.Meta +import org.typelevel.doobie.Meta import pl.iterators.kebs.core.enums.{EnumLike, ValueEnumLike, ValueEnumLikeEntry} import scala.reflect.ClassTag diff --git a/doobie/src/test/scala/pl/iterators/kebs/doobie/ComplexTypesTests.scala b/doobie/src/test/scala/pl/iterators/kebs/doobie/ComplexTypesTests.scala index 34452e4a..be7c2b5c 100644 --- a/doobie/src/test/scala/pl/iterators/kebs/doobie/ComplexTypesTests.scala +++ b/doobie/src/test/scala/pl/iterators/kebs/doobie/ComplexTypesTests.scala @@ -2,10 +2,10 @@ package pl.iterators.kebs.doobie import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers -import doobie._ -import doobie.implicits._ -import doobie.postgres._ -import doobie.postgres.implicits._ +import org.typelevel.doobie._ +import org.typelevel.doobie.implicits._ +import org.typelevel.doobie.postgres._ +import org.typelevel.doobie.postgres.implicits._ import pl.iterators.kebs.core.macros.CaseClass1ToValueClass import pl.iterators.kebs.doobie.enums._ import pl.iterators.kebs.doobie._ From f64e83aaabcfc66766e2be1991ddc691f5f506fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Sowa?= Date: Sat, 21 Nov 2026 10:21:13 +0000 Subject: [PATCH 03/10] kebs 3: drop kebs-akka-http (use kebs-pekko-http) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFD5QTj91bQhcjiNo9n48K --- .github/workflows/ci.yml | 4 +- README.md | 1 - .../matchers/KebsAkkaHttpMatchers.scala | 21 -- .../kebs/akkahttp/matchers/package.scala | 3 - .../KebsAkkaHttpUnmarshallers.scala | 79 ------ .../kebs/akkahttp/unmarshallers/package.scala | 3 - .../akkahttp/domain/AkkaHttpTagsDomain.scala | 84 ------ .../matchers/AkkaHttpMatchersTests.scala | 131 ---------- .../AkkaHttpUnmarshallersTests.scala | 240 ------------------ build.sbt | 37 --- docs/core-concepts.md | 2 +- docs/http4s.md | 2 +- docs/{akka-http.md => pekko-http.md} | 19 +- 13 files changed, 7 insertions(+), 619 deletions(-) delete mode 100644 akka-http/src/main/scala/pl/iterators/kebs/akkahttp/matchers/KebsAkkaHttpMatchers.scala delete mode 100644 akka-http/src/main/scala/pl/iterators/kebs/akkahttp/matchers/package.scala delete mode 100644 akka-http/src/main/scala/pl/iterators/kebs/akkahttp/unmarshallers/KebsAkkaHttpUnmarshallers.scala delete mode 100644 akka-http/src/main/scala/pl/iterators/kebs/akkahttp/unmarshallers/package.scala delete mode 100644 akka-http/src/test/scala/pl/iterators/kebs/akkahttp/domain/AkkaHttpTagsDomain.scala delete mode 100644 akka-http/src/test/scala/pl/iterators/kebs/akkahttp/matchers/AkkaHttpMatchersTests.scala delete mode 100644 akka-http/src/test/scala/pl/iterators/kebs/akkahttp/unmarshallers/AkkaHttpUnmarshallersTests.scala rename docs/{akka-http.md => pekko-http.md} (83%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index abbc8e57..4b20e09d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -83,11 +83,11 @@ jobs: - name: Make target directories if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/master') - run: mkdir -p tagged-meta/native/target enumeratum/.js/target play-json/.jvm/target opaque/.native/target scalacheck/target enum/.js/target http4s-stir/js/target baklava/target opaque/.js/target core/.native/target tagged/native/target circe/.jvm/target play-json/.js/target tagged/jvm/target instances/.jvm/target tagged-meta/jvm/target pekko-http/target core/.js/target pureconfig/target enumeratum/.jvm/target enumeratum/.native/target instances/.native/target http4s-stir/native/target jsonschema/target doobie/target circe/.js/target opaque/.jvm/target instances/.js/target http4s/native/target enum/.native/target spray-json/target core/.jvm/target enum/.jvm/target http4s/js/target slick/target http4s/jvm/target http4s-stir/jvm/target circe/.native/target tagged/js/target akka-http/target tagged-meta/js/target project/target + run: mkdir -p tagged-meta/native/target enumeratum/.js/target play-json/.jvm/target opaque/.native/target scalacheck/target enum/.js/target http4s-stir/js/target baklava/target opaque/.js/target core/.native/target tagged/native/target circe/.jvm/target play-json/.js/target tagged/jvm/target instances/.jvm/target tagged-meta/jvm/target pekko-http/target core/.js/target pureconfig/target enumeratum/.jvm/target enumeratum/.native/target instances/.native/target http4s-stir/native/target jsonschema/target doobie/target circe/.js/target opaque/.jvm/target instances/.js/target http4s/native/target enum/.native/target spray-json/target core/.jvm/target enum/.jvm/target http4s/js/target slick/target http4s/jvm/target http4s-stir/jvm/target circe/.native/target tagged/js/target tagged-meta/js/target project/target - name: Compress target directories if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/master') - run: tar cf targets.tar tagged-meta/native/target enumeratum/.js/target play-json/.jvm/target opaque/.native/target scalacheck/target enum/.js/target http4s-stir/js/target baklava/target opaque/.js/target core/.native/target tagged/native/target circe/.jvm/target play-json/.js/target tagged/jvm/target instances/.jvm/target tagged-meta/jvm/target pekko-http/target core/.js/target pureconfig/target enumeratum/.jvm/target enumeratum/.native/target instances/.native/target http4s-stir/native/target jsonschema/target doobie/target circe/.js/target opaque/.jvm/target instances/.js/target http4s/native/target enum/.native/target spray-json/target core/.jvm/target enum/.jvm/target http4s/js/target slick/target http4s/jvm/target http4s-stir/jvm/target circe/.native/target tagged/js/target akka-http/target tagged-meta/js/target project/target + run: tar cf targets.tar tagged-meta/native/target enumeratum/.js/target play-json/.jvm/target opaque/.native/target scalacheck/target enum/.js/target http4s-stir/js/target baklava/target opaque/.js/target core/.native/target tagged/native/target circe/.jvm/target play-json/.js/target tagged/jvm/target instances/.jvm/target tagged-meta/jvm/target pekko-http/target core/.js/target pureconfig/target enumeratum/.jvm/target enumeratum/.native/target instances/.native/target http4s-stir/native/target jsonschema/target doobie/target circe/.js/target opaque/.jvm/target instances/.js/target http4s/native/target enum/.native/target spray-json/target core/.jvm/target enum/.jvm/target http4s/js/target slick/target http4s/jvm/target http4s-stir/jvm/target circe/.native/target tagged/js/target tagged-meta/js/target project/target - name: Upload target directories if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/master') diff --git a/README.md b/README.md index 295b07c9..2b4e6711 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,6 @@ libraryDependencies ++= Seq( | `kebs-spray-json` | Spray `JsonFormat` derivation (flat, snakified, >22 fields) | | `kebs-play-json` | Play JSON `Format` instances | | `kebs-circe` | Circe `Encoder` / `Decoder` derivation (snakified/capitalized) | -| `kebs-akka-http` | Akka HTTP unmarshallers + path matchers (Scala 2 only) | | `kebs-pekko-http` | Pekko HTTP unmarshallers + path matchers | | `kebs-http4s` | http4s path/query parameter codecs | | `kebs-http4s-stir` | http4s-stir directives + path matchers | diff --git a/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/matchers/KebsAkkaHttpMatchers.scala b/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/matchers/KebsAkkaHttpMatchers.scala deleted file mode 100644 index 86b47c6b..00000000 --- a/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/matchers/KebsAkkaHttpMatchers.scala +++ /dev/null @@ -1,21 +0,0 @@ -package pl.iterators.kebs.akkahttp.matchers - -import akka.http.scaladsl.server.PathMatcher1 -import pl.iterators.kebs.core.enums.{EnumLike, ValueEnumLike, ValueEnumLikeEntry} -import pl.iterators.kebs.core.instances.InstanceConverter -import pl.iterators.kebs.core.macros.ValueClassLike - -trait KebsAkkaHttpMatchers extends akka.http.scaladsl.server.PathMatchers { - implicit class SegmentIsomorphism[U](segment: PathMatcher1[U]) { - def as[T](implicit rep: ValueClassLike[T, U]): PathMatcher1[T] = segment.map(rep.apply) - def asValueEnum[T <: ValueEnumLikeEntry[U]](implicit e: ValueEnumLike[U, T]): PathMatcher1[T] = segment.map(e.withValue) - } - - implicit class SegmentConversion[Source](segment: PathMatcher1[Source]) { - def to[Type](implicit ico: InstanceConverter[Type, Source]): PathMatcher1[Type] = segment.map(ico.decode) - } - - implicit class SegmentEnumIsomorphism[U](segment: PathMatcher1[String]) { - def asEnum[T](implicit e: EnumLike[T]): PathMatcher1[T] = segment.map(e.withNameIgnoreCase) - } -} diff --git a/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/matchers/package.scala b/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/matchers/package.scala deleted file mode 100644 index 17977487..00000000 --- a/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/matchers/package.scala +++ /dev/null @@ -1,3 +0,0 @@ -package pl.iterators.kebs.akkahttp - -package object matchers extends KebsAkkaHttpMatchers diff --git a/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/unmarshallers/KebsAkkaHttpUnmarshallers.scala b/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/unmarshallers/KebsAkkaHttpUnmarshallers.scala deleted file mode 100644 index b12659ed..00000000 --- a/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/unmarshallers/KebsAkkaHttpUnmarshallers.scala +++ /dev/null @@ -1,79 +0,0 @@ -package pl.iterators.kebs.akkahttp.unmarshallers - -import akka.http.scaladsl.unmarshalling.{FromStringUnmarshaller, Unmarshaller} -import pl.iterators.kebs.core.instances.InstanceConverter -import pl.iterators.kebs.core.macros.ValueClassLike -import akka.http.scaladsl.util.FastFuture -import akka.http.scaladsl.unmarshalling.PredefinedFromStringUnmarshallers._ -import pl.iterators.kebs.core.enums.{EnumLike, ValueEnumLike, ValueEnumLikeEntry} - -trait KebsAkkaHttpEnumUnmarshallers { - private final def enumUnmarshaller[E](`enum`: EnumLike[E]): FromStringUnmarshaller[E] = Unmarshaller { _ => name => - `enum`.withNameInsensitiveOption(name) match { - case Some(enumEntry) => FastFuture.successful(enumEntry) - case None => - FastFuture.failed( - new IllegalArgumentException(s"""Invalid value '$name'. Expected one of: ${`enum`.getNamesToValuesMap.keysIterator - .mkString(", ")}""") - ) - } - } - - implicit def kebsEnumUnmarshaller[E](implicit ev: EnumLike[E]): FromStringUnmarshaller[E] = - enumUnmarshaller(ev) -} - -trait KebsAkkaHttpValueEnumUnmarshallers { - final def valueEnumUnmarshaller[V, E <: ValueEnumLikeEntry[V]](`enum`: ValueEnumLike[V, E]): Unmarshaller[V, E] = Unmarshaller { - _ => v => - `enum`.withValueOption(v) match { - case Some(enumEntry) => FastFuture.successful(enumEntry) - case None => - FastFuture.failed( - new IllegalArgumentException(s"""Invalid value '$v'. Expected one of: ${`enum`.getValuesToEntriesMap.keysIterator - .mkString(", ")}""") - ) - } - } - - implicit def kebsValueEnumUnmarshaller[V, E <: ValueEnumLikeEntry[V]](implicit ev: ValueEnumLike[V, E]): Unmarshaller[V, E] = - valueEnumUnmarshaller(ev) - - implicit def kebsIntValueEnumFromStringUnmarshaller[E <: ValueEnumLikeEntry[Int]](implicit - ev: ValueEnumLike[Int, E] - ): FromStringUnmarshaller[E] = - intFromStringUnmarshaller andThen valueEnumUnmarshaller(ev) - implicit def kebsLongValueEnumFromStringUnmarshaller[E <: ValueEnumLikeEntry[Long]](implicit - ev: ValueEnumLike[Long, E] - ): FromStringUnmarshaller[E] = - longFromStringUnmarshaller andThen valueEnumUnmarshaller(ev) - implicit def kebsShortValueEnumFromStringUnmarshaller[E <: ValueEnumLikeEntry[Short]](implicit - ev: ValueEnumLike[Short, E] - ): FromStringUnmarshaller[E] = - shortFromStringUnmarshaller andThen valueEnumUnmarshaller(ev) - implicit def kebsByteValueEnumFromStringUnmarshaller[E <: ValueEnumLikeEntry[Byte]](implicit - ev: ValueEnumLike[Byte, E] - ): FromStringUnmarshaller[E] = - byteFromStringUnmarshaller andThen valueEnumUnmarshaller(ev) -} - -trait KebsAkkaHttpUnmarshallers extends KebsAkkaHttpEnumUnmarshallers with KebsAkkaHttpValueEnumUnmarshallers { - implicit def kebsUnmarshaller[A, B](implicit rep: ValueClassLike[B, A]): Unmarshaller[A, B] = - Unmarshaller.strict[A, B](rep.apply) - @inline - implicit def kebsFromStringUnmarshaller[A, B](implicit - rep: ValueClassLike[B, A], - fsu: FromStringUnmarshaller[A] - ): FromStringUnmarshaller[B] = - fsu andThen kebsUnmarshaller(rep) - - implicit def kebsInstancesUnmarshaller[A, B](implicit ico: InstanceConverter[B, A]): Unmarshaller[A, B] = - Unmarshaller.strict[A, B](ico.decode) - @inline - implicit def kebsInstancesFromStringUnmarshaller[A, B](implicit - ico: InstanceConverter[B, A], - fsu: FromStringUnmarshaller[A] - ): FromStringUnmarshaller[B] = - fsu andThen kebsInstancesUnmarshaller(ico) - -} diff --git a/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/unmarshallers/package.scala b/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/unmarshallers/package.scala deleted file mode 100644 index 799b2146..00000000 --- a/akka-http/src/main/scala/pl/iterators/kebs/akkahttp/unmarshallers/package.scala +++ /dev/null @@ -1,3 +0,0 @@ -package pl.iterators.kebs.akkahttp - -package object unmarshallers extends KebsAkkaHttpUnmarshallers diff --git a/akka-http/src/test/scala/pl/iterators/kebs/akkahttp/domain/AkkaHttpTagsDomain.scala b/akka-http/src/test/scala/pl/iterators/kebs/akkahttp/domain/AkkaHttpTagsDomain.scala deleted file mode 100644 index f6c34f3b..00000000 --- a/akka-http/src/test/scala/pl/iterators/kebs/akkahttp/domain/AkkaHttpTagsDomain.scala +++ /dev/null @@ -1,84 +0,0 @@ -package pl.iterators.kebs.akkahttp.domain - -import enumeratum.values.{IntEnum, IntEnumEntry, StringEnum, StringEnumEntry} -import enumeratum.{Enum, EnumEntry} -import pl.iterators.kebs.tag.meta.tagged -import pl.iterators.kebs.tagged._ -import pl.iterators.kebs.core.enums.ValueEnumLikeEntry - -import java.net.URI -import java.util.UUID - -@tagged trait Tags { - trait IdTag - type Id = Long @@ IdTag - - trait TestIdTag - type TestId = UUIDId @@ TestIdTag - - trait TestDoubleTag - type TestDouble = Double @@ TestDoubleTag - - type UUIDId = UUID - object UUIDId { - def generate[T]: UUIDId @@ T = UUID.randomUUID().taggedWith[T] - def fromString[T](str: String): UUIDId @@ T = - UUID.fromString(str).taggedWith[T] - } - - trait TestTaggedUriTag - type TestTaggedUri = URI @@ TestTaggedUriTag - -} - -object Domain extends Tags { - case class I(i: Int) - case class S(s: String) - case class P[A](a: A) - case class CantUnmarshall(s: String, i: Int) - case object O - - sealed trait Greeting extends EnumEntry - object Greeting extends Enum[Greeting] { - case object Hello extends Greeting - case object GoodBye extends Greeting - case object Hi extends Greeting - case object Bye extends Greeting - - val values = findValues - } - - sealed abstract class LibraryItem(val value: Int) extends IntEnumEntry with ValueEnumLikeEntry[Int] - - object LibraryItem extends IntEnum[LibraryItem] { - case object Book extends LibraryItem(1) - case object Movie extends LibraryItem(2) - case object Magazine extends LibraryItem(3) - case object CD extends LibraryItem(4) - - val values = findValues - } - - case class Red(value: Int) - case class Green(value: Int) - case class Blue(value: Int) - case class Color(red: Red, green: Green, blue: Blue) - - sealed abstract class ShirtSize(val value: String) extends StringEnumEntry with ValueEnumLikeEntry[String] - object ShirtSize extends StringEnum[ShirtSize] { - case object Small extends ShirtSize("S") - case object Medium extends ShirtSize("M") - case object Large extends ShirtSize("L") - - val values = findValues - } - - sealed trait SortOrder extends EnumEntry - object SortOrder extends Enum[SortOrder] { - case object Asc extends SortOrder - case object Desc extends SortOrder - - override val values = findValues - } - -} diff --git a/akka-http/src/test/scala/pl/iterators/kebs/akkahttp/matchers/AkkaHttpMatchersTests.scala b/akka-http/src/test/scala/pl/iterators/kebs/akkahttp/matchers/AkkaHttpMatchersTests.scala deleted file mode 100644 index 8ae23585..00000000 --- a/akka-http/src/test/scala/pl/iterators/kebs/akkahttp/matchers/AkkaHttpMatchersTests.scala +++ /dev/null @@ -1,131 +0,0 @@ -package pl.iterators.kebs.akkahttp.matchers - -import akka.http.scaladsl.server.Directives -import akka.http.scaladsl.testkit.ScalatestRouteTest -import org.scalatest.concurrent.ScalaFutures -import org.scalatest.funsuite.AnyFunSuite -import org.scalatest.matchers.should.Matchers -import pl.iterators.kebs.akkahttp.domain.Domain._ -import pl.iterators.kebs.core.macros.CaseClass1ToValueClass -import pl.iterators.kebs.enumeratum.{KebsEnumeratum, KebsValueEnumeratum} -import pl.iterators.kebs.instances.net.URIString -import pl.iterators.kebs.instances.time.{DayOfWeekInt, ZonedDateTimeString} -import pl.iterators.kebs.instances.time.mixins.InstantEpochMilliLong - -import java.net.URI -import java.time.{DayOfWeek, Instant, ZonedDateTime} - -class AkkaHttpMatchersTests - extends AnyFunSuite - with Matchers - with Directives - with ScalatestRouteTest - with ScalaFutures - with ZonedDateTimeString - with DayOfWeekInt - with InstantEpochMilliLong - with KebsEnumeratum - with KebsValueEnumeratum - with CaseClass1ToValueClass - with URIString { - - test("No ValueClassLike implicits derived") { - import pl.iterators.kebs.core.macros.ValueClassLike - - "implicitly[ValueClassLike[DayOfWeek, Int]]" shouldNot typeCheck - "implicitly[ValueClassLike[Int, DayOfWeek]]" shouldNot typeCheck - "implicitly[ValueClassLike[Instant, Long]]" shouldNot typeCheck - "implicitly[ValueClassLike[Long, Instant]]" shouldNot typeCheck - "implicitly[ValueClassLike[URI, String]]" shouldNot typeCheck - "implicitly[ValueClassLike[String, URI]]" shouldNot typeCheck - } - - test("Extract String to ZonedDateTime") { - val testRoute = path("test" / Segment.to[ZonedDateTime]) { zdt => - complete(zdt.toString) - } - Get("/test/2011-12-03T10:15:30+01:00") ~> testRoute ~> check { - responseAs[String] shouldEqual "2011-12-03T10:15:30+01:00" - } - } - - test("Extract Int to DayOfWeek") { - val testRoute = path("test" / IntNumber.to[DayOfWeek]) { dayOfWeek => - complete(dayOfWeek.getValue.toString) - } - Get("/test/1") ~> testRoute ~> check { - responseAs[String] shouldEqual "1" - } - } - - test("Extract Long to Instant ") { - val testRoute = path("test" / LongNumber.to[Instant]) { instant => - complete(instant.toEpochMilli.toString) - } - Get("/test/1621258399") ~> testRoute ~> check { - responseAs[String] shouldEqual "1621258399" - } - } - test("Extract Double as tagged Double") { - val testRoute = path("test" / DoubleNumber.as[TestDouble]) { test => - complete(test.toString) - } - Get("/test/1.23") ~> testRoute ~> check { - responseAs[String] shouldEqual "1.23" - } - } - - test("Extract Long as tagged Long") { - val testRoute = path("test" / LongNumber.as[Id]) { id => - complete(id.toString) - } - Get("/test/123456") ~> testRoute ~> check { - responseAs[String] shouldEqual "123456" - } - } - - test("Extract UUID as tagged UUID") { - val testRoute = path("test" / JavaUUID.as[TestId]) { id => - complete(id.toString) - } - Get("/test/ce7a7cf1-8c00-49a9-a963-9fd119dd0642") ~> testRoute ~> check { - responseAs[String] shouldEqual "ce7a7cf1-8c00-49a9-a963-9fd119dd0642" - } - } - - test("Extract String as Enum") { - val testRoute = path("test" / Segment.asEnum[Greeting]) { greeting => - complete(greeting.toString) - } - Get("/test/hello") ~> testRoute ~> check { - responseAs[String] shouldEqual "Hello" - } - } - - test("Extract String as value class") { - val testRoute = path("test" / Segment.as[S]) { item => - complete(item.toString) - } - Get("/test/check") ~> testRoute ~> check { - responseAs[String] shouldEqual "S(check)" - } - } - - test("Extract Int as ValueEnum") { - val testRoute = path("test" / IntNumber.asValueEnum[LibraryItem]) { item => - complete(item.toString) - } - Get("/test/1") ~> testRoute ~> check { - responseAs[String] shouldEqual "Book" - } - } - - test("Extract String to URI as tagged URI") { - val testRoute = path("test" / Segment.to[URI].as[TestTaggedUri]) { id => - complete(id.toString) - } - Get("/test/ce7a7cf1-8c00-49a9-a963-9fd119dd0642") ~> testRoute ~> check { - responseAs[String] shouldEqual "ce7a7cf1-8c00-49a9-a963-9fd119dd0642" - } - } -} diff --git a/akka-http/src/test/scala/pl/iterators/kebs/akkahttp/unmarshallers/AkkaHttpUnmarshallersTests.scala b/akka-http/src/test/scala/pl/iterators/kebs/akkahttp/unmarshallers/AkkaHttpUnmarshallersTests.scala deleted file mode 100644 index e2797a1d..00000000 --- a/akka-http/src/test/scala/pl/iterators/kebs/akkahttp/unmarshallers/AkkaHttpUnmarshallersTests.scala +++ /dev/null @@ -1,240 +0,0 @@ -package pl.iterators.kebs.akkahttp.unmarshallers - -import akka.http.scaladsl.model.FormData -import akka.http.scaladsl.server.{Directives, MalformedQueryParamRejection} -import akka.http.scaladsl.testkit.ScalatestRouteTest -import akka.http.scaladsl.unmarshalling.Unmarshal -import org.scalatest.concurrent.ScalaFutures -import org.scalatest.funsuite.AnyFunSuite -import org.scalatest.matchers.should.Matchers -import pl.iterators.kebs.akkahttp.domain.Domain.{Blue, Color, Green, Greeting, I, LibraryItem, P, Red, S, ShirtSize, SortOrder} -import pl.iterators.kebs.akkahttp.domain.Domain._ -import pl.iterators.kebs.instances.net.URIString -import pl.iterators.kebs.instances.time.{DayOfWeekInt, YearMonthString} -import pl.iterators.kebs.enumeratum.{KebsEnumeratum, KebsValueEnumeratum} -import pl.iterators.kebs.core.macros.CaseClass1ToValueClass - -import java.time.{DayOfWeek, YearMonth} - -class AkkaHttpUnmarshallersTests - extends AnyFunSuite - with Matchers - with ScalatestRouteTest - with ScalaFutures - with Directives - with KebsAkkaHttpUnmarshallers - with URIString - with YearMonthString - with DayOfWeekInt - with KebsEnumeratum - with KebsValueEnumeratum - with CaseClass1ToValueClass { - - test("No ValueClassLike implicits derived") { - import pl.iterators.kebs.core.macros.ValueClassLike - - "implicitly[ValueClassLike[URI, String]]" shouldNot typeCheck - "implicitly[ValueClassLike[String, URI]]" shouldNot typeCheck - "implicitly[ValueClassLike[YearMonth, String]]" shouldNot typeCheck - "implicitly[ValueClassLike[String, YearMonth]]" shouldNot typeCheck - "implicitly[ValueClassLike[DayOfWeek, Int]]" shouldNot typeCheck - "implicitly[ValueClassLike[Int, DayOfWeek]]" shouldNot typeCheck - } - - test("Unmarshal") { - Unmarshal(42).to[I].futureValue shouldBe I(42) - Unmarshal("42").to[S].futureValue shouldBe S("42") - } - - test("Unmarshal parametrized") { - Unmarshal("42").to[P[String]].futureValue shouldBe P("42") - } - - test("Unmarshal case object") { - """Unmarshal(42).to[O.type]""" shouldNot typeCheck - } - - test("Unmarshal enum") { - Unmarshal("hello").to[Greeting].futureValue shouldBe Greeting.Hello - Unmarshal("blah").to[Greeting].failed.futureValue shouldBe a[IllegalArgumentException] - } - - test("Unmarshal value enum") { - Unmarshal(3).to[LibraryItem].futureValue shouldBe LibraryItem.Magazine - Unmarshal(5).to[LibraryItem].failed.futureValue shouldBe a[IllegalArgumentException] - } - - test("No unmarshaller for case-classes of arity > 1") { - """Unmarshal("42").to[CantUnmarshall]""" shouldNot typeCheck - } - - test("Unmarshalling value enums is type-safe") { - """Unmarshal(1L).to[LibraryItem]""" shouldNot typeCheck - } - - test("Unmarshal from string") { - Unmarshal("42").to[I].futureValue shouldBe I(42) - } - - test("Unmarshalling parameter") { - val testRoute = parameters(Symbol("i").as[I]) { i => - complete(i.toString) - } - Get("/?i=42") ~> testRoute ~> check { - responseAs[String] shouldEqual "I(42)" - } - } - - test("Unmarshalling optional parameter") { - val testRoute = parameters(Symbol("i").as[I].?) { i => - complete(i.toString) - } - Get("/?i=42") ~> testRoute ~> check { - responseAs[String] shouldEqual "Some(I(42))" - } - } - - test("Unmarshalling enum parameter") { - val testRoute = parameters(Symbol("greeting").as[Greeting]) { greeting => - complete(greeting.toString) - } - Get("/?greeting=hi") ~> testRoute ~> check { - responseAs[String] shouldEqual "Hi" - } - Get("/?greeting=blah") ~> testRoute ~> check { - rejection shouldEqual MalformedQueryParamRejection( - "greeting", - "Invalid value 'blah'. Expected one of: Hello, GoodBye, Hi, Bye", - None - ) - } - } - - test("Unmarshalling value enum parameter") { - val testRoute = parameters(Symbol("libraryItem").as[LibraryItem]) { item => - complete(item.toString) - } - Get("/?libraryItem=1") ~> testRoute ~> check { - responseAs[String] shouldEqual "Book" - } - Get("/?libraryItem=10") ~> testRoute ~> check { - rejection shouldEqual MalformedQueryParamRejection("libraryItem", "Invalid value '10'. Expected one of: 1, 2, 3, 4", None) - } - } - - test("Case class extraction") { - val route = - path("color") { - parameters(Symbol("red").as[Red], Symbol("green").as[Green], Symbol("blue").as[Blue]).as(Color) { color => - complete(color.toString) - } - } - Get("/color?red=1&green=2&blue=3") ~> route ~> check { responseAs[String] shouldEqual "Color(Red(1),Green(2),Blue(3))" } - } - - test("Unmarshalling instances parameter") { - val testRoute = path("instances") { - parameters(Symbol("year").as[YearMonth]) { year => - complete(year.toString) - } - } - Get("/instances?year=2021-05") ~> testRoute ~> check { - responseAs[String] shouldEqual "2021-05" - } - } - - test("Unmarshalling string value enum parameter") { - val testRoute = parameters(Symbol("shirtSize").as[ShirtSize]) { shirtSize => - complete(shirtSize.toString) - } - Get("/?shirtSize=M") ~> testRoute ~> check { - responseAs[String] shouldEqual "Medium" - } - Get("/?shirtSize=XL") ~> testRoute ~> check { - rejection shouldEqual MalformedQueryParamRejection("shirtSize", "Invalid value 'XL'. Expected one of: S, M, L", None) - } - } - - test("bug: work with default enum values") { - val route = - path("test_enum") { - parameter(Symbol("sort").as[SortOrder] ? (SortOrder.Desc: SortOrder)) { sort => - complete { - s"Sort was $sort" - } - } - } - - Get("/test_enum?sort=Asc") ~> route ~> check { - responseAs[String] shouldBe "Sort was Asc" - } - Get("/test_enum") ~> route ~> check { - responseAs[String] shouldBe "Sort was Desc" - } - } - - test("Unmarshal form field from String") { - val route = - path("test_form_fields") { - formFields("yearMonth".as[YearMonth]) { yearMonth => - complete(yearMonth.toString) - } - } - - Post("/test_form_fields", FormData("yearMonth" -> "2021-05")) ~> route ~> check { - responseAs[String] shouldEqual "2021-05" - } - } - - test("Unmarshal form fields from Int") { - val route = - path("test_form_fields") { - formFields("dayOfWeek".as[DayOfWeek]) { dayOfWeek => - complete(dayOfWeek.getValue.toString) - } - } - - Post("/test_form_fields", FormData("dayOfWeek" -> "1")) ~> route ~> check { - responseAs[String] shouldEqual "1" - } - } - - test("Unmarshal tagged parameters from Long") { - val route = - path("test_tagged") { - parameter("tagged".as[Id]) { id => - complete(id.toString) - } - } - - Get("/test_tagged?tagged=123456") ~> route ~> check { - responseAs[String] shouldBe "123456" - } - } - - test("Unmarshal tagged parameters from UUID") { - val route = - path("test_tagged") { - parameter("tagged".as[TestId]) { id => - complete(id.toString) - } - } - - Get("/test_tagged?tagged=ce7a7cf1-8c00-49a9-a963-9fd119dd0642") ~> route ~> check { - responseAs[String] shouldBe "ce7a7cf1-8c00-49a9-a963-9fd119dd0642" - } - } - - test("Unmarshal tagged URI") { - val route = - path("test_tagged") { - parameter("tagged".as[TestTaggedUri]) { id => - complete(id.toString) - } - } - - Get("/test_tagged?tagged=www.test.pl") ~> route ~> check { - responseAs[String] shouldBe "www.test.pl" - } - } -} diff --git a/build.sbt b/build.sbt index 70afc74b..65de75ca 100644 --- a/build.sbt +++ b/build.sbt @@ -144,21 +144,6 @@ def enumeratumInExamples = { val optionalEnumeratum = Def.setting("com.beachape" %%% "enumeratum" % enumeratumVersion % "provided") val enumeratumInTest = Def.setting("com.beachape" %%% "enumeratum" % enumeratumVersion % "test") -val akkaVersion = "2.6.20" -val akkaHttpVersion = "10.2.10" -val akkaStream = "com.typesafe.akka" %% "akka-stream" % akkaVersion -val akkaStreamTestkit = "com.typesafe.akka" %% "akka-stream-testkit" % akkaVersion -val akkaHttp = "com.typesafe.akka" %% "akka-http" % akkaHttpVersion -val akkaHttpTestkit = "com.typesafe.akka" %% "akka-http-testkit" % akkaHttpVersion -def akkaHttpInExamples = { - val akkaHttpSprayJson = "com.typesafe.akka" %% "akka-http-spray-json" % akkaHttpVersion - Seq( - akkaStream.cross(CrossVersion.for3Use2_13), - akkaHttp.cross(CrossVersion.for3Use2_13), - akkaHttpSprayJson.cross(CrossVersion.for3Use2_13) - ) -} - val pekkoVersion = "1.7.1" val pekkoHttpVersion = "1.4.2" val pekkoHttpJsonV = "2.0.0" @@ -249,14 +234,6 @@ lazy val circeSettings = commonSettings ++ Seq( else Seq(circeAutoExtras.value)) ) -lazy val akkaHttpSettings = commonSettings ++ Seq( - libraryDependencies += (akkaHttp).cross(CrossVersion.for3Use2_13), - libraryDependencies += (akkaStreamTestkit % "test").cross(CrossVersion.for3Use2_13), - libraryDependencies += (akkaHttpTestkit % "test").cross(CrossVersion.for3Use2_13), - libraryDependencies += optionalEnumeratum.value, - scalacOptions ++= paradiseFlag(scalaVersion.value) -) - lazy val pekkoHttpSettings = commonSettings ++ Seq( libraryDependencies += pekkoHttp, libraryDependencies += pekkoStream, @@ -405,19 +382,6 @@ lazy val circeSupport = crossProject(JSPlatform, NativePlatform, JVMPlatform) moduleName := "kebs-circe" ) -lazy val akkaHttpSupport = project - .in(file("akka-http")) - .dependsOn(core.jvm, enumeratumSupport.jvm, instances.jvm % "test -> test", tagged.jvm % "test -> test", taggedMeta.jvm % "test -> test") - .settings(akkaHttpSettings *) - .settings(publishSettings *) - .settings(disableScala(List("3"))) - .settings( - name := "akka-http", - description := "Automatic generation of akka-http deserializers for 1-element case classes", - moduleName := "kebs-akka-http", - crossScalaVersions := supportedScalaVersions - ) - lazy val pekkoHttpSupport = project .in(file("pekko-http")) .dependsOn( @@ -674,7 +638,6 @@ lazy val kebs = project circeSupport.native, jsonschemaSupport, scalacheckSupport, - akkaHttpSupport, pekkoHttpSupport, http4sSupport.jvm, http4sSupport.js, diff --git a/docs/core-concepts.md b/docs/core-concepts.md index fdbe0f06..0c78ce5e 100644 --- a/docs/core-concepts.md +++ b/docs/core-concepts.md @@ -5,7 +5,7 @@ title: Core Concepts # Core Concepts -Kebs is built on four typeclasses. Each integration module (circe, slick, akka-http, etc.) provides implicit derivation rules that delegate to these. +Kebs is built on four typeclasses. Each integration module (circe, slick, pekko-http, etc.) provides implicit derivation rules that delegate to these. ## ValueClassLike[VC, F1] diff --git a/docs/http4s.md b/docs/http4s.md index 17d04c41..b508164c 100644 --- a/docs/http4s.md +++ b/docs/http4s.md @@ -106,4 +106,4 @@ import pl.iterators.kebs.http4sstir.matchers.KebsHttp4sStirMatchers // or: import pl.iterators.kebs.http4sstir.matchers._ ``` -Same extension methods as [Akka/Pekko HTTP matchers](akka-http.md#path-matchers): `.as[T]`, `.to[T]`, `.asEnum[T]`, `.asValueEnum[T]`, and chaining (`.to[URI].as[TaggedUri]`). +Same extension methods as [Pekko HTTP matchers](pekko-http.md#path-matchers): `.as[T]`, `.to[T]`, `.asEnum[T]`, `.asValueEnum[T]`, and chaining (`.to[URI].as[TaggedUri]`). diff --git a/docs/akka-http.md b/docs/pekko-http.md similarity index 83% rename from docs/akka-http.md rename to docs/pekko-http.md index 5c6b89e1..8ca8b584 100644 --- a/docs/akka-http.md +++ b/docs/pekko-http.md @@ -1,19 +1,15 @@ --- sidebar_position: 12 -title: Akka HTTP / Pekko HTTP +title: Pekko HTTP --- -# kebs-akka-http / kebs-pekko-http +# kebs-pekko-http -Automatic unmarshallers and path matchers for Akka HTTP and Pekko HTTP. +Automatic unmarshallers and path matchers for Pekko HTTP. ## Setup ```scala -// Akka HTTP (Scala 2 only) -libraryDependencies += "pl.iterators" %% "kebs-akka-http" % kebsVersion - -// Pekko HTTP (Scala 2 & 3) libraryDependencies += "pl.iterators" %% "kebs-pekko-http" % kebsVersion ``` @@ -46,12 +42,6 @@ val formRoute = post { } ``` -For Akka HTTP, use `KebsAkkaHttpUnmarshallers` instead: - -```scala -import pl.iterators.kebs.akkahttp.unmarshallers.KebsAkkaHttpUnmarshallers -``` - ## Path matchers A separate `matchers` package provides typed path segment extraction via extension methods on `PathMatcher1`: @@ -59,9 +49,6 @@ A separate `matchers` package provides typed path segment extraction via extensi ```scala import pl.iterators.kebs.pekkohttp.matchers.KebsPekkoHttpMatchers // or: import pl.iterators.kebs.pekkohttp.matchers._ - -// For Akka HTTP: -// import pl.iterators.kebs.akkahttp.matchers.KebsAkkaHttpMatchers ``` ### `.as[T]` — value class wrapping From cf3808d8e4055e105bb41745f93b71ffd7ed9168 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Sowa?= Date: Sat, 21 Nov 2026 10:27:14 +0000 Subject: [PATCH 04/10] kebs 3: ValueClassLike on hearth (companion apply on both Scala versions) One shared hearth implementation for 2.13 and 3.9. Values are built through the companion's apply, so validating/normalising apply methods now apply on Scala 3 too (kebs 2 used Mirror.fromProduct there, which bypassed them). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFD5QTj91bQhcjiNo9n48K --- build.sbt | 14 +++- .../macros/CaseClass1ToValueClassCompat.scala | 16 +++++ .../kebs/core/macros/ValueClassReps.scala | 34 --------- .../macros/CaseClass1ToValueClassCompat.scala | 22 ++++++ .../kebs/core/macros/ValueClassReps.scala | 15 ---- .../kebs/core/macros/ValueClassLike.scala | 6 ++ .../internal/ValueClassLikeMacrosImpl.scala | 71 +++++++++++++++++++ .../kebs/core/ValueClassLikeTests.scala | 56 +++++++++++++++ 8 files changed, 183 insertions(+), 51 deletions(-) create mode 100644 core/src/main/scala-2/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala delete mode 100644 core/src/main/scala-2/pl/iterators/kebs/core/macros/ValueClassReps.scala create mode 100644 core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala delete mode 100644 core/src/main/scala-3/pl/iterators/kebs/core/macros/ValueClassReps.scala create mode 100644 core/src/main/scala/pl/iterators/kebs/core/macros/ValueClassLike.scala create mode 100644 core/src/main/scala/pl/iterators/kebs/core/macros/internal/ValueClassLikeMacrosImpl.scala create mode 100644 core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeTests.scala diff --git a/build.sbt b/build.sbt index 65de75ca..36c1d261 100644 --- a/build.sbt +++ b/build.sbt @@ -30,7 +30,7 @@ lazy val baseSettings = Seq( homepage := Some(url("https://github.com/theiterators/kebs")), scalacOptions ++= Seq("-deprecation", "-unchecked", "-feature", "-encoding", "utf8") ++ (if (scalaVersion.value.startsWith("3")) Seq("-Xmax-inlines", "64", "-Yretain-trees") - else Seq.empty) + else Seq("-Xsource:3", "-Wconf:cat=scala3-migration:s")) ) lazy val commonMacroSettings = baseSettings ++ Seq( @@ -110,6 +110,8 @@ def paradiseFlag(scalaVersion: String): Seq[String] = else Seq("-Ymacro-annotations") +val hearthV = "0.4.5" + val scalaTest = Def.setting("org.scalatest" %%% "scalatest" % "3.2.20") val scalaCheck = Def.setting("org.scalacheck" %%% "scalacheck" % "1.19.0") @@ -198,7 +200,15 @@ lazy val doobieSettings = commonSettings ++ Seq( ) lazy val coreSettings = commonMacroSettings ++ Seq( - libraryDependencies += (scalaCheck.value % "test") + libraryDependencies += "com.kubuszok" %%% "hearth" % hearthV, + libraryDependencies ++= (if (scalaVersion.value.startsWith("3")) + Seq(compilerPlugin("com.kubuszok" % "hearth-cross-quotes_3" % hearthV)) + else Nil), + // hearth's path-dependent Method/Type ADTs trigger this harmless Scala 2 warning in macro code + scalacOptions ++= (if (scalaVersion.value.startsWith("3")) Nil + else Seq("-Wconf:msg=The outer reference in this type test cannot be checked at run time:s")), + libraryDependencies += (scalaCheck.value % "test"), + libraryDependencies += (scalaTest.value % "test") ) lazy val enumSettings = commonMacroSettings ++ Seq( diff --git a/core/src/main/scala-2/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala b/core/src/main/scala-2/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala new file mode 100644 index 00000000..043e5cd9 --- /dev/null +++ b/core/src/main/scala-2/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala @@ -0,0 +1,16 @@ +package pl.iterators.kebs.core.macros + +import pl.iterators.kebs.core.macros.internal.ValueClassLikeMacrosImpl + +import scala.language.experimental.macros +import scala.reflect.macros.whitebox + +private[macros] trait CaseClass1ToValueClassCompat { + implicit def repFromCaseClass[VC <: Product, F1]: ValueClassLike[VC, F1] = macro ValueClassRepMacros.materializeValueClassRep[VC, F1] +} + +// whitebox: the macro's result type fixes F1, which the caller leaves for the compiler to infer +final private[macros] class ValueClassRepMacros(val c: whitebox.Context) extends hearth.MacroCommonsScala2 with ValueClassLikeMacrosImpl { + def materializeValueClassRep[VC <: Product: c.WeakTypeTag, F1: c.WeakTypeTag]: c.Expr[ValueClassLike[VC, F1]] = + c.Expr[ValueClassLike[VC, F1]](deriveValueClassLike[VC].value.tree) +} diff --git a/core/src/main/scala-2/pl/iterators/kebs/core/macros/ValueClassReps.scala b/core/src/main/scala-2/pl/iterators/kebs/core/macros/ValueClassReps.scala deleted file mode 100644 index b6822885..00000000 --- a/core/src/main/scala-2/pl/iterators/kebs/core/macros/ValueClassReps.scala +++ /dev/null @@ -1,34 +0,0 @@ -package pl.iterators.kebs.core.macros - -import scala.language.experimental.macros -import scala.reflect.macros.whitebox - -final class ValueClassLike[VC, F1](val apply: F1 => VC, val unapply: VC => F1) - -trait CaseClass1ToValueClass { - implicit def repFromCaseClass[VC <: Product, F1]: ValueClassLike[VC, F1] = macro ValueClassRepMacros.materializeValueClassRep[VC, F1] -} -object CaseClass1ToValueClass extends CaseClass1ToValueClass - -class ValueClassRepMacros(override val c: whitebox.Context) extends MacroUtils { - import c.universe._ - - def materializeValueClassRep[VC <: Product: c.WeakTypeTag, F1: c.WeakTypeTag]: c.Expr[ValueClassLike[VC, F1]] = { - val ValueClass = weakTypeOf[VC] - assertCaseClass(ValueClass, s"To materialize value class representation, ${ValueClass.typeSymbol} must be a value class") - - ValueClass match { - case Product1(_1) => c.Expr[ValueClassLike[VC, F1]](materializeRep1(ValueClass, _1)) - case _ => c.abort(c.enclosingPosition, "To materialize ValueClassLike, case class must have arity == 1") - } - } - - private def materializeRep1(caseClassType: Type, caseAccessor: MethodSymbol) = { - val f1 = resultType(caseAccessor, caseClassType) - - val unapplyF = q"_.$caseAccessor" - val applyF = apply(caseClassType) - - q"new _root_.pl.iterators.kebs.core.macros.ValueClassLike[$caseClassType, $f1]($applyF, $unapplyF)" - } -} diff --git a/core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala b/core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala new file mode 100644 index 00000000..ff831040 --- /dev/null +++ b/core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala @@ -0,0 +1,22 @@ +package pl.iterators.kebs.core.macros + +import pl.iterators.kebs.core.macros.internal.ValueClassLikeMacrosImpl + +import scala.deriving.Mirror +import scala.quoted.* + +private[macros] trait CaseClass1ToValueClassCompat { + // The Mirror evidence infers F1 and keeps types that are not single-field products from reaching the macro + // (a non-transparent inline given is expanded after it has been selected, so a macro failure would be a hard error). + inline implicit def repFromCaseClass[T <: Product, F1](using + m: Mirror.ProductOf[T], + teq: m.MirroredElemTypes =:= F1 *: EmptyTuple.type + ): ValueClassLike[T, F1] = ${ ValueClassLikeMacros.materialize[T, F1] } +} + +final private[macros] class ValueClassLikeMacros(q: Quotes) extends hearth.MacroCommonsScala3(using q), ValueClassLikeMacrosImpl + +private[macros] object ValueClassLikeMacros { + def materialize[T: Type, F1: Type](using q: Quotes): Expr[ValueClassLike[T, F1]] = + new ValueClassLikeMacros(q).deriveValueClassLike[T].value.asInstanceOf[Expr[ValueClassLike[T, F1]]] +} diff --git a/core/src/main/scala-3/pl/iterators/kebs/core/macros/ValueClassReps.scala b/core/src/main/scala-3/pl/iterators/kebs/core/macros/ValueClassReps.scala deleted file mode 100644 index b9b2e5e7..00000000 --- a/core/src/main/scala-3/pl/iterators/kebs/core/macros/ValueClassReps.scala +++ /dev/null @@ -1,15 +0,0 @@ -package pl.iterators.kebs.core.macros - -import scala.deriving.Mirror - -final class ValueClassLike[VC, F1](val apply: F1 => VC, val unapply: VC => F1) - -trait CaseClass1ToValueClass { - implicit def repFromCaseClass[T <: Product, F1](using - m: Mirror.ProductOf[T], - teq: m.MirroredElemTypes =:= F1 *: EmptyTuple.type - ): ValueClassLike[T, F1] = { - new ValueClassLike[T, F1](f1 => m.fromProduct(Tuple1(f1)), _.productElement(0).asInstanceOf[F1]) - } -} -object CaseClass1ToValueClass extends CaseClass1ToValueClass diff --git a/core/src/main/scala/pl/iterators/kebs/core/macros/ValueClassLike.scala b/core/src/main/scala/pl/iterators/kebs/core/macros/ValueClassLike.scala new file mode 100644 index 00000000..67bd39ee --- /dev/null +++ b/core/src/main/scala/pl/iterators/kebs/core/macros/ValueClassLike.scala @@ -0,0 +1,6 @@ +package pl.iterators.kebs.core.macros + +final class ValueClassLike[VC, F1](val apply: F1 => VC, val unapply: VC => F1) + +trait CaseClass1ToValueClass extends CaseClass1ToValueClassCompat +object CaseClass1ToValueClass extends CaseClass1ToValueClass diff --git a/core/src/main/scala/pl/iterators/kebs/core/macros/internal/ValueClassLikeMacrosImpl.scala b/core/src/main/scala/pl/iterators/kebs/core/macros/internal/ValueClassLikeMacrosImpl.scala new file mode 100644 index 00000000..ee10ca3b --- /dev/null +++ b/core/src/main/scala/pl/iterators/kebs/core/macros/internal/ValueClassLikeMacrosImpl.scala @@ -0,0 +1,71 @@ +package pl.iterators.kebs.core.macros.internal + +import hearth.fp.effect.MIO +import hearth.fp.instances.* +import hearth.fp.syntax.* +import pl.iterators.kebs.core.macros.ValueClassLike + +/** Shared (Scala 2.13 + Scala 3) implementation of `ValueClassLike` derivation for single-field case classes. */ +private[kebs] trait ValueClassLikeMacrosImpl { this: hearth.MacroCommons => + + /** Builds `ValueClassLike[T, F]` where `F` is the type of the only field of case class `T`. + * + * Values are constructed through the companion's `apply` (so validating/normalising `apply`s are honoured); the primary constructor is + * used only when no matching `apply` is callable at the call site. + */ + def deriveValueClassLike[T: Type]: Expr_?? = { + val caseClass: CaseClass[T] = CaseClass.parse[T].toOption match { + case Some(cc) => cc + case None => Environment.reportErrorAndAbort(s"${Type[T].prettyPrint} is not a case class") + } + val field: Parameter = caseClass.primaryConstructor.parameters.flatMap(_.values.toList) match { + case single :: Nil => single + case _ => Environment.reportErrorAndAbort(s"To derive ValueClassLike, ${Type[T].prettyPrint} must have exactly one field") + } + // a nested path (`field.tpe.Underlying`) breaks cross-quotes on Scala 2.13 - bind it first + val fieldType: ?? = field.tpe + import fieldType.Underlying as F + implicit val ValueClassLikeType: Type[ValueClassLike[T, F]] = Type.of[ValueClassLike[T, F]] + + def construct(arg: Expr[F]): Expr[T] = + viaCompanionApply[T, F](arg).getOrElse { + caseClass.construct[MIO](_ => MIO.pure(arg.as_??)).unsafe.runSync._2 match { + case Right(Some(constructed)) => constructed + case _ => Environment.reportErrorAndAbort(s"${Type[T].prettyPrint} has no accessible apply or constructor") + } + } + + def access(value: Expr[T]): Expr[F] = { + val fieldValue = caseClass.caseFieldValuesAt(value).head._2 + import fieldValue.{Underlying as G, value as extracted} + extracted.asInstanceOf[Expr[F]] + } + + Expr.quote { + new ValueClassLike[T, F]( + (f: F) => Expr.splice(construct(Expr.quote(f))), + (t: T) => Expr.splice(access(Expr.quote(t))) + ) + }.as_?? + } + + /** Calls `T.apply(arg)` if the companion has an `apply` taking exactly one argument of type `F`. */ + private def viaCompanionApply[T: Type, F: Type](arg: Expr[F]): Option[Expr[T]] = { + def walk(method: Method): Option[Expr[T]] = method match { + case _: Method.OnInstance => None + case types: Method.ApplyTypes => + val typeParams = types.typeParams.flatten + val typeArgs = Type.typeArguments[T] + if (typeParams.size == typeArgs.size) walk(types.apply(typeParams.zip(typeArgs).toMap)) else None + case values: Method.ApplyValues => + values.parameters.flatMap(_.toList) match { + case (name, param) :: Nil if param.tpe.Underlying =:= Type[F] => walk(values.apply(Map(name -> arg.as_??))) + case _ => None + } + case result: Method.Result[?] => + import result.Returned + if (Returned <:< Type[T]) result.build().toOption.map(_.asInstanceOf[Expr[T]]) else None + } + Type[T].unsortedMethodsNamed("apply").iterator.filter(_.isAvailable(AtCallSite)).map(walk).collectFirst { case Some(e) => e } + } +} diff --git a/core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeTests.scala b/core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeTests.scala new file mode 100644 index 00000000..42dacdf2 --- /dev/null +++ b/core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeTests.scala @@ -0,0 +1,56 @@ +package pl.iterators.kebs.core + +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import pl.iterators.kebs.core.macros.{CaseClass1ToValueClass, ValueClassLike} + +object ValueClassLikeTestDomain { + final case class Plain(value: String) + final case class Box[A](a: A) + final case class Positive(value: Int) + object Positive { + def apply(value: Int): Positive = { + require(value > 0, "must be positive") + new Positive(value) + } + } + final case class Email(value: String) + object Email { + def apply(value: String): Email = new Email(value.toLowerCase) + } + final case class Two(a: Int, b: Int) + final class NotCase(val value: Int) +} + +class ValueClassLikeTests extends AnyFunSuite with Matchers with CaseClass1ToValueClass { + import ValueClassLikeTestDomain._ + + test("derives apply/unapply for a single-field case class") { + val rep = implicitly[ValueClassLike[Plain, String]] + rep.apply("a") shouldBe Plain("a") + rep.unapply(Plain("b")) shouldBe "b" + } + + test("infers the field type through an outer implicit") { + def find[T, A](implicit rep: ValueClassLike[T, A]): ValueClassLike[T, A] = rep + find[Plain, String].unapply(Plain("c")) shouldBe "c" + } + + test("generic case class") { + implicitly[ValueClassLike[Box[Int], Int]].apply(1) shouldBe Box(1) + } + + test("uses the companion apply (validation)") { + val rep = implicitly[ValueClassLike[Positive, Int]] + an[IllegalArgumentException] should be thrownBy rep.apply(-1) + } + + test("uses the companion apply (normalisation)") { + implicitly[ValueClassLike[Email, String]].apply("A@B.PL").value shouldBe "a@b.pl" + } + + test("no instance for a 2-field case class or a non-case class") { + assertDoesNotCompile("implicitly[ValueClassLike[Two, Int]]") + assertDoesNotCompile("implicitly[ValueClassLike[NotCase, Int]]") + } +} From 66fea71eca0bada9b3a5e57be405c12f9bc45c93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Sowa?= Date: Sat, 21 Nov 2026 10:31:59 +0000 Subject: [PATCH 05/10] kebs 3: kebs-testkit module and circe golden tests (2.x wire format) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFD5QTj91bQhcjiNo9n48K --- build.sbt | 20 +++- .../circe/golden/CirceAdtGoldenTests.scala | 27 +++++ .../kebs/circe/golden/CirceGoldenTests.scala | 103 ++++++++++++++++++ .../pl/iterators/kebs/testkit/model.scala | 66 +++++++++++ 4 files changed, 215 insertions(+), 1 deletion(-) create mode 100644 circe/src/test/scala-2/pl/iterators/kebs/circe/golden/CirceAdtGoldenTests.scala create mode 100644 circe/src/test/scala/pl/iterators/kebs/circe/golden/CirceGoldenTests.scala create mode 100644 testkit/src/main/scala/pl/iterators/kebs/testkit/model.scala diff --git a/build.sbt b/build.sbt index 36c1d261..b506ef89 100644 --- a/build.sbt +++ b/build.sbt @@ -382,7 +382,7 @@ lazy val circeSupport = crossProject(JSPlatform, NativePlatform, JVMPlatform) .withoutSuffixFor(JVMPlatform) .crossType(CrossType.Pure) .in(file("circe")) - .dependsOn(core, enumSupport, enumeratumSupport % "test -> test", instances % "test -> test") + .dependsOn(core, enumSupport, enumeratumSupport % "test -> test", instances % "test -> test", testkit % "test -> compile") .settings(circeSettings *) .settings(crossBuildSettings *) .settings(publishSettings *) @@ -625,6 +625,21 @@ lazy val docs = project ) ) +lazy val testkit = crossProject(JSPlatform, NativePlatform, JVMPlatform) + .withoutSuffixFor(JVMPlatform) + .crossType(CrossType.Pure) + .in(file("testkit")) + .dependsOn(core) + .settings(commonSettings *) + .settings(noPublishSettings *) + .settings( + name := "testkit", + description := "Shared test models and contract suites (not published)", + moduleName := "kebs-testkit", + crossScalaVersions := supportedScalaVersions, + libraryDependencies += enumeratum.value + ) + lazy val kebs = project .in(file(".")) .aggregate( @@ -637,6 +652,9 @@ lazy val kebs = project core.jvm, core.js, core.native, + testkit.jvm, + testkit.js, + testkit.native, baklavaSupport, slickSupport, doobieSupport, diff --git a/circe/src/test/scala-2/pl/iterators/kebs/circe/golden/CirceAdtGoldenTests.scala b/circe/src/test/scala-2/pl/iterators/kebs/circe/golden/CirceAdtGoldenTests.scala new file mode 100644 index 00000000..904cd6f9 --- /dev/null +++ b/circe/src/test/scala-2/pl/iterators/kebs/circe/golden/CirceAdtGoldenTests.scala @@ -0,0 +1,27 @@ +package pl.iterators.kebs.circe.golden + +import io.circe.{Decoder, Encoder, Json} +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import pl.iterators.kebs.circe.KebsCirce +import pl.iterators.kebs.testkit.model._ + +/** Scala 2 only: kebs 2 on Scala 3 does not derive sealed traits. The kebs 3 circe plan moves this to shared tests. */ +class CirceAdtGoldenTests extends AnyFunSuite with Matchers { + private def json(s: String): Json = io.circe.parser.parse(s).fold(throw _, identity) + + object Default extends KebsCirce + import Default._ + + test("sealed trait - case class child (wrapper object)") { + val value: Shape = Circle(1.0, "c") + implicitly[Encoder[Shape]].apply(value) shouldBe json("""{"Circle":{"r":1.0,"label":"c"}}""") + implicitly[Decoder[Shape]].decodeJson(json("""{"Circle":{"r":1.0,"label":"c"}}""")) shouldBe Right(value) + } + + test("sealed trait - case object child (wrapper object)") { + val value: Shape = Empty + implicitly[Encoder[Shape]].apply(value) shouldBe json("""{"Empty":{}}""") + implicitly[Decoder[Shape]].decodeJson(json("""{"Empty":{}}""")) shouldBe Right(value) + } +} diff --git a/circe/src/test/scala/pl/iterators/kebs/circe/golden/CirceGoldenTests.scala b/circe/src/test/scala/pl/iterators/kebs/circe/golden/CirceGoldenTests.scala new file mode 100644 index 00000000..f628d8f9 --- /dev/null +++ b/circe/src/test/scala/pl/iterators/kebs/circe/golden/CirceGoldenTests.scala @@ -0,0 +1,103 @@ +package pl.iterators.kebs.circe.golden + +import io.circe.{Decoder, Encoder, Json} +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import pl.iterators.kebs.circe.KebsCirce +import pl.iterators.kebs.circe.enums.{KebsCirceEnums, KebsCirceEnumsLowercase, KebsCirceEnumsUppercase, KebsCirceValueEnums} +import pl.iterators.kebs.core.macros.CaseClass1ToValueClass +import pl.iterators.kebs.enumeratum.{KebsEnumeratum, KebsValueEnumeratum} +import pl.iterators.kebs.instances.TimeInstances +import pl.iterators.kebs.testkit.model._ + +import java.time.Instant + +/** Wire format of kebs 2.x (captured before the kebs 3 rewrite). kebs 3 must produce the same JSON with default configuration; a + * deliberate change belongs in the migration guide, not in a silently edited expectation. + */ +class CirceGoldenTests extends AnyFunSuite with Matchers { + private def json(s: String): Json = io.circe.parser.parse(s).fold(throw _, identity) + + private def golden[A](value: A, expected: String)(implicit encoder: Encoder[A], decoder: Decoder[A]): Unit = { + encoder(value) shouldBe json(expected) + decoder.decodeJson(json(expected)) shouldBe Right(value) + } + + object Default extends KebsCirce + object Flat extends KebsCirce with CaseClass1ToValueClass + object FlatTime extends KebsCirce with CaseClass1ToValueClass with TimeInstances + object FlatEnums + extends KebsCirce + with CaseClass1ToValueClass + with KebsEnumeratum + with KebsValueEnumeratum + with KebsCirceEnums + with KebsCirceValueEnums + object FlatEnumsUppercase + extends KebsCirce + with CaseClass1ToValueClass + with KebsEnumeratum + with KebsValueEnumeratum + with KebsCirceEnumsUppercase + with KebsCirceValueEnums + object FlatEnumsLowercase + extends KebsCirce + with CaseClass1ToValueClass + with KebsEnumeratum + with KebsValueEnumeratum + with KebsCirceEnumsLowercase + with KebsCirceValueEnums + + test("person default") { + import Default._ + golden(Person(Id("x"), "Ann", 30, None), """{"id":{"value":"x"},"name":"Ann","age":30,"nickname":null}""") + } + + test("person flat") { + import Flat._ + golden(Person(Id("x"), "Ann", 30, Some("A")), """{"id":"x","name":"Ann","age":30,"nickname":"A"}""") + } + + test("naming snakified") { + import pl.iterators.kebs.circe.snakified._ + golden(Naming(1, "a", 2, "u"), """{"some_field":1,"another_field_name":"a","field1_name":2,"http_url":"u"}""") + } + + test("naming capitalized") { + import pl.iterators.kebs.circe.capitalized._ + golden(Naming(1, "a", 2, "u"), """{"SomeField":1,"AnotherFieldName":"a","Field1Name":2,"HttpURL":"u"}""") + } + + test("enums") { + import FlatEnums._ + golden(Paint(Color.DarkBlue, Level.High), """{"color":"DarkBlue","level":2}""") + } + + test("enums are decoded case-insensitively by default") { + import FlatEnums._ + implicitly[Decoder[Paint]].decodeJson(json("""{"color":"darkblue","level":2}""")) shouldBe Right(Paint(Color.DarkBlue, Level.High)) + } + + test("enums uppercase") { + import FlatEnumsUppercase._ + golden(Paint(Color.DarkBlue, Level.High), """{"color":"DARKBLUE","level":2}""") + } + + test("enums lowercase") { + import FlatEnumsLowercase._ + golden(Paint(Color.DarkBlue, Level.High), """{"color":"darkblue","level":2}""") + } + + test("instance converter") { + import FlatTime._ + golden(Event(Id("e"), Instant.parse("2026-01-02T03:04:05Z")), """{"id":"e","at":"2026-01-02T03:04:05Z"}""") + } + + test("wide (>22 fields)") { + import Default._ + golden( + Wide.sample, + """{"f1":1,"f2":2,"f3":3,"f4":4,"f5":5,"f6":6,"f7":7,"f8":8,"f9":9,"f10":10,"f11":11,"f12":12,"f13":13,"f14":14,"f15":15,"f16":16,"f17":17,"f18":18,"f19":19,"f20":20,"f21":21,"f22":22,"f23":null}""" + ) + } +} diff --git a/testkit/src/main/scala/pl/iterators/kebs/testkit/model.scala b/testkit/src/main/scala/pl/iterators/kebs/testkit/model.scala new file mode 100644 index 00000000..ed357c56 --- /dev/null +++ b/testkit/src/main/scala/pl/iterators/kebs/testkit/model.scala @@ -0,0 +1,66 @@ +package pl.iterators.kebs.testkit + +import enumeratum.values.{IntEnum, IntEnumEntry} +import enumeratum.{Enum, EnumEntry} +import pl.iterators.kebs.core.enums.ValueEnumLikeEntry + +import java.time.Instant + +/** Models shared by the golden and contract test suites of all kebs modules (compiled in a separate module on purpose: derivation must + * also work for types read from the classpath). + */ +object model { + final case class Id(value: String) + final case class Person(id: Id, name: String, age: Int, nickname: Option[String]) + final case class Naming(someField: Int, anotherFieldName: String, field1Name: Int, httpURL: String) + final case class Event(id: Id, at: Instant) + + final case class Wide( + f1: Int, + f2: Int, + f3: Int, + f4: Int, + f5: Int, + f6: Int, + f7: Int, + f8: Int, + f9: Int, + f10: Int, + f11: Int, + f12: Int, + f13: Int, + f14: Int, + f15: Int, + f16: Int, + f17: Int, + f18: Int, + f19: Int, + f20: Int, + f21: Int, + f22: Int, + f23: Option[String] + ) + object Wide { + val sample: Wide = Wide(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, None) + } + + sealed abstract class Color extends EnumEntry + object Color extends Enum[Color] { + case object Red extends Color + case object DarkBlue extends Color + val values = findValues + } + + sealed abstract class Level(val value: Int) extends IntEnumEntry with ValueEnumLikeEntry[Int] + object Level extends IntEnum[Level] { + case object Low extends Level(1) + case object High extends Level(2) + val values = findValues + } + + final case class Paint(color: Color, level: Level) + + sealed trait Shape + final case class Circle(r: Double, label: String) extends Shape + case object Empty extends Shape +} From 2eb36ce540a58e85777f484be9de9c9694046bce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Sowa?= Date: Sat, 21 Nov 2026 10:34:04 +0000 Subject: [PATCH 06/10] kebs 3: spray-json golden tests (2.x wire format) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFD5QTj91bQhcjiNo9n48K --- build.sbt | 2 +- .../sprayjson/golden/SprayGoldenTests.scala | 113 ++++++++++++++++++ 2 files changed, 114 insertions(+), 1 deletion(-) create mode 100644 spray-json/src/test/scala/pl/iterators/kebs/sprayjson/golden/SprayGoldenTests.scala diff --git a/build.sbt b/build.sbt index b506ef89..a0e3bc96 100644 --- a/build.sbt +++ b/build.sbt @@ -354,7 +354,7 @@ lazy val doobieSupport = project lazy val sprayJsonSupport = project .in(file("spray-json")) - .dependsOn(enumeratumSupport.jvm, instances.jvm % "test -> test") + .dependsOn(enumeratumSupport.jvm, instances.jvm % "test -> test", testkit.jvm % "test -> compile") .settings(sprayJsonSettings *) .settings(publishSettings *) .settings( diff --git a/spray-json/src/test/scala/pl/iterators/kebs/sprayjson/golden/SprayGoldenTests.scala b/spray-json/src/test/scala/pl/iterators/kebs/sprayjson/golden/SprayGoldenTests.scala new file mode 100644 index 00000000..bd5a7555 --- /dev/null +++ b/spray-json/src/test/scala/pl/iterators/kebs/sprayjson/golden/SprayGoldenTests.scala @@ -0,0 +1,113 @@ +package pl.iterators.kebs.sprayjson.golden + +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import pl.iterators.kebs.core.macros.CaseClass1ToValueClass +import pl.iterators.kebs.enumeratum.{KebsEnumeratum, KebsValueEnumeratum} +import pl.iterators.kebs.instances.TimeInstances +import pl.iterators.kebs.sprayjson.{KebsSprayJson, KebsSprayJsonEnums, KebsSprayJsonValueEnums} +import pl.iterators.kebs.sprayjson.enums.{KebsSprayJsonEnumsLowercase, KebsSprayJsonEnumsUppercase} +import pl.iterators.kebs.testkit.model._ +import spray.json._ + +import java.time.Instant + +/** Wire format of kebs 2.x (captured before the kebs 3 rewrite). kebs 3 must produce the same JSON with default configuration; a + * deliberate change belongs in the migration guide, not in a silently edited expectation. + */ +class SprayGoldenTests extends AnyFunSuite with Matchers { + private def golden[A](value: A, expected: String)(implicit format: JsonFormat[A]): Unit = { + format.write(value) shouldBe expected.parseJson + format.read(expected.parseJson) shouldBe value + } + + object Default extends DefaultJsonProtocol with KebsSprayJson + object Flat extends DefaultJsonProtocol with KebsSprayJson with CaseClass1ToValueClass + object FlatNulls extends DefaultJsonProtocol with KebsSprayJson with CaseClass1ToValueClass with NullOptions + object FlatTime extends DefaultJsonProtocol with KebsSprayJson with CaseClass1ToValueClass with TimeInstances + object FlatEnums + extends DefaultJsonProtocol + with KebsSprayJson + with CaseClass1ToValueClass + with KebsEnumeratum + with KebsValueEnumeratum + with KebsSprayJsonEnums + with KebsSprayJsonValueEnums + object FlatEnumsUppercase + extends DefaultJsonProtocol + with KebsSprayJson + with CaseClass1ToValueClass + with KebsEnumeratum + with KebsValueEnumeratum + with KebsSprayJsonEnumsUppercase + with KebsSprayJsonValueEnums + object FlatEnumsLowercase + extends DefaultJsonProtocol + with KebsSprayJson + with CaseClass1ToValueClass + with KebsEnumeratum + with KebsValueEnumeratum + with KebsSprayJsonEnumsLowercase + with KebsSprayJsonValueEnums + + test("person default") { + import Default._ + golden(Person(Id("x"), "Ann", 30, None), """{"id":{"value":"x"},"name":"Ann","age":30}""") + } + + test("person flat") { + import Flat._ + golden(Person(Id("x"), "Ann", 30, Some("A")), """{"id":"x","name":"Ann","age":30,"nickname":"A"}""") + } + + test("person NullOptions") { + import FlatNulls._ + golden(Person(Id("x"), "Ann", 30, None), """{"id":"x","name":"Ann","age":30,"nickname":null}""") + } + + test("naming snakified") { + import pl.iterators.kebs.sprayjson.snakified._ + golden(Naming(1, "a", 2, "u"), """{"some_field":1,"another_field_name":"a","field1_name":2,"http_url":"u"}""") + } + + test("naming capitalized") { + import pl.iterators.kebs.sprayjson.capitalized._ + golden(Naming(1, "a", 2, "u"), """{"SomeField":1,"AnotherFieldName":"a","Field1Name":2,"HttpURL":"u"}""") + } + + test("enums") { + import FlatEnums._ + golden(Paint(Color.DarkBlue, Level.High), """{"color":"DarkBlue","level":2}""") + } + + test("enums uppercase") { + import FlatEnumsUppercase._ + golden(Paint(Color.DarkBlue, Level.High), """{"color":"DARKBLUE","level":2}""") + } + + test("enums lowercase") { + import FlatEnumsLowercase._ + golden(Paint(Color.DarkBlue, Level.High), """{"color":"darkblue","level":2}""") + } + + test("instance converter") { + import FlatTime._ + golden(Event(Id("e"), Instant.parse("2026-01-02T03:04:05Z")), """{"id":"e","at":"2026-01-02T03:04:05Z"}""") + } + + test("wide (>22 fields)") { + import Default._ + golden( + Wide.sample, + """{"f1":1,"f2":2,"f3":3,"f4":4,"f5":5,"f6":6,"f7":7,"f8":8,"f9":9,"f10":10,"f11":11,"f12":12,"f13":13,"f14":14,"f15":15,"f16":16,"f17":17,"f18":18,"f19":19,"f20":20,"f21":21,"f22":22}""" + ) + } + + test("wide NullOptions") { + import FlatNulls._ + golden( + Wide.sample, + """{"f1":1,"f2":2,"f3":3,"f4":4,"f5":5,"f6":6,"f7":7,"f8":8,"f9":9,"f10":10,"f11":11,"f12":12,"f13":13,"f14":14,"f15":15,"f16":16,"f17":17,"f18":18,"f19":19,"f20":20,"f21":21,"f22":22,"f23":null}""" + ) + } +} From 8172854f97a645d4072f3d4f3b44513741cd0fd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Sowa?= Date: Sat, 21 Nov 2026 10:35:47 +0000 Subject: [PATCH 07/10] kebs 3: play-json golden tests (2.x wire format) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFD5QTj91bQhcjiNo9n48K --- build.sbt | 2 +- .../playjson/golden/PlayJsonGoldenTests.scala | 62 +++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 play-json/src/test/scala/pl/iterators/kebs/playjson/golden/PlayJsonGoldenTests.scala diff --git a/build.sbt b/build.sbt index a0e3bc96..c7d397df 100644 --- a/build.sbt +++ b/build.sbt @@ -368,7 +368,7 @@ lazy val playJsonSupport = crossProject(JSPlatform, JVMPlatform) .withoutSuffixFor(JVMPlatform) .crossType(CrossType.Pure) .in(file("play-json")) - .dependsOn(core, enumSupport, enumeratumSupport % "test -> test", instances % "test -> test") + .dependsOn(core, enumSupport, enumeratumSupport % "test -> test", instances % "test -> test", testkit % "test -> compile") .settings(playJsonSettings *) .settings(publishSettings *) .settings( diff --git a/play-json/src/test/scala/pl/iterators/kebs/playjson/golden/PlayJsonGoldenTests.scala b/play-json/src/test/scala/pl/iterators/kebs/playjson/golden/PlayJsonGoldenTests.scala new file mode 100644 index 00000000..2594cc87 --- /dev/null +++ b/play-json/src/test/scala/pl/iterators/kebs/playjson/golden/PlayJsonGoldenTests.scala @@ -0,0 +1,62 @@ +package pl.iterators.kebs.playjson.golden + +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import pl.iterators.kebs.core.macros.CaseClass1ToValueClass +import pl.iterators.kebs.enumeratum.{KebsEnumeratum, KebsValueEnumeratum} +import pl.iterators.kebs.instances.TimeInstances +import pl.iterators.kebs.playjson.KebsPlayJson +import pl.iterators.kebs.testkit.model._ +import play.api.libs.json._ + +import java.time.Instant + +/** What kebs 2.x provides for play-json (flat value classes, enums, instance converters) next to user-written `Json.format` codecs. kebs 3 + * adds case-class derivation; these codecs must keep winning and keep this output. + */ +class PlayJsonGoldenTests extends AnyFunSuite with Matchers { + private def golden[A](value: A, expected: String)(implicit format: Format[A]): Unit = { + format.writes(value) shouldBe Json.parse(expected) + format.reads(Json.parse(expected)) shouldBe JsSuccess(value) + } + + object Flat extends KebsPlayJson with CaseClass1ToValueClass with KebsEnumeratum with KebsValueEnumeratum with TimeInstances + + test("flat value class") { + import Flat._ + golden(Id("x"), "\"x\"") + } + + test("user Json.format with kebs field formats") { + import Flat._ + implicit val personFormat: OFormat[Person] = Json.format[Person] + golden(Person(Id("x"), "Ann", 30, None), """{"id":"x","name":"Ann","age":30}""") + } + + test("enums") { + import Flat._ + import pl.iterators.kebs.playjson.enums._ + implicit val paintFormat: OFormat[Paint] = Json.format[Paint] + golden(Paint(Color.DarkBlue, Level.High), """{"color":"DarkBlue","level":2}""") + } + + test("enums uppercase") { + import Flat._ + import pl.iterators.kebs.playjson.enums.uppercase._ + implicit val paintFormat: OFormat[Paint] = Json.format[Paint] + golden(Paint(Color.DarkBlue, Level.High), """{"color":"DARKBLUE","level":2}""") + } + + test("enums lowercase") { + import Flat._ + import pl.iterators.kebs.playjson.enums.lowercase._ + implicit val paintFormat: OFormat[Paint] = Json.format[Paint] + golden(Paint(Color.DarkBlue, Level.High), """{"color":"darkblue","level":2}""") + } + + test("instance converter") { + import Flat._ + implicit val eventFormat: OFormat[Event] = Json.format[Event] + golden(Event(Id("e"), Instant.parse("2026-01-02T03:04:05Z")), """{"id":"e","at":"2026-01-02T03:04:05Z"}""") + } +} From 691c9b8822d945af2e8b00b4099a37e2ba49d6da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Sowa?= Date: Sat, 21 Nov 2026 11:05:17 +0000 Subject: [PATCH 08/10] kebs 3: ValueClassLike never fails after Scala 3 Mirror selection A Scala 3 Mirror exists for single-field case classes with a private or protected constructor or a private field. The macro used to abort after the Mirror guard had selected the implicit - a hard compile error, or inside circe's inline derivation a silent switch from flat to object JSON. It now falls back to Mirror.fromProduct / productElement for what hearth cannot build or read (kebs 2's Scala 3 behaviour); the companion apply is still tried first. Scala 2 keeps aborting silently (no instance). Adds selection tests that tell 'no instance' from 'hard error', and private-constructor value-class goldens for circe, spray-json and play-json (captured against v2.3.0 on 2.13.18 and 3.3.9). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFD5QTj91bQhcjiNo9n48K --- .../kebs/circe/golden/CirceGoldenTests.scala | 5 ++ .../macros/CaseClass1ToValueClassCompat.scala | 19 +++-- .../internal/ValueClassLikeMacrosImpl.scala | 75 +++++++++++++------ .../ValueClassLikeScala2SelectionTests.scala | 18 +++++ .../ValueClassLikeScala3SelectionTests.scala | 32 ++++++++ .../core/ValueClassLikeSelectionTests.scala | 53 +++++++++++++ .../playjson/golden/PlayJsonGoldenTests.scala | 6 ++ .../sprayjson/golden/SprayGoldenTests.scala | 5 ++ .../pl/iterators/kebs/testkit/model.scala | 7 ++ 9 files changed, 193 insertions(+), 27 deletions(-) create mode 100644 core/src/test/scala-2/pl/iterators/kebs/core/ValueClassLikeScala2SelectionTests.scala create mode 100644 core/src/test/scala-3/pl/iterators/kebs/core/ValueClassLikeScala3SelectionTests.scala create mode 100644 core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeSelectionTests.scala diff --git a/circe/src/test/scala/pl/iterators/kebs/circe/golden/CirceGoldenTests.scala b/circe/src/test/scala/pl/iterators/kebs/circe/golden/CirceGoldenTests.scala index f628d8f9..da82d761 100644 --- a/circe/src/test/scala/pl/iterators/kebs/circe/golden/CirceGoldenTests.scala +++ b/circe/src/test/scala/pl/iterators/kebs/circe/golden/CirceGoldenTests.scala @@ -100,4 +100,9 @@ class CirceGoldenTests extends AnyFunSuite with Matchers { """{"f1":1,"f2":2,"f3":3,"f4":4,"f5":5,"f6":6,"f7":7,"f8":8,"f9":9,"f10":10,"f11":11,"f12":12,"f13":13,"f14":14,"f15":15,"f16":16,"f17":17,"f18":18,"f19":19,"f20":20,"f21":21,"f22":22,"f23":null}""" ) } + + test("private-constructor value class (flat)") { + import Flat._ + golden(Contact(Email.from("a@b.pl"), "n"), """{"email":"a@b.pl","name":"n"}""") + } } diff --git a/core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala b/core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala index ff831040..d7b503d8 100644 --- a/core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala +++ b/core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala @@ -6,17 +6,26 @@ import scala.deriving.Mirror import scala.quoted.* private[macros] trait CaseClass1ToValueClassCompat { - // The Mirror evidence infers F1 and keeps types that are not single-field products from reaching the macro - // (a non-transparent inline given is expanded after it has been selected, so a macro failure would be a hard error). + // The Mirror evidence infers F1 and keeps types that are not single-field products from reaching the macro. + // A non-transparent inline given is expanded after it has been selected, so the macro must never fail once the + // Mirror matched: what hearth cannot build or read (private/protected constructor, private field) goes through + // the Mirror itself, as in kebs 2. inline implicit def repFromCaseClass[T <: Product, F1](using m: Mirror.ProductOf[T], teq: m.MirroredElemTypes =:= F1 *: EmptyTuple.type - ): ValueClassLike[T, F1] = ${ ValueClassLikeMacros.materialize[T, F1] } + ): ValueClassLike[T, F1] = ${ ValueClassLikeMacros.materialize[T, F1]('m) } } final private[macros] class ValueClassLikeMacros(q: Quotes) extends hearth.MacroCommonsScala3(using q), ValueClassLikeMacrosImpl private[macros] object ValueClassLikeMacros { - def materialize[T: Type, F1: Type](using q: Quotes): Expr[ValueClassLike[T, F1]] = - new ValueClassLikeMacros(q).deriveValueClassLike[T].value.asInstanceOf[Expr[ValueClassLike[T, F1]]] + def materialize[T <: Product: Type, F1: Type](m: Expr[Mirror.ProductOf[T]])(using q: Quotes): Expr[ValueClassLike[T, F1]] = { + val macros = new ValueClassLikeMacros(q) + macros.deriveValueClassLikeWithFallback[T, F1]( + new macros.ProductFallback[T, F1]( + f => '{ $m.fromProduct(Tuple1($f)) }, + t => '{ $t.productElement(0).asInstanceOf[F1] } + ) + ) + } } diff --git a/core/src/main/scala/pl/iterators/kebs/core/macros/internal/ValueClassLikeMacrosImpl.scala b/core/src/main/scala/pl/iterators/kebs/core/macros/internal/ValueClassLikeMacrosImpl.scala index ee10ca3b..ab8971e0 100644 --- a/core/src/main/scala/pl/iterators/kebs/core/macros/internal/ValueClassLikeMacrosImpl.scala +++ b/core/src/main/scala/pl/iterators/kebs/core/macros/internal/ValueClassLikeMacrosImpl.scala @@ -5,50 +5,81 @@ import hearth.fp.instances.* import hearth.fp.syntax.* import pl.iterators.kebs.core.macros.ValueClassLike -/** Shared (Scala 2.13 + Scala 3) implementation of `ValueClassLike` derivation for single-field case classes. */ +/** Shared (Scala 2.13 + Scala 3) implementation of `ValueClassLike` derivation for single-field case classes. + * + * Values are constructed through the companion's `apply` (so validating/normalising `apply`s are honoured); the primary constructor is + * used when no matching `apply` is callable at the call site, and an optional [[ProductFallback]] (Scala 3: `Mirror.fromProduct` / + * `productElement`) when neither is accessible. + */ private[kebs] trait ValueClassLikeMacrosImpl { this: hearth.MacroCommons => - /** Builds `ValueClassLike[T, F]` where `F` is the type of the only field of case class `T`. - * - * Values are constructed through the companion's `apply` (so validating/normalising `apply`s are honoured); the primary constructor is - * used only when no matching `apply` is callable at the call site. - */ + /** How to build and read `T` when neither its `apply`/constructor nor its field accessor is accessible. */ + final class ProductFallback[T, F](val construct: Expr[F] => Expr[T], val access: Expr[T] => Expr[F]) + + /** Scala 2 entry point: `F` is the type of the only field; aborts (no instance) when `T` does not qualify. */ def deriveValueClassLike[T: Type]: Expr_?? = { val caseClass: CaseClass[T] = CaseClass.parse[T].toOption match { case Some(cc) => cc case None => Environment.reportErrorAndAbort(s"${Type[T].prettyPrint} is not a case class") } - val field: Parameter = caseClass.primaryConstructor.parameters.flatMap(_.values.toList) match { - case single :: Nil => single - case _ => Environment.reportErrorAndAbort(s"To derive ValueClassLike, ${Type[T].prettyPrint} must have exactly one field") - } + val field: Parameter = singleField(caseClass).getOrElse( + Environment.reportErrorAndAbort(s"To derive ValueClassLike, ${Type[T].prettyPrint} must have exactly one field") + ) // a nested path (`field.tpe.Underlying`) breaks cross-quotes on Scala 2.13 - bind it first val fieldType: ?? = field.tpe import fieldType.Underlying as F implicit val ValueClassLikeType: Type[ValueClassLike[T, F]] = Type.of[ValueClassLike[T, F]] + build[T, F](Some(caseClass), None).as_?? + } - def construct(arg: Expr[F]): Expr[T] = - viaCompanionApply[T, F](arg).getOrElse { - caseClass.construct[MIO](_ => MIO.pure(arg.as_??)).unsafe.runSync._2 match { - case Right(Some(constructed)) => constructed - case _ => Environment.reportErrorAndAbort(s"${Type[T].prettyPrint} has no accessible apply or constructor") - } - } + /** Scala 3 entry point: `F` is fixed by the `Mirror` that selected the implicit, so this never aborts — whatever hearth cannot build or + * read goes through `fallback`. + */ + def deriveValueClassLikeWithFallback[T: Type, F: Type](fallback: ProductFallback[T, F]): Expr[ValueClassLike[T, F]] = { + val caseClass = CaseClass.parse[T].toOption.filter(cc => singleField(cc).exists(_.tpe.Underlying =:= Type[F])) + build[T, F](caseClass, Some(fallback)) + } - def access(value: Expr[T]): Expr[F] = { - val fieldValue = caseClass.caseFieldValuesAt(value).head._2 - import fieldValue.{Underlying as G, value as extracted} - extracted.asInstanceOf[Expr[F]] + private def singleField[T](caseClass: CaseClass[T]): Option[Parameter] = + caseClass.primaryConstructor.parameters.flatMap(_.values.toList) match { + case single :: Nil => Some(single) + case _ => None } + private def build[T: Type, F: Type]( + caseClass: Option[CaseClass[T]], + fallback: Option[ProductFallback[T, F]] + ): Expr[ValueClassLike[T, F]] = { + def construct(arg: Expr[F]): Expr[T] = + viaCompanionApply[T, F](arg) + .orElse(caseClass.flatMap(viaConstructor[T, F](_, arg))) + .orElse(fallback.map(_.construct(arg))) + .getOrElse(Environment.reportErrorAndAbort(s"${Type[T].prettyPrint} has no accessible apply or constructor")) + + def access(value: Expr[T]): Expr[F] = + caseClass + .flatMap(_.caseFieldValuesAt(value).headOption) + .map { case (_, fieldValue) => + import fieldValue.{Underlying as G, value as extracted} + extracted.asInstanceOf[Expr[F]] + } + .orElse(fallback.map(_.access(value))) + .getOrElse(Environment.reportErrorAndAbort(s"The field of ${Type[T].prettyPrint} is not accessible")) + Expr.quote { new ValueClassLike[T, F]( (f: F) => Expr.splice(construct(Expr.quote(f))), (t: T) => Expr.splice(access(Expr.quote(t))) ) - }.as_?? + } } + private def viaConstructor[T: Type, F: Type](caseClass: CaseClass[T], arg: Expr[F]): Option[Expr[T]] = + caseClass.construct[MIO](_ => MIO.pure(arg.as_??)).unsafe.runSync._2 match { + case Right(Some(constructed)) => Some(constructed) + case _ => None + } + /** Calls `T.apply(arg)` if the companion has an `apply` taking exactly one argument of type `F`. */ private def viaCompanionApply[T: Type, F: Type](arg: Expr[F]): Option[Expr[T]] = { def walk(method: Method): Option[Expr[T]] = method match { diff --git a/core/src/test/scala-2/pl/iterators/kebs/core/ValueClassLikeScala2SelectionTests.scala b/core/src/test/scala-2/pl/iterators/kebs/core/ValueClassLikeScala2SelectionTests.scala new file mode 100644 index 00000000..e042c4ad --- /dev/null +++ b/core/src/test/scala-2/pl/iterators/kebs/core/ValueClassLikeScala2SelectionTests.scala @@ -0,0 +1,18 @@ +package pl.iterators.kebs.core + +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import pl.iterators.kebs.core.macros.CaseClass1ToValueClass + +object ValueClassLikeScala2SelectionDomain { + final case class PrivateField(private val value: Int) +} + +/** On Scala 2 a private case field has no readable accessor: kebs 2 gave no instance, silently; kebs 3 keeps that. */ +class ValueClassLikeScala2SelectionTests extends AnyFunSuite with Matchers with CaseClass1ToValueClass { + import ValueClassLikeScala2SelectionDomain._ + + test("case class with a private field falls back silently") { + implicitly[Pick[PrivateField]].chosen shouldBe "fallback" + } +} diff --git a/core/src/test/scala-3/pl/iterators/kebs/core/ValueClassLikeScala3SelectionTests.scala b/core/src/test/scala-3/pl/iterators/kebs/core/ValueClassLikeScala3SelectionTests.scala new file mode 100644 index 00000000..eb4a3002 --- /dev/null +++ b/core/src/test/scala-3/pl/iterators/kebs/core/ValueClassLikeScala3SelectionTests.scala @@ -0,0 +1,32 @@ +package pl.iterators.kebs.core + +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import pl.iterators.kebs.core.macros.{CaseClass1ToValueClass, ValueClassLike} + +object ValueClassLikeScala3SelectionDomain { + final case class ProtectedCtor protected (value: Int) + object ProtectedCtor { + def from(value: Int): ProtectedCtor = new ProtectedCtor(value) + } + final case class PrivateField(private val value: Int) +} + +/** Scala 3 synthesises a Mirror for these, so kebs 2 gave them a ValueClassLike (via Mirror.fromProduct / productElement); kebs 3 must + * keep doing so instead of failing after the Mirror guard selected the implicit. + */ +class ValueClassLikeScala3SelectionTests extends AnyFunSuite with Matchers with CaseClass1ToValueClass { + import ValueClassLikeScala3SelectionDomain._ + + test("protected-constructor value class gets the flat instance and round-trips") { + implicitly[Pick[ProtectedCtor]].chosen shouldBe "flat" + val rep = implicitly[ValueClassLike[ProtectedCtor, Int]] + rep.unapply(rep.apply(5)) shouldBe 5 + } + + test("case class with a private field gets the flat instance and round-trips") { + implicitly[Pick[PrivateField]].chosen shouldBe "flat" + val rep = implicitly[ValueClassLike[PrivateField, Int]] + rep.unapply(rep.apply(7)) shouldBe 7 + } +} diff --git a/core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeSelectionTests.scala b/core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeSelectionTests.scala new file mode 100644 index 00000000..1dcf9910 --- /dev/null +++ b/core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeSelectionTests.scala @@ -0,0 +1,53 @@ +package pl.iterators.kebs.core + +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import pl.iterators.kebs.core.macros.{CaseClass1ToValueClass, ValueClassLike} + +/** A type class with a flat instance (needs ValueClassLike) and a low-priority fallback: a type without a ValueClassLike must get the + * fallback, never a compile error - this is how every flat format in kebs is searched. + */ +final class Pick[A](val chosen: String) +trait LowPriorityPick { + implicit def fallback[A]: Pick[A] = new Pick[A]("fallback") +} +object Pick extends LowPriorityPick { + implicit def flat[T, A](implicit rep: ValueClassLike[T, A]): Pick[T] = new Pick[T]("flat") +} + +object ValueClassLikeSelectionDomain { + final case class Plain(value: String) + final case class Two(a: Int, b: Int) + final class NotCase(val value: Int) + final case class PrivateCtor private (value: String) + object PrivateCtor { + def from(value: String): PrivateCtor = new PrivateCtor(value) + } + final case class MultiList(a: Int)(val b: Int) +} + +class ValueClassLikeSelectionTests extends AnyFunSuite with Matchers with CaseClass1ToValueClass { + import ValueClassLikeSelectionDomain._ + + test("single-field case class gets the flat instance") { + implicitly[Pick[Plain]].chosen shouldBe "flat" + } + + test("2-field case class falls back silently") { + implicitly[Pick[Two]].chosen shouldBe "fallback" + } + + test("non-case class falls back silently") { + implicitly[Pick[NotCase]].chosen shouldBe "fallback" + } + + test("private-constructor value class gets the flat instance and round-trips") { + implicitly[Pick[PrivateCtor]].chosen shouldBe "flat" + val rep = implicitly[ValueClassLike[PrivateCtor, String]] + rep.unapply(rep.apply("x")) shouldBe "x" + } + + test("case class with several parameter lists never fails compilation") { + implicitly[Pick[MultiList]].chosen should (equal("flat") or equal("fallback")) + } +} diff --git a/play-json/src/test/scala/pl/iterators/kebs/playjson/golden/PlayJsonGoldenTests.scala b/play-json/src/test/scala/pl/iterators/kebs/playjson/golden/PlayJsonGoldenTests.scala index 2594cc87..f7b5c947 100644 --- a/play-json/src/test/scala/pl/iterators/kebs/playjson/golden/PlayJsonGoldenTests.scala +++ b/play-json/src/test/scala/pl/iterators/kebs/playjson/golden/PlayJsonGoldenTests.scala @@ -59,4 +59,10 @@ class PlayJsonGoldenTests extends AnyFunSuite with Matchers { implicit val eventFormat: OFormat[Event] = Json.format[Event] golden(Event(Id("e"), Instant.parse("2026-01-02T03:04:05Z")), """{"id":"e","at":"2026-01-02T03:04:05Z"}""") } + + test("private-constructor value class (flat)") { + import Flat._ + implicit val contactFormat: OFormat[Contact] = Json.format[Contact] + golden(Contact(Email.from("a@b.pl"), "n"), """{"email":"a@b.pl","name":"n"}""") + } } diff --git a/spray-json/src/test/scala/pl/iterators/kebs/sprayjson/golden/SprayGoldenTests.scala b/spray-json/src/test/scala/pl/iterators/kebs/sprayjson/golden/SprayGoldenTests.scala index bd5a7555..7f8350a1 100644 --- a/spray-json/src/test/scala/pl/iterators/kebs/sprayjson/golden/SprayGoldenTests.scala +++ b/spray-json/src/test/scala/pl/iterators/kebs/sprayjson/golden/SprayGoldenTests.scala @@ -110,4 +110,9 @@ class SprayGoldenTests extends AnyFunSuite with Matchers { """{"f1":1,"f2":2,"f3":3,"f4":4,"f5":5,"f6":6,"f7":7,"f8":8,"f9":9,"f10":10,"f11":11,"f12":12,"f13":13,"f14":14,"f15":15,"f16":16,"f17":17,"f18":18,"f19":19,"f20":20,"f21":21,"f22":22,"f23":null}""" ) } + + test("private-constructor value class (flat)") { + import Flat._ + golden(Contact(Email.from("a@b.pl"), "n"), """{"email":"a@b.pl","name":"n"}""") + } } diff --git a/testkit/src/main/scala/pl/iterators/kebs/testkit/model.scala b/testkit/src/main/scala/pl/iterators/kebs/testkit/model.scala index ed357c56..1c77f6ca 100644 --- a/testkit/src/main/scala/pl/iterators/kebs/testkit/model.scala +++ b/testkit/src/main/scala/pl/iterators/kebs/testkit/model.scala @@ -15,6 +15,13 @@ object model { final case class Naming(someField: Int, anotherFieldName: String, field1Name: Int, httpURL: String) final case class Event(id: Id, at: Instant) + /** The usual validated value class: private constructor, smart constructor in the companion. */ + final case class Email private (value: String) + object Email { + def from(value: String): Email = new Email(value.toLowerCase) + } + final case class Contact(email: Email, name: String) + final case class Wide( f1: Int, f2: Int, From a1fe8540d13a265e16c81aff94dd9c45c3daf588 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Sowa?= Date: Sat, 21 Nov 2026 12:20:15 +0000 Subject: [PATCH 09/10] Keep design docs out of the repo, trim comments to the house style Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFD5QTj91bQhcjiNo9n48K --- build.sbt | 2 +- .../circe/golden/CirceAdtGoldenTests.scala | 2 +- .../kebs/circe/golden/CirceGoldenTests.scala | 4 +- .../macros/CaseClass1ToValueClassCompat.scala | 2 +- .../macros/CaseClass1ToValueClassCompat.scala | 5 +- .../internal/ValueClassLikeMacrosImpl.scala | 15 +- .../ValueClassLikeScala2SelectionTests.scala | 2 +- .../ValueClassLikeScala3SelectionTests.scala | 4 +- .../core/ValueClassLikeSelectionTests.scala | 4 +- design/2026-11-21-kebs-3-design.md | 404 ------------------ .../plans/2026-11-21-plan-0-release-2.3.0.md | 106 ----- .../2026-11-21-plan-1-build-core-testkit.md | 345 --------------- .../playjson/golden/PlayJsonGoldenTests.scala | 4 +- .../sprayjson/golden/SprayGoldenTests.scala | 4 +- .../pl/iterators/kebs/testkit/model.scala | 5 +- 15 files changed, 13 insertions(+), 895 deletions(-) delete mode 100644 design/2026-11-21-kebs-3-design.md delete mode 100644 design/plans/2026-11-21-plan-0-release-2.3.0.md delete mode 100644 design/plans/2026-11-21-plan-1-build-core-testkit.md diff --git a/build.sbt b/build.sbt index c7d397df..eb781f7a 100644 --- a/build.sbt +++ b/build.sbt @@ -204,7 +204,7 @@ lazy val coreSettings = commonMacroSettings ++ Seq( libraryDependencies ++= (if (scalaVersion.value.startsWith("3")) Seq(compilerPlugin("com.kubuszok" % "hearth-cross-quotes_3" % hearthV)) else Nil), - // hearth's path-dependent Method/Type ADTs trigger this harmless Scala 2 warning in macro code + // harmless on hearth's path-dependent Method/Type ADTs scalacOptions ++= (if (scalaVersion.value.startsWith("3")) Nil else Seq("-Wconf:msg=The outer reference in this type test cannot be checked at run time:s")), libraryDependencies += (scalaCheck.value % "test"), diff --git a/circe/src/test/scala-2/pl/iterators/kebs/circe/golden/CirceAdtGoldenTests.scala b/circe/src/test/scala-2/pl/iterators/kebs/circe/golden/CirceAdtGoldenTests.scala index 904cd6f9..5cceca4c 100644 --- a/circe/src/test/scala-2/pl/iterators/kebs/circe/golden/CirceAdtGoldenTests.scala +++ b/circe/src/test/scala-2/pl/iterators/kebs/circe/golden/CirceAdtGoldenTests.scala @@ -6,7 +6,7 @@ import org.scalatest.matchers.should.Matchers import pl.iterators.kebs.circe.KebsCirce import pl.iterators.kebs.testkit.model._ -/** Scala 2 only: kebs 2 on Scala 3 does not derive sealed traits. The kebs 3 circe plan moves this to shared tests. */ +// Scala 2 only: kebs 2 on Scala 3 does not derive sealed traits class CirceAdtGoldenTests extends AnyFunSuite with Matchers { private def json(s: String): Json = io.circe.parser.parse(s).fold(throw _, identity) diff --git a/circe/src/test/scala/pl/iterators/kebs/circe/golden/CirceGoldenTests.scala b/circe/src/test/scala/pl/iterators/kebs/circe/golden/CirceGoldenTests.scala index da82d761..757a54a9 100644 --- a/circe/src/test/scala/pl/iterators/kebs/circe/golden/CirceGoldenTests.scala +++ b/circe/src/test/scala/pl/iterators/kebs/circe/golden/CirceGoldenTests.scala @@ -12,9 +12,7 @@ import pl.iterators.kebs.testkit.model._ import java.time.Instant -/** Wire format of kebs 2.x (captured before the kebs 3 rewrite). kebs 3 must produce the same JSON with default configuration; a - * deliberate change belongs in the migration guide, not in a silently edited expectation. - */ +// kebs 2.x wire format (verified against v2.3.0); a deliberate change goes to the migration guide, not into these expectations class CirceGoldenTests extends AnyFunSuite with Matchers { private def json(s: String): Json = io.circe.parser.parse(s).fold(throw _, identity) diff --git a/core/src/main/scala-2/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala b/core/src/main/scala-2/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala index 043e5cd9..75fab1ea 100644 --- a/core/src/main/scala-2/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala +++ b/core/src/main/scala-2/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala @@ -9,7 +9,7 @@ private[macros] trait CaseClass1ToValueClassCompat { implicit def repFromCaseClass[VC <: Product, F1]: ValueClassLike[VC, F1] = macro ValueClassRepMacros.materializeValueClassRep[VC, F1] } -// whitebox: the macro's result type fixes F1, which the caller leaves for the compiler to infer +// whitebox, so that the expansion's type fixes F1 left open by the caller final private[macros] class ValueClassRepMacros(val c: whitebox.Context) extends hearth.MacroCommonsScala2 with ValueClassLikeMacrosImpl { def materializeValueClassRep[VC <: Product: c.WeakTypeTag, F1: c.WeakTypeTag]: c.Expr[ValueClassLike[VC, F1]] = c.Expr[ValueClassLike[VC, F1]](deriveValueClassLike[VC].value.tree) diff --git a/core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala b/core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala index d7b503d8..11ba78ef 100644 --- a/core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala +++ b/core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala @@ -6,10 +6,7 @@ import scala.deriving.Mirror import scala.quoted.* private[macros] trait CaseClass1ToValueClassCompat { - // The Mirror evidence infers F1 and keeps types that are not single-field products from reaching the macro. - // A non-transparent inline given is expanded after it has been selected, so the macro must never fail once the - // Mirror matched: what hearth cannot build or read (private/protected constructor, private field) goes through - // the Mirror itself, as in kebs 2. + // selected via the Mirror, so the macro must not abort - it falls back to the Mirror instead inline implicit def repFromCaseClass[T <: Product, F1](using m: Mirror.ProductOf[T], teq: m.MirroredElemTypes =:= F1 *: EmptyTuple.type diff --git a/core/src/main/scala/pl/iterators/kebs/core/macros/internal/ValueClassLikeMacrosImpl.scala b/core/src/main/scala/pl/iterators/kebs/core/macros/internal/ValueClassLikeMacrosImpl.scala index ab8971e0..cd17a8fe 100644 --- a/core/src/main/scala/pl/iterators/kebs/core/macros/internal/ValueClassLikeMacrosImpl.scala +++ b/core/src/main/scala/pl/iterators/kebs/core/macros/internal/ValueClassLikeMacrosImpl.scala @@ -5,18 +5,10 @@ import hearth.fp.instances.* import hearth.fp.syntax.* import pl.iterators.kebs.core.macros.ValueClassLike -/** Shared (Scala 2.13 + Scala 3) implementation of `ValueClassLike` derivation for single-field case classes. - * - * Values are constructed through the companion's `apply` (so validating/normalising `apply`s are honoured); the primary constructor is - * used when no matching `apply` is callable at the call site, and an optional [[ProductFallback]] (Scala 3: `Mirror.fromProduct` / - * `productElement`) when neither is accessible. - */ private[kebs] trait ValueClassLikeMacrosImpl { this: hearth.MacroCommons => - /** How to build and read `T` when neither its `apply`/constructor nor its field accessor is accessible. */ final class ProductFallback[T, F](val construct: Expr[F] => Expr[T], val access: Expr[T] => Expr[F]) - /** Scala 2 entry point: `F` is the type of the only field; aborts (no instance) when `T` does not qualify. */ def deriveValueClassLike[T: Type]: Expr_?? = { val caseClass: CaseClass[T] = CaseClass.parse[T].toOption match { case Some(cc) => cc @@ -25,16 +17,13 @@ private[kebs] trait ValueClassLikeMacrosImpl { this: hearth.MacroCommons => val field: Parameter = singleField(caseClass).getOrElse( Environment.reportErrorAndAbort(s"To derive ValueClassLike, ${Type[T].prettyPrint} must have exactly one field") ) - // a nested path (`field.tpe.Underlying`) breaks cross-quotes on Scala 2.13 - bind it first + // a nested path (field.tpe.Underlying) breaks cross-quotes on 2.13 val fieldType: ?? = field.tpe import fieldType.Underlying as F implicit val ValueClassLikeType: Type[ValueClassLike[T, F]] = Type.of[ValueClassLike[T, F]] build[T, F](Some(caseClass), None).as_?? } - /** Scala 3 entry point: `F` is fixed by the `Mirror` that selected the implicit, so this never aborts — whatever hearth cannot build or - * read goes through `fallback`. - */ def deriveValueClassLikeWithFallback[T: Type, F: Type](fallback: ProductFallback[T, F]): Expr[ValueClassLike[T, F]] = { val caseClass = CaseClass.parse[T].toOption.filter(cc => singleField(cc).exists(_.tpe.Underlying =:= Type[F])) build[T, F](caseClass, Some(fallback)) @@ -50,6 +39,7 @@ private[kebs] trait ValueClassLikeMacrosImpl { this: hearth.MacroCommons => caseClass: Option[CaseClass[T]], fallback: Option[ProductFallback[T, F]] ): Expr[ValueClassLike[T, F]] = { + // companion apply first, so that validating/normalising applys are honoured def construct(arg: Expr[F]): Expr[T] = viaCompanionApply[T, F](arg) .orElse(caseClass.flatMap(viaConstructor[T, F](_, arg))) @@ -80,7 +70,6 @@ private[kebs] trait ValueClassLikeMacrosImpl { this: hearth.MacroCommons => case _ => None } - /** Calls `T.apply(arg)` if the companion has an `apply` taking exactly one argument of type `F`. */ private def viaCompanionApply[T: Type, F: Type](arg: Expr[F]): Option[Expr[T]] = { def walk(method: Method): Option[Expr[T]] = method match { case _: Method.OnInstance => None diff --git a/core/src/test/scala-2/pl/iterators/kebs/core/ValueClassLikeScala2SelectionTests.scala b/core/src/test/scala-2/pl/iterators/kebs/core/ValueClassLikeScala2SelectionTests.scala index e042c4ad..24eb177d 100644 --- a/core/src/test/scala-2/pl/iterators/kebs/core/ValueClassLikeScala2SelectionTests.scala +++ b/core/src/test/scala-2/pl/iterators/kebs/core/ValueClassLikeScala2SelectionTests.scala @@ -8,7 +8,7 @@ object ValueClassLikeScala2SelectionDomain { final case class PrivateField(private val value: Int) } -/** On Scala 2 a private case field has no readable accessor: kebs 2 gave no instance, silently; kebs 3 keeps that. */ +// a private case field has no accessor on Scala 2: no instance, as in kebs 2 class ValueClassLikeScala2SelectionTests extends AnyFunSuite with Matchers with CaseClass1ToValueClass { import ValueClassLikeScala2SelectionDomain._ diff --git a/core/src/test/scala-3/pl/iterators/kebs/core/ValueClassLikeScala3SelectionTests.scala b/core/src/test/scala-3/pl/iterators/kebs/core/ValueClassLikeScala3SelectionTests.scala index eb4a3002..02f496e7 100644 --- a/core/src/test/scala-3/pl/iterators/kebs/core/ValueClassLikeScala3SelectionTests.scala +++ b/core/src/test/scala-3/pl/iterators/kebs/core/ValueClassLikeScala3SelectionTests.scala @@ -12,9 +12,7 @@ object ValueClassLikeScala3SelectionDomain { final case class PrivateField(private val value: Int) } -/** Scala 3 synthesises a Mirror for these, so kebs 2 gave them a ValueClassLike (via Mirror.fromProduct / productElement); kebs 3 must - * keep doing so instead of failing after the Mirror guard selected the implicit. - */ +// Scala 3 has a Mirror for these, so kebs 2 derived them via Mirror.fromProduct; kebs 3 must not lose them class ValueClassLikeScala3SelectionTests extends AnyFunSuite with Matchers with CaseClass1ToValueClass { import ValueClassLikeScala3SelectionDomain._ diff --git a/core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeSelectionTests.scala b/core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeSelectionTests.scala index 1dcf9910..8aedc42d 100644 --- a/core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeSelectionTests.scala +++ b/core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeSelectionTests.scala @@ -4,9 +4,7 @@ import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import pl.iterators.kebs.core.macros.{CaseClass1ToValueClass, ValueClassLike} -/** A type class with a flat instance (needs ValueClassLike) and a low-priority fallback: a type without a ValueClassLike must get the - * fallback, never a compile error - this is how every flat format in kebs is searched. - */ +// flat formats are searched like this everywhere in kebs: no ValueClassLike must mean the fallback, never a compile error final class Pick[A](val chosen: String) trait LowPriorityPick { implicit def fallback[A]: Pick[A] = new Pick[A]("fallback") diff --git a/design/2026-11-21-kebs-3-design.md b/design/2026-11-21-kebs-3-design.md deleted file mode 100644 index da655f1f..00000000 --- a/design/2026-11-21-kebs-3-design.md +++ /dev/null @@ -1,404 +0,0 @@ -# kebs 3 — design - -Status: draft for maintainer review · 2026-11-21 - -## 1. Intent - -Rewrite kebs' macros on [hearth](https://github.com/kubuszok/hearth) — or delegate to -[kindlings](https://github.com/kubuszok/kindlings) where a kindlings module already does the job — so that: - -- **macros are faster** to compile (no inline/`Mirror` recursion, no implicit-search chains) and the generated code is - faster at runtime (no `productIterator` zipping, no `Tuple` allocation, no per-site anonymous classes — issue #417); -- **there is one implementation per macro** shared by Scala 2.13 and Scala 3, instead of two that drift apart; -- **behaviour is the same on both Scala versions** (today it is not — see §4.2). - -While the macros are being rewritten, kebs 3 also closes cheap feature gaps, unifies how JSON modules name fields and -enum values, and adds ADT support to the JSON modules. Because the Scala 3 floor moves (see §3), this is a major -release: **kebs 3.0**. - -Before kebs 3 work lands on master, kebs **2.3.0** is cut with dependency bumps only, as the (likely) last 2.x minor. - -## 2. Goals, non-goals, anti-goals - -**Goals** - -1. Every macro kebs owns is written once on hearth, cross-compiled for 2.13 and 3. -2. circe and scalacheck derivation delegate to kindlings; a new `kebs-jsoniter` module is built on kindlings. -3. The current test suites keep passing on both Scala versions; they are the behavioural spec (see §6). -4. Scala 2 vs Scala 3 inconsistencies listed in §4.2 are removed. -5. The gaps listed in §4.3 are filled. -6. One naming vocabulary for field names and enum values across all modules (§5.3). -7. JSON modules (circe, spray-json, play-json, jsoniter) derive case classes **and** sealed hierarchies the same way, - configured the same way (§5.4). - -**Non-goals** - -- tagged-meta (Scala 2 macro annotation) and jsonschema (scala-jsonschema is Scala 2 only) are not rewritten; they stay - Scala 2 only, unchanged apart from build changes. -- slick-pg issues (#4, #5, #6, #276) are not addressed. -- PATCH semantics (distinguishing absent vs `null` fields) are not exposed by kebs. -- No changes to `instances`, `opaque`, `tagged`, `slick`, `baklava` beyond what build/dependency/enum-naming changes - require. - -**Anti-goals** (a release that does these is a failure even if it compiles) - -- **Silent wire-format changes.** A kebs 2 user upgrading to kebs 3 must get the same JSON (and the same DB/HTTP enum - strings) unless the change is deliberate and listed in the migration guide. Defaults are chosen to preserve today's - output per module. -- Users having to rewrite call sites for things that did not change conceptually: the existing entry points - (`KebsCirce`, `circe.snakified`, `sprayjson.capitalized`, `enums.uppercase`, `KebsArbitrarySupport`, - `CaseClass1ToValueClass`, …) keep their names and roles. -- Worse error messages than today for a missing instance. - -## 3. Constraints - -- **Scala versions: 2.13.18 and 3.9.0 (LTS).** kindlings 0.4.0's Scala 3 artifacts are built with 3.8.4, so the kebs - Scala 3 floor rises from 3.3 to 3.9. Verified: kindlings-circe-derivation 0.4.0 compiles and runs from a 3.9.0 build. -- **JDK 17+.** Scala 3.8+ requires it. CI moves from JDK 11+17 to JDK 17+21. -- **hearth 0.4.5, kindlings 0.4.0.** kindlings 0.4.0 depends on hearth 0.4.5; kebs must depend on exactly the hearth - version its kindlings version uses (they run inside the compiler, an evicted mismatch can break macro expansion). - Policy: bump hearth and kindlings together. -- hearth is pre-1.0 and becomes a transitive dependency of every kebs user (via kebs-core). -- Cross-compiled hearth macros still need a small per-version entry file (`scala-2/` macro bundle, `scala-3/` - `inline … = ${…}`), and the `hearth-cross-quotes` compiler plugin on Scala 3. The macro logic is shared. -- Platforms stay as today (core/circe/http4s/… on JVM+JS+Native, play-json JVM+JS, others JVM). hearth and the used - kindlings modules are published for all three platforms. -- Binary compatibility: kebs 3.0 breaks it deliberately; MiMa is disabled for 3.0.0 and re-enabled with - `tlMimaPreviousVersions := Set("3.0.0")` afterwards. -- Generated docs (`docs/*.md`) are compiled by mdoc into the website; `ci.yml` is generated by sbt-github-actions - (never hand-edit; regenerate from build.sbt). The website workflow only runs on master. - -## 4. Scope - -### 4.1 Macro inventory and where each goes - -| Module | Today (2.13 / 3) | kebs 3 | -|---|---|---| -| core `ValueClassLike` (`CaseClass1ToValueClass`) | whitebox macro / `Mirror.ProductOf` + `productElement(0).asInstanceOf` | hearth macro | -| enum | `Enumeration` only / Scala 3 `enum` only; `KebsValueEnum` Scala 3 only | hearth macro (`Enum` view) | -| enumeratum | `Companion.values` / `Mirror` inline recursion | hearth macro, `Companion.values` on both | -| spray-json | own macro (spray `jsonFormat` ≤22, hand-rolled >22) / `Mirror` + runtime zip | hearth macro | -| play-json | none (flat/enum/instance formats only) | **new** hearth macro (issue #384) | -| circe | own macro + circe-generic `AutoDerivation` + generic-extras >22 / circe `ConfiguredDecoder` | kindlings-circe-derivation | -| jsoniter | — | **new** module on kindlings-jsoniter-derivation (issue #255) | -| scalacheck | magnolify / scalacheck-derived | kindlings-scalacheck-derivation | -| jsonschema, tagged-meta | Scala 2 only | unchanged | -| akka-http | Scala 2 only, Akka 2.6 | **dropped** (pekko-http replaces it) | - -### 4.2 Inconsistencies to remove - -1. `ValueClassLike` on Scala 3 constructs via `Mirror.fromProduct` (the constructor), bypassing a validating - companion `apply`; Scala 2 calls `apply`. → Both call the companion `apply` (verify a test exists; add one). -2. enum: Scala 2 handles only `scala.Enumeration`, Scala 3 only `scala.reflect.Enum`; value enums only on Scala 3. → - `KebsEnum` handles `Enumeration` on both versions and `enum` on Scala 3; `KebsValueEnum` on both versions for - sealed hierarchies / enums extending `ValueEnumLikeEntry` (today's Scala 3 bound, now also on 2.13). - **Plain sealed hierarchies of case objects do not get an `EnumLike` automatically** (decided 2026-11-21 after - review): enumeratum entries are such hierarchies too (the two implicits would compete), and it would silently turn - `{"Red":{}}` into `"Red"` for circe users. They stay ADTs; users who want enum strings use enumeratum, `Enumeration`, - a Scala 3 `enum`, or the ADT's `constructorNaming` with case objects. -3. enumeratum on Scala 3 ignores the user's `values` and fails on nested sealed hierarchies. → `Companion.values` on - both. -4. circe: Scala 2 auto-derives sealed traits, Scala 3 only case classes; snake_case comes from kebs' `snakify` on 2 and - circe's renaming on 3. → kindlings on both, given kebs' naming functions. -5. spray-json: `jsonFormatRec` is a real lazy format on 2, an alias on 3; >22 fields hand-rolled on 2 (and there it - drops *any* `JsNull` field, not only `None`); Scala 3 zips lists at runtime. → One hearth macro; recursion handled - inside the macro (`jsonFormatRec` kept as a deprecated alias of `jsonFormatN`). -6. scalacheck: different generators per version. → kindlings on both. -7. Tests: enum-related tests use enumeratum on Scala 2 and native enums on Scala 3. → Shared tests (`src/test/scala`) - exercising sealed-trait enums and enumeratum on both versions; Scala 3 `enum` tests stay in `scala-3/`. - -### 4.3 Gaps to fill - -- play-json auto-derivation (#384) — §5.4. -- jsoniter-scala module (#255) on kindlings. Contributor PR #531 (built on jsoniter's own macros) is closed with - thanks and credit in the release notes; its tests are reused where they fit. -- http4s: value-enum path matchers and `QueryParamDecoder` (parity with http4s-stir/pekko-http). -- pureconfig: `EnumLike`, `ValueEnumLike` and `InstanceConverter` readers/writers. -- scalacheck: `Arbitrary` for `EnumLike`, `ValueEnumLike` and `InstanceConverter` types. -- `EnumLike` lookups (`withNameInsensitiveOption`, upper/lower variants) use precomputed maps instead of linear scans. -- #417 is closed by the rewrite (no anonymous classes duplicated per inline site). -- #410 (sbt-typelevel) is already done — close it. - -## 5. Design - -### 5.1 Delivery - -**Approaches considered** - -- **A. One module per PR, straight into master** (picked). First PR switches the build and ports core; master - becomes 3.0-SNAPSHOT; 2.x fixes come from `series/2.x` cut at v2.3.0. Small reviewable PRs, both Scala versions - green at every step. -- B. Same PRs into a long-lived `kebs-3` branch merged at the end. Keeps master releasable as 2.x but needs rebasing. -- C. One big PR. Fast to start, hard to review and to bisect. - -**Order** - -0. **2.3.0 release** (on master, before any kebs 3 change): merge open Steward PRs except doobie RC13/RC14 (#556, - #611 — package relocation, breaking) and scala-library 3.10 (#604 — 2.x stays on 3.3 LTS). Set - `tlBaseVersion := "2.3"`, `tlMimaPreviousVersions := Set("2.2.2")`, README versions; maintainer confirms before - merges and before pushing tag `v2.3.0`. Cut `series/2.x` from the tag. -1. **Spike** (throwaway, worktree): see §7. -2. **PR: build + core** — Scala 3.9.0, JDK 17/21, `tlBaseVersion := "3.0"`, MiMa off, hearth + cross-quotes plugin - wiring, drop akka-http, doobie RC14 migration (`org.typelevel.doobie`), core `ValueClassLike` on hearth. -3. **PR: enum + enumeratum** on hearth; `EnumLike` map-based lookups; shared enum tests. -4. **PR: naming** — `Naming`, `EnumNaming`, `JsonConfig` in core (§5.3); enum codecs in every module (circe, spray, - play, doobie, baklava, pekko-http, http4s, http4s-stir, slick) moved onto `EnumNaming`. -5. **PR: spray-json** hearth macro (§5.4). -6. **PR: play-json** auto-derivation (§5.4). -7. **PR: circe** on kindlings (§5.4). -8. **PR: jsoniter** new module (§5.4). -9. **PR: scalacheck** on kindlings + enum/`InstanceConverter` arbitraries. -10. **PR: small gaps** — http4s value enums, pureconfig enum/`InstanceConverter`. -11. **Release** — docs for every module, a "Migrating to kebs 3" page, README; `v3.0.0-RC1`, then `v3.0.0`. - -Each PR keeps every existing test green on 2.13 and 3.9 (JVM; JS/Native where the module has them). - -### 5.2 Build - -- `scala_3 = "3.9.0"`; drop `-Xmax-inlines 64`/`-Yretain-trees` if no longer needed once inline derivation is gone. -- Modules containing hearth macros (core, enum, enumeratum, spray-json, play-json) get `"com.kubuszok" %%% "hearth"` and, - on Scala 3, `compilerPlugin("com.kubuszok" % "hearth-cross-quotes_3" % hearthV)`; on 2.13 they keep - `scala-reflect`/`scala-compiler % provided`. -- Layout per hearth macro: shared logic in `src/main/scala/.../internal/compiletime/*MacrosImpl.scala` - (`trait … { this: MacroCommons => … }`), entry points in `src/main/scala-2/…Compat.scala` and - `src/main/scala-3/…Compat.scala`. -- `disableScala(List("3"))` stays for jsonschema and tagged-meta; examples stay 2.13-only. - -### 5.3 Naming (core) - -A single vocabulary used for JSON field names, ADT case names and enum values, in `pl.iterators.kebs.core.naming`: - -```scala -final case class Naming(apply: String => String) { def andThen(that: Naming): Naming } -object Naming { - val identity, snakeCase, screamingSnakeCase, kebabCase, camelCase, pascalCase, lowercase, uppercase: Naming - def custom(f: String => String): Naming -} -``` - -- Word splitting lives in one place and reproduces today's `SnakifyVariant.snakify` exactly (so snake_case output does - not change for Scala 2 users); `capitalize` ≡ `pascalCase`. `SnakifyVariant`/`CapitalizeVariant` become deprecated - forwarders. -- **Enum values:** `final case class EnumNaming(naming: Naming, caseInsensitive: Boolean = true)`. Every enum codec in - every module takes an implicit `EnumNaming`; the companion holds the default (`identity`, case-insensitive), so a - user's implicit in lexical scope wins. Encoding writes `naming(name)`; decoding matches the mapped name (case- - insensitively by default — today the identity decoder is case-insensitive and upper/lower are strict; making all - lenient only accepts more input). The existing `enums.uppercase` / `enums.lowercase` objects become presets; new - presets for `snakeCase`, `screamingSnakeCase`, `kebabCase`. -- **JSON config:** one case class shared by all JSON modules: - - ```scala - final case class JsonConfig( - fieldNaming: Naming, - constructorNaming: Naming, // ADT case names - noneHandling: NoneHandling, // WriteNull | Omit - useDefaults: Boolean, // fill missing fields from case-class defaults - discriminator: Option[String] // None = wrapper object {"Case": {...}} - ) - ``` - - Each JSON protocol trait exposes an overridable `implicit def kebsJsonConfig: JsonConfig` with that module's default; - the presets (`snakified`, `capitalized`) override it. Users customise by overriding it in their protocol object, or - per type by passing a config to an explicit derivation method. (This replaces the separate `FieldNaming` / - `NoneHandling` implicits floated during discussion — one implicit is simpler to resolve unambiguously on 2.13.) -- **Module defaults preserve today's output:** - - | | fieldNaming | noneHandling | ADTs | - |---|---|---|---| - | circe | identity | WriteNull | wrapper (as circe-generic on 2.13 today) | - | spray-json | identity | Omit (`NullOptions` → WriteNull) | wrapper | - | play-json | identity | Omit (Play's convention) | wrapper | - | jsoniter (new) | identity | WriteNull (kindlings default, same as circe) | wrapper | - - `constructorNaming = identity`, `useDefaults = false`, `discriminator = None` everywhere. - -### 5.4 JSON modules - -Common rules for all four: - -- **Flatness is owned by kebs.** A single-field case class is encoded as its field only when a `ValueClassLike` is in - scope (`CaseClass1ToValueClass` mixed in), exactly as today. kindlings' own `AnyVal` unwrapping is turned off - (`unwrapValueClasses = false`) so `AnyVal` case classes without `CaseClass1ToValueClass` still encode as objects. -- **Existing instances win over kebs' auto-derivation — for the root type and for every field type.** That covers - user instances in companions (`Json.format`, circe `deriveEncoder`, Scala 3 `derives`, enumeratum's `CirceEnum` / - `PlayJsonEnum`, …), instances in lexical scope, and kebs' own flat / `InstanceConverter` / enum codecs. Mechanism: - - circe: auto entry points return `Exported[…]` (circe's low-priority hook; verified in the spike, §7.2). - - spray-json, play-json, jsoniter (no such hook): the auto entry point's macro first summons the type class for the - root type **ignoring its own entry point**; if something is found it returns that instance, otherwise it derives. - Because kindlings and our macros look up field instances through ordinary implicit search, which lands on kebs' - entry point, the same check makes companion instances win for fields too. - - Golden tests cover companion codecs, enumeratum `CirceEnum`/`PlayJsonEnum` and Scala 3 `derives`. - - Behaviour change to list in the migration guide: on **Scala 3**, kebs 2's circe auto-derivation beat companion - codecs (it sat in lexical scope); in kebs 3 companion codecs win, as they already did on Scala 2. -- Derivation is sanely-automatic where we own the macro (spray, play): the macro tries an implicit first (excluding - its own entry point), and derives otherwise, recursing internally — recursive types need no `lazy` tricks. -- **Per-field annotations are module-local, with consistent names**: each module has - `pl.iterators.kebs..annotations.{fieldName, transientField}`. - - circe and jsoniter: type aliases to kindlings' annotations (verified: aliased annotations are honoured by - kindlings on 2.13 and 3.9). jsoniter additionally aliases `named` and `stringified`. - - spray-json and play-json: one real pair of classes defined in core (`pl.iterators.kebs.core.annotations`) read by - our macros, aliased into both modules. -- ADT naming of cases uses `constructorNaming`; nested sealed hierarchies are flattened to their leaves (kindlings/ - circe semantics), in all four modules. - -Per module: - -- **circe** — `KebsCirce` keeps flat/`InstanceConverter` codecs and provides the auto entry point (implicit - `Exported[Encoder[A]]`/`Exported[Decoder[A]]` for case classes and sealed traits, see §7.2) backed by - `KindlingsEncoder`/`KindlingsDecoder.derived`, - with `JsonConfig` translated to kindlings' `Configuration` (`transformMemberNames`, `transformConstructorNames`, - `useDefaults`, `discriminator`, `unwrapValueClasses = false`). Drops the circe-generic and circe-generic-extras - dependencies. `NoneHandling.Omit` requires an upstream kindlings change (circe `transientNone`, which its jsoniter - module already has); until it is available, circe supports only `WriteNull` (today's behaviour) and `Omit` is a - compile-time error with a clear message. -- **spray-json** — hearth macro generating a `RootJsonFormat[T]` per case class (field-by-field `read`/`write`, no - 22-field limit, no runtime reflection) and per sealed hierarchy. Honors `JsonConfig` and the annotations. Missing - non-`Option` field without default → `DeserializationException` naming the field (same as spray's `fromField`). -- **play-json** — same macro shape producing `Reads`/`Writes`/`OFormat`; entry points `KebsPlayJson` (identity) plus - `snakified`/`capitalized` objects like the other JSON modules. Auto-derivation comes with the existing - `import pl.iterators.kebs.playjson._` / `KebsPlayJson` (decided 2026-11-21, for consistency with circe and spray); - existing `Json.format` / `PlayJsonEnum` instances keep winning (rule above), covered by golden tests, and the - migration guide calls out the new behaviour. -- **jsoniter** — `KebsJsoniter` provides flat/`InstanceConverter`/enum `JsonValueCodec`s and an auto entry point backed - by kindlings' jsoniter derivation, `JsonConfig` translated to `JsoniterConfig` (`withFieldNameMapper`, - `withAdtLeafClassNameMapper`, `withTransientNone` for `Omit`, discriminator/wrapper, defaults). Platforms JVM+JS+ - Native. - -### 5.5 Other modules - -- **core `ValueClassLike`** — hearth macro: for a case class with exactly one field, generates - `new ValueClassLike[T, F](v => T.apply(v), _.field)` (companion `apply`, direct accessor; no casts, no `Tuple1`). - The field type `F` must be inferred from `T` during implicit search on both versions (whitebox on 2.13; on Scala 3 a - transparent macro or retaining the `Mirror`-based type evidence while the body is macro-generated — the spike picks). - Non-case-classes and arity ≠ 1 fail fast and silently (they are implicit candidates in every flat-format search). -- **enum / enumeratum** — `EnumLike`/`ValueEnumLike` instances built from a static list of the cases (enumeratum: - `Companion.values`; `Enumeration`: `Obj.values.toList`; Scala 3 enums and `ValueEnumLikeEntry` hierarchies: the - cases in declaration order); - the name is `entryName` (enumeratum) or the case's simple name. Existing type bounds on the implicits stay, so the - enum and enumeratum implicits never compete. -- **scalacheck** — `ScalacheckInstancesSupport.arb[T]` delegates to kindlings' `Arbitrary` derivation; - `KebsArbitrarySupport` keeps its predefined instances and adds enum/`InstanceConverter` ones. -- **doobie** — migrated to doobie 1.0.0-RC14 (`org.typelevel` organisation, `org.typelevel.doobie` package). - -## 6. Behavioural spec and testing - -- Existing tests are the spec. They move from `scala-2/`/`scala-3/` into shared `src/test/scala` wherever the only - reason for the split was the macro implementation. Scala-3-only syntax (enums, opaque types) stays in `scala-3/`. -- New tests for every item in §4.2–§4.3 and §5.3–§5.4: naming presets and custom naming, annotations, `NoneHandling`, - `useDefaults`, ADTs (wrapper and discriminator, nested hierarchies, case objects), recursive types, >22 fields, - validating `apply` in `ValueClassLike`. -- **Wire-format golden tests**: for circe and spray-json, a fixed set of models encoded with kebs 2.3.0 output is - checked in as expected JSON; kebs 3 must produce identical JSON with default config. Any deliberate difference goes to - the migration guide. -- Compile-time regression check: a small benchmark (an existing test module's `Test/compile` time) recorded before and - after the circe and spray-json PRs, reported in the PR description. No hard threshold. - -### 6.1 Raising test coverage (requested 2026-11-21) - -- **`kebs-testkit`** — a test-only, unpublished cross-project (JVM/JS/Native) holding shared models and abstract - contract suites; modules depend on it `% "test->test"`. Created in the build + core PR. -- **Characterisation tests first** — golden JSON (circe, spray-json), enum strings (all enum-aware modules) and flat - formats are captured from current behaviour in the build + core PR, before any macro is swapped. -- **Contract suites** (each module plugs in its encode/decode or read/write functions): - - JSON (circe, spray-json, play-json, jsoniter): naming presets + custom, annotations, `NoneHandling`, `useDefaults`, - ADTs (wrapper, discriminator, nested, case objects), recursion (direct, mutual, generic, through `Option`/`Map`), - >22 and ~100 fields, flat value classes, `InstanceConverter`, enums, existing instances winning. - - Enums (circe, spray-json, play-json, jsoniter, doobie, slick, baklava, pekko-http, http4s, http4s-stir, - pureconfig, scalacheck): `EnumNaming` presets + custom, case-insensitive decoding, unknown values, for enumeratum, - `Enumeration`, Scala 3 `enum` and value enums. - - `ValueClassLike` / `InstanceConverter` across all integration modules. -- **Corner cases** (from hearth's derivation checklist): generic types, fixtures from another compilation unit, - private constructors and validating `apply`, zero-field classes, a user instance in the middle of a recursive - cycle, derivation inside generic functions. -- **Compile-time tests**: what must not compile, with the error message asserted (missing instance names the type and - field; no `ValueClassLike` for 2-field classes); stress — 100-field class and 100-case enum compile, no generated - method exceeds 8000 bytes (class-file `Code` attribute check). -- **Property-based round-trips** (encode→decode = identity) with generators from kebs-scalacheck. -- **Platforms**: shared suites also run on JS/Native for modules published there. -- **Line coverage**: sbt-scoverage, a CI coverage job on JVM for 2.13 and 3.9, reported per module; after 3.0 each - module's `coverageMinimumStmtTotal` is set just below what it reached (a ratchet). Line coverage cannot see macro - implementations (they run inside the compiler); for those, the contract suites and corner-case matrix are the - coverage. -- **doobie / slick value round-trips** against in-memory H2 (no Docker): today's doobie tests only assert that - `Get`/`Put` instances resolve (0% statement coverage) and slick's mostly that column types resolve (15%), so no - value is ever actually mapped. Postgres-specific types (slick-pg, doobie-postgres arrays) stay compile-level. -- Out of scope: Testcontainers / a real Postgres. - -**Baseline (master @ v2.2.2, Scala 2.13, JVM, scoverage statement / branch):** - -| Module | stmt | branch | Module | stmt | branch | -|---|---|---|---|---|---| -| core | 56% | 82% | http4s | 64% | 50% | -| instances | 84% | 100% | http4s-stir | 82% | 100% | -| enum | 100% (no runtime code) | – | pekko-http | 82% | 100% | -| enumeratum | 57% | 50% | akka-http | 86% | 100% | -| circe | 97% | 100% | slick | 15% | 0% | -| spray-json | 100% | 100% | doobie | 0% | 0% | -| play-json | 96% | 100% | baklava | 100% | 100% | -| scalacheck | 58% | 27% | pureconfig | 100% | 100% | -| jsonschema | 0% | 0% | tagged | 5% | 100% | -| tagged-meta | 93% | 82% | | | | - -High numbers in the JSON modules mostly reflect how little runtime code they have; their real logic is macro code, -which line coverage cannot see. - -## 7. Spike results (2026-11-21) - -Throwaway sbt project (2.13.18 + 3.9.0, hearth 0.4.5, kindlings-circe 0.4.0); all 9 tests green on both versions. - -1. **`ValueClassLike` with inferred `F`: works.** Shared hearth macro (`CaseClass.parse`, single primary-constructor - parameter, `Expr.quote { new ValueClassLike[T, F](…) }`). Entry points: - - 2.13: `implicit def repFromCaseClass[T <: Product, F1]: ValueClassLike[T, F1] = macro …` with a **whitebox** - bundle extending `hearth.MacroCommonsScala2`. - - 3.9: keep the `Mirror` evidence for inference and candidate filtering, body is the macro: - `inline implicit def repFromCaseClass[T <: Product, F1](using m: Mirror.ProductOf[T], teq: m.MirroredElemTypes =:= F1 *: EmptyTuple.type): ValueClassLike[T, F1] = ${ … }`. - A non-transparent inline given is expanded *after* it is selected, so the `Mirror` guard is what keeps non- - matching types from reaching the macro (a macro abort there would be a hard error, not a skipped candidate). - - Works through an outer implicit with unknown `A` (`find[T, A](implicit rep: ValueClassLike[T, A])`) and for - `ValueClassLike[T, ?]`; 2-field case classes get no instance. - - Cross-quotes gotcha on 2.13: `import field.tpe.Underlying as F` (nested path) breaks `Type.of[…F…]`; bind the - path first: `val fieldType: ?? = field.tpe; import fieldType.Underlying as F`. - - The spike constructs with `new T(…)`; the real implementation must call the companion `apply` (§4.2.1). -2. **kindlings circe inside a kebs trait: works, with one required design choice.** kebs' auto entry points must - return circe's `io.circe.export.Exported[Encoder[A]]` / `Exported[Decoder[A]]` (picked up by circe's low-priority - `importedEncoder`/`importedDecoder`), exactly like circe-generic's auto derivation. With a plain lexical implicit, - the imported kebs auto-derivation beats a user's instance in the type's companion. With `Exported`: - - companion instances win, at the top level and for fields; - - kebs' flat formats are used for fields (kindlings summons field instances first); - - recursive types, >22 fields, sealed traits (wrapper) work; - - entry-point guard: 2.13 macro aborts unless the type is a case class or sealed (candidate skipped); 3.9 uses - `inline m: Mirror.Of[A]`. - - **Semantics to keep and document:** with `CaseClass1ToValueClass` in scope, single-field ADT children are flat - too (`{"Dot":2.0}`), consistent with "every single-field case class is a value class". - - Nested derived types are expanded through kebs' entry point (one expansion per type, as in classic auto - derivation) because kindlings ignores only its own implicits. Acceptable; optional upstream improvement in §8. -3. **Aliased kindlings annotations: work** on 2.13.18 and 3.9.0 (`type fieldName = …circederivation.annotations.fieldName`). -4. **kindlings' 3.8.4-built artifacts from 3.9.0: work.** - -Consequence for spray-json, play-json and jsoniter: neither library has circe's `Exported` hook, so the auto entry -point's macro summons the root type class ignoring itself and returns what it finds, deriving only when nothing is -found (§5.4). No failure during implicit search is needed, so a plain `inline` entry point with a `Mirror.Of` guard -works on Scala 3. Verify with a spray-json test first in its PR. - -## 8. Upstream (kindlings) - -- Request: `transientNone`-style option for circe derivation (drop `None` fields when encoding). Needed for - `NoneHandling.Omit` in kebs-circe; not blocking the release. -- Optional request: a way for a wrapping library to add its own entry points to the implicits kindlings ignores when - summoning field instances (e.g. a `-Xmacro-settings` key or an annotation), so nested types are derived inside one - expansion instead of through kebs' entry point. Performance only; not blocking. -- Request: an `unwrapValueClasses`-style switch in kindlings' jsoniter derivation (0.4.0 always encodes `AnyVal` case - classes as their bare field). Until then kebs-jsoniter documents the exception: `AnyVal` case classes are flat in - jsoniter even without `CaseClass1ToValueClass`. New module, so no wire-compatibility impact. - -**Policy:** kebs 3.0 takes newer kindlings/hearth releases if they land before the release (hearth and kindlings -bumped together, all kebs hearth macros re-tested). Upstream requests never block 3.0: the fallback is a documented -per-module exception, not our own circe/jsoniter macros (writing those would defeat the "less code" goal). - -## 9. Left to the builder - -- Internal structure of the hearth macros (rules, caching), within the layout in §5.2. -- Exact names of explicit per-type derivation methods (e.g. `deriveEncoder[T](config)`), as long as they are consistent - across the four JSON modules. -- Whether `-Xmax-inlines`/`-Yretain-trees` can be dropped. -- Error message wording, as long as it names the type and the missing instance. diff --git a/design/plans/2026-11-21-plan-0-release-2.3.0.md b/design/plans/2026-11-21-plan-0-release-2.3.0.md deleted file mode 100644 index 68a95e19..00000000 --- a/design/plans/2026-11-21-plan-0-release-2.3.0.md +++ /dev/null @@ -1,106 +0,0 @@ -# Plan 0 — kebs 2.3.0 release (dependency bumps) Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Release kebs 2.3.0 from master with the pending dependency updates, then cut `series/2.x` so master can become 3.0-SNAPSHOT. - -**Architecture:** Operational plan — merge Scala Steward PRs, verify, prepare the release commit, tag, publish the drafted GitHub release, branch. No library code changes. - -**Tech Stack:** sbt 1.12.13, sbt-typelevel 0.8.7 (`tlBaseVersion`, `tlMimaPreviousVersions`, tag-triggered publishing), `gh` CLI. - -**Spec:** `design/2026-11-21-kebs-3-design.md` §5.1 step 0. - -## Global Constraints - -- 2.x stays on Scala 3.3 LTS (`scala_3 = "3.3.x"`) and Scala 2.13.18; JDK 11 + 17 in CI. -- Repo convention: squash merges titled ` (#N)`. -- **Every merge, every push to master, the tag push and the release publish need the maintainer's explicit go-ahead in the session** (outward-facing, hard to reverse). -- `ci.yml` is generated (sbt-github-actions); never hand-edit. The local `gh` token lacks the `workflow` scope: merging a PR that touches `.github/workflows/` fails — ask the maintainer to run `! gh auth refresh -h github.com -s workflow`. None of the PRs below touch workflows. -- Release process (from the 2.2.0 release): prep commit on master bumping `tlBaseVersion`, `tlMimaPreviousVersions`, README install-snippet versions; run `sbt +mimaReportBinaryIssues` locally before tagging; push tag `vX.Y.Z` (CI publishes to Maven Central); publish the Release Drafter draft with `gh release edit --tag vX.Y.Z --title "vX.Y.Z 🥙" --draft=false --latest`. - -## Review Focus - -- A Steward PR built against a newer Scala 3 (TASTy too new for 3.3) — CI fails with "TASTy signature has wrong version". Expected: not merged into 2.x (this is why #610 scala-java-time 2.11.0 is excluded). Re-check after each merge that master CI stays green. -- Two PRs editing adjacent lines of `build.sbt` — the second merge conflicts. Expected: resolve on the Steward branch (`gh pr checkout N`, rebase on master, push over SSH) or ask Steward to rebase; never push the PR content straight to master. -- MiMa against 2.2.2 reports a binary break caused by a dependency bump (e.g. http4s-stir 0.5 → 0.7 is early-semver-major for that library). Expected: kebs' own API unchanged → no MiMa problems in kebs artifacts; if MiMa does flag kebs classes, stop and report to the maintainer before tagging. -- The tag CI run fails mid-publish. Expected: do not re-tag blindly; report and investigate (Sonatype staging state). -- `series/2.x` branch name already exists on the remote. Expected: check first (`git ls-remote --heads origin series/2.x`), and ask if it exists. - ---- - -### Task 1: Merge the dependency PRs - -**PRs to merge (all CI-green or infra-flake only, as of 2026-11-21):** #607 (Scala 3.3.9), #596 (circe 0.14.17), #595 (pekko 1.7.1), #600 (pekko-http 1.4.2), #603 (pureconfig 0.17.11), #613 (http4s-dsl 0.23.39), #605 (http4s-stir 0.7.1), #612 (baklava-core 2.4.0), #602 (scalacheck-derived 0.11.0), #592 (magnolify-scalacheck 0.9.8), #614 (sbt-scalajs 1.23.0), #615 (sbt-jmh 0.4.9). - -**Not merged (left open for kebs 3):** #610 scala-java-time 2.11.0 (built with Scala 3.9), #611 / #556 doobie RC14 / RC13 (package relocation, breaking), #604 scala-library 3.10.0, #531 jsoniter (contributor PR, superseded by the kebs 3 jsoniter module — closed in the kebs 3 jsoniter plan with credit). - -- [ ] **Step 1: Re-run the failed "Validate Steward Config" check on #612** - -Run: `gh run rerun 44217261099 --failed` -Expected: the job passes (the failure was a coursier download error, not a code problem). Check with `gh pr checks 612`. - -- [ ] **Step 2: Get the maintainer's go-ahead to merge the 12 PRs listed above** - -- [ ] **Step 3: Merge each PR, one at a time, re-checking mergeability between merges** - -Run, per PR: `gh pr view N --json mergeable --jq .mergeable` → expect `MERGEABLE`; then -`gh pr merge N --squash --subject " (#N)"`. -If a PR becomes `CONFLICTING`, resolve as described in Review Focus, wait for its CI, then merge. - -- [ ] **Step 4: Verify master locally on both Scala versions** - -Run: `git checkout master && git pull --ff-only && sbt +test` -Expected: all tests pass on 2.13.18 and 3.3.9. - -- [ ] **Step 5: Verify master CI** - -Run: `gh run list --branch master --limit 3` -Expected: the latest CI run on master is `success`. - -### Task 2: Release commit, tag, GitHub release - -- [ ] **Step 1: Check binary compatibility against 2.2.2 before bumping** - -Run: `sbt +mimaReportBinaryIssues` -Expected: no binary incompatibilities reported for kebs modules. - -- [ ] **Step 2: Prepare the release commit** - -In `build.sbt`: `ThisBuild / tlBaseVersion := "2.3"` and `ThisBuild / tlMimaPreviousVersions := Set("2.2.2")`. -In `README.md`: install-snippet versions → `2.3.0`. -Commit message: `Update version to 2.3.0, bump MiMa previous to 2.2.2`. - -- [ ] **Step 3: Re-run MiMa with the new settings** - -Run: `sbt +mimaReportBinaryIssues` -Expected: no issues. - -- [ ] **Step 4: Get the maintainer's go-ahead, then push the commit and the tag** - -Run: `git push origin master && git tag v2.3.0 && git push origin v2.3.0` - -- [ ] **Step 5: Watch the tag's CI run until publishing finishes** - -Run: `gh run list --branch v2.3.0 --limit 1` then `gh run watch ` -Expected: `success`; artifacts appear under `https://repo1.maven.org/maven2/pl/iterators/kebs-core_3/2.3.0/` (may take up to ~30 min to sync). - -- [ ] **Step 6: Publish the drafted release** - -Run: `gh release list --limit 3` (find the Release Drafter draft), then -`gh release edit --tag v2.3.0 --title "v2.3.0 🥙" --draft=false --latest` -Expected: `gh release view v2.3.0` shows a published release with the changelog. - -### Task 3: Cut `series/2.x` and tidy the issue tracker - -- [ ] **Step 1: Check the branch name is free** - -Run: `git ls-remote --heads origin series/2.x` -Expected: no output. - -- [ ] **Step 2: Create and push `series/2.x` from the tag (maintainer go-ahead)** - -Run: `git branch series/2.x v2.3.0 && git push origin series/2.x` - -- [ ] **Step 3: Close #410 (sbt-typelevel migration — already done) with a short comment (maintainer go-ahead)** - -Run: `gh issue close 410 --comment "Done — kebs builds with sbt-typelevel (sbt-typelevel-ci-release 0.8.7)."` diff --git a/design/plans/2026-11-21-plan-1-build-core-testkit.md b/design/plans/2026-11-21-plan-1-build-core-testkit.md deleted file mode 100644 index f3969605..00000000 --- a/design/plans/2026-11-21-plan-1-build-core-testkit.md +++ /dev/null @@ -1,345 +0,0 @@ -# Plan 1 — kebs 3: build switch, core `ValueClassLike` on hearth, testkit + golden tests — Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Turn master into kebs 3.0-SNAPSHOT on Scala 2.13.18 + 3.9.0 / JDK 17+, port core's `ValueClassLike` macro to hearth, drop akka-http, migrate doobie to RC14, and pin today's JSON wire format with golden tests before any other macro is rewritten. - -**Architecture:** One PR ("kebs 3: build + core"). Build changes first, then the first hearth macro (shared logic in `src/main/scala`, thin `scala-2`/`scala-3` entry points), then a test-only `kebs-testkit` cross-project with shared models, and golden tests that capture current circe / spray-json / play-json output. - -**Tech Stack:** sbt 1.12.13, sbt-typelevel 0.8.7, Scala 2.13.18 / 3.9.0, hearth 0.4.5 (+ `hearth-cross-quotes_3` compiler plugin), scalatest 3.2.20, doobie 1.0.0-RC14. - -**Spec:** `design/2026-11-21-kebs-3-design.md` (§3 constraints, §4.2.1, §5.1 step 2, §5.2, §5.5 core, §6, §6.1, §7.1). - -**Prerequisite:** Plan 0 done (v2.3.0 tagged, `series/2.x` cut). Work on branch `kebs-3/build-core` from master. - -## Global Constraints - -- Scala versions: `scala_2_13 = "2.13.18"`, `scala_3 = "3.9.0"`. JDK 17 and 21 in CI. -- `tlBaseVersion := "3.0"`; MiMa off for 3.0.0 (`tlMimaPreviousVersions := Set.empty`). -- hearth `0.4.5` exactly (kindlings 0.4.0 depends on it; later plans add kindlings at the same hearth version). -- Every existing test stays green on 2.13 and 3.9 (JVM; JS/Native for modules that have them). -- Golden tests capture **current** behaviour. If current output differs from a literal in this plan, stop and report it — never adjust a literal to make a golden test pass without the maintainer's decision. -- `ci.yml` is generated: change `build.sbt`, run `sbt githubWorkflowGenerate`, commit the result. Pushing/merging changes to `.github/workflows/` needs the `workflow` token scope — ask the maintainer to run `! gh auth refresh -h github.com -s workflow` before opening the PR. -- Do not put planning/design files under `docs/` (mdoc publishes everything there). -- Scalafmt runs on compile; commit formatted code. - -## Review Focus - -- **Case class with a validating or normalising companion `apply`** (e.g. `object Email { def apply(v: String) = new Email(v.toLowerCase) }`). Expected: `ValueClassLike.apply` goes through it on both Scala versions (Scala 3 used to bypass it). Pinned in Task 3. -- **Generic single-field case class** (`Box[A](a: A)`) and one **defined in another compilation unit** (testkit). Expected: `ValueClassLike[Box[Int], Int]` and `ValueClassLike[testkit.Id, String]` resolve. Pinned in Task 3 (`Box`) and Task 4 (`person flat` resolves `ValueClassLike` for `testkit.model.Id`, compiled in another module; core's own tests cannot depend on testkit without a cycle). -- **Flat-format search over every type** — `flatDecoder[T, A](implicit rep: ValueClassLike[T, A], …)` is tried for `Int`, `List[X]`, 2-field case classes, sealed traits. Expected: no instance and no compile error for those (the existing JSON/HTTP test suites exercise this heavily; they must stay green). Pinned by Task 3's `assertDoesNotCompile` cases plus the full `+test` run. -- **A field the goldens don't cover changes encoding after Scala 3.9** (e.g. `Option` inside a flat value class). Expected: same JSON as 2.3.0. Goldens include `Option` fields, flat value classes, enums, >22 fields and an `InstanceConverter` type (Tasks 4–6). -- **JS/Native builds** of core with the hearth dependency. Expected: `coreJS/test` and `coreNative/test` pass (hearth is published for both). Pinned in Task 3 Step 6. - ---- - -### Task 1: Scala 3.9, JDK 17/21, version 3.0, doobie RC14, scala-java-time 2.11 - -**Files:** -- Modify: `build.sbt` (`scala_3`, `tlBaseVersion`, `tlMimaPreviousVersions`, `githubWorkflowJavaVersions`, doobie and scala-java-time coordinates, Scala 3 `-Ykind-projector` → `-Xkind-projector` in `commonSettings`) -- Modify: `doobie/src/main/scala/pl/iterators/kebs/doobie/KebsDoobie.scala`, `doobie/src/main/scala/pl/iterators/kebs/doobie/enums/KebsDoobieEnums.scala`, and the doobie test sources (6 `import doobie…` lines in total) -- Modify: `.github/workflows/ci.yml` (regenerated) - -- [ ] **Step 1: Apply the build changes** - -`val scala_3 = "3.9.0"`; `ThisBuild / tlBaseVersion := "3.0"`; `ThisBuild / tlMimaPreviousVersions := Set.empty`; -`ThisBuild / githubWorkflowJavaVersions := Seq(JavaSpec.temurin("17"), JavaSpec.temurin("21"))`; -`val doobie = "org.typelevel" %% "doobie-core" % "1.0.0-RC14"`, `val doobiePg = "org.typelevel" %% "doobie-postgres" % "1.0.0-RC14"`; -`scalaJavaTime` → `"2.11.0"`. - -- [ ] **Step 2: Run the doobie module to see the expected failure** - -Run: `sbt "++3.9.0" doobieSupport/Test/compile` -Expected: FAIL — `Not found: doobie` in `KebsDoobie.scala:3` and `KebsDoobieEnums.scala:3`. - -- [ ] **Step 3: Move doobie imports to the relocated package** - -Every `import doobie.X` / `import doobie._` / `import doobie.implicits._` / `import doobie.postgres._` becomes `import org.typelevel.doobie.X` / `org.typelevel.doobie._` / `org.typelevel.doobie.implicits._` / `org.typelevel.doobie.postgres._` (package verified in the RC14 jar: `org/typelevel/doobie/**`). - -- [ ] **Step 4: Run all tests on both Scala versions (JVM)** - -Run: `sbt +test` -Expected: PASS on 2.13.18 and 3.9.0. New Scala 3.9 deprecation warnings (`_` wildcard in types, `with` type operator, implicit args without `using`) are acceptable in this task. - -- [ ] **Step 5: Regenerate CI and commit** - -Run: `sbt githubWorkflowGenerate` -```bash -git add build.sbt doobie .github/workflows/ci.yml -git commit -m "kebs 3: Scala 3.9.0, JDK 17/21, version 3.0, doobie 1.0.0-RC14" -``` - -### Task 2: Drop akka-http - -**Files:** -- Delete: `akka-http/` -- Modify: `build.sbt` (remove `akkaHttpSupport`, `akkaHttpSettings`, `akkaVersion`, `akkaHttpVersion`, `akkaStream`, `akkaStreamTestkit`, `akkaHttp`, `akkaHttpTestkit`, `akkaHttpInExamples`, and `akkaHttpSupport` from the root `aggregate`) -- Rename: `docs/akka-http.md` → `docs/pekko-http.md` (title `Pekko HTTP`, heading `# kebs-pekko-http`, remove the Akka setup line and "Akka" wording) -- Modify: `docs/http4s.md` (link `akka-http.md#path-matchers` → `pekko-http.md#path-matchers`, "Akka/Pekko HTTP matchers" → "Pekko HTTP matchers"; keep "Akka HTTP-style directives" — that describes http4s-stir's style), `docs/core-concepts.md` ("circe, slick, akka-http, etc." → "circe, slick, pekko-http, etc."), `README.md` (remove the `kebs-akka-http` row) -- Modify: `.github/workflows/ci.yml` (regenerated) - -- [ ] **Step 1: Remove the module, its build definitions and docs references as listed above** - -- [ ] **Step 2: Verify nothing references akka any more** - -Run: `grep -rni "akka" --include=*.sbt --include=*.scala --include=*.md . | grep -v "/target/" | grep -vi "akka http-style"` -Expected: no output. - -- [ ] **Step 3: Verify the build and docs** - -Run: `sbt projects +compile docs/mdoc` -Expected: no `akkaHttpSupport` in the project list; compile and mdoc succeed. - -- [ ] **Step 4: Regenerate CI and commit** - -Run: `sbt githubWorkflowGenerate` -```bash -git add -A build.sbt akka-http docs README.md .github/workflows/ci.yml -git commit -m "kebs 3: drop kebs-akka-http (use kebs-pekko-http)" -``` - -### Task 3: hearth wiring + `ValueClassLike` on hearth - -**Files:** -- Modify: `build.sbt` — `coreSettings`: add `libraryDependencies += "com.kubuszok" %%% "hearth" % hearthV` (`val hearthV = "0.4.5"`), on Scala 3 `compilerPlugin("com.kubuszok" % "hearth-cross-quotes_3" % hearthV)`, `scalaTest.value % "test"`; `baseSettings` on 2.13: add `"-Xsource:3"` and `"-Wconf:cat=scala3-migration:s"` -- Create: `core/src/main/scala/pl/iterators/kebs/core/macros/ValueClassLike.scala` -- Create: `core/src/main/scala/pl/iterators/kebs/core/macros/internal/ValueClassLikeMacrosImpl.scala` -- Create: `core/src/main/scala-2/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala` -- Create: `core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala` -- Delete: `core/src/main/scala-2/pl/iterators/kebs/core/macros/ValueClassReps.scala`, `core/src/main/scala-3/pl/iterators/kebs/core/macros/ValueClassReps.scala` -- Keep: `core/src/main/scala-2/pl/iterators/kebs/core/macros/MacroUtils.scala` (still used by the Scala 2 circe/spray/enumeratum/jsonschema macros until their plans) -- Test: `core/src/test/scala/pl/iterators/kebs/core/ValueClassLikeTests.scala` - -**Interfaces:** -- Produces (public, unchanged names): `final class ValueClassLike[VC, F1](val apply: F1 => VC, val unapply: VC => F1)`; `trait CaseClass1ToValueClass { implicit def repFromCaseClass[VC <: Product, F1]: ValueClassLike[VC, F1] }` (Scala 2 signature) / `inline implicit def repFromCaseClass[T <: Product, F1](using m: Mirror.ProductOf[T], teq: m.MirroredElemTypes =:= F1 *: EmptyTuple.type): ValueClassLike[T, F1]` (Scala 3); `object CaseClass1ToValueClass extends CaseClass1ToValueClass`. -- Produces (internal, reused by later plans as the pattern): `private[kebs] trait ValueClassLikeMacrosImpl { this: hearth.MacroCommons => def deriveValueClassLike[T: Type]: Expr_?? }` returning an existential `Expr[ValueClassLike[T, F]]`. - -- [ ] **Step 1: Write the failing tests** - -```scala -package pl.iterators.kebs.core - -import org.scalatest.funsuite.AnyFunSuite -import org.scalatest.matchers.should.Matchers -import pl.iterators.kebs.core.macros.{CaseClass1ToValueClass, ValueClassLike} - -object ValueClassLikeTestDomain { - final case class Plain(value: String) - final case class Box[A](a: A) - final case class Positive(value: Int) - object Positive { def apply(value: Int): Positive = { require(value > 0, "must be positive"); new Positive(value) } } - final case class Email(value: String) - object Email { def apply(value: String): Email = new Email(value.toLowerCase) } - final case class Two(a: Int, b: Int) - final class NotCase(val value: Int) -} - -class ValueClassLikeTests extends AnyFunSuite with Matchers with CaseClass1ToValueClass { - import ValueClassLikeTestDomain._ - - test("derives apply/unapply for a single-field case class") { - val rep = implicitly[ValueClassLike[Plain, String]] - rep.apply("a") shouldBe Plain("a") - rep.unapply(Plain("b")) shouldBe "b" - } - test("infers the field type through an outer implicit") { - def find[T, A](implicit rep: ValueClassLike[T, A]): ValueClassLike[T, A] = rep - find[Plain, String].unapply(Plain("c")) shouldBe "c" - } - test("generic case class") { - implicitly[ValueClassLike[Box[Int], Int]].apply(1) shouldBe Box(1) - } - test("uses the companion apply (validation)") { - val rep = implicitly[ValueClassLike[Positive, Int]] - an[IllegalArgumentException] should be thrownBy rep.apply(-1) - } - test("uses the companion apply (normalisation)") { - implicitly[ValueClassLike[Email, String]].apply("A@B.PL").value shouldBe "a@b.pl" - } - test("no instance for a 2-field case class or a non-case class") { - assertDoesNotCompile("implicitly[ValueClassLike[Two, Int]]") - assertDoesNotCompile("implicitly[ValueClassLike[NotCase, Int]]") - } -} -``` - -- [ ] **Step 2: Run them to see the expected failure** - -Run: `sbt "++3.9.0" core/testOnly pl.iterators.kebs.core.ValueClassLikeTests` -Expected: FAIL — "uses the companion apply (validation)" and "(normalisation)" fail on Scala 3 (today's `Mirror.fromProduct` bypasses `apply`). (On 2.13 they already pass.) - -- [ ] **Step 3: Wire hearth into the build** (the `build.sbt` changes listed under Files) - -- [ ] **Step 4: Implement the shared macro and both entry points** - -`ValueClassLikeMacrosImpl.deriveValueClassLike[T]` (see design §7.1 for the shape proven in the spike): -1. `CaseClass.parse[T]`; not a case class → `Environment.reportErrorAndAbort` naming the type. -2. Exactly one parameter across the primary constructor's parameter lists, else abort. -3. Bind the field type without a nested path (`val fieldType: ?? = field.tpe; import fieldType.Underlying as F` — `import field.tpe.Underlying as F` breaks cross-quotes on 2.13). -4. Construct via the companion's `apply` taking exactly one parameter of type `F` (`Type[T].unsortedMethodsNamed("apply")`, then `Method.ApplyValues#apply(Map(name -> arg.as_??))` / `build()`), applying `T`'s type arguments for generic case classes; fall back to `CaseClass.construct` only when no such `apply` is callable at the call site. -5. Read the field with `caseClass.caseFieldValuesAt(t)`. -6. Return `Expr.quote { new ValueClassLike[T, F]((f: F) => …, (t: T) => …) }.as_??`. - -Scala 2 entry point: `implicit def repFromCaseClass[VC <: Product, F1]: ValueClassLike[VC, F1] = macro ValueClassRepMacros.materializeValueClassRep[VC, F1]` with `class ValueClassRepMacros(val c: whitebox.Context) extends hearth.MacroCommonsScala2 with ValueClassLikeMacrosImpl` (**whitebox** is required so `F1` is inferred). -Scala 3 entry point: the `inline implicit def` from Interfaces, body `${ ValueClassLikeMacros.materialize[T, F1] }` with `class ValueClassLikeMacros(q: Quotes) extends hearth.MacroCommonsScala3(using q), ValueClassLikeMacrosImpl`. The `Mirror` evidence stays: it drives inference of `F1` and keeps non-matching types from reaching the macro. - -- [ ] **Step 5: Run the new tests and the whole build on both versions** - -Run: `sbt core/testOnly pl.iterators.kebs.core.ValueClassLikeTests "++3.9.0" core/testOnly pl.iterators.kebs.core.ValueClassLikeTests` then `sbt +test` -Expected: PASS everywhere. - -- [ ] **Step 6: Run core on JS and Native** - -Run: `sbt +coreJS/test +coreNative/test` -Expected: PASS. - -- [ ] **Step 7: Commit** - -```bash -git add build.sbt core -git commit -m "kebs 3: ValueClassLike on hearth (companion apply on both Scala versions)" -``` - -### Task 4: `kebs-testkit` + circe golden tests - -**Files:** -- Modify: `build.sbt` — new `lazy val testkit = crossProject(JSPlatform, NativePlatform, JVMPlatform).withoutSuffixFor(JVMPlatform).crossType(CrossType.Pure).in(file("testkit")).dependsOn(core).settings(commonSettings *).settings(noPublishSettings *).settings(name := "testkit", moduleName := "kebs-testkit", libraryDependencies += enumeratum.value)` with `crossScalaVersions := supportedScalaVersions`; add `testkit` to the root `aggregate`; `circeSupport` gets `.dependsOn(testkit % "test->compile")` -- Create: `testkit/src/main/scala/pl/iterators/kebs/testkit/model.scala` -- Create: `circe/src/test/scala/pl/iterators/kebs/circe/golden/CirceGoldenTests.scala` -- Create: `circe/src/test/scala-2/pl/iterators/kebs/circe/golden/CirceAdtGoldenTests.scala` - -**Interfaces:** -- Produces (`pl.iterators.kebs.testkit.model`, used by Tasks 5–6 and later plans): - - `final case class Id(value: String)` - - `final case class Person(id: Id, name: String, age: Int, nickname: Option[String])` - - `final case class Naming(someField: Int, anotherFieldName: String, field1Name: Int, httpURL: String)` - - `final case class Event(id: Id, at: java.time.Instant)` - - `final case class Wide(f1: Int, …, f22: Int, f23: Option[String])` (23 fields `f1`..`f22: Int`, `f23: Option[String]`) - - `sealed abstract class Color extends enumeratum.EnumEntry; object Color extends enumeratum.Enum[Color] { case object Red; case object DarkBlue; val values = findValues }` - - `sealed abstract class Level(val value: Int) extends enumeratum.values.IntEnumEntry with pl.iterators.kebs.core.enums.ValueEnumLikeEntry[Int]; object Level extends enumeratum.values.IntEnum[Level] { case object Low extends Level(1); case object High extends Level(2); val values = findValues }` - - `final case class Paint(color: Color, level: Level)` - - `sealed trait Shape; final case class Circle(r: Double, label: String) extends Shape; case object Empty extends Shape` - -- [ ] **Step 1: Write the golden tests** (expected JSON parsed and compared as `Json` values; decode must round-trip) - -Protocols: `object Default extends KebsCirce`, `object Flat extends KebsCirce with CaseClass1ToValueClass`, `pl.iterators.kebs.circe.snakified`, `pl.iterators.kebs.circe.capitalized`; enums via `KebsEnumeratum`/`KebsValueEnumeratum` with `pl.iterators.kebs.circe.enums._`, plus `enums.uppercase` and `enums.lowercase`; `Instant` via `pl.iterators.kebs.instances.KebsInstances`. - -| Test name | Protocol | Value | Expected JSON | -|---|---|---|---| -| `person default` | Default | `Person(Id("x"), "Ann", 30, None)` | `{"id":{"value":"x"},"name":"Ann","age":30,"nickname":null}` | -| `person flat` | Flat | `Person(Id("x"), "Ann", 30, Some("A"))` | `{"id":"x","name":"Ann","age":30,"nickname":"A"}` | -| `naming snakified` | snakified | `Naming(1, "a", 2, "u")` | `{"some_field":1,"another_field_name":"a","field1_name":2,"http_url":"u"}` | -| `naming capitalized` | capitalized | `Naming(1, "a", 2, "u")` | `{"SomeField":1,"AnotherFieldName":"a","Field1Name":2,"HttpURL":"u"}` | -| `enums` | Flat + enums | `Paint(Color.DarkBlue, Level.High)` | `{"color":"DarkBlue","level":2}` | -| `enums uppercase` | Flat + enums.uppercase | `Paint(Color.DarkBlue, Level.High)` | `{"color":"DARKBLUE","level":2}` | -| `enums lowercase` | Flat + enums.lowercase | `Paint(Color.DarkBlue, Level.High)` | `{"color":"darkblue","level":2}` | -| `instance converter` | Flat + KebsInstances | `Event(Id("e"), Instant.parse("2026-01-02T03:04:05Z"))` | `{"id":"e","at":"2026-01-02T03:04:05Z"}` | -| `wide (>22 fields)` | Default | `Wide(1, 2, …, 22, None)` | `{"f1":1,…,"f22":22,"f23":null}` | - -Also assert case-insensitive decoding of the default enum decoder: decoding `{"color":"darkblue","level":2}` with the default protocol gives `Paint(Color.DarkBlue, Level.High)`. - -`CirceAdtGoldenTests` (Scala 2 only — Scala 3 kebs 2 does not derive sealed traits; the circe plan moves it to shared), using the `Default` protocol (with `Flat`, single-field children would be flat): -`Circle(1.0, "c"): Shape` → `{"Circle":{"r":1.0,"label":"c"}}`; `Empty: Shape` → `{"Empty":{}}`. - -- [ ] **Step 2: Run them against the current implementation** - -Run: `sbt +circeSupport/testOnly "pl.iterators.kebs.circe.golden.*"` -Expected: PASS on both versions. Any mismatch → stop and report it with the actual output (see Global Constraints). - -- [ ] **Step 3: Commit** - -```bash -git add build.sbt testkit circe/src/test -git commit -m "kebs 3: kebs-testkit module and circe golden tests (2.x wire format)" -``` - -### Task 5: spray-json golden tests - -**Files:** -- Modify: `build.sbt` — `sprayJsonSupport` gets `.dependsOn(testkit.jvm % "test->compile")` -- Create: `spray-json/src/test/scala/pl/iterators/kebs/sprayjson/golden/SprayGoldenTests.scala` - -**Interfaces:** -- Consumes: `pl.iterators.kebs.testkit.model._` (Task 4). - -- [ ] **Step 1: Write the golden tests** (expected parsed with `JsonParser`, compared as `JsValue`; read must round-trip) - -Protocols: `object Default extends DefaultJsonProtocol with KebsSprayJson`, `object Flat extends DefaultJsonProtocol with KebsSprayJson with CaseClass1ToValueClass`, `object FlatNulls extends DefaultJsonProtocol with KebsSprayJson with CaseClass1ToValueClass with NullOptions`, `pl.iterators.kebs.sprayjson.snakified`, `pl.iterators.kebs.sprayjson.capitalized`; enums via `pl.iterators.kebs.sprayjson.enums._` (+ `uppercase`, `lowercase`); `KebsInstances` for `Instant`. - -| Test name | Protocol | Value | Expected JSON | -|---|---|---|---| -| `person default` | Default | `Person(Id("x"), "Ann", 30, None)` | `{"id":{"value":"x"},"name":"Ann","age":30}` | -| `person flat` | Flat | `Person(Id("x"), "Ann", 30, Some("A"))` | `{"id":"x","name":"Ann","age":30,"nickname":"A"}` | -| `person NullOptions` | FlatNulls | `Person(Id("x"), "Ann", 30, None)` | `{"id":"x","name":"Ann","age":30,"nickname":null}` | -| `naming snakified` | snakified | `Naming(1, "a", 2, "u")` | `{"some_field":1,"another_field_name":"a","field1_name":2,"http_url":"u"}` | -| `naming capitalized` | capitalized | `Naming(1, "a", 2, "u")` | `{"SomeField":1,"AnotherFieldName":"a","Field1Name":2,"HttpURL":"u"}` | -| `enums` / `enums uppercase` / `enums lowercase` | Flat + enums variants | `Paint(Color.DarkBlue, Level.High)` | `{"color":"DarkBlue","level":2}` / `"DARKBLUE"` / `"darkblue"` | -| `instance converter` | Flat + KebsInstances | `Event(Id("e"), Instant.parse("2026-01-02T03:04:05Z"))` | `{"id":"e","at":"2026-01-02T03:04:05Z"}` | -| `wide (>22 fields)` | Default | `Wide(1, …, 22, None)` | `{"f1":1,…,"f22":22}` | -| `wide NullOptions` | FlatNulls | `Wide(1, …, 22, None)` | `{"f1":1,…,"f22":22,"f23":null}` | - -- [ ] **Step 2: Run them against the current implementation** - -Run: `sbt +sprayJsonSupport/testOnly "pl.iterators.kebs.sprayjson.golden.*"` -Expected: PASS on both versions; any mismatch → stop and report. - -- [ ] **Step 3: Commit** - -```bash -git add build.sbt spray-json/src/test -git commit -m "kebs 3: spray-json golden tests (2.x wire format)" -``` - -### Task 6: play-json golden tests - -**Files:** -- Modify: `build.sbt` — `playJsonSupport` gets `.dependsOn(testkit % "test->compile")` -- Create: `play-json/src/test/scala/pl/iterators/kebs/playjson/golden/PlayJsonGoldenTests.scala` - -**Interfaces:** -- Consumes: `pl.iterators.kebs.testkit.model._` (Task 4). - -- [ ] **Step 1: Write the golden tests** — kebs 2 has no case-class derivation for play-json, so the goldens pin what kebs does provide, with user-written `Json.format` for case classes (this is also the coexistence the play-json plan must preserve): - -Protocol: `object Flat extends KebsPlayJson with CaseClass1ToValueClass`, `pl.iterators.kebs.playjson.enums._` (+ `uppercase`, `lowercase`), `KebsInstances`; in the test: `implicit val personFormat: OFormat[Person] = Json.format[Person]`, same for `Paint` and `Event`. - -| Test name | Value | Expected JSON | -|---|---|---| -| `flat value class` | `Id("x")` | `"x"` | -| `user Json.format with kebs field formats` | `Person(Id("x"), "Ann", 30, None)` | `{"id":"x","name":"Ann","age":30}` | -| `enums` / `uppercase` / `lowercase` | `Paint(Color.DarkBlue, Level.High)` | `{"color":"DarkBlue","level":2}` / `"DARKBLUE"` / `"darkblue"` | -| `instance converter` | `Event(Id("e"), Instant.parse("2026-01-02T03:04:05Z"))` | `{"id":"e","at":"2026-01-02T03:04:05Z"}` | - -- [ ] **Step 2: Run them against the current implementation (JVM and JS)** - -Run: `sbt +playJsonSupport/testOnly "pl.iterators.kebs.playjson.golden.*" +playJsonSupportJS/testOnly "pl.iterators.kebs.playjson.golden.*"` -Expected: PASS; any mismatch → stop and report. - -- [ ] **Step 3: Commit** - -```bash -git add build.sbt play-json/src/test -git commit -m "kebs 3: play-json golden tests (2.x wire format)" -``` - -### Task 7: Open the PR - -- [ ] **Step 1: Full verification** - -Run: `sbt +test +coreJS/test +coreNative/test docs/mdoc` -Expected: all green. - -- [ ] **Step 2: Push and open the PR (maintainer go-ahead; `workflow` scope needed for `ci.yml`)** - -```bash -git push -u origin kebs-3/build-core -gh pr create --base master --title "kebs 3: Scala 3.9, ValueClassLike on hearth, testkit + golden tests" --body-file <(…summary of Tasks 1–6, link to design/2026-11-21-kebs-3-design.md…) -``` -Expected: CI green on JDK 17 and 21. - ---- - -## Notes for later plans (not tasks here) - -- Enum-string goldens for the non-JSON modules (doobie, slick, baklava, pekko-http, http4s, http4s-stir) and the H2 value round-trips for doobie/slick are written at the start of the naming plan, before its enum-codec refactor (same "capture before change" rule). -- `MacroUtils` (Scala 2) is deleted once circe, spray-json and enumeratum no longer use it; jsonschema then gets its own copy of the two helpers it needs. diff --git a/play-json/src/test/scala/pl/iterators/kebs/playjson/golden/PlayJsonGoldenTests.scala b/play-json/src/test/scala/pl/iterators/kebs/playjson/golden/PlayJsonGoldenTests.scala index f7b5c947..1c1a2c3c 100644 --- a/play-json/src/test/scala/pl/iterators/kebs/playjson/golden/PlayJsonGoldenTests.scala +++ b/play-json/src/test/scala/pl/iterators/kebs/playjson/golden/PlayJsonGoldenTests.scala @@ -11,9 +11,7 @@ import play.api.libs.json._ import java.time.Instant -/** What kebs 2.x provides for play-json (flat value classes, enums, instance converters) next to user-written `Json.format` codecs. kebs 3 - * adds case-class derivation; these codecs must keep winning and keep this output. - */ +// kebs 2.x output next to user-written Json.format codecs (verified against v2.3.0); those codecs must keep winning over derivation class PlayJsonGoldenTests extends AnyFunSuite with Matchers { private def golden[A](value: A, expected: String)(implicit format: Format[A]): Unit = { format.writes(value) shouldBe Json.parse(expected) diff --git a/spray-json/src/test/scala/pl/iterators/kebs/sprayjson/golden/SprayGoldenTests.scala b/spray-json/src/test/scala/pl/iterators/kebs/sprayjson/golden/SprayGoldenTests.scala index 7f8350a1..f5cff4d2 100644 --- a/spray-json/src/test/scala/pl/iterators/kebs/sprayjson/golden/SprayGoldenTests.scala +++ b/spray-json/src/test/scala/pl/iterators/kebs/sprayjson/golden/SprayGoldenTests.scala @@ -12,9 +12,7 @@ import spray.json._ import java.time.Instant -/** Wire format of kebs 2.x (captured before the kebs 3 rewrite). kebs 3 must produce the same JSON with default configuration; a - * deliberate change belongs in the migration guide, not in a silently edited expectation. - */ +// kebs 2.x wire format (verified against v2.3.0); a deliberate change goes to the migration guide, not into these expectations class SprayGoldenTests extends AnyFunSuite with Matchers { private def golden[A](value: A, expected: String)(implicit format: JsonFormat[A]): Unit = { format.write(value) shouldBe expected.parseJson diff --git a/testkit/src/main/scala/pl/iterators/kebs/testkit/model.scala b/testkit/src/main/scala/pl/iterators/kebs/testkit/model.scala index 1c77f6ca..d403cf8e 100644 --- a/testkit/src/main/scala/pl/iterators/kebs/testkit/model.scala +++ b/testkit/src/main/scala/pl/iterators/kebs/testkit/model.scala @@ -6,16 +6,13 @@ import pl.iterators.kebs.core.enums.ValueEnumLikeEntry import java.time.Instant -/** Models shared by the golden and contract test suites of all kebs modules (compiled in a separate module on purpose: derivation must - * also work for types read from the classpath). - */ +// a separate module on purpose: derivation must also work for types read from the classpath object model { final case class Id(value: String) final case class Person(id: Id, name: String, age: Int, nickname: Option[String]) final case class Naming(someField: Int, anotherFieldName: String, field1Name: Int, httpURL: String) final case class Event(id: Id, at: Instant) - /** The usual validated value class: private constructor, smart constructor in the companion. */ final case class Email private (value: String) object Email { def from(value: String): Email = new Email(value.toLowerCase) From d5235414676ec4f253e2bf7791c6dd623b369d22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Sowa?= Date: Sat, 21 Nov 2026 12:23:21 +0000 Subject: [PATCH 10/10] Clarify why the Scala 3 ValueClassLike falls back to the Mirror Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFD5QTj91bQhcjiNo9n48K --- .../kebs/core/macros/CaseClass1ToValueClassCompat.scala | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala b/core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala index 11ba78ef..c4347962 100644 --- a/core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala +++ b/core/src/main/scala-3/pl/iterators/kebs/core/macros/CaseClass1ToValueClassCompat.scala @@ -6,7 +6,8 @@ import scala.deriving.Mirror import scala.quoted.* private[macros] trait CaseClass1ToValueClassCompat { - // selected via the Mirror, so the macro must not abort - it falls back to the Mirror instead + // selected via the Mirror, so the macro must not abort: a private/protected constructor or field is not accessible at + // the call site, but the Mirror's fromProduct (generated in the companion) is inline implicit def repFromCaseClass[T <: Product, F1](using m: Mirror.ProductOf[T], teq: m.MirroredElemTypes =:= F1 *: EmptyTuple.type