@sanity/codegen 3.86.2-experimental.0 → 3.87.1-canary.4

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.
@@ -12,7 +12,6 @@ const require = createRequire(__filename)
12
12
 
13
13
  const groqTagName = 'groq'
14
14
  const defineQueryFunctionName = 'defineQuery'
15
- const defineProjectionFunctionName = 'defineProjection'
16
15
  const groqModuleName = 'groq'
17
16
  const nextSanityModuleName = 'next-sanity'
18
17
 
@@ -51,14 +50,13 @@ export function findQueriesInSource(
51
50
  babelTypes.isIdentifier(init.tag) &&
52
51
  init.tag.name === groqTagName
53
52
 
54
- // Look for strings wrapped in a defineQuery or defineProjection function call
55
- const isDefineCall =
53
+ // Look for strings wrapped in a defineQuery function call
54
+ const isDefineQueryCall =
56
55
  babelTypes.isCallExpression(init) &&
57
56
  (isImportFrom(groqModuleName, defineQueryFunctionName, scope, init.callee) ||
58
- isImportFrom(groqModuleName, defineProjectionFunctionName, scope, init.callee) ||
59
57
  isImportFrom(nextSanityModuleName, defineQueryFunctionName, scope, init.callee))
60
58
 
61
- if (babelTypes.isIdentifier(node.id) && (isGroqTemplateTag || isDefineCall)) {
59
+ if (babelTypes.isIdentifier(node.id) && (isGroqTemplateTag || isDefineQueryCall)) {
62
60
  // If we find a comment leading the decleration which macthes with ignoreValue we don't add
63
61
  // the query
64
62
  if (declarationLeadingCommentContains(path, ignoreValue)) {
@@ -66,26 +64,8 @@ export function findQueriesInSource(
66
64
  }
67
65
 
68
66
  const queryName = `${node.id.name}`
69
-
70
- // Determine the kind based on the call or tag
71
- let resultType: 'query' | 'projection' = 'query' // Default to query
72
- let expressionToResolve: babelTypes.Expression = init // Default to the original init expression
73
-
74
- if (isDefineCall) {
75
- // If it's a define call, resolve the first argument instead of the whole call
76
- if (init.arguments.length > 0 && babelTypes.isExpression(init.arguments[0])) {
77
- expressionToResolve = init.arguments[0]
78
- }
79
- // Check specifically if it's a defineProjection call from groq
80
- if (isImportFrom(groqModuleName, defineProjectionFunctionName, scope, init.callee)) {
81
- resultType = 'projection'
82
- }
83
- // Otherwise, it remains 'query' (for defineQuery from groq or next-sanity)
84
- }
85
- // isGroqTemplateTag implies 'query', and we resolve the tagged template itself
86
-
87
67
  const queryResult = resolveExpression({
88
- node: expressionToResolve, // Use the potentially updated expression node
68
+ node: init,
89
69
  file,
90
70
  scope,
91
71
  babelConfig,
@@ -104,7 +84,7 @@ export function findQueriesInSource(
104
84
  }
105
85
  : {}
106
86
 
107
- queries.push({name: queryName, result: queryResult, type: resultType, location})
87
+ queries.push({name: queryName, result: queryResult, location})
108
88
  }
109
89
  },
110
90
  })
@@ -0,0 +1,374 @@
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
+ }
@@ -1,100 +0,0 @@
1
- /**
2
- * Implements an asynchronous queue pattern. Allows enqueueing items,
3
- * consuming them via an async iterator, and signaling completion or errors.
4
- */
5
- export class AsyncQueue<T> {
6
- // Internal state:
7
- // `queue`: Holds items yet to be consumed.
8
- // `resume`: A callback to signal the consumer when new items arrive or the queue finishes/errors.
9
- // `finished`: Flag indicating if the producer is done adding items (via `finish` or `throwError`).
10
- // `pendingError`: Stores an error passed to `throwError`, to be thrown by the consumer.
11
- private queue: T[] = []
12
- private resume: (() => void) | null = null
13
- private finished = false
14
- private pendingError: unknown = null
15
-
16
- /**
17
- * Enqueues an item. Throws if `finish` or `throwError` has been called.
18
- */
19
- public enqueue(item: T): void {
20
- if (this.finished) {
21
- throw new Error('Cannot enqueue items to a finished AsyncQueue.')
22
- }
23
- this.queue.push(item)
24
- // If the iterator is waiting, resume it.
25
- if (this.resume) {
26
- this.resume()
27
- this.resume = null
28
- }
29
- }
30
-
31
- /**
32
- * Signals that no more items will be enqueued. Idempotent.
33
- */
34
- public finish(): void {
35
- if (!this.finished) {
36
- this.finished = true
37
- // If the iterator is waiting, resume it.
38
- if (this.resume) {
39
- this.resume()
40
- this.resume = null
41
- }
42
- }
43
- }
44
-
45
- /**
46
- * Signals an error occurred during production. Finishes the queue. Idempotent.
47
- */
48
- public throwError(error: unknown): void {
49
- if (!this.finished) {
50
- this.pendingError = error
51
- this.finished = true
52
- // If the iterator is waiting, resume it.
53
- if (this.resume) {
54
- this.resume()
55
- this.resume = null
56
- }
57
- }
58
- }
59
-
60
- /**
61
- * Async iterator to consume enqueued items.
62
- * Throws if `throwError` was called.
63
- */
64
- public async *[Symbol.asyncIterator](): AsyncIterableIterator<T> {
65
- while (true) {
66
- // Throw immediately if an error occurred before or during waiting.
67
- if (this.pendingError) {
68
- throw this.pendingError
69
- }
70
-
71
- // Wait for new items if the queue is empty and not finished.
72
- if (this.queue.length === 0 && !this.finished) {
73
- await new Promise<void>((resolve) => {
74
- this.resume = resolve
75
- })
76
- // Re-check for errors after resuming, as `throwError` could have been called
77
- // while we were waiting.
78
- if (this.pendingError) {
79
- throw this.pendingError
80
- }
81
- }
82
-
83
- // Yield available items.
84
- while (this.queue.length > 0) {
85
- // `!` is safe because `this.queue.length > 0`.
86
- yield this.queue.shift()!
87
- }
88
-
89
- // If finished and queue is empty, the loop is done.
90
- if (this.finished && this.queue.length === 0) {
91
- break
92
- }
93
- }
94
- // Final check for errors, in case `throwError` was called after the last item
95
- // was yielded but before the loop condition was checked again.
96
- if (this.pendingError) {
97
- throw this.pendingError
98
- }
99
- }
100
- }