@sanity/codegen 8.1.0 → 8.2.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.
@@ -2,7 +2,7 @@
2
2
  import * as t from '@babel/types';
3
3
  import { createSelector } from 'reselect';
4
4
  import { resultSuffix } from '../casing.js';
5
- import { ALL_SANITY_SCHEMA_TYPES, ARRAY_OF, INTERNAL_REFERENCE_SYMBOL, SANITY_QUERIES } from './constants.js';
5
+ import { ALL_SANITY_SCHEMA_TYPES, ARRAY_OF, INTERNAL_REFERENCE_SYMBOL, SANITY_PROJECTIONS_BY_RESOURCE, SANITY_QUERIES, SANITY_QUERIES_BY_RESOURCE, SANITY_SCHEMAS_BY_RESOURCE } from './constants.js';
6
6
  import { computeOnce, generateCode, getUniqueIdentifierForName, normalizePrintablePath, tsDeclareGlobal, tsDeclareModule } from './helpers.js';
7
7
  import { SchemaTypeGenerator } from './schemaTypeGenerator.js';
8
8
  import { QueryEvaluationError } from './types.js';
@@ -88,13 +88,69 @@ import { QueryEvaluationError } from './types.js';
88
88
  id
89
89
  };
90
90
  });
91
- static async getEvaluatedModules({ queries: extractedModules, reporter: report, root = process.cwd(), schemaTypeDeclarations, schemaTypeGenerator }) {
91
+ /**
92
+ * Evaluates a projection against its document type, or against every document type when it
93
+ * names none. Document types with the same result share one group, so a projection that does
94
+ * not apply to most types does not repeat the same type once per document type.
95
+ *
96
+ * Returns `undefined` for a document type this schema does not have when generating for a
97
+ * resource: datasets of one app can scan the same files, and the type can belong to another.
98
+ */ static evaluateProjection({ extractedProjection, filename, resource, schemaTypeGenerator }) {
99
+ const { documentType, projection } = extractedProjection;
100
+ const documentTypeNames = schemaTypeGenerator.documentTypeNames();
101
+ // Without this, an unknown or non-document type evaluates to `null` and is registered as if
102
+ // it were a result. An object type is a mistake in any run.
103
+ if (documentType !== undefined && !documentTypeNames.includes(documentType)) {
104
+ if (resource && !schemaTypeGenerator.hasType(documentType)) return undefined;
105
+ throw new Error(`"${documentType}" is not a document type in the schema`);
106
+ }
107
+ const documentTypes = documentType === undefined ? documentTypeNames : [
108
+ documentType
109
+ ];
110
+ const groups = new Map();
111
+ const stats = {
112
+ allTypes: 0,
113
+ emptyUnions: 0,
114
+ unknownTypes: 0
115
+ };
116
+ for (const type of documentTypes){
117
+ const result = schemaTypeGenerator.evaluateProjection({
118
+ documentType: type,
119
+ projection
120
+ });
121
+ const key = generateCode(result.tsType);
122
+ const group = groups.get(key);
123
+ if (group) {
124
+ group.documentTypes.push(type);
125
+ continue;
126
+ }
127
+ groups.set(key, {
128
+ documentTypes: [
129
+ type
130
+ ],
131
+ tsType: result.tsType
132
+ });
133
+ stats.allTypes += result.stats.allTypes;
134
+ stats.emptyUnions += result.stats.emptyUnions;
135
+ stats.unknownTypes += result.stats.unknownTypes;
136
+ }
137
+ return {
138
+ extractedProjection,
139
+ filename,
140
+ groups: [
141
+ ...groups.values()
142
+ ],
143
+ stats
144
+ };
145
+ }
146
+ static async getEvaluatedModules({ queries: extractedModules, reporter: report, resource, root = process.cwd(), schemaTypeDeclarations, schemaTypeGenerator }) {
92
147
  if (!extractedModules) {
93
148
  report?.stream.evaluatedModules.end();
94
149
  return [];
95
150
  }
96
151
  const currentIdentifiers = new Set(schemaTypeDeclarations.map(({ id })=>id.name));
97
152
  const evaluatedModuleResults = [];
153
+ const unnamedProjectionsByModule = new Map();
98
154
  for await (const { filename, ...extractedModule } of extractedModules){
99
155
  const queries = [];
100
156
  const errors = [
@@ -139,6 +195,26 @@ import { QueryEvaluationError } from './types.js';
139
195
  }));
140
196
  }
141
197
  }
198
+ const unnamedProjections = [];
199
+ for (const extractedProjection of extractedModule.projections ?? []){
200
+ const { variable } = extractedProjection;
201
+ try {
202
+ const unnamedProjection = TypeGenerator.evaluateProjection({
203
+ extractedProjection,
204
+ filename,
205
+ resource,
206
+ schemaTypeGenerator
207
+ });
208
+ if (unnamedProjection) unnamedProjections.push(unnamedProjection);
209
+ } catch (cause) {
210
+ errors.push(new QueryEvaluationError({
211
+ cause,
212
+ filename,
213
+ variable
214
+ }));
215
+ }
216
+ }
217
+ // Streamed without projections, which are named once every file has been read.
142
218
  const evaluatedModule = {
143
219
  errors,
144
220
  filename,
@@ -146,33 +222,48 @@ import { QueryEvaluationError } from './types.js';
146
222
  };
147
223
  report?.stream.evaluatedModules.emit(evaluatedModule);
148
224
  evaluatedModuleResults.push(evaluatedModule);
225
+ unnamedProjectionsByModule.set(evaluatedModule, unnamedProjections);
149
226
  }
150
227
  report?.stream.evaluatedModules.end();
228
+ // Projections are named after every query, so a query result keeps the name it had before
229
+ // projections were generated, whatever the file order. A projection sharing a query's
230
+ // variable name gets the numeric suffix instead.
231
+ for (const [evaluatedModule, unnamedProjections] of unnamedProjectionsByModule){
232
+ evaluatedModule.projections = unnamedProjections.map((unnamedProjection)=>TypeGenerator.nameProjection({
233
+ currentIdentifiers,
234
+ root,
235
+ unnamedProjection
236
+ }));
237
+ }
151
238
  return evaluatedModuleResults;
152
239
  }
