@sanity/codegen 5.9.1 → 5.9.2

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.
@@ -16,6 +16,7 @@ export class SchemaTypeGenerator {
16
16
  tsType
17
17
  };
18
18
  });
19
+ arrayOfUsed = false;
19
20
  identifiers = new Map();
20
21
  tsTypes = new Map();
21
22
  constructor(schema){
@@ -50,6 +51,9 @@ export class SchemaTypeGenerator {
50
51
  hasType(typeName) {
51
52
  return this.tsTypes.has(typeName);
52
53
  }
54
+ isArrayOfUsed() {
55
+ return this.arrayOfUsed;
56
+ }
53
57
  *[Symbol.iterator]() {
54
58
  for (const { name } of this.schema){
55
59
  yield {
@@ -65,6 +69,7 @@ export class SchemaTypeGenerator {
65
69
  * Helper function used to generate TS types for arrays of inline types, or arrays of inline types
66
70
  * wrapped in the ArrayOf wrapper that adds _key prop
67
71
  */ generateArrayOfTsType(typeNode) {
72
+ this.arrayOfUsed = true;
68
73
  const typeNodes = this.generateTsType(typeNode.of);
69
74
  return t.tsTypeReference(ARRAY_OF, t.tsTypeParameterInstantiation([
70
75
  typeNodes
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/typescript/schemaTypeGenerator.ts"],"sourcesContent":["import * as t from '@babel/types'\nimport {\n type ArrayTypeNode,\n type DocumentSchemaType,\n type InlineTypeNode,\n type ObjectAttribute,\n type ObjectTypeNode,\n type SchemaType,\n type TypeDeclarationSchemaType,\n typeEvaluate,\n type TypeNode,\n type UnionTypeNode,\n} from 'groq-js'\n\nimport {safeParseQuery} from '../safeParseQuery.js'\nimport {ARRAY_OF, INTERNAL_REFERENCE_SYMBOL} from './constants.js'\nimport {\n getFilterArrayUnionType,\n getUniqueIdentifierForName,\n isIdentifierName,\n weakMapMemo,\n} from './helpers.js'\nimport {type ExtractedQuery, type TypeEvaluationStats} from './types.js'\n\nexport class SchemaTypeGenerator {\n public readonly schema: SchemaType\n evaluateQuery = weakMapMemo(\n // eslint-disable-next-line unicorn/consistent-function-scoping\n ({query}: Pick<ExtractedQuery, 'query'>): {stats: TypeEvaluationStats; tsType: t.TSType} => {\n const ast = safeParseQuery(query)\n const typeNode = typeEvaluate(ast, this.schema)\n const tsType = this.generateTsType(typeNode)\n const stats = walkAndCountQueryTypeNodeStats(typeNode)\n return {stats, tsType}\n },\n )\n private identifiers = new Map<string, t.Identifier>()\n\n private tsTypes = new Map<string, t.TSType>()\n\n constructor(schema: SchemaType) {\n this.schema = schema\n\n const uniqueTypeNames = new Set<string>()\n for (const type of schema) {\n if (uniqueTypeNames.has(type.name)) {\n throw new Error(\n `Duplicate type name \"${type.name}\" in schema. Type names must be unique within the same schema.`,\n )\n }\n uniqueTypeNames.add(type.name)\n }\n\n for (const type of schema) {\n const currentIdentifierNames = new Set([...this.identifiers.values()].map((id) => id.name))\n const uniqueIdentifier = getUniqueIdentifierForName(type.name, currentIdentifierNames)\n this.identifiers.set(type.name, uniqueIdentifier)\n }\n\n for (const type of schema) {\n this.tsTypes.set(type.name, this.generateTsType(type))\n }\n }\n\n getType(typeName: string): {id: t.Identifier; tsType: t.TSType} | undefined {\n const tsType = this.tsTypes.get(typeName)\n const id = this.identifiers.get(typeName)\n if (tsType && id) return {id, tsType}\n return undefined\n }\n\n hasType(typeName: string): boolean {\n return this.tsTypes.has(typeName)\n }\n\n *[Symbol.iterator]() {\n for (const {name} of this.schema) {\n yield {name, ...this.getType(name)!}\n }\n }\n\n typeNames(): string[] {\n return this.schema.map((schemaType) => schemaType.name)\n }\n\n /**\n * Helper function used to generate TS types for arrays of inline types, or arrays of inline types\n * wrapped in the ArrayOf wrapper that adds _key prop\n */\n private generateArrayOfTsType(typeNode: ArrayTypeNode): t.TSTypeReference {\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(ARRAY_OF, t.tsTypeParameterInstantiation([typeNodes]))\n }\n\n // Helper function used to generate TS types for array type nodes.\n private generateArrayTsType(typeNode: ArrayTypeNode): t.TSTypeReference | t.TSUnionType {\n // if it's an array of a single inline type, wrap it in ArrayOf\n if (typeNode.of.type === 'inline') {\n return this.generateArrayOfTsType(typeNode)\n }\n\n // if it's not an inline object and not a union, wrap in Array\n if (typeNode.of.type !== 'union') {\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(t.identifier('Array'), t.tsTypeParameterInstantiation([typeNodes]))\n }\n\n // if it's not a union type or all of the union type members are non-inlines, wrap type in Array\n if (typeNode.of.of.every((unionTypeNode) => unionTypeNode.type !== 'inline')) {\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(t.identifier('Array'), t.tsTypeParameterInstantiation([typeNodes]))\n }\n\n // all the union types nodes are inline\n if (typeNode.of.of.every((unionMember) => unionMember.type === 'inline')) {\n return this.generateArrayOfTsType(typeNode)\n }\n\n // some of the union types are inlines, while some are not - split and recurse\n const arrayOfNonInline = getFilterArrayUnionType(typeNode, (member) => member.type !== 'inline')\n const arrayOfInline = getFilterArrayUnionType(typeNode, (member) => member.type === 'inline')\n\n return t.tsUnionType([\n this.generateArrayTsType(arrayOfNonInline),\n this.generateArrayTsType(arrayOfInline),\n ])\n }\n\n // Helper function used to generate TS types for document type nodes.\n private generateDocumentTsType(document: DocumentSchemaType): t.TSType {\n const props = Object.entries(document.attributes).map(([key, node]) =>\n this.generateTsObjectProperty(key, node),\n )\n\n return t.tsTypeLiteral(props)\n }\n\n private generateInlineTsType(typeNode: InlineTypeNode): t.TSType {\n const id = this.identifiers.get(typeNode.name)\n if (!id) {\n // Not found in schema, return unknown type\n return t.addComment(\n t.tsUnknownKeyword(),\n 'trailing',\n ` Unable to locate the referenced type \"${typeNode.name}\" in schema`,\n true,\n )\n }\n\n return t.tsTypeReference(id)\n }\n\n // Helper function used to generate TS types for object type nodes.\n private generateObjectTsType(typeNode: ObjectTypeNode): t.TSType {\n const props: t.TSPropertySignature[] = []\n for (const [key, attribute] of Object.entries(typeNode.attributes)) {\n props.push(this.generateTsObjectProperty(key, attribute))\n }\n const rest = typeNode.rest\n\n if (rest) {\n switch (rest.type) {\n case 'inline': {\n const resolved = this.generateInlineTsType(rest)\n // if object rest is unknown, we can't generate a type literal for it\n if (t.isTSUnknownKeyword(resolved)) return resolved\n return t.tsIntersectionType([t.tsTypeLiteral(props), resolved])\n }\n case 'object': {\n for (const [key, attribute] of Object.entries(rest.attributes)) {\n props.push(this.generateTsObjectProperty(key, attribute))\n }\n break\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n default: {\n // @ts-expect-error This should never happen\n throw new Error(`Type \"${rest.type}\" not found in schema`)\n }\n }\n }\n\n if (typeNode.dereferencesTo) {\n const derefType = Object.assign(\n t.tsPropertySignature(\n INTERNAL_REFERENCE_SYMBOL,\n t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo))),\n ),\n {computed: true, optional: true},\n )\n props.push(derefType)\n }\n\n return t.tsTypeLiteral(props)\n }\n\n // Helper function used to generate TS types for object properties.\n private generateTsObjectProperty(key: string, attribute: ObjectAttribute): t.TSPropertySignature {\n const type = this.generateTsType(attribute.value)\n const keyNode = isIdentifierName(key) ? t.identifier(key) : t.stringLiteral(key)\n const propertySignature = t.tsPropertySignature(keyNode, t.tsTypeAnnotation(type))\n propertySignature.optional = attribute.optional\n\n return propertySignature\n }\n\n private generateTsType(\n typeNode: DocumentSchemaType | TypeDeclarationSchemaType | TypeNode,\n ): t.TSType {\n switch (typeNode.type) {\n case 'array': {\n return this.generateArrayTsType(typeNode)\n }\n case 'boolean': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.booleanLiteral(typeNode.value))\n }\n return t.tsBooleanKeyword()\n }\n case 'document': {\n return this.generateDocumentTsType(typeNode)\n }\n case 'inline': {\n return this.generateInlineTsType(typeNode)\n }\n case 'null': {\n return t.tsNullKeyword()\n }\n case 'number': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.numericLiteral(typeNode.value))\n }\n return t.tsNumberKeyword()\n }\n case 'object': {\n return this.generateObjectTsType(typeNode)\n }\n case 'string': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.stringLiteral(typeNode.value))\n }\n return t.tsStringKeyword()\n }\n case 'type': {\n return this.generateTsType(typeNode.value)\n }\n case 'union': {\n return this.generateUnionTsType(typeNode)\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n\n default: {\n throw new Error(\n `Encountered unsupported node type \"${\n // @ts-expect-error This should never happen\n typeNode.type\n }\" while generating schema types`,\n )\n }\n }\n }\n\n // Helper function used to generate TS types for union type nodes.\n private generateUnionTsType(typeNode: UnionTypeNode): t.TSType {\n if (typeNode.of.length === 0) return t.tsNeverKeyword()\n if (typeNode.of.length === 1) return this.generateTsType(typeNode.of[0]!)\n return t.tsUnionType(typeNode.of.map((node) => this.generateTsType(node)))\n }\n}\n\nexport function walkAndCountQueryTypeNodeStats(typeNode: TypeNode): TypeEvaluationStats {\n switch (typeNode.type) {\n case 'array': {\n const acc = walkAndCountQueryTypeNodeStats(typeNode.of)\n acc.allTypes += 1 // count the array type itself\n return acc\n }\n case 'object': {\n // if the rest is unknown, we count it as one unknown type\n if (typeNode.rest && typeNode.rest.type === 'unknown') {\n return {allTypes: 2, emptyUnions: 0, unknownTypes: 1} // count the object type itself as well\n }\n\n const restStats = typeNode.rest\n ? walkAndCountQueryTypeNodeStats(typeNode.rest)\n : {allTypes: 0, emptyUnions: 0, unknownTypes: 0}\n\n // count the object type itself\n restStats.allTypes += 1\n\n const attrs = Object.values(typeNode.attributes)\n let acc = restStats\n for (const attribute of attrs) {\n const {allTypes, emptyUnions, unknownTypes} = walkAndCountQueryTypeNodeStats(\n attribute.value,\n )\n acc = {\n allTypes: acc.allTypes + allTypes,\n emptyUnions: acc.emptyUnions + emptyUnions,\n unknownTypes: acc.unknownTypes + unknownTypes,\n }\n }\n return acc\n }\n case 'union': {\n if (typeNode.of.length === 0) {\n return {allTypes: 1, emptyUnions: 1, unknownTypes: 0}\n }\n\n let acc = {allTypes: 1, emptyUnions: 0, unknownTypes: 0} // count the union type itself\n for (const type of typeNode.of) {\n const {allTypes, emptyUnions, unknownTypes} = walkAndCountQueryTypeNodeStats(type)\n acc = {\n allTypes: acc.allTypes + allTypes,\n emptyUnions: acc.emptyUnions + emptyUnions,\n unknownTypes: acc.unknownTypes + unknownTypes,\n }\n }\n return acc\n }\n case 'unknown': {\n return {allTypes: 1, emptyUnions: 0, unknownTypes: 1}\n }\n default: {\n return {allTypes: 1, emptyUnions: 0, unknownTypes: 0}\n }\n }\n}\n"],"names":["t","typeEvaluate","safeParseQuery","ARRAY_OF","INTERNAL_REFERENCE_SYMBOL","getFilterArrayUnionType","getUniqueIdentifierForName","isIdentifierName","weakMapMemo","SchemaTypeGenerator","schema","evaluateQuery","query","ast","typeNode","tsType","generateTsType","stats","walkAndCountQueryTypeNodeStats","identifiers","Map","tsTypes","uniqueTypeNames","Set","type","has","name","Error","add","currentIdentifierNames","values","map","id","uniqueIdentifier","set","getType","typeName","get","undefined","hasType","Symbol","iterator","typeNames","schemaType","generateArrayOfTsType","typeNodes","of","tsTypeReference","tsTypeParameterInstantiation","generateArrayTsType","identifier","every","unionTypeNode","unionMember","arrayOfNonInline","member","arrayOfInline","tsUnionType","generateDocumentTsType","document","props","Object","entries","attributes","key","node","generateTsObjectProperty","tsTypeLiteral","generateInlineTsType","addComment","tsUnknownKeyword","generateObjectTsType","attribute","push","rest","resolved","isTSUnknownKeyword","tsIntersectionType","dereferencesTo","derefType","assign","tsPropertySignature","tsTypeAnnotation","tsLiteralType","stringLiteral","computed","optional","value","keyNode","propertySignature","booleanLiteral","tsBooleanKeyword","tsNullKeyword","numericLiteral","tsNumberKeyword","tsStringKeyword","generateUnionTsType","length","tsNeverKeyword","acc","allTypes","emptyUnions","unknownTypes","restStats","attrs"],"mappings":"AAAA,YAAYA,OAAO,eAAc;AACjC,SAQEC,YAAY,QAGP,UAAS;AAEhB,SAAQC,cAAc,QAAO,uBAAsB;AACnD,SAAQC,QAAQ,EAAEC,yBAAyB,QAAO,iBAAgB;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AAO/B,MAAM,CAAChB,SAASiD,UAAU;gBAC/C,IAAIoC,MAAMI;gBACV,KAAK,MAAM/B,aAAagC,MAAO;oBAC7B,MAAM,EAACJ,QAAQ,EAAEC,WAAW,EAAEC,YAAY,EAAC,GAAGpF,+BAC5CsD,UAAUe,KAAK;oBAEjBY,MAAM;wBACJC,UAAUD,IAAIC,QAAQ,GAAGA;wBACzBC,aAAaF,IAAIE,WAAW,GAAGA;wBAC/BC,cAAcH,IAAIG,YAAY,GAAGA;oBACnC;gBACF;gBACA,OAAOH;YACT;QACA,KAAK;YAAS;gBACZ,IAAIrF,SAASgC,EAAE,CAACmD,MAAM,KAAK,GAAG;oBAC5B,OAAO;wBAACG,UAAU;wBAAGC,aAAa;wBAAGC,cAAc;oBAAC;gBACtD;gBAEA,IAAIH,MAAM;oBAACC,UAAU;oBAAGC,aAAa;oBAAGC,cAAc;gBAAC,EAAE,8BAA8B;;gBACvF,KAAK,MAAM9E,QAAQV,SAASgC,EAAE,CAAE;oBAC9B,MAAM,EAACsD,QAAQ,EAAEC,WAAW,EAAEC,YAAY,EAAC,GAAGpF,+BAA+BM;oBAC7E2E,MAAM;wBACJC,UAAUD,IAAIC,QAAQ,GAAGA;wBACzBC,aAAaF,IAAIE,WAAW,GAAGA;wBAC/BC,cAAcH,IAAIG,YAAY,GAAGA;oBACnC;gBACF;gBACA,OAAOH;YACT;QACA,KAAK;YAAW;gBACd,OAAO;oBAACC,UAAU;oBAAGC,aAAa;oBAAGC,cAAc;gBAAC;YACtD;QACA;YAAS;gBACP,OAAO;oBAACF,UAAU;oBAAGC,aAAa;oBAAGC,cAAc;gBAAC;YACtD;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/typescript/schemaTypeGenerator.ts"],"sourcesContent":["import * as t from '@babel/types'\nimport {\n type ArrayTypeNode,\n type DocumentSchemaType,\n type InlineTypeNode,\n type ObjectAttribute,\n type ObjectTypeNode,\n type SchemaType,\n type TypeDeclarationSchemaType,\n typeEvaluate,\n type TypeNode,\n type UnionTypeNode,\n} from 'groq-js'\n\nimport {safeParseQuery} from '../safeParseQuery.js'\nimport {ARRAY_OF, INTERNAL_REFERENCE_SYMBOL} from './constants.js'\nimport {\n getFilterArrayUnionType,\n getUniqueIdentifierForName,\n isIdentifierName,\n weakMapMemo,\n} from './helpers.js'\nimport {type ExtractedQuery, type TypeEvaluationStats} from './types.js'\n\nexport class SchemaTypeGenerator {\n public readonly schema: SchemaType\n evaluateQuery = weakMapMemo(\n // eslint-disable-next-line unicorn/consistent-function-scoping\n ({query}: Pick<ExtractedQuery, 'query'>): {stats: TypeEvaluationStats; tsType: t.TSType} => {\n const ast = safeParseQuery(query)\n const typeNode = typeEvaluate(ast, this.schema)\n const tsType = this.generateTsType(typeNode)\n const stats = walkAndCountQueryTypeNodeStats(typeNode)\n return {stats, tsType}\n },\n )\n private arrayOfUsed = false\n\n private identifiers = new Map<string, t.Identifier>()\n\n private tsTypes = new Map<string, t.TSType>()\n\n constructor(schema: SchemaType) {\n this.schema = schema\n\n const uniqueTypeNames = new Set<string>()\n for (const type of schema) {\n if (uniqueTypeNames.has(type.name)) {\n throw new Error(\n `Duplicate type name \"${type.name}\" in schema. Type names must be unique within the same schema.`,\n )\n }\n uniqueTypeNames.add(type.name)\n }\n\n for (const type of schema) {\n const currentIdentifierNames = new Set([...this.identifiers.values()].map((id) => id.name))\n const uniqueIdentifier = getUniqueIdentifierForName(type.name, currentIdentifierNames)\n this.identifiers.set(type.name, uniqueIdentifier)\n }\n\n for (const type of schema) {\n this.tsTypes.set(type.name, this.generateTsType(type))\n }\n }\n\n getType(typeName: string): {id: t.Identifier; tsType: t.TSType} | undefined {\n const tsType = this.tsTypes.get(typeName)\n const id = this.identifiers.get(typeName)\n if (tsType && id) return {id, tsType}\n return undefined\n }\n\n hasType(typeName: string): boolean {\n return this.tsTypes.has(typeName)\n }\n\n isArrayOfUsed(): boolean {\n return this.arrayOfUsed\n }\n\n *[Symbol.iterator]() {\n for (const {name} of this.schema) {\n yield {name, ...this.getType(name)!}\n }\n }\n\n typeNames(): string[] {\n return this.schema.map((schemaType) => schemaType.name)\n }\n\n /**\n * Helper function used to generate TS types for arrays of inline types, or arrays of inline types\n * wrapped in the ArrayOf wrapper that adds _key prop\n */\n private generateArrayOfTsType(typeNode: ArrayTypeNode): t.TSTypeReference {\n this.arrayOfUsed = true\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(ARRAY_OF, t.tsTypeParameterInstantiation([typeNodes]))\n }\n\n // Helper function used to generate TS types for array type nodes.\n private generateArrayTsType(typeNode: ArrayTypeNode): t.TSTypeReference | t.TSUnionType {\n // if it's an array of a single inline type, wrap it in ArrayOf\n if (typeNode.of.type === 'inline') {\n return this.generateArrayOfTsType(typeNode)\n }\n\n // if it's not an inline object and not a union, wrap in Array\n if (typeNode.of.type !== 'union') {\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(t.identifier('Array'), t.tsTypeParameterInstantiation([typeNodes]))\n }\n\n // if it's not a union type or all of the union type members are non-inlines, wrap type in Array\n if (typeNode.of.of.every((unionTypeNode) => unionTypeNode.type !== 'inline')) {\n const typeNodes = this.generateTsType(typeNode.of)\n return t.tsTypeReference(t.identifier('Array'), t.tsTypeParameterInstantiation([typeNodes]))\n }\n\n // all the union types nodes are inline\n if (typeNode.of.of.every((unionMember) => unionMember.type === 'inline')) {\n return this.generateArrayOfTsType(typeNode)\n }\n\n // some of the union types are inlines, while some are not - split and recurse\n const arrayOfNonInline = getFilterArrayUnionType(typeNode, (member) => member.type !== 'inline')\n const arrayOfInline = getFilterArrayUnionType(typeNode, (member) => member.type === 'inline')\n\n return t.tsUnionType([\n this.generateArrayTsType(arrayOfNonInline),\n this.generateArrayTsType(arrayOfInline),\n ])\n }\n\n // Helper function used to generate TS types for document type nodes.\n private generateDocumentTsType(document: DocumentSchemaType): t.TSType {\n const props = Object.entries(document.attributes).map(([key, node]) =>\n this.generateTsObjectProperty(key, node),\n )\n\n return t.tsTypeLiteral(props)\n }\n\n private generateInlineTsType(typeNode: InlineTypeNode): t.TSType {\n const id = this.identifiers.get(typeNode.name)\n if (!id) {\n // Not found in schema, return unknown type\n return t.addComment(\n t.tsUnknownKeyword(),\n 'trailing',\n ` Unable to locate the referenced type \"${typeNode.name}\" in schema`,\n true,\n )\n }\n\n return t.tsTypeReference(id)\n }\n\n // Helper function used to generate TS types for object type nodes.\n private generateObjectTsType(typeNode: ObjectTypeNode): t.TSType {\n const props: t.TSPropertySignature[] = []\n for (const [key, attribute] of Object.entries(typeNode.attributes)) {\n props.push(this.generateTsObjectProperty(key, attribute))\n }\n const rest = typeNode.rest\n\n if (rest) {\n switch (rest.type) {\n case 'inline': {\n const resolved = this.generateInlineTsType(rest)\n // if object rest is unknown, we can't generate a type literal for it\n if (t.isTSUnknownKeyword(resolved)) return resolved\n return t.tsIntersectionType([t.tsTypeLiteral(props), resolved])\n }\n case 'object': {\n for (const [key, attribute] of Object.entries(rest.attributes)) {\n props.push(this.generateTsObjectProperty(key, attribute))\n }\n break\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n default: {\n // @ts-expect-error This should never happen\n throw new Error(`Type \"${rest.type}\" not found in schema`)\n }\n }\n }\n\n if (typeNode.dereferencesTo) {\n const derefType = Object.assign(\n t.tsPropertySignature(\n INTERNAL_REFERENCE_SYMBOL,\n t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo))),\n ),\n {computed: true, optional: true},\n )\n props.push(derefType)\n }\n\n return t.tsTypeLiteral(props)\n }\n\n // Helper function used to generate TS types for object properties.\n private generateTsObjectProperty(key: string, attribute: ObjectAttribute): t.TSPropertySignature {\n const type = this.generateTsType(attribute.value)\n const keyNode = isIdentifierName(key) ? t.identifier(key) : t.stringLiteral(key)\n const propertySignature = t.tsPropertySignature(keyNode, t.tsTypeAnnotation(type))\n propertySignature.optional = attribute.optional\n\n return propertySignature\n }\n\n private generateTsType(\n typeNode: DocumentSchemaType | TypeDeclarationSchemaType | TypeNode,\n ): t.TSType {\n switch (typeNode.type) {\n case 'array': {\n return this.generateArrayTsType(typeNode)\n }\n case 'boolean': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.booleanLiteral(typeNode.value))\n }\n return t.tsBooleanKeyword()\n }\n case 'document': {\n return this.generateDocumentTsType(typeNode)\n }\n case 'inline': {\n return this.generateInlineTsType(typeNode)\n }\n case 'null': {\n return t.tsNullKeyword()\n }\n case 'number': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.numericLiteral(typeNode.value))\n }\n return t.tsNumberKeyword()\n }\n case 'object': {\n return this.generateObjectTsType(typeNode)\n }\n case 'string': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.stringLiteral(typeNode.value))\n }\n return t.tsStringKeyword()\n }\n case 'type': {\n return this.generateTsType(typeNode.value)\n }\n case 'union': {\n return this.generateUnionTsType(typeNode)\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n\n default: {\n throw new Error(\n `Encountered unsupported node type \"${\n // @ts-expect-error This should never happen\n typeNode.type\n }\" while generating schema types`,\n )\n }\n }\n }\n\n // Helper function used to generate TS types for union type nodes.\n private generateUnionTsType(typeNode: UnionTypeNode): t.TSType {\n if (typeNode.of.length === 0) return t.tsNeverKeyword()\n if (typeNode.of.length === 1) return this.generateTsType(typeNode.of[0]!)\n return t.tsUnionType(typeNode.of.map((node) => this.generateTsType(node)))\n }\n}\n\nexport function walkAndCountQueryTypeNodeStats(typeNode: TypeNode): TypeEvaluationStats {\n switch (typeNode.type) {\n case 'array': {\n const acc = walkAndCountQueryTypeNodeStats(typeNode.of)\n acc.allTypes += 1 // count the array type itself\n return acc\n }\n case 'object': {\n // if the rest is unknown, we count it as one unknown type\n if (typeNode.rest && typeNode.rest.type === 'unknown') {\n return {allTypes: 2, emptyUnions: 0, unknownTypes: 1} // count the object type itself as well\n }\n\n const restStats = typeNode.rest\n ? walkAndCountQueryTypeNodeStats(typeNode.rest)\n : {allTypes: 0, emptyUnions: 0, unknownTypes: 0}\n\n // count the object type itself\n restStats.allTypes += 1\n\n const attrs = Object.values(typeNode.attributes)\n let acc = restStats\n for (const attribute of attrs) {\n const {allTypes, emptyUnions, unknownTypes} = walkAndCountQueryTypeNodeStats(\n attribute.value,\n )\n acc = {\n allTypes: acc.allTypes + allTypes,\n emptyUnions: acc.emptyUnions + emptyUnions,\n unknownTypes: acc.unknownTypes + unknownTypes,\n }\n }\n return acc\n }\n case 'union': {\n if (typeNode.of.length === 0) {\n return {allTypes: 1, emptyUnions: 1, unknownTypes: 0}\n }\n\n let acc = {allTypes: 1, emptyUnions: 0, unknownTypes: 0} // count the union type itself\n for (const type of typeNode.of) {\n const {allTypes, emptyUnions, unknownTypes} = walkAndCountQueryTypeNodeStats(type)\n acc = {\n allTypes: acc.allTypes + allTypes,\n emptyUnions: acc.emptyUnions + emptyUnions,\n unknownTypes: acc.unknownTypes + unknownTypes,\n }\n }\n return acc\n }\n case 'unknown': {\n return {allTypes: 1, emptyUnions: 0, unknownTypes: 1}\n }\n default: {\n return {allTypes: 1, emptyUnions: 0, unknownTypes: 0}\n }\n }\n}\n"],"names":["t","typeEvaluate","safeParseQuery","ARRAY_OF","INTERNAL_REFERENCE_SYMBOL","getFilterArrayUnionType","getUniqueIdentifierForName","isIdentifierName","weakMapMemo","SchemaTypeGenerator","schema","evaluateQuery","query","ast","typeNode","tsType","generateTsType","stats","walkAndCountQueryTypeNodeStats","arrayOfUsed","identifiers","Map","tsTypes","uniqueTypeNames","Set","type","has","name","Error","add","currentIdentifierNames","values","map","id","uniqueIdentifier","set","getType","typeName","get","undefined","hasType","isArrayOfUsed","Symbol","iterator","typeNames","schemaType","generateArrayOfTsType","typeNodes","of","tsTypeReference","tsTypeParameterInstantiation","generateArrayTsType","identifier","every","unionTypeNode","unionMember","arrayOfNonInline","member","arrayOfInline","tsUnionType","generateDocumentTsType","document","props","Object","entries","attributes","key","node","generateTsObjectProperty","tsTypeLiteral","generateInlineTsType","addComment","tsUnknownKeyword","generateObjectTsType","attribute","push","rest","resolved","isTSUnknownKeyword","tsIntersectionType","dereferencesTo","derefType","assign","tsPropertySignature","tsTypeAnnotation","tsLiteralType","stringLiteral","computed","optional","value","keyNode","propertySignature","booleanLiteral","tsBooleanKeyword","tsNullKeyword","numericLiteral","tsNumberKeyword","tsStringKeyword","generateUnionTsType","length","tsNeverKeyword","acc","allTypes","emptyUnions","unknownTypes","restStats","attrs"],"mappings":"AAAA,YAAYA,OAAO,eAAc;AACjC,SAQEC,YAAY,QAGP,UAAS;AAEhB,SAAQC,cAAc,QAAO,uBAAsB;AACnD,SAAQC,QAAQ,EAAEC,yBAAyB,QAAO,iBAAgB;AAClE,SACEC,uBAAuB,EACvBC,0BAA0B,EAC1BC,gBAAgB,EAChBC,WAAW,QACN,eAAc;AAGrB,OAAO,MAAMC;IACKC,OAAkB;IAClCC,gBAAgBH,YACd,+DAA+D;IAC/D,CAAC,EAACI,KAAK,EAAgC;QACrC,MAAMC,MAAMX,eAAeU;QAC3B,MAAME,WAAWb,aAAaY,KAAK,IAAI,CAACH,MAAM;QAC9C,MAAMK,SAAS,IAAI,CAACC,cAAc,CAACF;QACnC,MAAMG,QAAQC,+BAA+BJ;QAC7C,OAAO;YAACG;YAAOF;QAAM;IACvB,GACD;IACOI,cAAc,MAAK;IAEnBC,cAAc,IAAIC,MAA2B;IAE7CC,UAAU,IAAID,MAAuB;IAE7C,YAAYX,MAAkB,CAAE;QAC9B,IAAI,CAACA,MAAM,GAAGA;QAEd,MAAMa,kBAAkB,IAAIC;QAC5B,KAAK,MAAMC,QAAQf,OAAQ;YACzB,IAAIa,gBAAgBG,GAAG,CAACD,KAAKE,IAAI,GAAG;gBAClC,MAAM,IAAIC,MACR,CAAC,qBAAqB,EAAEH,KAAKE,IAAI,CAAC,8DAA8D,CAAC;YAErG;YACAJ,gBAAgBM,GAAG,CAACJ,KAAKE,IAAI;QAC/B;QAEA,KAAK,MAAMF,QAAQf,OAAQ;YACzB,MAAMoB,yBAAyB,IA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E,MAAM;wBACJC,UAAUD,IAAIC,QAAQ,GAAGA;wBACzBC,aAAaF,IAAIE,WAAW,GAAGA;wBAC/BC,cAAcH,IAAIG,YAAY,GAAGA;oBACnC;gBACF;gBACA,OAAOH;YACT;QACA,KAAK;YAAW;gBACd,OAAO;oBAACC,UAAU;oBAAGC,aAAa;oBAAGC,cAAc;gBAAC;YACtD;QACA;YAAS;gBACP,OAAO;oBAACF,UAAU;oBAAGC,aAAa;oBAAGC,cAAc;gBAAC;YACtD;IACF;AACF"}
@@ -190,7 +190,7 @@ import { QueryEvaluationError } from './types.js';
190
190
  async generateTypes(options) {
191
191
  const { reporter: report } = options;
192
192
  const internalReferenceSymbol = this.getInternalReferenceSymbolDeclaration();
193
- const arrayOfDeclaration = this.getArrayOfDeclaration();
193
+ const schemaTypeGenerator = this.getSchemaTypeGenerator(options);
194
194
  const schemaTypeDeclarations = this.getSchemaTypeDeclarations(options);
195
195
  const allSanitySchemaTypesDeclaration = this.getAllSanitySchemaTypesDeclaration(options);
196
196
  report?.event.generatedSchemaTypes({
@@ -208,13 +208,17 @@ import { QueryEvaluationError } from './types.js';
208
208
  code += allSanitySchemaTypesDeclaration.code;
209
209
  program.body.push(internalReferenceSymbol.ast);
210
210
  code += internalReferenceSymbol.code;
211
- program.body.push(arrayOfDeclaration.ast);
212
- code += arrayOfDeclaration.code;
213
211
  const evaluatedModules = await TypeGenerator.getEvaluatedModules({
214
212
  ...options,
215
213
  schemaTypeDeclarations,
216
- schemaTypeGenerator: this.getSchemaTypeGenerator(options)
214
+ schemaTypeGenerator
217
215
  });
216
+ // Only generate ArrayOf if it's actually used
217
+ if (schemaTypeGenerator.isArrayOfUsed()) {
218
+ const arrayOfDeclaration = this.getArrayOfDeclaration();
219
+ program.body.push(arrayOfDeclaration.ast);
220
+ code += arrayOfDeclaration.code;
221
+ }
218
222
  for (const { queries } of evaluatedModules){
219
223
  for (const query of queries){
220
224
  program.body.push(query.ast);
@@ -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} 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\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\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 types.length > 0\n ? t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type))))\n : t.tsNeverKeyword(),\n ),\n )\n }),\n ),\n )\n\n const declareModule = t.declareModule(\n t.stringLiteral('@sanity/client'),\n t.blockStatement([queryReturnInterface]),\n )\n\n const clientImport = t.addComments(\n t.importDeclaration([], t.stringLiteral('@sanity/client')),\n 'leading',\n [{type: 'CommentLine', value: ' Query TypeMap'}],\n )\n\n const ast = t.program([clientImport, declareModule])\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 arrayOfDeclaration = this.getArrayOfDeclaration()\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 const program = t.program([])\n let code = ''\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 program.body.push(internalReferenceSymbol.ast)\n code += internalReferenceSymbol.code\n\n program.body.push(arrayOfDeclaration.ast)\n code += arrayOfDeclaration.code\n\n const evaluatedModules = await TypeGenerator.getEvaluatedModules({\n ...options,\n schemaTypeDeclarations,\n schemaTypeGenerator: this.getSchemaTypeGenerator(options),\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","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","declareModule","blockStatement","clientImport","importDeclaration","generateTypes","internalReferenceSymbol","arrayOfDeclaration","allSanitySchemaTypesDeclaration","event","generatedSchemaTypes","body","queryMapDeclaration","generatedQueryTypes"],"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,cAAc,QACT,iBAAgB;AACvB,SACEC,WAAW,EACXC,YAAY,EACZC,0BAA0B,EAC1BC,sBAAsB,QACjB,eAAc;AACrB,SAAQC,mBAAmB,QAAO,2BAA0B;AAC5D,SAIEC,oBAAoB,QAEf,aAAY;AA8CnB;;;CAGC,GACD,OAAO,MAAMC;IACHC,yBAAyBb,eAC/B;QAAC,CAACc,UAAkCA,QAAQC,MAAM;KAAC,EAEnD,CAACA,SAAW,IAAIL,oBAAoBK,SACrC;IAEOC,4BAA4BhB,eAClC;QACE,CAACc,UAAkCA,QAAQG,IAAI;QAC/C,CAACH,UAAkCA,QAAQI,UAAU;QACrD,IAAI,CAACL,sBAAsB;KAC5B,EAED,CAACI,OAAOnB,QAAQqB,GAAG,EAAE,EAAED,YAAYH,SACjC;eAAIA;SAAO,CAACK,GAAG,CAAC,CAAC,EAACC,EAAE,EAAEC,IAAI,EAAEC,MAAM,EAAC,EAAEC;YACnC,MAAMC,YAAY1B,EAAE2B,sBAAsB,CAACL,IAAI,MAAME;YACrD,I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BxF,GAAG,CAACuF,IAAI;QACjDlF,QAAQmF,oBAAoBnF,IAAI;QAEhCiC,QAAQ+C,MAAMI,oBAAoB;YAACD;QAAmB;QAEtD,OAAO;YAACxF,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_QUERIES,\n} from './constants.js'\nimport {\n computeOnce,\n generateCode,\n getUniqueIdentifierForName,\n normalizePrintablePath,\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\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\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 types.length > 0\n ? t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type))))\n : t.tsNeverKeyword(),\n ),\n )\n }),\n ),\n )\n\n const declareModule = t.declareModule(\n t.stringLiteral('@sanity/client'),\n t.blockStatement([queryReturnInterface]),\n )\n\n const clientImport = t.addComments(\n t.importDeclaration([], t.stringLiteral('@sanity/client')),\n 'leading',\n [{type: 'CommentLine', value: ' Query TypeMap'}],\n )\n\n const ast = t.program([clientImport, declareModule])\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 const program = t.program([])\n let code = ''\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 program.body.push(internalReferenceSymbol.ast)\n code += internalReferenceSymbol.code\n\n const evaluatedModules = await TypeGenerator.getEvaluatedModules({\n ...options,\n schemaTypeDeclarations,\n schemaTypeGenerator,\n })\n\n // Only generate ArrayOf if it's actually used\n if (schemaTypeGenerator.isArrayOfUsed()) {\n const arrayOfDeclaration = this.getArrayOfDeclaration()\n program.body.push(arrayOfDeclaration.ast)\n code += arrayOfDeclaration.code\n }\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","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","declareModule","blockStatement","clientImport","importDeclaration","generateTypes","internalReferenceSymbol","allSanitySchemaTypesDeclaration","event","generatedSchemaTypes","body","isArrayOfUsed","arrayOfDeclaration","queryMapDeclaration","generatedQueryTypes"],"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,cAAc,QACT,iBAAgB;AACvB,SACEC,WAAW,EACXC,YAAY,EACZC,0BAA0B,EAC1BC,sBAAsB,QACjB,eAAc;AACrB,SAAQC,mBAAmB,QAAO,2BAA0B;AAC5D,SAIEC,oBAAoB,QAEf,aAAY;AA8CnB;;;CAGC,GACD,OAAO,MAAMC;IACHC,yBAAyBb,eAC/B;QAAC,CAACc,UAAkCA,QAAQC,MAAM;KAAC,EAEnD,CAACA,SAAW,IAAIL,oBAAoBK,SACrC;IAEOC,4BAA4BhB,eAClC;QACE,CAACc,UAAkCA,QAAQG,IAAI;QAC/C,CAAC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,IAAI;QACjC;QAEA,KAAK,MAAM,EAAC8B,OAAO,EAAC,IAAIO,iBAAkB;YACxC,KAAK,MAAMa,SAASpB,QAAS;gBAC3B+B,QAAQoB,IAAI,CAAC1B,IAAI,CAACL,MAAMvD,GAAG;gBAC3BK,QAAQkD,MAAMlD,IAAI;YACpB;QACF;QAEA,MAAMoF,sBAAsB,MAAMxG,cAAc+E,sBAAsB,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"}
@@ -41,5 +41,5 @@
41
41
  ]
42
42
  }
43
43
  },
44
- "version": "5.9.1"
44
+ "version": "5.9.2"
45
45
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/codegen",
3
- "version": "5.9.1",
3
+ "version": "5.9.2",
4
4
  "description": "Codegen toolkit for Sanity.io",
5
5
  "keywords": [
6
6
  "sanity",