@sanity/codegen 3.88.0 → 3.88.1-typegen-experimental.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.
@@ -1,374 +1,513 @@
1
+ /* eslint-disable max-nested-callbacks */
1
2
  import {CodeGenerator} from '@babel/generator'
2
3
  import * as t from '@babel/types'
3
- import {
4
- type ArrayTypeNode,
5
- type DocumentSchemaType,
6
- type InlineTypeNode,
7
- type ObjectAttribute,
8
- type ObjectTypeNode,
9
- type SchemaType,
10
- type TypeDeclarationSchemaType,
11
- type TypeNode,
12
- type UnionTypeNode,
13
- } from 'groq-js'
14
-
15
- const REFERENCE_SYMBOL_NAME = 'internalGroqTypeReferenceTo'
16
- const ALL_SCHEMA_TYPES = 'AllSanitySchemaTypes'
17
-
18
- type QueryWithTypeNode = {
4
+ import {type SchemaType} from 'groq-js'
5
+
6
+ import {AsyncQueue} from './asyncQueue'
7
+ import {type NamedQueryResult} from './expressionResolvers'
8
+ import {type QueryExtractionResult} from './findQueriesInPath'
9
+ import {SchemaTypeGenerator, type TypeEvaluationStats} from './schemaTypeGenerator'
10
+
11
+ const SanityQueries = t.identifier('SanityQueries')
12
+ const SanityProjections = t.identifier('SanityProjections')
13
+ const SanitySchemas = t.identifier('SanitySchemas')
14
+ const SchemaOrigin = t.identifier('SchemaOrigin')
15
+ const PickSchema = t.identifier('PickSchema')
16
+ const AllSanitySchemaTypes = t.identifier('AllSanitySchemaTypes')
17
+
18
+ export interface QueryResultDeclaration {
19
+ filename: string
20
+ name: string
21
+ id: t.Identifier
19
22
  query: string
20
- typeNode: TypeNode
23
+ code: string
24
+ type: 'query' | 'projection'
25
+ stats: TypeEvaluationStats
21
26
  }
22
27
 
28
+ export type QueryResultDeclarationsFileResult =
29
+ | {
30
+ type: 'queries'
31
+ filename: string
32
+ queryResultDeclarations: QueryResultDeclaration[]
33
+ }
34
+ | {
35
+ type: 'error'
36
+ filename: string
37
+ error: unknown
38
+ }
39
+
23
40
  /**
24
- * A class used to generate TypeScript types from a given schema
25
41
  * @internal
26
- * @beta
27
42
  */
28
- export class TypeGenerator {
29
- // Simple set to keep track of generated type names, to avoid conflicts
30
- private generatedTypeName: Set<string> = new Set()
31
- // Map between type names and their generated type names, used to resolve the correct generated type name
32
- private typeNameMap: Map<string, string> = new Map()
33
- // Map between type nodes and their generated type names, used for query mapping
34
- private typeNodeNameMap: Map<TypeNode | DocumentSchemaType | TypeDeclarationSchemaType, string> =
35
- new Map()
36
-
37
- private readonly schema: SchemaType
43
+ export interface TypeGeneratorOptions {
44
+ schemas: {schema: SchemaType; schemaId: string; filename?: string}[]
45
+ queriesByFile?: AsyncIterable<QueryExtractionResult>
46
+ augmentGroqModule?: boolean
47
+ overloadClientMethods?: boolean
48
+ }
38
49
 
39
- constructor(schema: SchemaType) {
40
- this.schema = schema
50
+ /**
51
+ * @internal
52
+ */
53
+ export class TypeGenerator {
54
+ public readonly schemas: SchemaTypeGenerator[]
55
+ public readonly augmentGroqModule: boolean
56
+ public readonly overloadClientMethods: boolean
57
+
58
+ private schemaFilenames = new Map<string, string>()
59
+ private globalIdentifiers = new Set<string>()
60
+ private identifiersByQuery = new Map<string, t.Identifier[]>()
61
+ private identifiersByProjection = new Map<string, t.Identifier[]>()
62
+ private queryResultsQueue = new AsyncQueue<QueryResultDeclarationsFileResult>()
63
+ private augmentedQueryResultsPromise = promiseWithResolvers<{code: string}>()
64
+ private queryFileCountPromise = promiseWithResolvers<{fileCount: number}>()
65
+
66
+ constructor({
67
+ schemas,
68
+ queriesByFile,
69
+ augmentGroqModule = true,
70
+ overloadClientMethods = true,
71
+ }: TypeGeneratorOptions) {
72
+ this.globalIdentifiers.add(SanityQueries.name)
73
+ this.globalIdentifiers.add(SanityProjections.name)
74
+ this.globalIdentifiers.add(SanitySchemas.name)
75
+ this.globalIdentifiers.add(SchemaOrigin.name)
76
+ this.globalIdentifiers.add(PickSchema.name)
77
+ this.globalIdentifiers.add(AllSanitySchemaTypes.name)
78
+ this.globalIdentifiers.add(SchemaTypeGenerator.InternalReferenceSymbol.name)
79
+ this.globalIdentifiers.add(SchemaTypeGenerator.ProjectionBase.name)
80
+
81
+ const schemaIds = new Set<string>()
82
+ for (const {schemaId, filename} of schemas) {
83
+ if (schemaIds.has(schemaId)) {
84
+ throw new Error(`Duplicate schema ID "${schemaId}". Schema IDs must be unique.`)
85
+ }
86
+ schemaIds.add(schemaId)
87
+ if (filename) {
88
+ this.schemaFilenames.set(schemaId, filename)
89
+ }
90
+ }
41
91
 
42
- this.schema.forEach((s) => {
43
- this.getTypeName(s.name, s)
44
- })
92
+ this.schemas = schemas.map((opts) => new SchemaTypeGenerator(opts))
93
+ this.augmentGroqModule = augmentGroqModule
94
+ this.overloadClientMethods = overloadClientMethods
95
+
96
+ // We need to eagerly compute these in the constructor because
97
+ // `generateAndRegisterExportedTypeAlias` has a side effect of reserving
98
+ // global identifier names. The order also matters as `getSchemaDeclarations`
99
+ // depends on the identifiers generated by `getSchemaTypeDeclarations`.
100
+ this.getSchemaTypeDeclarations()
101
+ this.getSchemaDeclarations()
102
+
103
+ if (queriesByFile) {
104
+ this.handleQueries(queriesByFile).catch((error) => {
105
+ this.queryFileCountPromise.reject(error)
106
+ this.queryResultsQueue.throwError(error)
107
+ this.augmentedQueryResultsPromise.reject(error)
108
+ })
109
+ } else {
110
+ this.queryFileCountPromise.resolve({fileCount: 0})
111
+ }
45
112
  }
46
113
 
47
- /**
48
- * Generate TypeScript types for the given schema
49
- * @returns string
50
- * @internal
51
- * @beta
52
- */
53
- generateSchemaTypes(): string {
54
- const typeDeclarations: (t.TSTypeAliasDeclaration | t.ExportNamedDeclaration)[] = []
55
-
56
- const schemaNames = new Set<string>()
57
- this.schema.forEach((schema) => {
58
- const typeLiteral = this.getTypeNodeType(schema)
59
-
60
- const schemaName = this.typeNodeNameMap.get(schema)
61
- if (!schemaName) {
62
- throw new Error(`Schema name not found for schema ${schema.name}`)
114
+ private async handleQueries(queriesByFile: AsyncIterable<QueryExtractionResult>) {
115
+ for await (const result of queriesByFile) {
116
+ if (result.type === 'files') {
117
+ this.queryFileCountPromise.resolve({fileCount: result.fileCount})
118
+ continue
63
119
  }
64
120
 
65
- schemaNames.add(schemaName)
66
- const typeAlias = t.tsTypeAliasDeclaration(t.identifier(schemaName), null, typeLiteral)
121
+ try {
122
+ if (result.type === 'error') throw result.error
123
+ const {filename, queries} = result
124
+
125
+ const queryResultDeclarations: QueryResultDeclaration[] = []
126
+ for (const query of queries) {
127
+ try {
128
+ queryResultDeclarations.push({
129
+ filename,
130
+ query: query.result,
131
+ ...this.generateQueryResultType({...query, filename}),
132
+ })
133
+ } catch (error) {
134
+ this.queryResultsQueue.enqueue({type: 'error', filename, error})
135
+ }
136
+ }
67
137
 
68
- typeDeclarations.push(t.exportNamedDeclaration(typeAlias))
69
- })
138
+ this.queryResultsQueue.enqueue({type: 'queries', filename, queryResultDeclarations})
139
+ } catch (error) {
140
+ this.queryResultsQueue.enqueue({type: 'error', filename: result.filename, error})
141
+ }
142
+ }
70
143
 
71
- typeDeclarations.push(
72
- t.exportNamedDeclaration(
73
- t.tsTypeAliasDeclaration(
74
- t.identifier(this.getTypeName(ALL_SCHEMA_TYPES)),
75
- null,
76
- t.tsUnionType(
77
- [...schemaNames].map((typeName) => t.tsTypeReference(t.identifier(typeName))),
144
+ this.queryResultsQueue.finish()
145
+
146
+ let augmentedQueryResultsCode = ''
147
+ const clientModuleBlockStatement: t.Statement[] = []
148
+ const groqModuleBlockStatement: t.Statement[] = []
149
+
150
+ // Only generate SanityQueries if there are query results
151
+ if (this.identifiersByQuery.size > 0) {
152
+ const sanityQueriesInterfaceDeclaration = t.tsInterfaceDeclaration(
153
+ SanityQueries,
154
+ null,
155
+ [],
156
+ t.tsInterfaceBody(
157
+ Array.from(this.identifiersByQuery).map(([query, identifiers]) =>
158
+ t.tsPropertySignature(
159
+ t.stringLiteral(query),
160
+ t.tsTypeAnnotation(
161
+ identifiers.length === 1
162
+ ? t.tsTypeReference(identifiers[0])
163
+ : t.tsUnionType(identifiers.map((i) => t.tsTypeReference(i))),
164
+ ),
165
+ ),
78
166
  ),
79
167
  ),
80
- ),
81
- )
168
+ )
169
+ // Add to both module declarations if needed
170
+ clientModuleBlockStatement.push(sanityQueriesInterfaceDeclaration)
171
+ groqModuleBlockStatement.push(sanityQueriesInterfaceDeclaration)
172
+ }
82
173
 
83
- // Generate TypeScript code from the AST nodes
84
- return typeDeclarations.map((decl) => new CodeGenerator(decl).generate().code).join('\n\n')
85
- }
174
+ // Only generate SanityProjections if there are projection results
175
+ if (this.identifiersByProjection.size > 0) {
176
+ const sanityProjectionsInterfaceDeclaration = t.tsInterfaceDeclaration(
177
+ SanityProjections,
178
+ null,
179
+ [],
180
+ t.tsInterfaceBody(
181
+ Array.from(this.identifiersByProjection).map(([projection, identifiers]) =>
182
+ t.tsPropertySignature(
183
+ t.stringLiteral(projection),
184
+ t.tsTypeAnnotation(
185
+ identifiers.length === 1
186
+ ? t.tsTypeReference(identifiers[0])
187
+ : t.tsUnionType(identifiers.map((i) => t.tsTypeReference(i))),
188
+ ),
189
+ ),
190
+ ),
191
+ ),
192
+ )
86
193
 
87
- /**
88
- * Takes a identifier and a type node and generates a type alias for the type node.
89
- * @param identifierName - The name of the type to generated
90
- * @param typeNode - The type node to generate the type for
91
- * @returns
92
- * @internal
93
- * @beta
94
- */
95
- generateTypeNodeTypes(identifierName: string, typeNode: TypeNode): string {
96
- const type = this.getTypeNodeType(typeNode)
97
-
98
- const typeName = this.getTypeName(identifierName, typeNode)
99
- const typeAlias = t.tsTypeAliasDeclaration(t.identifier(typeName), null, type)
100
-
101
- return new CodeGenerator(t.exportNamedDeclaration(typeAlias)).generate().code.trim()
102
- }
194
+ // Add only to groq module declaration
195
+ groqModuleBlockStatement.push(sanityProjectionsInterfaceDeclaration)
196
+ }
103
197
 
104
- static generateKnownTypes(): string {
105
- const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword())
106
- typeOperator.operator = 'unique'
198
+ if (this.overloadClientMethods && clientModuleBlockStatement.length > 0) {
199
+ const clientModuleDeclaration = t.declareModule(
200
+ t.stringLiteral('@sanity/client'),
201
+ t.blockStatement(clientModuleBlockStatement),
202
+ )
203
+ augmentedQueryResultsCode += generateCode(clientModuleDeclaration)
204
+ }
107
205
 
108
- const identifier = t.identifier(REFERENCE_SYMBOL_NAME)
109
- identifier.typeAnnotation = t.tsTypeAnnotation(typeOperator)
206
+ if (this.augmentGroqModule && groqModuleBlockStatement.length > 0) {
207
+ const groqModuleDeclaration = t.declareModule(
208
+ t.stringLiteral('groq'),
209
+ t.blockStatement(groqModuleBlockStatement),
210
+ )
211
+ augmentedQueryResultsCode += generateCode(groqModuleDeclaration)
212
+ }
110
213
 
111
- const decleration = t.variableDeclaration('const', [t.variableDeclarator(identifier)])
112
- decleration.declare = true
113
- return new CodeGenerator(t.exportNamedDeclaration(decleration)).generate().code.trim()
214
+ this.augmentedQueryResultsPromise.resolve({code: augmentedQueryResultsCode})
114
215
  }
115
216
 
116
- /**
117
- * Takes a list of queries from the codebase and generates a type declaration
118
- * for SanityClient to consume.
119
- *
120
- * Note: only types that have previously been generated with `generateTypeNodeTypes`
121
- * will be included in the query map.
122
- *
123
- * @param queries - A list of queries to generate a type declaration for
124
- * @returns
125
- * @internal
126
- * @beta
127
- */
128
- generateQueryMap(queries: QueryWithTypeNode[]): string {
129
- const typesByQuerystring: {[query: string]: string[]} = {}
130
-
131
- for (const query of queries) {
132
- const name = this.typeNodeNameMap.get(query.typeNode)
133
- if (!name) {
134
- continue
217
+ private generateQueryResultType({
218
+ name,
219
+ result,
220
+ type,
221
+ filename,
222
+ }: NamedQueryResult & {filename: string}) {
223
+ const evaluationResults: {schemaId: string; tsType: t.TSType; stats: TypeEvaluationStats}[] = []
224
+ for (const schema of this.schemas) {
225
+ const {schemaId} = schema
226
+
227
+ if (type === 'projection') {
228
+ const projectionResult = schema.evaluateProjection(result)
229
+ if (!projectionResult) continue
230
+ evaluationResults.push({schemaId, ...projectionResult})
231
+ } else {
232
+ const queryResult = schema.evaluateQuery(result)
233
+ evaluationResults.push({schemaId, ...queryResult})
135
234
  }
136
-
137
- typesByQuerystring[query.query] ??= []
138
- typesByQuerystring[query.query].push(name)
139
235
  }
140
236
 
141
- const queryReturnInterface = t.tsInterfaceDeclaration(
142
- t.identifier('SanityQueries'),
143
- null,
144
- [],
145
- t.tsInterfaceBody(
146
- Object.entries(typesByQuerystring).map(([query, types]) => {
147
- return t.tsPropertySignature(
148
- t.stringLiteral(query),
149
- t.tsTypeAnnotation(
150
- t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type)))),
151
- ),
152
- )
153
- }),
154
- ),
155
- )
237
+ const tsTypes = evaluationResults.map(({tsType, schemaId}) => {
238
+ if (this.schemas.length === 1) return tsType
239
+ return addSchemaOrigin(tsType, schemaId)
240
+ })
241
+
242
+ const tsType = tsTypes.length === 1 ? tsTypes[0] : t.tsUnionType(tsTypes)
156
243
 
157
- const declareModule = t.declareModule(
158
- t.stringLiteral('@sanity/client'),
159
- t.blockStatement([queryReturnInterface]),
244
+ const {code, id} = this.generateAndRegisterExportedTypeAlias(
245
+ `${name}${type === 'projection' ? 'ProjectionResult' : 'Result'}`,
246
+ tsType,
247
+ [
248
+ {type: 'CommentLine', value: ` Source: ${filename}`},
249
+ {type: 'CommentLine', value: ` Variable: ${name}`},
250
+ {
251
+ type: 'CommentLine',
252
+ value: ` ${type === 'projection' ? 'Projection' : 'Query'}: ${result.replace(/(\r\n|\n|\r)/gm, '').trim()}`,
253
+ },
254
+ ],
160
255
  )
161
256
 
162
- const clientImport = t.importDeclaration([], t.stringLiteral('@sanity/client'))
257
+ const identifiersByProjectionOrQuery =
258
+ type === 'projection' ? this.identifiersByProjection : this.identifiersByQuery
259
+
260
+ let identifiers = identifiersByProjectionOrQuery.get(result)
163
261
 
164
- return new CodeGenerator(t.program([clientImport, declareModule])).generate().code.trim()
262
+ if (!identifiers) {
263
+ identifiers = []
264
+ identifiersByProjectionOrQuery.set(result, identifiers)
265
+ }
266
+ identifiers.push(id)
267
+
268
+ return {
269
+ code,
270
+ id,
271
+ name,
272
+ type,
273
+ stats: evaluationResults.reduce<TypeEvaluationStats>(
274
+ (acc, {stats}) => ({
275
+ allTypes: acc.allTypes + stats.allTypes,
276
+ unknownTypes: acc.unknownTypes + stats.unknownTypes,
277
+ emptyUnions: acc.emptyUnions + stats.emptyUnions,
278
+ }),
279
+ {allTypes: 0, unknownTypes: 0, emptyUnions: 0},
280
+ ),
281
+ }
165
282
  }
166
283
 
167
- /**
168
- * Since we are sanitizing identifiers we migt end up with collisions. Ie there might be a type mux.video and muxVideo, both these
169
- * types would be sanityized into MuxVideo. To avoid this we keep track of the generated type names and add a index to the name.
170
- * When we reference a type we also keep track of the original name so we can reference the correct type later.
171
- */
172
- private getTypeName(
284
+ private generateAndRegisterExportedTypeAlias(
173
285
  name: string,
174
- typeNode?: TypeNode | DocumentSchemaType | TypeDeclarationSchemaType,
175
- ): string {
176
- const desiredName = uppercaseFirstLetter(sanitizeIdentifier(name))
177
-
178
- let generatedName = desiredName
179
- let i = 2
180
- while (this.generatedTypeName.has(generatedName)) {
181
- // add _ and a index and increment that index until we find a name that is not in the map
182
- generatedName = `${desiredName}_${i++}`
286
+ tsType: t.TSType,
287
+ comments?: t.Comment[],
288
+ ): {code: string; id: t.Identifier} {
289
+ const desiredName = SchemaTypeGenerator.normalizeIdentifier(name)
290
+
291
+ let resultingName = desiredName
292
+ let index = 2
293
+ while (this.globalIdentifiers.has(resultingName)) {
294
+ resultingName = `${desiredName}_${index}`
295
+ index++
183
296
  }
184
- this.generatedTypeName.add(generatedName)
185
- this.typeNameMap.set(name, generatedName)
186
- if (typeNode) {
187
- this.typeNodeNameMap.set(typeNode, generatedName)
297
+
298
+ this.globalIdentifiers.add(resultingName)
299
+
300
+ const id = t.identifier(resultingName)
301
+
302
+ const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)
303
+ let exportDeclaration = t.exportNamedDeclaration(typeAlias)
304
+
305
+ if (comments) {
306
+ exportDeclaration = t.addComments(exportDeclaration, 'leading', comments)
188
307
  }
189
308
 
190
- return generatedName
309
+ const code = generateCode(exportDeclaration)
310
+
311
+ return {id, code}
191
312
  }
192
313
 
193
- private getTypeNodeType(
194
- typeNode: TypeNode | TypeDeclarationSchemaType | DocumentSchemaType,
195
- ): t.TSType {
196
- switch (typeNode.type) {
197
- case 'string': {
198
- if (typeNode.value !== undefined) {
199
- return t.tsLiteralType(t.stringLiteral(typeNode.value))
200
- }
201
- return t.tsStringKeyword()
202
- }
203
- case 'number': {
204
- if (typeNode.value !== undefined) {
205
- return t.tsLiteralType(t.numericLiteral(typeNode.value))
206
- }
207
- return t.tsNumberKeyword()
208
- }
209
- case 'boolean': {
210
- if (typeNode.value !== undefined) {
211
- return t.tsLiteralType(t.booleanLiteral(typeNode.value))
212
- }
213
- return t.tsBooleanKeyword()
214
- }
215
- case 'unknown': {
216
- return t.tsUnknownKeyword()
217
- }
218
- case 'document': {
219
- return this.generateDocumentType(typeNode)
220
- }
221
- case 'type': {
222
- return this.getTypeNodeType(typeNode.value)
223
- }
224
- case 'array': {
225
- return this.generateArrayTsType(typeNode)
226
- }
227
- case 'object': {
228
- return this.generateObjectTsType(typeNode)
229
- }
230
- case 'union': {
231
- return this.generateUnionTsType(typeNode)
232
- }
233
- case 'inline': {
234
- return this.generateInlineTsType(typeNode)
235
- }
236
- case 'null': {
237
- return t.tsNullKeyword()
238
- }
314
+ getKnownTypes = computeOnce(() => {
315
+ let code = ''
239
316
 
240
- default:
241
- // @ts-expect-error This should never happen
242
- throw new Error(`Type "${typeNode.type}" not found in schema`)
317
+ if (this.overloadClientMethods) {
318
+ code += generateCode(t.importDeclaration([], t.stringLiteral('@sanity/client')))
243
319
  }
244
- }
245
320
 
246
- // Helper function used to generate TS types for array type nodes.
247
- private generateArrayTsType(typeNode: ArrayTypeNode): t.TSTypeReference {
248
- const typeNodes = this.getTypeNodeType(typeNode.of)
249
- const arrayType = t.tsTypeReference(
250
- t.identifier('Array'),
251
- t.tsTypeParameterInstantiation([typeNodes]),
252
- )
321
+ const importSpecifiers = [
322
+ t.importSpecifier(SchemaTypeGenerator.ProjectionBase, SchemaTypeGenerator.ProjectionBase),
323
+ ]
253
324
 
254
- return arrayType
255
- }
325
+ if (this.schemas.length > 1) {
326
+ importSpecifiers.push(t.importSpecifier(PickSchema, PickSchema))
327
+ importSpecifiers.push(t.importSpecifier(SchemaOrigin, SchemaOrigin))
328
+ }
256
329
 
257
- // Helper function used to generate TS types for object properties.
258
- private generateObjectProperty(key: string, attribute: ObjectAttribute): t.TSPropertySignature {
259
- const type = this.getTypeNodeType(attribute.value)
260
- const propertySignature = t.tsPropertySignature(
261
- t.identifier(sanitizeIdentifier(key)),
262
- t.tsTypeAnnotation(type),
330
+ code += generateCode(
331
+ Object.assign(t.importDeclaration(importSpecifiers, t.stringLiteral('groq')), {
332
+ importKind: 'type',
333
+ }),
263
334
  )
264
- propertySignature.optional = attribute.optional
265
335
 
266
- return propertySignature
267
- }
336
+ code += generateCode(
337
+ t.exportNamedDeclaration(
338
+ Object.assign(
339
+ t.variableDeclaration('const', [
340
+ t.variableDeclarator(SchemaTypeGenerator.InternalReferenceSymbol),
341
+ ]),
342
+ {declare: true},
343
+ ),
344
+ ),
345
+ )
268
346
 
269
- // Helper function used to generate TS types for object type nodes.
270
- private generateObjectTsType(typeNode: ObjectTypeNode): t.TSType {
271
- const props: t.TSPropertySignature[] = []
272
- Object.entries(typeNode.attributes).forEach(([key, attribute]) => {
273
- props.push(this.generateObjectProperty(key, attribute))
274
- })
275
- const rest = typeNode.rest
276
- if (rest !== undefined) {
277
- switch (rest.type) {
278
- case 'unknown': {
279
- return t.tsUnknownKeyword()
280
- }
281
- case 'object': {
282
- Object.entries(rest.attributes).forEach(([key, attribute]) => {
283
- props.push(this.generateObjectProperty(key, attribute))
347
+ return {code}
348
+ })
349
+
350
+ getSchemaTypeDeclarations = computeOnce(() => {
351
+ const typeNames = new Set(this.schemas.flatMap((schema) => schema.getTypeNames()))
352
+
353
+ return Array.from(typeNames).flatMap((typeName) => {
354
+ const identifiers = new Set(
355
+ this.schemas
356
+ .map((schema) => schema.getIdentifier(typeName)?.name)
357
+ .filter((i) => typeof i === 'string'),
358
+ )
359
+
360
+ return Array.from(identifiers).map((identifier) => {
361
+ const types = this.schemas
362
+ .filter(
363
+ (schema) =>
364
+ schema.getIdentifier(typeName)?.name === identifier && !!schema.getTsType(typeName),
365
+ )
366
+ .map((schema) => {
367
+ const tsType = schema.getTsType(typeName)!
368
+ const schemaId = schema.schemaId
369
+
370
+ // no need to wrap with SchemaOrigin if there aren't at least 2 schemas
371
+ if (this.schemas.length < 2) return {schemaId, tsType}
372
+ return {schemaId, tsType: addSchemaOrigin(tsType, schemaId)}
284
373
  })
285
- break
286
- }
287
- case 'inline': {
288
- const resolved = this.generateInlineTsType(rest)
289
374
 
290
- // if an object's rest type is unknown, we can't generate a type literal for it
291
- // so we return unknown
292
- if (t.isTSUnknownKeyword(resolved)) {
293
- return resolved
294
- }
295
- return t.tsIntersectionType([t.tsTypeLiteral(props), resolved])
296
- }
297
- default: {
298
- // @ts-expect-error This should never happen
299
- throw new Error(`Type "${rest.type}" not found in schema`)
300
- }
375
+ const schemaIds = types.map((i) => i.schemaId)
376
+ const tsType =
377
+ types.length === 1 ? types[0].tsType : t.tsUnionType(types.map((i) => i.tsType))
378
+ const {id, code} = this.generateAndRegisterExportedTypeAlias(identifier, tsType)
379
+
380
+ return {id, code, schemaIds}
381
+ })
382
+ })
383
+ })
384
+
385
+ getAllSanitySchemaTypesDeclaration = computeOnce(() => {
386
+ const schemaTypeDeclarations = this.getSchemaTypeDeclarations()
387
+ const code = generateCode(
388
+ t.exportNamedDeclaration(
389
+ t.tsTypeAliasDeclaration(
390
+ AllSanitySchemaTypes,
391
+ null,
392
+ t.tsUnionType(schemaTypeDeclarations.map(({id}) => t.tsTypeReference(id))),
393
+ ),
394
+ ),
395
+ )
396
+ return {code}
397
+ })
398
+
399
+ getSchemaDeclarations = computeOnce(() => {
400
+ const schemaTypeDeclarations = this.getSchemaTypeDeclarations()
401
+ const identifierUsageCountBySchemaId = schemaTypeDeclarations.reduce<{
402
+ [schemaId: string]: {[identifier: string]: number}
403
+ }>((acc, {schemaIds, id}) => {
404
+ for (const schemaId of schemaIds) {
405
+ acc[schemaId] = acc[schemaId] ?? {}
406
+ acc[schemaId][id.name] = schemaIds.length
301
407
  }
302
- }
303
- if (typeNode.dereferencesTo !== undefined) {
304
- const derefType = t.tsPropertySignature(
305
- t.identifier(REFERENCE_SYMBOL_NAME),
306
- t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo))),
408
+ return acc
409
+ }, {})
410
+
411
+ return this.schemas.map(({schemaId}) => {
412
+ const tsTypes = Object.entries(identifierUsageCountBySchemaId[schemaId]).map(
413
+ ([identifierName, schemaCount]) => {
414
+ const schemaTypeReferencer = t.tsTypeReference(t.identifier(identifierName))
415
+ if (schemaCount > 1) return addPickSchema(schemaTypeReferencer, schemaId)
416
+ return schemaTypeReferencer
417
+ },
307
418
  )
308
- derefType.computed = true
309
- derefType.optional = true
310
- props.push(derefType)
311
- }
312
- return t.tsTypeLiteral(props)
313
- }
419
+ const tsType = tsTypes.length === 1 ? tsTypes[0] : t.tsUnionType(tsTypes)
420
+
421
+ const comments: t.Comment[] = []
314
422
 
315
- private generateInlineTsType(typeNode: InlineTypeNode): t.TSType {
316
- const referencedTypeNode = this.schema.find((schema) => schema.name === typeNode.name)
317
- // Check if we have a schema reference for the type node
318
- if (referencedTypeNode === undefined) {
319
- // Is it already generated by another type node?
320
- const generatedName = this.typeNameMap.get(typeNode.name)
321
- if (generatedName) {
322
- return t.tsTypeReference(t.identifier(generatedName))
423
+ const filename = this.schemaFilenames.get(schemaId)
424
+ if (filename) {
425
+ comments.push({type: 'CommentLine', value: ` Source: ${filename}`})
323
426
  }
427
+ comments.push({type: 'CommentLine', value: ` Schema ID: ${schemaId}`})
324
428
 
325
- // Not found in schema, return unknown type
326
- const missing = t.tsUnknownKeyword()
327
- missing.trailingComments = [
328
- {
329
- type: 'CommentLine',
330
- value: ` Unable to locate the referenced type "${typeNode.name}" in schema`,
331
- },
332
- ]
333
- return missing
334
- }
429
+ const {id, code} = this.generateAndRegisterExportedTypeAlias(
430
+ `${schemaId}Schema`,
431
+ tsType,
432
+ comments,
433
+ )
335
434
 
336
- const generatedName = this.typeNameMap.get(referencedTypeNode.name)
435
+ return {id, code, schemaId}
436
+ })
437
+ })
337
438
 
338
- if (generatedName) {
339
- return t.tsTypeReference(t.identifier(generatedName))
340
- }
439
+ getAugmentedSchemasDeclarations = computeOnce(() => {
440
+ if (!this.augmentGroqModule) return {code: ''}
441
+ const schemaDeclarations = this.getSchemaDeclarations()
341
442
 
342
- return t.tsUnknownKeyword()
343
- }
443
+ const groqModuleDeclaration = t.declareModule(
444
+ t.stringLiteral('groq'),
445
+ t.blockStatement([
446
+ t.tsInterfaceDeclaration(
447
+ SanitySchemas,
448
+ null,
449
+ [],
450
+ t.tsInterfaceBody(
451
+ schemaDeclarations.map(({id, schemaId}) =>
452
+ t.tsPropertySignature(
453
+ t.stringLiteral(schemaId),
454
+ t.tsTypeAnnotation(t.tsTypeReference(id)),
455
+ ),
456
+ ),
457
+ ),
458
+ ),
459
+ ]),
460
+ )
344
461
 
345
- // Helper function used to generate TS types for union type nodes.
346
- private generateUnionTsType(typeNode: UnionTypeNode): t.TSType {
347
- if (typeNode.of.length === 0) {
348
- return t.tsNeverKeyword()
349
- }
350
- if (typeNode.of.length === 1) {
351
- return this.getTypeNodeType(typeNode.of[0])
352
- }
462
+ return {code: generateCode(groqModuleDeclaration)}
463
+ })
353
464
 
354
- const typeNodes = typeNode.of.map((node) => this.getTypeNodeType(node))
465
+ getQueryFileCount = (): Promise<{fileCount: number}> => this.queryFileCountPromise.promise
355
466
 
356
- return t.tsUnionType(typeNodes)
357
- }
467
+ getQueryResultDeclarations = (): AsyncIterable<QueryResultDeclarationsFileResult> =>
468
+ this.queryResultsQueue
358
469
 
359
- // Helper function used to generate TS types for document type nodes.
360
- private generateDocumentType(document: DocumentSchemaType): t.TSType {
361
- const props = Object.entries(document.attributes).map(([key, node]) =>
362
- this.generateObjectProperty(key, node),
363
- )
470
+ getAugmentedQueryResultsDeclarations = (): Promise<{code: string}> =>
471
+ this.augmentedQueryResultsPromise.promise
472
+ }
364
473
 
365
- return t.tsTypeLiteral(props)
474
+ function computeOnce<TThis, TReturn>(this: TThis, fn: () => TReturn): (this: TThis) => TReturn {
475
+ const ref = {current: undefined as TReturn | undefined, computed: false}
476
+
477
+ return function (this: TThis) {
478
+ if (ref.computed) return ref.current as TReturn
479
+ ref.current = fn.call(this)
480
+ ref.computed = true
481
+ return ref.current
366
482
  }
367
483
  }
368
- function uppercaseFirstLetter(input: string): string {
369
- return input.charAt(0).toUpperCase() + input.slice(1)
484
+
485
+ function addSchemaOrigin(tsType: t.TSType, schemaId: string) {
486
+ return t.tsTypeReference(
487
+ SchemaOrigin,
488
+ t.tsTypeParameterInstantiation([tsType, t.tsLiteralType(t.stringLiteral(schemaId))]),
489
+ )
490
+ }
491
+
492
+ function addPickSchema(tsType: t.TSType, schemaId: string) {
493
+ return t.tsTypeReference(
494
+ PickSchema,
495
+ t.tsTypeParameterInstantiation([tsType, t.tsLiteralType(t.stringLiteral(schemaId))]),
496
+ )
497
+ }
498
+
499
+ function generateCode(node: t.Node) {
500
+ return `${new CodeGenerator(node).generate().code.trim()}\n\n`
370
501
  }
371
502
 
372
- function sanitizeIdentifier(input: string): string {
373
- return `${input.replace(/^\d/, '_').replace(/[^$\w]+(.)/g, (_, char) => char.toUpperCase())}`
503
+ // Similar to `Promise.withResolvers`
504
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers
505
+ function promiseWithResolvers<T = void>() {
506
+ let resolve!: (t: T) => void
507
+ let reject!: (error: unknown) => void
508
+ const promise = new Promise<T>((thisResolve, thisReject) => {
509
+ resolve = thisResolve
510
+ reject = thisReject
511
+ })
512
+ return {promise, resolve, reject}
374
513
  }