@sanity/codegen 8.1.1 → 8.3.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.
@@ -11,6 +11,11 @@ const defineQueryFunctionName = 'defineQuery';
11
11
  const groqModuleName = 'groq';
12
12
  const nextSanityModuleName = 'next-sanity';
13
13
  const sveltekitModuleName = '@sanity/sveltekit';
14
+ const defineProjectionFunctionName = 'defineProjection';
15
+ const projectionModuleNames = [
16
+ '@sanity/sdk',
17
+ '@sanity/sdk-react'
18
+ ];
14
19
  const ignoreValue = '@sanity-typegen-ignore';
15
20
  /**
16
21
  * findQueriesInSource takes a source string and returns all GROQ queries in it.
@@ -23,6 +28,7 @@ const ignoreValue = '@sanity-typegen-ignore';
23
28
  * @internal
24
29
  */ export function findQueriesInSource(source, filename, babelConfig = getBabelConfig(), resolver = require.resolve) {
25
30
  const queries = [];
31
+ const projections = [];
26
32
  const errors = [];
27
33
  const file = parseSourceFile(source, filename, babelConfig);
28
34
  traverse(file, {
@@ -73,11 +79,53 @@ const ignoreValue = '@sanity-typegen-ignore';
73
79
  }));
74
80
  }
75
81
  }
82
+ // Look for `defineProjection(projection)` or `defineProjection(documentType, projection)`
83
+ // imported from the App SDK
84
+ if (babelTypes.isIdentifier(node.id) && babelTypes.isCallExpression(init) && projectionModuleNames.some((moduleName)=>isImportFrom(moduleName, defineProjectionFunctionName, scope, init.callee)) && !declarationLeadingCommentContains(path, ignoreValue)) {
85
+ const { end, id, start } = node;
86
+ const variable = {
87
+ id,
88
+ ...start && {
89
+ start
90
+ },
91
+ ...end && {
92
+ end
93
+ }
94
+ };
95
+ const resolve = (argument)=>resolveExpression({
96
+ babelConfig,
97
+ file,
98
+ filename,
99
+ node: argument,
100
+ resolver,
101
+ scope
102
+ });
103
+ try {
104
+ const [first, second] = init.arguments;
105
+ const projectionNode = second ?? first;
106
+ if (!projectionNode) throw new Error('defineProjection needs a projection');
107
+ projections.push({
108
+ filename,
109
+ projection: resolve(projectionNode),
110
+ variable,
111
+ ...second && first ? {
112
+ documentType: resolve(first)
113
+ } : {}
114
+ });
115
+ } catch (cause) {
116
+ errors.push(new QueryExtractionError({
117
+ cause,
118
+ filename,
119
+ variable
120
+ }));
121
+ }
122
+ }
76
123
  }
77
124
  });
78
125
  return {
79
126
  errors,
80
127
  filename,
128
+ projections,
81
129
  queries
82
130
  };
