@sanity/codegen 3.93.1-next.5.23de35272e → 3.93.1-next.50.c40683a957

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 +0,0 @@
1
- import {CodeGenerator} from '@babel/generator'
2
- 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 = {
19
- query: string
20
- typeNode: TypeNode
21
- }
22
-
23
- /**
24
- * A class used to generate TypeScript types from a given schema
25
- * @internal
26
- * @beta
27
- */
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
38
-
39
- constructor(schema: SchemaType) {
40
- this.schema = schema
41
-
42
- this.schema.forEach((s) => {
43
- this.getTypeName(s.name, s)
44
- })
45
- }
46
-
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}`)
63
- }
64
-
65
- schemaNames.add(schemaName)
66
- const typeAlias = t.tsTypeAliasDeclaration(t.identifier(schemaName), null, typeLiteral)
67
-
68
- typeDeclarations.push(t.exportNamedDeclaration(typeAlias))
69
- })
70
-
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))),
78
- ),
79
- ),
80
- ),
81
- )
82
-
83
- // Generate TypeScript code from the AST nodes
84
- return typeDeclarations.map((decl) => new CodeGenerator(decl).generate().code).join('\n\n')
85
- }
86
-
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
- }
103
-
104
- static generateKnownTypes(): string {
105
- const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword())
106
- typeOperator.operator = 'unique'
107
-
108
- const identifier = t.identifier(REFERENCE_SYMBOL_NAME)
109
- identifier.typeAnnotation = t.tsTypeAnnotation(typeOperator)
110
-
111
- const decleration = t.variableDeclaration('const', [t.variableDeclarator(identifier)])
112
- decleration.declare = true
113
- return new CodeGenerator(t.exportNamedDeclaration(decleration)).generate().code.trim()
114
- }
115
-
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
135
- }
136
-
137
- typesByQuerystring[query.query] ??= []
138
- typesByQuerystring[query.query].push(name)
139
- }
140
-
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
- )
156
-
157
- const declareModule = t.declareModule(
158
- t.stringLiteral('@sanity/client'),
159
- t.blockStatement([queryReturnInterface]),
160
- )
161
-
162
- const clientImport = t.importDeclaration([], t.stringLiteral('@sanity/client'))
163
-
164
- return new CodeGenerator(t.program([clientImport, declareModule])).generate().code.trim()
165
- }
166
-
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(
173
- 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++}`
183
- }
184
- this.generatedTypeName.add(generatedName)
185
- this.typeNameMap.set(name, generatedName)
186
- if (typeNode) {
187
- this.typeNodeNameMap.set(typeNode, generatedName)
188
- }
189
-
190
- return generatedName
191
- }
192
-
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
- }
239
-
240
- default:
241
- // @ts-expect-error This should never happen
242
- throw new Error(`Type "${typeNode.type}" not found in schema`)
243
- }
244
- }
245
-
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
- )
253
-
254
- return arrayType
255
- }
256
-
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),
263
- )
264
- propertySignature.optional = attribute.optional
265
-
266
- return propertySignature
267
- }
268
-
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))
284
- })
285
- break
286
- }
287
- case 'inline': {
288
- const resolved = this.generateInlineTsType(rest)
289
-
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
- }
301
- }
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))),
307
- )
308
- derefType.computed = true
309
- derefType.optional = true
310
- props.push(derefType)
311
- }
312
- return t.tsTypeLiteral(props)
313
- }
314
-
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))
323
- }
324
-
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
- }
335
-
336
- const generatedName = this.typeNameMap.get(referencedTypeNode.name)
337
-
338
- if (generatedName) {
339
- return t.tsTypeReference(t.identifier(generatedName))
340
- }
341
-
342
- return t.tsUnknownKeyword()
343
- }
344
-
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
- }
353
-
354
- const typeNodes = typeNode.of.map((node) => this.getTypeNodeType(node))
355
-
356
- return t.tsUnionType(typeNodes)
357
- }
358
-
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
- )
364
-
365
- return t.tsTypeLiteral(props)
366
- }
367
- }
368
- function uppercaseFirstLetter(input: string): string {
369
- return input.charAt(0).toUpperCase() + input.slice(1)
370
- }
371
-
372
- function sanitizeIdentifier(input: string): string {
373
- return `${input.replace(/^\d/, '_').replace(/[^$\w]+(.)/g, (_, char) => char.toUpperCase())}`
374
- }