@sanity/codegen 3.52.5-canary.18 → 3.52.5-canary.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.esm.js +12 -15
- package/lib/index.esm.js.map +1 -1
- package/lib/index.js +12 -15
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +12 -15
- package/lib/index.mjs.map +1 -1
- package/package.json +3 -3
package/lib/index.esm.js
CHANGED
|
@@ -90,9 +90,8 @@ function resolveExpression({
|
|
|
90
90
|
params = [],
|
|
91
91
|
fnArguments = []
|
|
92
92
|
}) {
|
|
93
|
-
var _a, _b, _c, _d;
|
|
94
93
|
if (debug$2(
|
|
95
|
-
`Resolving node ${node.type} in ${filename}:${
|
|
94
|
+
`Resolving node ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`
|
|
96
95
|
), t.isTaggedTemplateExpression(node) && t.isIdentifier(node.tag) && TAGGED_TEMPLATE_ALLOW_LIST.includes(node.tag.name))
|
|
97
96
|
return resolveExpression({
|
|
98
97
|
node: node.quasi,
|
|
@@ -203,7 +202,7 @@ function resolveExpression({
|
|
|
203
202
|
fnArguments
|
|
204
203
|
});
|
|
205
204
|
throw new Error(
|
|
206
|
-
`Unsupported expression type: ${node.type} in ${filename}:${
|
|
205
|
+
`Unsupported expression type: ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`
|
|
207
206
|
);
|
|
208
207
|
}
|
|
209
208
|
function resolveIdentifier({
|
|
@@ -216,7 +215,6 @@ function resolveIdentifier({
|
|
|
216
215
|
fnArguments,
|
|
217
216
|
params
|
|
218
217
|
}) {
|
|
219
|
-
var _a, _b, _c, _d;
|
|
220
218
|
const paramIndex = params.findIndex(
|
|
221
219
|
(param) => t.isIdentifier(param) && node.name === param.name || t.isAssignmentPattern(param) && t.isIdentifier(param.left) && node.name === param.left.name
|
|
222
220
|
), argument = fnArguments[paramIndex];
|
|
@@ -235,7 +233,7 @@ function resolveIdentifier({
|
|
|
235
233
|
if (binding) {
|
|
236
234
|
if (t.isIdentifier(binding.path.node) && binding.path.node.name === node.name)
|
|
237
235
|
throw new Error(
|
|
238
|
-
`Could not resolve same identifier "${node.name}" in "${filename}:${
|
|
236
|
+
`Could not resolve same identifier "${node.name}" in "${filename}:${node.loc?.start.line}:${node.loc?.start.column}"`
|
|
239
237
|
);
|
|
240
238
|
return resolveExpression({
|
|
241
239
|
node: binding.path.node,
|
|
@@ -249,7 +247,7 @@ function resolveIdentifier({
|
|
|
249
247
|
});
|
|
250
248
|
}
|
|
251
249
|
throw new Error(
|
|
252
|
-
`Could not find binding for node "${node.name}" in ${filename}:${
|
|
250
|
+
`Could not find binding for node "${node.name}" in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`
|
|
253
251
|
);
|
|
254
252
|
}
|
|
255
253
|
function resolveCallExpression({
|
|
@@ -283,10 +281,9 @@ function resolveImportSpecifier({
|
|
|
283
281
|
let importDeclaration;
|
|
284
282
|
if (traverse(file, {
|
|
285
283
|
ImportDeclaration(n) {
|
|
286
|
-
var _a;
|
|
287
284
|
if (t.isImportDeclaration(n.node))
|
|
288
285
|
for (const specifier of n.node.specifiers) {
|
|
289
|
-
if (t.isImportDefaultSpecifier(specifier) &&
|
|
286
|
+
if (t.isImportDefaultSpecifier(specifier) && specifier.local.loc?.identifierName === node.local.name) {
|
|
290
287
|
importDeclaration = n.node;
|
|
291
288
|
break;
|
|
292
289
|
}
|
|
@@ -384,11 +381,10 @@ function findQueriesInSource(source, filename, babelConfig = getBabelConfig(), r
|
|
|
384
381
|
}), queries;
|
|
385
382
|
}
|
|
386
383
|
function declarationLeadingCommentContains(path2, comment) {
|
|
387
|
-
var _a, _b;
|
|
388
384
|
const variableDeclaration = path2.find((node) => node.isVariableDeclaration());
|
|
389
|
-
return variableDeclaration ? !!(
|
|
385
|
+
return variableDeclaration ? !!(variableDeclaration.node.leadingComments?.find(
|
|
390
386
|
(commentItem) => commentItem.value.trim() === comment
|
|
391
|
-
) ||
|
|
387
|
+
) || variableDeclaration.parent.leadingComments?.find(
|
|
392
388
|
(commentItem) => commentItem.value.trim() === comment
|
|
393
389
|
)) : !1;
|
|
394
390
|
}
|
|
@@ -469,11 +465,13 @@ function registerBabel(babelOptions) {
|
|
|
469
465
|
const options = babelOptions || getBabelConfig();
|
|
470
466
|
register({ ...options, extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"] });
|
|
471
467
|
}
|
|
472
|
-
var __defProp = Object.defineProperty, __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
|
|
473
468
|
const REFERENCE_SYMBOL_NAME = "internalGroqTypeReferenceTo", ALL_SCHEMA_TYPES = "AllSanitySchemaTypes";
|
|
474
469
|
class TypeGenerator {
|
|
470
|
+
generatedTypeName = /* @__PURE__ */ new Set();
|
|
471
|
+
typeNameMap = /* @__PURE__ */ new Map();
|
|
472
|
+
schema;
|
|
475
473
|
constructor(schema) {
|
|
476
|
-
|
|
474
|
+
this.schema = schema;
|
|
477
475
|
}
|
|
478
476
|
/**
|
|
479
477
|
* Generate TypeScript types for the given schema
|
|
@@ -535,11 +533,10 @@ class TypeGenerator {
|
|
|
535
533
|
* @beta
|
|
536
534
|
*/
|
|
537
535
|
generateQueryMap(queries) {
|
|
538
|
-
var _a;
|
|
539
536
|
const typesByQuerystring = {};
|
|
540
537
|
for (const query of queries) {
|
|
541
538
|
const name = this.typeNameMap.get(query.typeNode);
|
|
542
|
-
name && (typesByQuerystring[
|
|
539
|
+
name && (typesByQuerystring[query.query] ??= [], typesByQuerystring[query.query].push(name));
|
|
543
540
|
}
|
|
544
541
|
const queryReturnInterface = t.tsInterfaceDeclaration(
|
|
545
542
|
t.identifier("SanityQueries"),
|
package/lib/index.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.js","sources":["../src/readConfig.ts","../src/readSchema.ts","../src/safeParseQuery.ts","../src/getBabelConfig.ts","../src/typescript/parseSource.ts","../src/typescript/expressionResolvers.ts","../src/typescript/findQueriesInSource.ts","../src/typescript/moduleResolver.ts","../src/typescript/findQueriesInPath.ts","../src/typescript/registerBabel.ts","../src/typescript/typeGenerator.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport * as json5 from 'json5'\nimport * as z from 'zod'\n\nexport const configDefintion = z.object({\n path: z\n .string()\n .or(z.array(z.string()))\n .default([\n './src/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n './app/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n ]),\n schema: z.string().default('./schema.json'),\n generates: z.string().default('./sanity.types.ts'),\n formatGeneratedCode: z.boolean().default(true),\n overloadClientMethods: z.boolean().default(false),\n})\n\nexport type CodegenConfig = z.infer<typeof configDefintion>\n\nexport async function readConfig(path: string): Promise<CodegenConfig> {\n try {\n const content = await readFile(path, 'utf-8')\n const json = json5.parse(content)\n return configDefintion.parseAsync(json)\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(`Error in config file\\n ${error.errors.map((err) => err.message).join('\\n')}`)\n }\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return configDefintion.parse({})\n }\n\n throw error\n }\n}\n","import {readFile} from 'node:fs/promises'\n\nimport {type SchemaType} from 'groq-js'\n\n/**\n * Read a schema from a given path\n * @param path - The path to the schema\n * @returns The schema\n * @internal\n * @beta\n **/\nexport async function readSchema(path: string): Promise<SchemaType> {\n const content = await readFile(path, 'utf-8')\n return JSON.parse(content) // todo: ZOD validation?\n}\n","import {parse} from 'groq-js'\n\n/**\n * safeParseQuery parses a GROQ query string, but first attempts to extract any parameters used in slices. This method is _only_\n * intended for use in type generation where we don't actually execute the parsed AST on a dataset, and should not be used elsewhere.\n * @internal\n */\nexport function safeParseQuery(query: string) {\n const params: Record<string, unknown> = {}\n\n for (const param of extractSliceParams(query)) {\n params[param] = 0 // we don't care about the value, just the type\n }\n return parse(query, {params})\n}\n\n/**\n * Finds occurences of `[($start|{number})..($end|{number})]` in a query string and returns the start and end values, and return\n * the names of the start and end variables.\n * @internal\n */\nexport function* extractSliceParams(query: string): Generator<string> {\n const sliceRegex = /\\[(\\$(\\w+)|\\d)\\.\\.\\.?(\\$(\\w+)|\\d)\\]/g\n const matches = query.matchAll(sliceRegex)\n if (!matches) {\n return\n }\n const params = new Set<string>()\n for (const match of matches) {\n const start = match[1] === `$${match[2]}` ? match[2] : null\n if (start !== null) {\n yield start\n }\n const end = match[3] === `$${match[4]}` ? match[4] : null\n if (end !== null) {\n yield end\n }\n }\n}\n","import {existsSync} from 'node:fs'\nimport {join, resolve} from 'node:path'\n\nimport {type TransformOptions} from '@babel/core'\n\n/**\n * Because of bundlers and compilers, knowing the exact path the babel configuration will be\n * located at post - build is not always trivial. We traverse from the current directory upwards\n * until we find the first `babel.config.json` and use that path.\n *\n * @param path - The path to start looking for the babel configuration\n * @returns The path to the `babel.config.json` file\n * @internal\n */\nexport function findBabelConfig(path: string): string {\n const configPath = join(path, 'babel.config.json')\n if (existsSync(configPath)) {\n return configPath\n }\n\n const parent = resolve(join(path, '..'))\n if (parent && parent !== path) {\n return findBabelConfig(parent)\n }\n\n throw new Error('Could not find `babel.config.json` in @sanity/codegen')\n}\n\n/**\n * Get the default babel configuration for `@sanity/codegen`\n *\n * @param path - The path to start looking for the babel configuration. Defaults to `__dirname`\n * @returns A babel configuration object\n * @internal\n */\nexport function getBabelConfig(path?: string): TransformOptions {\n const configPath = findBabelConfig(path || __dirname)\n return {extends: configPath}\n}\n","import {parse, type TransformOptions} from '@babel/core'\nimport type * as babelTypes from '@babel/types'\n\n// helper function to parse a source file\nexport function parseSourceFile(\n source: string,\n filename: string,\n babelOptions: TransformOptions,\n): babelTypes.File {\n const result = parse(source, {\n ...babelOptions,\n filename,\n })\n\n if (!result) {\n throw new Error(`Failed to parse ${filename}`)\n }\n\n return result\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type TransformOptions} from '@babel/core'\nimport traverse, {type Scope} from '@babel/traverse'\nimport * as babelTypes from '@babel/types'\nimport createDebug from 'debug'\n\nimport {parseSourceFile} from './parseSource'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ntype resolveExpressionReturnType = string\n\n/**\n * NamedQueryResult is a result of a named query\n */\nexport interface NamedQueryResult {\n /** name is the name of the query */\n name: string\n /** result is a groq query */\n result: resolveExpressionReturnType\n}\n\nconst TAGGED_TEMPLATE_ALLOW_LIST = ['groq']\nconst FUNCTION_WRAPPER_ALLOW_LIST = ['defineQuery']\n\n/**\n * resolveExpression takes a node and returns the resolved value of the expression.\n * @beta\n * @internal\n */\nexport function resolveExpression({\n node,\n file,\n scope,\n filename,\n resolver,\n babelConfig,\n params = [],\n fnArguments = [],\n}: {\n node: babelTypes.Node\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n params?: babelTypes.Node[]\n fnArguments?: babelTypes.Node[]\n}): resolveExpressionReturnType {\n debug(\n `Resolving node ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n if (\n babelTypes.isTaggedTemplateExpression(node) &&\n babelTypes.isIdentifier(node.tag) &&\n TAGGED_TEMPLATE_ALLOW_LIST.includes(node.tag.name)\n ) {\n return resolveExpression({\n node: node.quasi,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n\n if (babelTypes.isTemplateLiteral(node)) {\n const resolvedExpressions = node.expressions.map((expression) =>\n resolveExpression({\n node: expression,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n }),\n )\n return node.quasis\n .map((quasi, idx) => {\n return (quasi.value.cooked || '') + (resolvedExpressions[idx] || '')\n })\n .join('')\n }\n\n if (babelTypes.isLiteral(node)) {\n if (node.type === 'NullLiteral' || node.type === 'RegExpLiteral') {\n throw new Error(`Unsupported literal type: ${node.type}`)\n }\n\n return node.value.toString()\n }\n\n if (babelTypes.isIdentifier(node)) {\n return resolveIdentifier({\n node,\n scope,\n filename,\n file,\n resolver,\n fnArguments,\n babelConfig,\n params,\n })\n }\n\n if (babelTypes.isVariableDeclarator(node)) {\n if (!node.init) {\n throw new Error(`Unsupported variable declarator`)\n }\n\n return resolveExpression({\n node: node.init,\n fnArguments,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (\n babelTypes.isCallExpression(node) &&\n babelTypes.isIdentifier(node.callee) &&\n FUNCTION_WRAPPER_ALLOW_LIST.includes(node.callee.name)\n ) {\n return resolveExpression({\n node: node.arguments[0],\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n })\n }\n\n if (babelTypes.isCallExpression(node)) {\n return resolveCallExpression({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n fnArguments,\n })\n }\n\n if (\n babelTypes.isArrowFunctionExpression(node) ||\n babelTypes.isFunctionDeclaration(node) ||\n babelTypes.isFunctionExpression(node)\n ) {\n return resolveExpression({\n node: node.body,\n params: node.params,\n fnArguments,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (babelTypes.isNewExpression(node)) {\n return resolveExpression({\n node: node.callee,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (babelTypes.isImportDefaultSpecifier(node) || babelTypes.isImportSpecifier(node)) {\n return resolveImportSpecifier({node, file, scope, filename, resolver, babelConfig})\n }\n\n if (babelTypes.isAssignmentPattern(node)) {\n return resolveExpression({\n node: node.right,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n\n throw new Error(\n `Unsupported expression type: ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveIdentifier({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n fnArguments,\n params,\n}: {\n node: babelTypes.Identifier\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n fnArguments: babelTypes.Node[]\n params: babelTypes.Node[]\n}): resolveExpressionReturnType {\n const paramIndex = params.findIndex(\n (param) =>\n (babelTypes.isIdentifier(param) && node.name === param.name) ||\n (babelTypes.isAssignmentPattern(param) &&\n babelTypes.isIdentifier(param.left) &&\n node.name === param.left.name),\n )\n const argument = fnArguments[paramIndex]\n if (argument && babelTypes.isLiteral(argument)) {\n return resolveExpression({\n node: argument,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n const binding = scope.getBinding(node.name)\n if (binding) {\n if (babelTypes.isIdentifier(binding.path.node)) {\n const isSame = binding.path.node.name === node.name\n if (isSame) {\n throw new Error(\n `Could not resolve same identifier \"${node.name}\" in \"${filename}:${node.loc?.start.line}:${node.loc?.start.column}\"`,\n )\n }\n }\n return resolveExpression({\n node: binding.path.node,\n params,\n fnArguments,\n scope,\n filename,\n babelConfig,\n file,\n resolver,\n })\n }\n\n throw new Error(\n `Could not find binding for node \"${node.name}\" in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveCallExpression({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n}: {\n node: babelTypes.CallExpression\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n fnArguments: babelTypes.Node[]\n params: babelTypes.Node[]\n}): resolveExpressionReturnType {\n const {callee} = node\n return resolveExpression({\n node: callee,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n fnArguments: node.arguments,\n })\n}\n\nfunction resolveImportSpecifier({\n node,\n file,\n filename,\n resolver,\n babelConfig,\n}: {\n node: babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier | babelTypes.ExportSpecifier\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n}): resolveExpressionReturnType {\n let importDeclaration: babelTypes.ImportDeclaration | undefined\n traverse(file, {\n ImportDeclaration(n) {\n if (!babelTypes.isImportDeclaration(n.node)) {\n return\n }\n for (const specifier of n.node.specifiers) {\n if (babelTypes.isImportDefaultSpecifier(specifier)) {\n if (specifier.local.loc?.identifierName === node.local.name) {\n importDeclaration = n.node\n break\n }\n }\n if (specifier.local.name === node.local.name) {\n importDeclaration = n.node\n }\n }\n },\n })\n\n if (!importDeclaration) {\n throw new Error(`Could not find import declaration for ${node.local.name}`)\n }\n\n const importName = node.local.name // the name of the variable to import\n const importFileName = importDeclaration.source.value // the file to import from\n\n const importPath =\n importFileName.startsWith('./') || importFileName.startsWith('../')\n ? path.resolve(path.dirname(filename), importFileName)\n : importFileName\n\n const resolvedFile = resolver(importPath)\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let newScope: Scope | undefined\n traverse(tree, {\n Program(p) {\n newScope = p.scope\n },\n })\n if (!newScope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = newScope.getBinding(importName)\n if (binding) {\n return resolveExpression({\n node: binding.path.node,\n file: tree,\n scope: newScope,\n babelConfig,\n filename: resolvedFile,\n resolver,\n })\n }\n\n // It's not a global binding, but it might be a named export\n let namedExport: babelTypes.ExportNamedDeclaration | undefined\n let newImportName: string | undefined\n traverse(tree, {\n ExportDeclaration(p) {\n if (p.node.type === 'ExportNamedDeclaration') {\n for (const specifier of p.node.specifiers) {\n if (\n specifier.type === 'ExportSpecifier' &&\n specifier.exported.type === 'Identifier' &&\n specifier.exported.name === importName\n ) {\n namedExport = p.node\n newImportName = specifier.exported.name\n }\n }\n }\n },\n })\n\n if (namedExport && newImportName) {\n return resolveExportSpecifier({\n node: namedExport,\n importName: newImportName,\n filename: resolvedFile,\n resolver,\n babelConfig,\n })\n }\n\n throw new Error(`Could not find binding for import \"${importName}\" in ${importFileName}`)\n}\n\nfunction resolveExportSpecifier({\n node,\n importName,\n filename,\n babelConfig,\n resolver,\n}: {\n node: babelTypes.ExportNamedDeclaration\n importName: string\n filename: string\n babelConfig: TransformOptions\n resolver: NodeJS.RequireResolve\n}): resolveExpressionReturnType {\n if (!node.source) {\n throw new Error(`Could not find source for export \"${importName}\" in ${filename}`)\n }\n\n const importFileName = node.source.value\n const importPath = path.resolve(path.dirname(filename), importFileName)\n const resolvedFile = resolver(importPath)\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let newScope: Scope | undefined\n traverse(tree, {\n Program(p) {\n newScope = p.scope\n },\n })\n if (!newScope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = newScope.getBinding(importName)\n if (binding) {\n return resolveExpression({\n node: binding.path.node,\n file: tree,\n scope: newScope,\n filename: importFileName,\n babelConfig,\n resolver,\n })\n }\n\n throw new Error(`Could not find binding for export \"${importName}\" in ${importFileName}`)\n}\n","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'\nimport {type NamedQueryResult, resolveExpression} from './expressionResolvers'\nimport {parseSourceFile} from './parseSource'\n\nconst require = createRequire(__filename)\n\nconst groqTagName = 'groq'\nconst defineQueryFunctionName = 'defineQuery'\nconst groqModuleName = 'groq'\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): NamedQueryResult[] {\n const queries: NamedQueryResult[] = []\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\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 queryName = `${node.id.name}`\n const queryResult = resolveExpression({\n node: init,\n file,\n scope,\n babelConfig,\n filename,\n resolver,\n })\n\n queries.push({name: queryName, result: queryResult})\n }\n },\n })\n\n return 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","import createDebug from 'debug'\nimport {createMatchPath, loadConfig as loadTSConfig} from 'tsconfig-paths'\n\nconst debug = createDebug('sanity:codegen:moduleResolver')\n\n/**\n * This is a custom implementation of require.resolve that takes into account the paths\n * configuration in tsconfig.json. This is necessary if we want to resolve paths that are\n * custom defined in the tsconfig.json file.\n * Resolving here is best effort and might not work in all cases.\n * @beta\n */\nexport function getResolver(cwd?: string): NodeJS.RequireResolve {\n const tsConfig = loadTSConfig(cwd)\n\n if (tsConfig.resultType === 'failed') {\n debug('Could not load tsconfig, using default resolver: %s', tsConfig.message)\n return require.resolve\n }\n\n const matchPath = createMatchPath(\n tsConfig.absoluteBaseUrl,\n tsConfig.paths,\n tsConfig.mainFields,\n tsConfig.addMatchAll,\n )\n\n const resolve = function (request: string, options?: {paths?: string[]}): string {\n const found = matchPath(request)\n if (found !== undefined) {\n return require.resolve(found, options)\n }\n return require.resolve(request, options)\n }\n\n // wrap the resolve.path function to make it available.\n resolve.paths = (request: string): string[] | null => {\n return require.resolve.paths(request)\n }\n return resolve\n}\n","import fs from 'node:fs/promises'\n\nimport {type TransformOptions} from '@babel/core'\nimport createDebug from 'debug'\nimport glob from 'globby'\n\nimport {getBabelConfig} from '../getBabelConfig'\nimport {type NamedQueryResult} from './expressionResolvers'\nimport {findQueriesInSource} from './findQueriesInSource'\nimport {getResolver} from './moduleResolver'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ntype ResultQueries = {\n type: 'queries'\n filename: string\n queries: NamedQueryResult[]\n}\ntype ResultError = {\n type: 'error'\n error: Error\n filename: string\n}\n\n/**\n * findQueriesInPath takes a path or array of paths and returns all GROQ queries in the files.\n * @param path - The path or array of paths to search for queries\n * @param babelOptions - The babel configuration to use when parsing the source\n * @param resolver - A resolver function to use when resolving module imports\n * @returns An async generator that yields the results of the search\n * @beta\n * @internal\n */\nexport async function* findQueriesInPath({\n path,\n babelOptions = getBabelConfig(),\n resolver = getResolver(),\n}: {\n path: string | string[]\n babelOptions?: TransformOptions\n resolver?: NodeJS.RequireResolve\n}): AsyncGenerator<ResultQueries | ResultError> {\n const queryNames = new Set()\n // Holds all query names found in the source files\n debug(`Globing ${path}`)\n\n const stream = glob.stream(path, {\n absolute: false,\n ignore: ['**/node_modules/**'], // we never want to look in node_modules\n onlyFiles: true,\n })\n\n for await (const filename of stream) {\n if (typeof filename !== 'string') {\n continue\n }\n\n debug(`Found file \"${filename}\"`)\n try {\n const source = await fs.readFile(filename, 'utf8')\n const queries = findQueriesInSource(source, filename, babelOptions, resolver)\n // Check and error on duplicate query names, because we can't generate types with the same name.\n for (const query of queries) {\n if (queryNames.has(query.name)) {\n throw new Error(\n `Duplicate query name found: \"${query.name}\". Query names must be unique across all files.`,\n )\n }\n queryNames.add(query.name)\n }\n yield {type: 'queries', filename, queries}\n } catch (error) {\n debug(`Error in file \"${filename}\"`, error)\n yield {type: 'error', error, filename}\n }\n }\n}\n","import {type TransformOptions} from '@babel/core'\nimport register from '@babel/register'\n\nimport {getBabelConfig} from '../getBabelConfig'\n\n/**\n * Register Babel with the given options\n *\n * @param babelOptions - The options to use when registering Babel\n * @beta\n */\nexport function registerBabel(babelOptions?: TransformOptions): void {\n const options = babelOptions || getBabelConfig()\n\n register({...options, extensions: ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']})\n}\n","import {CodeGenerator} from '@babel/generator'\nimport * as t from '@babel/types'\nimport {\n type ArrayTypeNode,\n type DocumentSchemaType,\n type ObjectAttribute,\n type ObjectTypeNode,\n type SchemaType,\n type TypeDeclarationSchemaType,\n type TypeNode,\n type UnionTypeNode,\n} from 'groq-js'\n\nconst REFERENCE_SYMBOL_NAME = 'internalGroqTypeReferenceTo'\nconst ALL_SCHEMA_TYPES = 'AllSanitySchemaTypes'\n\ntype QueryWithTypeNode = {\n query: string\n typeNode: TypeNode\n}\n\n/**\n * A class used to generate TypeScript types from a given schema\n * @internal\n * @beta\n */\nexport class TypeGenerator {\n private generatedTypeName: Set<string> = new Set()\n private typeNameMap: Map<TypeNode | DocumentSchemaType | TypeDeclarationSchemaType, string> =\n new Map()\n\n private readonly schema: SchemaType\n\n constructor(schema: SchemaType) {\n this.schema = schema\n }\n\n /**\n * Generate TypeScript types for the given schema\n * @returns string\n * @internal\n * @beta\n */\n generateSchemaTypes(): string {\n const typeDeclarations: (t.TSTypeAliasDeclaration | t.ExportNamedDeclaration)[] = []\n\n const schemaNames = new Set<string>()\n this.schema.forEach((schema) => {\n const typeLiteral = this.getTypeNodeType(schema)\n\n const schemaName = this.getTypeName(schema.name, schema)\n schemaNames.add(schemaName)\n const typeAlias = t.tsTypeAliasDeclaration(t.identifier(schemaName), null, typeLiteral)\n\n typeDeclarations.push(t.exportNamedDeclaration(typeAlias))\n })\n\n typeDeclarations.push(\n t.exportNamedDeclaration(\n t.tsTypeAliasDeclaration(\n t.identifier(this.getTypeName(ALL_SCHEMA_TYPES)),\n null,\n t.tsUnionType(\n [...schemaNames].map((typeName) => t.tsTypeReference(t.identifier(typeName))),\n ),\n ),\n ),\n )\n\n // Generate TypeScript code from the AST nodes\n return typeDeclarations.map((decl) => new CodeGenerator(decl).generate().code).join('\\n\\n')\n }\n\n /**\n * Takes a identifier and a type node and generates a type alias for the type node.\n * @param identifierName - The name of the type to generated\n * @param typeNode - The type node to generate the type for\n * @returns\n * @internal\n * @beta\n */\n generateTypeNodeTypes(identifierName: string, typeNode: TypeNode): string {\n const type = this.getTypeNodeType(typeNode)\n\n const typeName = this.getTypeName(identifierName, typeNode)\n const typeAlias = t.tsTypeAliasDeclaration(t.identifier(typeName), null, type)\n\n return new CodeGenerator(t.exportNamedDeclaration(typeAlias)).generate().code.trim()\n }\n\n static generateKnownTypes(): string {\n const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword())\n typeOperator.operator = 'unique'\n\n const identifier = t.identifier(REFERENCE_SYMBOL_NAME)\n identifier.typeAnnotation = t.tsTypeAnnotation(typeOperator)\n\n const decleration = t.variableDeclaration('const', [t.variableDeclarator(identifier)])\n decleration.declare = true\n return new CodeGenerator(t.exportNamedDeclaration(decleration)).generate().code.trim()\n }\n\n /**\n * Takes a list of queries from the codebase and generates a type declaration\n * for SanityClient to consume.\n *\n * Note: only types that have previously been generated with `generateTypeNodeTypes`\n * will be included in the query map.\n *\n * @param queries - A list of queries to generate a type declaration for\n * @returns\n * @internal\n * @beta\n */\n generateQueryMap(queries: QueryWithTypeNode[]): string {\n const typesByQuerystring: {[query: string]: string[]} = {}\n\n for (const query of queries) {\n const name = this.typeNameMap.get(query.typeNode)\n if (!name) {\n continue\n }\n\n typesByQuerystring[query.query] ??= []\n typesByQuerystring[query.query].push(name)\n }\n\n const queryReturnInterface = t.tsInterfaceDeclaration(\n t.identifier('SanityQueries'),\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 declareModule = t.declareModule(\n t.stringLiteral('@sanity/client'),\n t.blockStatement([queryReturnInterface]),\n )\n\n const clientImport = t.importDeclaration([], t.stringLiteral('@sanity/client'))\n\n return new CodeGenerator(t.program([clientImport, declareModule])).generate().code.trim()\n }\n\n /**\n * Since we are sanitizing identifiers we migt end up with collisions. Ie there might be a type mux.video and muxVideo, both these\n * types would be sanityized into MuxVideo. To avoid this we keep track of the generated type names and add a index to the name.\n * When we reference a type we also keep track of the original name so we can reference the correct type later.\n */\n private getTypeName(\n name: string,\n typeNode?: TypeNode | DocumentSchemaType | TypeDeclarationSchemaType,\n ): string {\n const desiredName = uppercaseFirstLetter(sanitizeIdentifier(name))\n\n let generatedName = desiredName\n let i = 2\n while (this.generatedTypeName.has(generatedName)) {\n // add _ and a index and increment that index until we find a name that is not in the map\n generatedName = `${desiredName}_${i++}`\n }\n this.generatedTypeName.add(generatedName)\n if (typeNode) {\n this.typeNameMap.set(typeNode, generatedName)\n }\n\n return generatedName\n }\n\n private getTypeNodeType(\n typeNode: TypeNode | TypeDeclarationSchemaType | DocumentSchemaType,\n ): t.TSType {\n switch (typeNode.type) {\n case 'string': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.stringLiteral(typeNode.value))\n }\n return t.tsStringKeyword()\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 'boolean': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.booleanLiteral(typeNode.value))\n }\n return t.tsBooleanKeyword()\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n case 'document': {\n return this.generateDocumentType(typeNode)\n }\n case 'type': {\n return this.getTypeNodeType(typeNode.value)\n }\n case 'array': {\n return this.generateArrayTsType(typeNode)\n }\n case 'object': {\n return this.generateObjectTsType(typeNode)\n }\n case 'union': {\n return this.generateUnionTsType(typeNode)\n }\n case 'inline': {\n return t.tsTypeReference(\n t.identifier(uppercaseFirstLetter(sanitizeIdentifier(typeNode.name))),\n )\n }\n case 'null': {\n return t.tsNullKeyword()\n }\n\n default:\n // @ts-expect-error This should never happen\n throw new Error(`Type \"${typeNode.type}\" not found in schema`)\n }\n }\n\n // Helper function used to generate TS types for array type nodes.\n private generateArrayTsType(typeNode: ArrayTypeNode): t.TSTypeReference {\n const typeNodes = this.getTypeNodeType(typeNode.of)\n const arrayType = t.tsTypeReference(\n t.identifier('Array'),\n t.tsTypeParameterInstantiation([typeNodes]),\n )\n\n return arrayType\n }\n\n // Helper function used to generate TS types for object properties.\n private generateObjectProperty(key: string, attribute: ObjectAttribute): t.TSPropertySignature {\n const type = this.getTypeNodeType(attribute.value)\n const propertySignature = t.tsPropertySignature(\n t.identifier(sanitizeIdentifier(key)),\n t.tsTypeAnnotation(type),\n )\n propertySignature.optional = attribute.optional\n\n return propertySignature\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 Object.entries(typeNode.attributes).forEach(([key, attribute]) => {\n props.push(this.generateObjectProperty(key, attribute))\n })\n const rest = typeNode.rest\n if (rest !== undefined) {\n switch (rest.type) {\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n case 'object': {\n Object.entries(rest.attributes).forEach(([key, attribute]) => {\n props.push(this.generateObjectProperty(key, attribute))\n })\n break\n }\n case 'inline': {\n const referencedTypeNode = this.schema.find((schema) => schema.name === rest.name)\n if (referencedTypeNode === undefined) {\n const missing = t.tsUnknownKeyword()\n missing.trailingComments = [\n {\n type: 'CommentLine',\n value: ` Unable to locate the referenced type \"${rest.name}\" in schema`,\n },\n ]\n return missing\n }\n\n return t.tsIntersectionType([\n t.tsTypeLiteral(props),\n t.tsTypeReference(\n t.identifier(\n this.typeNameMap.get(referencedTypeNode) ||\n uppercaseFirstLetter(sanitizeIdentifier(rest.name)),\n ),\n ),\n ])\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 if (typeNode.dereferencesTo !== undefined) {\n const derefType = t.tsPropertySignature(\n t.identifier(REFERENCE_SYMBOL_NAME),\n t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo))),\n )\n derefType.computed = true\n derefType.optional = true\n props.push(derefType)\n }\n return t.tsTypeLiteral(props)\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) {\n return t.tsNeverKeyword()\n }\n if (typeNode.of.length === 1) {\n return this.getTypeNodeType(typeNode.of[0])\n }\n\n const typeNodes = typeNode.of.map((node) => this.getTypeNodeType(node))\n\n return t.tsUnionType(typeNodes)\n }\n\n // Helper function used to generate TS types for document type nodes.\n private generateDocumentType(document: DocumentSchemaType): t.TSType {\n const props = Object.entries(document.attributes).map(([key, node]) =>\n this.generateObjectProperty(key, node),\n )\n\n return t.tsTypeLiteral(props)\n }\n}\nfunction uppercaseFirstLetter(input: string): string {\n return input.charAt(0).toUpperCase() + input.slice(1)\n}\n\nfunction sanitizeIdentifier(input: string): string {\n return `${input.replace(/^\\d/, '_').replace(/[^$\\w]+(.)/g, (_, char) => char.toUpperCase())}`\n}\n"],"names":["path","parse","debug","babelTypes","require","traverse","loadTSConfig","resolve","fs"],"mappings":";;;;;;;;;;;;;;;AAKa,MAAA,kBAAkB,EAAE,OAAO;AAAA,EACtC,MAAM,EACH,OAAO,EACP,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,EACtB,QAAQ;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AAAA,EACH,QAAQ,EAAE,SAAS,QAAQ,eAAe;AAAA,EAC1C,WAAW,EAAE,SAAS,QAAQ,mBAAmB;AAAA,EACjD,qBAAqB,EAAE,QAAQ,EAAE,QAAQ,EAAI;AAAA,EAC7C,uBAAuB,EAAE,QAAQ,EAAE,QAAQ,EAAK;AAClD,CAAC;AAID,eAAsB,WAAWA,OAAsC;AACjE,MAAA;AACI,UAAA,UAAU,MAAM,SAASA,OAAM,OAAO,GACtC,OAAO,MAAM,MAAM,OAAO;AACzB,WAAA,gBAAgB,WAAW,IAAI;AAAA,WAC/B,OAAO;AACd,QAAI,iBAAiB,EAAE;AACrB,YAAM,IAAI,MAAM;AAAA,GAA0B,MAAM,OAAO,IAAI,CAAC,QAAQ,IAAI,OAAO,EAAE,KAAK;AAAA,CAAI,CAAC,EAAE;AAE3F,QAAA,OAAO,SAAU,YAAY,UAAU,QAAQ,UAAU,SAAS,MAAM,SAAS;AAC5E,aAAA,gBAAgB,MAAM,CAAA,CAAE;AAG3B,UAAA;AAAA,EACR;AACF;AC1BA,eAAsB,WAAWA,OAAmC;AAClE,QAAM,UAAU,MAAM,SAASA,OAAM,OAAO;AACrC,SAAA,KAAK,MAAM,O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QAAA,SAAS,mBAAmB,QAAW;AACzC,YAAM,YAAY,EAAE;AAAA,QAClB,EAAE,WAAW,qBAAqB;AAAA,QAClC,EAAE,iBAAiB,EAAE,cAAc,EAAE,cAAc,SAAS,cAAc,CAAC,CAAC;AAAA,MAAA;AAE9E,gBAAU,WAAW,IACrB,UAAU,WAAW,IACrB,MAAM,KAAK,SAAS;AAAA,IACtB;AACO,WAAA,EAAE,cAAc,KAAK;AAAA,EAC9B;AAAA;AAAA,EAGQ,oBAAoB,UAAmC;AACzD,QAAA,SAAS,GAAG,WAAW;AACzB,aAAO,EAAE;AAEP,QAAA,SAAS,GAAG,WAAW;AACzB,aAAO,KAAK,gBAAgB,SAAS,GAAG,CAAC,CAAC;AAGtC,UAAA,YAAY,SAAS,GAAG,IAAI,CAAC,SAAS,KAAK,gBAAgB,IAAI,CAAC;AAE/D,WAAA,EAAE,YAAY,SAAS;AAAA,EAChC;AAAA;AAAA,EAGQ,qBAAqB,UAAwC;AACnE,UAAM,QAAQ,OAAO,QAAQ,SAAS,UAAU,EAAE;AAAA,MAAI,CAAC,CAAC,KAAK,IAAI,MAC/D,KAAK,uBAAuB,KAAK,IAAI;AAAA,IAAA;AAGhC,WAAA,EAAE,cAAc,KAAK;AAAA,EAC9B;AACF;AACA,SAAS,qBAAqB,OAAuB;AAC5C,SAAA,MAAM,OAAO,CAAC,EAAE,gBAAgB,MAAM,MAAM,CAAC;AACtD;AAEA,SAAS,mBAAmB,OAAuB;AACjD,SAAO,GAAG,MAAM,QAAQ,OAAO,GAAG,EAAE,QAAQ,eAAe,CAAC,GAAG,SAAS,KAAK,YAAa,CAAA,CAAC;AAC7F;"}
|
|
1
|
+
{"version":3,"file":"index.esm.js","sources":["../src/readConfig.ts","../src/readSchema.ts","../src/safeParseQuery.ts","../src/getBabelConfig.ts","../src/typescript/parseSource.ts","../src/typescript/expressionResolvers.ts","../src/typescript/findQueriesInSource.ts","../src/typescript/moduleResolver.ts","../src/typescript/findQueriesInPath.ts","../src/typescript/registerBabel.ts","../src/typescript/typeGenerator.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport * as json5 from 'json5'\nimport * as z from 'zod'\n\nexport const configDefintion = z.object({\n path: z\n .string()\n .or(z.array(z.string()))\n .default([\n './src/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n './app/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n ]),\n schema: z.string().default('./schema.json'),\n generates: z.string().default('./sanity.types.ts'),\n formatGeneratedCode: z.boolean().default(true),\n overloadClientMethods: z.boolean().default(false),\n})\n\nexport type CodegenConfig = z.infer<typeof configDefintion>\n\nexport async function readConfig(path: string): Promise<CodegenConfig> {\n try {\n const content = await readFile(path, 'utf-8')\n const json = json5.parse(content)\n return configDefintion.parseAsync(json)\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(`Error in config file\\n ${error.errors.map((err) => err.message).join('\\n')}`)\n }\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return configDefintion.parse({})\n }\n\n throw error\n }\n}\n","import {readFile} from 'node:fs/promises'\n\nimport {type SchemaType} from 'groq-js'\n\n/**\n * Read a schema from a given path\n * @param path - The path to the schema\n * @returns The schema\n * @internal\n * @beta\n **/\nexport async function readSchema(path: string): Promise<SchemaType> {\n const content = await readFile(path, 'utf-8')\n return JSON.parse(content) // todo: ZOD validation?\n}\n","import {parse} from 'groq-js'\n\n/**\n * safeParseQuery parses a GROQ query string, but first attempts to extract any parameters used in slices. This method is _only_\n * intended for use in type generation where we don't actually execute the parsed AST on a dataset, and should not be used elsewhere.\n * @internal\n */\nexport function safeParseQuery(query: string) {\n const params: Record<string, unknown> = {}\n\n for (const param of extractSliceParams(query)) {\n params[param] = 0 // we don't care about the value, just the type\n }\n return parse(query, {params})\n}\n\n/**\n * Finds occurences of `[($start|{number})..($end|{number})]` in a query string and returns the start and end values, and return\n * the names of the start and end variables.\n * @internal\n */\nexport function* extractSliceParams(query: string): Generator<string> {\n const sliceRegex = /\\[(\\$(\\w+)|\\d)\\.\\.\\.?(\\$(\\w+)|\\d)\\]/g\n const matches = query.matchAll(sliceRegex)\n if (!matches) {\n return\n }\n const params = new Set<string>()\n for (const match of matches) {\n const start = match[1] === `$${match[2]}` ? match[2] : null\n if (start !== null) {\n yield start\n }\n const end = match[3] === `$${match[4]}` ? match[4] : null\n if (end !== null) {\n yield end\n }\n }\n}\n","import {existsSync} from 'node:fs'\nimport {join, resolve} from 'node:path'\n\nimport {type TransformOptions} from '@babel/core'\n\n/**\n * Because of bundlers and compilers, knowing the exact path the babel configuration will be\n * located at post - build is not always trivial. We traverse from the current directory upwards\n * until we find the first `babel.config.json` and use that path.\n *\n * @param path - The path to start looking for the babel configuration\n * @returns The path to the `babel.config.json` file\n * @internal\n */\nexport function findBabelConfig(path: string): string {\n const configPath = join(path, 'babel.config.json')\n if (existsSync(configPath)) {\n return configPath\n }\n\n const parent = resolve(join(path, '..'))\n if (parent && parent !== path) {\n return findBabelConfig(parent)\n }\n\n throw new Error('Could not find `babel.config.json` in @sanity/codegen')\n}\n\n/**\n * Get the default babel configuration for `@sanity/codegen`\n *\n * @param path - The path to start looking for the babel configuration. Defaults to `__dirname`\n * @returns A babel configuration object\n * @internal\n */\nexport function getBabelConfig(path?: string): TransformOptions {\n const configPath = findBabelConfig(path || __dirname)\n return {extends: configPath}\n}\n","import {parse, type TransformOptions} from '@babel/core'\nimport type * as babelTypes from '@babel/types'\n\n// helper function to parse a source file\nexport function parseSourceFile(\n source: string,\n filename: string,\n babelOptions: TransformOptions,\n): babelTypes.File {\n const result = parse(source, {\n ...babelOptions,\n filename,\n })\n\n if (!result) {\n throw new Error(`Failed to parse ${filename}`)\n }\n\n return result\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type TransformOptions} from '@babel/core'\nimport traverse, {type Scope} from '@babel/traverse'\nimport * as babelTypes from '@babel/types'\nimport createDebug from 'debug'\n\nimport {parseSourceFile} from './parseSource'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ntype resolveExpressionReturnType = string\n\n/**\n * NamedQueryResult is a result of a named query\n */\nexport interface NamedQueryResult {\n /** name is the name of the query */\n name: string\n /** result is a groq query */\n result: resolveExpressionReturnType\n}\n\nconst TAGGED_TEMPLATE_ALLOW_LIST = ['groq']\nconst FUNCTION_WRAPPER_ALLOW_LIST = ['defineQuery']\n\n/**\n * resolveExpression takes a node and returns the resolved value of the expression.\n * @beta\n * @internal\n */\nexport function resolveExpression({\n node,\n file,\n scope,\n filename,\n resolver,\n babelConfig,\n params = [],\n fnArguments = [],\n}: {\n node: babelTypes.Node\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n params?: babelTypes.Node[]\n fnArguments?: babelTypes.Node[]\n}): resolveExpressionReturnType {\n debug(\n `Resolving node ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n if (\n babelTypes.isTaggedTemplateExpression(node) &&\n babelTypes.isIdentifier(node.tag) &&\n TAGGED_TEMPLATE_ALLOW_LIST.includes(node.tag.name)\n ) {\n return resolveExpression({\n node: node.quasi,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n\n if (babelTypes.isTemplateLiteral(node)) {\n const resolvedExpressions = node.expressions.map((expression) =>\n resolveExpression({\n node: expression,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n }),\n )\n return node.quasis\n .map((quasi, idx) => {\n return (quasi.value.cooked || '') + (resolvedExpressions[idx] || '')\n })\n .join('')\n }\n\n if (babelTypes.isLiteral(node)) {\n if (node.type === 'NullLiteral' || node.type === 'RegExpLiteral') {\n throw new Error(`Unsupported literal type: ${node.type}`)\n }\n\n return node.value.toString()\n }\n\n if (babelTypes.isIdentifier(node)) {\n return resolveIdentifier({\n node,\n scope,\n filename,\n file,\n resolver,\n fnArguments,\n babelConfig,\n params,\n })\n }\n\n if (babelTypes.isVariableDeclarator(node)) {\n if (!node.init) {\n throw new Error(`Unsupported variable declarator`)\n }\n\n return resolveExpression({\n node: node.init,\n fnArguments,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (\n babelTypes.isCallExpression(node) &&\n babelTypes.isIdentifier(node.callee) &&\n FUNCTION_WRAPPER_ALLOW_LIST.includes(node.callee.name)\n ) {\n return resolveExpression({\n node: node.arguments[0],\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n })\n }\n\n if (babelTypes.isCallExpression(node)) {\n return resolveCallExpression({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n fnArguments,\n })\n }\n\n if (\n babelTypes.isArrowFunctionExpression(node) ||\n babelTypes.isFunctionDeclaration(node) ||\n babelTypes.isFunctionExpression(node)\n ) {\n return resolveExpression({\n node: node.body,\n params: node.params,\n fnArguments,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (babelTypes.isNewExpression(node)) {\n return resolveExpression({\n node: node.callee,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (babelTypes.isImportDefaultSpecifier(node) || babelTypes.isImportSpecifier(node)) {\n return resolveImportSpecifier({node, file, scope, filename, resolver, babelConfig})\n }\n\n if (babelTypes.isAssignmentPattern(node)) {\n return resolveExpression({\n node: node.right,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n\n throw new Error(\n `Unsupported expression type: ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveIdentifier({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n fnArguments,\n params,\n}: {\n node: babelTypes.Identifier\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n fnArguments: babelTypes.Node[]\n params: babelTypes.Node[]\n}): resolveExpressionReturnType {\n const paramIndex = params.findIndex(\n (param) =>\n (babelTypes.isIdentifier(param) && node.name === param.name) ||\n (babelTypes.isAssignmentPattern(param) &&\n babelTypes.isIdentifier(param.left) &&\n node.name === param.left.name),\n )\n const argument = fnArguments[paramIndex]\n if (argument && babelTypes.isLiteral(argument)) {\n return resolveExpression({\n node: argument,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n const binding = scope.getBinding(node.name)\n if (binding) {\n if (babelTypes.isIdentifier(binding.path.node)) {\n const isSame = binding.path.node.name === node.name\n if (isSame) {\n throw new Error(\n `Could not resolve same identifier \"${node.name}\" in \"${filename}:${node.loc?.start.line}:${node.loc?.start.column}\"`,\n )\n }\n }\n return resolveExpression({\n node: binding.path.node,\n params,\n fnArguments,\n scope,\n filename,\n babelConfig,\n file,\n resolver,\n })\n }\n\n throw new Error(\n `Could not find binding for node \"${node.name}\" in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveCallExpression({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n}: {\n node: babelTypes.CallExpression\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n fnArguments: babelTypes.Node[]\n params: babelTypes.Node[]\n}): resolveExpressionReturnType {\n const {callee} = node\n return resolveExpression({\n node: callee,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n fnArguments: node.arguments,\n })\n}\n\nfunction resolveImportSpecifier({\n node,\n file,\n filename,\n resolver,\n babelConfig,\n}: {\n node: babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier | babelTypes.ExportSpecifier\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n}): resolveExpressionReturnType {\n let importDeclaration: babelTypes.ImportDeclaration | undefined\n traverse(file, {\n ImportDeclaration(n) {\n if (!babelTypes.isImportDeclaration(n.node)) {\n return\n }\n for (const specifier of n.node.specifiers) {\n if (babelTypes.isImportDefaultSpecifier(specifier)) {\n if (specifier.local.loc?.identifierName === node.local.name) {\n importDeclaration = n.node\n break\n }\n }\n if (specifier.local.name === node.local.name) {\n importDeclaration = n.node\n }\n }\n },\n })\n\n if (!importDeclaration) {\n throw new Error(`Could not find import declaration for ${node.local.name}`)\n }\n\n const importName = node.local.name // the name of the variable to import\n const importFileName = importDeclaration.source.value // the file to import from\n\n const importPath =\n importFileName.startsWith('./') || importFileName.startsWith('../')\n ? path.resolve(path.dirname(filename), importFileName)\n : importFileName\n\n const resolvedFile = resolver(importPath)\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let newScope: Scope | undefined\n traverse(tree, {\n Program(p) {\n newScope = p.scope\n },\n })\n if (!newScope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = newScope.getBinding(importName)\n if (binding) {\n return resolveExpression({\n node: binding.path.node,\n file: tree,\n scope: newScope,\n babelConfig,\n filename: resolvedFile,\n resolver,\n })\n }\n\n // It's not a global binding, but it might be a named export\n let namedExport: babelTypes.ExportNamedDeclaration | undefined\n let newImportName: string | undefined\n traverse(tree, {\n ExportDeclaration(p) {\n if (p.node.type === 'ExportNamedDeclaration') {\n for (const specifier of p.node.specifiers) {\n if (\n specifier.type === 'ExportSpecifier' &&\n specifier.exported.type === 'Identifier' &&\n specifier.exported.name === importName\n ) {\n namedExport = p.node\n newImportName = specifier.exported.name\n }\n }\n }\n },\n })\n\n if (namedExport && newImportName) {\n return resolveExportSpecifier({\n node: namedExport,\n importName: newImportName,\n filename: resolvedFile,\n resolver,\n babelConfig,\n })\n }\n\n throw new Error(`Could not find binding for import \"${importName}\" in ${importFileName}`)\n}\n\nfunction resolveExportSpecifier({\n node,\n importName,\n filename,\n babelConfig,\n resolver,\n}: {\n node: babelTypes.ExportNamedDeclaration\n importName: string\n filename: string\n babelConfig: TransformOptions\n resolver: NodeJS.RequireResolve\n}): resolveExpressionReturnType {\n if (!node.source) {\n throw new Error(`Could not find source for export \"${importName}\" in ${filename}`)\n }\n\n const importFileName = node.source.value\n const importPath = path.resolve(path.dirname(filename), importFileName)\n const resolvedFile = resolver(importPath)\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let newScope: Scope | undefined\n traverse(tree, {\n Program(p) {\n newScope = p.scope\n },\n })\n if (!newScope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = newScope.getBinding(importName)\n if (binding) {\n return resolveExpression({\n node: binding.path.node,\n file: tree,\n scope: newScope,\n filename: importFileName,\n babelConfig,\n resolver,\n })\n }\n\n throw new Error(`Could not find binding for export \"${importName}\" in ${importFileName}`)\n}\n","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'\nimport {type NamedQueryResult, resolveExpression} from './expressionResolvers'\nimport {parseSourceFile} from './parseSource'\n\nconst require = createRequire(__filename)\n\nconst groqTagName = 'groq'\nconst defineQueryFunctionName = 'defineQuery'\nconst groqModuleName = 'groq'\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): NamedQueryResult[] {\n const queries: NamedQueryResult[] = []\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\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 queryName = `${node.id.name}`\n const queryResult = resolveExpression({\n node: init,\n file,\n scope,\n babelConfig,\n filename,\n resolver,\n })\n\n queries.push({name: queryName, result: queryResult})\n }\n },\n })\n\n return 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","import createDebug from 'debug'\nimport {createMatchPath, loadConfig as loadTSConfig} from 'tsconfig-paths'\n\nconst debug = createDebug('sanity:codegen:moduleResolver')\n\n/**\n * This is a custom implementation of require.resolve that takes into account the paths\n * configuration in tsconfig.json. This is necessary if we want to resolve paths that are\n * custom defined in the tsconfig.json file.\n * Resolving here is best effort and might not work in all cases.\n * @beta\n */\nexport function getResolver(cwd?: string): NodeJS.RequireResolve {\n const tsConfig = loadTSConfig(cwd)\n\n if (tsConfig.resultType === 'failed') {\n debug('Could not load tsconfig, using default resolver: %s', tsConfig.message)\n return require.resolve\n }\n\n const matchPath = createMatchPath(\n tsConfig.absoluteBaseUrl,\n tsConfig.paths,\n tsConfig.mainFields,\n tsConfig.addMatchAll,\n )\n\n const resolve = function (request: string, options?: {paths?: string[]}): string {\n const found = matchPath(request)\n if (found !== undefined) {\n return require.resolve(found, options)\n }\n return require.resolve(request, options)\n }\n\n // wrap the resolve.path function to make it available.\n resolve.paths = (request: string): string[] | null => {\n return require.resolve.paths(request)\n }\n return resolve\n}\n","import fs from 'node:fs/promises'\n\nimport {type TransformOptions} from '@babel/core'\nimport createDebug from 'debug'\nimport glob from 'globby'\n\nimport {getBabelConfig} from '../getBabelConfig'\nimport {type NamedQueryResult} from './expressionResolvers'\nimport {findQueriesInSource} from './findQueriesInSource'\nimport {getResolver} from './moduleResolver'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ntype ResultQueries = {\n type: 'queries'\n filename: string\n queries: NamedQueryResult[]\n}\ntype ResultError = {\n type: 'error'\n error: Error\n filename: string\n}\n\n/**\n * findQueriesInPath takes a path or array of paths and returns all GROQ queries in the files.\n * @param path - The path or array of paths to search for queries\n * @param babelOptions - The babel configuration to use when parsing the source\n * @param resolver - A resolver function to use when resolving module imports\n * @returns An async generator that yields the results of the search\n * @beta\n * @internal\n */\nexport async function* findQueriesInPath({\n path,\n babelOptions = getBabelConfig(),\n resolver = getResolver(),\n}: {\n path: string | string[]\n babelOptions?: TransformOptions\n resolver?: NodeJS.RequireResolve\n}): AsyncGenerator<ResultQueries | ResultError> {\n const queryNames = new Set()\n // Holds all query names found in the source files\n debug(`Globing ${path}`)\n\n const stream = glob.stream(path, {\n absolute: false,\n ignore: ['**/node_modules/**'], // we never want to look in node_modules\n onlyFiles: true,\n })\n\n for await (const filename of stream) {\n if (typeof filename !== 'string') {\n continue\n }\n\n debug(`Found file \"${filename}\"`)\n try {\n const source = await fs.readFile(filename, 'utf8')\n const queries = findQueriesInSource(source, filename, babelOptions, resolver)\n // Check and error on duplicate query names, because we can't generate types with the same name.\n for (const query of queries) {\n if (queryNames.has(query.name)) {\n throw new Error(\n `Duplicate query name found: \"${query.name}\". Query names must be unique across all files.`,\n )\n }\n queryNames.add(query.name)\n }\n yield {type: 'queries', filename, queries}\n } catch (error) {\n debug(`Error in file \"${filename}\"`, error)\n yield {type: 'error', error, filename}\n }\n }\n}\n","import {type TransformOptions} from '@babel/core'\nimport register from '@babel/register'\n\nimport {getBabelConfig} from '../getBabelConfig'\n\n/**\n * Register Babel with the given options\n *\n * @param babelOptions - The options to use when registering Babel\n * @beta\n */\nexport function registerBabel(babelOptions?: TransformOptions): void {\n const options = babelOptions || getBabelConfig()\n\n register({...options, extensions: ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']})\n}\n","import {CodeGenerator} from '@babel/generator'\nimport * as t from '@babel/types'\nimport {\n type ArrayTypeNode,\n type DocumentSchemaType,\n type ObjectAttribute,\n type ObjectTypeNode,\n type SchemaType,\n type TypeDeclarationSchemaType,\n type TypeNode,\n type UnionTypeNode,\n} from 'groq-js'\n\nconst REFERENCE_SYMBOL_NAME = 'internalGroqTypeReferenceTo'\nconst ALL_SCHEMA_TYPES = 'AllSanitySchemaTypes'\n\ntype QueryWithTypeNode = {\n query: string\n typeNode: TypeNode\n}\n\n/**\n * A class used to generate TypeScript types from a given schema\n * @internal\n * @beta\n */\nexport class TypeGenerator {\n private generatedTypeName: Set<string> = new Set()\n private typeNameMap: Map<TypeNode | DocumentSchemaType | TypeDeclarationSchemaType, string> =\n new Map()\n\n private readonly schema: SchemaType\n\n constructor(schema: SchemaType) {\n this.schema = schema\n }\n\n /**\n * Generate TypeScript types for the given schema\n * @returns string\n * @internal\n * @beta\n */\n generateSchemaTypes(): string {\n const typeDeclarations: (t.TSTypeAliasDeclaration | t.ExportNamedDeclaration)[] = []\n\n const schemaNames = new Set<string>()\n this.schema.forEach((schema) => {\n const typeLiteral = this.getTypeNodeType(schema)\n\n const schemaName = this.getTypeName(schema.name, schema)\n schemaNames.add(schemaName)\n const typeAlias = t.tsTypeAliasDeclaration(t.identifier(schemaName), null, typeLiteral)\n\n typeDeclarations.push(t.exportNamedDeclaration(typeAlias))\n })\n\n typeDeclarations.push(\n t.exportNamedDeclaration(\n t.tsTypeAliasDeclaration(\n t.identifier(this.getTypeName(ALL_SCHEMA_TYPES)),\n null,\n t.tsUnionType(\n [...schemaNames].map((typeName) => t.tsTypeReference(t.identifier(typeName))),\n ),\n ),\n ),\n )\n\n // Generate TypeScript code from the AST nodes\n return typeDeclarations.map((decl) => new CodeGenerator(decl).generate().code).join('\\n\\n')\n }\n\n /**\n * Takes a identifier and a type node and generates a type alias for the type node.\n * @param identifierName - The name of the type to generated\n * @param typeNode - The type node to generate the type for\n * @returns\n * @internal\n * @beta\n */\n generateTypeNodeTypes(identifierName: string, typeNode: TypeNode): string {\n const type = this.getTypeNodeType(typeNode)\n\n const typeName = this.getTypeName(identifierName, typeNode)\n const typeAlias = t.tsTypeAliasDeclaration(t.identifier(typeName), null, type)\n\n return new CodeGenerator(t.exportNamedDeclaration(typeAlias)).generate().code.trim()\n }\n\n static generateKnownTypes(): string {\n const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword())\n typeOperator.operator = 'unique'\n\n const identifier = t.identifier(REFERENCE_SYMBOL_NAME)\n identifier.typeAnnotation = t.tsTypeAnnotation(typeOperator)\n\n const decleration = t.variableDeclaration('const', [t.variableDeclarator(identifier)])\n decleration.declare = true\n return new CodeGenerator(t.exportNamedDeclaration(decleration)).generate().code.trim()\n }\n\n /**\n * Takes a list of queries from the codebase and generates a type declaration\n * for SanityClient to consume.\n *\n * Note: only types that have previously been generated with `generateTypeNodeTypes`\n * will be included in the query map.\n *\n * @param queries - A list of queries to generate a type declaration for\n * @returns\n * @internal\n * @beta\n */\n generateQueryMap(queries: QueryWithTypeNode[]): string {\n const typesByQuerystring: {[query: string]: string[]} = {}\n\n for (const query of queries) {\n const name = this.typeNameMap.get(query.typeNode)\n if (!name) {\n continue\n }\n\n typesByQuerystring[query.query] ??= []\n typesByQuerystring[query.query].push(name)\n }\n\n const queryReturnInterface = t.tsInterfaceDeclaration(\n t.identifier('SanityQueries'),\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 declareModule = t.declareModule(\n t.stringLiteral('@sanity/client'),\n t.blockStatement([queryReturnInterface]),\n )\n\n const clientImport = t.importDeclaration([], t.stringLiteral('@sanity/client'))\n\n return new CodeGenerator(t.program([clientImport, declareModule])).generate().code.trim()\n }\n\n /**\n * Since we are sanitizing identifiers we migt end up with collisions. Ie there might be a type mux.video and muxVideo, both these\n * types would be sanityized into MuxVideo. To avoid this we keep track of the generated type names and add a index to the name.\n * When we reference a type we also keep track of the original name so we can reference the correct type later.\n */\n private getTypeName(\n name: string,\n typeNode?: TypeNode | DocumentSchemaType | TypeDeclarationSchemaType,\n ): string {\n const desiredName = uppercaseFirstLetter(sanitizeIdentifier(name))\n\n let generatedName = desiredName\n let i = 2\n while (this.generatedTypeName.has(generatedName)) {\n // add _ and a index and increment that index until we find a name that is not in the map\n generatedName = `${desiredName}_${i++}`\n }\n this.generatedTypeName.add(generatedName)\n if (typeNode) {\n this.typeNameMap.set(typeNode, generatedName)\n }\n\n return generatedName\n }\n\n private getTypeNodeType(\n typeNode: TypeNode | TypeDeclarationSchemaType | DocumentSchemaType,\n ): t.TSType {\n switch (typeNode.type) {\n case 'string': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.stringLiteral(typeNode.value))\n }\n return t.tsStringKeyword()\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 'boolean': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.booleanLiteral(typeNode.value))\n }\n return t.tsBooleanKeyword()\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n case 'document': {\n return this.generateDocumentType(typeNode)\n }\n case 'type': {\n return this.getTypeNodeType(typeNode.value)\n }\n case 'array': {\n return this.generateArrayTsType(typeNode)\n }\n case 'object': {\n return this.generateObjectTsType(typeNode)\n }\n case 'union': {\n return this.generateUnionTsType(typeNode)\n }\n case 'inline': {\n return t.tsTypeReference(\n t.identifier(uppercaseFirstLetter(sanitizeIdentifier(typeNode.name))),\n )\n }\n case 'null': {\n return t.tsNullKeyword()\n }\n\n default:\n // @ts-expect-error This should never happen\n throw new Error(`Type \"${typeNode.type}\" not found in schema`)\n }\n }\n\n // Helper function used to generate TS types for array type nodes.\n private generateArrayTsType(typeNode: ArrayTypeNode): t.TSTypeReference {\n const typeNodes = this.getTypeNodeType(typeNode.of)\n const arrayType = t.tsTypeReference(\n t.identifier('Array'),\n t.tsTypeParameterInstantiation([typeNodes]),\n )\n\n return arrayType\n }\n\n // Helper function used to generate TS types for object properties.\n private generateObjectProperty(key: string, attribute: ObjectAttribute): t.TSPropertySignature {\n const type = this.getTypeNodeType(attribute.value)\n const propertySignature = t.tsPropertySignature(\n t.identifier(sanitizeIdentifier(key)),\n t.tsTypeAnnotation(type),\n )\n propertySignature.optional = attribute.optional\n\n return propertySignature\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 Object.entries(typeNode.attributes).forEach(([key, attribute]) => {\n props.push(this.generateObjectProperty(key, attribute))\n })\n const rest = typeNode.rest\n if (rest !== undefined) {\n switch (rest.type) {\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n case 'object': {\n Object.entries(rest.attributes).forEach(([key, attribute]) => {\n props.push(this.generateObjectProperty(key, attribute))\n })\n break\n }\n case 'inline': {\n const referencedTypeNode = this.schema.find((schema) => schema.name === rest.name)\n if (referencedTypeNode === undefined) {\n const missing = t.tsUnknownKeyword()\n missing.trailingComments = [\n {\n type: 'CommentLine',\n value: ` Unable to locate the referenced type \"${rest.name}\" in schema`,\n },\n ]\n return missing\n }\n\n return t.tsIntersectionType([\n t.tsTypeLiteral(props),\n t.tsTypeReference(\n t.identifier(\n this.typeNameMap.get(referencedTypeNode) ||\n uppercaseFirstLetter(sanitizeIdentifier(rest.name)),\n ),\n ),\n ])\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 if (typeNode.dereferencesTo !== undefined) {\n const derefType = t.tsPropertySignature(\n t.identifier(REFERENCE_SYMBOL_NAME),\n t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo))),\n )\n derefType.computed = true\n derefType.optional = true\n props.push(derefType)\n }\n return t.tsTypeLiteral(props)\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) {\n return t.tsNeverKeyword()\n }\n if (typeNode.of.length === 1) {\n return this.getTypeNodeType(typeNode.of[0])\n }\n\n const typeNodes = typeNode.of.map((node) => this.getTypeNodeType(node))\n\n return t.tsUnionType(typeNodes)\n }\n\n // Helper function used to generate TS types for document type nodes.\n private generateDocumentType(document: DocumentSchemaType): t.TSType {\n const props = Object.entries(document.attributes).map(([key, node]) =>\n this.generateObjectProperty(key, node),\n )\n\n return t.tsTypeLiteral(props)\n }\n}\nfunction uppercaseFirstLetter(input: string): string {\n return input.charAt(0).toUpperCase() + input.slice(1)\n}\n\nfunction sanitizeIdentifier(input: string): string {\n return `${input.replace(/^\\d/, '_').replace(/[^$\\w]+(.)/g, (_, char) => char.toUpperCase())}`\n}\n"],"names":["path","parse","debug","babelTypes","require","traverse","loadTSConfig","resolve","fs"],"mappings":";;;;;;;;;;;;;;;AAKa,MAAA,kBAAkB,EAAE,OAAO;AAAA,EACtC,MAAM,EACH,OAAO,EACP,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,EACtB,QAAQ;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AAAA,EACH,QAAQ,EAAE,SAAS,QAAQ,eAAe;AAAA,EAC1C,WAAW,EAAE,SAAS,QAAQ,mBAAmB;AAAA,EACjD,qBAAqB,EAAE,QAAQ,EAAE,QAAQ,EAAI;AAAA,EAC7C,uBAAuB,EAAE,QAAQ,EAAE,QAAQ,EAAK;AAClD,CAAC;AAID,eAAsB,WAAWA,OAAsC;AACjE,MAAA;AACI,UAAA,UAAU,MAAM,SAASA,OAAM,OAAO,GACtC,OAAO,MAAM,MAAM,OAAO;AACzB,WAAA,gBAAgB,WAAW,IAAI;AAAA,WAC/B,OAAO;AACd,QAAI,iBAAiB,EAAE;AACrB,YAAM,IAAI,MAAM;AAAA,GAA0B,MAAM,OAAO,IAAI,CAAC,QAAQ,IAAI,OAAO,EAAE,KAAK;AAAA,CAAI,CAAC,EAAE;AAE3F,QAAA,OAAO,SAAU,YAAY,UAAU,QAAQ,UAAU,SAAS,MAAM,SAAS;AAC5E,aAAA,gBAAgB,MAAM,CAAA,CAAE;AAG3B,UAAA;AAAA,EACR;AACF;AC1BA,eAAsB,WAAWA,OAAmC;AAClE,QAAM,UAAU,MAAM,SAASA,OAAM,OAAO;AACrC,SAAA,KAAK,MAAM,OAAO;AAC3B;ACPO,SAAS,eAAe,OAAe;AAC5C,QAAM,SAAkC,CAAA;AAE7B,aAAA,SAAS,mBAAmB,KAAK;AAC1C,WAAO,KAAK,IAAI;AAElB,SAAO,MAAM,OAAO,EAAC,OAAO,CAAA;AAC9B;AAOO,UAAU,mB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AAA,MAAI,CAAC,CAAC,KAAK,IAAI,MAC/D,KAAK,uBAAuB,KAAK,IAAI;AAAA,IAAA;AAGhC,WAAA,EAAE,cAAc,KAAK;AAAA,EAC9B;AACF;AACA,SAAS,qBAAqB,OAAuB;AAC5C,SAAA,MAAM,OAAO,CAAC,EAAE,gBAAgB,MAAM,MAAM,CAAC;AACtD;AAEA,SAAS,mBAAmB,OAAuB;AACjD,SAAO,GAAG,MAAM,QAAQ,OAAO,GAAG,EAAE,QAAQ,eAAe,CAAC,GAAG,SAAS,KAAK,YAAa,CAAA,CAAC;AAC7F;"}
|
package/lib/index.js
CHANGED
|
@@ -97,9 +97,8 @@ function resolveExpression({
|
|
|
97
97
|
params = [],
|
|
98
98
|
fnArguments = []
|
|
99
99
|
}) {
|
|
100
|
-
var _a, _b, _c, _d;
|
|
101
100
|
if (debug$2(
|
|
102
|
-
`Resolving node ${node.type} in ${filename}:${
|
|
101
|
+
`Resolving node ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`
|
|
103
102
|
), t__namespace.isTaggedTemplateExpression(node) && t__namespace.isIdentifier(node.tag) && TAGGED_TEMPLATE_ALLOW_LIST.includes(node.tag.name))
|
|
104
103
|
return resolveExpression({
|
|
105
104
|
node: node.quasi,
|
|
@@ -210,7 +209,7 @@ function resolveExpression({
|
|
|
210
209
|
fnArguments
|
|
211
210
|
});
|
|
212
211
|
throw new Error(
|
|
213
|
-
`Unsupported expression type: ${node.type} in ${filename}:${
|
|
212
|
+
`Unsupported expression type: ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`
|
|
214
213
|
);
|
|
215
214
|
}
|
|
216
215
|
function resolveIdentifier({
|
|
@@ -223,7 +222,6 @@ function resolveIdentifier({
|
|
|
223
222
|
fnArguments,
|
|
224
223
|
params
|
|
225
224
|
}) {
|
|
226
|
-
var _a, _b, _c, _d;
|
|
227
225
|
const paramIndex = params.findIndex(
|
|
228
226
|
(param) => t__namespace.isIdentifier(param) && node.name === param.name || t__namespace.isAssignmentPattern(param) && t__namespace.isIdentifier(param.left) && node.name === param.left.name
|
|
229
227
|
), argument = fnArguments[paramIndex];
|
|
@@ -242,7 +240,7 @@ function resolveIdentifier({
|
|
|
242
240
|
if (binding) {
|
|
243
241
|
if (t__namespace.isIdentifier(binding.path.node) && binding.path.node.name === node.name)
|
|
244
242
|
throw new Error(
|
|
245
|
-
`Could not resolve same identifier "${node.name}" in "${filename}:${
|
|
243
|
+
`Could not resolve same identifier "${node.name}" in "${filename}:${node.loc?.start.line}:${node.loc?.start.column}"`
|
|
246
244
|
);
|
|
247
245
|
return resolveExpression({
|
|
248
246
|
node: binding.path.node,
|
|
@@ -256,7 +254,7 @@ function resolveIdentifier({
|
|
|
256
254
|
});
|
|
257
255
|
}
|
|
258
256
|
throw new Error(
|
|
259
|
-
`Could not find binding for node "${node.name}" in ${filename}:${
|
|
257
|
+
`Could not find binding for node "${node.name}" in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`
|
|
260
258
|
);
|
|
261
259
|
}
|
|
262
260
|
function resolveCallExpression({
|
|
@@ -290,10 +288,9 @@ function resolveImportSpecifier({
|
|
|
290
288
|
let importDeclaration;
|
|
291
289
|
if (traverse__default.default(file, {
|
|
292
290
|
ImportDeclaration(n) {
|
|
293
|
-
var _a;
|
|
294
291
|
if (t__namespace.isImportDeclaration(n.node))
|
|
295
292
|
for (const specifier of n.node.specifiers) {
|
|
296
|
-
if (t__namespace.isImportDefaultSpecifier(specifier) &&
|
|
293
|
+
if (t__namespace.isImportDefaultSpecifier(specifier) && specifier.local.loc?.identifierName === node.local.name) {
|
|
297
294
|
importDeclaration = n.node;
|
|
298
295
|
break;
|
|
299
296
|
}
|
|
@@ -391,11 +388,10 @@ function findQueriesInSource(source, filename, babelConfig = getBabelConfig(), r
|
|
|
391
388
|
}), queries;
|
|
392
389
|
}
|
|
393
390
|
function declarationLeadingCommentContains(path2, comment) {
|
|
394
|
-
var _a, _b;
|
|
395
391
|
const variableDeclaration = path2.find((node) => node.isVariableDeclaration());
|
|
396
|
-
return variableDeclaration ? !!(
|
|
392
|
+
return variableDeclaration ? !!(variableDeclaration.node.leadingComments?.find(
|
|
397
393
|
(commentItem) => commentItem.value.trim() === comment
|
|
398
|
-
) ||
|
|
394
|
+
) || variableDeclaration.parent.leadingComments?.find(
|
|
399
395
|
(commentItem) => commentItem.value.trim() === comment
|
|
400
396
|
)) : !1;
|
|
401
397
|
}
|
|
@@ -476,11 +472,13 @@ function registerBabel(babelOptions) {
|
|
|
476
472
|
const options = babelOptions || getBabelConfig();
|
|
477
473
|
register__default.default({ ...options, extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"] });
|
|
478
474
|
}
|
|
479
|
-
var __defProp = Object.defineProperty, __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
|
|
480
475
|
const REFERENCE_SYMBOL_NAME = "internalGroqTypeReferenceTo", ALL_SCHEMA_TYPES = "AllSanitySchemaTypes";
|
|
481
476
|
class TypeGenerator {
|
|
477
|
+
generatedTypeName = /* @__PURE__ */ new Set();
|
|
478
|
+
typeNameMap = /* @__PURE__ */ new Map();
|
|
479
|
+
schema;
|
|
482
480
|
constructor(schema) {
|
|
483
|
-
|
|
481
|
+
this.schema = schema;
|
|
484
482
|
}
|
|
485
483
|
/**
|
|
486
484
|
* Generate TypeScript types for the given schema
|
|
@@ -542,11 +540,10 @@ class TypeGenerator {
|
|
|
542
540
|
* @beta
|
|
543
541
|
*/
|
|
544
542
|
generateQueryMap(queries) {
|
|
545
|
-
var _a;
|
|
546
543
|
const typesByQuerystring = {};
|
|
547
544
|
for (const query of queries) {
|
|
548
545
|
const name = this.typeNameMap.get(query.typeNode);
|
|
549
|
-
name && (typesByQuerystring[
|
|
546
|
+
name && (typesByQuerystring[query.query] ??= [], typesByQuerystring[query.query].push(name));
|
|
550
547
|
}
|
|
551
548
|
const queryReturnInterface = t__namespace.tsInterfaceDeclaration(
|
|
552
549
|
t__namespace.identifier("SanityQueries"),
|
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/readConfig.ts","../src/readSchema.ts","../src/safeParseQuery.ts","../src/getBabelConfig.ts","../src/typescript/parseSource.ts","../src/typescript/expressionResolvers.ts","../src/typescript/findQueriesInSource.ts","../src/typescript/moduleResolver.ts","../src/typescript/findQueriesInPath.ts","../src/typescript/registerBabel.ts","../src/typescript/typeGenerator.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport * as json5 from 'json5'\nimport * as z from 'zod'\n\nexport const configDefintion = z.object({\n path: z\n .string()\n .or(z.array(z.string()))\n .default([\n './src/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n './app/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n ]),\n schema: z.string().default('./schema.json'),\n generates: z.string().default('./sanity.types.ts'),\n formatGeneratedCode: z.boolean().default(true),\n overloadClientMethods: z.boolean().default(false),\n})\n\nexport type CodegenConfig = z.infer<typeof configDefintion>\n\nexport async function readConfig(path: string): Promise<CodegenConfig> {\n try {\n const content = await readFile(path, 'utf-8')\n const json = json5.parse(content)\n return configDefintion.parseAsync(json)\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(`Error in config file\\n ${error.errors.map((err) => err.message).join('\\n')}`)\n }\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return configDefintion.parse({})\n }\n\n throw error\n }\n}\n","import {readFile} from 'node:fs/promises'\n\nimport {type SchemaType} from 'groq-js'\n\n/**\n * Read a schema from a given path\n * @param path - The path to the schema\n * @returns The schema\n * @internal\n * @beta\n **/\nexport async function readSchema(path: string): Promise<SchemaType> {\n const content = await readFile(path, 'utf-8')\n return JSON.parse(content) // todo: ZOD validation?\n}\n","import {parse} from 'groq-js'\n\n/**\n * safeParseQuery parses a GROQ query string, but first attempts to extract any parameters used in slices. This method is _only_\n * intended for use in type generation where we don't actually execute the parsed AST on a dataset, and should not be used elsewhere.\n * @internal\n */\nexport function safeParseQuery(query: string) {\n const params: Record<string, unknown> = {}\n\n for (const param of extractSliceParams(query)) {\n params[param] = 0 // we don't care about the value, just the type\n }\n return parse(query, {params})\n}\n\n/**\n * Finds occurences of `[($start|{number})..($end|{number})]` in a query string and returns the start and end values, and return\n * the names of the start and end variables.\n * @internal\n */\nexport function* extractSliceParams(query: string): Generator<string> {\n const sliceRegex = /\\[(\\$(\\w+)|\\d)\\.\\.\\.?(\\$(\\w+)|\\d)\\]/g\n const matches = query.matchAll(sliceRegex)\n if (!matches) {\n return\n }\n const params = new Set<string>()\n for (const match of matches) {\n const start = match[1] === `$${match[2]}` ? match[2] : null\n if (start !== null) {\n yield start\n }\n const end = match[3] === `$${match[4]}` ? match[4] : null\n if (end !== null) {\n yield end\n }\n }\n}\n","import {existsSync} from 'node:fs'\nimport {join, resolve} from 'node:path'\n\nimport {type TransformOptions} from '@babel/core'\n\n/**\n * Because of bundlers and compilers, knowing the exact path the babel configuration will be\n * located at post - build is not always trivial. We traverse from the current directory upwards\n * until we find the first `babel.config.json` and use that path.\n *\n * @param path - The path to start looking for the babel configuration\n * @returns The path to the `babel.config.json` file\n * @internal\n */\nexport function findBabelConfig(path: string): string {\n const configPath = join(path, 'babel.config.json')\n if (existsSync(configPath)) {\n return configPath\n }\n\n const parent = resolve(join(path, '..'))\n if (parent && parent !== path) {\n return findBabelConfig(parent)\n }\n\n throw new Error('Could not find `babel.config.json` in @sanity/codegen')\n}\n\n/**\n * Get the default babel configuration for `@sanity/codegen`\n *\n * @param path - The path to start looking for the babel configuration. Defaults to `__dirname`\n * @returns A babel configuration object\n * @internal\n */\nexport function getBabelConfig(path?: string): TransformOptions {\n const configPath = findBabelConfig(path || __dirname)\n return {extends: configPath}\n}\n","import {parse, type TransformOptions} from '@babel/core'\nimport type * as babelTypes from '@babel/types'\n\n// helper function to parse a source file\nexport function parseSourceFile(\n source: string,\n filename: string,\n babelOptions: TransformOptions,\n): babelTypes.File {\n const result = parse(source, {\n ...babelOptions,\n filename,\n })\n\n if (!result) {\n throw new Error(`Failed to parse ${filename}`)\n }\n\n return result\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type TransformOptions} from '@babel/core'\nimport traverse, {type Scope} from '@babel/traverse'\nimport * as babelTypes from '@babel/types'\nimport createDebug from 'debug'\n\nimport {parseSourceFile} from './parseSource'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ntype resolveExpressionReturnType = string\n\n/**\n * NamedQueryResult is a result of a named query\n */\nexport interface NamedQueryResult {\n /** name is the name of the query */\n name: string\n /** result is a groq query */\n result: resolveExpressionReturnType\n}\n\nconst TAGGED_TEMPLATE_ALLOW_LIST = ['groq']\nconst FUNCTION_WRAPPER_ALLOW_LIST = ['defineQuery']\n\n/**\n * resolveExpression takes a node and returns the resolved value of the expression.\n * @beta\n * @internal\n */\nexport function resolveExpression({\n node,\n file,\n scope,\n filename,\n resolver,\n babelConfig,\n params = [],\n fnArguments = [],\n}: {\n node: babelTypes.Node\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n params?: babelTypes.Node[]\n fnArguments?: babelTypes.Node[]\n}): resolveExpressionReturnType {\n debug(\n `Resolving node ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n if (\n babelTypes.isTaggedTemplateExpression(node) &&\n babelTypes.isIdentifier(node.tag) &&\n TAGGED_TEMPLATE_ALLOW_LIST.includes(node.tag.name)\n ) {\n return resolveExpression({\n node: node.quasi,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n\n if (babelTypes.isTemplateLiteral(node)) {\n const resolvedExpressions = node.expressions.map((expression) =>\n resolveExpression({\n node: expression,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n }),\n )\n return node.quasis\n .map((quasi, idx) => {\n return (quasi.value.cooked || '') + (resolvedExpressions[idx] || '')\n })\n .join('')\n }\n\n if (babelTypes.isLiteral(node)) {\n if (node.type === 'NullLiteral' || node.type === 'RegExpLiteral') {\n throw new Error(`Unsupported literal type: ${node.type}`)\n }\n\n return node.value.toString()\n }\n\n if (babelTypes.isIdentifier(node)) {\n return resolveIdentifier({\n node,\n scope,\n filename,\n file,\n resolver,\n fnArguments,\n babelConfig,\n params,\n })\n }\n\n if (babelTypes.isVariableDeclarator(node)) {\n if (!node.init) {\n throw new Error(`Unsupported variable declarator`)\n }\n\n return resolveExpression({\n node: node.init,\n fnArguments,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (\n babelTypes.isCallExpression(node) &&\n babelTypes.isIdentifier(node.callee) &&\n FUNCTION_WRAPPER_ALLOW_LIST.includes(node.callee.name)\n ) {\n return resolveExpression({\n node: node.arguments[0],\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n })\n }\n\n if (babelTypes.isCallExpression(node)) {\n return resolveCallExpression({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n fnArguments,\n })\n }\n\n if (\n babelTypes.isArrowFunctionExpression(node) ||\n babelTypes.isFunctionDeclaration(node) ||\n babelTypes.isFunctionExpression(node)\n ) {\n return resolveExpression({\n node: node.body,\n params: node.params,\n fnArguments,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (babelTypes.isNewExpression(node)) {\n return resolveExpression({\n node: node.callee,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (babelTypes.isImportDefaultSpecifier(node) || babelTypes.isImportSpecifier(node)) {\n return resolveImportSpecifier({node, file, scope, filename, resolver, babelConfig})\n }\n\n if (babelTypes.isAssignmentPattern(node)) {\n return resolveExpression({\n node: node.right,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n\n throw new Error(\n `Unsupported expression type: ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveIdentifier({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n fnArguments,\n params,\n}: {\n node: babelTypes.Identifier\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n fnArguments: babelTypes.Node[]\n params: babelTypes.Node[]\n}): resolveExpressionReturnType {\n const paramIndex = params.findIndex(\n (param) =>\n (babelTypes.isIdentifier(param) && node.name === param.name) ||\n (babelTypes.isAssignmentPattern(param) &&\n babelTypes.isIdentifier(param.left) &&\n node.name === param.left.name),\n )\n const argument = fnArguments[paramIndex]\n if (argument && babelTypes.isLiteral(argument)) {\n return resolveExpression({\n node: argument,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n const binding = scope.getBinding(node.name)\n if (binding) {\n if (babelTypes.isIdentifier(binding.path.node)) {\n const isSame = binding.path.node.name === node.name\n if (isSame) {\n throw new Error(\n `Could not resolve same identifier \"${node.name}\" in \"${filename}:${node.loc?.start.line}:${node.loc?.start.column}\"`,\n )\n }\n }\n return resolveExpression({\n node: binding.path.node,\n params,\n fnArguments,\n scope,\n filename,\n babelConfig,\n file,\n resolver,\n })\n }\n\n throw new Error(\n `Could not find binding for node \"${node.name}\" in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveCallExpression({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n}: {\n node: babelTypes.CallExpression\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n fnArguments: babelTypes.Node[]\n params: babelTypes.Node[]\n}): resolveExpressionReturnType {\n const {callee} = node\n return resolveExpression({\n node: callee,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n fnArguments: node.arguments,\n })\n}\n\nfunction resolveImportSpecifier({\n node,\n file,\n filename,\n resolver,\n babelConfig,\n}: {\n node: babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier | babelTypes.ExportSpecifier\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n}): resolveExpressionReturnType {\n let importDeclaration: babelTypes.ImportDeclaration | undefined\n traverse(file, {\n ImportDeclaration(n) {\n if (!babelTypes.isImportDeclaration(n.node)) {\n return\n }\n for (const specifier of n.node.specifiers) {\n if (babelTypes.isImportDefaultSpecifier(specifier)) {\n if (specifier.local.loc?.identifierName === node.local.name) {\n importDeclaration = n.node\n break\n }\n }\n if (specifier.local.name === node.local.name) {\n importDeclaration = n.node\n }\n }\n },\n })\n\n if (!importDeclaration) {\n throw new Error(`Could not find import declaration for ${node.local.name}`)\n }\n\n const importName = node.local.name // the name of the variable to import\n const importFileName = importDeclaration.source.value // the file to import from\n\n const importPath =\n importFileName.startsWith('./') || importFileName.startsWith('../')\n ? path.resolve(path.dirname(filename), importFileName)\n : importFileName\n\n const resolvedFile = resolver(importPath)\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let newScope: Scope | undefined\n traverse(tree, {\n Program(p) {\n newScope = p.scope\n },\n })\n if (!newScope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = newScope.getBinding(importName)\n if (binding) {\n return resolveExpression({\n node: binding.path.node,\n file: tree,\n scope: newScope,\n babelConfig,\n filename: resolvedFile,\n resolver,\n })\n }\n\n // It's not a global binding, but it might be a named export\n let namedExport: babelTypes.ExportNamedDeclaration | undefined\n let newImportName: string | undefined\n traverse(tree, {\n ExportDeclaration(p) {\n if (p.node.type === 'ExportNamedDeclaration') {\n for (const specifier of p.node.specifiers) {\n if (\n specifier.type === 'ExportSpecifier' &&\n specifier.exported.type === 'Identifier' &&\n specifier.exported.name === importName\n ) {\n namedExport = p.node\n newImportName = specifier.exported.name\n }\n }\n }\n },\n })\n\n if (namedExport && newImportName) {\n return resolveExportSpecifier({\n node: namedExport,\n importName: newImportName,\n filename: resolvedFile,\n resolver,\n babelConfig,\n })\n }\n\n throw new Error(`Could not find binding for import \"${importName}\" in ${importFileName}`)\n}\n\nfunction resolveExportSpecifier({\n node,\n importName,\n filename,\n babelConfig,\n resolver,\n}: {\n node: babelTypes.ExportNamedDeclaration\n importName: string\n filename: string\n babelConfig: TransformOptions\n resolver: NodeJS.RequireResolve\n}): resolveExpressionReturnType {\n if (!node.source) {\n throw new Error(`Could not find source for export \"${importName}\" in ${filename}`)\n }\n\n const importFileName = node.source.value\n const importPath = path.resolve(path.dirname(filename), importFileName)\n const resolvedFile = resolver(importPath)\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let newScope: Scope | undefined\n traverse(tree, {\n Program(p) {\n newScope = p.scope\n },\n })\n if (!newScope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = newScope.getBinding(importName)\n if (binding) {\n return resolveExpression({\n node: binding.path.node,\n file: tree,\n scope: newScope,\n filename: importFileName,\n babelConfig,\n resolver,\n })\n }\n\n throw new Error(`Could not find binding for export \"${importName}\" in ${importFileName}`)\n}\n","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'\nimport {type NamedQueryResult, resolveExpression} from './expressionResolvers'\nimport {parseSourceFile} from './parseSource'\n\nconst require = createRequire(__filename)\n\nconst groqTagName = 'groq'\nconst defineQueryFunctionName = 'defineQuery'\nconst groqModuleName = 'groq'\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): NamedQueryResult[] {\n const queries: NamedQueryResult[] = []\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\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 queryName = `${node.id.name}`\n const queryResult = resolveExpression({\n node: init,\n file,\n scope,\n babelConfig,\n filename,\n resolver,\n })\n\n queries.push({name: queryName, result: queryResult})\n }\n },\n })\n\n return 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","import createDebug from 'debug'\nimport {createMatchPath, loadConfig as loadTSConfig} from 'tsconfig-paths'\n\nconst debug = createDebug('sanity:codegen:moduleResolver')\n\n/**\n * This is a custom implementation of require.resolve that takes into account the paths\n * configuration in tsconfig.json. This is necessary if we want to resolve paths that are\n * custom defined in the tsconfig.json file.\n * Resolving here is best effort and might not work in all cases.\n * @beta\n */\nexport function getResolver(cwd?: string): NodeJS.RequireResolve {\n const tsConfig = loadTSConfig(cwd)\n\n if (tsConfig.resultType === 'failed') {\n debug('Could not load tsconfig, using default resolver: %s', tsConfig.message)\n return require.resolve\n }\n\n const matchPath = createMatchPath(\n tsConfig.absoluteBaseUrl,\n tsConfig.paths,\n tsConfig.mainFields,\n tsConfig.addMatchAll,\n )\n\n const resolve = function (request: string, options?: {paths?: string[]}): string {\n const found = matchPath(request)\n if (found !== undefined) {\n return require.resolve(found, options)\n }\n return require.resolve(request, options)\n }\n\n // wrap the resolve.path function to make it available.\n resolve.paths = (request: string): string[] | null => {\n return require.resolve.paths(request)\n }\n return resolve\n}\n","import fs from 'node:fs/promises'\n\nimport {type TransformOptions} from '@babel/core'\nimport createDebug from 'debug'\nimport glob from 'globby'\n\nimport {getBabelConfig} from '../getBabelConfig'\nimport {type NamedQueryResult} from './expressionResolvers'\nimport {findQueriesInSource} from './findQueriesInSource'\nimport {getResolver} from './moduleResolver'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ntype ResultQueries = {\n type: 'queries'\n filename: string\n queries: NamedQueryResult[]\n}\ntype ResultError = {\n type: 'error'\n error: Error\n filename: string\n}\n\n/**\n * findQueriesInPath takes a path or array of paths and returns all GROQ queries in the files.\n * @param path - The path or array of paths to search for queries\n * @param babelOptions - The babel configuration to use when parsing the source\n * @param resolver - A resolver function to use when resolving module imports\n * @returns An async generator that yields the results of the search\n * @beta\n * @internal\n */\nexport async function* findQueriesInPath({\n path,\n babelOptions = getBabelConfig(),\n resolver = getResolver(),\n}: {\n path: string | string[]\n babelOptions?: TransformOptions\n resolver?: NodeJS.RequireResolve\n}): AsyncGenerator<ResultQueries | ResultError> {\n const queryNames = new Set()\n // Holds all query names found in the source files\n debug(`Globing ${path}`)\n\n const stream = glob.stream(path, {\n absolute: false,\n ignore: ['**/node_modules/**'], // we never want to look in node_modules\n onlyFiles: true,\n })\n\n for await (const filename of stream) {\n if (typeof filename !== 'string') {\n continue\n }\n\n debug(`Found file \"${filename}\"`)\n try {\n const source = await fs.readFile(filename, 'utf8')\n const queries = findQueriesInSource(source, filename, babelOptions, resolver)\n // Check and error on duplicate query names, because we can't generate types with the same name.\n for (const query of queries) {\n if (queryNames.has(query.name)) {\n throw new Error(\n `Duplicate query name found: \"${query.name}\". Query names must be unique across all files.`,\n )\n }\n queryNames.add(query.name)\n }\n yield {type: 'queries', filename, queries}\n } catch (error) {\n debug(`Error in file \"${filename}\"`, error)\n yield {type: 'error', error, filename}\n }\n }\n}\n","import {type TransformOptions} from '@babel/core'\nimport register from '@babel/register'\n\nimport {getBabelConfig} from '../getBabelConfig'\n\n/**\n * Register Babel with the given options\n *\n * @param babelOptions - The options to use when registering Babel\n * @beta\n */\nexport function registerBabel(babelOptions?: TransformOptions): void {\n const options = babelOptions || getBabelConfig()\n\n register({...options, extensions: ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']})\n}\n","import {CodeGenerator} from '@babel/generator'\nimport * as t from '@babel/types'\nimport {\n type ArrayTypeNode,\n type DocumentSchemaType,\n type ObjectAttribute,\n type ObjectTypeNode,\n type SchemaType,\n type TypeDeclarationSchemaType,\n type TypeNode,\n type UnionTypeNode,\n} from 'groq-js'\n\nconst REFERENCE_SYMBOL_NAME = 'internalGroqTypeReferenceTo'\nconst ALL_SCHEMA_TYPES = 'AllSanitySchemaTypes'\n\ntype QueryWithTypeNode = {\n query: string\n typeNode: TypeNode\n}\n\n/**\n * A class used to generate TypeScript types from a given schema\n * @internal\n * @beta\n */\nexport class TypeGenerator {\n private generatedTypeName: Set<string> = new Set()\n private typeNameMap: Map<TypeNode | DocumentSchemaType | TypeDeclarationSchemaType, string> =\n new Map()\n\n private readonly schema: SchemaType\n\n constructor(schema: SchemaType) {\n this.schema = schema\n }\n\n /**\n * Generate TypeScript types for the given schema\n * @returns string\n * @internal\n * @beta\n */\n generateSchemaTypes(): string {\n const typeDeclarations: (t.TSTypeAliasDeclaration | t.ExportNamedDeclaration)[] = []\n\n const schemaNames = new Set<string>()\n this.schema.forEach((schema) => {\n const typeLiteral = this.getTypeNodeType(schema)\n\n const schemaName = this.getTypeName(schema.name, schema)\n schemaNames.add(schemaName)\n const typeAlias = t.tsTypeAliasDeclaration(t.identifier(schemaName), null, typeLiteral)\n\n typeDeclarations.push(t.exportNamedDeclaration(typeAlias))\n })\n\n typeDeclarations.push(\n t.exportNamedDeclaration(\n t.tsTypeAliasDeclaration(\n t.identifier(this.getTypeName(ALL_SCHEMA_TYPES)),\n null,\n t.tsUnionType(\n [...schemaNames].map((typeName) => t.tsTypeReference(t.identifier(typeName))),\n ),\n ),\n ),\n )\n\n // Generate TypeScript code from the AST nodes\n return typeDeclarations.map((decl) => new CodeGenerator(decl).generate().code).join('\\n\\n')\n }\n\n /**\n * Takes a identifier and a type node and generates a type alias for the type node.\n * @param identifierName - The name of the type to generated\n * @param typeNode - The type node to generate the type for\n * @returns\n * @internal\n * @beta\n */\n generateTypeNodeTypes(identifierName: string, typeNode: TypeNode): string {\n const type = this.getTypeNodeType(typeNode)\n\n const typeName = this.getTypeName(identifierName, typeNode)\n const typeAlias = t.tsTypeAliasDeclaration(t.identifier(typeName), null, type)\n\n return new CodeGenerator(t.exportNamedDeclaration(typeAlias)).generate().code.trim()\n }\n\n static generateKnownTypes(): string {\n const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword())\n typeOperator.operator = 'unique'\n\n const identifier = t.identifier(REFERENCE_SYMBOL_NAME)\n identifier.typeAnnotation = t.tsTypeAnnotation(typeOperator)\n\n const decleration = t.variableDeclaration('const', [t.variableDeclarator(identifier)])\n decleration.declare = true\n return new CodeGenerator(t.exportNamedDeclaration(decleration)).generate().code.trim()\n }\n\n /**\n * Takes a list of queries from the codebase and generates a type declaration\n * for SanityClient to consume.\n *\n * Note: only types that have previously been generated with `generateTypeNodeTypes`\n * will be included in the query map.\n *\n * @param queries - A list of queries to generate a type declaration for\n * @returns\n * @internal\n * @beta\n */\n generateQueryMap(queries: QueryWithTypeNode[]): string {\n const typesByQuerystring: {[query: string]: string[]} = {}\n\n for (const query of queries) {\n const name = this.typeNameMap.get(query.typeNode)\n if (!name) {\n continue\n }\n\n typesByQuerystring[query.query] ??= []\n typesByQuerystring[query.query].push(name)\n }\n\n const queryReturnInterface = t.tsInterfaceDeclaration(\n t.identifier('SanityQueries'),\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 declareModule = t.declareModule(\n t.stringLiteral('@sanity/client'),\n t.blockStatement([queryReturnInterface]),\n )\n\n const clientImport = t.importDeclaration([], t.stringLiteral('@sanity/client'))\n\n return new CodeGenerator(t.program([clientImport, declareModule])).generate().code.trim()\n }\n\n /**\n * Since we are sanitizing identifiers we migt end up with collisions. Ie there might be a type mux.video and muxVideo, both these\n * types would be sanityized into MuxVideo. To avoid this we keep track of the generated type names and add a index to the name.\n * When we reference a type we also keep track of the original name so we can reference the correct type later.\n */\n private getTypeName(\n name: string,\n typeNode?: TypeNode | DocumentSchemaType | TypeDeclarationSchemaType,\n ): string {\n const desiredName = uppercaseFirstLetter(sanitizeIdentifier(name))\n\n let generatedName = desiredName\n let i = 2\n while (this.generatedTypeName.has(generatedName)) {\n // add _ and a index and increment that index until we find a name that is not in the map\n generatedName = `${desiredName}_${i++}`\n }\n this.generatedTypeName.add(generatedName)\n if (typeNode) {\n this.typeNameMap.set(typeNode, generatedName)\n }\n\n return generatedName\n }\n\n private getTypeNodeType(\n typeNode: TypeNode | TypeDeclarationSchemaType | DocumentSchemaType,\n ): t.TSType {\n switch (typeNode.type) {\n case 'string': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.stringLiteral(typeNode.value))\n }\n return t.tsStringKeyword()\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 'boolean': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.booleanLiteral(typeNode.value))\n }\n return t.tsBooleanKeyword()\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n case 'document': {\n return this.generateDocumentType(typeNode)\n }\n case 'type': {\n return this.getTypeNodeType(typeNode.value)\n }\n case 'array': {\n return this.generateArrayTsType(typeNode)\n }\n case 'object': {\n return this.generateObjectTsType(typeNode)\n }\n case 'union': {\n return this.generateUnionTsType(typeNode)\n }\n case 'inline': {\n return t.tsTypeReference(\n t.identifier(uppercaseFirstLetter(sanitizeIdentifier(typeNode.name))),\n )\n }\n case 'null': {\n return t.tsNullKeyword()\n }\n\n default:\n // @ts-expect-error This should never happen\n throw new Error(`Type \"${typeNode.type}\" not found in schema`)\n }\n }\n\n // Helper function used to generate TS types for array type nodes.\n private generateArrayTsType(typeNode: ArrayTypeNode): t.TSTypeReference {\n const typeNodes = this.getTypeNodeType(typeNode.of)\n const arrayType = t.tsTypeReference(\n t.identifier('Array'),\n t.tsTypeParameterInstantiation([typeNodes]),\n )\n\n return arrayType\n }\n\n // Helper function used to generate TS types for object properties.\n private generateObjectProperty(key: string, attribute: ObjectAttribute): t.TSPropertySignature {\n const type = this.getTypeNodeType(attribute.value)\n const propertySignature = t.tsPropertySignature(\n t.identifier(sanitizeIdentifier(key)),\n t.tsTypeAnnotation(type),\n )\n propertySignature.optional = attribute.optional\n\n return propertySignature\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 Object.entries(typeNode.attributes).forEach(([key, attribute]) => {\n props.push(this.generateObjectProperty(key, attribute))\n })\n const rest = typeNode.rest\n if (rest !== undefined) {\n switch (rest.type) {\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n case 'object': {\n Object.entries(rest.attributes).forEach(([key, attribute]) => {\n props.push(this.generateObjectProperty(key, attribute))\n })\n break\n }\n case 'inline': {\n const referencedTypeNode = this.schema.find((schema) => schema.name === rest.name)\n if (referencedTypeNode === undefined) {\n const missing = t.tsUnknownKeyword()\n missing.trailingComments = [\n {\n type: 'CommentLine',\n value: ` Unable to locate the referenced type \"${rest.name}\" in schema`,\n },\n ]\n return missing\n }\n\n return t.tsIntersectionType([\n t.tsTypeLiteral(props),\n t.tsTypeReference(\n t.identifier(\n this.typeNameMap.get(referencedTypeNode) ||\n uppercaseFirstLetter(sanitizeIdentifier(rest.name)),\n ),\n ),\n ])\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 if (typeNode.dereferencesTo !== undefined) {\n const derefType = t.tsPropertySignature(\n t.identifier(REFERENCE_SYMBOL_NAME),\n t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo))),\n )\n derefType.computed = true\n derefType.optional = true\n props.push(derefType)\n }\n return t.tsTypeLiteral(props)\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) {\n return t.tsNeverKeyword()\n }\n if (typeNode.of.length === 1) {\n return this.getTypeNodeType(typeNode.of[0])\n }\n\n const typeNodes = typeNode.of.map((node) => this.getTypeNodeType(node))\n\n return t.tsUnionType(typeNodes)\n }\n\n // Helper function used to generate TS types for document type nodes.\n private generateDocumentType(document: DocumentSchemaType): t.TSType {\n const props = Object.entries(document.attributes).map(([key, node]) =>\n this.generateObjectProperty(key, node),\n )\n\n return t.tsTypeLiteral(props)\n }\n}\nfunction uppercaseFirstLetter(input: string): string {\n return input.charAt(0).toUpperCase() + input.slice(1)\n}\n\nfunction sanitizeIdentifier(input: string): string {\n return `${input.replace(/^\\d/, '_').replace(/[^$\\w]+(.)/g, (_, char) => char.toUpperCase())}`\n}\n"],"names":["z","path","readFile","json5","parse","join","existsSync","resolve","debug","createDebug","babelTypes","traverse","fs","require","createRequire","loadTSConfig","createMatchPath","glob","register","t","CodeGenerator"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAKa,MAAA,kBAAkBA,aAAE,OAAO;AAAA,EACtC,MAAMA,aACH,OAAO,EACP,GAAGA,aAAE,MAAMA,aAAE,QAAQ,CAAC,EACtB,QAAQ;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AAAA,EACH,QAAQA,aAAE,SAAS,QAAQ,eAAe;AAAA,EAC1C,WAAWA,aAAE,SAAS,QAAQ,mBAAmB;AAAA,EACjD,qBAAqBA,aAAE,QAAQ,EAAE,QAAQ,EAAI;AAAA,EAC7C,uBAAuBA,aAAE,QAAQ,EAAE,QAAQ,EAAK;AAClD,CAAC;AAID,eAAsB,WAAWC,OAAsC;AACjE,MAAA;AACI,UAAA,UAAU,MAAMC,GAAS,SAAAD,OAAM,OAAO,GACtC,OAAOE,iBAAM,MAAM,OAAO;AACzB,WAAA,gBAAgB,WAAW,IAAI;AAAA,WAC/B,OAAO;AACd,QAAI,iBAAiBH,aAAE;AACrB,YAAM,IAAI,MAAM;AAAA,GAA0B,MAAM,OAAO,IAAI,CAAC,QAAQ,IAAI,OAAO,EAAE,KAAK;AAAA,CAAI,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,KAAK,uBAAuB,KAAK,IAAI;AAAA,IAAA;AAGhC,WAAAA,aAAE,cAAc,KAAK;AAAA,EAC9B;AACF;AACA,SAAS,qBAAqB,OAAuB;AAC5C,SAAA,MAAM,OAAO,CAAC,EAAE,gBAAgB,MAAM,MAAM,CAAC;AACtD;AAEA,SAAS,mBAAmB,OAAuB;AACjD,SAAO,GAAG,MAAM,QAAQ,OAAO,GAAG,EAAE,QAAQ,eAAe,CAAC,GAAG,SAAS,KAAK,YAAa,CAAA,CAAC;AAC7F;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/readConfig.ts","../src/readSchema.ts","../src/safeParseQuery.ts","../src/getBabelConfig.ts","../src/typescript/parseSource.ts","../src/typescript/expressionResolvers.ts","../src/typescript/findQueriesInSource.ts","../src/typescript/moduleResolver.ts","../src/typescript/findQueriesInPath.ts","../src/typescript/registerBabel.ts","../src/typescript/typeGenerator.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport * as json5 from 'json5'\nimport * as z from 'zod'\n\nexport const configDefintion = z.object({\n path: z\n .string()\n .or(z.array(z.string()))\n .default([\n './src/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n './app/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n ]),\n schema: z.string().default('./schema.json'),\n generates: z.string().default('./sanity.types.ts'),\n formatGeneratedCode: z.boolean().default(true),\n overloadClientMethods: z.boolean().default(false),\n})\n\nexport type CodegenConfig = z.infer<typeof configDefintion>\n\nexport async function readConfig(path: string): Promise<CodegenConfig> {\n try {\n const content = await readFile(path, 'utf-8')\n const json = json5.parse(content)\n return configDefintion.parseAsync(json)\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(`Error in config file\\n ${error.errors.map((err) => err.message).join('\\n')}`)\n }\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return configDefintion.parse({})\n }\n\n throw error\n }\n}\n","import {readFile} from 'node:fs/promises'\n\nimport {type SchemaType} from 'groq-js'\n\n/**\n * Read a schema from a given path\n * @param path - The path to the schema\n * @returns The schema\n * @internal\n * @beta\n **/\nexport async function readSchema(path: string): Promise<SchemaType> {\n const content = await readFile(path, 'utf-8')\n return JSON.parse(content) // todo: ZOD validation?\n}\n","import {parse} from 'groq-js'\n\n/**\n * safeParseQuery parses a GROQ query string, but first attempts to extract any parameters used in slices. This method is _only_\n * intended for use in type generation where we don't actually execute the parsed AST on a dataset, and should not be used elsewhere.\n * @internal\n */\nexport function safeParseQuery(query: string) {\n const params: Record<string, unknown> = {}\n\n for (const param of extractSliceParams(query)) {\n params[param] = 0 // we don't care about the value, just the type\n }\n return parse(query, {params})\n}\n\n/**\n * Finds occurences of `[($start|{number})..($end|{number})]` in a query string and returns the start and end values, and return\n * the names of the start and end variables.\n * @internal\n */\nexport function* extractSliceParams(query: string): Generator<string> {\n const sliceRegex = /\\[(\\$(\\w+)|\\d)\\.\\.\\.?(\\$(\\w+)|\\d)\\]/g\n const matches = query.matchAll(sliceRegex)\n if (!matches) {\n return\n }\n const params = new Set<string>()\n for (const match of matches) {\n const start = match[1] === `$${match[2]}` ? match[2] : null\n if (start !== null) {\n yield start\n }\n const end = match[3] === `$${match[4]}` ? match[4] : null\n if (end !== null) {\n yield end\n }\n }\n}\n","import {existsSync} from 'node:fs'\nimport {join, resolve} from 'node:path'\n\nimport {type TransformOptions} from '@babel/core'\n\n/**\n * Because of bundlers and compilers, knowing the exact path the babel configuration will be\n * located at post - build is not always trivial. We traverse from the current directory upwards\n * until we find the first `babel.config.json` and use that path.\n *\n * @param path - The path to start looking for the babel configuration\n * @returns The path to the `babel.config.json` file\n * @internal\n */\nexport function findBabelConfig(path: string): string {\n const configPath = join(path, 'babel.config.json')\n if (existsSync(configPath)) {\n return configPath\n }\n\n const parent = resolve(join(path, '..'))\n if (parent && parent !== path) {\n return findBabelConfig(parent)\n }\n\n throw new Error('Could not find `babel.config.json` in @sanity/codegen')\n}\n\n/**\n * Get the default babel configuration for `@sanity/codegen`\n *\n * @param path - The path to start looking for the babel configuration. Defaults to `__dirname`\n * @returns A babel configuration object\n * @internal\n */\nexport function getBabelConfig(path?: string): TransformOptions {\n const configPath = findBabelConfig(path || __dirname)\n return {extends: configPath}\n}\n","import {parse, type TransformOptions} from '@babel/core'\nimport type * as babelTypes from '@babel/types'\n\n// helper function to parse a source file\nexport function parseSourceFile(\n source: string,\n filename: string,\n babelOptions: TransformOptions,\n): babelTypes.File {\n const result = parse(source, {\n ...babelOptions,\n filename,\n })\n\n if (!result) {\n throw new Error(`Failed to parse ${filename}`)\n }\n\n return result\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type TransformOptions} from '@babel/core'\nimport traverse, {type Scope} from '@babel/traverse'\nimport * as babelTypes from '@babel/types'\nimport createDebug from 'debug'\n\nimport {parseSourceFile} from './parseSource'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ntype resolveExpressionReturnType = string\n\n/**\n * NamedQueryResult is a result of a named query\n */\nexport interface NamedQueryResult {\n /** name is the name of the query */\n name: string\n /** result is a groq query */\n result: resolveExpressionReturnType\n}\n\nconst TAGGED_TEMPLATE_ALLOW_LIST = ['groq']\nconst FUNCTION_WRAPPER_ALLOW_LIST = ['defineQuery']\n\n/**\n * resolveExpression takes a node and returns the resolved value of the expression.\n * @beta\n * @internal\n */\nexport function resolveExpression({\n node,\n file,\n scope,\n filename,\n resolver,\n babelConfig,\n params = [],\n fnArguments = [],\n}: {\n node: babelTypes.Node\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n params?: babelTypes.Node[]\n fnArguments?: babelTypes.Node[]\n}): resolveExpressionReturnType {\n debug(\n `Resolving node ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n if (\n babelTypes.isTaggedTemplateExpression(node) &&\n babelTypes.isIdentifier(node.tag) &&\n TAGGED_TEMPLATE_ALLOW_LIST.includes(node.tag.name)\n ) {\n return resolveExpression({\n node: node.quasi,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n\n if (babelTypes.isTemplateLiteral(node)) {\n const resolvedExpressions = node.expressions.map((expression) =>\n resolveExpression({\n node: expression,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n }),\n )\n return node.quasis\n .map((quasi, idx) => {\n return (quasi.value.cooked || '') + (resolvedExpressions[idx] || '')\n })\n .join('')\n }\n\n if (babelTypes.isLiteral(node)) {\n if (node.type === 'NullLiteral' || node.type === 'RegExpLiteral') {\n throw new Error(`Unsupported literal type: ${node.type}`)\n }\n\n return node.value.toString()\n }\n\n if (babelTypes.isIdentifier(node)) {\n return resolveIdentifier({\n node,\n scope,\n filename,\n file,\n resolver,\n fnArguments,\n babelConfig,\n params,\n })\n }\n\n if (babelTypes.isVariableDeclarator(node)) {\n if (!node.init) {\n throw new Error(`Unsupported variable declarator`)\n }\n\n return resolveExpression({\n node: node.init,\n fnArguments,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (\n babelTypes.isCallExpression(node) &&\n babelTypes.isIdentifier(node.callee) &&\n FUNCTION_WRAPPER_ALLOW_LIST.includes(node.callee.name)\n ) {\n return resolveExpression({\n node: node.arguments[0],\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n })\n }\n\n if (babelTypes.isCallExpression(node)) {\n return resolveCallExpression({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n fnArguments,\n })\n }\n\n if (\n babelTypes.isArrowFunctionExpression(node) ||\n babelTypes.isFunctionDeclaration(node) ||\n babelTypes.isFunctionExpression(node)\n ) {\n return resolveExpression({\n node: node.body,\n params: node.params,\n fnArguments,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (babelTypes.isNewExpression(node)) {\n return resolveExpression({\n node: node.callee,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (babelTypes.isImportDefaultSpecifier(node) || babelTypes.isImportSpecifier(node)) {\n return resolveImportSpecifier({node, file, scope, filename, resolver, babelConfig})\n }\n\n if (babelTypes.isAssignmentPattern(node)) {\n return resolveExpression({\n node: node.right,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n\n throw new Error(\n `Unsupported expression type: ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveIdentifier({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n fnArguments,\n params,\n}: {\n node: babelTypes.Identifier\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n fnArguments: babelTypes.Node[]\n params: babelTypes.Node[]\n}): resolveExpressionReturnType {\n const paramIndex = params.findIndex(\n (param) =>\n (babelTypes.isIdentifier(param) && node.name === param.name) ||\n (babelTypes.isAssignmentPattern(param) &&\n babelTypes.isIdentifier(param.left) &&\n node.name === param.left.name),\n )\n const argument = fnArguments[paramIndex]\n if (argument && babelTypes.isLiteral(argument)) {\n return resolveExpression({\n node: argument,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n const binding = scope.getBinding(node.name)\n if (binding) {\n if (babelTypes.isIdentifier(binding.path.node)) {\n const isSame = binding.path.node.name === node.name\n if (isSame) {\n throw new Error(\n `Could not resolve same identifier \"${node.name}\" in \"${filename}:${node.loc?.start.line}:${node.loc?.start.column}\"`,\n )\n }\n }\n return resolveExpression({\n node: binding.path.node,\n params,\n fnArguments,\n scope,\n filename,\n babelConfig,\n file,\n resolver,\n })\n }\n\n throw new Error(\n `Could not find binding for node \"${node.name}\" in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveCallExpression({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n}: {\n node: babelTypes.CallExpression\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n fnArguments: babelTypes.Node[]\n params: babelTypes.Node[]\n}): resolveExpressionReturnType {\n const {callee} = node\n return resolveExpression({\n node: callee,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n fnArguments: node.arguments,\n })\n}\n\nfunction resolveImportSpecifier({\n node,\n file,\n filename,\n resolver,\n babelConfig,\n}: {\n node: babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier | babelTypes.ExportSpecifier\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n}): resolveExpressionReturnType {\n let importDeclaration: babelTypes.ImportDeclaration | undefined\n traverse(file, {\n ImportDeclaration(n) {\n if (!babelTypes.isImportDeclaration(n.node)) {\n return\n }\n for (const specifier of n.node.specifiers) {\n if (babelTypes.isImportDefaultSpecifier(specifier)) {\n if (specifier.local.loc?.identifierName === node.local.name) {\n importDeclaration = n.node\n break\n }\n }\n if (specifier.local.name === node.local.name) {\n importDeclaration = n.node\n }\n }\n },\n })\n\n if (!importDeclaration) {\n throw new Error(`Could not find import declaration for ${node.local.name}`)\n }\n\n const importName = node.local.name // the name of the variable to import\n const importFileName = importDeclaration.source.value // the file to import from\n\n const importPath =\n importFileName.startsWith('./') || importFileName.startsWith('../')\n ? path.resolve(path.dirname(filename), importFileName)\n : importFileName\n\n const resolvedFile = resolver(importPath)\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let newScope: Scope | undefined\n traverse(tree, {\n Program(p) {\n newScope = p.scope\n },\n })\n if (!newScope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = newScope.getBinding(importName)\n if (binding) {\n return resolveExpression({\n node: binding.path.node,\n file: tree,\n scope: newScope,\n babelConfig,\n filename: resolvedFile,\n resolver,\n })\n }\n\n // It's not a global binding, but it might be a named export\n let namedExport: babelTypes.ExportNamedDeclaration | undefined\n let newImportName: string | undefined\n traverse(tree, {\n ExportDeclaration(p) {\n if (p.node.type === 'ExportNamedDeclaration') {\n for (const specifier of p.node.specifiers) {\n if (\n specifier.type === 'ExportSpecifier' &&\n specifier.exported.type === 'Identifier' &&\n specifier.exported.name === importName\n ) {\n namedExport = p.node\n newImportName = specifier.exported.name\n }\n }\n }\n },\n })\n\n if (namedExport && newImportName) {\n return resolveExportSpecifier({\n node: namedExport,\n importName: newImportName,\n filename: resolvedFile,\n resolver,\n babelConfig,\n })\n }\n\n throw new Error(`Could not find binding for import \"${importName}\" in ${importFileName}`)\n}\n\nfunction resolveExportSpecifier({\n node,\n importName,\n filename,\n babelConfig,\n resolver,\n}: {\n node: babelTypes.ExportNamedDeclaration\n importName: string\n filename: string\n babelConfig: TransformOptions\n resolver: NodeJS.RequireResolve\n}): resolveExpressionReturnType {\n if (!node.source) {\n throw new Error(`Could not find source for export \"${importName}\" in ${filename}`)\n }\n\n const importFileName = node.source.value\n const importPath = path.resolve(path.dirname(filename), importFileName)\n const resolvedFile = resolver(importPath)\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let newScope: Scope | undefined\n traverse(tree, {\n Program(p) {\n newScope = p.scope\n },\n })\n if (!newScope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = newScope.getBinding(importName)\n if (binding) {\n return resolveExpression({\n node: binding.path.node,\n file: tree,\n scope: newScope,\n filename: importFileName,\n babelConfig,\n resolver,\n })\n }\n\n throw new Error(`Could not find binding for export \"${importName}\" in ${importFileName}`)\n}\n","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'\nimport {type NamedQueryResult, resolveExpression} from './expressionResolvers'\nimport {parseSourceFile} from './parseSource'\n\nconst require = createRequire(__filename)\n\nconst groqTagName = 'groq'\nconst defineQueryFunctionName = 'defineQuery'\nconst groqModuleName = 'groq'\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): NamedQueryResult[] {\n const queries: NamedQueryResult[] = []\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\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 queryName = `${node.id.name}`\n const queryResult = resolveExpression({\n node: init,\n file,\n scope,\n babelConfig,\n filename,\n resolver,\n })\n\n queries.push({name: queryName, result: queryResult})\n }\n },\n })\n\n return 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","import createDebug from 'debug'\nimport {createMatchPath, loadConfig as loadTSConfig} from 'tsconfig-paths'\n\nconst debug = createDebug('sanity:codegen:moduleResolver')\n\n/**\n * This is a custom implementation of require.resolve that takes into account the paths\n * configuration in tsconfig.json. This is necessary if we want to resolve paths that are\n * custom defined in the tsconfig.json file.\n * Resolving here is best effort and might not work in all cases.\n * @beta\n */\nexport function getResolver(cwd?: string): NodeJS.RequireResolve {\n const tsConfig = loadTSConfig(cwd)\n\n if (tsConfig.resultType === 'failed') {\n debug('Could not load tsconfig, using default resolver: %s', tsConfig.message)\n return require.resolve\n }\n\n const matchPath = createMatchPath(\n tsConfig.absoluteBaseUrl,\n tsConfig.paths,\n tsConfig.mainFields,\n tsConfig.addMatchAll,\n )\n\n const resolve = function (request: string, options?: {paths?: string[]}): string {\n const found = matchPath(request)\n if (found !== undefined) {\n return require.resolve(found, options)\n }\n return require.resolve(request, options)\n }\n\n // wrap the resolve.path function to make it available.\n resolve.paths = (request: string): string[] | null => {\n return require.resolve.paths(request)\n }\n return resolve\n}\n","import fs from 'node:fs/promises'\n\nimport {type TransformOptions} from '@babel/core'\nimport createDebug from 'debug'\nimport glob from 'globby'\n\nimport {getBabelConfig} from '../getBabelConfig'\nimport {type NamedQueryResult} from './expressionResolvers'\nimport {findQueriesInSource} from './findQueriesInSource'\nimport {getResolver} from './moduleResolver'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ntype ResultQueries = {\n type: 'queries'\n filename: string\n queries: NamedQueryResult[]\n}\ntype ResultError = {\n type: 'error'\n error: Error\n filename: string\n}\n\n/**\n * findQueriesInPath takes a path or array of paths and returns all GROQ queries in the files.\n * @param path - The path or array of paths to search for queries\n * @param babelOptions - The babel configuration to use when parsing the source\n * @param resolver - A resolver function to use when resolving module imports\n * @returns An async generator that yields the results of the search\n * @beta\n * @internal\n */\nexport async function* findQueriesInPath({\n path,\n babelOptions = getBabelConfig(),\n resolver = getResolver(),\n}: {\n path: string | string[]\n babelOptions?: TransformOptions\n resolver?: NodeJS.RequireResolve\n}): AsyncGenerator<ResultQueries | ResultError> {\n const queryNames = new Set()\n // Holds all query names found in the source files\n debug(`Globing ${path}`)\n\n const stream = glob.stream(path, {\n absolute: false,\n ignore: ['**/node_modules/**'], // we never want to look in node_modules\n onlyFiles: true,\n })\n\n for await (const filename of stream) {\n if (typeof filename !== 'string') {\n continue\n }\n\n debug(`Found file \"${filename}\"`)\n try {\n const source = await fs.readFile(filename, 'utf8')\n const queries = findQueriesInSource(source, filename, babelOptions, resolver)\n // Check and error on duplicate query names, because we can't generate types with the same name.\n for (const query of queries) {\n if (queryNames.has(query.name)) {\n throw new Error(\n `Duplicate query name found: \"${query.name}\". Query names must be unique across all files.`,\n )\n }\n queryNames.add(query.name)\n }\n yield {type: 'queries', filename, queries}\n } catch (error) {\n debug(`Error in file \"${filename}\"`, error)\n yield {type: 'error', error, filename}\n }\n }\n}\n","import {type TransformOptions} from '@babel/core'\nimport register from '@babel/register'\n\nimport {getBabelConfig} from '../getBabelConfig'\n\n/**\n * Register Babel with the given options\n *\n * @param babelOptions - The options to use when registering Babel\n * @beta\n */\nexport function registerBabel(babelOptions?: TransformOptions): void {\n const options = babelOptions || getBabelConfig()\n\n register({...options, extensions: ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']})\n}\n","import {CodeGenerator} from '@babel/generator'\nimport * as t from '@babel/types'\nimport {\n type ArrayTypeNode,\n type DocumentSchemaType,\n type ObjectAttribute,\n type ObjectTypeNode,\n type SchemaType,\n type TypeDeclarationSchemaType,\n type TypeNode,\n type UnionTypeNode,\n} from 'groq-js'\n\nconst REFERENCE_SYMBOL_NAME = 'internalGroqTypeReferenceTo'\nconst ALL_SCHEMA_TYPES = 'AllSanitySchemaTypes'\n\ntype QueryWithTypeNode = {\n query: string\n typeNode: TypeNode\n}\n\n/**\n * A class used to generate TypeScript types from a given schema\n * @internal\n * @beta\n */\nexport class TypeGenerator {\n private generatedTypeName: Set<string> = new Set()\n private typeNameMap: Map<TypeNode | DocumentSchemaType | TypeDeclarationSchemaType, string> =\n new Map()\n\n private readonly schema: SchemaType\n\n constructor(schema: SchemaType) {\n this.schema = schema\n }\n\n /**\n * Generate TypeScript types for the given schema\n * @returns string\n * @internal\n * @beta\n */\n generateSchemaTypes(): string {\n const typeDeclarations: (t.TSTypeAliasDeclaration | t.ExportNamedDeclaration)[] = []\n\n const schemaNames = new Set<string>()\n this.schema.forEach((schema) => {\n const typeLiteral = this.getTypeNodeType(schema)\n\n const schemaName = this.getTypeName(schema.name, schema)\n schemaNames.add(schemaName)\n const typeAlias = t.tsTypeAliasDeclaration(t.identifier(schemaName), null, typeLiteral)\n\n typeDeclarations.push(t.exportNamedDeclaration(typeAlias))\n })\n\n typeDeclarations.push(\n t.exportNamedDeclaration(\n t.tsTypeAliasDeclaration(\n t.identifier(this.getTypeName(ALL_SCHEMA_TYPES)),\n null,\n t.tsUnionType(\n [...schemaNames].map((typeName) => t.tsTypeReference(t.identifier(typeName))),\n ),\n ),\n ),\n )\n\n // Generate TypeScript code from the AST nodes\n return typeDeclarations.map((decl) => new CodeGenerator(decl).generate().code).join('\\n\\n')\n }\n\n /**\n * Takes a identifier and a type node and generates a type alias for the type node.\n * @param identifierName - The name of the type to generated\n * @param typeNode - The type node to generate the type for\n * @returns\n * @internal\n * @beta\n */\n generateTypeNodeTypes(identifierName: string, typeNode: TypeNode): string {\n const type = this.getTypeNodeType(typeNode)\n\n const typeName = this.getTypeName(identifierName, typeNode)\n const typeAlias = t.tsTypeAliasDeclaration(t.identifier(typeName), null, type)\n\n return new CodeGenerator(t.exportNamedDeclaration(typeAlias)).generate().code.trim()\n }\n\n static generateKnownTypes(): string {\n const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword())\n typeOperator.operator = 'unique'\n\n const identifier = t.identifier(REFERENCE_SYMBOL_NAME)\n identifier.typeAnnotation = t.tsTypeAnnotation(typeOperator)\n\n const decleration = t.variableDeclaration('const', [t.variableDeclarator(identifier)])\n decleration.declare = true\n return new CodeGenerator(t.exportNamedDeclaration(decleration)).generate().code.trim()\n }\n\n /**\n * Takes a list of queries from the codebase and generates a type declaration\n * for SanityClient to consume.\n *\n * Note: only types that have previously been generated with `generateTypeNodeTypes`\n * will be included in the query map.\n *\n * @param queries - A list of queries to generate a type declaration for\n * @returns\n * @internal\n * @beta\n */\n generateQueryMap(queries: QueryWithTypeNode[]): string {\n const typesByQuerystring: {[query: string]: string[]} = {}\n\n for (const query of queries) {\n const name = this.typeNameMap.get(query.typeNode)\n if (!name) {\n continue\n }\n\n typesByQuerystring[query.query] ??= []\n typesByQuerystring[query.query].push(name)\n }\n\n const queryReturnInterface = t.tsInterfaceDeclaration(\n t.identifier('SanityQueries'),\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 declareModule = t.declareModule(\n t.stringLiteral('@sanity/client'),\n t.blockStatement([queryReturnInterface]),\n )\n\n const clientImport = t.importDeclaration([], t.stringLiteral('@sanity/client'))\n\n return new CodeGenerator(t.program([clientImport, declareModule])).generate().code.trim()\n }\n\n /**\n * Since we are sanitizing identifiers we migt end up with collisions. Ie there might be a type mux.video and muxVideo, both these\n * types would be sanityized into MuxVideo. To avoid this we keep track of the generated type names and add a index to the name.\n * When we reference a type we also keep track of the original name so we can reference the correct type later.\n */\n private getTypeName(\n name: string,\n typeNode?: TypeNode | DocumentSchemaType | TypeDeclarationSchemaType,\n ): string {\n const desiredName = uppercaseFirstLetter(sanitizeIdentifier(name))\n\n let generatedName = desiredName\n let i = 2\n while (this.generatedTypeName.has(generatedName)) {\n // add _ and a index and increment that index until we find a name that is not in the map\n generatedName = `${desiredName}_${i++}`\n }\n this.generatedTypeName.add(generatedName)\n if (typeNode) {\n this.typeNameMap.set(typeNode, generatedName)\n }\n\n return generatedName\n }\n\n private getTypeNodeType(\n typeNode: TypeNode | TypeDeclarationSchemaType | DocumentSchemaType,\n ): t.TSType {\n switch (typeNode.type) {\n case 'string': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.stringLiteral(typeNode.value))\n }\n return t.tsStringKeyword()\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 'boolean': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.booleanLiteral(typeNode.value))\n }\n return t.tsBooleanKeyword()\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n case 'document': {\n return this.generateDocumentType(typeNode)\n }\n case 'type': {\n return this.getTypeNodeType(typeNode.value)\n }\n case 'array': {\n return this.generateArrayTsType(typeNode)\n }\n case 'object': {\n return this.generateObjectTsType(typeNode)\n }\n case 'union': {\n return this.generateUnionTsType(typeNode)\n }\n case 'inline': {\n return t.tsTypeReference(\n t.identifier(uppercaseFirstLetter(sanitizeIdentifier(typeNode.name))),\n )\n }\n case 'null': {\n return t.tsNullKeyword()\n }\n\n default:\n // @ts-expect-error This should never happen\n throw new Error(`Type \"${typeNode.type}\" not found in schema`)\n }\n }\n\n // Helper function used to generate TS types for array type nodes.\n private generateArrayTsType(typeNode: ArrayTypeNode): t.TSTypeReference {\n const typeNodes = this.getTypeNodeType(typeNode.of)\n const arrayType = t.tsTypeReference(\n t.identifier('Array'),\n t.tsTypeParameterInstantiation([typeNodes]),\n )\n\n return arrayType\n }\n\n // Helper function used to generate TS types for object properties.\n private generateObjectProperty(key: string, attribute: ObjectAttribute): t.TSPropertySignature {\n const type = this.getTypeNodeType(attribute.value)\n const propertySignature = t.tsPropertySignature(\n t.identifier(sanitizeIdentifier(key)),\n t.tsTypeAnnotation(type),\n )\n propertySignature.optional = attribute.optional\n\n return propertySignature\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 Object.entries(typeNode.attributes).forEach(([key, attribute]) => {\n props.push(this.generateObjectProperty(key, attribute))\n })\n const rest = typeNode.rest\n if (rest !== undefined) {\n switch (rest.type) {\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n case 'object': {\n Object.entries(rest.attributes).forEach(([key, attribute]) => {\n props.push(this.generateObjectProperty(key, attribute))\n })\n break\n }\n case 'inline': {\n const referencedTypeNode = this.schema.find((schema) => schema.name === rest.name)\n if (referencedTypeNode === undefined) {\n const missing = t.tsUnknownKeyword()\n missing.trailingComments = [\n {\n type: 'CommentLine',\n value: ` Unable to locate the referenced type \"${rest.name}\" in schema`,\n },\n ]\n return missing\n }\n\n return t.tsIntersectionType([\n t.tsTypeLiteral(props),\n t.tsTypeReference(\n t.identifier(\n this.typeNameMap.get(referencedTypeNode) ||\n uppercaseFirstLetter(sanitizeIdentifier(rest.name)),\n ),\n ),\n ])\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 if (typeNode.dereferencesTo !== undefined) {\n const derefType = t.tsPropertySignature(\n t.identifier(REFERENCE_SYMBOL_NAME),\n t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo))),\n )\n derefType.computed = true\n derefType.optional = true\n props.push(derefType)\n }\n return t.tsTypeLiteral(props)\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) {\n return t.tsNeverKeyword()\n }\n if (typeNode.of.length === 1) {\n return this.getTypeNodeType(typeNode.of[0])\n }\n\n const typeNodes = typeNode.of.map((node) => this.getTypeNodeType(node))\n\n return t.tsUnionType(typeNodes)\n }\n\n // Helper function used to generate TS types for document type nodes.\n private generateDocumentType(document: DocumentSchemaType): t.TSType {\n const props = Object.entries(document.attributes).map(([key, node]) =>\n this.generateObjectProperty(key, node),\n )\n\n return t.tsTypeLiteral(props)\n }\n}\nfunction uppercaseFirstLetter(input: string): string {\n return input.charAt(0).toUpperCase() + input.slice(1)\n}\n\nfunction sanitizeIdentifier(input: string): string {\n return `${input.replace(/^\\d/, '_').replace(/[^$\\w]+(.)/g, (_, char) => char.toUpperCase())}`\n}\n"],"names":["z","path","readFile","json5","parse","join","existsSync","resolve","debug","createDebug","babelTypes","traverse","fs","require","createRequire","loadTSConfig","createMatchPath","glob","register","t","CodeGenerator"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAKa,MAAA,kBAAkBA,aAAE,OAAO;AAAA,EACtC,MAAMA,aACH,OAAO,EACP,GAAGA,aAAE,MAAMA,aAAE,QAAQ,CAAC,EACtB,QAAQ;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AAAA,EACH,QAAQA,aAAE,SAAS,QAAQ,eAAe;AAAA,EAC1C,WAAWA,aAAE,SAAS,QAAQ,mBAAmB;AAAA,EACjD,qBAAqBA,aAAE,QAAQ,EAAE,QAAQ,EAAI;AAAA,EAC7C,uBAAuBA,aAAE,QAAQ,EAAE,QAAQ,EAAK;AAClD,CAAC;AAID,eAAsB,WAAWC,OAAsC;AACjE,MAAA;AACI,UAAA,UAAU,MAAMC,GAAS,SAAAD,OAAM,OAAO,GACtC,OAAOE,iBA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AAe,CAAC,GAAG,SAAS,KAAK,YAAa,CAAA,CAAC;AAC7F;;;;;;;;;"}
|
package/lib/index.mjs
CHANGED
|
@@ -90,9 +90,8 @@ function resolveExpression({
|
|
|
90
90
|
params = [],
|
|
91
91
|
fnArguments = []
|
|
92
92
|
}) {
|
|
93
|
-
var _a, _b, _c, _d;
|
|
94
93
|
if (debug$2(
|
|
95
|
-
`Resolving node ${node.type} in ${filename}:${
|
|
94
|
+
`Resolving node ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`
|
|
96
95
|
), t.isTaggedTemplateExpression(node) && t.isIdentifier(node.tag) && TAGGED_TEMPLATE_ALLOW_LIST.includes(node.tag.name))
|
|
97
96
|
return resolveExpression({
|
|
98
97
|
node: node.quasi,
|
|
@@ -203,7 +202,7 @@ function resolveExpression({
|
|
|
203
202
|
fnArguments
|
|
204
203
|
});
|
|
205
204
|
throw new Error(
|
|
206
|
-
`Unsupported expression type: ${node.type} in ${filename}:${
|
|
205
|
+
`Unsupported expression type: ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`
|
|
207
206
|
);
|
|
208
207
|
}
|
|
209
208
|
function resolveIdentifier({
|
|
@@ -216,7 +215,6 @@ function resolveIdentifier({
|
|
|
216
215
|
fnArguments,
|
|
217
216
|
params
|
|
218
217
|
}) {
|
|
219
|
-
var _a, _b, _c, _d;
|
|
220
218
|
const paramIndex = params.findIndex(
|
|
221
219
|
(param) => t.isIdentifier(param) && node.name === param.name || t.isAssignmentPattern(param) && t.isIdentifier(param.left) && node.name === param.left.name
|
|
222
220
|
), argument = fnArguments[paramIndex];
|
|
@@ -235,7 +233,7 @@ function resolveIdentifier({
|
|
|
235
233
|
if (binding) {
|
|
236
234
|
if (t.isIdentifier(binding.path.node) && binding.path.node.name === node.name)
|
|
237
235
|
throw new Error(
|
|
238
|
-
`Could not resolve same identifier "${node.name}" in "${filename}:${
|
|
236
|
+
`Could not resolve same identifier "${node.name}" in "${filename}:${node.loc?.start.line}:${node.loc?.start.column}"`
|
|
239
237
|
);
|
|
240
238
|
return resolveExpression({
|
|
241
239
|
node: binding.path.node,
|
|
@@ -249,7 +247,7 @@ function resolveIdentifier({
|
|
|
249
247
|
});
|
|
250
248
|
}
|
|
251
249
|
throw new Error(
|
|
252
|
-
`Could not find binding for node "${node.name}" in ${filename}:${
|
|
250
|
+
`Could not find binding for node "${node.name}" in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`
|
|
253
251
|
);
|
|
254
252
|
}
|
|
255
253
|
function resolveCallExpression({
|
|
@@ -283,10 +281,9 @@ function resolveImportSpecifier({
|
|
|
283
281
|
let importDeclaration;
|
|
284
282
|
if (traverse(file, {
|
|
285
283
|
ImportDeclaration(n) {
|
|
286
|
-
var _a;
|
|
287
284
|
if (t.isImportDeclaration(n.node))
|
|
288
285
|
for (const specifier of n.node.specifiers) {
|
|
289
|
-
if (t.isImportDefaultSpecifier(specifier) &&
|
|
286
|
+
if (t.isImportDefaultSpecifier(specifier) && specifier.local.loc?.identifierName === node.local.name) {
|
|
290
287
|
importDeclaration = n.node;
|
|
291
288
|
break;
|
|
292
289
|
}
|
|
@@ -384,11 +381,10 @@ function findQueriesInSource(source, filename, babelConfig = getBabelConfig(), r
|
|
|
384
381
|
}), queries;
|
|
385
382
|
}
|
|
386
383
|
function declarationLeadingCommentContains(path2, comment) {
|
|
387
|
-
var _a, _b;
|
|
388
384
|
const variableDeclaration = path2.find((node) => node.isVariableDeclaration());
|
|
389
|
-
return variableDeclaration ? !!(
|
|
385
|
+
return variableDeclaration ? !!(variableDeclaration.node.leadingComments?.find(
|
|
390
386
|
(commentItem) => commentItem.value.trim() === comment
|
|
391
|
-
) ||
|
|
387
|
+
) || variableDeclaration.parent.leadingComments?.find(
|
|
392
388
|
(commentItem) => commentItem.value.trim() === comment
|
|
393
389
|
)) : !1;
|
|
394
390
|
}
|
|
@@ -469,11 +465,13 @@ function registerBabel(babelOptions) {
|
|
|
469
465
|
const options = babelOptions || getBabelConfig();
|
|
470
466
|
register({ ...options, extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"] });
|
|
471
467
|
}
|
|
472
|
-
var __defProp = Object.defineProperty, __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
|
|
473
468
|
const REFERENCE_SYMBOL_NAME = "internalGroqTypeReferenceTo", ALL_SCHEMA_TYPES = "AllSanitySchemaTypes";
|
|
474
469
|
class TypeGenerator {
|
|
470
|
+
generatedTypeName = /* @__PURE__ */ new Set();
|
|
471
|
+
typeNameMap = /* @__PURE__ */ new Map();
|
|
472
|
+
schema;
|
|
475
473
|
constructor(schema) {
|
|
476
|
-
|
|
474
|
+
this.schema = schema;
|
|
477
475
|
}
|
|
478
476
|
/**
|
|
479
477
|
* Generate TypeScript types for the given schema
|
|
@@ -535,11 +533,10 @@ class TypeGenerator {
|
|
|
535
533
|
* @beta
|
|
536
534
|
*/
|
|
537
535
|
generateQueryMap(queries) {
|
|
538
|
-
var _a;
|
|
539
536
|
const typesByQuerystring = {};
|
|
540
537
|
for (const query of queries) {
|
|
541
538
|
const name = this.typeNameMap.get(query.typeNode);
|
|
542
|
-
name && (typesByQuerystring[
|
|
539
|
+
name && (typesByQuerystring[query.query] ??= [], typesByQuerystring[query.query].push(name));
|
|
543
540
|
}
|
|
544
541
|
const queryReturnInterface = t.tsInterfaceDeclaration(
|
|
545
542
|
t.identifier("SanityQueries"),
|
package/lib/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../src/readConfig.ts","../src/readSchema.ts","../src/safeParseQuery.ts","../src/getBabelConfig.ts","../src/typescript/parseSource.ts","../src/typescript/expressionResolvers.ts","../src/typescript/findQueriesInSource.ts","../src/typescript/moduleResolver.ts","../src/typescript/findQueriesInPath.ts","../src/typescript/registerBabel.ts","../src/typescript/typeGenerator.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport * as json5 from 'json5'\nimport * as z from 'zod'\n\nexport const configDefintion = z.object({\n path: z\n .string()\n .or(z.array(z.string()))\n .default([\n './src/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n './app/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n ]),\n schema: z.string().default('./schema.json'),\n generates: z.string().default('./sanity.types.ts'),\n formatGeneratedCode: z.boolean().default(true),\n overloadClientMethods: z.boolean().default(false),\n})\n\nexport type CodegenConfig = z.infer<typeof configDefintion>\n\nexport async function readConfig(path: string): Promise<CodegenConfig> {\n try {\n const content = await readFile(path, 'utf-8')\n const json = json5.parse(content)\n return configDefintion.parseAsync(json)\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(`Error in config file\\n ${error.errors.map((err) => err.message).join('\\n')}`)\n }\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return configDefintion.parse({})\n }\n\n throw error\n }\n}\n","import {readFile} from 'node:fs/promises'\n\nimport {type SchemaType} from 'groq-js'\n\n/**\n * Read a schema from a given path\n * @param path - The path to the schema\n * @returns The schema\n * @internal\n * @beta\n **/\nexport async function readSchema(path: string): Promise<SchemaType> {\n const content = await readFile(path, 'utf-8')\n return JSON.parse(content) // todo: ZOD validation?\n}\n","import {parse} from 'groq-js'\n\n/**\n * safeParseQuery parses a GROQ query string, but first attempts to extract any parameters used in slices. This method is _only_\n * intended for use in type generation where we don't actually execute the parsed AST on a dataset, and should not be used elsewhere.\n * @internal\n */\nexport function safeParseQuery(query: string) {\n const params: Record<string, unknown> = {}\n\n for (const param of extractSliceParams(query)) {\n params[param] = 0 // we don't care about the value, just the type\n }\n return parse(query, {params})\n}\n\n/**\n * Finds occurences of `[($start|{number})..($end|{number})]` in a query string and returns the start and end values, and return\n * the names of the start and end variables.\n * @internal\n */\nexport function* extractSliceParams(query: string): Generator<string> {\n const sliceRegex = /\\[(\\$(\\w+)|\\d)\\.\\.\\.?(\\$(\\w+)|\\d)\\]/g\n const matches = query.matchAll(sliceRegex)\n if (!matches) {\n return\n }\n const params = new Set<string>()\n for (const match of matches) {\n const start = match[1] === `$${match[2]}` ? match[2] : null\n if (start !== null) {\n yield start\n }\n const end = match[3] === `$${match[4]}` ? match[4] : null\n if (end !== null) {\n yield end\n }\n }\n}\n","import {existsSync} from 'node:fs'\nimport {join, resolve} from 'node:path'\n\nimport {type TransformOptions} from '@babel/core'\n\n/**\n * Because of bundlers and compilers, knowing the exact path the babel configuration will be\n * located at post - build is not always trivial. We traverse from the current directory upwards\n * until we find the first `babel.config.json` and use that path.\n *\n * @param path - The path to start looking for the babel configuration\n * @returns The path to the `babel.config.json` file\n * @internal\n */\nexport function findBabelConfig(path: string): string {\n const configPath = join(path, 'babel.config.json')\n if (existsSync(configPath)) {\n return configPath\n }\n\n const parent = resolve(join(path, '..'))\n if (parent && parent !== path) {\n return findBabelConfig(parent)\n }\n\n throw new Error('Could not find `babel.config.json` in @sanity/codegen')\n}\n\n/**\n * Get the default babel configuration for `@sanity/codegen`\n *\n * @param path - The path to start looking for the babel configuration. Defaults to `__dirname`\n * @returns A babel configuration object\n * @internal\n */\nexport function getBabelConfig(path?: string): TransformOptions {\n const configPath = findBabelConfig(path || __dirname)\n return {extends: configPath}\n}\n","import {parse, type TransformOptions} from '@babel/core'\nimport type * as babelTypes from '@babel/types'\n\n// helper function to parse a source file\nexport function parseSourceFile(\n source: string,\n filename: string,\n babelOptions: TransformOptions,\n): babelTypes.File {\n const result = parse(source, {\n ...babelOptions,\n filename,\n })\n\n if (!result) {\n throw new Error(`Failed to parse ${filename}`)\n }\n\n return result\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type TransformOptions} from '@babel/core'\nimport traverse, {type Scope} from '@babel/traverse'\nimport * as babelTypes from '@babel/types'\nimport createDebug from 'debug'\n\nimport {parseSourceFile} from './parseSource'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ntype resolveExpressionReturnType = string\n\n/**\n * NamedQueryResult is a result of a named query\n */\nexport interface NamedQueryResult {\n /** name is the name of the query */\n name: string\n /** result is a groq query */\n result: resolveExpressionReturnType\n}\n\nconst TAGGED_TEMPLATE_ALLOW_LIST = ['groq']\nconst FUNCTION_WRAPPER_ALLOW_LIST = ['defineQuery']\n\n/**\n * resolveExpression takes a node and returns the resolved value of the expression.\n * @beta\n * @internal\n */\nexport function resolveExpression({\n node,\n file,\n scope,\n filename,\n resolver,\n babelConfig,\n params = [],\n fnArguments = [],\n}: {\n node: babelTypes.Node\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n params?: babelTypes.Node[]\n fnArguments?: babelTypes.Node[]\n}): resolveExpressionReturnType {\n debug(\n `Resolving node ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n if (\n babelTypes.isTaggedTemplateExpression(node) &&\n babelTypes.isIdentifier(node.tag) &&\n TAGGED_TEMPLATE_ALLOW_LIST.includes(node.tag.name)\n ) {\n return resolveExpression({\n node: node.quasi,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n\n if (babelTypes.isTemplateLiteral(node)) {\n const resolvedExpressions = node.expressions.map((expression) =>\n resolveExpression({\n node: expression,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n }),\n )\n return node.quasis\n .map((quasi, idx) => {\n return (quasi.value.cooked || '') + (resolvedExpressions[idx] || '')\n })\n .join('')\n }\n\n if (babelTypes.isLiteral(node)) {\n if (node.type === 'NullLiteral' || node.type === 'RegExpLiteral') {\n throw new Error(`Unsupported literal type: ${node.type}`)\n }\n\n return node.value.toString()\n }\n\n if (babelTypes.isIdentifier(node)) {\n return resolveIdentifier({\n node,\n scope,\n filename,\n file,\n resolver,\n fnArguments,\n babelConfig,\n params,\n })\n }\n\n if (babelTypes.isVariableDeclarator(node)) {\n if (!node.init) {\n throw new Error(`Unsupported variable declarator`)\n }\n\n return resolveExpression({\n node: node.init,\n fnArguments,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (\n babelTypes.isCallExpression(node) &&\n babelTypes.isIdentifier(node.callee) &&\n FUNCTION_WRAPPER_ALLOW_LIST.includes(node.callee.name)\n ) {\n return resolveExpression({\n node: node.arguments[0],\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n })\n }\n\n if (babelTypes.isCallExpression(node)) {\n return resolveCallExpression({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n fnArguments,\n })\n }\n\n if (\n babelTypes.isArrowFunctionExpression(node) ||\n babelTypes.isFunctionDeclaration(node) ||\n babelTypes.isFunctionExpression(node)\n ) {\n return resolveExpression({\n node: node.body,\n params: node.params,\n fnArguments,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (babelTypes.isNewExpression(node)) {\n return resolveExpression({\n node: node.callee,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (babelTypes.isImportDefaultSpecifier(node) || babelTypes.isImportSpecifier(node)) {\n return resolveImportSpecifier({node, file, scope, filename, resolver, babelConfig})\n }\n\n if (babelTypes.isAssignmentPattern(node)) {\n return resolveExpression({\n node: node.right,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n\n throw new Error(\n `Unsupported expression type: ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveIdentifier({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n fnArguments,\n params,\n}: {\n node: babelTypes.Identifier\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n fnArguments: babelTypes.Node[]\n params: babelTypes.Node[]\n}): resolveExpressionReturnType {\n const paramIndex = params.findIndex(\n (param) =>\n (babelTypes.isIdentifier(param) && node.name === param.name) ||\n (babelTypes.isAssignmentPattern(param) &&\n babelTypes.isIdentifier(param.left) &&\n node.name === param.left.name),\n )\n const argument = fnArguments[paramIndex]\n if (argument && babelTypes.isLiteral(argument)) {\n return resolveExpression({\n node: argument,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n const binding = scope.getBinding(node.name)\n if (binding) {\n if (babelTypes.isIdentifier(binding.path.node)) {\n const isSame = binding.path.node.name === node.name\n if (isSame) {\n throw new Error(\n `Could not resolve same identifier \"${node.name}\" in \"${filename}:${node.loc?.start.line}:${node.loc?.start.column}\"`,\n )\n }\n }\n return resolveExpression({\n node: binding.path.node,\n params,\n fnArguments,\n scope,\n filename,\n babelConfig,\n file,\n resolver,\n })\n }\n\n throw new Error(\n `Could not find binding for node \"${node.name}\" in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveCallExpression({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n}: {\n node: babelTypes.CallExpression\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n fnArguments: babelTypes.Node[]\n params: babelTypes.Node[]\n}): resolveExpressionReturnType {\n const {callee} = node\n return resolveExpression({\n node: callee,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n fnArguments: node.arguments,\n })\n}\n\nfunction resolveImportSpecifier({\n node,\n file,\n filename,\n resolver,\n babelConfig,\n}: {\n node: babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier | babelTypes.ExportSpecifier\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n}): resolveExpressionReturnType {\n let importDeclaration: babelTypes.ImportDeclaration | undefined\n traverse(file, {\n ImportDeclaration(n) {\n if (!babelTypes.isImportDeclaration(n.node)) {\n return\n }\n for (const specifier of n.node.specifiers) {\n if (babelTypes.isImportDefaultSpecifier(specifier)) {\n if (specifier.local.loc?.identifierName === node.local.name) {\n importDeclaration = n.node\n break\n }\n }\n if (specifier.local.name === node.local.name) {\n importDeclaration = n.node\n }\n }\n },\n })\n\n if (!importDeclaration) {\n throw new Error(`Could not find import declaration for ${node.local.name}`)\n }\n\n const importName = node.local.name // the name of the variable to import\n const importFileName = importDeclaration.source.value // the file to import from\n\n const importPath =\n importFileName.startsWith('./') || importFileName.startsWith('../')\n ? path.resolve(path.dirname(filename), importFileName)\n : importFileName\n\n const resolvedFile = resolver(importPath)\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let newScope: Scope | undefined\n traverse(tree, {\n Program(p) {\n newScope = p.scope\n },\n })\n if (!newScope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = newScope.getBinding(importName)\n if (binding) {\n return resolveExpression({\n node: binding.path.node,\n file: tree,\n scope: newScope,\n babelConfig,\n filename: resolvedFile,\n resolver,\n })\n }\n\n // It's not a global binding, but it might be a named export\n let namedExport: babelTypes.ExportNamedDeclaration | undefined\n let newImportName: string | undefined\n traverse(tree, {\n ExportDeclaration(p) {\n if (p.node.type === 'ExportNamedDeclaration') {\n for (const specifier of p.node.specifiers) {\n if (\n specifier.type === 'ExportSpecifier' &&\n specifier.exported.type === 'Identifier' &&\n specifier.exported.name === importName\n ) {\n namedExport = p.node\n newImportName = specifier.exported.name\n }\n }\n }\n },\n })\n\n if (namedExport && newImportName) {\n return resolveExportSpecifier({\n node: namedExport,\n importName: newImportName,\n filename: resolvedFile,\n resolver,\n babelConfig,\n })\n }\n\n throw new Error(`Could not find binding for import \"${importName}\" in ${importFileName}`)\n}\n\nfunction resolveExportSpecifier({\n node,\n importName,\n filename,\n babelConfig,\n resolver,\n}: {\n node: babelTypes.ExportNamedDeclaration\n importName: string\n filename: string\n babelConfig: TransformOptions\n resolver: NodeJS.RequireResolve\n}): resolveExpressionReturnType {\n if (!node.source) {\n throw new Error(`Could not find source for export \"${importName}\" in ${filename}`)\n }\n\n const importFileName = node.source.value\n const importPath = path.resolve(path.dirname(filename), importFileName)\n const resolvedFile = resolver(importPath)\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let newScope: Scope | undefined\n traverse(tree, {\n Program(p) {\n newScope = p.scope\n },\n })\n if (!newScope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = newScope.getBinding(importName)\n if (binding) {\n return resolveExpression({\n node: binding.path.node,\n file: tree,\n scope: newScope,\n filename: importFileName,\n babelConfig,\n resolver,\n })\n }\n\n throw new Error(`Could not find binding for export \"${importName}\" in ${importFileName}`)\n}\n","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'\nimport {type NamedQueryResult, resolveExpression} from './expressionResolvers'\nimport {parseSourceFile} from './parseSource'\n\nconst require = createRequire(__filename)\n\nconst groqTagName = 'groq'\nconst defineQueryFunctionName = 'defineQuery'\nconst groqModuleName = 'groq'\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): NamedQueryResult[] {\n const queries: NamedQueryResult[] = []\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\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 queryName = `${node.id.name}`\n const queryResult = resolveExpression({\n node: init,\n file,\n scope,\n babelConfig,\n filename,\n resolver,\n })\n\n queries.push({name: queryName, result: queryResult})\n }\n },\n })\n\n return 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","import createDebug from 'debug'\nimport {createMatchPath, loadConfig as loadTSConfig} from 'tsconfig-paths'\n\nconst debug = createDebug('sanity:codegen:moduleResolver')\n\n/**\n * This is a custom implementation of require.resolve that takes into account the paths\n * configuration in tsconfig.json. This is necessary if we want to resolve paths that are\n * custom defined in the tsconfig.json file.\n * Resolving here is best effort and might not work in all cases.\n * @beta\n */\nexport function getResolver(cwd?: string): NodeJS.RequireResolve {\n const tsConfig = loadTSConfig(cwd)\n\n if (tsConfig.resultType === 'failed') {\n debug('Could not load tsconfig, using default resolver: %s', tsConfig.message)\n return require.resolve\n }\n\n const matchPath = createMatchPath(\n tsConfig.absoluteBaseUrl,\n tsConfig.paths,\n tsConfig.mainFields,\n tsConfig.addMatchAll,\n )\n\n const resolve = function (request: string, options?: {paths?: string[]}): string {\n const found = matchPath(request)\n if (found !== undefined) {\n return require.resolve(found, options)\n }\n return require.resolve(request, options)\n }\n\n // wrap the resolve.path function to make it available.\n resolve.paths = (request: string): string[] | null => {\n return require.resolve.paths(request)\n }\n return resolve\n}\n","import fs from 'node:fs/promises'\n\nimport {type TransformOptions} from '@babel/core'\nimport createDebug from 'debug'\nimport glob from 'globby'\n\nimport {getBabelConfig} from '../getBabelConfig'\nimport {type NamedQueryResult} from './expressionResolvers'\nimport {findQueriesInSource} from './findQueriesInSource'\nimport {getResolver} from './moduleResolver'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ntype ResultQueries = {\n type: 'queries'\n filename: string\n queries: NamedQueryResult[]\n}\ntype ResultError = {\n type: 'error'\n error: Error\n filename: string\n}\n\n/**\n * findQueriesInPath takes a path or array of paths and returns all GROQ queries in the files.\n * @param path - The path or array of paths to search for queries\n * @param babelOptions - The babel configuration to use when parsing the source\n * @param resolver - A resolver function to use when resolving module imports\n * @returns An async generator that yields the results of the search\n * @beta\n * @internal\n */\nexport async function* findQueriesInPath({\n path,\n babelOptions = getBabelConfig(),\n resolver = getResolver(),\n}: {\n path: string | string[]\n babelOptions?: TransformOptions\n resolver?: NodeJS.RequireResolve\n}): AsyncGenerator<ResultQueries | ResultError> {\n const queryNames = new Set()\n // Holds all query names found in the source files\n debug(`Globing ${path}`)\n\n const stream = glob.stream(path, {\n absolute: false,\n ignore: ['**/node_modules/**'], // we never want to look in node_modules\n onlyFiles: true,\n })\n\n for await (const filename of stream) {\n if (typeof filename !== 'string') {\n continue\n }\n\n debug(`Found file \"${filename}\"`)\n try {\n const source = await fs.readFile(filename, 'utf8')\n const queries = findQueriesInSource(source, filename, babelOptions, resolver)\n // Check and error on duplicate query names, because we can't generate types with the same name.\n for (const query of queries) {\n if (queryNames.has(query.name)) {\n throw new Error(\n `Duplicate query name found: \"${query.name}\". Query names must be unique across all files.`,\n )\n }\n queryNames.add(query.name)\n }\n yield {type: 'queries', filename, queries}\n } catch (error) {\n debug(`Error in file \"${filename}\"`, error)\n yield {type: 'error', error, filename}\n }\n }\n}\n","import {type TransformOptions} from '@babel/core'\nimport register from '@babel/register'\n\nimport {getBabelConfig} from '../getBabelConfig'\n\n/**\n * Register Babel with the given options\n *\n * @param babelOptions - The options to use when registering Babel\n * @beta\n */\nexport function registerBabel(babelOptions?: TransformOptions): void {\n const options = babelOptions || getBabelConfig()\n\n register({...options, extensions: ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']})\n}\n","import {CodeGenerator} from '@babel/generator'\nimport * as t from '@babel/types'\nimport {\n type ArrayTypeNode,\n type DocumentSchemaType,\n type ObjectAttribute,\n type ObjectTypeNode,\n type SchemaType,\n type TypeDeclarationSchemaType,\n type TypeNode,\n type UnionTypeNode,\n} from 'groq-js'\n\nconst REFERENCE_SYMBOL_NAME = 'internalGroqTypeReferenceTo'\nconst ALL_SCHEMA_TYPES = 'AllSanitySchemaTypes'\n\ntype QueryWithTypeNode = {\n query: string\n typeNode: TypeNode\n}\n\n/**\n * A class used to generate TypeScript types from a given schema\n * @internal\n * @beta\n */\nexport class TypeGenerator {\n private generatedTypeName: Set<string> = new Set()\n private typeNameMap: Map<TypeNode | DocumentSchemaType | TypeDeclarationSchemaType, string> =\n new Map()\n\n private readonly schema: SchemaType\n\n constructor(schema: SchemaType) {\n this.schema = schema\n }\n\n /**\n * Generate TypeScript types for the given schema\n * @returns string\n * @internal\n * @beta\n */\n generateSchemaTypes(): string {\n const typeDeclarations: (t.TSTypeAliasDeclaration | t.ExportNamedDeclaration)[] = []\n\n const schemaNames = new Set<string>()\n this.schema.forEach((schema) => {\n const typeLiteral = this.getTypeNodeType(schema)\n\n const schemaName = this.getTypeName(schema.name, schema)\n schemaNames.add(schemaName)\n const typeAlias = t.tsTypeAliasDeclaration(t.identifier(schemaName), null, typeLiteral)\n\n typeDeclarations.push(t.exportNamedDeclaration(typeAlias))\n })\n\n typeDeclarations.push(\n t.exportNamedDeclaration(\n t.tsTypeAliasDeclaration(\n t.identifier(this.getTypeName(ALL_SCHEMA_TYPES)),\n null,\n t.tsUnionType(\n [...schemaNames].map((typeName) => t.tsTypeReference(t.identifier(typeName))),\n ),\n ),\n ),\n )\n\n // Generate TypeScript code from the AST nodes\n return typeDeclarations.map((decl) => new CodeGenerator(decl).generate().code).join('\\n\\n')\n }\n\n /**\n * Takes a identifier and a type node and generates a type alias for the type node.\n * @param identifierName - The name of the type to generated\n * @param typeNode - The type node to generate the type for\n * @returns\n * @internal\n * @beta\n */\n generateTypeNodeTypes(identifierName: string, typeNode: TypeNode): string {\n const type = this.getTypeNodeType(typeNode)\n\n const typeName = this.getTypeName(identifierName, typeNode)\n const typeAlias = t.tsTypeAliasDeclaration(t.identifier(typeName), null, type)\n\n return new CodeGenerator(t.exportNamedDeclaration(typeAlias)).generate().code.trim()\n }\n\n static generateKnownTypes(): string {\n const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword())\n typeOperator.operator = 'unique'\n\n const identifier = t.identifier(REFERENCE_SYMBOL_NAME)\n identifier.typeAnnotation = t.tsTypeAnnotation(typeOperator)\n\n const decleration = t.variableDeclaration('const', [t.variableDeclarator(identifier)])\n decleration.declare = true\n return new CodeGenerator(t.exportNamedDeclaration(decleration)).generate().code.trim()\n }\n\n /**\n * Takes a list of queries from the codebase and generates a type declaration\n * for SanityClient to consume.\n *\n * Note: only types that have previously been generated with `generateTypeNodeTypes`\n * will be included in the query map.\n *\n * @param queries - A list of queries to generate a type declaration for\n * @returns\n * @internal\n * @beta\n */\n generateQueryMap(queries: QueryWithTypeNode[]): string {\n const typesByQuerystring: {[query: string]: string[]} = {}\n\n for (const query of queries) {\n const name = this.typeNameMap.get(query.typeNode)\n if (!name) {\n continue\n }\n\n typesByQuerystring[query.query] ??= []\n typesByQuerystring[query.query].push(name)\n }\n\n const queryReturnInterface = t.tsInterfaceDeclaration(\n t.identifier('SanityQueries'),\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 declareModule = t.declareModule(\n t.stringLiteral('@sanity/client'),\n t.blockStatement([queryReturnInterface]),\n )\n\n const clientImport = t.importDeclaration([], t.stringLiteral('@sanity/client'))\n\n return new CodeGenerator(t.program([clientImport, declareModule])).generate().code.trim()\n }\n\n /**\n * Since we are sanitizing identifiers we migt end up with collisions. Ie there might be a type mux.video and muxVideo, both these\n * types would be sanityized into MuxVideo. To avoid this we keep track of the generated type names and add a index to the name.\n * When we reference a type we also keep track of the original name so we can reference the correct type later.\n */\n private getTypeName(\n name: string,\n typeNode?: TypeNode | DocumentSchemaType | TypeDeclarationSchemaType,\n ): string {\n const desiredName = uppercaseFirstLetter(sanitizeIdentifier(name))\n\n let generatedName = desiredName\n let i = 2\n while (this.generatedTypeName.has(generatedName)) {\n // add _ and a index and increment that index until we find a name that is not in the map\n generatedName = `${desiredName}_${i++}`\n }\n this.generatedTypeName.add(generatedName)\n if (typeNode) {\n this.typeNameMap.set(typeNode, generatedName)\n }\n\n return generatedName\n }\n\n private getTypeNodeType(\n typeNode: TypeNode | TypeDeclarationSchemaType | DocumentSchemaType,\n ): t.TSType {\n switch (typeNode.type) {\n case 'string': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.stringLiteral(typeNode.value))\n }\n return t.tsStringKeyword()\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 'boolean': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.booleanLiteral(typeNode.value))\n }\n return t.tsBooleanKeyword()\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n case 'document': {\n return this.generateDocumentType(typeNode)\n }\n case 'type': {\n return this.getTypeNodeType(typeNode.value)\n }\n case 'array': {\n return this.generateArrayTsType(typeNode)\n }\n case 'object': {\n return this.generateObjectTsType(typeNode)\n }\n case 'union': {\n return this.generateUnionTsType(typeNode)\n }\n case 'inline': {\n return t.tsTypeReference(\n t.identifier(uppercaseFirstLetter(sanitizeIdentifier(typeNode.name))),\n )\n }\n case 'null': {\n return t.tsNullKeyword()\n }\n\n default:\n // @ts-expect-error This should never happen\n throw new Error(`Type \"${typeNode.type}\" not found in schema`)\n }\n }\n\n // Helper function used to generate TS types for array type nodes.\n private generateArrayTsType(typeNode: ArrayTypeNode): t.TSTypeReference {\n const typeNodes = this.getTypeNodeType(typeNode.of)\n const arrayType = t.tsTypeReference(\n t.identifier('Array'),\n t.tsTypeParameterInstantiation([typeNodes]),\n )\n\n return arrayType\n }\n\n // Helper function used to generate TS types for object properties.\n private generateObjectProperty(key: string, attribute: ObjectAttribute): t.TSPropertySignature {\n const type = this.getTypeNodeType(attribute.value)\n const propertySignature = t.tsPropertySignature(\n t.identifier(sanitizeIdentifier(key)),\n t.tsTypeAnnotation(type),\n )\n propertySignature.optional = attribute.optional\n\n return propertySignature\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 Object.entries(typeNode.attributes).forEach(([key, attribute]) => {\n props.push(this.generateObjectProperty(key, attribute))\n })\n const rest = typeNode.rest\n if (rest !== undefined) {\n switch (rest.type) {\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n case 'object': {\n Object.entries(rest.attributes).forEach(([key, attribute]) => {\n props.push(this.generateObjectProperty(key, attribute))\n })\n break\n }\n case 'inline': {\n const referencedTypeNode = this.schema.find((schema) => schema.name === rest.name)\n if (referencedTypeNode === undefined) {\n const missing = t.tsUnknownKeyword()\n missing.trailingComments = [\n {\n type: 'CommentLine',\n value: ` Unable to locate the referenced type \"${rest.name}\" in schema`,\n },\n ]\n return missing\n }\n\n return t.tsIntersectionType([\n t.tsTypeLiteral(props),\n t.tsTypeReference(\n t.identifier(\n this.typeNameMap.get(referencedTypeNode) ||\n uppercaseFirstLetter(sanitizeIdentifier(rest.name)),\n ),\n ),\n ])\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 if (typeNode.dereferencesTo !== undefined) {\n const derefType = t.tsPropertySignature(\n t.identifier(REFERENCE_SYMBOL_NAME),\n t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo))),\n )\n derefType.computed = true\n derefType.optional = true\n props.push(derefType)\n }\n return t.tsTypeLiteral(props)\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) {\n return t.tsNeverKeyword()\n }\n if (typeNode.of.length === 1) {\n return this.getTypeNodeType(typeNode.of[0])\n }\n\n const typeNodes = typeNode.of.map((node) => this.getTypeNodeType(node))\n\n return t.tsUnionType(typeNodes)\n }\n\n // Helper function used to generate TS types for document type nodes.\n private generateDocumentType(document: DocumentSchemaType): t.TSType {\n const props = Object.entries(document.attributes).map(([key, node]) =>\n this.generateObjectProperty(key, node),\n )\n\n return t.tsTypeLiteral(props)\n }\n}\nfunction uppercaseFirstLetter(input: string): string {\n return input.charAt(0).toUpperCase() + input.slice(1)\n}\n\nfunction sanitizeIdentifier(input: string): string {\n return `${input.replace(/^\\d/, '_').repl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AU,WAAW,IACrB,MAAM,KAAK,SAAS;AAAA,IACtB;AACO,WAAA,EAAE,cAAc,KAAK;AAAA,EAC9B;AAAA;AAAA,EAGQ,oBAAoB,UAAmC;AACzD,QAAA,SAAS,GAAG,WAAW;AACzB,aAAO,EAAE;AAEP,QAAA,SAAS,GAAG,WAAW;AACzB,aAAO,KAAK,gBAAgB,SAAS,GAAG,CAAC,CAAC;AAGtC,UAAA,YAAY,SAAS,GAAG,IAAI,CAAC,SAAS,KAAK,gBAAgB,IAAI,CAAC;AAE/D,WAAA,EAAE,YAAY,SAAS;AAAA,EAChC;AAAA;AAAA,EAGQ,qBAAqB,UAAwC;AACnE,UAAM,QAAQ,OAAO,QAAQ,SAAS,UAAU,EAAE;AAAA,MAAI,CAAC,CAAC,KAAK,IAAI,MAC/D,KAAK,uBAAuB,KAAK,IAAI;AAAA,IAAA;AAGhC,WAAA,EAAE,cAAc,KAAK;AAAA,EAC9B;AACF;AACA,SAAS,qBAAqB,OAAuB;AAC5C,SAAA,MAAM,OAAO,CAAC,EAAE,gBAAgB,MAAM,MAAM,CAAC;AACtD;AAEA,SAAS,mBAAmB,OAAuB;AACjD,SAAO,GAAG,MAAM,QAAQ,OAAO,GAAG,EAAE,QAAQ,eAAe,CAAC,GAAG,SAAS,KAAK,YAAa,CAAA,CAAC;AAC7F;"}
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../src/readConfig.ts","../src/readSchema.ts","../src/safeParseQuery.ts","../src/getBabelConfig.ts","../src/typescript/parseSource.ts","../src/typescript/expressionResolvers.ts","../src/typescript/findQueriesInSource.ts","../src/typescript/moduleResolver.ts","../src/typescript/findQueriesInPath.ts","../src/typescript/registerBabel.ts","../src/typescript/typeGenerator.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport * as json5 from 'json5'\nimport * as z from 'zod'\n\nexport const configDefintion = z.object({\n path: z\n .string()\n .or(z.array(z.string()))\n .default([\n './src/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n './app/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n ]),\n schema: z.string().default('./schema.json'),\n generates: z.string().default('./sanity.types.ts'),\n formatGeneratedCode: z.boolean().default(true),\n overloadClientMethods: z.boolean().default(false),\n})\n\nexport type CodegenConfig = z.infer<typeof configDefintion>\n\nexport async function readConfig(path: string): Promise<CodegenConfig> {\n try {\n const content = await readFile(path, 'utf-8')\n const json = json5.parse(content)\n return configDefintion.parseAsync(json)\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(`Error in config file\\n ${error.errors.map((err) => err.message).join('\\n')}`)\n }\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return configDefintion.parse({})\n }\n\n throw error\n }\n}\n","import {readFile} from 'node:fs/promises'\n\nimport {type SchemaType} from 'groq-js'\n\n/**\n * Read a schema from a given path\n * @param path - The path to the schema\n * @returns The schema\n * @internal\n * @beta\n **/\nexport async function readSchema(path: string): Promise<SchemaType> {\n const content = await readFile(path, 'utf-8')\n return JSON.parse(content) // todo: ZOD validation?\n}\n","import {parse} from 'groq-js'\n\n/**\n * safeParseQuery parses a GROQ query string, but first attempts to extract any parameters used in slices. This method is _only_\n * intended for use in type generation where we don't actually execute the parsed AST on a dataset, and should not be used elsewhere.\n * @internal\n */\nexport function safeParseQuery(query: string) {\n const params: Record<string, unknown> = {}\n\n for (const param of extractSliceParams(query)) {\n params[param] = 0 // we don't care about the value, just the type\n }\n return parse(query, {params})\n}\n\n/**\n * Finds occurences of `[($start|{number})..($end|{number})]` in a query string and returns the start and end values, and return\n * the names of the start and end variables.\n * @internal\n */\nexport function* extractSliceParams(query: string): Generator<string> {\n const sliceRegex = /\\[(\\$(\\w+)|\\d)\\.\\.\\.?(\\$(\\w+)|\\d)\\]/g\n const matches = query.matchAll(sliceRegex)\n if (!matches) {\n return\n }\n const params = new Set<string>()\n for (const match of matches) {\n const start = match[1] === `$${match[2]}` ? match[2] : null\n if (start !== null) {\n yield start\n }\n const end = match[3] === `$${match[4]}` ? match[4] : null\n if (end !== null) {\n yield end\n }\n }\n}\n","import {existsSync} from 'node:fs'\nimport {join, resolve} from 'node:path'\n\nimport {type TransformOptions} from '@babel/core'\n\n/**\n * Because of bundlers and compilers, knowing the exact path the babel configuration will be\n * located at post - build is not always trivial. We traverse from the current directory upwards\n * until we find the first `babel.config.json` and use that path.\n *\n * @param path - The path to start looking for the babel configuration\n * @returns The path to the `babel.config.json` file\n * @internal\n */\nexport function findBabelConfig(path: string): string {\n const configPath = join(path, 'babel.config.json')\n if (existsSync(configPath)) {\n return configPath\n }\n\n const parent = resolve(join(path, '..'))\n if (parent && parent !== path) {\n return findBabelConfig(parent)\n }\n\n throw new Error('Could not find `babel.config.json` in @sanity/codegen')\n}\n\n/**\n * Get the default babel configuration for `@sanity/codegen`\n *\n * @param path - The path to start looking for the babel configuration. Defaults to `__dirname`\n * @returns A babel configuration object\n * @internal\n */\nexport function getBabelConfig(path?: string): TransformOptions {\n const configPath = findBabelConfig(path || __dirname)\n return {extends: configPath}\n}\n","import {parse, type TransformOptions} from '@babel/core'\nimport type * as babelTypes from '@babel/types'\n\n// helper function to parse a source file\nexport function parseSourceFile(\n source: string,\n filename: string,\n babelOptions: TransformOptions,\n): babelTypes.File {\n const result = parse(source, {\n ...babelOptions,\n filename,\n })\n\n if (!result) {\n throw new Error(`Failed to parse ${filename}`)\n }\n\n return result\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type TransformOptions} from '@babel/core'\nimport traverse, {type Scope} from '@babel/traverse'\nimport * as babelTypes from '@babel/types'\nimport createDebug from 'debug'\n\nimport {parseSourceFile} from './parseSource'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ntype resolveExpressionReturnType = string\n\n/**\n * NamedQueryResult is a result of a named query\n */\nexport interface NamedQueryResult {\n /** name is the name of the query */\n name: string\n /** result is a groq query */\n result: resolveExpressionReturnType\n}\n\nconst TAGGED_TEMPLATE_ALLOW_LIST = ['groq']\nconst FUNCTION_WRAPPER_ALLOW_LIST = ['defineQuery']\n\n/**\n * resolveExpression takes a node and returns the resolved value of the expression.\n * @beta\n * @internal\n */\nexport function resolveExpression({\n node,\n file,\n scope,\n filename,\n resolver,\n babelConfig,\n params = [],\n fnArguments = [],\n}: {\n node: babelTypes.Node\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n params?: babelTypes.Node[]\n fnArguments?: babelTypes.Node[]\n}): resolveExpressionReturnType {\n debug(\n `Resolving node ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n if (\n babelTypes.isTaggedTemplateExpression(node) &&\n babelTypes.isIdentifier(node.tag) &&\n TAGGED_TEMPLATE_ALLOW_LIST.includes(node.tag.name)\n ) {\n return resolveExpression({\n node: node.quasi,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n\n if (babelTypes.isTemplateLiteral(node)) {\n const resolvedExpressions = node.expressions.map((expression) =>\n resolveExpression({\n node: expression,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n }),\n )\n return node.quasis\n .map((quasi, idx) => {\n return (quasi.value.cooked || '') + (resolvedExpressions[idx] || '')\n })\n .join('')\n }\n\n if (babelTypes.isLiteral(node)) {\n if (node.type === 'NullLiteral' || node.type === 'RegExpLiteral') {\n throw new Error(`Unsupported literal type: ${node.type}`)\n }\n\n return node.value.toString()\n }\n\n if (babelTypes.isIdentifier(node)) {\n return resolveIdentifier({\n node,\n scope,\n filename,\n file,\n resolver,\n fnArguments,\n babelConfig,\n params,\n })\n }\n\n if (babelTypes.isVariableDeclarator(node)) {\n if (!node.init) {\n throw new Error(`Unsupported variable declarator`)\n }\n\n return resolveExpression({\n node: node.init,\n fnArguments,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (\n babelTypes.isCallExpression(node) &&\n babelTypes.isIdentifier(node.callee) &&\n FUNCTION_WRAPPER_ALLOW_LIST.includes(node.callee.name)\n ) {\n return resolveExpression({\n node: node.arguments[0],\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n })\n }\n\n if (babelTypes.isCallExpression(node)) {\n return resolveCallExpression({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n fnArguments,\n })\n }\n\n if (\n babelTypes.isArrowFunctionExpression(node) ||\n babelTypes.isFunctionDeclaration(node) ||\n babelTypes.isFunctionExpression(node)\n ) {\n return resolveExpression({\n node: node.body,\n params: node.params,\n fnArguments,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (babelTypes.isNewExpression(node)) {\n return resolveExpression({\n node: node.callee,\n scope,\n filename,\n file,\n babelConfig,\n resolver,\n })\n }\n\n if (babelTypes.isImportDefaultSpecifier(node) || babelTypes.isImportSpecifier(node)) {\n return resolveImportSpecifier({node, file, scope, filename, resolver, babelConfig})\n }\n\n if (babelTypes.isAssignmentPattern(node)) {\n return resolveExpression({\n node: node.right,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n\n throw new Error(\n `Unsupported expression type: ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveIdentifier({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n fnArguments,\n params,\n}: {\n node: babelTypes.Identifier\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n fnArguments: babelTypes.Node[]\n params: babelTypes.Node[]\n}): resolveExpressionReturnType {\n const paramIndex = params.findIndex(\n (param) =>\n (babelTypes.isIdentifier(param) && node.name === param.name) ||\n (babelTypes.isAssignmentPattern(param) &&\n babelTypes.isIdentifier(param.left) &&\n node.name === param.left.name),\n )\n const argument = fnArguments[paramIndex]\n if (argument && babelTypes.isLiteral(argument)) {\n return resolveExpression({\n node: argument,\n scope,\n filename,\n file,\n resolver,\n params,\n babelConfig,\n fnArguments,\n })\n }\n const binding = scope.getBinding(node.name)\n if (binding) {\n if (babelTypes.isIdentifier(binding.path.node)) {\n const isSame = binding.path.node.name === node.name\n if (isSame) {\n throw new Error(\n `Could not resolve same identifier \"${node.name}\" in \"${filename}:${node.loc?.start.line}:${node.loc?.start.column}\"`,\n )\n }\n }\n return resolveExpression({\n node: binding.path.node,\n params,\n fnArguments,\n scope,\n filename,\n babelConfig,\n file,\n resolver,\n })\n }\n\n throw new Error(\n `Could not find binding for node \"${node.name}\" in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveCallExpression({\n node,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n}: {\n node: babelTypes.CallExpression\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n fnArguments: babelTypes.Node[]\n params: babelTypes.Node[]\n}): resolveExpressionReturnType {\n const {callee} = node\n return resolveExpression({\n node: callee,\n scope,\n filename,\n file,\n resolver,\n babelConfig,\n params,\n fnArguments: node.arguments,\n })\n}\n\nfunction resolveImportSpecifier({\n node,\n file,\n filename,\n resolver,\n babelConfig,\n}: {\n node: babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier | babelTypes.ExportSpecifier\n file: babelTypes.File\n scope: Scope\n filename: string\n resolver: NodeJS.RequireResolve\n babelConfig: TransformOptions\n}): resolveExpressionReturnType {\n let importDeclaration: babelTypes.ImportDeclaration | undefined\n traverse(file, {\n ImportDeclaration(n) {\n if (!babelTypes.isImportDeclaration(n.node)) {\n return\n }\n for (const specifier of n.node.specifiers) {\n if (babelTypes.isImportDefaultSpecifier(specifier)) {\n if (specifier.local.loc?.identifierName === node.local.name) {\n importDeclaration = n.node\n break\n }\n }\n if (specifier.local.name === node.local.name) {\n importDeclaration = n.node\n }\n }\n },\n })\n\n if (!importDeclaration) {\n throw new Error(`Could not find import declaration for ${node.local.name}`)\n }\n\n const importName = node.local.name // the name of the variable to import\n const importFileName = importDeclaration.source.value // the file to import from\n\n const importPath =\n importFileName.startsWith('./') || importFileName.startsWith('../')\n ? path.resolve(path.dirname(filename), importFileName)\n : importFileName\n\n const resolvedFile = resolver(importPath)\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let newScope: Scope | undefined\n traverse(tree, {\n Program(p) {\n newScope = p.scope\n },\n })\n if (!newScope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = newScope.getBinding(importName)\n if (binding) {\n return resolveExpression({\n node: binding.path.node,\n file: tree,\n scope: newScope,\n babelConfig,\n filename: resolvedFile,\n resolver,\n })\n }\n\n // It's not a global binding, but it might be a named export\n let namedExport: babelTypes.ExportNamedDeclaration | undefined\n let newImportName: string | undefined\n traverse(tree, {\n ExportDeclaration(p) {\n if (p.node.type === 'ExportNamedDeclaration') {\n for (const specifier of p.node.specifiers) {\n if (\n specifier.type === 'ExportSpecifier' &&\n specifier.exported.type === 'Identifier' &&\n specifier.exported.name === importName\n ) {\n namedExport = p.node\n newImportName = specifier.exported.name\n }\n }\n }\n },\n })\n\n if (namedExport && newImportName) {\n return resolveExportSpecifier({\n node: namedExport,\n importName: newImportName,\n filename: resolvedFile,\n resolver,\n babelConfig,\n })\n }\n\n throw new Error(`Could not find binding for import \"${importName}\" in ${importFileName}`)\n}\n\nfunction resolveExportSpecifier({\n node,\n importName,\n filename,\n babelConfig,\n resolver,\n}: {\n node: babelTypes.ExportNamedDeclaration\n importName: string\n filename: string\n babelConfig: TransformOptions\n resolver: NodeJS.RequireResolve\n}): resolveExpressionReturnType {\n if (!node.source) {\n throw new Error(`Could not find source for export \"${importName}\" in ${filename}`)\n }\n\n const importFileName = node.source.value\n const importPath = path.resolve(path.dirname(filename), importFileName)\n const resolvedFile = resolver(importPath)\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let newScope: Scope | undefined\n traverse(tree, {\n Program(p) {\n newScope = p.scope\n },\n })\n if (!newScope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = newScope.getBinding(importName)\n if (binding) {\n return resolveExpression({\n node: binding.path.node,\n file: tree,\n scope: newScope,\n filename: importFileName,\n babelConfig,\n resolver,\n })\n }\n\n throw new Error(`Could not find binding for export \"${importName}\" in ${importFileName}`)\n}\n","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'\nimport {type NamedQueryResult, resolveExpression} from './expressionResolvers'\nimport {parseSourceFile} from './parseSource'\n\nconst require = createRequire(__filename)\n\nconst groqTagName = 'groq'\nconst defineQueryFunctionName = 'defineQuery'\nconst groqModuleName = 'groq'\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): NamedQueryResult[] {\n const queries: NamedQueryResult[] = []\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\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 queryName = `${node.id.name}`\n const queryResult = resolveExpression({\n node: init,\n file,\n scope,\n babelConfig,\n filename,\n resolver,\n })\n\n queries.push({name: queryName, result: queryResult})\n }\n },\n })\n\n return 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","import createDebug from 'debug'\nimport {createMatchPath, loadConfig as loadTSConfig} from 'tsconfig-paths'\n\nconst debug = createDebug('sanity:codegen:moduleResolver')\n\n/**\n * This is a custom implementation of require.resolve that takes into account the paths\n * configuration in tsconfig.json. This is necessary if we want to resolve paths that are\n * custom defined in the tsconfig.json file.\n * Resolving here is best effort and might not work in all cases.\n * @beta\n */\nexport function getResolver(cwd?: string): NodeJS.RequireResolve {\n const tsConfig = loadTSConfig(cwd)\n\n if (tsConfig.resultType === 'failed') {\n debug('Could not load tsconfig, using default resolver: %s', tsConfig.message)\n return require.resolve\n }\n\n const matchPath = createMatchPath(\n tsConfig.absoluteBaseUrl,\n tsConfig.paths,\n tsConfig.mainFields,\n tsConfig.addMatchAll,\n )\n\n const resolve = function (request: string, options?: {paths?: string[]}): string {\n const found = matchPath(request)\n if (found !== undefined) {\n return require.resolve(found, options)\n }\n return require.resolve(request, options)\n }\n\n // wrap the resolve.path function to make it available.\n resolve.paths = (request: string): string[] | null => {\n return require.resolve.paths(request)\n }\n return resolve\n}\n","import fs from 'node:fs/promises'\n\nimport {type TransformOptions} from '@babel/core'\nimport createDebug from 'debug'\nimport glob from 'globby'\n\nimport {getBabelConfig} from '../getBabelConfig'\nimport {type NamedQueryResult} from './expressionResolvers'\nimport {findQueriesInSource} from './findQueriesInSource'\nimport {getResolver} from './moduleResolver'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ntype ResultQueries = {\n type: 'queries'\n filename: string\n queries: NamedQueryResult[]\n}\ntype ResultError = {\n type: 'error'\n error: Error\n filename: string\n}\n\n/**\n * findQueriesInPath takes a path or array of paths and returns all GROQ queries in the files.\n * @param path - The path or array of paths to search for queries\n * @param babelOptions - The babel configuration to use when parsing the source\n * @param resolver - A resolver function to use when resolving module imports\n * @returns An async generator that yields the results of the search\n * @beta\n * @internal\n */\nexport async function* findQueriesInPath({\n path,\n babelOptions = getBabelConfig(),\n resolver = getResolver(),\n}: {\n path: string | string[]\n babelOptions?: TransformOptions\n resolver?: NodeJS.RequireResolve\n}): AsyncGenerator<ResultQueries | ResultError> {\n const queryNames = new Set()\n // Holds all query names found in the source files\n debug(`Globing ${path}`)\n\n const stream = glob.stream(path, {\n absolute: false,\n ignore: ['**/node_modules/**'], // we never want to look in node_modules\n onlyFiles: true,\n })\n\n for await (const filename of stream) {\n if (typeof filename !== 'string') {\n continue\n }\n\n debug(`Found file \"${filename}\"`)\n try {\n const source = await fs.readFile(filename, 'utf8')\n const queries = findQueriesInSource(source, filename, babelOptions, resolver)\n // Check and error on duplicate query names, because we can't generate types with the same name.\n for (const query of queries) {\n if (queryNames.has(query.name)) {\n throw new Error(\n `Duplicate query name found: \"${query.name}\". Query names must be unique across all files.`,\n )\n }\n queryNames.add(query.name)\n }\n yield {type: 'queries', filename, queries}\n } catch (error) {\n debug(`Error in file \"${filename}\"`, error)\n yield {type: 'error', error, filename}\n }\n }\n}\n","import {type TransformOptions} from '@babel/core'\nimport register from '@babel/register'\n\nimport {getBabelConfig} from '../getBabelConfig'\n\n/**\n * Register Babel with the given options\n *\n * @param babelOptions - The options to use when registering Babel\n * @beta\n */\nexport function registerBabel(babelOptions?: TransformOptions): void {\n const options = babelOptions || getBabelConfig()\n\n register({...options, extensions: ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']})\n}\n","import {CodeGenerator} from '@babel/generator'\nimport * as t from '@babel/types'\nimport {\n type ArrayTypeNode,\n type DocumentSchemaType,\n type ObjectAttribute,\n type ObjectTypeNode,\n type SchemaType,\n type TypeDeclarationSchemaType,\n type TypeNode,\n type UnionTypeNode,\n} from 'groq-js'\n\nconst REFERENCE_SYMBOL_NAME = 'internalGroqTypeReferenceTo'\nconst ALL_SCHEMA_TYPES = 'AllSanitySchemaTypes'\n\ntype QueryWithTypeNode = {\n query: string\n typeNode: TypeNode\n}\n\n/**\n * A class used to generate TypeScript types from a given schema\n * @internal\n * @beta\n */\nexport class TypeGenerator {\n private generatedTypeName: Set<string> = new Set()\n private typeNameMap: Map<TypeNode | DocumentSchemaType | TypeDeclarationSchemaType, string> =\n new Map()\n\n private readonly schema: SchemaType\n\n constructor(schema: SchemaType) {\n this.schema = schema\n }\n\n /**\n * Generate TypeScript types for the given schema\n * @returns string\n * @internal\n * @beta\n */\n generateSchemaTypes(): string {\n const typeDeclarations: (t.TSTypeAliasDeclaration | t.ExportNamedDeclaration)[] = []\n\n const schemaNames = new Set<string>()\n this.schema.forEach((schema) => {\n const typeLiteral = this.getTypeNodeType(schema)\n\n const schemaName = this.getTypeName(schema.name, schema)\n schemaNames.add(schemaName)\n const typeAlias = t.tsTypeAliasDeclaration(t.identifier(schemaName), null, typeLiteral)\n\n typeDeclarations.push(t.exportNamedDeclaration(typeAlias))\n })\n\n typeDeclarations.push(\n t.exportNamedDeclaration(\n t.tsTypeAliasDeclaration(\n t.identifier(this.getTypeName(ALL_SCHEMA_TYPES)),\n null,\n t.tsUnionType(\n [...schemaNames].map((typeName) => t.tsTypeReference(t.identifier(typeName))),\n ),\n ),\n ),\n )\n\n // Generate TypeScript code from the AST nodes\n return typeDeclarations.map((decl) => new CodeGenerator(decl).generate().code).join('\\n\\n')\n }\n\n /**\n * Takes a identifier and a type node and generates a type alias for the type node.\n * @param identifierName - The name of the type to generated\n * @param typeNode - The type node to generate the type for\n * @returns\n * @internal\n * @beta\n */\n generateTypeNodeTypes(identifierName: string, typeNode: TypeNode): string {\n const type = this.getTypeNodeType(typeNode)\n\n const typeName = this.getTypeName(identifierName, typeNode)\n const typeAlias = t.tsTypeAliasDeclaration(t.identifier(typeName), null, type)\n\n return new CodeGenerator(t.exportNamedDeclaration(typeAlias)).generate().code.trim()\n }\n\n static generateKnownTypes(): string {\n const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword())\n typeOperator.operator = 'unique'\n\n const identifier = t.identifier(REFERENCE_SYMBOL_NAME)\n identifier.typeAnnotation = t.tsTypeAnnotation(typeOperator)\n\n const decleration = t.variableDeclaration('const', [t.variableDeclarator(identifier)])\n decleration.declare = true\n return new CodeGenerator(t.exportNamedDeclaration(decleration)).generate().code.trim()\n }\n\n /**\n * Takes a list of queries from the codebase and generates a type declaration\n * for SanityClient to consume.\n *\n * Note: only types that have previously been generated with `generateTypeNodeTypes`\n * will be included in the query map.\n *\n * @param queries - A list of queries to generate a type declaration for\n * @returns\n * @internal\n * @beta\n */\n generateQueryMap(queries: QueryWithTypeNode[]): string {\n const typesByQuerystring: {[query: string]: string[]} = {}\n\n for (const query of queries) {\n const name = this.typeNameMap.get(query.typeNode)\n if (!name) {\n continue\n }\n\n typesByQuerystring[query.query] ??= []\n typesByQuerystring[query.query].push(name)\n }\n\n const queryReturnInterface = t.tsInterfaceDeclaration(\n t.identifier('SanityQueries'),\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 declareModule = t.declareModule(\n t.stringLiteral('@sanity/client'),\n t.blockStatement([queryReturnInterface]),\n )\n\n const clientImport = t.importDeclaration([], t.stringLiteral('@sanity/client'))\n\n return new CodeGenerator(t.program([clientImport, declareModule])).generate().code.trim()\n }\n\n /**\n * Since we are sanitizing identifiers we migt end up with collisions. Ie there might be a type mux.video and muxVideo, both these\n * types would be sanityized into MuxVideo. To avoid this we keep track of the generated type names and add a index to the name.\n * When we reference a type we also keep track of the original name so we can reference the correct type later.\n */\n private getTypeName(\n name: string,\n typeNode?: TypeNode | DocumentSchemaType | TypeDeclarationSchemaType,\n ): string {\n const desiredName = uppercaseFirstLetter(sanitizeIdentifier(name))\n\n let generatedName = desiredName\n let i = 2\n while (this.generatedTypeName.has(generatedName)) {\n // add _ and a index and increment that index until we find a name that is not in the map\n generatedName = `${desiredName}_${i++}`\n }\n this.generatedTypeName.add(generatedName)\n if (typeNode) {\n this.typeNameMap.set(typeNode, generatedName)\n }\n\n return generatedName\n }\n\n private getTypeNodeType(\n typeNode: TypeNode | TypeDeclarationSchemaType | DocumentSchemaType,\n ): t.TSType {\n switch (typeNode.type) {\n case 'string': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.stringLiteral(typeNode.value))\n }\n return t.tsStringKeyword()\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 'boolean': {\n if (typeNode.value !== undefined) {\n return t.tsLiteralType(t.booleanLiteral(typeNode.value))\n }\n return t.tsBooleanKeyword()\n }\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n case 'document': {\n return this.generateDocumentType(typeNode)\n }\n case 'type': {\n return this.getTypeNodeType(typeNode.value)\n }\n case 'array': {\n return this.generateArrayTsType(typeNode)\n }\n case 'object': {\n return this.generateObjectTsType(typeNode)\n }\n case 'union': {\n return this.generateUnionTsType(typeNode)\n }\n case 'inline': {\n return t.tsTypeReference(\n t.identifier(uppercaseFirstLetter(sanitizeIdentifier(typeNode.name))),\n )\n }\n case 'null': {\n return t.tsNullKeyword()\n }\n\n default:\n // @ts-expect-error This should never happen\n throw new Error(`Type \"${typeNode.type}\" not found in schema`)\n }\n }\n\n // Helper function used to generate TS types for array type nodes.\n private generateArrayTsType(typeNode: ArrayTypeNode): t.TSTypeReference {\n const typeNodes = this.getTypeNodeType(typeNode.of)\n const arrayType = t.tsTypeReference(\n t.identifier('Array'),\n t.tsTypeParameterInstantiation([typeNodes]),\n )\n\n return arrayType\n }\n\n // Helper function used to generate TS types for object properties.\n private generateObjectProperty(key: string, attribute: ObjectAttribute): t.TSPropertySignature {\n const type = this.getTypeNodeType(attribute.value)\n const propertySignature = t.tsPropertySignature(\n t.identifier(sanitizeIdentifier(key)),\n t.tsTypeAnnotation(type),\n )\n propertySignature.optional = attribute.optional\n\n return propertySignature\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 Object.entries(typeNode.attributes).forEach(([key, attribute]) => {\n props.push(this.generateObjectProperty(key, attribute))\n })\n const rest = typeNode.rest\n if (rest !== undefined) {\n switch (rest.type) {\n case 'unknown': {\n return t.tsUnknownKeyword()\n }\n case 'object': {\n Object.entries(rest.attributes).forEach(([key, attribute]) => {\n props.push(this.generateObjectProperty(key, attribute))\n })\n break\n }\n case 'inline': {\n const referencedTypeNode = this.schema.find((schema) => schema.name === rest.name)\n if (referencedTypeNode === undefined) {\n const missing = t.tsUnknownKeyword()\n missing.trailingComments = [\n {\n type: 'CommentLine',\n value: ` Unable to locate the referenced type \"${rest.name}\" in schema`,\n },\n ]\n return missing\n }\n\n return t.tsIntersectionType([\n t.tsTypeLiteral(props),\n t.tsTypeReference(\n t.identifier(\n this.typeNameMap.get(referencedTypeNode) ||\n uppercaseFirstLetter(sanitizeIdentifier(rest.name)),\n ),\n ),\n ])\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 if (typeNode.dereferencesTo !== undefined) {\n const derefType = t.tsPropertySignature(\n t.identifier(REFERENCE_SYMBOL_NAME),\n t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo))),\n )\n derefType.computed = true\n derefType.optional = true\n props.push(derefType)\n }\n return t.tsTypeLiteral(props)\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) {\n return t.tsNeverKeyword()\n }\n if (typeNode.of.length === 1) {\n return this.getTypeNodeType(typeNode.of[0])\n }\n\n const typeNodes = typeNode.of.map((node) => this.getTypeNodeType(node))\n\n return t.tsUnionType(typeNodes)\n }\n\n // Helper function used to generate TS types for document type nodes.\n private generateDocumentType(document: DocumentSchemaType): t.TSType {\n const props = Object.entries(document.attributes).map(([key, node]) =>\n this.generateObjectProperty(key, node),\n )\n\n return t.tsTypeLiteral(props)\n }\n}\nfunction uppercaseFirstLetter(input: string): string {\n return input.charAt(0).toUpperCase() + input.slice(1)\n}\n\nfunction sanitizeIdentifier(input: string): string {\n return `${input.replace(/^\\d/, '_').replace(/[^$\\w]+(.)/g, (_, char) => char.toUpperCase())}`\n}\n"],"names":["path","parse","debug","babelTypes","require","traverse","loadTSConfig","resolve","fs"],"mappings":";;;;;;;;;;;;;;;AAKa,MAAA,kBAAkB,EAAE,OAAO;AAAA,EACtC,MAAM,EACH,OAAO,EACP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B,MAAM,MAAM,CAAC;AACtD;AAEA,SAAS,mBAAmB,OAAuB;AACjD,SAAO,GAAG,MAAM,QAAQ,OAAO,GAAG,EAAE,QAAQ,eAAe,CAAC,GAAG,SAAS,KAAK,YAAa,CAAA,CAAC;AAC7F;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/codegen",
|
|
3
|
-
"version": "3.52.5-canary.
|
|
3
|
+
"version": "3.52.5-canary.41+812e1e3930",
|
|
4
4
|
"description": "Codegen toolkit for Sanity.io",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sanity",
|
|
@@ -60,7 +60,7 @@
|
|
|
60
60
|
"@babel/types": "^7.23.9",
|
|
61
61
|
"debug": "^4.3.4",
|
|
62
62
|
"globby": "^10.0.0",
|
|
63
|
-
"groq": "3.52.5-canary.
|
|
63
|
+
"groq": "3.52.5-canary.41+812e1e3930",
|
|
64
64
|
"groq-js": "^1.12.0",
|
|
65
65
|
"json5": "^2.2.3",
|
|
66
66
|
"tsconfig-paths": "^4.2.0",
|
|
@@ -82,5 +82,5 @@
|
|
|
82
82
|
"publishConfig": {
|
|
83
83
|
"access": "public"
|
|
84
84
|
},
|
|
85
|
-
"gitHead": "
|
|
85
|
+
"gitHead": "812e1e393037e12bad90533b992ab4043396b21a"
|
|
86
86
|
}
|