240
+ /**
241
+ * One property per document type, each holding one property per distinct projection string,
242
+ * typed as the union of every result alias generated for that pair.
243
+ */ static getProjectionResultProperties(evaluatedModules) {
244
+ const typesByDocumentType = {};
245
+ for (const { projections = [] } of evaluatedModules){
246
+ for (const { projection, resultsByDocumentType } of projections){
247
+ for (const [documentType, id] of Object.entries(resultsByDocumentType)){
248
+ typesByDocumentType[documentType] ??= {};
249
+ typesByDocumentType[documentType][projection] ??= [];
250
+ typesByDocumentType[documentType][projection].push(id.name);
251
+ }
252
+ }
253
+ }
254
+ return Object.entries(typesByDocumentType).map(([documentType, typesByProjection])=>t.tsPropertySignature(t.stringLiteral(documentType), t.tsTypeAnnotation(t.tsTypeLiteral(Object.entries(typesByProjection).map(([projection, types])=>t.tsPropertySignature(t.stringLiteral(projection), t.tsTypeAnnotation(t.tsUnionType(types.map((type)=>t.tsTypeReference(t.identifier(type)))))))))));
255
+ }
153
256
  static async getQueryMapDeclaration({ evaluatedModules, overloadClientMethods = true }) {
154
257
  if (!overloadClientMethods) return {
155
258
  ast: t.program([]),
156
259
  code: ''
157
260
  };
158
- const queries = evaluatedModules.flatMap((module)=>module.queries);
159
- if (queries.length === 0) return {
261
+ const properties = TypeGenerator.getQueryResultProperties(evaluatedModules);
262
+ if (properties.length === 0) return {
160
263
  ast: t.program([]),
161
264
  code: ''
162
265
  };
163
- const typesByQuerystring = {};
164
- for (const { id, query } of queries){
165
- typesByQuerystring[query] ??= [];
166
- typesByQuerystring[query].push(id.name);
167
- }
168
- const queryReturnInterface = t.tsInterfaceDeclaration(SANITY_QUERIES, null, [], t.tsInterfaceBody(Object.entries(typesByQuerystring).map(([query, types])=>{
169
- return t.tsPropertySignature(t.stringLiteral(query), t.tsTypeAnnotation(t.tsUnionType(types.map((type)=>t.tsTypeReference(t.identifier(type))))));
170
- })));
171
- // The registry lives on the global `SanityQueries` interface, which `@sanity/client`'s exported
172
- // `SanityQueries` inherits from. Registering globally needs no import of, and no module
173
- // resolution to, `@sanity/client`: the registrations are seen whether or not the client is a
174
- // direct dependency of this file, however many copies of it are installed, and from every entry
175
- // point including `@sanity/client/stega`.
266
+ const queryReturnInterface = t.tsInterfaceDeclaration(SANITY_QUERIES, null, [], t.tsInterfaceBody(properties));
176
267
  const globalRegistry = t.addComments(tsDeclareGlobal([
177
268
  queryReturnInterface
178
269
  ]), 'leading', [
@@ -181,16 +272,11 @@ import { QueryEvaluationError } from './types.js';
181
272
  value: ' Query TypeMap'
182
273
  }
183
274
  ]);
184
- // `@sanity/client` releases that predate the global registry only read their exported
185
- // `SanityQueries` interface. Interface merging unions the `extends` clauses of every
186
- // declaration, so adding the global interface as a base type makes those releases read the
187
- // registry above. Releases that already inherit the global see a duplicate `extends` of the
188
- // same type, which is accepted, so the same output works with either.
189
- // `SANITY_QUERIES` is already the registry's identifier and a node must not appear twice in one
190
- // tree, so the bridge mints its own.
275
+ // The client-side global registry: https://github.com/sanity-io/client/pull/1319 (8.x) and
276
+ // https://github.com/sanity-io/client/pull/1320 (7.x)
191
277
  const bridge = t.addComments(tsDeclareModule('@sanity/client', [
192
- t.tsInterfaceDeclaration(t.identifier(SANITY_QUERIES.name), null, [
193
- t.tsExpressionWithTypeArguments(t.tsQualifiedName(t.identifier('globalThis'), t.identifier(SANITY_QUERIES.name)))
278
+ t.tsInterfaceDeclaration(SANITY_QUERIES, null, [
279
+ t.tsExpressionWithTypeArguments(t.tsQualifiedName(t.identifier('globalThis'), SANITY_QUERIES))
194
280
  ], t.tsInterfaceBody([]))
195
281
  ]), 'leading', [
196
282
  {
@@ -208,7 +294,95 @@ import { QueryEvaluationError } from './types.js';
208
294
  code
209
295
  };
210
296
  }
297
+ /**
298
+ * One property per distinct query string, typed as the union of every result type generated
299
+ * for it. Two variables holding the same query text share a key.
300
+ */ static getQueryResultProperties(evaluatedModules) {
301
+ const typesByQuerystring = {};
302
+ for (const { queries } of evaluatedModules){
303
+ for (const { id, query } of queries){
304
+ typesByQuerystring[query] ??= [];
305
+ typesByQuerystring[query].push(id.name);
306
+ }
307
+ }
308
+ return Object.entries(typesByQuerystring).map(([query, types])=>t.tsPropertySignature(t.stringLiteral(query), t.tsTypeAnnotation(t.tsUnionType(types.map((type)=>t.tsTypeReference(t.identifier(type)))))));
309
+ }
310
+ static getResourceRegistryDeclaration({ evaluatedModules, resource }) {
311
+ const key = `${resource.projectId}.${resource.dataset}`;
312
+ const schemas = t.tsInterfaceDeclaration(SANITY_SCHEMAS_BY_RESOURCE, null, [], t.tsInterfaceBody([
313
+ t.tsPropertySignature(t.stringLiteral(key), t.tsTypeAnnotation(t.tsTypeReference(ALL_SANITY_SCHEMA_TYPES)))
314
+ ]));
315
+ // Written even with no queries, and the projection entry below even with no projections. An
316
+ // entry, empty or not, tells consumers this resource is generated, so a query or projection
317
+ // missing from it is a miss rather than a reason to fall back.
318
+ const queries = t.tsInterfaceDeclaration(SANITY_QUERIES_BY_RESOURCE, null, [], t.tsInterfaceBody([
319
+ t.tsPropertySignature(t.stringLiteral(key), t.tsTypeAnnotation(t.tsTypeLiteral(TypeGenerator.getQueryResultProperties(evaluatedModules))))
320
+ ]));
321
+ const projections = t.tsInterfaceDeclaration(SANITY_PROJECTIONS_BY_RESOURCE, null, [], t.tsInterfaceBody([
322
+ t.tsPropertySignature(t.stringLiteral(key), t.tsTypeAnnotation(t.tsTypeLiteral(TypeGenerator.getProjectionResultProperties(evaluatedModules))))
323
+ ]));
324
+ // No `declare module "@sanity/client"` bridge, unlike the flat map. These registries first
325
+ // shipped already global, so no client release needs one, and an augmentation would fail
326
+ // with TS2664 wherever `@sanity/client` is not resolvable from the generated file.
327
+ const ast = t.program([
328
+ t.addComments(tsDeclareGlobal([
329
+ schemas,
330
+ queries,
331
+ projections
332
+ ]), 'leading', [
333
+ {
334
+ type: 'CommentLine',
335
+ value: ` Resource TypeMap: ${key}`
336
+ }
337
+ ])
338
+ ]);
339
+ const code = generateCode(ast);
340
+ return {
341
+ ast,
342
+ code
343
+ };
344
+ }
345
+ /** Declares one result alias per group, with names not yet in `currentIdentifiers`. */ static nameProjection({ currentIdentifiers, root, unnamedProjection: { extractedProjection, filename, groups, stats } }) {
346
+ const { projection, variable } = extractedProjection;
347
+ const trimmedProjection = projection.replaceAll(/(\r\n|\n|\r)/gm, '').trim();
348
+ const declarations = [];
349
+ const resultsByDocumentType = {};
350
+ for (const group of groups){
351
+ const name = groups.length === 1 ? variable.id.name : `${variable.id.name}${pascalCase(group.documentTypes[0])}`;
352
+ const id = getUniqueIdentifierForName(resultSuffix(name), currentIdentifiers);
353
+ currentIdentifiers.add(id.name);
354
+ const ast = t.addComments(t.exportNamedDeclaration(t.tsTypeAliasDeclaration(id, null, group.tsType)), 'leading', [
355
+ {
356
+ type: 'CommentLine',
357
+ value: ` Source: ${normalizePrintablePath(root, filename)}`
358
+ },
359
+ {
360
+ type: 'CommentLine',
361
+ value: ` Variable: ${variable.id.name}`
362
+ },
363
+ {
364
+ type: 'CommentLine',
365
+ value: ` Projection on ${group.documentTypes.join(', ')}: ${trimmedProjection}`
366
+ }
367
+ ]);
368
+ declarations.push({
369
+ ast,
370
+ code: generateCode(ast),
371
+ id
372
+ });
373
+ for (const type of group.documentTypes)resultsByDocumentType[type] = id;
374
+ }
375
+ return {
376
+ ...extractedProjection,
377
+ declarations,
378
+ resultsByDocumentType,
379
+ stats
380
+ };
381
+ }
211
382
  async generateTypes(options) {
383
+ if (options.resource && (!options.resource.projectId || !options.resource.dataset)) {
384
+ throw new TypeError('A typegen resource needs both a projectId and a dataset');
385
+ }
212
386
  const { reporter: report } = options;
213
387
  const internalReferenceSymbol = this.getInternalReferenceSymbolDeclaration();
214
388
  const schemaTypeGenerator = this.getSchemaTypeGenerator(options);
@@ -249,12 +423,29 @@ import { QueryEvaluationError } from './types.js';
249
423
  code += query.code;
250
424
  }
251
425
  }
426
+ for (const { projections = [] } of evaluatedModules){
427
+ for (const { declarations } of projections){
428
+ for (const declaration of declarations){
429
+ program.body.push(declaration.ast);
430
+ code += declaration.code;
431
+ }
432
+ }
433
+ }
252
434
  const queryMapDeclaration = await TypeGenerator.getQueryMapDeclaration({
253
435
  ...options,
254
436
  evaluatedModules
255
437
  });
256
438
  program.body.push(...queryMapDeclaration.ast.body);
257
439
  code += queryMapDeclaration.code;
440
+ if (options.resource) {
441
+ const resourceRegistry = TypeGenerator.getResourceRegistryDeclaration({
442
+ ...options,
443
+ evaluatedModules,
444
+ resource: options.resource
445
+ });
446
+ program.body.push(...resourceRegistry.ast.body);
447
+ code += resourceRegistry.code;
448
+ }
258
449
  report?.event.generatedQueryTypes({
259
450
  queryMapDeclaration
260
451
  });
@@ -264,5 +455,8 @@ import { QueryEvaluationError } from './types.js';
264
455
  };
265
456
  }
266
457
  }
458
+ /** `sanity.imageAsset` to `SanityImageAsset`, for naming a result alias after a document type. */ function pascalCase(value) {
459
+ return value.split(/[^A-Za-z0-9]+/).filter(Boolean).map((part)=>part[0].toUpperCase() + part.slice(1)).join('');
460
+ }
267
461
 
