-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.gen.ts
567 lines (452 loc) · 15.8 KB
/
api.gen.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
import type { TypedDocumentNode } from '@graphql-typed-document-node/core'
import { gql } from 'graphql-tag'
/* tslint:disable */
/* eslint-disable */
const VariableName = ' $1fcbcbff-3e78-462f-b45c-668a3e09bfd8'
const ScalarBrandingField = ' $1fcbcbff-3e78-462f-b45c-668a3e09bfd9'
type CustomScalar<T> = { [ScalarBrandingField]: T }
class Variable<T, Name extends string> {
private [VariableName]: Name
// @ts-ignore
private _type?: T
// @ts-ignore
constructor(name: Name, private readonly isRequired?: boolean) {
this[VariableName] = name
}
}
type ArrayInput<I> = [I] extends [$Atomic] ? never : ReadonlyArray<VariabledInput<I>>
type AllowedInlineScalars<S> = S extends string | number ? S : never
export type UnwrapCustomScalars<T> = T extends CustomScalar<infer S>
? S
: T extends ReadonlyArray<infer I>
? ReadonlyArray<UnwrapCustomScalars<I>>
: T extends Record<string, any>
? { [K in keyof T]: UnwrapCustomScalars<T[K]> }
: T
type VariableWithoutScalars<T, Str extends string> = Variable<UnwrapCustomScalars<T>, Str>
// the array wrapper prevents distributive conditional types
// https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
type VariabledInput<T> = [T] extends [CustomScalar<infer S> | null | undefined]
? // scalars only support variable input
Variable<S | null | undefined, any> | AllowedInlineScalars<S> | null | undefined
: [T] extends [CustomScalar<infer S>]
? Variable<S, any> | AllowedInlineScalars<S>
: [T] extends [$Atomic]
? Variable<T, any> | T
: T extends ReadonlyArray<infer I>
? VariableWithoutScalars<T, any> | T | ArrayInput<I>
: T extends Record<string, any> | null | undefined
?
| VariableWithoutScalars<T | null | undefined, any>
| null
| undefined
| { [K in keyof T]: VariabledInput<T[K]> }
| T
: T extends Record<string, any>
? VariableWithoutScalars<T, any> | { [K in keyof T]: VariabledInput<T[K]> } | T
: never
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void
? I
: never
/**
* Creates a new query variable
*
* @param name The variable name
*/
export const $ = <Type, Name extends string>(name: Name): Variable<Type, Name> => {
return new Variable(name)
}
/**
* Creates a new query variable. A value will be required even if the input is optional
*
* @param name The variable name
*/
export const $$ = <Type, Name extends string>(name: Name): Variable<NonNullable<Type>, Name> => {
return new Variable(name, true)
}
type SelectOptions = {
argTypes?: { [key: string]: string }
args?: { [key: string]: any }
selection?: Selection<any>
}
class $Field<Name extends string, Type, Vars = {}> {
public kind: 'field' = 'field'
public type!: Type
public vars!: Vars
public alias: string | null = null
constructor(public name: Name, public options: SelectOptions) {}
as<Rename extends string>(alias: Rename): $Field<Rename, Type, Vars> {
const f = new $Field(this.name, this.options)
f.alias = alias
return f as any
}
}
class $Base<Name extends string> {
// @ts-ignore
constructor(private $$name: Name) {}
protected $_select<Key extends string>(
name: Key,
options: SelectOptions = {}
): $Field<Key, any, any> {
return new $Field(name, options)
}
}
// @ts-ignore
class $Union<T, Name extends String> extends $Base<Name> {
// @ts-ignore
private $$type!: T
// @ts-ignore
private $$name!: Name
constructor(private selectorClasses: { [K in keyof T]: { new (): T[K] } }, $$name: Name) {
super($$name)
}
$on<Type extends keyof T, Sel extends Selection<T[Type]>>(
alternative: Type,
selectorFn: (selector: T[Type]) => [...Sel]
): $UnionSelection<GetOutput<Sel>, GetVariables<Sel>> {
const selection = selectorFn(new this.selectorClasses[alternative]())
return new $UnionSelection(alternative as string, selection)
}
}
// @ts-ignore
class $Interface<T, Name extends string> extends $Base<Name> {
// @ts-ignore
private $$type!: T
// @ts-ignore
private $$name!: Name
constructor(private selectorClasses: { [K in keyof T]: { new (): T[K] } }, $$name: Name) {
super($$name)
}
$on<Type extends keyof T, Sel extends Selection<T[Type]>>(
alternative: Type,
selectorFn: (selector: T[Type]) => [...Sel]
): $UnionSelection<GetOutput<Sel>, GetVariables<Sel>> {
const selection = selectorFn(new this.selectorClasses[alternative]())
return new $UnionSelection(alternative as string, selection)
}
}
class $UnionSelection<T, Vars> {
public kind: 'union' = 'union'
// @ts-ignore
private vars!: Vars
constructor(public alternativeName: string, public alternativeSelection: Selection<T>) {}
}
type Selection<_any> = ReadonlyArray<$Field<any, any, any> | $UnionSelection<any, any>>
type NeverNever<T> = [T] extends [never] ? {} : T
type Simplify<T> = { [K in keyof T]: T[K] } & {}
type LeafType<T> = T extends CustomScalar<infer S> ? S : T
export type GetOutput<X extends Selection<any>> = Simplify<
UnionToIntersection<
{
[I in keyof X]: X[I] extends $Field<infer Name, infer Type, any>
? { [K in Name]: LeafType<Type> }
: never
}[keyof X & number]
> &
NeverNever<
{
[I in keyof X]: X[I] extends $UnionSelection<infer Type, any> ? LeafType<Type> : never
}[keyof X & number]
>
>
type PossiblyOptionalVar<VName extends string, VType> = undefined extends VType
? { [key in VName]?: VType }
: null extends VType
? { [key in VName]?: VType }
: { [key in VName]: VType }
type ExtractInputVariables<Inputs> = Inputs extends Variable<infer VType, infer VName>
? PossiblyOptionalVar<VName, VType>
: // Avoid generating an index signature for possibly undefined or null inputs.
// The compiler incorrectly infers null or undefined, and we must force access the Inputs
// type to convince the compiler its "never", while still retaining {} as the result
// for null and undefined cases
// Works around issue 79
Inputs extends null | undefined
? { [K in keyof Inputs]: Inputs[K] }
: Inputs extends $Atomic
? {}
: Inputs extends any[] | readonly any[]
? UnionToIntersection<
{ [K in keyof Inputs]: ExtractInputVariables<Inputs[K]> }[keyof Inputs & number]
>
: UnionToIntersection<{ [K in keyof Inputs]: ExtractInputVariables<Inputs[K]> }[keyof Inputs]>
export type GetVariables<Sel extends Selection<any>, ExtraVars = {}> = UnionToIntersection<
{
[I in keyof Sel]: Sel[I] extends $Field<any, any, infer Vars>
? Vars
: Sel[I] extends $UnionSelection<any, infer Vars>
? Vars
: never
}[keyof Sel & number]
> &
ExtractInputVariables<ExtraVars>
type ArgVarType = {
type: string
isRequired: boolean
array: {
isRequired: boolean
} | null
}
const arrRegex = /\[(.*?)\]/
/**
* Converts graphql string type to `ArgVarType`
* @param input
* @returns
*/
function getArgVarType(input: string): ArgVarType {
const array = input.includes('[')
? {
isRequired: input.endsWith('!'),
}
: null
const type = array ? arrRegex.exec(input)![1]! : input
const isRequired = type.endsWith('!')
return {
array,
isRequired: isRequired,
type: type.replace('!', ''),
}
}
function fieldToQuery(prefix: string, field: $Field<any, any, any>) {
const variables = new Map<string, { variable: Variable<any, any>; type: ArgVarType }>()
function stringifyArgs(
args: any,
argTypes: { [key: string]: string },
argVarType?: ArgVarType
): string {
switch (typeof args) {
case 'string':
const cleanType = argVarType!.type
if ($Enums.has(cleanType!)) return args
else return JSON.stringify(args)
case 'number':
case 'boolean':
return JSON.stringify(args)
default:
if (args == null) return 'null'
if (VariableName in (args as any)) {
if (!argVarType)
throw new globalThis.Error('Cannot use variabe as sole unnamed field argument')
const variable = args as Variable<any, any>
const argVarName = variable[VariableName]
variables.set(argVarName, { type: argVarType, variable: variable })
return '$' + argVarName
}
if (Array.isArray(args))
return '[' + args.map(arg => stringifyArgs(arg, argTypes, argVarType)).join(',') + ']'
const wrapped = (content: string) => (argVarType ? '{' + content + '}' : content)
return wrapped(
Array.from(Object.entries(args))
.map(([key, val]) => {
let argTypeForKey = argTypes[key]
if (!argTypeForKey) {
throw new globalThis.Error(`Argument type for ${key} not found`)
}
const cleanType = argTypeForKey.replace('[', '').replace(']', '').replace(/!/g, '')
return (
key +
':' +
stringifyArgs(val, $InputTypes[cleanType]!, getArgVarType(argTypeForKey))
)
})
.join(',')
)
}
}
function extractTextAndVars(field: $Field<any, any, any> | $UnionSelection<any, any>) {
if (field.kind === 'field') {
let retVal = field.name
if (field.alias) retVal = field.alias + ':' + retVal
const args = field.options.args,
argTypes = field.options.argTypes
if (args && Object.keys(args).length > 0) {
retVal += '(' + stringifyArgs(args, argTypes!) + ')'
}
let sel = field.options.selection
if (sel) {
retVal += '{'
for (let subField of sel) {
retVal += extractTextAndVars(subField)
}
retVal += '}'
}
return retVal + ' '
} else if (field.kind === 'union') {
let retVal = '... on ' + field.alternativeName + ' {'
for (let subField of field.alternativeSelection) {
retVal += extractTextAndVars(subField)
}
retVal += '}'
return retVal + ' '
} else {
throw new globalThis.Error('Uknown field kind')
}
}
const queryRaw = extractTextAndVars(field)!
const queryBody = queryRaw.substring(queryRaw.indexOf('{'))
const varList = Array.from(variables.entries())
let ret = prefix
if (varList.length) {
ret +=
'(' +
varList
.map(([name, { type: kind, variable }]) => {
let type = kind.array ? '[' : ''
type += kind.type
if (kind.isRequired) type += '!'
if (kind.array) type += kind.array.isRequired ? ']!' : ']'
if (!type.endsWith('!') && (variable as any).isRequired === true) {
type += '!'
}
return '$' + name + ':' + type
})
.join(',') +
')'
}
ret += queryBody
return ret
}
export type OutputTypeOf<T> = T extends $Interface<infer Subtypes, any>
? { [K in keyof Subtypes]: OutputTypeOf<Subtypes[K]> }[keyof Subtypes]
: T extends $Union<infer Subtypes, any>
? { [K in keyof Subtypes]: OutputTypeOf<Subtypes[K]> }[keyof Subtypes]
: T extends $Base<any>
? { [K in keyof T]?: OutputTypeOf<T[K]> }
: [T] extends [$Field<any, infer FieldType, any>]
? FieldType
: [T] extends [(selFn: (arg: infer Inner) => any) => any]
? OutputTypeOf<Inner>
: [T] extends [(args: any, selFn: (arg: infer Inner) => any) => any]
? OutputTypeOf<Inner>
: never
export type QueryOutputType<T extends TypedDocumentNode<any>> = T extends TypedDocumentNode<
infer Out
>
? Out
: never
export type QueryInputType<T extends TypedDocumentNode<any>> = T extends TypedDocumentNode<
any,
infer In
>
? In
: never
export function fragment<T, Sel extends Selection<T>>(
GQLType: { new (): T },
selectFn: (selector: T) => [...Sel]
) {
return selectFn(new GQLType())
}
type LastOf<T> = UnionToIntersection<T extends any ? () => T : never> extends () => infer R
? R
: never
// TS4.0+
type Push<T extends any[], V> = [...T, V]
// TS4.1+
type TuplifyUnion<T, L = LastOf<T>, N = [T] extends [never] ? true : false> = true extends N
? []
: Push<TuplifyUnion<Exclude<T, L>>, L>
type AllFieldProperties<I> = {
[K in keyof I]: I[K] extends $Field<infer Name, infer Type, any> ? $Field<Name, Type, any> : never
}
type ValueOf<T> = T[keyof T]
export type AllFields<T> = TuplifyUnion<ValueOf<AllFieldProperties<T>>>
export function all<I extends $Base<any>>(instance: I) {
const prototype = Object.getPrototypeOf(instance)
const allFields = Object.getOwnPropertyNames(prototype)
.map(k => prototype[k])
.filter(o => o?.kind === 'field')
.map(o => o?.name) as (keyof typeof instance)[]
return allFields.map(fieldName => instance?.[fieldName]) as any as AllFields<I>
}
// We use a dummy conditional type that involves GenericType to defer the compiler's inference of
// any possible variables nested in this type. This addresses a problem where variables are
// inferred with type unknown
type ExactArgNames<GenericType, Constraint> = GenericType extends never
? never
: [Constraint] extends [$Atomic | CustomScalar<any>]
? GenericType
: Constraint extends ReadonlyArray<infer InnerConstraint>
? GenericType extends ReadonlyArray<infer Inner>
? ReadonlyArray<ExactArgNames<Inner, InnerConstraint>>
: GenericType
: GenericType & {
[Key in keyof GenericType]: Key extends keyof Constraint
? ExactArgNames<GenericType[Key], Constraint[Key]>
: never
}
type $Atomic = number | string | boolean | null | undefined
let $Enums = new Set<string>([])
export class Author extends $Base<"Author"> {
constructor() {
super("Author")
}
get id(): $Field<"id", number> {
return this.$_select("id") as any
}
get name(): $Field<"name", string> {
return this.$_select("name") as any
}
get __typename(): $Field<"__typename", "Author"> {
return this.$_select("__typename") as any
}
}
export class Post extends $Base<"Post"> {
constructor() {
super("Post")
}
author<Sel extends Selection<Author>>(selectorFn: (s: Author) => [...Sel]):$Field<"author", GetOutput<Sel> | undefined , GetVariables<Sel>> {
const options = {
selection: selectorFn(new Author)
};
return this.$_select("author", options as any) as any
}
get id(): $Field<"id", number> {
return this.$_select("id") as any
}
get title(): $Field<"title", string> {
return this.$_select("title") as any
}
get __typename(): $Field<"__typename", "Post"> {
return this.$_select("__typename") as any
}
}
export class Query extends $Base<"Query"> {
constructor() {
super("Query")
}
posts<Sel extends Selection<Post>>(selectorFn: (s: Post) => [...Sel]):$Field<"posts", Array<GetOutput<Sel>> | undefined , GetVariables<Sel>> {
const options = {
selection: selectorFn(new Post)
};
return this.$_select("posts", options as any) as any
}
get __typename(): $Field<"__typename", "Query"> {
return this.$_select("__typename") as any
}
}
const $Root = {
query: Query
}
namespace $RootTypes {
export type query = Query
}
export function query<Sel extends Selection<$RootTypes.query>>(
name: string,
selectFn: (q: $RootTypes.query) => [...Sel]
): TypedDocumentNode<GetOutput<Sel>, GetVariables<Sel>>
export function query<Sel extends Selection<$RootTypes.query>>(
selectFn: (q: $RootTypes.query) => [...Sel]
): TypedDocumentNode<GetOutput<Sel>, Simplify<GetVariables<Sel>>>
export function query<Sel extends Selection<$RootTypes.query>>(name: any, selectFn?: any) {
if (!selectFn) {
selectFn = name
name = ''
}
let field = new $Field<'query', GetOutput<Sel>, GetVariables<Sel>>('query', {
selection: selectFn(new $Root.query()),
})
const str = fieldToQuery(`query ${name}`, field)
return gql(str) as any
}
const $InputTypes: {[key: string]: {[key: string]: string}} = {
}