@sanity/codegen 3.86.1 → 3.86.2-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.
- package/lib/index.d.mts +79 -91
- package/lib/index.d.ts +79 -91
- package/lib/index.js +492 -151
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +493 -152
- package/lib/index.mjs.map +1 -1
- package/package.json +15 -17
- package/src/_exports/index.ts +16 -3
- package/src/readConfig.ts +77 -19
- package/src/typescript/asyncQueue.ts +100 -0
- package/src/typescript/expressionResolvers.ts +4 -3
- package/src/typescript/findQueriesInPath.ts +2 -2
- package/src/typescript/findQueriesInSource.ts +25 -5
- package/src/typescript/generateTypes.ts +425 -0
- package/src/typescript/schemaTypeGenerator.ts +415 -0
- package/src/typescript/typeGenerator.ts +0 -374
|
@@ -0,0 +1,100 @@
|
|
|
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
|
+
}
|
|
@@ -20,9 +20,10 @@ export interface NamedQueryResult {
|
|
|
20
20
|
name: string
|
|
21
21
|
/** result is a groq query */
|
|
22
22
|
result: resolveExpressionReturnType
|
|
23
|
-
|
|
23
|
+
/** type indicates whether this is a query or projection */
|
|
24
|
+
type: 'query' | 'projection'
|
|
24
25
|
/** location is the location of the query in the source */
|
|
25
|
-
location
|
|
26
|
+
location?: {
|
|
26
27
|
start?: {
|
|
27
28
|
line: number
|
|
28
29
|
column: number
|
|
@@ -37,7 +38,7 @@ export interface NamedQueryResult {
|
|
|
37
38
|
}
|
|
38
39
|
|
|
39
40
|
const TAGGED_TEMPLATE_ALLOW_LIST = ['groq']
|
|
40
|
-
const FUNCTION_WRAPPER_ALLOW_LIST = ['defineQuery']
|
|
41
|
+
const FUNCTION_WRAPPER_ALLOW_LIST = ['defineQuery', 'defineProjection']
|
|
41
42
|
|
|
42
43
|
/**
|
|
43
44
|
* resolveExpression takes a node and returns the resolved value of the expression.
|
|
@@ -11,12 +11,12 @@ import {getResolver} from './moduleResolver'
|
|
|
11
11
|
|
|
12
12
|
const debug = createDebug('sanity:codegen:findQueries:debug')
|
|
13
13
|
|
|
14
|
-
type ResultQueries = {
|
|
14
|
+
export type ResultQueries = {
|
|
15
15
|
type: 'queries'
|
|
16
16
|
filename: string
|
|
17
17
|
queries: NamedQueryResult[]
|
|
18
18
|
}
|
|
19
|
-
type ResultError = {
|
|
19
|
+
export type ResultError = {
|
|
20
20
|
type: 'error'
|
|
21
21
|
error: Error
|
|
22
22
|
filename: string
|
|
@@ -12,6 +12,7 @@ const require = createRequire(__filename)
|
|
|
12
12
|
|
|
13
13
|
const groqTagName = 'groq'
|
|
14
14
|
const defineQueryFunctionName = 'defineQuery'
|
|
15
|
+
const defineProjectionFunctionName = 'defineProjection'
|
|
15
16
|
const groqModuleName = 'groq'
|
|
16
17
|
const nextSanityModuleName = 'next-sanity'
|
|
17
18
|
|
|
@@ -50,13 +51,14 @@ export function findQueriesInSource(
|
|
|
50
51
|
babelTypes.isIdentifier(init.tag) &&
|
|
51
52
|
init.tag.name === groqTagName
|
|
52
53
|
|
|
53
|
-
// Look for strings wrapped in a defineQuery function call
|
|
54
|
-
const
|
|
54
|
+
// Look for strings wrapped in a defineQuery or defineProjection function call
|
|
55
|
+
const isDefineCall =
|
|
55
56
|
babelTypes.isCallExpression(init) &&
|
|
56
57
|
(isImportFrom(groqModuleName, defineQueryFunctionName, scope, init.callee) ||
|
|
58
|
+
isImportFrom(groqModuleName, defineProjectionFunctionName, scope, init.callee) ||
|
|
57
59
|
isImportFrom(nextSanityModuleName, defineQueryFunctionName, scope, init.callee))
|
|
58
60
|
|
|
59
|
-
if (babelTypes.isIdentifier(node.id) && (isGroqTemplateTag ||
|
|
61
|
+
if (babelTypes.isIdentifier(node.id) && (isGroqTemplateTag || isDefineCall)) {
|
|
60
62
|
// If we find a comment leading the decleration which macthes with ignoreValue we don't add
|
|
61
63
|
// the query
|
|
62
64
|
if (declarationLeadingCommentContains(path, ignoreValue)) {
|
|
@@ -64,8 +66,26 @@ export function findQueriesInSource(
|
|
|
64
66
|
}
|
|
65
67
|
|
|
66
68
|
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
|
+
|
|
67
87
|
const queryResult = resolveExpression({
|
|
68
|
-
node:
|
|
88
|
+
node: expressionToResolve, // Use the potentially updated expression node
|
|
69
89
|
file,
|
|
70
90
|
scope,
|
|
71
91
|
babelConfig,
|
|
@@ -84,7 +104,7 @@ export function findQueriesInSource(
|
|
|
84
104
|
}
|
|
85
105
|
: {}
|
|
86
106
|
|
|
87
|
-
queries.push({name: queryName, result: queryResult, location})
|
|
107
|
+
queries.push({name: queryName, result: queryResult, type: resultType, location})
|
|
88
108
|
}
|
|
89
109
|
},
|
|
90
110
|
})
|
|
@@ -0,0 +1,425 @@
|
|
|
1
|
+
/* eslint-disable max-depth */
|
|
2
|
+
/* eslint-disable max-statements */
|
|
3
|
+
import {CodeGenerator} from '@babel/generator'
|
|
4
|
+
import * as t from '@babel/types'
|
|
5
|
+
import {type SchemaType} from 'groq-js'
|
|
6
|
+
|
|
7
|
+
import {AsyncQueue} from './asyncQueue'
|
|
8
|
+
import {type ResultError, type ResultQueries} 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 DocumentTypeScoped = t.identifier('DocumentTypeScoped')
|
|
15
|
+
const DatasetScoped = t.identifier('DatasetScoped')
|
|
16
|
+
const ExtractDataset = t.identifier('ExtractDataset')
|
|
17
|
+
const AllSchemaTypes = t.identifier('AllSanitySchemaTypes')
|
|
18
|
+
const ReferenceSymbol = Object.assign(t.identifier(SchemaTypeGenerator.REFERENCE_SYMBOL_NAME), {
|
|
19
|
+
typeAnnotation: t.tsTypeAnnotation(
|
|
20
|
+
Object.assign(t.tsTypeOperator(t.tsSymbolKeyword()), {operator: 'unique'}),
|
|
21
|
+
),
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
export interface GeneratedSchema {
|
|
25
|
+
code: string
|
|
26
|
+
schemas: {
|
|
27
|
+
filename: string
|
|
28
|
+
projectId: string | 'default'
|
|
29
|
+
dataset: string | 'default'
|
|
30
|
+
typeCount: number
|
|
31
|
+
}[]
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface GeneratedQueries {
|
|
35
|
+
filename: string
|
|
36
|
+
results: GeneratedQuery[]
|
|
37
|
+
error?: unknown
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface GeneratedQuery {
|
|
41
|
+
name: string
|
|
42
|
+
query: string
|
|
43
|
+
code: string
|
|
44
|
+
type: 'query' | 'projection'
|
|
45
|
+
stats: TypeEvaluationStats
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface GeneratedTypemap {
|
|
49
|
+
code: string
|
|
50
|
+
stats: TypeEvaluationStats
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface TypegenResults {
|
|
54
|
+
generatedSchema: () => Promise<GeneratedSchema>
|
|
55
|
+
generatedQueries: () => AsyncIterable<GeneratedQueries>
|
|
56
|
+
generatedTypemap: () => Promise<GeneratedTypemap>
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface GenerateTypesOptions {
|
|
60
|
+
schemas: {
|
|
61
|
+
projectId: string
|
|
62
|
+
dataset: string
|
|
63
|
+
filename: string
|
|
64
|
+
schema: SchemaType
|
|
65
|
+
}[]
|
|
66
|
+
queriesByFile: AsyncIterable<ResultQueries | ResultError>
|
|
67
|
+
augmentGroqModule: boolean
|
|
68
|
+
overloadClientMethods: boolean
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function generateCode(node: t.Node) {
|
|
72
|
+
return `${new CodeGenerator(node).generate().code.trim()}\n\n`
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function scopeByDataset(tsType: t.TSType, options: {dataset: string; projectId: string}) {
|
|
76
|
+
return t.tsTypeReference(
|
|
77
|
+
DatasetScoped,
|
|
78
|
+
t.tsTypeParameterInstantiation([
|
|
79
|
+
tsType,
|
|
80
|
+
t.tsLiteralType(t.stringLiteral(options.dataset)),
|
|
81
|
+
t.tsLiteralType(t.stringLiteral(options.projectId)),
|
|
82
|
+
]),
|
|
83
|
+
)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// TODO: replace with `Promise.withResolvers` once the environments supports it
|
|
87
|
+
function PromiseWithResolvers<T = void>() {
|
|
88
|
+
let resolve!: (value: T) => void
|
|
89
|
+
let reject!: (error: unknown) => void
|
|
90
|
+
const promise = new Promise<T>((thisResolve, thisReject) => {
|
|
91
|
+
resolve = thisResolve
|
|
92
|
+
reject = thisReject
|
|
93
|
+
})
|
|
94
|
+
return {promise, resolve, reject}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function generateTypes({
|
|
98
|
+
schemas,
|
|
99
|
+
queriesByFile,
|
|
100
|
+
augmentGroqModule,
|
|
101
|
+
overloadClientMethods,
|
|
102
|
+
}: GenerateTypesOptions): TypegenResults {
|
|
103
|
+
const globalIdentifiers = new Set<string>()
|
|
104
|
+
|
|
105
|
+
globalIdentifiers.add(SanityQueries.name)
|
|
106
|
+
globalIdentifiers.add(SanityProjections.name)
|
|
107
|
+
globalIdentifiers.add(SanitySchemas.name)
|
|
108
|
+
globalIdentifiers.add(DocumentTypeScoped.name)
|
|
109
|
+
globalIdentifiers.add(DatasetScoped.name)
|
|
110
|
+
globalIdentifiers.add(ExtractDataset.name)
|
|
111
|
+
globalIdentifiers.add(AllSchemaTypes.name)
|
|
112
|
+
globalIdentifiers.add(ReferenceSymbol.name)
|
|
113
|
+
|
|
114
|
+
const generatedQueries = new AsyncQueue<GeneratedQueries>()
|
|
115
|
+
const {
|
|
116
|
+
promise: generatedSchema,
|
|
117
|
+
resolve: resolveGeneratedSchema,
|
|
118
|
+
reject: rejectGeneratedSchema,
|
|
119
|
+
} = PromiseWithResolvers<GeneratedSchema>()
|
|
120
|
+
const {
|
|
121
|
+
promise: generatedTypemap,
|
|
122
|
+
resolve: resolveGeneratedTypemap,
|
|
123
|
+
reject: rejectGeneratedTypemap,
|
|
124
|
+
} = PromiseWithResolvers<GeneratedTypemap>()
|
|
125
|
+
|
|
126
|
+
;(async () => {
|
|
127
|
+
const schemaGenerators = schemas.map((options) => new SchemaTypeGenerator(options))
|
|
128
|
+
const typeNames = new Set(schemaGenerators.flatMap((i) => i.getTypeNames()))
|
|
129
|
+
|
|
130
|
+
let schemaCode = ''
|
|
131
|
+
|
|
132
|
+
if (overloadClientMethods) {
|
|
133
|
+
schemaCode += generateCode(t.importDeclaration([], t.stringLiteral('@sanity/client')))
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
schemaCode += generateCode(
|
|
137
|
+
Object.assign(
|
|
138
|
+
t.importDeclaration(
|
|
139
|
+
[
|
|
140
|
+
t.importSpecifier(DocumentTypeScoped, DocumentTypeScoped),
|
|
141
|
+
t.importSpecifier(ExtractDataset, ExtractDataset),
|
|
142
|
+
t.importSpecifier(DatasetScoped, DatasetScoped),
|
|
143
|
+
],
|
|
144
|
+
t.stringLiteral('groq'),
|
|
145
|
+
),
|
|
146
|
+
{importKind: 'type'},
|
|
147
|
+
),
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
schemaCode += generateCode(
|
|
151
|
+
t.exportNamedDeclaration(
|
|
152
|
+
Object.assign(t.variableDeclaration('const', [t.variableDeclarator(ReferenceSymbol)]), {
|
|
153
|
+
declare: true,
|
|
154
|
+
}),
|
|
155
|
+
),
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
const schemaIdentifiers = new Set<string>()
|
|
159
|
+
|
|
160
|
+
for (const typeName of typeNames) {
|
|
161
|
+
const identifiers = new Set(
|
|
162
|
+
schemaGenerators
|
|
163
|
+
.map((i) => i.getIdentifier(typeName)?.name)
|
|
164
|
+
.filter((i) => typeof i === 'string'),
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
for (const identifier of identifiers) {
|
|
168
|
+
globalIdentifiers.add(identifier)
|
|
169
|
+
|
|
170
|
+
const tsTypes = schemaGenerators
|
|
171
|
+
.filter((i) => i.getIdentifier(typeName)?.name === identifier)
|
|
172
|
+
.map((i) => {
|
|
173
|
+
const tsType = i.getTsType(typeName)
|
|
174
|
+
if (tsType && schemaGenerators.length > 1) return scopeByDataset(tsType, i)
|
|
175
|
+
return tsType
|
|
176
|
+
})
|
|
177
|
+
.filter((i) => i !== undefined)
|
|
178
|
+
|
|
179
|
+
const tsType = tsTypes.length === 1 ? tsTypes[0] : t.tsUnionType(tsTypes)
|
|
180
|
+
|
|
181
|
+
const typeAlias = t.tsTypeAliasDeclaration(t.identifier(identifier), null, tsType)
|
|
182
|
+
const code = generateCode(t.exportNamedDeclaration(typeAlias))
|
|
183
|
+
schemaIdentifiers.add(identifier)
|
|
184
|
+
schemaCode += code
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const allSchemaTypesDeclaration = generateCode(
|
|
189
|
+
t.exportNamedDeclaration(
|
|
190
|
+
t.tsTypeAliasDeclaration(
|
|
191
|
+
AllSchemaTypes,
|
|
192
|
+
null,
|
|
193
|
+
t.tsUnionType(
|
|
194
|
+
Array.from(schemaIdentifiers).map((identifier) =>
|
|
195
|
+
t.tsTypeReference(t.identifier(identifier)),
|
|
196
|
+
),
|
|
197
|
+
),
|
|
198
|
+
),
|
|
199
|
+
),
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
schemaCode += allSchemaTypesDeclaration
|
|
203
|
+
|
|
204
|
+
if (augmentGroqModule) {
|
|
205
|
+
const sanitySchemasProperties = schemas.map(({dataset, projectId}) =>
|
|
206
|
+
t.tsPropertySignature(
|
|
207
|
+
t.stringLiteral(`${projectId}:${dataset}`),
|
|
208
|
+
t.tsTypeAnnotation(
|
|
209
|
+
t.tsTypeReference(
|
|
210
|
+
ExtractDataset,
|
|
211
|
+
t.tsTypeParameterInstantiation([
|
|
212
|
+
t.tsTypeReference(AllSchemaTypes),
|
|
213
|
+
t.tsLiteralType(t.stringLiteral(dataset)),
|
|
214
|
+
t.tsLiteralType(t.stringLiteral(projectId)),
|
|
215
|
+
]),
|
|
216
|
+
),
|
|
217
|
+
),
|
|
218
|
+
),
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
const sanitySchemasDeclaration = generateCode(
|
|
222
|
+
t.declareModule(
|
|
223
|
+
t.stringLiteral('groq'),
|
|
224
|
+
t.blockStatement([
|
|
225
|
+
t.tsInterfaceDeclaration(
|
|
226
|
+
SanitySchemas,
|
|
227
|
+
null,
|
|
228
|
+
[],
|
|
229
|
+
t.tsInterfaceBody(sanitySchemasProperties),
|
|
230
|
+
),
|
|
231
|
+
]),
|
|
232
|
+
),
|
|
233
|
+
)
|
|
234
|
+
schemaCode += sanitySchemasDeclaration
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
resolveGeneratedSchema({
|
|
238
|
+
code: schemaCode,
|
|
239
|
+
schemas: schemas.map(({schema, ...rest}) => ({
|
|
240
|
+
...rest,
|
|
241
|
+
typeCount: schema.length,
|
|
242
|
+
})),
|
|
243
|
+
})
|
|
244
|
+
|
|
245
|
+
const queryIdentifiers = new Map<string, t.Identifier[]>()
|
|
246
|
+
const projectionIdentifiers = new Map<string, t.Identifier[]>()
|
|
247
|
+
const totalStats: TypeEvaluationStats = {
|
|
248
|
+
totalTypeNodes: 0,
|
|
249
|
+
unknownTypeCount: 0,
|
|
250
|
+
emptyUnionCount: 0,
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
for await (const input of queriesByFile) {
|
|
254
|
+
try {
|
|
255
|
+
if (input.type === 'error') throw input.error
|
|
256
|
+
|
|
257
|
+
const results: GeneratedQuery[] = []
|
|
258
|
+
for (const query of input.queries) {
|
|
259
|
+
const desiredName = SchemaTypeGenerator.sanitizeIdentifier(
|
|
260
|
+
query.type === 'projection' ? `${query.name}ProjectionResult` : `${query.name}Result`,
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
let resultingName = desiredName
|
|
264
|
+
let index = 2
|
|
265
|
+
while (globalIdentifiers.has(resultingName)) {
|
|
266
|
+
resultingName = `${desiredName}_${index}`
|
|
267
|
+
index++
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const identifier = t.identifier(resultingName)
|
|
271
|
+
let identifiers =
|
|
272
|
+
query.type === 'projection'
|
|
273
|
+
? projectionIdentifiers.get(query.result)
|
|
274
|
+
: queryIdentifiers.get(query.result)
|
|
275
|
+
|
|
276
|
+
if (!identifiers) {
|
|
277
|
+
identifiers = []
|
|
278
|
+
if (query.type === 'projection') {
|
|
279
|
+
projectionIdentifiers.set(query.result, identifiers)
|
|
280
|
+
} else {
|
|
281
|
+
queryIdentifiers.set(query.result, identifiers)
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
identifiers.push(identifier)
|
|
285
|
+
|
|
286
|
+
const evaluationResults = schemaGenerators.map((i) => {
|
|
287
|
+
const result =
|
|
288
|
+
query.type === 'projection'
|
|
289
|
+
? i.evaluateProjection(query.result)
|
|
290
|
+
: i.evaluateQuery(query.result)
|
|
291
|
+
|
|
292
|
+
return result
|
|
293
|
+
})
|
|
294
|
+
|
|
295
|
+
const aggregatedQueryStats = evaluationResults.reduce<TypeEvaluationStats>(
|
|
296
|
+
(acc, {stats}) => ({
|
|
297
|
+
totalTypeNodes: acc.totalTypeNodes + stats.totalTypeNodes,
|
|
298
|
+
unknownTypeCount: acc.unknownTypeCount + stats.unknownTypeCount,
|
|
299
|
+
emptyUnionCount: acc.emptyUnionCount + stats.emptyUnionCount,
|
|
300
|
+
}),
|
|
301
|
+
{totalTypeNodes: 0, unknownTypeCount: 0, emptyUnionCount: 0},
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
totalStats.totalTypeNodes += aggregatedQueryStats.totalTypeNodes
|
|
305
|
+
totalStats.unknownTypeCount += aggregatedQueryStats.unknownTypeCount
|
|
306
|
+
totalStats.emptyUnionCount += aggregatedQueryStats.emptyUnionCount
|
|
307
|
+
|
|
308
|
+
const tsTypes = evaluationResults.map(({tsType}, resultIndex) => {
|
|
309
|
+
if (schemas.length === 1) return tsType
|
|
310
|
+
return scopeByDataset(tsType, schemaGenerators[resultIndex])
|
|
311
|
+
})
|
|
312
|
+
|
|
313
|
+
const tsType = tsTypes.length === 1 ? tsTypes[0] : t.tsUnionType(tsTypes)
|
|
314
|
+
const typeAlias = t.tsTypeAliasDeclaration(identifier, null, tsType)
|
|
315
|
+
|
|
316
|
+
const code = generateCode(
|
|
317
|
+
t.addComments(t.exportNamedDeclaration(typeAlias), 'leading', [
|
|
318
|
+
{type: 'CommentLine', value: ` Source: ${input.filename}`},
|
|
319
|
+
{type: 'CommentLine', value: ` Variable: ${query.name}`},
|
|
320
|
+
{
|
|
321
|
+
type: 'CommentLine',
|
|
322
|
+
value: ` ${query.type === 'projection' ? 'Projection' : 'Query'}: ${query.result.replace(/(\r\n|\n|\r)/gm, '').trim()}`,
|
|
323
|
+
},
|
|
324
|
+
]),
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
results.push({
|
|
328
|
+
name: query.name,
|
|
329
|
+
query: query.result,
|
|
330
|
+
type: query.type,
|
|
331
|
+
code,
|
|
332
|
+
stats: aggregatedQueryStats,
|
|
333
|
+
})
|
|
334
|
+
}
|
|
335
|
+
generatedQueries.enqueue({filename: input.filename, results})
|
|
336
|
+
} catch (error) {
|
|
337
|
+
generatedQueries.enqueue({filename: input.filename, results: [], error})
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
generatedQueries.finish()
|
|
342
|
+
|
|
343
|
+
let typemapCode = ''
|
|
344
|
+
const clientModuleBlockStatement: t.Statement[] = []
|
|
345
|
+
const groqModuleBlockStatement: t.Statement[] = []
|
|
346
|
+
|
|
347
|
+
// Only generate SanityQueries if there are query results
|
|
348
|
+
if (queryIdentifiers.size > 0) {
|
|
349
|
+
const sanityQueriesInterfaceDeclaration = t.tsInterfaceDeclaration(
|
|
350
|
+
SanityQueries,
|
|
351
|
+
null,
|
|
352
|
+
[],
|
|
353
|
+
t.tsInterfaceBody(
|
|
354
|
+
Array.from(queryIdentifiers).map(([query, identifiers]) =>
|
|
355
|
+
t.tsPropertySignature(
|
|
356
|
+
t.stringLiteral(query),
|
|
357
|
+
t.tsTypeAnnotation(
|
|
358
|
+
identifiers.length === 1
|
|
359
|
+
? t.tsTypeReference(identifiers[0])
|
|
360
|
+
: t.tsUnionType(identifiers.map((i) => t.tsTypeReference(i))),
|
|
361
|
+
),
|
|
362
|
+
),
|
|
363
|
+
),
|
|
364
|
+
),
|
|
365
|
+
)
|
|
366
|
+
// Add to both module declarations if needed
|
|
367
|
+
clientModuleBlockStatement.push(sanityQueriesInterfaceDeclaration)
|
|
368
|
+
groqModuleBlockStatement.push(sanityQueriesInterfaceDeclaration)
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// Only generate SanityProjections if there are projection results
|
|
372
|
+
if (projectionIdentifiers.size > 0) {
|
|
373
|
+
const sanityProjectionsInterfaceDeclaration = t.tsInterfaceDeclaration(
|
|
374
|
+
SanityProjections,
|
|
375
|
+
null,
|
|
376
|
+
[],
|
|
377
|
+
t.tsInterfaceBody(
|
|
378
|
+
Array.from(projectionIdentifiers).map(([projection, identifiers]) =>
|
|
379
|
+
t.tsPropertySignature(
|
|
380
|
+
t.stringLiteral(projection),
|
|
381
|
+
t.tsTypeAnnotation(
|
|
382
|
+
identifiers.length === 1
|
|
383
|
+
? t.tsTypeReference(identifiers[0])
|
|
384
|
+
: t.tsUnionType(identifiers.map((i) => t.tsTypeReference(i))),
|
|
385
|
+
),
|
|
386
|
+
),
|
|
387
|
+
),
|
|
388
|
+
),
|
|
389
|
+
)
|
|
390
|
+
// Add only to groq module declaration
|
|
391
|
+
groqModuleBlockStatement.push(sanityProjectionsInterfaceDeclaration)
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
if (overloadClientMethods && clientModuleBlockStatement.length > 0) {
|
|
395
|
+
const clientModuleDeclaration = t.declareModule(
|
|
396
|
+
t.stringLiteral('@sanity/client'),
|
|
397
|
+
t.blockStatement(clientModuleBlockStatement),
|
|
398
|
+
)
|
|
399
|
+
typemapCode += generateCode(clientModuleDeclaration)
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
if (augmentGroqModule && groqModuleBlockStatement.length > 0) {
|
|
403
|
+
const groqModuleDeclaration = t.declareModule(
|
|
404
|
+
t.stringLiteral('groq'),
|
|
405
|
+
t.blockStatement(groqModuleBlockStatement),
|
|
406
|
+
)
|
|
407
|
+
typemapCode += generateCode(groqModuleDeclaration)
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
resolveGeneratedTypemap({
|
|
411
|
+
code: typemapCode,
|
|
412
|
+
stats: totalStats,
|
|
413
|
+
})
|
|
414
|
+
})().catch((err) => {
|
|
415
|
+
generatedQueries.throwError(err)
|
|
416
|
+
rejectGeneratedSchema(err)
|
|
417
|
+
rejectGeneratedTypemap(err)
|
|
418
|
+
})
|
|
419
|
+
|
|
420
|
+
return {
|
|
421
|
+
generatedSchema: () => generatedSchema,
|
|
422
|
+
generatedQueries: () => generatedQueries,
|
|
423
|
+
generatedTypemap: () => generatedTypemap,
|
|
424
|
+
}
|
|
425
|
+
}
|