Skip to content

Commit

Permalink
Further fixes for the Serializable type
Browse files Browse the repository at this point in the history
- Fixed Serializable to properly resolve structured composite types.
- Fixed missing generic types in Serializable usages.
- Fixed issue where interfaces were not being stubified.
  • Loading branch information
alpertuna authored Oct 7, 2024
1 parent e8ab708 commit 09429df
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions types/defines/rpc.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ declare namespace Rpc {
export type Stubable = RpcTargetBranded | ((...args: any[]) => any);

// Types that can be passed over RPC
// The reason for using a generic type here is to build a serializable subset of structured
// cloneable composite types. This allows types defined with the "interface" keyword to pass the
// serializable check as well. Otherwise, only types defined with the "type" keyword would pass.
type Serializable<T> =
// Structured cloneables
| void
Expand All @@ -48,9 +51,12 @@ declare namespace Rpc {
| Error
| RegExp
// Structured cloneable composites
| Map<Serializable<T>, Serializable<T>>
| Set<Serializable<T>>
| ReadonlyArray<Serializable<T>>
| Map<
T extends Map<infer U, unknown> ? Serializable<U> : never,
T extends Map<unknown, infer U> ? Serializable<U> : never
>
| Set<T extends Set<infer U> ? Serializable<U> : never>
| ReadonlyArray<T extends ReadonlyArray<infer U> ? Serializable<U> : never>
| {
[K in keyof T]: K extends number | string ? Serializable<T[K]> : never;
}
Expand Down Expand Up @@ -80,7 +86,8 @@ declare namespace Rpc {
: T extends Set<infer V> ? Set<Stubify<V>>
: T extends Array<infer V> ? Array<Stubify<V>>
: T extends ReadonlyArray<infer V> ? ReadonlyArray<Stubify<V>>
: T extends { [key: string | number]: unknown } ? { [K in keyof T]: Stubify<T[K]> }
// When using "unknown" instead of "any", interfaces are not stubified.
: T extends { [key: string | number]: any } ? { [K in keyof T]: Stubify<T[K]> }
: T;

// Recursively rewrite all `Stub<T>`s with the corresponding `T`s.
Expand Down Expand Up @@ -227,7 +234,7 @@ declare module "cloudflare:workers" {
};

export type WorkflowStep = {
do: <T extends Rpc.Serializable>(
do: <T extends Rpc.Serializable<T>>(
name: string,
callback: () => Promise<T>,
config?: WorkflowStepConfig
Expand All @@ -240,7 +247,7 @@ declare module "cloudflare:workers" {

export abstract class Workflow<
Env = unknown,
T extends Rpc.Serializable | unknown = unknown,
T extends Rpc.Serializable<T> | unknown = unknown,
> implements Rpc.WorkflowBranded
{
[Rpc.__WORKFLOW_BRAND]: never;
Expand Down

0 comments on commit 09429df

Please sign in to comment.