Skip to content

Commit 306cb3c

Browse files
fix(fetchium): widen static adapter type to accept any subclass constructor (#11)
* fix(fetchium): widen static adapter type to accept any subclass constructor Assigning a concrete adapter subclass with required constructor arguments to `static adapter` produced a contravariant-parameter error because the field was typed as `typeof AbstractAdapter` (i.e. `abstract new () => T`). Introduce `QueryAdapterClass<T>` = `abstract new (...args: any[]) => T` and use it uniformly on `Query.adapter`, `Mutation.adapter`, `TopicQuery.adapter`, and the internal map/lookup types in `QueryClient`. * test(fetchium): add compile-time type tests for static adapter contract Pins the widened adapter type so future edits cannot silently regress: - Accepts any QueryAdapter subclass with any constructor signature - Rejects non-adapter classes, plain objects, and plain functions - TopicQuery's generic binding still rejects sibling QueryAdapter classes - End-to-end check via TopicQuery subclass with a required-arg adapter The file is named `*.test-d.ts` so vitest's `*.test.ts` glob skips it. tsc picks it up via tsconfig's `src` include, so `@ts-expect-error` assertions run during `check-types`. * test(fetchium): rewrite adapter type tests as realistic TopicQuery definitions Restructure the compile-time assertions as actual TopicQuery subclasses with `static override adapter = ...`, matching how users write queries. - Positive cases: concrete TopicQuery subclasses that assign a concrete adapter with required constructor args, directly and via a shared abstract base class (the MockTopicQuery pattern from the test suite) - Negative cases: `@ts-expect-error` on class declarations that assign a non-TopicQueryAdapter (RESTQueryAdapter, a sibling QueryAdapter, or an unrelated class) If the widening regresses, the positive cases fail to compile. If the generic constraint is lost, the `@ts-expect-error` directives become unused and tsc reports TS2578. * test(fetchium): drop redundant positive cases from adapter type tests GetBalances duplicated GetPrices at the type level (params field is orthogonal to adapter typing), and GetTrades inherited adapter from WebSocketTopicQuery without re-declaring it, so the type check was already covered by the abstract base. Keeping one direct subclass (GetPrices) and the abstract-base pattern (WebSocketTopicQuery). * test(fetchium): extend adapter type tests to cover Query and Mutation TopicQuery already exercised the widening for TopicQueryAdapter. Query and Mutation share an independent code path (QueryAdapterClass with no generic bound), so a separate regression check is worthwhile. - Swap CustomQueryAdapter for AuthenticatedAdapter (required-args QueryAdapter). It now serves both as a TopicQuery negative (sibling QueryAdapter rejected) and a Query / Mutation positive - Add FetchUser / UpdateUser to prove Query and Mutation accept a concrete QueryAdapter with required constructor args - Add one Query negative; Mutation shares the same type as Query, so no separate negative is needed * test(fetchium): add symmetric Mutation negative case Pair every positive with a negative per class — cheap and keeps the file's structure consistent instead of footnoting why one class skips the symmetric assertion.
1 parent c707e40 commit 306cb3c

8 files changed

Lines changed: 184 additions & 12 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"fetchium": patch
3+
---
4+
5+
Allow concrete adapter subclasses with required constructor args to be assigned to `static adapter` without casts

‎packages/fetchium/src/QueryAdapter.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,22 @@ export interface IQueryClientForAdapter {
1212
applyMutationEvent(event: import('./types.js').MutationEvent): void;
1313
}
1414

15+
// ================================
16+
// QueryAdapterClass — constructor reference for an adapter class
17+
// ================================
18+
19+
/**
20+
* A reference to an adapter class (abstract or concrete) with any constructor
21+
* signature. Used as the type of `static adapter` properties on Query/Mutation
22+
* classes, so that subclasses with required constructor arguments can be
23+
* assigned directly without casts.
24+
*
25+
* The framework never instantiates these classes via this type (adapters are
26+
* registered as pre-built instances on the QueryClient); it only uses the
27+
* reference as a map key and for prototype/name introspection.
28+
*/
29+
export type QueryAdapterClass<T extends QueryAdapter = QueryAdapter> = abstract new (...args: any[]) => T;
30+
1531
// ================================
1632
// QueryAdapter base class
1733
// ================================

‎packages/fetchium/src/QueryClient.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import { applyEntityRefs, type ApplyResult } from './applyEntities.js';
2424
import { ValidatorDef } from './typeDefs.js';
2525
import { ConstraintMatcher, EVENT_SOURCE_FIELD } from './ConstraintMatcher.js';
2626
import { LiveCollectionBinding } from './LiveCollection.js';
27-
import { QueryAdapter } from './QueryAdapter.js';
27+
import { QueryAdapter, type QueryAdapterClass } from './QueryAdapter.js';
2828
import {
2929
type QueryContext,
3030
type QueryStore,
@@ -78,7 +78,7 @@ export class QueryClient {
7878
private typenameRegistry = new Map<string, ValidatorDef<any>[]>();
7979
private constraintRegistry = new Map<string, ConstraintMatcher>();
8080
private mergedDefCache = new Map<string, ValidatorDef<any>>();
81-
private adapters = new Map<typeof QueryAdapter, QueryAdapter>();
81+
private adapters = new Map<QueryAdapterClass, QueryAdapter>();
8282
private networkUnsubscribe: (() => void) | undefined;
8383

8484
constructor(config: QueryClientConfig = {}) {
@@ -102,7 +102,7 @@ export class QueryClient {
102102

103103
// Register user-supplied adapters
104104
for (const adapter of config.adapters ?? []) {
105-
this.adapters.set(adapter.constructor as typeof QueryAdapter, adapter);
105+
this.adapters.set(adapter.constructor as QueryAdapterClass, adapter);
106106
adapter.register(this);
107107
}
108108

@@ -126,7 +126,7 @@ export class QueryClient {
126126
* Returns the registered adapter instance for the given adapter class.
127127
* Throws if no adapter of that class has been registered.
128128
*/
129-
getAdapter(adapterClass: typeof QueryAdapter): QueryAdapter {
129+
getAdapter(adapterClass: QueryAdapterClass): QueryAdapter {
130130
let adapter = this.adapters.get(adapterClass);
131131
if (!adapter) {
132132
// Auto-instantiate with no-arg constructor as fallback.
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
// Compile-time type tests for the `static adapter` property on Query,
2+
// Mutation, and TopicQuery. Validated by `tsc --noEmit` (via `check-types`).
3+
// Vitest's test glob is `*.test.ts`, so `.test-d.ts` files are not executed
4+
// at runtime.
5+
6+
import { t } from '../typeDefs.js';
7+
import { Query } from '../query.js';
8+
import { Mutation } from '../mutation.js';
9+
import { QueryAdapter } from '../QueryAdapter.js';
10+
import { TopicQuery } from '../topic/TopicQuery.js';
11+
import { TopicQueryAdapter } from '../topic/TopicQueryAdapter.js';
12+
import { RESTQueryAdapter } from '../rest/RESTQueryAdapter.js';
13+
14+
// A realistic TopicQueryAdapter that requires construction arguments —
15+
// the shape of a real-world wallet/chain/websocket adapter. Before this
16+
// PR, assigning this to `static override adapter` required the cast
17+
// `as unknown as typeof TopicQueryAdapter`.
18+
class WebSocketTopicAdapter extends TopicQueryAdapter {
19+
constructor(
20+
private readonly url: string,
21+
private readonly token: string,
22+
) {
23+
super();
24+
}
25+
subscribe(_topic: string): void {}
26+
unsubscribe(_topic: string): void {}
27+
}
28+
29+
// A plain QueryAdapter (not a TopicQueryAdapter) with a required
30+
// constructor arg. Used as a positive fixture for Query / Mutation and
31+
// as a negative fixture for TopicQuery.
32+
class AuthenticatedAdapter extends QueryAdapter {
33+
constructor(private readonly token: string) {
34+
super();
35+
}
36+
async send(): Promise<unknown> {
37+
return undefined;
38+
}
39+
}
40+
41+
class NotAnAdapter {}
42+
43+
// ============================================================
44+
// TopicQuery.adapter — generic constraint to TopicQueryAdapter subclasses
45+
// ============================================================
46+
47+
// Direct subclass — the standard pattern.
48+
class GetPrices extends TopicQuery {
49+
static override adapter = WebSocketTopicAdapter;
50+
51+
topic = 'prices:live';
52+
result = {
53+
price: t.number,
54+
timestamp: t.number,
55+
};
56+
}
57+
58+
// Shared abstract base — the pattern used in Fetchium's own test suite
59+
// (MockTopicQuery) — must also compile without a cast.
60+
abstract class WebSocketTopicQuery extends TopicQuery {
61+
static override adapter = WebSocketTopicAdapter;
62+
}
63+
64+
// @ts-expect-error — RESTQueryAdapter is a QueryAdapter but not a TopicQueryAdapter
65+
class BadRestAdapter extends TopicQuery {
66+
static override adapter = RESTQueryAdapter;
67+
68+
topic = 'bad-rest';
69+
result = {};
70+
}
71+
72+
// @ts-expect-error — AuthenticatedAdapter is a QueryAdapter but not a TopicQueryAdapter
73+
class BadSiblingAdapter extends TopicQuery {
74+
static override adapter = AuthenticatedAdapter;
75+
76+
topic = 'bad-sibling';
77+
result = {};
78+
}
79+
80+
// @ts-expect-error — NotAnAdapter does not extend TopicQueryAdapter
81+
class BadRandomClass extends TopicQuery {
82+
static override adapter = NotAnAdapter;
83+
84+
topic = 'bad-random';
85+
result = {};
86+
}
87+
88+
// ============================================================
89+
// Query.adapter — accepts any QueryAdapter subclass, rejects non-adapters
90+
// ============================================================
91+
92+
class FetchUser extends Query {
93+
static override adapter = AuthenticatedAdapter;
94+
95+
params = { userId: t.string };
96+
result = {
97+
id: t.string,
98+
name: t.string,
99+
};
100+
101+
getIdentityKey() {
102+
return 'fetch-user';
103+
}
104+
}
105+
106+
// @ts-expect-error — NotAnAdapter does not extend QueryAdapter
107+
class BadQuery extends Query {
108+
static override adapter = NotAnAdapter;
109+
110+
result = {};
111+
112+
getIdentityKey() {
113+
return 'bad-query';
114+
}
115+
}
116+
117+
// ============================================================
118+
// Mutation.adapter — accepts any QueryAdapter subclass, rejects non-adapters
119+
// ============================================================
120+
121+
class UpdateUser extends Mutation {
122+
static override adapter = AuthenticatedAdapter;
123+
124+
params = { userId: t.string, name: t.string };
125+
126+
getIdentityKey() {
127+
return 'update-user';
128+
}
129+
}
130+
131+
// @ts-expect-error — NotAnAdapter does not extend QueryAdapter
132+
class BadMutation extends Mutation {
133+
static override adapter = NotAnAdapter;
134+
135+
getIdentityKey() {
136+
return 'bad-mutation';
137+
}
138+
}
139+
140+
// Prevent "declared but unused" diagnostics for the fixtures above.
141+
export type _AdapterTypeTests =
142+
| typeof GetPrices
143+
| typeof WebSocketTopicQuery
144+
| typeof BadRestAdapter
145+
| typeof BadSiblingAdapter
146+
| typeof BadRandomClass
147+
| typeof FetchUser
148+
| typeof BadQuery
149+
| typeof UpdateUser
150+
| typeof BadMutation;

‎packages/fetchium/src/__tests__/topic-query.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ class TopicNotFoundError extends Error {
207207
// ============================================================
208208

209209
abstract class MockTopicQuery extends TopicQuery {
210-
static override adapter = MockTopicQueryAdapter as unknown as typeof TopicQueryAdapter;
210+
static override adapter = MockTopicQueryAdapter;
211211
}
212212

213213
// ============================================================

‎packages/fetchium/src/mutation.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { ExtractType, InternalTypeDef, MutationEffects, TypeDef, RetryConfig, Ty
33
import { QueryClientContext, type QueryContext } from './QueryClient.js';
44
import { ValidatorDef, t } from './typeDefs.js';
55
import { createDefinitionProxy, extractDefinition, type CapturedDefinition } from './fieldRef.js';
6-
import type { QueryAdapter } from './QueryAdapter.js';
6+
import type { QueryAdapter, QueryAdapterClass } from './QueryAdapter.js';
77

88
// ================================
99
// Mutation Definition Types
@@ -22,15 +22,15 @@ export interface MutationDefinition<Request, Response> {
2222
config?: MutationConfigOptions;
2323
effects?: MutationEffects;
2424
hasGetEffects: boolean;
25-
adapterClass: typeof QueryAdapter;
25+
adapterClass: QueryAdapterClass;
2626
}
2727

2828
// ================================
2929
// Mutation base class
3030
// ================================
3131

3232
export abstract class Mutation {
33-
static adapter?: typeof QueryAdapter;
33+
static adapter?: QueryAdapterClass;
3434

3535
readonly params?: TypeDefShape;
3636
readonly result?: TypeDefShape;

‎packages/fetchium/src/query.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import {
1616
createExecutionContext as createExecutionContextUtil,
1717
type CapturedDefinition,
1818
} from './fieldRef.js';
19-
import type { QueryAdapter } from './QueryAdapter.js';
19+
import type { QueryAdapter, QueryAdapterClass } from './QueryAdapter.js';
2020

2121
// ================================
2222
// Retry config
@@ -61,7 +61,7 @@ export abstract class Query {
6161
* The adapter class responsible for sending requests for this query type.
6262
* Must be set on each concrete Query subclass (or inherited from a base like RESTQuery).
6363
*/
64-
static adapter?: typeof QueryAdapter;
64+
static adapter?: QueryAdapterClass;
6565

6666
params?: Record<string, TypeDef>;
6767
abstract result: TypeDefShape;
@@ -106,7 +106,7 @@ export interface QueryDefinitionStatics {
106106
/** Whether the result shape is already an entity (vs synthetic wrapper). */
107107
readonly isEntityResult: boolean;
108108
/** The adapter class responsible for sending requests. */
109-
readonly adapterClass: typeof QueryAdapter;
109+
readonly adapterClass: QueryAdapterClass;
110110
}
111111

112112
export class QueryDefinition<Params extends QueryParams | undefined, Result, StreamType> {

‎packages/fetchium/src/topic/TopicQuery.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
import { Query } from '../query.js';
22
import type { TopicQueryAdapter } from './TopicQueryAdapter.js';
3+
import type { QueryAdapterClass } from '../QueryAdapter.js';
34
import type { QueryConfigOptions } from '../query-types.js';
45

56
// ================================
67
// TopicQuery — declarative topic-based query definition
78
// ================================
89

910
export abstract class TopicQuery extends Query {
10-
static override adapter: typeof TopicQueryAdapter;
11+
static override adapter: QueryAdapterClass<TopicQueryAdapter>;
1112

1213
abstract topic: string;
1314

0 commit comments

Comments
 (0)