-
Notifications
You must be signed in to change notification settings - Fork 276
/
Copy pathtypegenAutoConfig.ts
302 lines (274 loc) · 9.98 KB
/
typegenAutoConfig.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
import { GraphQLNamedType, GraphQLSchema, isOutputType } from 'graphql'
import type { TypegenInfo } from './builder'
import type { TypingImport } from './definitions/_types'
import { TYPEGEN_HEADER } from './lang'
import { nodeImports } from './node'
import { getOwnPackage, log, objValues, relativePathTo, typeScriptFileExtension } from './utils'
/** Any common types / constants that would otherwise be circular-imported */
export const SCALAR_TYPES = {
Int: 'number',
String: 'string',
ID: 'string',
Float: 'number',
Boolean: 'boolean',
}
export interface SourceTypeModule {
/**
* The module for where to look for the types. This uses the node resolution algorithm via require.resolve,
* so if this lives in node_modules, you can just provide the module name otherwise you should provide the
* absolute path to the file.
*/
module: string
/**
* When we import the module, we use `import * as ____` to prevent conflicts. This alias should be a name
* that doesn't conflict with any other types, usually a short lowercase name.
*/
alias: string
/**
* Provides a custom approach to matching for the type
*
* If not provided, the default implementation is:
*
* (type) => [ new RegExp(`(?:interface|type|class|enum)\\s+(${type.name})\\W`, "g"), ]
*/
typeMatch?: (type: GraphQLNamedType, defaultRegex: RegExp) => RegExp | RegExp[]
/**
* A list of typesNames or regular expressions matching type names that should be resolved by this import.
* Provide an empty array if you wish to use the file for context and ensure no other types are matched.
*/
onlyTypes?: (string | RegExp)[]
/**
* By default the import is configured `import * as alias from`, setting glob to false will change this to
* `import alias from`
*/
glob?: false
}
export interface SourceTypesConfigOptions {
/** Any headers to prefix on the generated type file */
headers?: string[]
/**
* Array of SourceTypeModule's to look in and match the type names against.
*
* @example
* modules: [
* { module: 'typescript', alias: 'ts' },
* { module: path.join(__dirname, '../sourceTypes'), alias: 'b' },
* ]
*/
modules: SourceTypeModule[]
/**
* Types that should not be matched for a source type,
*
* By default this is set to ['Query', 'Mutation', 'Subscription']
*
* @example
* skipTypes: ['Query', 'Mutation', /(.*?)Edge/, /(.*?)Connection/]
*/
skipTypes?: (string | RegExp)[]
/**
* If debug is set to true, this will log out info about all types found, skipped, etc. for the type
* generation files. @default false
*/
debug?: boolean
/**
* If provided this will be used for the source types rather than the auto-resolve mechanism above. Useful
* as an override for one-off cases, or for scalar source types.
*/
mapping?: Record<string, string>
}
/**
* This is an approach for handling type definition auto-resolution. It is designed to handle the most common
* cases, as can be seen in the examples / the simplicity of the implementation.
*
* If you wish to do something more complex, involving full AST parsing, etc, you can provide a different
* function to the `typegenInfo` property of the `makeSchema` config.
*
* @param options
*/
export function typegenAutoConfig(options: SourceTypesConfigOptions, contextType: TypingImport | undefined) {
return async (schema: GraphQLSchema, outputPath: string): Promise<TypegenInfo> => {
const {
headers,
skipTypes = ['Query', 'Mutation', 'Subscription'],
mapping: _sourceTypeMap,
debug,
} = options
const typeMap = schema.getTypeMap()
const typesToIgnore = new Set<string>()
const typesToIgnoreRegex: RegExp[] = []
const allImportsMap: Record<string, string> = {}
const importsMap: Record<string, [string, boolean]> = {}
const sourceTypeMap: Record<string, string> = {
...SCALAR_TYPES,
..._sourceTypeMap,
}
const forceImports = new Set(
objValues(sourceTypeMap)
.concat(typeof contextType === 'string' ? contextType || '' : '')
.map((t) => {
const match = t.match(/^(\w+)\./)
return match ? match[1] : null
})
.filter((f) => f)
)
skipTypes.forEach((skip) => {
if (typeof skip === 'string') {
typesToIgnore.add(skip)
} else if (skip instanceof RegExp) {
typesToIgnoreRegex.push(skip)
} else {
throw new Error('Invalid type for options.skipTypes, expected string or RegExp')
}
})
const path = nodeImports().path
const typeSources = await Promise.all(
options.modules.map(async (source) => {
// Keeping all of this in here so if we don't have any sources
// e.g. in the Playground, it doesn't break things.
const { module: pathOrModule, glob = true, onlyTypes, alias, typeMatch } = source
if (path.isAbsolute(pathOrModule) && path.extname(pathOrModule) !== '.ts') {
return console.warn(
`Nexus Schema Typegen: Expected module ${pathOrModule} to be an absolute path to a TypeScript module, skipping.`
)
}
let resolvedPath: string
let fileContents: string
try {
resolvedPath = require.resolve(pathOrModule, {
paths: [process.cwd()],
})
if (path.extname(resolvedPath) !== '.ts') {
resolvedPath = findTypingForFile(resolvedPath, pathOrModule)
}
fileContents = String(await nodeImports().fs.promises.readFile(resolvedPath, 'utf-8'))
} catch (e) {
if (e instanceof Error && e.message.indexOf('Cannot find module') !== -1) {
console.error(`GraphQL Nexus: Unable to find file or module ${pathOrModule}, skipping`)
} else {
console.error(e.message)
}
return null
}
const importPath = (
path.isAbsolute(pathOrModule) ? relativePathTo(resolvedPath, outputPath) : pathOrModule
).replace(typeScriptFileExtension, '')
if (allImportsMap[alias] && allImportsMap[alias] !== importPath) {
return console.warn(
`Nexus Schema Typegen: Cannot have multiple type sources ${importsMap[alias]} and ${pathOrModule} with the same alias ${alias}, skipping`
)
}
allImportsMap[alias] = importPath
if (forceImports.has(alias)) {
importsMap[alias] = [importPath, glob]
forceImports.delete(alias)
}
return {
alias,
glob,
importPath,
fileContents,
onlyTypes,
typeMatch: typeMatch || defaultTypeMatcher,
}
})
)
const builtinScalars = new Set(Object.keys(SCALAR_TYPES))
Object.keys(typeMap).forEach((typeName) => {
if (typeName.startsWith('__')) {
return
}
if (typesToIgnore.has(typeName)) {
return
}
if (typesToIgnoreRegex.some((r) => r.test(typeName))) {
return
}
if (sourceTypeMap[typeName]) {
return
}
if (builtinScalars.has(typeName)) {
return
}
const type = schema.getType(typeName)
// For now we'll say that if it's output type it can be backed
if (isOutputType(type)) {
for (let i = 0; i < typeSources.length; i++) {
const typeSource = typeSources[i]
if (!typeSource) {
continue
}
// If we've specified an array of "onlyTypes" to match ensure the
// `typeName` falls within that list.
if (typeSource.onlyTypes) {
if (
!typeSource.onlyTypes.some((t) => {
return t instanceof RegExp ? t.test(typeName) : t === typeName
})
) {
continue
}
}
const { fileContents, importPath, glob, alias, typeMatch } = typeSource
const typeRegex = typeMatch(type, defaultTypeMatcher(type)[0])
const matched = firstMatch(fileContents, Array.isArray(typeRegex) ? typeRegex : [typeRegex])
if (matched) {
if (debug) {
log(`Matched type - ${typeName} in "${importPath}" - ${alias}.${matched[1]}`)
}
importsMap[alias] = [importPath, glob]
sourceTypeMap[typeName] = `${alias}.${matched[1]}`
} else {
if (debug) {
log(`No match for ${typeName} in "${importPath}" using ${typeRegex}`)
}
}
}
}
})
if (forceImports.size > 0) {
console.error(`Missing required typegen import: ${Array.from(forceImports)}`)
}
const imports: string[] = []
Object.keys(importsMap)
.sort()
.forEach((alias) => {
const [importPath, glob] = importsMap[alias]
const safeImportPath = importPath.replace(/\\+/g, '/')
imports.push(`import type ${glob ? '* as ' : ''}${alias} from "${safeImportPath}"`)
})
const typegenInfo = {
headers: headers || [TYPEGEN_HEADER],
sourceTypeMap,
imports,
contextTypeImport: contextType,
nexusSchemaImportId: getOwnPackage().name,
}
return typegenInfo
}
}
function findTypingForFile(absolutePath: string, pathOrModule: string) {
// First try to find the "d.ts" adjacent to the file
try {
const typeDefPath = absolutePath.replace(nodeImports().path.extname(absolutePath), '.d.ts')
require.resolve(typeDefPath)
return typeDefPath
} catch (e) {
console.error(e)
}
// TODO: need to figure out cases where it's a node module
// and "typings" is set in the package.json
throw new Error(`Unable to find typings associated with ${pathOrModule}, skipping`)
}
const firstMatch = (fileContents: string, typeRegex: RegExp[]): RegExpExecArray | null => {
for (let i = 0; i < typeRegex.length; i++) {
const regex = typeRegex[i]
const match = regex.exec(fileContents)
if (match) {
return match
}
}
return null
}
const defaultTypeMatcher = (type: GraphQLNamedType) => {
return [new RegExp(`(?:interface|type|class|enum)\\s+(${type.name})\\W`, 'g')]
}