@rpc-dart/trpc-adapter 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -5
- package/dist/classify.d.ts +1 -40
- package/dist/classify.js +1 -362
- package/dist/extract.js +12 -63
- package/dist/harness.d.ts +1 -21
- package/dist/harness.js +3 -25
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -31,13 +31,14 @@ pnpm add @rpc-dart/trpc-adapter
|
|
|
31
31
|
## Usage
|
|
32
32
|
|
|
33
33
|
```typescript
|
|
34
|
-
import {
|
|
34
|
+
import { extractContract } from '@rpc-dart/trpc-adapter';
|
|
35
35
|
|
|
36
|
-
const {
|
|
37
|
-
|
|
36
|
+
const { ir, diagnostics } = await extractContract({
|
|
37
|
+
tsconfigPath: './tsconfig.json',
|
|
38
|
+
entryFile: './src/trpc/router.ts',
|
|
38
39
|
exportName: 'appRouter',
|
|
39
|
-
transformer: 'superjson',
|
|
40
|
-
|
|
40
|
+
protocol: { kind: 'trpc', version: '11', transformer: 'superjson' },
|
|
41
|
+
policies: { unserializablePolicy: 'error' }, // 'warn-dynamic' | 'skip-procedure'
|
|
41
42
|
});
|
|
42
43
|
```
|
|
43
44
|
|
package/dist/classify.d.ts
CHANGED
|
@@ -1,40 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import type { FieldDef, TypeRef } from '@rpc-dart/core';
|
|
3
|
-
import type { RpcDartDiagnostic } from '@rpc-dart/core';
|
|
4
|
-
export declare class TypeClassificationError extends Error {
|
|
5
|
-
readonly diagnostic: RpcDartDiagnostic;
|
|
6
|
-
constructor(diagnostic: RpcDartDiagnostic);
|
|
7
|
-
}
|
|
8
|
-
export declare function pascal(input: string): string;
|
|
9
|
-
/**
|
|
10
|
-
* TypeChecker type -> Contract IR TypeDef. Field optionality/nullability is
|
|
11
|
-
* decided here (undefined -> optional, null -> nullable) so the emitter never
|
|
12
|
-
* sees unions for optionality.
|
|
13
|
-
*
|
|
14
|
-
* Recursive types are handled with an in-progress stack: re-entering a type
|
|
15
|
-
* currently being classified yields a transient selfRef that the assembler
|
|
16
|
-
* resolves into a forward $ref.
|
|
17
|
-
*/
|
|
18
|
-
export type UnserializablePolicy = 'error' | 'warn-dynamic' | 'skip-procedure';
|
|
19
|
-
export declare class TypeClassifier {
|
|
20
|
-
private readonly ts;
|
|
21
|
-
private readonly checker;
|
|
22
|
-
private readonly unserializablePolicy;
|
|
23
|
-
private readonly cache;
|
|
24
|
-
private readonly inProgress;
|
|
25
|
-
private readonly stack;
|
|
26
|
-
currentProcedure: string | undefined;
|
|
27
|
-
/** Warnings recorded when per-field warn-dynamic downgrades occur. */
|
|
28
|
-
readonly collectedDiagnostics: RpcDartDiagnostic[];
|
|
29
|
-
constructor(ts: typeof tsTypes, checker: tsTypes.TypeChecker, unserializablePolicy?: UnserializablePolicy);
|
|
30
|
-
classifyProperty(symbol: tsTypes.Symbol, parentName: string): FieldDef;
|
|
31
|
-
classify(type: tsTypes.Type, nameHint: string): TypeRef;
|
|
32
|
-
private classifyUncached;
|
|
33
|
-
private classifyUnion;
|
|
34
|
-
private tryDiscriminatedUnion;
|
|
35
|
-
private classifyObject;
|
|
36
|
-
private locationOf;
|
|
37
|
-
private isOptional;
|
|
38
|
-
private stripNullish;
|
|
39
|
-
private typeArgument;
|
|
40
|
-
}
|
|
1
|
+
export { TypeClassificationError, TypeClassifier, pascal, type UnserializablePolicy } from '@rpc-dart/core';
|
package/dist/classify.js
CHANGED
|
@@ -1,362 +1 @@
|
|
|
1
|
-
export
|
|
2
|
-
diagnostic;
|
|
3
|
-
constructor(diagnostic) {
|
|
4
|
-
super(`${diagnostic.code}: ${diagnostic.message}`);
|
|
5
|
-
this.name = 'TypeClassificationError';
|
|
6
|
-
this.diagnostic = diagnostic;
|
|
7
|
-
}
|
|
8
|
-
}
|
|
9
|
-
export function pascal(input) {
|
|
10
|
-
return input
|
|
11
|
-
.split(/[.\-_]/)
|
|
12
|
-
.filter((s) => s.length > 0)
|
|
13
|
-
.map((s) => s.charAt(0).toUpperCase() + s.slice(1))
|
|
14
|
-
.join('');
|
|
15
|
-
}
|
|
16
|
-
function fail(code, message, hint, context = {}) {
|
|
17
|
-
return new TypeClassificationError({
|
|
18
|
-
code,
|
|
19
|
-
severity: 'error',
|
|
20
|
-
message,
|
|
21
|
-
procedurePath: context.procedurePath,
|
|
22
|
-
file: context.file,
|
|
23
|
-
line: context.line,
|
|
24
|
-
column: context.column,
|
|
25
|
-
hint,
|
|
26
|
-
});
|
|
27
|
-
}
|
|
28
|
-
export class TypeClassifier {
|
|
29
|
-
ts;
|
|
30
|
-
checker;
|
|
31
|
-
unserializablePolicy;
|
|
32
|
-
cache = new Map();
|
|
33
|
-
inProgress = new Set();
|
|
34
|
-
stack = [];
|
|
35
|
-
currentProcedure;
|
|
36
|
-
/** Warnings recorded when per-field warn-dynamic downgrades occur. */
|
|
37
|
-
collectedDiagnostics = [];
|
|
38
|
-
constructor(ts, checker, unserializablePolicy = 'error') {
|
|
39
|
-
this.ts = ts;
|
|
40
|
-
this.checker = checker;
|
|
41
|
-
this.unserializablePolicy = unserializablePolicy;
|
|
42
|
-
}
|
|
43
|
-
classifyProperty(symbol, parentName) {
|
|
44
|
-
const name = symbol.getName();
|
|
45
|
-
const declared = this.checker.getTypeOfSymbol(symbol);
|
|
46
|
-
const optional = this.isOptional(symbol, declared);
|
|
47
|
-
const { stripped, nullable } = this.stripNullish(declared);
|
|
48
|
-
let type;
|
|
49
|
-
try {
|
|
50
|
-
type = this.classify(stripped, `${parentName}${pascal(name)}`);
|
|
51
|
-
}
|
|
52
|
-
catch (error) {
|
|
53
|
-
if (error instanceof TypeClassificationError) {
|
|
54
|
-
if (error.diagnostic.file === undefined) {
|
|
55
|
-
const location = this.locationOf(symbol);
|
|
56
|
-
if (location) {
|
|
57
|
-
error.diagnostic.file = location.file;
|
|
58
|
-
error.diagnostic.line = location.line;
|
|
59
|
-
error.diagnostic.column = location.column;
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
// Per-field warn-dynamic: downgrade only this offending field to an
|
|
63
|
-
// unknown (JsonValue) type and record the warning; siblings stay
|
|
64
|
-
// strongly typed.
|
|
65
|
-
if (this.unserializablePolicy === 'warn-dynamic' && error.diagnostic.code === 'RPCDART0201') {
|
|
66
|
-
error.diagnostic.severity = 'warning';
|
|
67
|
-
this.collectedDiagnostics.push(error.diagnostic);
|
|
68
|
-
return { name, wireName: name, type: { kind: 'unknown' }, optional, nullable };
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
throw error;
|
|
72
|
-
}
|
|
73
|
-
return { name, wireName: name, type, optional, nullable };
|
|
74
|
-
}
|
|
75
|
-
classify(type, nameHint) {
|
|
76
|
-
const cached = this.cache.get(type);
|
|
77
|
-
if (cached)
|
|
78
|
-
return cached;
|
|
79
|
-
if (this.inProgress.has(type)) {
|
|
80
|
-
// Recursion: the enclosing named type will resolve this marker.
|
|
81
|
-
return { kind: 'selfRef', name: this.stack[this.stack.length - 1] ?? nameHint };
|
|
82
|
-
}
|
|
83
|
-
this.inProgress.add(type);
|
|
84
|
-
try {
|
|
85
|
-
const def = this.classifyUncached(type, nameHint);
|
|
86
|
-
this.cache.set(type, def);
|
|
87
|
-
return def;
|
|
88
|
-
}
|
|
89
|
-
finally {
|
|
90
|
-
this.inProgress.delete(type);
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
classifyUncached(type, nameHint) {
|
|
94
|
-
const ts = this.ts;
|
|
95
|
-
const flags = type.flags;
|
|
96
|
-
if (flags & ts.TypeFlags.String)
|
|
97
|
-
return 'string';
|
|
98
|
-
if (flags & ts.TypeFlags.Number)
|
|
99
|
-
return 'number';
|
|
100
|
-
if (flags & ts.TypeFlags.Boolean)
|
|
101
|
-
return 'boolean';
|
|
102
|
-
if (flags & ts.TypeFlags.BigInt)
|
|
103
|
-
return 'BigInt';
|
|
104
|
-
if (flags & ts.TypeFlags.Void)
|
|
105
|
-
return 'void';
|
|
106
|
-
if (flags & ts.TypeFlags.Never)
|
|
107
|
-
return 'never';
|
|
108
|
-
if (flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
|
|
109
|
-
return { kind: 'unknown' };
|
|
110
|
-
if (flags & ts.TypeFlags.Null || flags & ts.TypeFlags.Undefined)
|
|
111
|
-
return { kind: 'unknown' };
|
|
112
|
-
if (flags & (ts.TypeFlags.StringLiteral | ts.TypeFlags.NumberLiteral)) {
|
|
113
|
-
return { kind: 'literal', value: type.value };
|
|
114
|
-
}
|
|
115
|
-
if (flags & ts.TypeFlags.BooleanLiteral) {
|
|
116
|
-
const intrinsic = type.intrinsicName;
|
|
117
|
-
return { kind: 'literal', value: intrinsic === 'true' };
|
|
118
|
-
}
|
|
119
|
-
if (type.isUnion())
|
|
120
|
-
return this.classifyUnion(type, nameHint);
|
|
121
|
-
if (flags & ts.TypeFlags.Intersection) {
|
|
122
|
-
// Branded/nominal types (string & BRAND<'X'>) are intersections whose
|
|
123
|
-
// phantom members carry only `__@`-prefixed symbol properties; the
|
|
124
|
-
// real payload is the first non-phantom member.
|
|
125
|
-
const members = type.types;
|
|
126
|
-
const nonPhantom = members.filter((member) => {
|
|
127
|
-
const apparent = this.checker.getApparentType(member);
|
|
128
|
-
if (!(apparent.flags & this.ts.TypeFlags.Object))
|
|
129
|
-
return true;
|
|
130
|
-
const props = this.checker.getPropertiesOfType(apparent);
|
|
131
|
-
return props.length > 0 && props.some((p2) => !p2.getName().startsWith('__@'));
|
|
132
|
-
});
|
|
133
|
-
if (nonPhantom.length >= 1) {
|
|
134
|
-
return this.classify(nonPhantom[0], nameHint);
|
|
135
|
-
}
|
|
136
|
-
throw fail('RPCDART0201', `cannot classify intersection at ${nameHint}`, 'simplify the intersection type', {
|
|
137
|
-
procedurePath: this.currentProcedure,
|
|
138
|
-
});
|
|
139
|
-
}
|
|
140
|
-
if (flags & ts.TypeFlags.Object) {
|
|
141
|
-
const symbol = type.getSymbol() ?? type.aliasSymbol;
|
|
142
|
-
const symbolName = symbol ? symbol.getName() : '';
|
|
143
|
-
if (symbolName === 'Date')
|
|
144
|
-
return 'Date';
|
|
145
|
-
if (symbolName === 'Function') {
|
|
146
|
-
throw fail('RPCDART0201', `unserializable type Function at ${nameHint}`, 'remove the field from the schema, or set unserializablePolicy in the generator config', { procedurePath: this.currentProcedure });
|
|
147
|
-
}
|
|
148
|
-
if (symbolName === 'Promise') {
|
|
149
|
-
throw fail('RPCDART0201', `unserializable type Promise at ${nameHint} (async values cannot cross the wire)`, 'await the promise inside the resolver and return its resolved type', { procedurePath: this.currentProcedure });
|
|
150
|
-
}
|
|
151
|
-
if (symbolName === 'Symbol') {
|
|
152
|
-
throw fail('RPCDART0201', `unserializable type Symbol at ${nameHint}`, 'use a string identifier instead', {
|
|
153
|
-
procedurePath: this.currentProcedure,
|
|
154
|
-
});
|
|
155
|
-
}
|
|
156
|
-
if (symbolName === 'RegExp') {
|
|
157
|
-
throw fail('RPCDART0201', `unserializable type RegExp at ${nameHint}`, 'serialize as a string pattern instead', {
|
|
158
|
-
procedurePath: this.currentProcedure,
|
|
159
|
-
});
|
|
160
|
-
}
|
|
161
|
-
if (symbolName === 'Set') {
|
|
162
|
-
const element = this.checker.getIndexTypeOfType(type, this.ts.IndexKind.Number) ??
|
|
163
|
-
this.typeArgument(type, 0);
|
|
164
|
-
if (!element) {
|
|
165
|
-
throw fail('RPCDART0201', `Set without a type argument at ${nameHint}`, 'give Set an explicit element type', {
|
|
166
|
-
procedurePath: this.currentProcedure,
|
|
167
|
-
});
|
|
168
|
-
}
|
|
169
|
-
return { kind: 'set', element: this.classify(element, `${nameHint}Item`) };
|
|
170
|
-
}
|
|
171
|
-
if (symbolName === 'Map') {
|
|
172
|
-
const key = this.typeArgument(type, 0);
|
|
173
|
-
const value = this.typeArgument(type, 1);
|
|
174
|
-
if (!key || !value) {
|
|
175
|
-
throw fail('RPCDART0201', `Map without type arguments at ${nameHint}`, 'give Map explicit key and value types', {
|
|
176
|
-
procedurePath: this.currentProcedure,
|
|
177
|
-
});
|
|
178
|
-
}
|
|
179
|
-
const keyType = this.classify(key, `${nameHint}Key`);
|
|
180
|
-
if (typeof keyType !== 'string') {
|
|
181
|
-
throw fail('RPCDART0203', `unmappable map key type at ${nameHint}`, 'use string or enum keys', {
|
|
182
|
-
procedurePath: this.currentProcedure,
|
|
183
|
-
});
|
|
184
|
-
}
|
|
185
|
-
return {
|
|
186
|
-
kind: 'record',
|
|
187
|
-
keyType,
|
|
188
|
-
valueType: this.classify(value, `${nameHint}Value`),
|
|
189
|
-
};
|
|
190
|
-
}
|
|
191
|
-
if (this.checker.isArrayType(type) || symbolName === 'ReadonlyArray') {
|
|
192
|
-
const element = this.checker.getIndexTypeOfType(type, this.ts.IndexKind.Number) ??
|
|
193
|
-
this.typeArgument(type, 0);
|
|
194
|
-
if (!element) {
|
|
195
|
-
throw fail('RPCDART0201', `array without element at ${nameHint}`, 'give the array an explicit element type', {
|
|
196
|
-
procedurePath: this.currentProcedure,
|
|
197
|
-
});
|
|
198
|
-
}
|
|
199
|
-
return { kind: 'list', element: this.classify(element, `${nameHint}Item`) };
|
|
200
|
-
}
|
|
201
|
-
if (this.checker.isTupleType(type)) {
|
|
202
|
-
const args = type.typeArguments ?? [];
|
|
203
|
-
return { kind: 'tuple', items: args.map((a, i) => this.classify(a, `${nameHint}${i}`)) };
|
|
204
|
-
}
|
|
205
|
-
const props = this.checker.getPropertiesOfType(type);
|
|
206
|
-
const indexInfos = this.checker.getIndexInfosOfType(type);
|
|
207
|
-
if (props.length === 0 && this.checker.getSignaturesOfType(type, this.ts.SignatureKind.Call).length > 0) {
|
|
208
|
-
// Anonymous function types (e.g. z.function() inference) carry no
|
|
209
|
-
// Function symbol but are equally unserializable.
|
|
210
|
-
throw fail('RPCDART0201', `unserializable function type at ${nameHint}`, 'remove the field from the schema, or set unserializablePolicy in the generator config', {
|
|
211
|
-
procedurePath: this.currentProcedure,
|
|
212
|
-
});
|
|
213
|
-
}
|
|
214
|
-
if (props.length === 0 && indexInfos.length > 0) {
|
|
215
|
-
const info = indexInfos[0];
|
|
216
|
-
if (!info.keyType) {
|
|
217
|
-
throw fail('RPCDART0203', `record key type missing at ${nameHint}`, 'use string keys', {
|
|
218
|
-
procedurePath: this.currentProcedure,
|
|
219
|
-
});
|
|
220
|
-
}
|
|
221
|
-
const keyType = this.classify(info.keyType, `${nameHint}Key`);
|
|
222
|
-
if (typeof keyType !== 'string') {
|
|
223
|
-
throw fail('RPCDART0203', `unmappable record key type at ${nameHint}`, 'use string or enum keys', {
|
|
224
|
-
procedurePath: this.currentProcedure,
|
|
225
|
-
});
|
|
226
|
-
}
|
|
227
|
-
const kind = keyType === 'string' ? this.ts.IndexKind.String : this.ts.IndexKind.Number;
|
|
228
|
-
const valueType = this.checker.getIndexTypeOfType(type, kind);
|
|
229
|
-
if (!valueType) {
|
|
230
|
-
throw fail('RPCDART0203', `record value type missing at ${nameHint}`, 'give the record a value type', {
|
|
231
|
-
procedurePath: this.currentProcedure,
|
|
232
|
-
});
|
|
233
|
-
}
|
|
234
|
-
return {
|
|
235
|
-
kind: 'record',
|
|
236
|
-
keyType,
|
|
237
|
-
valueType: this.classify(valueType, `${nameHint}Value`),
|
|
238
|
-
};
|
|
239
|
-
}
|
|
240
|
-
if (props.length > 0) {
|
|
241
|
-
this.stack.push(nameHint);
|
|
242
|
-
try {
|
|
243
|
-
return this.classifyObject(type, nameHint);
|
|
244
|
-
}
|
|
245
|
-
finally {
|
|
246
|
-
this.stack.pop();
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
throw fail('RPCDART0201', `cannot classify type at ${nameHint}`, 'simplify the type or use a schema primitive', {
|
|
251
|
-
procedurePath: this.currentProcedure,
|
|
252
|
-
});
|
|
253
|
-
}
|
|
254
|
-
classifyUnion(type, nameHint) {
|
|
255
|
-
const members = type.types.filter((t) => !(t.flags & (this.ts.TypeFlags.Null | this.ts.TypeFlags.Undefined)));
|
|
256
|
-
if (members.length === 0)
|
|
257
|
-
return { kind: 'unknown' };
|
|
258
|
-
const allLiterals = members.every((t) => (t.flags & (this.ts.TypeFlags.StringLiteral | this.ts.TypeFlags.NumberLiteral)) !== 0);
|
|
259
|
-
if (allLiterals) {
|
|
260
|
-
const values = [
|
|
261
|
-
...new Set(members.map((t) => t.value)),
|
|
262
|
-
].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
263
|
-
const def = { kind: 'enum', name: nameHint, values };
|
|
264
|
-
return def;
|
|
265
|
-
}
|
|
266
|
-
const du = this.tryDiscriminatedUnion(members, nameHint);
|
|
267
|
-
if (du)
|
|
268
|
-
return du;
|
|
269
|
-
if (members.length === 1)
|
|
270
|
-
return this.classify(members[0], nameHint);
|
|
271
|
-
throw fail('RPCDART0202', `non-discriminated object union at ${nameHint}`, 'add a literal discriminator field (z.discriminatedUnion) or widen to a single shape', { procedurePath: this.currentProcedure });
|
|
272
|
-
}
|
|
273
|
-
tryDiscriminatedUnion(members, nameHint) {
|
|
274
|
-
const propsPerMember = [];
|
|
275
|
-
for (const member of members) {
|
|
276
|
-
if (!(member.flags & this.ts.TypeFlags.Object))
|
|
277
|
-
return null;
|
|
278
|
-
const resolved = this.checker.getApparentType(member);
|
|
279
|
-
const props = this.checker.getPropertiesOfType(resolved);
|
|
280
|
-
if (props.length === 0)
|
|
281
|
-
return null;
|
|
282
|
-
const map = new Map(props.map((s) => [s.getName(), s]));
|
|
283
|
-
propsPerMember.push(map);
|
|
284
|
-
}
|
|
285
|
-
const first = propsPerMember[0];
|
|
286
|
-
for (const [tagField] of first) {
|
|
287
|
-
const tags = [];
|
|
288
|
-
let viable = true;
|
|
289
|
-
for (const map of propsPerMember) {
|
|
290
|
-
const sym = map.get(tagField);
|
|
291
|
-
if (!sym) {
|
|
292
|
-
viable = false;
|
|
293
|
-
break;
|
|
294
|
-
}
|
|
295
|
-
const t = this.checker.getTypeOfSymbol(sym);
|
|
296
|
-
if (!(t.flags & (this.ts.TypeFlags.StringLiteral | this.ts.TypeFlags.NumberLiteral))) {
|
|
297
|
-
viable = false;
|
|
298
|
-
break;
|
|
299
|
-
}
|
|
300
|
-
tags.push(t.value);
|
|
301
|
-
}
|
|
302
|
-
if (!viable)
|
|
303
|
-
continue;
|
|
304
|
-
if (new Set(tags.map((t) => `${t}`)).size !== tags.length)
|
|
305
|
-
continue;
|
|
306
|
-
const variants = members.map((member, i) => ({
|
|
307
|
-
tag: tags[i],
|
|
308
|
-
object: this.classify(member, `${nameHint}${pascal(String(tags[i]))}`),
|
|
309
|
-
}));
|
|
310
|
-
variants.sort((a, b) => (String(a.tag) < String(b.tag) ? -1 : String(a.tag) > String(b.tag) ? 1 : 0));
|
|
311
|
-
return { kind: 'discriminatedUnion', name: nameHint, tagField, variants };
|
|
312
|
-
}
|
|
313
|
-
return null;
|
|
314
|
-
}
|
|
315
|
-
classifyObject(type, name) {
|
|
316
|
-
const props = this.checker.getPropertiesOfType(type);
|
|
317
|
-
const fields = props.map((sym) => this.classifyProperty(sym, name));
|
|
318
|
-
fields.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
319
|
-
return { kind: 'object', name, fields };
|
|
320
|
-
}
|
|
321
|
-
locationOf(symbol) {
|
|
322
|
-
const declaration = symbol.valueDeclaration ?? symbol.declarations?.[0];
|
|
323
|
-
if (!declaration)
|
|
324
|
-
return null;
|
|
325
|
-
const sourceFile = declaration.getSourceFile();
|
|
326
|
-
const { line, character } = sourceFile.getLineAndCharacterOfPosition(declaration.getStart());
|
|
327
|
-
return { file: sourceFile.fileName, line: line + 1, column: character + 1 };
|
|
328
|
-
}
|
|
329
|
-
isOptional(symbol, declared) {
|
|
330
|
-
if ((symbol.flags & this.ts.SymbolFlags.Optional) !== 0)
|
|
331
|
-
return true;
|
|
332
|
-
const question = (symbol.declarations ?? []).some((d) => 'questionToken' in d && d.questionToken !== undefined);
|
|
333
|
-
if (question)
|
|
334
|
-
return true;
|
|
335
|
-
if (declared.isUnion()) {
|
|
336
|
-
return declared.types.some((t) => (t.flags & this.ts.TypeFlags.Undefined) !== 0);
|
|
337
|
-
}
|
|
338
|
-
return false;
|
|
339
|
-
}
|
|
340
|
-
stripNullish(type) {
|
|
341
|
-
if (!type.isUnion())
|
|
342
|
-
return { stripped: type, nullable: false };
|
|
343
|
-
const hasNull = type.types.some((t) => (t.flags & this.ts.TypeFlags.Null) !== 0);
|
|
344
|
-
const hasUndefined = type.types.some((t) => (t.flags & this.ts.TypeFlags.Undefined) !== 0);
|
|
345
|
-
if (!hasNull && !hasUndefined)
|
|
346
|
-
return { stripped: type, nullable: false };
|
|
347
|
-
const rest = type.types.filter((t) => !(t.flags & (this.ts.TypeFlags.Null | this.ts.TypeFlags.Undefined)));
|
|
348
|
-
if (rest.length === 0)
|
|
349
|
-
return { stripped: type, nullable: hasNull };
|
|
350
|
-
if (rest.length === 1)
|
|
351
|
-
return { stripped: rest[0], nullable: hasNull };
|
|
352
|
-
// Multiple value members plus a nullish member cannot be rebuilt without
|
|
353
|
-
// a public checker union API - surface it rather than guessing.
|
|
354
|
-
throw fail('RPCDART0201', 'union with value members and nullish members cannot be decoded', 'restructure the union', {
|
|
355
|
-
procedurePath: this.currentProcedure,
|
|
356
|
-
});
|
|
357
|
-
}
|
|
358
|
-
typeArgument(type, index) {
|
|
359
|
-
const args = type.typeArguments;
|
|
360
|
-
return args ? args[index] : undefined;
|
|
361
|
-
}
|
|
362
|
-
}
|
|
1
|
+
export { TypeClassificationError, TypeClassifier, pascal } from '@rpc-dart/core';
|
package/dist/extract.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
1
2
|
import path from 'node:path';
|
|
2
3
|
import * as ts from 'typescript';
|
|
3
|
-
import { assembleContract, ExtractionFailure, } from '@rpc-dart/core';
|
|
4
|
-
import {
|
|
4
|
+
import { assembleContract, ExtractionFailure, TypeClassificationError, TypeClassifier, entryImportPath, harnessFileName, neutralizeOptions, overlayHost, pascal, pathAlias, resolutionKind, typeFromAlias, } from '@rpc-dart/core';
|
|
5
|
+
import { buildHarness } from './harness.js';
|
|
5
6
|
import { probeRouter } from './probe.js';
|
|
6
|
-
|
|
7
|
-
const GENERATOR = { name: 'rpc-dart', version:
|
|
7
|
+
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf-8'));
|
|
8
|
+
const GENERATOR = { name: 'rpc-dart', version: pkg.version };
|
|
8
9
|
export async function extractContract(options) {
|
|
9
10
|
const tsconfigDir = path.dirname(options.tsconfigPath);
|
|
10
11
|
const entryAbsolute = path.resolve(tsconfigDir, options.entryFile);
|
|
@@ -38,35 +39,14 @@ export async function extractContract(options) {
|
|
|
38
39
|
}
|
|
39
40
|
const parsed = ts.parseJsonConfigFileContent(configFile.config, ts.sys, tsconfigDir);
|
|
40
41
|
// 3. Virtual harness over the public inference utilities, one alias pair per path.
|
|
41
|
-
const resolution = parsed.options.moduleResolution
|
|
42
|
-
? 'node16'
|
|
43
|
-
: parsed.options.moduleResolution === ts.ModuleResolutionKind.NodeNext
|
|
44
|
-
? 'nodenext'
|
|
45
|
-
: undefined;
|
|
42
|
+
const resolution = resolutionKind(ts, parsed.options.moduleResolution);
|
|
46
43
|
const subscriptionPaths = new Set(probePaths.filter((p) => p.kind === 'subscription').map((p) => p.path));
|
|
47
44
|
const harnessPath = path.join(tsconfigDir, harnessFileName());
|
|
48
45
|
const harnessSource = buildHarness(entryImportPath(tsconfigDir, entryAbsolute, resolution), options.exportName, probePaths.map((p) => p.path), subscriptionPaths);
|
|
49
46
|
// 4. Program under the user's own tsconfig, harness overlaid in memory.
|
|
50
|
-
|
|
51
|
-
// answer type queries on the harness, so build/lint-only flags are
|
|
52
|
-
// neutralized regardless of the user's tsconfig — they would otherwise
|
|
53
|
-
// reject the synthetic harness (rootDir, composite emit rules) or surface
|
|
54
|
-
// lint-only semantic errors (noUnusedLocals/noUnusedParameters,
|
|
55
|
-
// isolatedDeclarations) that have nothing to do with contract extraction.
|
|
56
|
-
const extractionOptions = {
|
|
57
|
-
...parsed.options,
|
|
58
|
-
noEmit: true,
|
|
59
|
-
declaration: false,
|
|
60
|
-
declarationMap: false,
|
|
61
|
-
composite: false,
|
|
62
|
-
incremental: false,
|
|
63
|
-
isolatedDeclarations: false,
|
|
64
|
-
noUnusedLocals: false,
|
|
65
|
-
noUnusedParameters: false,
|
|
66
|
-
rootDir: undefined,
|
|
67
|
-
};
|
|
47
|
+
const extractionOptions = neutralizeOptions(parsed.options);
|
|
68
48
|
const baseHost = ts.createCompilerHost(extractionOptions, true);
|
|
69
|
-
const host = overlayHost(baseHost, harnessPath, harnessSource);
|
|
49
|
+
const host = overlayHost(ts, baseHost, harnessPath, harnessSource);
|
|
70
50
|
const program = ts.createProgram({
|
|
71
51
|
rootNames: [harnessPath, ...parsed.fileNames],
|
|
72
52
|
options: extractionOptions,
|
|
@@ -107,8 +87,8 @@ export async function extractContract(options) {
|
|
|
107
87
|
const entries = [];
|
|
108
88
|
for (const p of probePaths) {
|
|
109
89
|
classifier.currentProcedure = p.path;
|
|
110
|
-
const inputType = typeFromAlias(harnessSf, checker, pathAlias(p.path, 'in'));
|
|
111
|
-
const outputType = typeFromAlias(harnessSf, checker, pathAlias(p.path, 'out'));
|
|
90
|
+
const inputType = typeFromAlias(ts, harnessSf, checker, pathAlias(p.path, 'in'));
|
|
91
|
+
const outputType = typeFromAlias(ts, harnessSf, checker, pathAlias(p.path, 'out'));
|
|
112
92
|
if (outputType === undefined) {
|
|
113
93
|
diagnostics.push({
|
|
114
94
|
code: 'RPCDART0106',
|
|
@@ -155,7 +135,7 @@ export async function extractContract(options) {
|
|
|
155
135
|
if (p.kind === 'subscription') {
|
|
156
136
|
// `tracked()` yields resolve to a true literal via the harness; without
|
|
157
137
|
// tracked events the client cannot resume, so the flag stays false.
|
|
158
|
-
const trackedType = typeFromAlias(harnessSf, checker, pathAlias(p.path, 'tracked'));
|
|
138
|
+
const trackedType = typeFromAlias(ts, harnessSf, checker, pathAlias(p.path, 'tracked'));
|
|
159
139
|
meta.extra['supportsLastEventId'] =
|
|
160
140
|
trackedType !== undefined && checker.typeToString(trackedType) === 'true';
|
|
161
141
|
}
|
|
@@ -170,7 +150,7 @@ export async function extractContract(options) {
|
|
|
170
150
|
entryFile: options.entryFile,
|
|
171
151
|
exportName: options.exportName,
|
|
172
152
|
tsconfigFile: options.tsconfigPath,
|
|
173
|
-
adapterVersion:
|
|
153
|
+
adapterVersion: pkg.version,
|
|
174
154
|
},
|
|
175
155
|
entries,
|
|
176
156
|
});
|
|
@@ -179,34 +159,3 @@ export async function extractContract(options) {
|
|
|
179
159
|
function isVoidish(type) {
|
|
180
160
|
return ((type.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined | ts.TypeFlags.Never)) !== 0);
|
|
181
161
|
}
|
|
182
|
-
function typeFromAlias(sourceFile, checker, name) {
|
|
183
|
-
for (const statement of sourceFile.statements) {
|
|
184
|
-
if (ts.isTypeAliasDeclaration(statement) && statement.name.text === name) {
|
|
185
|
-
return checker.getTypeFromTypeNode(statement.type);
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
return undefined;
|
|
189
|
-
}
|
|
190
|
-
function overlayHost(base, harnessPath, harnessSource) {
|
|
191
|
-
const cache = new Map();
|
|
192
|
-
return {
|
|
193
|
-
...base,
|
|
194
|
-
fileExists(name) {
|
|
195
|
-
return name === harnessPath || base.fileExists(name);
|
|
196
|
-
},
|
|
197
|
-
readFile(name) {
|
|
198
|
-
return name === harnessPath ? harnessSource : base.readFile(name);
|
|
199
|
-
},
|
|
200
|
-
getSourceFile(name, languageVersion, onError, shouldCreate) {
|
|
201
|
-
if (name === harnessPath) {
|
|
202
|
-
const cached = cache.get(name);
|
|
203
|
-
if (cached)
|
|
204
|
-
return cached;
|
|
205
|
-
const sf = ts.createSourceFile(name, harnessSource, languageVersion, true);
|
|
206
|
-
cache.set(name, sf);
|
|
207
|
-
return sf;
|
|
208
|
-
}
|
|
209
|
-
return base.getSourceFile(name, languageVersion, onError, shouldCreate);
|
|
210
|
-
},
|
|
211
|
-
};
|
|
212
|
-
}
|
package/dist/harness.d.ts
CHANGED
|
@@ -1,22 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
* Virtual type-harness generation.
|
|
3
|
-
* The harness imports ONLY the user's router and tRPC's public inference
|
|
4
|
-
* utilities - never private internals. Per-path aliases force indexed-access
|
|
5
|
-
* evaluation so deep conditional/mapped types resolve concretely, and make
|
|
6
|
-
* per-procedure failures point at exactly one line.
|
|
7
|
-
*
|
|
8
|
-
* Subscription procedures get an extra unwrap layer: tRPC v11 subscription
|
|
9
|
-
* outputs are `AsyncGenerator<Y>` / `AsyncIterable<Y>` / `Observable<Y>` and
|
|
10
|
-
* tracked generators wrap each yield in `TrackedEnvelope<T>` ([id, data,
|
|
11
|
-
* symbol]), so the aliases resolve straight to the streamed item type Y.
|
|
12
|
-
*/
|
|
13
|
-
export declare function harnessFileName(): string;
|
|
14
|
-
export type HarnessAliasRole = 'in' | 'out' | 'tracked';
|
|
15
|
-
export declare function pathAlias(path: string, role: HarnessAliasRole): string;
|
|
1
|
+
export { entryImportPath, harnessFileName, pathAlias, type HarnessAliasRole } from '@rpc-dart/core';
|
|
16
2
|
export declare function buildHarness(entryImportPath: string, exportName: string, paths: string[], subscriptionPaths?: ReadonlySet<string>): string;
|
|
17
|
-
/** './router.ts' -> './router' (bundler-style), or explicit extensions under
|
|
18
|
-
* node16/nodenext resolution, where extensionless relative imports are
|
|
19
|
-
* illegal (TS5097) and the TS-standard specifiers (.js/.mjs/.cjs) resolve to
|
|
20
|
-
* the .ts/.mts/.cts sources with or without allowImportingTsExtensions.
|
|
21
|
-
*/
|
|
22
|
-
export declare function entryImportPath(tsconfigDir: string, entryAbsolute: string, resolution?: 'node16' | 'nodenext'): string;
|
package/dist/harness.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Virtual type-harness generation.
|
|
2
|
+
* Virtual type-harness generation (tRPC-specific).
|
|
3
3
|
* The harness imports ONLY the user's router and tRPC's public inference
|
|
4
4
|
* utilities - never private internals. Per-path aliases force indexed-access
|
|
5
5
|
* evaluation so deep conditional/mapped types resolve concretely, and make
|
|
@@ -10,13 +10,8 @@
|
|
|
10
10
|
* tracked generators wrap each yield in `TrackedEnvelope<T>` ([id, data,
|
|
11
11
|
* symbol]), so the aliases resolve straight to the streamed item type Y.
|
|
12
12
|
*/
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
}
|
|
16
|
-
export function pathAlias(path, role) {
|
|
17
|
-
const segments = path.split('.').map((s) => s.replace(/[^A-Za-z0-9_]/g, '_'));
|
|
18
|
-
return ['__p', ...segments, role].join('_');
|
|
19
|
-
}
|
|
13
|
+
import { pathAlias } from '@rpc-dart/core';
|
|
14
|
+
export { entryImportPath, harnessFileName, pathAlias } from '@rpc-dart/core';
|
|
20
15
|
export function buildHarness(entryImportPath, exportName, paths, subscriptionPaths = new Set()) {
|
|
21
16
|
const aliases = paths
|
|
22
17
|
.map((p) => {
|
|
@@ -62,20 +57,3 @@ type __rpc_dart_is_tracked<T> =
|
|
|
62
57
|
${aliases}
|
|
63
58
|
`;
|
|
64
59
|
}
|
|
65
|
-
/** './router.ts' -> './router' (bundler-style), or explicit extensions under
|
|
66
|
-
* node16/nodenext resolution, where extensionless relative imports are
|
|
67
|
-
* illegal (TS5097) and the TS-standard specifiers (.js/.mjs/.cjs) resolve to
|
|
68
|
-
* the .ts/.mts/.cts sources with or without allowImportingTsExtensions.
|
|
69
|
-
*/
|
|
70
|
-
export function entryImportPath(tsconfigDir, entryAbsolute, resolution) {
|
|
71
|
-
const rel = relative(tsconfigDir, entryAbsolute);
|
|
72
|
-
const specifier = resolution === undefined
|
|
73
|
-
? rel.replace(/\.(mts|cts|tsx?)$/, '')
|
|
74
|
-
: rel
|
|
75
|
-
.replace(/\.tsx$/, '.js')
|
|
76
|
-
.replace(/\.mts$/, '.mjs')
|
|
77
|
-
.replace(/\.cts$/, '.cjs')
|
|
78
|
-
.replace(/\.ts$/, '.js');
|
|
79
|
-
return specifier.startsWith('.') ? specifier : `./${specifier}`;
|
|
80
|
-
}
|
|
81
|
-
import { relative } from 'node:path';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export { extractContract, type ExtractOptions, type ExtractPolicies, type ExtractResult, } from './extract.js';
|
|
2
|
-
export { TypeClassificationError, pascal } from '
|
|
2
|
+
export { TypeClassificationError, pascal } from '@rpc-dart/core';
|
|
3
3
|
export { ProbeError, probeRouter, type ProbePath } from './probe.js';
|
package/dist/index.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rpc-dart/trpc-adapter",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "tRPC v11 extraction adapter: route probe, inference harness, and Contract IR normalizer.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
"dist"
|
|
10
10
|
],
|
|
11
11
|
"dependencies": {
|
|
12
|
-
"@rpc-dart/core": "0.
|
|
12
|
+
"@rpc-dart/core": "0.3.0",
|
|
13
13
|
"jiti": "^2.6.0",
|
|
14
14
|
"typescript": "^5.9.0"
|
|
15
15
|
},
|