83
131
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/typescript/findQueriesInSource.ts"],"sourcesContent":["import {createRequire} from 'node:module'\n\nimport {type NodePath, type TransformOptions, traverse} from '@babel/core'\nimport {type Scope} from '@babel/traverse'\nimport * as babelTypes from '@babel/types'\n\nimport {getBabelConfig} from '../getBabelConfig.js'\nimport {resolveExpression} from './expressionResolvers.js'\nimport {parseSourceFile} from './parseSource.js'\nimport {type ExtractedModule, type ExtractedQuery, QueryExtractionError} from './types.js'\n\nconst require = createRequire(import.meta.url)\n\nconst groqTagName = 'groq'\nconst defineQueryFunctionName = 'defineQuery'\nconst groqModuleName = 'groq'\nconst nextSanityModuleName = 'next-sanity'\nconst sveltekitModuleName = '@sanity/sveltekit'\n\nconst ignoreValue = '@sanity-typegen-ignore'\n\n/**\n * findQueriesInSource takes a source string and returns all GROQ queries in it.\n * @param source - The source code to search for queries\n * @param filename - The filename of the source code\n * @param babelConfig - The babel configuration to use when parsing the source\n * @param resolver - A resolver function to use when resolving module imports\n * @returns\n * @beta\n * @internal\n */\nexport function findQueriesInSource(\n source: string,\n filename: string,\n babelConfig: TransformOptions = getBabelConfig(),\n resolver: NodeJS.RequireResolve = require.resolve,\n): ExtractedModule {\n const queries: ExtractedQuery[] = []\n const errors: QueryExtractionError[] = []\n const file = parseSourceFile(source, filename, babelConfig)\n\n traverse(file, {\n // Look for variable declarations, e.g. `const myQuery = groq`... and extract the query.\n // The variable name is used as the name of the query result type\n VariableDeclarator(path) {\n const {node, scope} = path\n\n const init = node.init\n\n // Look for tagged template expressions that are called with the `groq` tag\n const isGroqTemplateTag =\n babelTypes.isTaggedTemplateExpression(init) &&\n babelTypes.isIdentifier(init.tag) &&\n init.tag.name === groqTagName\n\n // Look for strings wrapped in a defineQuery function call\n const isDefineQueryCall =\n babelTypes.isCallExpression(init) &&\n (isImportFrom(groqModuleName, defineQueryFunctionName, scope, init.callee) ||\n isImportFrom(nextSanityModuleName, defineQueryFunctionName, scope, init.callee) ||\n isImportFrom(sveltekitModuleName, defineQueryFunctionName, scope, init.callee))\n\n if (babelTypes.isIdentifier(node.id) && (isGroqTemplateTag || isDefineQueryCall)) {\n // If we find a comment leading the decleration which macthes with ignoreValue we don't add\n // the query\n if (declarationLeadingCommentContains(path, ignoreValue)) {\n return\n }\n\n const {end, id, start} = node\n const variable = {id, ...(start && {start}), ...(end && {end})}\n\n try {\n const query = resolveExpression({\n babelConfig,\n file,\n filename,\n node: init,\n resolver,\n scope,\n })\n queries.push({filename, query, variable})\n } catch (cause) {\n errors.push(new QueryExtractionError({cause, filename, variable}))\n }\n }\n },\n })\n\n return {errors, filename, queries}\n}\n\nfunction declarationLeadingCommentContains(path: NodePath, comment: string): boolean {\n /*\n * We have to consider these cases:\n *\n * // @sanity-typegen-ignore\n * const query = groq`...`\n *\n * // AST\n * VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * leadingComments: ...\n * }\n *\n * // @sanity-typegen-ignore\n * const query1 = groq`...`, query2 = groq`...`\n *\n * // AST\n * VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * leadingComments: ...\n * }\n *\n * // @sanity-typegen-ignore\n * export const query = groq`...`\n *\n * // AST\n * ExportNamedDeclaration {\n * declaration: VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * },\n * leadingComments: ...\n * }\n *\n * In the case where multiple variables are under the same VariableDeclaration the leadingComments\n * will still be on the VariableDeclaration\n *\n * In the case where the variable is exported, the leadingComments are on the\n * ExportNamedDeclaration which includes the VariableDeclaration in its own declaration property\n */\n\n const variableDeclaration = path.find((node) => node.isVariableDeclaration())\n if (!variableDeclaration) return false\n\n if (\n variableDeclaration.node.leadingComments?.find(\n (commentItem) => commentItem.value.trim() === comment,\n )\n ) {\n return true\n }\n\n // If the declaration is exported, the comment lies on the parent of the export declaration\n if (\n variableDeclaration.parent.leadingComments?.find(\n (commentItem) => commentItem.value.trim() === comment,\n )\n ) {\n return true\n }\n\n return false\n}\n\nfunction isImportFrom(\n moduleName: string,\n importName: string,\n scope: Scope,\n node: babelTypes.Expression | babelTypes.V8IntrinsicIdentifier,\n) {\n if (babelTypes.isIdentifier(node)) {\n const binding = scope.getBinding(node.name)\n if (!binding) {\n return false\n }\n\n const {path} = binding\n\n // import { foo } from 'groq'\n if (babelTypes.isImportSpecifier(path.node)) {\n return (\n path.node.importKind === 'value' &&\n path.parentPath &&\n babelTypes.isImportDeclaration(path.parentPath.node) &&\n path.parentPath.node.source.value === moduleName &&\n babelTypes.isIdentifier(path.node.imported) &&\n path.node.imported.name === importName\n )\n }\n\n // const { defineQuery } = require('groq')\n if (babelTypes.isVariableDeclarator(path.node)) {\n const {init} = path.node\n return (\n babelTypes.isCallExpression(init) &&\n babelTypes.isIdentifier(init.callee) &&\n init.callee.name === 'require' &&\n babelTypes.isStringLiteral(init.arguments[0]) &&\n init.arguments[0].value === moduleName\n )\n }\n }\n\n // import * as foo from 'groq'\n // foo.defineQuery(...)\n if (babelTypes.isMemberExpression(node)) {\n const {object, property} = node\n\n if (!babelTypes.isIdentifier(object)) {\n return false\n }\n\n const binding = scope.getBinding(object.name)\n if (!binding) {\n return false\n }\n const {path} = binding\n\n return (\n babelTypes.isIdentifier(object) &&\n babelTypes.isIdentifier(property) &&\n property.name === importName &&\n babelTypes.isImportNamespaceSpecifier(path.node) &&\n path.parentPath &&\n babelTypes.isImportDeclaration(path.parentPath.node) &&\n path.parentPath.node.source.value === moduleName\n )\n }\n\n return false\n}\n"],"names":["createRequire","traverse","babelTypes","getBabelConfig","resolveExpression","parseSourceFile","QueryExtractionError","require","url","groqTagName","defineQueryFunctionName","groqModuleName","nextSanityModuleName","sveltekitModuleName","ignoreValue","findQueriesInSource","source","filename","babelConfig","resolver","resolve","queries","errors","file","VariableDeclarator","path","node","scope","init","isGroqTemplateTag","isTaggedTemplateExpression","isIdentifier","tag","name","isDefineQueryCall","isCallExpression","isImportFrom","callee","id","declarationLeadingCommentContains","end","start","variable","query","push","cause","comment","variableDeclaration","find","isVariableDeclaration","leadingComments","commentItem","value","trim","parent","moduleName","importName","binding","getBinding","isImportSpecifier","importKind","parentPath","isImportDeclaration","imported","isVariableDeclarator","isStringLiteral","arguments","isMemberExpression","object","property","isImportNamespaceSpecifier"],"mappings":"AAAA,SAAQA,aAAa,QAAO,cAAa;AAEzC,SAA8CC,QAAQ,QAAO,cAAa;AAE1E,YAAYC,gBAAgB,eAAc;AAE1C,SAAQC,cAAc,QAAO,uBAAsB;AACnD,SAAQC,iBAAiB,QAAO,2BAA0B;AAC1D,SAAQC,eAAe,QAAO,mBAAkB;AAChD,SAAmDC,oBAAoB,QAAO,aAAY;AAE1F,MAAMC,UAAUP,cAAc,YAAYQ,GAAG;AAE7C,MAAMC,cAAc;AACpB,MAAMC,0BAA0B;AAChC,MAAMC,iBAAiB;AACvB,MAAMC,uBAAuB;AAC7B,MAAMC,sBAAsB;AAE5B,MAAMC,cAAc;AAEpB;;;;;;;;;CASC,GACD,OAAO,SAASC,oBACdC,MAAc,EACdC,QAAgB,EAChBC,cAAgCf,gBAAgB,EAChDgB,WAAkCZ,QAAQa,OAAO;IAEjD,MAAMC,UAA4B,EAAE;IACpC,MAAMC,SAAiC,EAAE;IACzC,MAAMC,OAAOlB,gBAAgBW,QAAQC,UAAUC;IAE/CjB,SAASsB,MAAM;QACb,wFAAwF;QACxF,iEAAiE;QACjEC,oBAAmBC,IAAI;YACr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,CAACP,SAC5B1B,WAAW6B,YAAY,CAACH,KAAKS,MAAM,KACnCT,KAAKS,MAAM,CAACJ,IAAI,KAAK,aACrB/B,WAAW+D,eAAe,CAACrC,KAAKsC,SAAS,CAAC,EAAE,KAC5CtC,KAAKsC,SAAS,CAAC,EAAE,CAACd,KAAK,KAAKG;QAEhC;IACF;IAEA,8BAA8B;IAC9B,uBAAuB;IACvB,IAAIrD,WAAWiE,kBAAkB,CAACzC,OAAO;QACvC,MAAM,EAAC0C,MAAM,EAAEC,QAAQ,EAAC,GAAG3C;QAE3B,IAAI,CAACxB,WAAW6B,YAAY,CAACqC,SAAS;YACpC,OAAO;QACT;QAEA,MAAMX,UAAU9B,MAAM+B,UAAU,CAACU,OAAOnC,IAAI;QAC5C,IAAI,CAACwB,SAAS;YACZ,OAAO;QACT;QACA,MAAM,EAAChC,IAAI,EAAC,GAAGgC;QAEf,OACEvD,WAAW6B,YAAY,CAACqC,WACxBlE,WAAW6B,YAAY,CAACsC,aACxBA,SAASpC,IAAI,KAAKuB,cAClBtD,WAAWoE,0BAA0B,CAAC7C,KAAKC,IAAI,KAC/CD,KAAKoC,UAAU,IACf3D,WAAW4D,mBAAmB,CAACrC,KAAKoC,UAAU,CAACnC,IAAI,KACnDD,KAAKoC,UAAU,CAACnC,IAAI,CAACV,MAAM,CAACoC,KAAK,KAAKG;IAE1C;IAEA,OAAO;AACT"}
1
+ {"version":3,"sources":["../../src/typescript/findQueriesInSource.ts"],"sourcesContent":["import {createRequire} from 'node:module'\n\nimport {type NodePath, type TransformOptions, traverse} from '@babel/core'\nimport {type Scope} from '@babel/traverse'\nimport * as babelTypes from '@babel/types'\n\nimport {getBabelConfig} from '../getBabelConfig.js'\nimport {resolveExpression} from './expressionResolvers.js'\nimport {parseSourceFile} from './parseSource.js'\nimport {\n type ExtractedModule,\n type ExtractedProjection,\n type ExtractedQuery,\n QueryExtractionError,\n} from './types.js'\n\nconst require = createRequire(import.meta.url)\n\nconst groqTagName = 'groq'\nconst defineQueryFunctionName = 'defineQuery'\nconst groqModuleName = 'groq'\nconst nextSanityModuleName = 'next-sanity'\nconst sveltekitModuleName = '@sanity/sveltekit'\nconst defineProjectionFunctionName = 'defineProjection'\nconst projectionModuleNames = ['@sanity/sdk', '@sanity/sdk-react']\n\nconst ignoreValue = '@sanity-typegen-ignore'\n\n/**\n * findQueriesInSource takes a source string and returns all GROQ queries in it.\n * @param source - The source code to search for queries\n * @param filename - The filename of the source code\n * @param babelConfig - The babel configuration to use when parsing the source\n * @param resolver - A resolver function to use when resolving module imports\n * @returns\n * @beta\n * @internal\n */\nexport function findQueriesInSource(\n source: string,\n filename: string,\n babelConfig: TransformOptions = getBabelConfig(),\n resolver: NodeJS.RequireResolve = require.resolve,\n): ExtractedModule {\n const queries: ExtractedQuery[] = []\n const projections: ExtractedProjection[] = []\n const errors: QueryExtractionError[] = []\n const file = parseSourceFile(source, filename, babelConfig)\n\n traverse(file, {\n // Look for variable declarations, e.g. `const myQuery = groq`... and extract the query.\n // The variable name is used as the name of the query result type\n VariableDeclarator(path) {\n const {node, scope} = path\n\n const init = node.init\n\n // Look for tagged template expressions that are called with the `groq` tag\n const isGroqTemplateTag =\n babelTypes.isTaggedTemplateExpression(init) &&\n babelTypes.isIdentifier(init.tag) &&\n init.tag.name === groqTagName\n\n // Look for strings wrapped in a defineQuery function call\n const isDefineQueryCall =\n babelTypes.isCallExpression(init) &&\n (isImportFrom(groqModuleName, defineQueryFunctionName, scope, init.callee) ||\n isImportFrom(nextSanityModuleName, defineQueryFunctionName, scope, init.callee) ||\n isImportFrom(sveltekitModuleName, defineQueryFunctionName, scope, init.callee))\n\n if (babelTypes.isIdentifier(node.id) && (isGroqTemplateTag || isDefineQueryCall)) {\n // If we find a comment leading the decleration which macthes with ignoreValue we don't add\n // the query\n if (declarationLeadingCommentContains(path, ignoreValue)) {\n return\n }\n\n const {end, id, start} = node\n const variable = {id, ...(start && {start}), ...(end && {end})}\n\n try {\n const query = resolveExpression({\n babelConfig,\n file,\n filename,\n node: init,\n resolver,\n scope,\n })\n queries.push({filename, query, variable})\n } catch (cause) {\n errors.push(new QueryExtractionError({cause, filename, variable}))\n }\n }\n\n // Look for `defineProjection(projection)` or `defineProjection(documentType, projection)`\n // imported from the App SDK\n if (\n babelTypes.isIdentifier(node.id) &&\n babelTypes.isCallExpression(init) &&\n projectionModuleNames.some((moduleName) =>\n isImportFrom(moduleName, defineProjectionFunctionName, scope, init.callee),\n ) &&\n !declarationLeadingCommentContains(path, ignoreValue)\n ) {\n const {end, id, start} = node\n const variable = {id, ...(start && {start}), ...(end && {end})}\n const resolve = (argument: babelTypes.Node) =>\n resolveExpression({babelConfig, file, filename, node: argument, resolver, scope})\n\n try {\n const [first, second] = init.arguments\n const projectionNode = second ?? first\n if (!projectionNode) throw new Error('defineProjection needs a projection')\n\n projections.push({\n filename,\n projection: resolve(projectionNode),\n variable,\n ...(second && first ? {documentType: resolve(first)} : {}),\n })\n } catch (cause) {\n errors.push(new QueryExtractionError({cause, filename, variable}))\n }\n }\n },\n })\n\n return {errors, filename, projections, queries}\n}\n\nfunction declarationLeadingCommentContains(path: NodePath, comment: string): boolean {\n /*\n * We have to consider these cases:\n *\n * // @sanity-typegen-ignore\n * const query = groq`...`\n *\n * // AST\n * VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * leadingComments: ...\n * }\n *\n * // @sanity-typegen-ignore\n * const query1 = groq`...`, query2 = groq`...`\n *\n * // AST\n * VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * leadingComments: ...\n * }\n *\n * // @sanity-typegen-ignore\n * export const query = groq`...`\n *\n * // AST\n * ExportNamedDeclaration {\n * declaration: VariableDeclaration {\n * declarations: [\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * VariableDeclarator: {init: tag: {name: \"groq\"}}\n * ],\n * },\n * leadingComments: ...\n * }\n *\n * In the case where multiple variables are under the same VariableDeclaration the leadingComments\n * will still be on the VariableDeclaration\n *\n * In the case where the variable is exported, the leadingComments are on the\n * ExportNamedDeclaration which includes the VariableDeclaration in its own declaration property\n */\n\n const variableDeclaration = path.find((node) => node.isVariableDeclaration())\n if (!variableDeclaration) return false\n\n if (\n variableDeclaration.node.leadingComments?.find(\n (commentItem) => commentItem.value.trim() === comment,\n )\n ) {\n return true\n }\n\n // If the declaration is exported, the comment lies on the parent of the export declaration\n if (\n variableDeclaration.parent.leadingComments?.find(\n (commentItem) => commentItem.value.trim() === comment,\n )\n ) {\n return true\n }\n\n return false\n}\n\nfunction isImportFrom(\n moduleName: string,\n importName: string,\n scope: Scope,\n node: babelTypes.Expression | babelTypes.V8IntrinsicIdentifier,\n) {\n if (babelTypes.isIdentifier(node)) {\n const binding = scope.getBinding(node.name)\n if (!binding) {\n return false\n }\n\n const {path} = binding\n\n // import { foo } from 'groq'\n if (babelTypes.isImportSpecifier(path.node)) {\n return (\n path.node.importKind === 'value' &&\n path.parentPath &&\n babelTypes.isImportDeclaration(path.parentPath.node) &&\n path.parentPath.node.source.value === moduleName &&\n babelTypes.isIdentifier(path.node.imported) &&\n path.node.imported.name === importName\n )\n }\n\n // const { defineQuery } = require('groq')\n if (babelTypes.isVariableDeclarator(path.node)) {\n const {init} = path.node\n return (\n babelTypes.isCallExpression(init) &&\n babelTypes.isIdentifier(init.callee) &&\n init.callee.name === 'require' &&\n babelTypes.isStringLiteral(init.arguments[0]) &&\n init.arguments[0].value === moduleName\n )\n }\n }\n\n // import * as foo from 'groq'\n // foo.defineQuery(...)\n if (babelTypes.isMemberExpression(node)) {\n const {object, property} = node\n\n if (!babelTypes.isIdentifier(object)) {\n return false\n }\n\n const binding = scope.getBinding(object.name)\n if (!binding) {\n return false\n }\n const {path} = binding\n\n return (\n babelTypes.isIdentifier(object) &&\n babelTypes.isIdentifier(property) &&\n property.name === importName &&\n babelTypes.isImportNamespaceSpecifier(path.node) &&\n path.parentPath &&\n babelTypes.isImportDeclaration(path.parentPath.node) &&\n path.parentPath.node.source.value === moduleName\n )\n }\n\n return false\n}\n"],"names":["createRequire","traverse","babelTypes","getBabelConfig","resolveExpression","parseSourceFile","QueryExtractionError","require","url","groqTagName","defineQueryFunctionName","groqModuleName","nextSanityModuleName","sveltekitModuleName","defineProjectionFunctionName","projectionModuleNames","ignoreValue","findQueriesInSource","source","filename","babelConfig","resolver","resolve","queries","projections","errors","file","VariableDeclarator","path","node","scope","init","isGroqTemplateTag","isTaggedTemplateExpression","isIdentifier","tag","name","isDefineQueryCall","isCallExpression","isImportFrom","callee","id","declarationLeadingCommentContains","end","start","variable","query","push","cause","some","moduleName","argument","first","second","arguments","projectionNode","Error","projection","documentType","comment","variableDeclaration","find","isVariableDeclaration","leadingComments","commentItem","value","trim","parent","importName","binding","getBinding","isImportSpecifier","importKind","parentPath","isImportDeclaration","imported","isVariableDeclarator","isStringLiteral","isMemberExpression","object","property","isImportNamespaceSpecifier"],"mappings":"AAAA,SAAQA,aAAa,QAAO,cAAa;AAEzC,SAA8CC,QAAQ,QAAO,cAAa;AAE1E,YAAYC,gBAAgB,eAAc;AAE1C,SAAQC,cAAc,QAAO,uBAAsB;AACnD,SAAQC,iBAAiB,QAAO,2BAA0B;AAC1D,SAAQC,eAAe,QAAO,mBAAkB;AAChD,SAIEC,oBAAoB,QACf,aAAY;AAEnB,MAAMC,UAAUP,cAAc,YAAYQ,GAAG;AAE7C,MAAMC,cAAc;AACpB,MAAMC,0BAA0B;AAChC,MAAMC,iBAAiB;AACvB,MAAMC,uBAAuB;AAC7B,MAAMC,sBAAsB;AAC5B,MAAMC,+BAA+B;AACrC,MAAMC,wBAAwB;IAAC;IAAe;CAAoB;AAElE,MAAMC,cAAc;AAEpB;;;;;;;;;CASC,GACD,OAAO,SAASC,oBACdC,MAAc,EACdC,QAAgB,EAChBC,cAAgCjB,gBAAgB,EAChDkB,WAAkCd,QAAQe,OAAO;IAEjD,MAAMC,UAA4B,EAAE;I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MAAM,CAACJ,IAAI,KAAK,aACrBlC,WAAW2E,eAAe,CAAC9C,KAAKuB,SAAS,CAAC,EAAE,KAC5CvB,KAAKuB,SAAS,CAAC,EAAE,CAACW,KAAK,KAAKf;QAEhC;IACF;IAEA,8BAA8B;IAC9B,uBAAuB;IACvB,IAAIhD,WAAW4E,kBAAkB,CAACjD,OAAO;QACvC,MAAM,EAACkD,MAAM,EAAEC,QAAQ,EAAC,GAAGnD;QAE3B,IAAI,CAAC3B,WAAWgC,YAAY,CAAC6C,SAAS;YACpC,OAAO;QACT;QAEA,MAAMV,UAAUvC,MAAMwC,UAAU,CAACS,OAAO3C,IAAI;QAC5C,IAAI,CAACiC,SAAS;YACZ,OAAO;QACT;QACA,MAAM,EAACzC,IAAI,EAAC,GAAGyC;QAEf,OACEnE,WAAWgC,YAAY,CAAC6C,WACxB7E,WAAWgC,YAAY,CAAC8C,aACxBA,SAAS5C,IAAI,KAAKgC,cAClBlE,WAAW+E,0BAA0B,CAACrD,KAAKC,IAAI,KAC/CD,KAAK6C,UAAU,IACfvE,WAAWwE,mBAAmB,CAAC9C,KAAK6C,UAAU,CAAC5C,IAAI,KACnDD,KAAK6C,UAAU,CAAC5C,IAAI,CAACX,MAAM,CAAC+C,KAAK,KAAKf;IAE1C;IAEA,OAAO;AACT"}
@@ -3,7 +3,17 @@ import { typeEvaluate } from 'groq-js';
3
3
  import { safeParseQuery } from '../safeParseQuery.js';
4
4
  import { ARRAY_OF, INTERNAL_REFERENCE_SYMBOL } from './constants.js';
5
5
  import { getFilterArrayUnionType, getUniqueIdentifierForName, isIdentifierName, weakMapMemo } from './helpers.js';
6
- export class SchemaTypeGenerator {
6
+ /**
7
+ * Generates TypeScript types from a schema, as `sanity schema extract` writes it.
8
+ *
9
+ * On construction, every type in the schema gets a TypeScript type and a unique alias
10
+ * identifier; iterating the instance yields them as `{name, id, tsType}`, in schema order.
11
+ * `generateTsType` turns any groq-js type node into a TypeScript type that names schema types
12
+ * by those aliases, and `evaluateQuery` does so for the result of a GROQ query. A tool that
13
+ * types GROQ outside `TypeGenerator`, such as a TypeScript content mapper for `.groq` files,
14
+ * uses this class so that its output agrees with what `sanity typegen generate` writes.
15
+ * @beta
16
+ */ export class SchemaTypeGenerator {
7
17
  schema;
8
18
  evaluateQuery = weakMapMemo(// eslint-disable-next-line unicorn/consistent-function-scoping
9
19
  ({ query })=>{
@@ -39,6 +49,86 @@ export class SchemaTypeGenerator {
39
49
  this.tsTypes.set(type.name, this.generateTsType(type));
40
50
  }
41
51
  }
52
+ /** The names of the schema's document types, in schema order. */ documentTypeNames() {
53
+ return this.schema.filter((schemaType)=>schemaType.type === 'document').map(({ name })=>name);
54
+ }
55
+ /**
56
+ * Evaluates a projection for one document type, as `*[_type == TYPE][0]PROJECTION` without
57
+ * the `null` for a missing document: the SDK projects documents it has found.
58
+ */ evaluateProjection({ documentType, projection }) {
59
+ const ast = safeParseQuery(`*[_type == ${JSON.stringify(documentType)}][0]${projection}`);
60
+ const typeNode = withoutNull(typeEvaluate(ast, this.schema));
61
+ return {
62
+ stats: walkAndCountQueryTypeNodeStats(typeNode),
63
+ tsType: this.generateTsType(typeNode)
64
+ };
65
+ }
66
+ /**
67
+ * The TypeScript type for a groq-js type node. A reference to a schema type becomes its alias
68
+ * identifier, an array of inline types becomes `ArrayOf<...>` (and `isArrayOfUsed` reports
69
+ * that the helper is needed), and a reference object carries `internalGroqTypeReferenceTo`.
70
+ */ generateTsType(typeNode) {
71
+ switch(typeNode.type){
72
+ case 'array':
73
+ {
74
+ return this.generateArrayTsType(typeNode);
75
+ }
76
+ case 'boolean':
77
+ {
78
+ if (typeNode.value !== undefined) {
79
+ return t.tsLiteralType(t.booleanLiteral(typeNode.value));
80
+ }
81
+ return t.tsBooleanKeyword();
82
+ }
83
+ case 'document':
84
+ {
85
+ return this.generateDocumentTsType(typeNode);
86
+ }
87
+ case 'inline':
88
+ {
89
+ return this.generateInlineTsType(typeNode);
90
+ }
91
+ case 'null':
92
+ {
93
+ return t.tsNullKeyword();
94
+ }
95
+ case 'number':
96
+ {
97
+ if (typeNode.value !== undefined) {
98
+ return t.tsLiteralType(t.numericLiteral(typeNode.value));
99
+ }
100
+ return t.tsNumberKeyword();
101
+ }
102
+ case 'object':
103
+ {
104
+ return this.generateObjectTsType(typeNode);
105
+ }
106
+ case 'string':
107
+ {
108
+ if (typeNode.value !== undefined) {
109
+ return t.tsLiteralType(t.stringLiteral(typeNode.value));
110
+ }
111
+ return t.tsStringKeyword();
112
+ }
113
+ case 'type':
114
+ {
115
+ return this.generateTsType(typeNode.value);
116
+ }
117
+ case 'union':
118
+ {
119
+ return this.generateUnionTsType(typeNode);
120
+ }
121
+ case 'unknown':
122
+ {
123
+ return t.tsUnknownKeyword();
124
+ }
125
+ default:
126
+ {
127
+ throw new Error(`Encountered unsupported node type "${// @ts-expect-error This should never happen
128
+ typeNode.type}" while generating schema types`);
129
+ }
130
+ }
131
+ }
42
132
  getType(typeName) {
43
133
  const tsType = this.tsTypes.get(typeName);
44
134
  const id = this.identifiers.get(typeName);
@@ -174,68 +264,6 @@ export class SchemaTypeGenerator {
174
264
  propertySignature.optional = attribute.optional;
175
265
  return propertySignature;
176
266
  }
177
- generateTsType(typeNode) {
178
- switch(typeNode.type){
179
- case 'array':
180
- {
181
- return this.generateArrayTsType(typeNode);
182
- }
183
- case 'boolean':
184
- {
185
- if (typeNode.value !== undefined) {
186
- return t.tsLiteralType(t.booleanLiteral(typeNode.value));
187
- }
188
- return t.tsBooleanKeyword();
189
- }
190
- case 'document':
191
- {
192
- return this.generateDocumentTsType(typeNode);
193
- }
194
- case 'inline':
195
- {
196
- return this.generateInlineTsType(typeNode);
197
- }
198
- case 'null':
199
- {
200
- return t.tsNullKeyword();
201
- }
202
- case 'number':
203
- {
204
- if (typeNode.value !== undefined) {
205
- return t.tsLiteralType(t.numericLiteral(typeNode.value));
206
- }
207
- return t.tsNumberKeyword();
208
- }
209
- case 'object':
210
- {
211
- return this.generateObjectTsType(typeNode);
212
- }
213
- case 'string':
214
- {
215
- if (typeNode.value !== undefined) {
216
- return t.tsLiteralType(t.stringLiteral(typeNode.value));
217
- }
218
- return t.tsStringKeyword();
219
- }
220
- case 'type':
221
- {
222
- return this.generateTsType(typeNode.value);
223
- }
224
- case 'union':
225
- {
226
- return this.generateUnionTsType(typeNode);
227
- }
228
- case 'unknown':
229
- {
230
- return t.tsUnknownKeyword();
231
- }
232
- default:
233
- {
234
- throw new Error(`Encountered unsupported node type "${// @ts-expect-error This should never happen
235
- typeNode.type}" while generating schema types`);
236
- }
237
- }
238
- }
239
267
  // Helper function used to generate TS types for union type nodes.
240
268
  generateUnionTsType(typeNode) {
241
269
  if (typeNode.of.length === 0) return t.tsNeverKeyword();
@@ -324,5 +352,13 @@ export function walkAndCountQueryTypeNodeStats(typeNode) {
324
352
  }
325
353
  }
326
354
  }
355
+ function withoutNull(typeNode) {
356
+ if (typeNode.type !== 'union') return typeNode;
357
+ const of = typeNode.of.filter((member)=>member.type !== 'null');
358
+ return of.length === 1 ? of[0] : {
359
+ ...typeNode,
360
+ of
361
+ };
362
+ }
327
363
 
328
364
  //# sourceMappingURL=schemaTypeGenerator.js.map
@@ -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 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,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AAC;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\n/**\n * Generates TypeScript types from a schema, as `sanity schema extract` writes it.\n *\n * On construction, every type in the schema gets a TypeScript type and a unique alias\n * identifier; iterating the instance yields them as `{name, id, tsType}`, in schema order.\n * `generateTsType` turns any groq-js type node into a TypeScript type that names schema types\n * by those aliases, and `evaluateQuery` does so for the result of a GROQ query. A tool that\n * types GROQ outside `TypeGenerator`, such as a TypeScript content mapper for `.groq` files,\n * uses this class so that its output agrees with what `sanity typegen generate` writes.\n * @beta\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 /** The names of the schema's document types, in schema order. */\n documentTypeNames(): string[] {\n return this.schema.filter((schemaType) => schemaType.type === 'document').map(({name}) => name)\n }\n\n /**\n * Evaluates a projection for one document type, as `*[_type == TYPE][0]PROJECTION` without\n * the `null` for a missing document: the SDK projects documents it has found.\n */\n evaluateProjection({documentType, projection}: {documentType: string; projection: string}): {\n stats: TypeEvaluationStats\n tsType: t.TSType\n } {\n const ast = safeParseQuery(`*[_type == ${JSON.stringify(documentType)}][0]${projection}`)\n const typeNode = withoutNull(typeEvaluate(ast, this.schema))\n return {stats: walkAndCountQueryTypeNodeStats(typeNode), tsType: this.generateTsType(typeNode)}\n }\n\n /**\n * The TypeScript type for a groq-js type node. A reference to a schema type becomes its alias\n * identifier, an array of inline types becomes `ArrayOf<...>` (and `isArrayOfUsed` reports\n * that the helper is needed), and a reference object carries `internalGroqTypeReferenceTo`.\n */\n generateTsType(typeNode: DocumentSchemaType | TypeDeclarationSchemaType | TypeNode): 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 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 // 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\nfunction withoutNull(typeNode: TypeNode): TypeNode {\n if (typeNode.type !== 'union') return typeNode\n const of = typeNode.of.filter((member) => member.type !== 'null')\n return of.length === 1 ? of[0]! : {...typeNode, of}\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","documentTypeNames","filter","schemaType","evaluateProjection","documentType","projection","JSON","stringify","withoutNull","generateArrayTsType","value","undefined","tsLiteralType","booleanLiteral","tsBooleanKeyword","generateDocumentTsType","generateInlineTsType","tsNullKeyword","numericLiteral","tsNumberKeyword","generateObjectTsType","stringLiteral","tsStringKeyword","generateUnionTsType","tsUnknownKeyword","getType","typeName","get","hasType","isArrayOfUsed","Symbol","iterator","typeNames","generateArrayOfTsType","typeNodes","of","tsTypeReference","tsTypeParameterInstantiation","identifier","every","unionTypeNode","unionMember","arrayOfNonInline","member","arrayOfInline","tsUnionType","document","props","Object","entries","attributes","key","node","generateTsObjectProperty","tsTypeLiteral","addComment","attribute","push","rest","resolved","isTSUnknownKeyword","tsIntersectionType","dereferencesTo","derefType","assign","tsPropertySignature","tsTypeAnnotation","computed","optional","keyNode","propertySignature","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;;;;;;;;;;CAUC,GACD,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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