@sanity/codegen 8.1.1 → 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.
- package/README.md +53 -0
- package/dist/_exports/index.d.ts +123 -18
- package/dist/_exports/index.js.map +1 -1
- package/dist/actions/typegenGenerate.js +4 -1
- package/dist/actions/typegenGenerate.js.map +1 -1
- package/dist/actions/typegenGenerate.worker.js +9 -4
- package/dist/actions/typegenGenerate.worker.js.map +1 -1
- package/dist/actions/typegenWatch.js +3 -2
- package/dist/actions/typegenWatch.js.map +1 -1
- package/dist/actions/types.js.map +1 -1
- package/dist/typescript/constants.js +3 -0
- package/dist/typescript/constants.js.map +1 -1
- package/dist/typescript/findQueriesInSource.js +48 -0
- package/dist/typescript/findQueriesInSource.js.map +1 -1
- package/dist/typescript/schemaTypeGenerator.js +22 -0
- package/dist/typescript/schemaTypeGenerator.js.map +1 -1
- package/dist/typescript/typeGenerator.js +216 -12
- package/dist/typescript/typeGenerator.js.map +1 -1
- package/dist/typescript/types.js.map +1 -1
- package/package.json +1 -1
|
@@ -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 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 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","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,EACtBC,eAAe,EACfC,eAAe,QACV,eAAc;AACrB,SAAQC,mBAAmB,QAAO,2BAA0B;AAC5D,SAIEC,oBAAoB,QAEf,aAAY;AAgDnB;;;CAGC,GACD,OAAO,MAAMC;IACHC,yBAAyBf,eAC/B;QAAC,CAACgB,UAAkCA,QAAQC,MAAM;KAAC,EAEnD,CAACA,SAAW,IAAIL,oBAAoBK,SACrC;IAEOC,4BAA4BlB,eAClC;QACE,CAACgB,UAAkCA,QAAQG,IAAI;QAC/C,CAACH,UAAkCA,QAAQI,UAAU;QACrD,IAAI,CAACL,sBAAsB;KAC5B,EAED,CAACI,OAAOrB,QAAQuB,GAAG,EAAE,EAAED,YAAYH,SACjC;eAAIA;SAAO,CAACK,GAAG,CAAC,CAAC,EAACC,EAAE,EAAEC,IAAI,EAAEC,MAAM,EAAC,EAAEC;YACnC,MAAMC,YAAY5B,EAAE6B,sBAAsB,CAACL,IAA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BAC3B+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"}
|
|
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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CAACC,SACP7I,GAAG,CAAC,CAAC8I,OAASA,IAAI,CAAC,EAAE,CAAEC,WAAW,KAAKD,KAAKE,KAAK,CAAC,IAClDlB,IAAI,CAAC;AACV"}
|
|
@@ -1 +1 @@
|
|
|
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 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;
|
|
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"}
|