268
462
  //# sourceMappingURL=typeGenerator.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/typescript/typeGenerator.ts"],"sourcesContent":["/* eslint-disable unicorn/consistent-function-scoping */\nimport process from 'node:process'\n\nimport * as t from '@babel/types'\nimport {type WorkerChannel, type WorkerChannelReporter} from '@sanity/worker-channels'\nimport {type SchemaType} from 'groq-js'\nimport {createSelector} from 'reselect'\n\nimport {resultSuffix} from '../casing.js'\nimport {\n ALL_SANITY_SCHEMA_TYPES,\n ARRAY_OF,\n INTERNAL_REFERENCE_SYMBOL,\n SANITY_QUERIES,\n} from './constants.js'\nimport {\n computeOnce,\n generateCode,\n getUniqueIdentifierForName,\n normalizePrintablePath,\n tsDeclareGlobal,\n tsDeclareModule,\n} from './helpers.js'\nimport {SchemaTypeGenerator} from './schemaTypeGenerator.js'\nimport {\n type EvaluatedModule,\n type EvaluatedQuery,\n type ExtractedModule,\n QueryEvaluationError,\n type QueryExtractionError,\n} from './types.js'\n\n/** @public */\nexport type TypegenWorkerChannel = WorkerChannel.Definition<{\n evaluatedModules: WorkerChannel.Stream<EvaluatedModule>\n generatedQueryTypes: WorkerChannel.Event<{\n queryMapDeclaration: {ast: t.Program; code: string}\n }>\n generatedSchemaTypes: WorkerChannel.Event<{\n allSanitySchemaTypesDeclaration: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n }\n internalReferenceSymbol: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n }\n schemaTypeDeclarations: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n name: string\n tsType: t.TSType\n }[]\n }>\n}>\n\n/** @public */\nexport interface GenerateTypesOptions {\n schema: SchemaType\n\n overloadClientMethods?: boolean\n queries?: AsyncIterable<ExtractedModule>\n reporter?: WorkerChannelReporter<TypegenWorkerChannel>\n root?: string\n schemaPath?: string\n}\n\ntype GetEvaluatedModulesOptions = GenerateTypesOptions & {\n schemaTypeDeclarations: ReturnType<TypeGenerator['getSchemaTypeDeclarations']>\n schemaTypeGenerator: SchemaTypeGenerator\n}\ntype GetQueryMapDeclarationOptions = GenerateTypesOptions & {\n evaluatedModules: EvaluatedModule[]\n}\n\n/**\n * A class used to generate TypeScript types from a given schema\n * @beta\n */\nexport class TypeGenerator {\n private getSchemaTypeGenerator = createSelector(\n [(options: GenerateTypesOptions) => options.schema],\n\n (schema) => new SchemaTypeGenerator(schema),\n )\n\n private getSchemaTypeDeclarations = createSelector(\n [\n (options: GenerateTypesOptions) => options.root,\n (options: GenerateTypesOptions) => options.schemaPath,\n this.getSchemaTypeGenerator,\n ],\n\n (root = process.cwd(), schemaPath, schema) =>\n [...schema].map(({id, name, tsType}, index) => {\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n let ast = t.exportNamedDeclaration(typeAlias)\n\n if (index === 0 && schemaPath) {\n ast = t.addComments(ast, 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePrintablePath(root, schemaPath)}`},\n ])\n }\n const code = generateCode(ast)\n return {ast, code, id, name, tsType}\n }),\n )\n\n private getAllSanitySchemaTypesDeclaration = createSelector(\n [this.getSchemaTypeDeclarations],\n (schemaTypes) => {\n const ast = t.exportNamedDeclaration(\n t.tsTypeAliasDeclaration(\n ALL_SANITY_SCHEMA_TYPES,\n null,\n schemaTypes.length > 0\n ? t.tsUnionType(schemaTypes.map(({id}) => t.tsTypeReference(id)))\n : t.tsNeverKeyword(),\n ),\n )\n const code = generateCode(ast)\n\n return {ast, code, id: ALL_SANITY_SCHEMA_TYPES}\n },\n )\n\n private getArrayOfDeclaration = computeOnce(() => {\n // Creates: type ArrayOf<T> = Array<T & { _key: string }>;\n const typeParam = t.tsTypeParameter(null, null, 'T')\n const intersectionType = t.tsIntersectionType([\n t.tsTypeReference(t.identifier('T')),\n t.tsTypeLiteral([\n t.tsPropertySignature(t.identifier('_key'), t.tsTypeAnnotation(t.tsStringKeyword())),\n ]),\n ])\n const arrayType = t.tsTypeReference(\n t.identifier('Array'),\n t.tsTypeParameterInstantiation([intersectionType]),\n )\n\n const ast = t.tsTypeAliasDeclaration(\n ARRAY_OF,\n t.tsTypeParameterDeclaration([typeParam]),\n arrayType,\n )\n const code = generateCode(ast)\n\n return {ast, code, id: ARRAY_OF}\n })\n\n private getInternalReferenceSymbolDeclaration = computeOnce(() => {\n const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword(), 'unique')\n\n const id = INTERNAL_REFERENCE_SYMBOL\n id.typeAnnotation = t.tsTypeAnnotation(typeOperator)\n\n const declaration = t.variableDeclaration('const', [t.variableDeclarator(id)])\n declaration.declare = true\n const ast = t.exportNamedDeclaration(declaration)\n const code = generateCode(ast)\n\n return {ast, code, id}\n })\n\n private static async getEvaluatedModules({\n queries: extractedModules,\n reporter: report,\n root = process.cwd(),\n schemaTypeDeclarations,\n schemaTypeGenerator,\n }: GetEvaluatedModulesOptions) {\n if (!extractedModules) {\n report?.stream.evaluatedModules.end()\n return []\n }\n\n const currentIdentifiers = new Set<string>(schemaTypeDeclarations.map(({id}) => id.name))\n const evaluatedModuleResults: EvaluatedModule[] = []\n\n for await (const {filename, ...extractedModule} of extractedModules) {\n const queries: EvaluatedQuery[] = []\n const errors: (QueryEvaluationError | QueryExtractionError)[] = [...extractedModule.errors]\n\n for (const extractedQuery of extractedModule.queries) {\n const {variable} = extractedQuery\n try {\n const {stats, tsType} = schemaTypeGenerator.evaluateQuery(extractedQuery)\n const id = getUniqueIdentifierForName(resultSuffix(variable.id.name), currentIdentifiers)\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n const trimmedQuery = extractedQuery.query.replaceAll(/(\\r\\n|\\n|\\r)/gm, '').trim()\n const ast = t.addComments(t.exportNamedDeclaration(typeAlias), 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePrintablePath(root, filename)}`},\n {type: 'CommentLine', value: ` Variable: ${variable.id.name}`},\n {type: 'CommentLine', value: ` Query: ${trimmedQuery}`},\n ])\n\n const evaluatedQueryResult: EvaluatedQuery = {\n ast,\n code: generateCode(ast),\n id,\n stats,\n tsType,\n ...extractedQuery,\n }\n\n currentIdentifiers.add(id.name)\n queries.push(evaluatedQueryResult)\n } catch (cause) {\n errors.push(new QueryEvaluationError({cause, filename, variable}))\n }\n }\n\n const evaluatedModule: EvaluatedModule = {\n errors,\n filename,\n queries,\n }\n report?.stream.evaluatedModules.emit(evaluatedModule)\n evaluatedModuleResults.push(evaluatedModule)\n }\n report?.stream.evaluatedModules.end()\n\n return evaluatedModuleResults\n }\n\n private static async getQueryMapDeclaration({\n evaluatedModules,\n overloadClientMethods = true,\n }: GetQueryMapDeclarationOptions) {\n if (!overloadClientMethods) return {ast: t.program([]), code: ''}\n\n const queries = evaluatedModules.flatMap((module) => module.queries)\n if (queries.length === 0) return {ast: t.program([]), code: ''}\n\n const typesByQuerystring: {[query: string]: string[]} = {}\n for (const {id, query} of queries) {\n typesByQuerystring[query] ??= []\n typesByQuerystring[query].push(id.name)\n }\n\n const queryReturnInterface = t.tsInterfaceDeclaration(\n SANITY_QUERIES,\n null,\n [],\n t.tsInterfaceBody(\n Object.entries(typesByQuerystring).map(([query, types]) => {\n return t.tsPropertySignature(\n t.stringLiteral(query),\n t.tsTypeAnnotation(\n t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type)))),\n ),\n )\n }),\n ),\n )\n\n // The registry lives on the global `SanityQueries` interface, which `@sanity/client`'s exported\n // `SanityQueries` inherits from. Registering globally needs no import of, and no module\n // resolution to, `@sanity/client`: the registrations are seen whether or not the client is a\n // direct dependency of this file, however many copies of it are installed, and from every entry\n // point including `@sanity/client/stega`.\n const globalRegistry = t.addComments(tsDeclareGlobal([queryReturnInterface]), 'leading', [\n {type: 'CommentLine', value: ' Query TypeMap'},\n ])\n\n // `@sanity/client` releases that predate the global registry only read their exported\n // `SanityQueries` interface. Interface merging unions the `extends` clauses of every\n // declaration, so adding the global interface as a base type makes those releases read the\n // registry above. Releases that already inherit the global see a duplicate `extends` of the\n // same type, which is accepted, so the same output works with either.\n // `SANITY_QUERIES` is already the registry's identifier and a node must not appear twice in one\n // tree, so the bridge mints its own.\n const bridge = t.addComments(\n tsDeclareModule('@sanity/client', [\n t.tsInterfaceDeclaration(\n t.identifier(SANITY_QUERIES.name),\n null,\n [\n t.tsExpressionWithTypeArguments(\n t.tsQualifiedName(t.identifier('globalThis'), t.identifier(SANITY_QUERIES.name)),\n ),\n ],\n t.tsInterfaceBody([]),\n ),\n ]),\n 'leading',\n [\n {\n type: 'CommentLine',\n value: ' Lets @sanity/client releases that predate the global registry read it too',\n },\n ],\n )\n\n const ast = t.program([globalRegistry, bridge])\n const code = generateCode(ast)\n return {ast, code}\n }\n\n async generateTypes(options: GenerateTypesOptions) {\n const {reporter: report} = options\n const internalReferenceSymbol = this.getInternalReferenceSymbolDeclaration()\n const schemaTypeGenerator = this.getSchemaTypeGenerator(options)\n const schemaTypeDeclarations = this.getSchemaTypeDeclarations(options)\n const allSanitySchemaTypesDeclaration = this.getAllSanitySchemaTypesDeclaration(options)\n\n report?.event.generatedSchemaTypes({\n allSanitySchemaTypesDeclaration,\n internalReferenceSymbol,\n schemaTypeDeclarations,\n })\n\n // Queries can produce `inline` type nodes that the schema-side generator\n // never sees (e.g. filtering a tagged-union array down to its inline\n // members). Evaluate modules before deciding whether the ArrayOf helper is\n // needed, so query-only usage still triggers the declaration.\n const evaluatedModules = await TypeGenerator.getEvaluatedModules({\n ...options,\n schemaTypeDeclarations,\n schemaTypeGenerator,\n })\n\n const program = t.program([])\n let code = ''\n\n program.body.push(internalReferenceSymbol.ast)\n code += internalReferenceSymbol.code\n\n if (schemaTypeGenerator.isArrayOfUsed()) {\n const arrayOfDeclaration = this.getArrayOfDeclaration()\n program.body.push(arrayOfDeclaration.ast)\n code += arrayOfDeclaration.code\n }\n\n for (const declaration of schemaTypeDeclarations) {\n program.body.push(declaration.ast)\n code += declaration.code\n }\n\n program.body.push(allSanitySchemaTypesDeclaration.ast)\n code += allSanitySchemaTypesDeclaration.code\n\n for (const {queries} of evaluatedModules) {\n for (const query of queries) {\n program.body.push(query.ast)\n code += query.code\n }\n }\n\n const queryMapDeclaration = await TypeGenerator.getQueryMapDeclaration({\n ...options,\n evaluatedModules,\n })\n program.body.push(...queryMapDeclaration.ast.body)\n code += queryMapDeclaration.code\n\n report?.event.generatedQueryTypes({queryMapDeclaration})\n\n return {ast: program, code}\n }\n}\n"],"names":["process","t","createSelector","resultSuffix","ALL_SANITY_SCHEMA_TYPES","ARRAY_OF","INTERNAL_REFERENCE_SYMBOL","SANITY_QUERIES","computeOnce","generateCode","getUniqueIdentifierForName","normalizePrintablePath","tsDeclareGlobal","tsDeclareModule","SchemaTypeGenerator","QueryEvaluationError","TypeGenerator","getSchemaTypeGenerator","options","schema","getSchemaTypeDeclarations","root","schemaPath","cwd","map","id","name","tsType","index","typeAlias","tsTypeAliasDeclaration","ast","exportNamedDeclaration","addComments","type","value","code","getAllSanitySchemaTypesDeclaration","schemaTypes","length","tsUnionType","tsTypeReference","tsNeverKeyword","getArrayOfDeclaration","typeParam","tsTypeParameter","intersectionType","tsIntersectionType","identifier","tsTypeLiteral","tsPropertySignature","tsTypeAnnotation","tsStringKeyword","arrayType","tsTypeParameterInstantiation","tsTypeParameterDeclaration","getInternalReferenceSymbolDeclaration","typeOperator","tsTypeOperator","tsSymbolKeyword","typeAnnotation","declaration","variableDeclaration","variableDeclarator","declare","getEvaluatedModules","queries","extractedModules","reporter","report","schemaTypeDeclarations","schemaTypeGenerator","stream","evaluatedModules","end","currentIdentifiers","Set","evaluatedModuleResults","filename","extractedModule","errors","extractedQuery","variable","stats","evaluateQuery","trimmedQuery","query","replaceAll","trim","evaluatedQueryResult","add","push","cause","evaluatedModule","emit","getQueryMapDeclaration","overloadClientMethods","program","flatMap","module","typesByQuerystring","queryReturnInterface","tsInterfaceDeclaration","tsInterfaceBody","Object","entries","types","stringLiteral","globalRegistry","bridge","tsExpressionWithTypeArguments","tsQualifiedName","generateTypes","internalReferenceSymbol","allSanitySchemaTypesDeclaration","event","generatedSchemaTypes","body","isArrayOfUsed","arrayOfDeclaration","query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BAAsB,CAAC;YACrE,GAAG7E,OAAO;YACVuD;QACF;QACAwB,QAAQoB,IAAI,CAAC1B,IAAI,IAAI6B,oBAAoBzF,GAAG,CAACsF,IAAI;QACjDjF,QAAQoF,oBAAoBpF,IAAI;QAEhCiC,QAAQ8C,MAAMM,oBAAoB;YAACD;QAAmB;QAEtD,OAAO;YAACzF,KAAKkE;YAAS7D;QAAI;IAC5B;AACF"}
