@sanity/codegen 3.86.2-experimental.0 → 3.87.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,415 +0,0 @@
1
- import * as t from '@babel/types'
2
- import {
3
- type ArrayTypeNode,
4
- type DocumentSchemaType,
5
- type ObjectAttribute,
6
- type ObjectTypeNode,
7
- type SchemaType,
8
- type TypeDeclarationSchemaType,
9
- typeEvaluate,
10
- type TypeNode,
11
- type UnionTypeNode,
12
- } from 'groq-js'
13
-
14
- import {safeParseQuery} from '../safeParseQuery'
15
-
16
- /** @internal */
17
- export interface TypeEvaluationStats {
18
- totalTypeNodes: number
19
- unknownTypeCount: number
20
- emptyUnionCount: number
21
- }
22
-
23
- // Helper: Uppercase first letter
24
- function uppercaseFirstLetter(input: string): string {
25
- return input.charAt(0).toUpperCase() + input.slice(1)
26
- }
27
-
28
- // Helper: Sanitize identifier
29
- function sanitizeIdentifier(input: string): string {
30
- return `${input.replace(/^\d/, '_').replace(/[^$\w]+(.)/g, (_, char) => char.toUpperCase())}`
31
- }
32
-
33
- interface TypeGeneratorOptions {
34
- schema: SchemaType
35
- projectId: string | 'default'
36
- dataset: string | 'default'
37
- }
38
-
39
- export class SchemaTypeGenerator {
40
- private tsTypes: Map<string, t.TSType>
41
- private documentTypeNames: Set<string>
42
- private identifiers: Map<string, t.Identifier>
43
-
44
- public schema: SchemaType
45
- public projectId: string | 'default'
46
- public dataset: string | 'default'
47
-
48
- static REFERENCE_SYMBOL_NAME = 'internalGroqTypeReferenceTo'
49
-
50
- static sanitizeIdentifier(input: string): string {
51
- return uppercaseFirstLetter(sanitizeIdentifier(input))
52
- }
53
-
54
- constructor({dataset, projectId, schema}: TypeGeneratorOptions) {
55
- this.dataset = dataset
56
- this.projectId = projectId
57
- this.schema = schema
58
-
59
- // Build unique sanitized name mapping to avoid collisions
60
- const sanitizedCounts: Record<string, number> = {}
61
-
62
- this.identifiers = this.schema.reduce((acc, {name}) => {
63
- const base = SchemaTypeGenerator.sanitizeIdentifier(name)
64
- const count = (sanitizedCounts[base] || 0) + 1
65
- sanitizedCounts[base] = count
66
- const uniqueName = count === 1 ? base : `${base}_${count}`
67
- acc.set(name, t.identifier(uniqueName))
68
- return acc
69
- }, new Map<string, t.Identifier>())
70
-
71
- this.documentTypeNames = new Set(schema.filter((i) => i.type === 'document').map((i) => i.name))
72
-
73
- this.tsTypes = schema.reduce((acc, i) => {
74
- acc.set(i.name, this.getTypeNodeType(i))
75
- return acc
76
- }, new Map<string, t.TSType>())
77
- }
78
-
79
- getTypeNames(): string[] {
80
- return Array.from(this.tsTypes.keys())
81
- }
82
-
83
- getDocumentTypeNames(): string[] {
84
- return Array.from(this.documentTypeNames)
85
- }
86
-
87
- getTsType(name: string): t.TSType | undefined {
88
- return this.tsTypes.get(name)
89
- }
90
-
91
- getIdentifier(name: string): t.Identifier | undefined {
92
- return this.identifiers.get(name)
93
- }
94
-
95
- evaluateQuery(query: string): {tsType: t.TSType; stats: TypeEvaluationStats} {
96
- const ast = safeParseQuery(query)
97
- const typeNode = typeEvaluate(ast, this.schema)
98
- const tsType = this.getTypeNodeType(typeNode)
99
- const stats = SchemaTypeGenerator.calculateTypeStats(typeNode)
100
- return {tsType, stats}
101
- }
102
-
103
- evaluateProjection(projection: string): {tsType: t.TSType; stats: TypeEvaluationStats} {
104
- const results = this.getDocumentTypeNames()
105
- .map((typeName) => {
106
- const ast = safeParseQuery(`* [_type==${JSON.stringify(typeName)}] ${projection} [0]`)
107
- let typeNode = typeEvaluate(ast, this.schema)
108
-
109
- // manually remove `null` from type node since `[0]` will always result
110
- // in a union with null
111
- if (typeNode.type === 'union') {
112
- const nonNullMembers = typeNode.of.filter((member) => member.type !== 'null')
113
- if (nonNullMembers.length === 0) {
114
- return null
115
- } else if (nonNullMembers.length === 1) {
116
- typeNode = nonNullMembers[0]
117
- } else {
118
- typeNode = {...typeNode, of: nonNullMembers}
119
- }
120
- }
121
-
122
- if (typeNode.type === 'object') {
123
- // Check if all attributes are null and there is no meaningful rest
124
- const attributeValues = Object.values(typeNode.attributes)
125
- const allAttributesNull = attributeValues.every((attr) => attr.value.type === 'null')
126
- const hasMeaningfulRest = typeNode.rest && typeNode.rest.type !== 'unknown'
127
-
128
- // Only simplify if there are attributes AND all are null
129
- if (attributeValues.length > 0 && allAttributesNull && !hasMeaningfulRest) {
130
- return null
131
- }
132
- }
133
-
134
- if (typeNode.type === 'null') {
135
- return null
136
- }
137
-
138
- const stats = SchemaTypeGenerator.calculateTypeStats(typeNode)
139
- const tsType = t.tsTypeReference(
140
- t.identifier('DocumentTypeScoped'),
141
- t.tsTypeParameterInstantiation([
142
- this.getTypeNodeType(typeNode),
143
- t.tsLiteralType(t.stringLiteral(typeName)),
144
- ]),
145
- )
146
-
147
- return {tsType, stats}
148
- })
149
- .filter((i) => !!i)
150
-
151
- if (!results.length) {
152
- return {
153
- tsType: t.tsNeverKeyword(),
154
- // emptyUnions is 1 because the union type has no members, resulting in a `never` type
155
- stats: {totalTypeNodes: 0, unknownTypeCount: 0, emptyUnionCount: 1},
156
- }
157
- }
158
-
159
- if (results.length === 1) return results[0]
160
-
161
- const combinedTsType = t.tsUnionType(results.map((i) => i.tsType))
162
- const accumulatedStats = results.reduce(
163
- (acc, {stats}) => ({
164
- totalTypeNodes: acc.totalTypeNodes + stats.totalTypeNodes,
165
- emptyUnionCount: acc.emptyUnionCount + stats.emptyUnionCount,
166
- unknownTypeCount: acc.unknownTypeCount + stats.unknownTypeCount,
167
- }),
168
- {totalTypeNodes: 0, unknownTypeCount: 0, emptyUnionCount: 0},
169
- )
170
- // Add 1 for the final union type since multiple results were combined
171
- accumulatedStats.totalTypeNodes += 1
172
-
173
- return {tsType: combinedTsType, stats: accumulatedStats}
174
- }
175
-
176
- private getTypeNodeType(
177
- typeNode: TypeNode | TypeDeclarationSchemaType | DocumentSchemaType,
178
- ): t.TSType {
179
- switch (typeNode.type) {
180
- case 'string': {
181
- if (typeNode.value !== undefined) {
182
- return t.tsLiteralType(t.stringLiteral(typeNode.value))
183
- }
184
- return t.tsStringKeyword()
185
- }
186
- case 'number': {
187
- if (typeNode.value !== undefined) {
188
- return t.tsLiteralType(t.numericLiteral(typeNode.value))
189
- }
190
- return t.tsNumberKeyword()
191
- }
192
- case 'boolean': {
193
- if (typeNode.value !== undefined) {
194
- return t.tsLiteralType(t.booleanLiteral(typeNode.value))
195
- }
196
- return t.tsBooleanKeyword()
197
- }
198
- case 'unknown': {
199
- return t.tsUnknownKeyword()
200
- }
201
- case 'document': {
202
- return this.generateDocumentType(typeNode)
203
- }
204
- case 'type': {
205
- return this.getTypeNodeType(typeNode.value)
206
- }
207
- case 'array': {
208
- return this.generateArrayTsType(typeNode)
209
- }
210
- case 'object': {
211
- return this.generateObjectTsType(typeNode)
212
- }
213
- case 'union': {
214
- return this.generateUnionTsType(typeNode)
215
- }
216
- case 'inline': {
217
- const identifier = this.getIdentifier(typeNode.name)
218
- if (!identifier) throw new Error(`Type "${typeNode.name}" not found in schema`)
219
- return t.tsTypeReference(identifier)
220
- }
221
- case 'null': {
222
- return t.tsNullKeyword()
223
- }
224
-
225
- default:
226
- // @ts-expect-error This should never happen
227
- throw new Error(`Type "${typeNode.type}" not found in schema`)
228
- }
229
- }
230
-
231
- // Helper function used to generate TS types for array type nodes.
232
- private generateArrayTsType(typeNode: ArrayTypeNode): t.TSTypeReference {
233
- const typeNodes = this.getTypeNodeType(typeNode.of)
234
- const arrayType = t.tsTypeReference(
235
- t.identifier('Array'),
236
- t.tsTypeParameterInstantiation([typeNodes]),
237
- )
238
-
239
- return arrayType
240
- }
241
-
242
- // Helper function used to generate TS types for object properties.
243
- private generateObjectProperty(key: string, attribute: ObjectAttribute): t.TSPropertySignature {
244
- const type = this.getTypeNodeType(attribute.value)
245
- const propertySignature = t.tsPropertySignature(
246
- t.identifier(sanitizeIdentifier(key)),
247
- t.tsTypeAnnotation(type),
248
- )
249
- propertySignature.optional = attribute.optional
250
-
251
- return propertySignature
252
- }
253
-
254
- // Helper function used to generate TS types for object type nodes.
255
- private generateObjectTsType(typeNode: ObjectTypeNode): t.TSType {
256
- const props: t.TSPropertySignature[] = []
257
- Object.entries(typeNode.attributes).forEach(([key, attribute]) => {
258
- props.push(this.generateObjectProperty(key, attribute))
259
- })
260
- const rest = typeNode.rest
261
- if (rest !== undefined) {
262
- switch (rest.type) {
263
- case 'unknown': {
264
- return t.tsUnknownKeyword()
265
- }
266
- case 'object': {
267
- Object.entries(rest.attributes).forEach(([key, attribute]) => {
268
- props.push(this.generateObjectProperty(key, attribute))
269
- })
270
- break
271
- }
272
- case 'inline': {
273
- const identifier = this.getIdentifier(rest.name)
274
- if (!identifier) {
275
- const missing = t.tsUnknownKeyword()
276
- missing.trailingComments = [
277
- {
278
- type: 'CommentLine',
279
- value: ` Unable to locate the referenced type "${rest.name}" in schema`,
280
- },
281
- ]
282
- return missing
283
- }
284
-
285
- return t.tsIntersectionType([t.tsTypeLiteral(props), t.tsTypeReference(identifier)])
286
- }
287
- default: {
288
- // @ts-expect-error This should never happen
289
- throw new Error(`Type "${rest.type}" not found in schema`)
290
- }
291
- }
292
- }
293
- if (typeNode.dereferencesTo !== undefined) {
294
- const derefType = t.tsPropertySignature(
295
- t.identifier(SchemaTypeGenerator.REFERENCE_SYMBOL_NAME),
296
- t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo))),
297
- )
298
- derefType.computed = true
299
- derefType.optional = true
300
- props.push(derefType)
301
- }
302
- return t.tsTypeLiteral(props)
303
- }
304
-
305
- // Helper function used to generate TS types for union type nodes.
306
- private generateUnionTsType(typeNode: UnionTypeNode): t.TSType {
307
- if (typeNode.of.length === 0) {
308
- return t.tsNeverKeyword()
309
- }
310
- if (typeNode.of.length === 1) {
311
- return this.getTypeNodeType(typeNode.of[0])
312
- }
313
-
314
- const typeNodes = typeNode.of.map((node) => this.getTypeNodeType(node))
315
-
316
- return t.tsUnionType(typeNodes)
317
- }
318
-
319
- // Helper function used to generate TS types for document type nodes.
320
- private generateDocumentType(document: DocumentSchemaType): t.TSType {
321
- const props = Object.entries(document.attributes).map(([key, node]) =>
322
- this.generateObjectProperty(key, node),
323
- )
324
-
325
- return t.tsTypeLiteral(props)
326
- }
327
-
328
- // Helper function to calculate statistics for a TypeNode
329
- private static calculateTypeStats(
330
- typeNode: TypeNode | TypeDeclarationSchemaType | DocumentSchemaType,
331
- ): TypeEvaluationStats {
332
- switch (typeNode.type) {
333
- case 'unknown':
334
- return {totalTypeNodes: 1, unknownTypeCount: 1, emptyUnionCount: 0}
335
-
336
- case 'array': {
337
- const stats = SchemaTypeGenerator.calculateTypeStats(typeNode.of)
338
- stats.totalTypeNodes += 1 // count the array type itself
339
- return stats
340
- }
341
-
342
- case 'object': {
343
- const initialStats: TypeEvaluationStats = {
344
- totalTypeNodes: 1,
345
- unknownTypeCount: 0,
346
- emptyUnionCount: 0,
347
- } // count the object type itself
348
-
349
- const restStats = typeNode.rest
350
- ? SchemaTypeGenerator.calculateTypeStats(typeNode.rest)
351
- : null
352
- if (restStats) {
353
- initialStats.totalTypeNodes += restStats.totalTypeNodes
354
- initialStats.unknownTypeCount += restStats.unknownTypeCount
355
- initialStats.emptyUnionCount += restStats.emptyUnionCount
356
- }
357
-
358
- return Object.values(typeNode.attributes).reduce<TypeEvaluationStats>((acc, attribute) => {
359
- const stats = SchemaTypeGenerator.calculateTypeStats(attribute.value)
360
- acc.totalTypeNodes += stats.totalTypeNodes
361
- acc.unknownTypeCount += stats.unknownTypeCount
362
- acc.emptyUnionCount += stats.emptyUnionCount
363
- return acc
364
- }, initialStats)
365
- }
366
-
367
- case 'union': {
368
- if (typeNode.of.length === 0) {
369
- return {totalTypeNodes: 1, unknownTypeCount: 0, emptyUnionCount: 1}
370
- }
371
-
372
- return typeNode.of.reduce(
373
- (acc, type) => {
374
- const stats = SchemaTypeGenerator.calculateTypeStats(type)
375
- acc.totalTypeNodes += stats.totalTypeNodes
376
- acc.unknownTypeCount += stats.unknownTypeCount
377
- acc.emptyUnionCount += stats.emptyUnionCount
378
- return acc
379
- },
380
- {totalTypeNodes: 1, unknownTypeCount: 0, emptyUnionCount: 0}, // count the union type itself
381
- )
382
- }
383
-
384
- case 'type': {
385
- // Type declarations don't add to the count themselves, only their value does.
386
- return SchemaTypeGenerator.calculateTypeStats(typeNode.value)
387
- }
388
-
389
- case 'document': {
390
- // Documents behave like objects for stats calculation
391
- const initialStats: TypeEvaluationStats = {
392
- totalTypeNodes: 1,
393
- unknownTypeCount: 0,
394
- emptyUnionCount: 0,
395
- }
396
- return Object.values(typeNode.attributes).reduce<TypeEvaluationStats>((acc, attribute) => {
397
- const stats = SchemaTypeGenerator.calculateTypeStats(attribute.value)
398
- acc.totalTypeNodes += stats.totalTypeNodes
399
- acc.unknownTypeCount += stats.unknownTypeCount
400
- acc.emptyUnionCount += stats.emptyUnionCount
401
- return acc
402
- }, initialStats)
403
- }
404
-
405
- // Base types
406
- case 'string':
407
- case 'number':
408
- case 'boolean':
409
- case 'null':
410
- case 'inline':
411
- default:
412
- return {totalTypeNodes: 1, unknownTypeCount: 0, emptyUnionCount: 0}
413
- }
414
- }
415
- }