@sanity/codegen 3.52.4 → 3.53.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,6 +1,7 @@
1
1
  import {createRequire} from 'node:module'
2
2
 
3
3
  import {type NodePath, type TransformOptions, traverse} from '@babel/core'
4
+ import {type Scope} from '@babel/traverse'
4
5
  import * as babelTypes from '@babel/types'
5
6
 
6
7
  import {getBabelConfig} from '../getBabelConfig'
@@ -10,6 +11,8 @@ import {parseSourceFile} from './parseSource'
10
11
  const require = createRequire(__filename)
11
12
 
12
13
  const groqTagName = 'groq'
14
+ const defineQueryFunctionName = 'defineQuery'
15
+ const groqModuleName = 'groq'
13
16
 
14
17
  const ignoreValue = '@sanity-typegen-ignore'
15
18
 
@@ -41,12 +44,17 @@ export function findQueriesInSource(
41
44
  const init = node.init
42
45
 
43
46
  // Look for tagged template expressions that are called with the `groq` tag
44
- if (
47
+ const isGroqTemplateTag =
45
48
  babelTypes.isTaggedTemplateExpression(init) &&
46
49
  babelTypes.isIdentifier(init.tag) &&
47
- babelTypes.isIdentifier(node.id) &&
48
50
  init.tag.name === groqTagName
49
- ) {
51
+
52
+ // Look for strings wrapped in a defineQuery function call
53
+ const isDefineQueryCall =
54
+ babelTypes.isCallExpression(init) &&
55
+ isImportFrom(groqModuleName, defineQueryFunctionName, scope, init.callee)
56
+
57
+ if (babelTypes.isIdentifier(node.id) && (isGroqTemplateTag || isDefineQueryCall)) {
50
58
  // If we find a comment leading the decleration which macthes with ignoreValue we don't add
51
59
  // the query
52
60
  if (declarationLeadingCommentContains(path, ignoreValue)) {
@@ -63,7 +71,18 @@ export function findQueriesInSource(
63
71
  resolver,
64
72
  })
65
73
 
66
- queries.push({name: queryName, result: queryResult})
74
+ const location = node.loc
75
+ ? {
76
+ start: {
77
+ ...node.loc?.start,
78
+ },
79
+ end: {
80
+ ...node.loc?.end,
81
+ },
82
+ }
83
+ : {}
84
+
85
+ queries.push({name: queryName, result: queryResult, location})
67
86
  }
68
87
  },
69
88
  })
@@ -141,3 +160,71 @@ function declarationLeadingCommentContains(path: NodePath, comment: string): boo
141
160
 
142
161
  return false
143
162
  }