1
+ {"version":3,"sources":["../../src/typescript/typeGenerator.ts"],"sourcesContent":["/* eslint-disable unicorn/consistent-function-scoping */\nimport process from 'node:process'\n\nimport * as t from '@babel/types'\nimport {type WorkerChannel, type WorkerChannelReporter} from '@sanity/worker-channels'\nimport {type SchemaType} from 'groq-js'\nimport {createSelector} from 'reselect'\n\nimport {resultSuffix} from '../casing.js'\nimport {\n ALL_SANITY_SCHEMA_TYPES,\n ARRAY_OF,\n INTERNAL_REFERENCE_SYMBOL,\n SANITY_PROJECTIONS_BY_RESOURCE,\n SANITY_QUERIES,\n SANITY_QUERIES_BY_RESOURCE,\n SANITY_SCHEMAS_BY_RESOURCE,\n} from './constants.js'\nimport {\n computeOnce,\n generateCode,\n getUniqueIdentifierForName,\n normalizePrintablePath,\n tsDeclareGlobal,\n tsDeclareModule,\n} from './helpers.js'\nimport {SchemaTypeGenerator} from './schemaTypeGenerator.js'\nimport {\n type EvaluatedModule,\n type EvaluatedProjection,\n type EvaluatedQuery,\n type ExtractedModule,\n type ExtractedProjection,\n QueryEvaluationError,\n type QueryExtractionError,\n type TypeEvaluationStats,\n} from './types.js'\n\n/** @public */\nexport type TypegenWorkerChannel = WorkerChannel.Definition<{\n evaluatedModules: WorkerChannel.Stream<EvaluatedModule>\n generatedQueryTypes: WorkerChannel.Event<{\n queryMapDeclaration: {ast: t.Program; code: string}\n }>\n generatedSchemaTypes: WorkerChannel.Event<{\n allSanitySchemaTypesDeclaration: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n }\n internalReferenceSymbol: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n }\n schemaTypeDeclarations: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n name: string\n tsType: t.TSType\n }[]\n }>\n}>\n\n/**\n * The project and dataset a schema belongs to.\n * @beta\n */\nexport interface TypegenResource {\n dataset: string\n projectId: string\n}\n\n/** @public */\nexport interface GenerateTypesOptions {\n schema: SchemaType\n\n /**\n * Generate the client's flat `SanityQueries` map, which types `client.fetch`. Independent of\n * `resource`. When an app generates types for more than one resource into one TypeScript\n * program, set this to `false` for all of them: each file would declare the same query text\n * in the flat map with a different type, and TypeScript rejects that merge.\n */\n overloadClientMethods?: boolean\n queries?: AsyncIterable<ExtractedModule>\n reporter?: WorkerChannelReporter<TypegenWorkerChannel>\n /**\n * Also register the schema and query result types under this project and dataset, so one\n * app can read more than one dataset and resolve the same query text to a different type for\n * each. Types go into the global `SanitySchemasByResource` and `SanityQueriesByResource`\n * interfaces that `@sanity/client` 8.7.0 and later declare, keyed `projectId.dataset`, the\n * same string the App SDK uses for its runtime cache.\n *\n * The registration is a plain global declaration and never resolves `@sanity/client`, so it\n * works when the client is only a dependency of another package, as with the App SDK under\n * pnpm. The flat map's bridge does resolve it, so in that layout also set\n * `overloadClientMethods: false`. Generate one file per resource per TypeScript program: two\n * files registering the same resource conflict.\n * @beta\n */\n resource?: TypegenResource\n root?: string\n schemaPath?: string\n}\n\ntype GetEvaluatedModulesOptions = GenerateTypesOptions & {\n schemaTypeDeclarations: ReturnType<TypeGenerator['getSchemaTypeDeclarations']>\n schemaTypeGenerator: SchemaTypeGenerator\n}\ntype GetQueryMapDeclarationOptions = GenerateTypesOptions & {\n evaluatedModules: EvaluatedModule[]\n}\n\n/**\n * A class used to generate TypeScript types from a given schema\n * @beta\n */\nexport class TypeGenerator {\n private getSchemaTypeGenerator = createSelector(\n [(options: GenerateTypesOptions) => options.schema],\n\n (schema) => new SchemaTypeGenerator(schema),\n )\n\n private getSchemaTypeDeclarations = createSelector(\n [\n (options: GenerateTypesOptions) => options.root,\n (options: GenerateTypesOptions) => options.schemaPath,\n this.getSchemaTypeGenerator,\n ],\n\n (root = process.cwd(), schemaPath, schema) =>\n [...schema].map(({id, name, tsType}, index) => {\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n let ast = t.exportNamedDeclaration(typeAlias)\n\n if (index === 0 && schemaPath) {\n ast = t.addComments(ast, 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePrintablePath(root, schemaPath)}`},\n ])\n }\n const code = generateCode(ast)\n return {ast, code, id, name, tsType}\n }),\n )\n\n private getAllSanitySchemaTypesDeclaration = createSelector(\n [this.getSchemaTypeDeclarations],\n (schemaTypes) => {\n const ast = t.exportNamedDeclaration(\n t.tsTypeAliasDeclaration(\n ALL_SANITY_SCHEMA_TYPES,\n null,\n schemaTypes.length > 0\n ? t.tsUnionType(schemaTypes.map(({id}) => t.tsTypeReference(id)))\n : t.tsNeverKeyword(),\n ),\n )\n const code = generateCode(ast)\n\n return {ast, code, id: ALL_SANITY_SCHEMA_TYPES}\n },\n )\n\n private getArrayOfDeclaration = computeOnce(() => {\n // Creates: type ArrayOf<T> = Array<T & { _key: string }>;\n const typeParam = t.tsTypeParameter(null, null, 'T')\n const intersectionType = t.tsIntersectionType([\n t.tsTypeReference(t.identifier('T')),\n t.tsTypeLiteral([\n t.tsPropertySignature(t.identifier('_key'), t.tsTypeAnnotation(t.tsStringKeyword())),\n ]),\n ])\n const arrayType = t.tsTypeReference(\n t.identifier('Array'),\n t.tsTypeParameterInstantiation([intersectionType]),\n )\n\n const ast = t.tsTypeAliasDeclaration(\n ARRAY_OF,\n t.tsTypeParameterDeclaration([typeParam]),\n arrayType,\n )\n const code = generateCode(ast)\n\n return {ast, code, id: ARRAY_OF}\n })\n\n private getInternalReferenceSymbolDeclaration = computeOnce(() => {\n const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword(), 'unique')\n\n const id = INTERNAL_REFERENCE_SYMBOL\n id.typeAnnotation = t.tsTypeAnnotation(typeOperator)\n\n const declaration = t.variableDeclaration('const', [t.variableDeclarator(id)])\n declaration.declare = true\n const ast = t.exportNamedDeclaration(declaration)\n const code = generateCode(ast)\n\n return {ast, code, id}\n })\n\n /**\n * Evaluates a projection against its document type, or against every document type when it\n * names none. Document types with the same result share one group, so a projection that does\n * not apply to most types does not repeat the same type once per document type.\n *\n * Returns `undefined` for a document type this schema does not have when generating for a\n * resource: datasets of one app can scan the same files, and the type can belong to another.\n */\n private static evaluateProjection({\n extractedProjection,\n filename,\n resource,\n schemaTypeGenerator,\n }: {\n extractedProjection: ExtractedProjection\n filename: string\n resource: TypegenResource | undefined\n schemaTypeGenerator: SchemaTypeGenerator\n }): UnnamedProjection | undefined {\n const {documentType, projection} = extractedProjection\n const documentTypeNames = schemaTypeGenerator.documentTypeNames()\n // Without this, an unknown or non-document type evaluates to `null` and is registered as if\n // it were a result. An object type is a mistake in any run.\n if (documentType !== undefined && !documentTypeNames.includes(documentType)) {\n if (resource && !schemaTypeGenerator.hasType(documentType)) return undefined\n throw new Error(`\"${documentType}\" is not a document type in the schema`)\n }\n const documentTypes = documentType === undefined ? documentTypeNames : [documentType]\n\n const groups = new Map<string, {documentTypes: string[]; tsType: t.TSType}>()\n const stats = {allTypes: 0, emptyUnions: 0, unknownTypes: 0}\n for (const type of documentTypes) {\n const result = schemaTypeGenerator.evaluateProjection({documentType: type, projection})\n const key = generateCode(result.tsType)\n const group = groups.get(key)\n if (group) {\n group.documentTypes.push(type)\n continue\n }\n groups.set(key, {documentTypes: [type], tsType: result.tsType})\n stats.allTypes += result.stats.allTypes\n stats.emptyUnions += result.stats.emptyUnions\n stats.unknownTypes += result.stats.unknownTypes\n }\n\n return {extractedProjection, filename, groups: [...groups.values()], stats}\n }\n\n private static async getEvaluatedModules({\n queries: extractedModules,\n reporter: report,\n resource,\n root = process.cwd(),\n schemaTypeDeclarations,\n schemaTypeGenerator,\n }: GetEvaluatedModulesOptions) {\n if (!extractedModules) {\n report?.stream.evaluatedModules.end()\n return []\n }\n\n const currentIdentifiers = new Set<string>(schemaTypeDeclarations.map(({id}) => id.name))\n const evaluatedModuleResults: EvaluatedModule[] = []\n const unnamedProjectionsByModule = new Map<EvaluatedModule, UnnamedProjection[]>()\n\n for await (const {filename, ...extractedModule} of extractedModules) {\n const queries: EvaluatedQuery[] = []\n const errors: (QueryEvaluationError | QueryExtractionError)[] = [...extractedModule.errors]\n\n for (const extractedQuery of extractedModule.queries) {\n const {variable} = extractedQuery\n try {\n const {stats, tsType} = schemaTypeGenerator.evaluateQuery(extractedQuery)\n const id = getUniqueIdentifierForName(resultSuffix(variable.id.name), currentIdentifiers)\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n const trimmedQuery = extractedQuery.query.replaceAll(/(\\r\\n|\\n|\\r)/gm, '').trim()\n const ast = t.addComments(t.exportNamedDeclaration(typeAlias), 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePrintablePath(root, filename)}`},\n {type: 'CommentLine', value: ` Variable: ${variable.id.name}`},\n {type: 'CommentLine', value: ` Query: ${trimmedQuery}`},\n ])\n\n const evaluatedQueryResult: EvaluatedQuery = {\n ast,\n code: generateCode(ast),\n id,\n stats,\n tsType,\n ...extractedQuery,\n }\n\n currentIdentifiers.add(id.name)\n queries.push(evaluatedQueryResult)\n } catch (cause) {\n errors.push(new QueryEvaluationError({cause, filename, variable}))\n }\n }\n\n const unnamedProjections: UnnamedProjection[] = []\n for (const extractedProjection of extractedModule.projections ?? []) {\n const {variable} = extractedProjection\n try {\n const unnamedProjection = TypeGenerator.evaluateProjection({\n extractedProjection,\n filename,\n resource,\n schemaTypeGenerator,\n })\n if (unnamedProjection) unnamedProjections.push(unnamedProjection)\n } catch (cause) {\n errors.push(new QueryEvaluationError({cause, filename, variable}))\n }\n }\n\n // Streamed without projections, which are named once every file has been read.\n const evaluatedModule: EvaluatedModule = {errors, filename, queries}\n report?.stream.evaluatedModules.emit(evaluatedModule)\n evaluatedModuleResults.push(evaluatedModule)\n unnamedProjectionsByModule.set(evaluatedModule, unnamedProjections)\n }\n report?.stream.evaluatedModules.end()\n\n // Projections are named after every query, so a query result keeps the name it had before\n // projections were generated, whatever the file order. A projection sharing a query's\n // variable name gets the numeric suffix instead.\n for (const [evaluatedModule, unnamedProjections] of unnamedProjectionsByModule) {\n evaluatedModule.projections = unnamedProjections.map((unnamedProjection) =>\n TypeGenerator.nameProjection({currentIdentifiers, root, unnamedProjection}),\n )\n }\n\n return evaluatedModuleResults\n }\n\n /**\n * One property per document type, each holding one property per distinct projection string,\n * typed as the union of every result alias generated for that pair.\n */\n private static getProjectionResultProperties(evaluatedModules: EvaluatedModule[]) {\n const typesByDocumentType: {[documentType: string]: {[projection: string]: string[]}} = {}\n for (const {projections = []} of evaluatedModules) {\n for (const {projection, resultsByDocumentType} of projections) {\n for (const [documentType, id] of Object.entries(resultsByDocumentType)) {\n typesByDocumentType[documentType] ??= {}\n typesByDocumentType[documentType][projection] ??= []\n typesByDocumentType[documentType][projection].push(id.name)\n }\n }\n }\n\n return Object.entries(typesByDocumentType).map(([documentType, typesByProjection]) =>\n t.tsPropertySignature(\n t.stringLiteral(documentType),\n t.tsTypeAnnotation(\n t.tsTypeLiteral(\n Object.entries(typesByProjection).map(([projection, types]) =>\n t.tsPropertySignature(\n t.stringLiteral(projection),\n t.tsTypeAnnotation(\n t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type)))),\n ),\n ),\n ),\n ),\n ),\n ),\n )\n }\n\n private static async getQueryMapDeclaration({\n evaluatedModules,\n overloadClientMethods = true,\n }: GetQueryMapDeclarationOptions) {\n if (!overloadClientMethods) return {ast: t.program([]), code: ''}\n\n const properties = TypeGenerator.getQueryResultProperties(evaluatedModules)\n if (properties.length === 0) return {ast: t.program([]), code: ''}\n\n const queryReturnInterface = t.tsInterfaceDeclaration(\n SANITY_QUERIES,\n null,\n [],\n t.tsInterfaceBody(properties),\n )\n\n const globalRegistry = t.addComments(tsDeclareGlobal([queryReturnInterface]), 'leading', [\n {type: 'CommentLine', value: ' Query TypeMap'},\n ])\n\n // The client-side global registry: https://github.com/sanity-io/client/pull/1319 (8.x) and\n // https://github.com/sanity-io/client/pull/1320 (7.x)\n const bridge = t.addComments(\n tsDeclareModule('@sanity/client', [\n t.tsInterfaceDeclaration(\n SANITY_QUERIES,\n null,\n [\n t.tsExpressionWithTypeArguments(\n t.tsQualifiedName(t.identifier('globalThis'), SANITY_QUERIES),\n ),\n ],\n t.tsInterfaceBody([]),\n ),\n ]),\n 'leading',\n [\n {\n type: 'CommentLine',\n value: ' Lets @sanity/client releases that predate the global registry read it too',\n },\n ],\n )\n\n const ast = t.program([globalRegistry, bridge])\n const code = generateCode(ast)\n return {ast, code}\n }\n\n /**\n * One property per distinct query string, typed as the union of every result type generated\n * for it. Two variables holding the same query text share a key.\n */\n private static getQueryResultProperties(evaluatedModules: EvaluatedModule[]) {\n const typesByQuerystring: {[query: string]: string[]} = {}\n for (const {queries} of evaluatedModules) {\n for (const {id, query} of queries) {\n typesByQuerystring[query] ??= []\n typesByQuerystring[query].push(id.name)\n }\n }\n\n return Object.entries(typesByQuerystring).map(([query, types]) =>\n t.tsPropertySignature(\n t.stringLiteral(query),\n t.tsTypeAnnotation(\n t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type)))),\n ),\n ),\n )\n }\n\n private static getResourceRegistryDeclaration({\n evaluatedModules,\n resource,\n }: GetQueryMapDeclarationOptions & {resource: TypegenResource}) {\n const key = `${resource.projectId}.${resource.dataset}`\n\n const schemas = t.tsInterfaceDeclaration(\n SANITY_SCHEMAS_BY_RESOURCE,\n null,\n [],\n t.tsInterfaceBody([\n t.tsPropertySignature(\n t.stringLiteral(key),\n t.tsTypeAnnotation(t.tsTypeReference(ALL_SANITY_SCHEMA_TYPES)),\n ),\n ]),\n )\n\n // Written even with no queries, and the projection entry below even with no projections. An\n // entry, empty or not, tells consumers this resource is generated, so a query or projection\n // missing from it is a miss rather than a reason to fall back.\n const queries = t.tsInterfaceDeclaration(\n SANITY_QUERIES_BY_RESOURCE,\n null,\n [],\n t.tsInterfaceBody([\n t.tsPropertySignature(\n t.stringLiteral(key),\n t.tsTypeAnnotation(\n t.tsTypeLiteral(TypeGenerator.getQueryResultProperties(evaluatedModules)),\n ),\n ),\n ]),\n )\n\n const projections = t.tsInterfaceDeclaration(\n SANITY_PROJECTIONS_BY_RESOURCE,\n null,\n [],\n t.tsInterfaceBody([\n t.tsPropertySignature(\n t.stringLiteral(key),\n t.tsTypeAnnotation(\n t.tsTypeLiteral(TypeGenerator.getProjectionResultProperties(evaluatedModules)),\n ),\n ),\n ]),\n )\n\n // No `declare module \"@sanity/client\"` bridge, unlike the flat map. These registries first\n // shipped already global, so no client release needs one, and an augmentation would fail\n // with TS2664 wherever `@sanity/client` is not resolvable from the generated file.\n const ast = t.program([\n t.addComments(tsDeclareGlobal([schemas, queries, projections]), 'leading', [\n {type: 'CommentLine', value: ` Resource TypeMap: ${key}`},\n ]),\n ])\n const code = generateCode(ast)\n return {ast, code}\n }\n\n /** Declares one result alias per group, with names not yet in `currentIdentifiers`. */\n private static nameProjection({\n currentIdentifiers,\n root,\n unnamedProjection: {extractedProjection, filename, groups, stats},\n }: {\n currentIdentifiers: Set<string>\n root: string\n unnamedProjection: UnnamedProjection\n }): EvaluatedProjection {\n const {projection, variable} = extractedProjection\n const trimmedProjection = projection.replaceAll(/(\\r\\n|\\n|\\r)/gm, '').trim()\n const declarations: EvaluatedProjection['declarations'] = []\n const resultsByDocumentType: EvaluatedProjection['resultsByDocumentType'] = {}\n for (const group of groups) {\n const name =\n groups.length === 1\n ? variable.id.name\n : `${variable.id.name}${pascalCase(group.documentTypes[0]!)}`\n const id = getUniqueIdentifierForName(resultSuffix(name), currentIdentifiers)\n currentIdentifiers.add(id.name)\n const ast = t.addComments(\n t.exportNamedDeclaration(t.tsTypeAliasDeclaration(id, null, group.tsType)),\n 'leading',\n [\n {type: 'CommentLine', value: ` Source: ${normalizePrintablePath(root, filename)}`},\n {type: 'CommentLine', value: ` Variable: ${variable.id.name}`},\n {\n type: 'CommentLine',\n value: ` Projection on ${group.documentTypes.join(', ')}: ${trimmedProjection}`,\n },\n ],\n )\n declarations.push({ast, code: generateCode(ast), id})\n for (const type of group.documentTypes) resultsByDocumentType[type] = id\n }\n\n return {...extractedProjection, declarations, resultsByDocumentType, stats}\n }\n\n async generateTypes(options: GenerateTypesOptions) {\n if (options.resource && (!options.resource.projectId || !options.resource.dataset)) {\n throw new TypeError('A typegen resource needs both a projectId and a dataset')\n }\n\n const {reporter: report} = options\n const internalReferenceSymbol = this.getInternalReferenceSymbolDeclaration()\n const schemaTypeGenerator = this.getSchemaTypeGenerator(options)\n const schemaTypeDeclarations = this.getSchemaTypeDeclarations(options)\n const allSanitySchemaTypesDeclaration = this.getAllSanitySchemaTypesDeclaration(options)\n\n report?.event.generatedSchemaTypes({\n allSanitySchemaTypesDeclaration,\n internalReferenceSymbol,\n schemaTypeDeclarations,\n })\n\n // Queries can produce `inline` type nodes that the schema-side generator\n // never sees (e.g. filtering a tagged-union array down to its inline\n // members). Evaluate modules before deciding whether the ArrayOf helper is\n // needed, so query-only usage still triggers the declaration.\n const evaluatedModules = await TypeGenerator.getEvaluatedModules({\n ...options,\n schemaTypeDeclarations,\n schemaTypeGenerator,\n })\n\n const program = t.program([])\n let code = ''\n\n program.body.push(internalReferenceSymbol.ast)\n code += internalReferenceSymbol.code\n\n if (schemaTypeGenerator.isArrayOfUsed()) {\n const arrayOfDeclaration = this.getArrayOfDeclaration()\n program.body.push(arrayOfDeclaration.ast)\n code += arrayOfDeclaration.code\n }\n\n for (const declaration of schemaTypeDeclarations) {\n program.body.push(declaration.ast)\n code += declaration.code\n }\n\n program.body.push(allSanitySchemaTypesDeclaration.ast)\n code += allSanitySchemaTypesDeclaration.code\n\n for (const {queries} of evaluatedModules) {\n for (const query of queries) {\n program.body.push(query.ast)\n code += query.code\n }\n }\n\n for (const {projections = []} of evaluatedModules) {\n for (const {declarations} of projections) {\n for (const declaration of declarations) {\n program.body.push(declaration.ast)\n code += declaration.code\n }\n }\n }\n\n const queryMapDeclaration = await TypeGenerator.getQueryMapDeclaration({\n ...options,\n evaluatedModules,\n })\n program.body.push(...queryMapDeclaration.ast.body)\n code += queryMapDeclaration.code\n\n if (options.resource) {\n const resourceRegistry = TypeGenerator.getResourceRegistryDeclaration({\n ...options,\n evaluatedModules,\n resource: options.resource,\n })\n program.body.push(...resourceRegistry.ast.body)\n code += resourceRegistry.code\n }\n\n report?.event.generatedQueryTypes({queryMapDeclaration})\n\n return {ast: program, code}\n }\n}\n\n/** A projection's result types, grouped by document type, before they are given names. */\ninterface UnnamedProjection {\n extractedProjection: ExtractedProjection\n filename: string\n groups: {documentTypes: string[]; tsType: t.TSType}[]\n stats: TypeEvaluationStats\n}\n\n/** `sanity.imageAsset` to `SanityImageAsset`, for naming a result alias after a document type. */\nfunction pascalCase(value: string): string {\n return value\n .split(/[^A-Za-z0-9]+/)\n .filter(Boolean)\n .map((part) => part[0]!.toUpperCase() + part.slice(1))\n .join('')\n}\n"],"names":["process","t","createSelector","resultSuffix","ALL_SANITY_SCHEMA_TYPES","ARRAY_OF","INTERNAL_REFERENCE_SYMBOL","SANITY_PROJECTIONS_BY_RESOURCE","SANITY_QUERIES","SANITY_QUERIES_BY_RESOURCE","SANITY_SCHEMAS_BY_RESOURCE","computeOnce","generateCode","getUniqueIdentifierForName","normalizePrintablePath","tsDeclareGlobal","tsDeclareModule","SchemaTypeGenerator","QueryEvaluationError","TypeGenerator","getSchemaTypeGenerator","options","schema","getSchemaTypeDeclarations","root","schemaPath","cwd","map","id","name","tsType","index","typeAlias","tsTypeAliasDeclaration","ast","exportNamedDeclaration","addComments","type","value","code","getAllSanitySchemaTypesDeclaration","schemaTypes","length","tsUnionType","tsTypeReference","tsNeverKeyword","getArrayOfDeclaration","typeParam","tsTypeParameter","intersectionType","tsIntersectionType","identifier","tsTypeLiteral","tsPropertySignature","tsTypeAnnotation","tsStringKeyword","arrayType","tsTypeParameterInstantiation","tsTypeParameterDeclaration","getInternalReferenceSymbolDeclaration","typeOperator","tsTypeOperator","tsSymbolKeyword","typeAnnotation","declaration","variableDeclaration","variableDeclarator","declare","evaluateProjection","extractedProjection","filename","resource","schemaTypeGenerator","documentType","projection","documentTypeNames","undefined","includes","hasType","Error","documentTypes","groups","Map","stats","allTypes","emptyUnions","unknownTypes","result","key","group","get","push","set","values","getEvaluatedModules","queries","extractedModules","reporter","report","schemaTypeDeclarations","stream","evaluatedModules","end","currentIdentifiers","Set","evaluatedModuleResults","unnamedProjectionsByModule","extractedModule","errors","extractedQuery","variable","evaluateQuery","trimmedQuery","query","replaceAll","trim","evaluatedQueryResult","add","cause","unnamedProjections","projections","unnamedProjection","evaluatedModule","emit","nameProjection","getProjectionResultProperties","typesByDocumentType","resultsByDocumentType","Object","entries","typesByProjection","stringLiteral","types","getQueryMapDeclaration","overloadClientMethods","program","properties","getQueryResultProperties","queryReturnInterface","tsInterfaceDeclaration","tsInterfaceBody","globalRegistry","bridge","tsExpressionWithTypeArguments","tsQualifiedName","typesByQuerystring","getResourceRegistryDeclaration","projectId","dataset","schemas","trimmedProjection","declarations","pascalCase","join","generateTypes","TypeError","internalReferenceSymbol","allSanitySchemaTypesDeclaration","event","generatedSchemaTypes","body","isArrayOfUsed","arrayOfDeclaration","queryMapDeclaration","resourceRegistry","generatedQueryTypes","split","filter","Boolean","part","toUpperCase","slice"],"mappings":"AAAA,sDAAsD,GACtD,OAAOA,aAAa,eAAc;AAElC,YAAYC,OAAO,eAAc;AAGjC,SAAQC,cAAc,QAAO,WAAU;AAEvC,SAAQC,YAAY,QAAO,eAAc;AACzC,SACEC,uBAAuB,EACvBC,QAAQ,EACRC,yBAAyB,EACzBC,8BAA8B,EAC9BC,cAAc,EACdC,0BAA0B,EAC1BC,0BAA0B,QACrB,iBAAgB;AACvB,SACEC,WAAW,EACXC,YAAY,EACZC,0BAA0B,EAC1BC,sBAAsB,EACtBC,eAAe,EACfC,eAAe,QACV,eAAc;AACrB,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"sources":["../../src/typescript/types.ts"],"sourcesContent":["import type * as t from '@babel/types'\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n (typeof value === 'object' || typeof value === 'function') && !!value\n\n/**\n * Statistics from the query type evaluation process.\n * @public\n */\nexport interface TypeEvaluationStats {\n allTypes: number\n emptyUnions: number\n unknownTypes: number\n}\n\ninterface QueryVariable {\n id: t.Identifier\n\n end?: number\n start?: number\n}\n\n/**\n * A GROQ query extracted from a source file.\n * @public\n */\nexport interface ExtractedQuery {\n filename: string\n query: string\n variable: QueryVariable\n}\n\n/**\n * A module (file) containing extracted GROQ queries.\n * @public\n */\nexport interface ExtractedModule {\n errors: QueryExtractionError[]\n filename: string\n queries: ExtractedQuery[]\n}\n\n/**\n * An `ExtractedQuery` that has been evaluated against a schema, yielding a TypeScript type.\n * @public\n */\nexport interface EvaluatedQuery extends ExtractedQuery {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n stats: TypeEvaluationStats\n tsType: t.TSType\n}\n\n/**\n * A module containing queries that have been evaluated.\n * @public\n */\nexport interface EvaluatedModule {\n errors: (QueryEvaluationError | QueryExtractionError)[]\n filename: string\n queries: EvaluatedQuery[]\n}\n\ninterface QueryExtractionErrorOptions {\n cause: unknown\n filename: string\n\n variable?: QueryVariable\n}\n\n/**\n * An error that occurred during query extraction.\n * @public\n */\nexport class QueryExtractionError extends Error {\n filename: string\n variable?: QueryVariable\n constructor({cause, filename, variable}: QueryExtractionErrorOptions) {\n super(\n `Error while extracting query ${variable ? `from variable '${variable.id.name}' ` : ''}in ${filename}: ${\n isRecord(cause) && typeof cause.message === 'string' ? cause.message : 'Unknown error'\n }`,\n )\n this.name = 'QueryExtractionError'\n this.cause = cause\n this.variable = variable\n this.filename = filename\n }\n}\n\ninterface QueryEvaluationErrorOptions {\n cause: unknown\n filename: string\n\n variable?: QueryVariable\n}\n\n/**\n * An error that occurred during query evaluation.\n * @public\n */\nexport class QueryEvaluationError extends Error {\n filename: string\n variable?: QueryVariable\n constructor({cause, filename, variable}: QueryEvaluationErrorOptions) {\n super(\n `Error while evaluating query ${variable ? `from variable '${variable.id.name}' ` : ''}in ${filename}: ${\n isRecord(cause) && typeof cause.message === 'string' ? cause.message : 'Unknown error'\n }`,\n )\n this.name = 'QueryEvaluationError'\n this.cause = cause\n this.variable = variable\n this.filename = filename\n }\n}\n"],"names":["isRecord","value","QueryExtractionError","Error","filename","variable","cause","id","name","message","QueryEvaluationError"],"mappings":"AAEA,MAAMA,WAAW,CAACC,QAChB,AAAC,CAAA,OAAOA,UAAU,YAAY,OAAOA,UAAU,UAAS,KAAM,CAAC,CAACA;AAoElE;;;CAGC,GACD,OAAO,MAAMC,6BAA6BC;IACxCC,SAAgB;IAChBC,SAAwB;IACxB,YAAY,EAACC,KAAK,EAAEF,QAAQ,EAAEC,QAAQ,EAA8B,CAAE;QACpE,KAAK,CACH,CAAC,6BAA6B,EAAEA,WAAW,CAAC,eAAe,EAAEA,SAASE,EAAE,CAACC,IAAI,CAAC,EAAE,CAAC,GAAG,GAAG,GAAG,EAAEJ,SAAS,EAAE,EACrGJ,SAASM,UAAU,OAAOA,MAAMG,OAAO,KAAK,WAAWH,MAAMG,OAAO,GAAG,iBACvE;QAEJ,IAAI,CAACD,IAAI,GAAG;QACZ,IAAI,CAACF,KAAK,GAAGA;QACb,IAAI,CAACD,QAAQ,GAAGA;QAChB,IAAI,CAACD,QAAQ,GAAGA;IAClB;AACF;AASA;;;CAGC,GACD,OAAO,MAAMM,6BAA6BP;IACxCC,SAAgB;IAChBC,SAAwB;IACxB,YAAY,EAACC,KAAK,EAAEF,QAAQ,EAAEC,QAAQ,EAA8B,CAAE;QACpE,KAAK,CACH,CAAC,6BAA6B,EAAEA,WAAW,CAAC,eAAe,EAAEA,SAASE,EAAE,CAACC,IAAI,CAAC,EAAE,CAAC,GAAG,GAAG,GAAG,EAAEJ,SAAS,EAAE,EACrGJ,SAASM,UAAU,OAAOA,MAAMG,OAAO,KAAK,WAAWH,MAAMG,OAAO,GAAG,iBACvE;QAEJ,IAAI,CAACD,IAAI,GAAG;QACZ,IAAI,CAACF,KAAK,GAAGA;QACb,IAAI,CAACD,QAAQ,GAAGA;QAChB,IAAI,CAACD,QAAQ,GAAGA;IAClB;AACF"}
1
+ {"version":3,"sources":["../../src/typescript/types.ts"],"sourcesContent":["import type * as t from '@babel/types'\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n (typeof value === 'object' || typeof value === 'function') && !!value\n\n/**\n * Statistics from the query type evaluation process.\n * @public\n */\nexport interface TypeEvaluationStats {\n allTypes: number\n emptyUnions: number\n unknownTypes: number\n}\n\ninterface QueryVariable {\n id: t.Identifier\n\n end?: number\n start?: number\n}\n\n/**\n * A GROQ query extracted from a source file.\n * @public\n */\nexport interface ExtractedQuery {\n filename: string\n query: string\n variable: QueryVariable\n}\n\n/**\n * A projection extracted from a `defineProjection` call in a source file.\n * @beta\n */\nexport interface ExtractedProjection {\n filename: string\n /** The exact projection string, which is also its lookup key. */\n projection: string\n variable: QueryVariable\n\n /**\n * The document type the projection is written for, when passed as the first argument.\n * Without it, the projection is evaluated against every document type.\n */\n documentType?: string\n}\n\n/**\n * A module (file) containing extracted GROQ queries.\n * @public\n */\nexport interface ExtractedModule {\n errors: QueryExtractionError[]\n filename: string\n queries: ExtractedQuery[]\n\n /** @beta */\n projections?: ExtractedProjection[]\n}\n\n/**\n * An `ExtractedQuery` that has been evaluated against a schema, yielding a TypeScript type.\n * @public\n */\nexport interface EvaluatedQuery extends ExtractedQuery {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n stats: TypeEvaluationStats\n tsType: t.TSType\n}\n\n/**\n * An `ExtractedProjection` evaluated against the document types it applies to.\n * @beta\n */\nexport interface EvaluatedProjection extends ExtractedProjection {\n /** One result type alias per distinct result. */\n declarations: {ast: t.ExportNamedDeclaration; code: string; id: t.Identifier}[]\n /** The result alias for each document type the projection was evaluated against. */\n resultsByDocumentType: {[documentType: string]: t.Identifier}\n stats: TypeEvaluationStats\n}\n\n/**\n * A module containing queries that have been evaluated.\n * @public\n */\nexport interface EvaluatedModule {\n errors: (QueryEvaluationError | QueryExtractionError)[]\n filename: string\n queries: EvaluatedQuery[]\n\n /** @beta */\n projections?: EvaluatedProjection[]\n}\n\ninterface QueryExtractionErrorOptions {\n cause: unknown\n filename: string\n\n variable?: QueryVariable\n}\n\n/**\n * An error that occurred during query extraction.\n * @public\n */\nexport class QueryExtractionError extends Error {\n filename: string\n variable?: QueryVariable\n constructor({cause, filename, variable}: QueryExtractionErrorOptions) {\n super(\n `Error while extracting query ${variable ? `from variable '${variable.id.name}' ` : ''}in ${filename}: ${\n isRecord(cause) && typeof cause.message === 'string' ? cause.message : 'Unknown error'\n }`,\n )\n this.name = 'QueryExtractionError'\n this.cause = cause\n this.variable = variable\n this.filename = filename\n }\n}\n\ninterface QueryEvaluationErrorOptions {\n cause: unknown\n filename: string\n\n variable?: QueryVariable\n}\n\n/**\n * An error that occurred during query evaluation.\n * @public\n */\nexport class QueryEvaluationError extends Error {\n filename: string\n variable?: QueryVariable\n constructor({cause, filename, variable}: QueryEvaluationErrorOptions) {\n super(\n `Error while evaluating query ${variable ? `from variable '${variable.id.name}' ` : ''}in ${filename}: ${\n isRecord(cause) && typeof cause.message === 'string' ? cause.message : 'Unknown error'\n }`,\n )\n this.name = 'QueryEvaluationError'\n this.cause = cause\n this.variable = variable\n this.filename = filename\n }\n}\n"],"names":["isRecord","value","QueryExtractionError","Error","filename","variable","cause","id","name","message","QueryEvaluationError"],"mappings":"AAEA,MAAMA,WAAW,CAACC,QAChB,AAAC,CAAA,OAAOA,UAAU,YAAY,OAAOA,UAAU,UAAS,KAAM,CAAC,CAACA;AAuGlE;;;CAGC,GACD,OAAO,MAAMC,6BAA6BC;IACxCC,SAAgB;IAChBC,SAAwB;IACxB,YAAY,EAACC,KAAK,EAAEF,QAAQ,EAAEC,QAAQ,EAA8B,CAAE;QACpE,KAAK,CACH,CAAC,6BAA6B,EAAEA,WAAW,CAAC,eAAe,EAAEA,SAASE,EAAE,CAACC,IAAI,CAAC,EAAE,CAAC,GAAG,GAAG,GAAG,EAAEJ,SAAS,EAAE,EACrGJ,SAASM,UAAU,OAAOA,MAAMG,OAAO,KAAK,WAAWH,MAAMG,OAAO,GAAG,iBACvE;QAEJ,IAAI,CAACD,IAAI,GAAG;QACZ,IAAI,CAACF,KAAK,GAAGA;QACb,IAAI,CAACD,QAAQ,GAAGA;QAChB,IAAI,CAACD,QAAQ,GAAGA;IAClB;AACF;AASA;;;CAGC,GACD,OAAO,MAAMM,6BAA6BP;IACxCC,SAAgB;IAChBC,SAAwB;IACxB,YAAY,EAACC,KAAK,EAAEF,QAAQ,EAAEC,QAAQ,EAA8B,CAAE;QACpE,KAAK,CACH,CAAC,6BAA6B,EAAEA,WAAW,CAAC,eAAe,EAAEA,SAASE,EAAE,CAACC,IAAI,CAAC,EAAE,CAAC,GAAG,GAAG,GAAG,EAAEJ,SAAS,EAAE,EACrGJ,SAASM,UAAU,OAAOA,MAAMG,OAAO,KAAK,WAAWH,MAAMG,OAAO,GAAG,iBACvE;QAEJ,IAAI,CAACD,IAAI,GAAG;QACZ,IAAI,CAACF,KAAK,GAAGA;QACb,IAAI,CAACD,QAAQ,GAAGA;QAChB,IAAI,CAACD,QAAQ,GAAGA;IAClB;AACF"}
@@ -1,4 +1,4 @@
1
- import createDebug from 'debug';
1
+ import { createDebug } from 'obug';
2
2
  export const debug = createDebug('sanity:typegen:generate');
3
3
 
4
4
  //# sourceMappingURL=debug.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/debug.ts"],"sourcesContent":["import createDebug from 'debug'\n\nexport const debug = createDebug('sanity:typegen:generate')\n"],"names":["createDebug","debug"],"mappings":"AAAA,OAAOA,iBAAiB,QAAO;AAE/B,OAAO,MAAMC,QAAQD,YAAY,2BAA0B"}
1
+ {"version":3,"sources":["../../src/utils/debug.ts"],"sourcesContent":["import {createDebug} from 'obug'\n\nexport const debug = createDebug('sanity:typegen:generate')\n"],"names":["createDebug","debug"],"mappings":"AAAA,SAAQA,WAAW,QAAO,OAAM;AAEhC,OAAO,MAAMC,QAAQD,YAAY,2BAA0B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/codegen",
3
- "version": "8.1.0",
3
+ "version": "8.2.0",
4
4
  "description": "Codegen toolkit for Sanity.io",
5
5
  "keywords": [
6
6
  "sanity",
@@ -47,12 +47,12 @@
47
47
  "@sanity/telemetry": "^1.1.0",
48
48
  "@sanity/worker-channels": "^2.0.0",
49
49
  "chokidar": "^3.6.0",
50
- "debug": "^4.4.3",
51
50
  "globby": "^11.1.0",
52
51
  "groq": "^6.0.0",
53
52
  "groq-js": "^2.0.0",
54
53
  "json5": "^2.2.3",
55
54
  "lodash-es": "^4.18.1",
55
+ "obug": "^3.0.0",
56
56
  "prettier": "^3.8.3",
57
57
  "reselect": "^5.2.0",
58
58
  "tsconfig-paths": "^4.2.0",
@@ -70,7 +70,6 @@
70
70
  "@types/babel__generator": "^7.27.0",
71
71
  "@types/babel__register": "^7.17.3",
72
72
  "@types/babel__traverse": "^7.28.0",
73
- "@types/debug": "^4.1.13",
74
73
  "@types/lodash-es": "^4.17.12",
75
74
  "@types/node": "^24.13.3",
76
75
  "@vitest/coverage-istanbul": "^4.1.8",