Repository navigation
Description
🤷 Motivation
We have types like JS Date or an internal LocalDate (only calendar dates, no times) that we want to encode/decode to JSON (or a string, like in a query string).
Libraries like Zod/Arktype/etc generally support deserialization, i.e. here's an unknown blob object literal, parse/safeParse it into my structure, and also transform the dueDate: "2024-01-01" key into --> dueDate: new LocalDate(...) during the process (zod transformers).
But they don't have serialization, which is if I have an object { dueDate: someJsDate }, and I want to serialize it, I want it to come out as dueDate: "2024-01-01" and not dueDate: Date.toString() or Date.toJSON() which is some really long ISO string.
Ideally I want to have a two-way codec, that for a given key, can do both custom serialization & deserialization.
Why should we prioritize solving it?
Because you're a new market entrant and hopefully will see this as an edge/feature to help drive your adoption. :-) 🤞
💡 Solution
How do you think we should solve the problem?
Ideally with something similar to Zod's transformers, but more of a "codec" or "serde" that does both serialization & deserialization.
This would mean new high-level methods like serialize or format (opposite of parse).
Why do you think this is the best solution?
This sort of approach keeps the schema in control of both serialization & deserialization, instead of being at the whims of whatever .toString / .toJSON behavior the values happen to use.
Did you consider any alternatives?
I've been looking for a runtime type library (Zod, see this comment, others) and the only one that does codecs/serde afaict is io-ts, which comes with too much baggage.
Honestly I understand if you consider this out-of-scope, but I'm just really surprised that so far basically all of the runtime type libraries have somewhat myopically focused on "only parse" and forgotten the other half of serde.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone (merged or closed)
Activity
ssalbdivad commentedon Feb 17, 2024
This is a really interesting topic and one I've thought a lot about but am still not quite sure of my stance on.
When I was initially implementing morphs, I considered many solutions including a unique input/output that could be associated with a type. Especially working in the type system, I eventually determined that fundamentally, there was nothing special about input/output or serialize/deserialize compared to any other arbitrarily named transformations you might create for a type. Essentially, if you think about your types as a graph, really what you're defining is new edges (morphs) from the your vertex (type) to some other type (in this case
string).I do think this is a very powerful concept (I created an empty issue a long time ago to follow up #574), but it seems to me bidirectional codecs are more an application of this larger morph-based graph than inherently useful in and of themselves, and in fact I've seen a lot of questions about why in
@effect/schemacodecs must always be bidirectional when often it doesn't reflect a valid transformation in one direction, so you end up creating an implementation that just throws which feels very clunky to me.That said, if you haven't seen https://github.com/Effect-TS/schema already it's a great library and might be just what you're looking for!
If you're interested in fleshing out some of what I described re: morphs I'd definitely be interested in working together to tackle that, especially after the 2.0 release.
stephenh commentedon Apr 7, 2024
Hello! Apologies from the really long delay in replying; your response made a lot of sense, but I was like "ah wow, 'graph of types'?! I'm going to really need to think about my reply...", and then well, finally got a chance to think/play with it today. :-)
I can see this being true...
I think I see what you mean; I hadn't actually tried morphs yet, so just now sketched out a "User type to JSON, JSON back to User type" prototype here:
https://github.com/stephenh/typescript-sandbox/blob/arktype/src/arktype.test.ts#L6
And, yeah, it looks like it works if I treat each "version of type" (User-as-json and User-as-pojo) as its own thing.
Which makes sense, that for Arktype's current API there is only ever "input type --> output type", so to go the other way around, it makes sense to just flip the "output type --> input type".
I think what's less than ideal, at least for this very specific use-case (storing a POJO as JSON, i.e. storing POJOs into
jsonbcolumns), is the duplication in definingUsertwice.Is there a way to avoid that? Ideally I'd like to just define the
Useron its own, and have that definition know how to do In -> Out as well as Out -> In...Which, per your link:
Oh nice! I knew of Effect, but have historically shied away from it b/c of naively assuming it would to too-monad-y; I wrote Scala for ~3-4 years and really enjoyed it, but personally more so from the "better Java" angle than the "getting Haskell on the JVM" angle. :-)
But they definitely have the type + encode + decode setup that I'm looking for, so I'll take a look!
I'm definitely happy to chat over use cases and potential APIs!
At first I was assuming that supporting the codec pattern (being able to call
encode) would be a pretty large/breaking change to the Arktype API, because right now when I douserAsPojo(...json...)it didn't seem clear "if that's (implicitly) decode, where would the encode method even go?"But maybe something like:
Would work, and
user(...)stays as the common-case API/syntax-sugar for decoding.Granted, morphs would need to learn to (optionally--maybe by default the
encodeFnis justvalue?.toJSON()) be two-way (accept an encodeFn), maybe something like:I know I flipped the order of
"|>"there (I putLocalDatefirst instead ofstring)...At first that was an unintentional mistake, but actually I like it b/c imo it better communicates the "
User.birthdayis going to be aLocalDate" intent, and pushes the "here's how its encoded/decoded" to later in the tuple (maybe "two-way morphs" / codecs would have a different operator than|>...<|>maybe?).Vs. the current API of
birthday: ["string", ...]almost makes it sound likebirthday: stringis whatUser.birthdaywill be typed as, until you see/realize that thedecodeFntuple argument swaps it over toLocalDate.Anyway, that's my...mumble...months later thoughts! Thanks!
ssalbdivad commentedon Apr 11, 2024
My intuition is that I'd rather have some way to define a group of "variants" of a type along with a syntax that allows you to conveniently transform between them, but I suppose that API could be defined in such a way that
encodeanddecodecould be defined and used in a way similar to what you describe.I definitely want to revisit this after the next release once the core type system is stable.
robyoder commentedon Feb 5, 2025
👋 A teammate linked me to this. Just wanted to add a vote and some context.
We've used
io-tsfor years but most devs aren't familiar/comfortable with FP patterns and structures (Eitheret al) so we've built helper functions around it to make the codecs easier to use. Defining codecs is also somewhat annoying, though, especially how optional fields need to be represented as an intersection between a type and a partial type.All this to say, we've had conversations internally about moving to something else with a friendlier API, but I'm going to be really sad to lose bidirectional codecs. For example, we have some data structures that have to be transformed from base64url to bytes to JSON string to object, and then back again when encoding. We can make separate functions for these, but that really breaks composability. Now any type that uses one of these transforms (or includes a type that uses, etc. recursively) would have to have a twin type that goes the other direction.
We could pair these twin types with our own data structure, but it's the fact that the type has to be defined twice and kept in sync that's the real annoyance and opportunity for divergence.
I share Stephen's sentiment of frustration that only deeply functional libraries seem to care about this kind of composability.
gabrielgrant commentedon Feb 13, 2025
This might be naive, but could the duplication not be avoided by extracting the base type definition from the
type()calls?So (from your linked example) instead of
do
Obviously more useful if there are more shared fields
Assuming the encoding/decoding just happens at the edge of the application, whereas the POJO version is used throughout, I might be inclined to consider that the "canonical" type, with the conversions being variants. But I think the same basic pattern would work, right?
Thinking something like this (which also adds validation to the actual date string. In this particular case might be better done using builtin JS date logic. And if you didn't want to make
LocalDatea ArkType type, I think it could just be replaced withinstanceOf):Note haven't actually tested this, so likely has some errors
frolic commentedon Mar 9, 2025
I have a codec pattern inside another project I am working on:
https://github.com/frolic/typed-http/blob/main/src/arktype/codec.test.ts
Let me know if it would be useful to lift this out into its own package and I will!
stephenh commentedon Mar 10, 2025
@frolic I scanned your codec tests & (more briefly) the impl--it looks great, and exactly what I'm looking for! Would be great to have it packaged as its own thing or even better worked into arktype itself. 🎉
Thanks for linking to it!
ssalbdivad commentedon Mar 10, 2025
Would love to see this published so I have something to point people to.
I mentioned to @frolic it's probably best we not build it in to ArkType yet because of the graph-based approach I mentioned previously being the long term vision for the internal API that would solve this.
Likely, the end result would be some sugar over that so it ended up looking very similar to @frolic's API, but would want to avoid committing to that internally until we nail down what n-vertices solution would look like.
stephenh commentedon Mar 11, 2025
@ssalbdivad just curious, but what do you mean by an n-vertices solution?
I get you're saying (using the example from @frolic 's test cases) "bigint is a vertex/node in the type graph", "string is a vertex/node in the type graph", and besides just "two-way edges between bigint and string", we might have a 3rd vertex/node come into play? Do you have an example, just to wrap my head around?
Also @frolic this might be a lazy ask, but I didn't see it in the test cases--does your codec library support reusing/composing the codecs, i.e. our use case is storing jsonb columns in postgres:
Temporal.PlainDateofbirthdayin our POJOPlainDate <=> stringto store in a jsonb columnAuthorPOJO that has several fields, one of which is abirthday: Temporal.PlainDate, that reuses theplainDateCodecfor its serdeI think this is a very standard/vanilla use case, so is probably something you already support / had in mind while building your codec library?
Thanks!
frolic commentedon Mar 11, 2025
Yep! I think this might be hidden inside some other parts of this library, but I'll be sure to expose that if I pull this into a codec lib. The idea is that codecs become part of your type scope so you can compose them however you need.
ssalbdivad commentedon Mar 11, 2025
@stephenh I haven't figured out the API for representing it but essentially, instead of thinking of it as relationships between arbitrary types, thing of a group of representations of the same entity.
Maybe you have one type representing a JSON string for the server, the object it is parsed to, and an alternate variant for the database with an
idfield added.Bidirectional encoding is a special case of this sort of graph.
DrJume commentedon Feb 27, 2026
This would also enable usage of Date() with a schema that can be transformed to a JSON Schema (using a bidirectional Date↔string (iso datetime) transformation).
Just like with Zod Codecs 👍
feat(type): add codecs
ssalbdivad commentedon Nov 18, 2026
Fixed in 3.0.0-beta.0 (#1728). Try it with
npm i arktype@next.