163
+
164
+ function isImportFrom(
165
+ moduleName: string,
166
+ importName: string,
167
+ scope: Scope,
168
+ node: babelTypes.Expression | babelTypes.V8IntrinsicIdentifier,
169
+ ) {
170
+ if (babelTypes.isIdentifier(node)) {
171
+ const binding = scope.getBinding(node.name)
172
+ if (!binding) {
173
+ return false
174
+ }
175
+
176
+ const {path} = binding
177
+
178
+ // import { foo } from 'groq'
179
+ if (babelTypes.isImportSpecifier(path.node)) {
180
+ return (
181
+ path.node.importKind === 'value' &&
182
+ path.parentPath &&
183
+ babelTypes.isImportDeclaration(path.parentPath.node) &&
184
+ path.parentPath.node.source.value === moduleName &&
185
+ babelTypes.isIdentifier(path.node.imported) &&
186
+ path.node.imported.name === importName
187
+ )
188
+ }
189
+
190
+ // const { defineQuery } = require('groq')
191
+ if (babelTypes.isVariableDeclarator(path.node)) {
192
+ const {init} = path.node
193
+ return (
194
+ babelTypes.isCallExpression(init) &&
195
+ babelTypes.isIdentifier(init.callee) &&
196
+ init.callee.name === 'require' &&
197
+ babelTypes.isStringLiteral(init.arguments[0]) &&
198
+ init.arguments[0].value === moduleName
199
+ )
200
+ }
201
+ }
202
+
203
+ // import * as foo from 'groq'
204
+ // foo.defineQuery(...)
205
+ if (babelTypes.isMemberExpression(node)) {
206
+ const {object, property} = node
207
+
208
+ if (!babelTypes.isIdentifier(object)) {
209
+ return false
210
+ }
211
+
212
+ const binding = scope.getBinding(object.name)
213
+ if (!binding) {
214
+ return false
215
+ }
216
+ const {path} = binding
217
+
218
+ return (
219
+ babelTypes.isIdentifier(object) &&
220
+ babelTypes.isIdentifier(property) &&
221
+ property.name === importName &&
222
+ babelTypes.isImportNamespaceSpecifier(path.node) &&
223
+ path.parentPath &&
224
+ babelTypes.isImportDeclaration(path.parentPath.node) &&
225
+ path.parentPath.node.source.value === moduleName
226
+ )
227
+ }
228
+
229
+ return false
230
+ }
@@ -14,6 +14,11 @@ import {
14
14
  const REFERENCE_SYMBOL_NAME = 'internalGroqTypeReferenceTo'
15
15
  const ALL_SCHEMA_TYPES = 'AllSanitySchemaTypes'
16
16
 
17
+ type QueryWithTypeNode = {
18
+ query: string
19
+ typeNode: TypeNode
20
+ }
21
+
17
22
  /**
18
23
  * A class used to generate TypeScript types from a given schema
19
24
  * @internal
@@ -77,11 +82,8 @@ export class TypeGenerator {
77
82
  generateTypeNodeTypes(identifierName: string, typeNode: TypeNode): string {
78
83
  const type = this.getTypeNodeType(typeNode)
79
84
 
80
- const typeAlias = t.tsTypeAliasDeclaration(
81
- t.identifier(this.getTypeName(identifierName, typeNode)),
82
- null,
83
- type,
84
- )
85
+ const typeName = this.getTypeName(identifierName, typeNode)
86
+ const typeAlias = t.tsTypeAliasDeclaration(t.identifier(typeName), null, type)
85
87
 
86
88
  return new CodeGenerator(t.exportNamedDeclaration(typeAlias)).generate().code.trim()
87
89
  }
@@ -98,6 +100,57 @@ export class TypeGenerator {
98
100
  return new CodeGenerator(t.exportNamedDeclaration(decleration)).generate().code.trim()
99
101
  }
100
102
 
103
+ /**
104
+ * Takes a list of queries from the codebase and generates a type declaration
105
+ * for SanityClient to consume.
106
+ *
107
+ * Note: only types that have previously been generated with `generateTypeNodeTypes`
108
+ * will be included in the query map.
109
+ *
110
+ * @param queries - A list of queries to generate a type declaration for
111
+ * @returns
112
+ * @internal
113
+ * @beta
114
+ */
115
+ generateQueryMap(queries: QueryWithTypeNode[]): string {
116
+ const typesByQuerystring: {[query: string]: string[]} = {}
117
+
118
+ for (const query of queries) {
119
+ const name = this.typeNameMap.get(query.typeNode)
120
+ if (!name) {
121
+ continue
122
+ }
123
+
124
+ typesByQuerystring[query.query] ??= []
125
+ typesByQuerystring[query.query].push(name)
126
+ }
127
+
128
+ const queryReturnInterface = t.tsInterfaceDeclaration(
129
+ t.identifier('SanityQueries'),
130
+ null,
131
+ [],
132
+ t.tsInterfaceBody(
133
+ Object.entries(typesByQuerystring).map(([query, types]) => {
134
+ return t.tsPropertySignature(
135
+ t.stringLiteral(query),
136
+ t.tsTypeAnnotation(
137
+ t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type)))),
138
+ ),
139
+ )
140
+ }),
141
+ ),
142
+ )
143
+
144
+ const declareModule = t.declareModule(
145
+ t.stringLiteral('@sanity/client'),
146
+ t.blockStatement([queryReturnInterface]),
147
+ )
148
+
149
+ const clientImport = t.importDeclaration([], t.stringLiteral('@sanity/client'))
150
+
151
+ return new CodeGenerator(t.program([clientImport, declareModule])).generate().code.trim()
152
+ }
153
+
101
154
  /**
102
155
  * Since we are sanitizing identifiers we migt end up with collisions. Ie there might be a type mux.video and muxVideo, both these
103
156
  * types would be sanityized into MuxVideo. To avoid this we keep track of the generated type names and add a index to the name.