@sanity/cli 4.18.1-next.9 → 4.19.0-next.19

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.
@@ -1,5 +1,9 @@
1
1
  "use strict";
2
- var fs = require("node:fs/promises"), path = require("node:path"), node_worker_threads = require("node:worker_threads"), codegen = require("@sanity/codegen"), prettier = require("prettier"), cliWorker = require("./cliWorker.js"), telemetry = require("@sanity/telemetry");
2
+ var fs = require("node:fs/promises"), path = require("node:path"), node_worker_threads = require("node:worker_threads"), codegen = require("@sanity/codegen"), chalk = require("chalk"), prettier = require("prettier"), cliWorker = require("./cliWorker.js"), getCliConfig = require("./getCliConfig.js"), telemetry = require("@sanity/telemetry");
3
+ function _interopDefaultCompat(e) {
4
+ return e && typeof e == "object" && "default" in e ? e : { default: e };
5
+ }
6
+ var chalk__default = /* @__PURE__ */ _interopDefaultCompat(chalk);
3
7
  const TypesGeneratedTrace = telemetry.defineTrace({
4
8
  name: "Types Generated",
5
9
  version: 0,
@@ -19,10 +23,48 @@ const TypesGeneratedTrace = telemetry.defineTrace({
19
23
  */
20
24
 
21
25
  `;
26
+ async function getConfig(workDir, configPath) {
27
+ const config = await getCliConfig.getCliConfig(workDir), legacyConfigPath = configPath || "sanity-typegen.json";
28
+ let hasLegacyConfig = !1;
29
+ try {
30
+ hasLegacyConfig = (await fs.stat(legacyConfigPath)).isFile();
31
+ } catch (err) {
32
+ if (err.code === "ENOENT" && configPath)
33
+ throw new Error(`Typegen config file not found: ${configPath}`, { cause: err });
34
+ if (err.code !== "ENOENT")
35
+ throw new Error(`Error when checking if typegen config file exists: ${legacyConfigPath}`, {
36
+ cause: err
37
+ });
38
+ }
39
+ return config?.config?.typegen && hasLegacyConfig ? (console.warn(
40
+ chalk__default.default.yellow(
41
+ `You've specified typegen in your Sanity CLI config, but also have a typegen config.
42
+
43
+ The config from the Sanity CLI config is used.
44
+ `
45
+ )
46
+ ), {
47
+ config: codegen.configDefinition.parse(config.config.typegen || {}),
48
+ type: "cli"
49
+ }) : hasLegacyConfig ? (console.warn(
50
+ chalk__default.default.yellow(
51
+ "The separate typegen config has been deprecated. Use `typegen` in the sanity CLI config instead.\n\nSee: https://www.sanity.io/docs/help/configuring-typegen-in-sanity-cli-config"
52
+ )
53
+ ), {
54
+ config: await codegen.readConfig(legacyConfigPath),
55
+ type: "legacy"
56
+ }) : {
57
+ config: codegen.configDefinition.parse(config?.config?.typegen || {}),
58
+ type: "cli"
59
+ };
60
+ }
22
61
  async function typegenGenerateAction(args, context) {
23
62
  const flags = args.extOptions, { output, workDir, telemetry: telemetry2 } = context, trace = telemetry2.trace(TypesGeneratedTrace);
24
63
  trace.start();
25
- const codegenConfig = await codegen.readConfig(flags["config-path"] || "sanity-typegen.json");
64
+ const { config: codegenConfig, type: codegenConfigMethod } = await getConfig(
65
+ workDir,
66
+ flags["config-path"]
67
+ );
26
68
  try {
27
69
  if (!(await fs.stat(codegenConfig.schema)).isFile())
28
70
  throw new Error(`Schema path is not a file: ${codegenConfig.schema}`);
@@ -125,6 +167,7 @@ async function typegenGenerateAction(args, context) {
125
167
  schemaTypesCount: stats.schemaTypesCount,
126
168
  queryFilesCount: stats.queryFilesCount,
127
169
  filesWithErrors: stats.errors,
170
+ configMethod: codegenConfigMethod,
128
171
  typeNodesGenerated: stats.typeNodesGenerated,
129
172
  unknownTypeNodesGenerated: stats.unknownTypeNodesGenerated,
130
173
  unknownTypeNodesRatio: stats.typeNodesGenerated > 0 ? stats.unknownTypeNodesGenerated / stats.typeNodesGenerated : 0,
@@ -1 +1 @@
1
- {"version":3,"file":"generateAction.js","sources":["../../src/actions/typegen/generate.telemetry.ts","../../src/actions/typegen/generateAction.ts"],"sourcesContent":["import {defineTrace} from '@sanity/telemetry'\n\ninterface TypesGeneratedTraceAttrubutes {\n outputSize: number\n queriesCount: number\n schemaTypesCount: number\n queryFilesCount: number\n filesWithErrors: number\n typeNodesGenerated: number\n unknownTypeNodesGenerated: number\n unknownTypeNodesRatio: number\n emptyUnionTypeNodesGenerated: number\n configOverloadClientMethods: boolean\n}\n\nexport const TypesGeneratedTrace = defineTrace<TypesGeneratedTraceAttrubutes>({\n name: 'Types Generated',\n version: 0,\n description: 'Trace emitted when generating TypeScript types for queries',\n})\n","import {constants, mkdir, open, stat} from 'node:fs/promises'\nimport {dirname, isAbsolute, join} from 'node:path'\nimport {Worker} from 'node:worker_threads'\n\nimport {readConfig} from '@sanity/codegen'\nimport {format as prettierFormat, resolveConfig as resolvePrettierConfig} from 'prettier'\n\nimport {type CliCommandArguments, type CliCommandContext} from '../../types'\nimport {getCliWorkerPath} from '../../util/cliWorker'\nimport {\n type TypegenGenerateTypesWorkerData,\n type TypegenGenerateTypesWorkerMessage,\n} from '../../workers/typegenGenerate'\nimport {TypesGeneratedTrace} from './generate.telemetry'\n\nexport interface TypegenGenerateTypesCommandFlags {\n 'config-path'?: string\n}\n\nconst generatedFileWarning = `/**\n * ---------------------------------------------------------------------------------\n * This file has been generated by Sanity TypeGen.\n * Command: \\`sanity typegen generate\\`\n *\n * Any modifications made directly to this file will be overwritten the next time\n * the TypeScript definitions are generated. Please make changes to the Sanity\n * schema definitions and/or GROQ queries if you need to update these types.\n *\n * For more information on how to use Sanity TypeGen, visit the official documentation:\n * https://www.sanity.io/docs/sanity-typegen\n * ---------------------------------------------------------------------------------\n */\\n\\n`\n\nexport default async function typegenGenerateAction(\n args: CliCommandArguments<TypegenGenerateTypesCommandFlags>,\n context: CliCommandContext,\n): Promise<void> {\n const flags = args.extOptions\n const {output, workDir, telemetry} = context\n\n const trace = telemetry.trace(TypesGeneratedTrace)\n trace.start()\n\n const codegenConfig = await readConfig(flags['config-path'] || 'sanity-typegen.json')\n\n try {\n const schemaStats = await stat(codegenConfig.schema)\n if (!schemaStats.isFile()) {\n throw new Error(`Schema path is not a file: ${codegenConfig.schema}`)\n }\n } catch (err) {\n if (err.code === 'ENOENT') {\n // If the user has not provided a specific schema path (eg we're using the default), give some help\n const hint =\n codegenConfig.schema === './schema.json' ? ` - did you run \"sanity schema extract\"?` : ''\n throw new Error(`Schema file not found: ${codegenConfig.schema}${hint}`, {cause: err})\n }\n throw err\n }\n\n const outputPath = isAbsolute(codegenConfig.generates)\n ? codegenConfig.generates\n : join(process.cwd(), codegenConfig.generates)\n const outputDir = dirname(outputPath)\n await mkdir(outputDir, {recursive: true})\n const workerPath = await getCliWorkerPath('typegenGenerate')\n\n const spinner = output.spinner({}).start('Generating types')\n\n const worker = new Worker(workerPath, {\n workerData: {\n workDir,\n schemaPath: codegenConfig.schema,\n searchPath: codegenConfig.path,\n overloadClientMethods: codegenConfig.overloadClientMethods,\n } satisfies TypegenGenerateTypesWorkerData,\n env: process.env,\n })\n\n const typeFile = await open(\n outputPath,\n // eslint-disable-next-line no-bitwise\n constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY,\n )\n\n void typeFile.write(generatedFileWarning)\n\n const stats = {\n queryFilesCount: 0,\n errors: 0,\n queriesCount: 0,\n schemaTypesCount: 0,\n unknownTypeNodesGenerated: 0,\n typeNodesGenerated: 0,\n emptyUnionTypeNodesGenerated: 0,\n size: 0,\n }\n\n await new Promise<void>((resolve, reject) => {\n worker.addListener('message', (msg: TypegenGenerateTypesWorkerMessage) => {\n if (msg.type === 'error') {\n if (msg.fatal) {\n trace.error(msg.error)\n reject(msg.error)\n return\n }\n const errorMessage = msg.filename\n ? `${msg.error.message} in \"${msg.filename}\"`\n : msg.error.message\n spinner.fail(errorMessage)\n stats.errors++\n return\n }\n if (msg.type === 'complete') {\n resolve()\n return\n }\n\n if (msg.type === 'typemap') {\n let typeMapStr = `// Query TypeMap\\n`\n typeMapStr += msg.typeMap\n void typeFile.write(typeMapStr)\n stats.size += Buffer.byteLength(typeMapStr)\n return\n }\n\n let fileTypeString = `// Source: ${msg.filename}\\n`\n\n if (msg.type === 'schema') {\n stats.schemaTypesCount += msg.length\n fileTypeString += msg.schema\n void typeFile.write(fileTypeString)\n return\n }\n\n if (msg.type === 'types') {\n stats.queryFilesCount++\n for (const {\n queryName,\n query,\n type,\n typeNodesGenerated,\n unknownTypeNodesGenerated,\n emptyUnionTypeNodesGenerated,\n } of msg.types) {\n fileTypeString += `// Variable: ${queryName}\\n`\n fileTypeString += `// Query: ${query.replace(/(\\r\\n|\\n|\\r)/gm, '').trim()}\\n`\n fileTypeString += type\n stats.queriesCount++\n stats.typeNodesGenerated += typeNodesGenerated\n stats.unknownTypeNodesGenerated += unknownTypeNodesGenerated\n stats.emptyUnionTypeNodesGenerated += emptyUnionTypeNodesGenerated\n }\n void typeFile.write(`${fileTypeString}\\n`)\n stats.size += Buffer.byteLength(fileTypeString)\n }\n })\n worker.addListener('error', reject)\n })\n\n await typeFile.close()\n\n const prettierConfig = codegenConfig.formatGeneratedCode\n ? await resolvePrettierConfig(outputPath).catch((err) => {\n output.warn(`Failed to load prettier config: ${err.message}`)\n return null\n })\n : null\n\n if (prettierConfig) {\n const formatFile = await open(outputPath, constants.O_RDWR)\n try {\n const code = await formatFile.readFile()\n const formattedCode = await prettierFormat(code.toString(), {\n ...prettierConfig,\n parser: 'typescript' as const,\n })\n await formatFile.truncate()\n await formatFile.write(formattedCode, 0)\n\n spinner.info('Formatted generated types with Prettier')\n } catch (err) {\n output.warn(`Failed to format generated types with Prettier: ${err.message}`)\n } finally {\n await formatFile.close()\n }\n }\n\n trace.log({\n outputSize: stats.size,\n queriesCount: stats.queriesCount,\n schemaTypesCount: stats.schemaTypesCount,\n queryFilesCount: stats.queryFilesCount,\n filesWithErrors: stats.errors,\n typeNodesGenerated: stats.typeNodesGenerated,\n unknownTypeNodesGenerated: stats.unknownTypeNodesGenerated,\n unknownTypeNodesRatio:\n stats.typeNodesGenerated > 0 ? stats.unknownTypeNodesGenerated / stats.typeNodesGenerated : 0,\n emptyUnionTypeNodesGenerated: stats.emptyUnionTypeNodesGenerated,\n configOverloadClientMethods: codegenConfig.overloadClientMethods,\n })\n\n trace.complete()\n if (stats.errors > 0) {\n spinner.warn(`Encountered errors in ${stats.errors} files while generating types`)\n }\n\n spinner.succeed(\n `Generated TypeScript types for ${stats.schemaTypesCount} schema types and ${stats.queriesCount} GROQ queries in ${stats.queryFilesCount} files into: ${codegenConfig.generates}`,\n )\n}\n"],"names":["defineTrace","telemetry","readConfig","stat","isAbsolute","join","dirname","mkdir","getCliWorkerPath","Worker","open","constants","resolvePrettierConfig","prettierFormat"],"mappings":";;AAeO,MAAM,sBAAsBA,UAAAA,YAA2C;AAAA,EAC5E,MAAM;AAAA,EACN,SAAS;AAAA,EACT,aAAa;AACf,CAAC,GCAK,uBAAuB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAc7B,eAA8B,sBAC5B,MACA,SACe;AACf,QAAM,QAAQ,KAAK,YACb,EAAC,QAAQ,SAAS,WAAAC,WAAA,IAAa,SAE/B,QAAQA,WAAU,MAAM,mBAAmB;AACjD,QAAM,MAAA;AAEN,QAAM,gBAAgB,MAAMC,QAAAA,WAAW,MAAM,aAAa,KAAK,qBAAqB;AAEpF,MAAI;AAEF,QAAI,EADgB,MAAMC,GAAAA,KAAK,cAAc,MAAM,GAClC,OAAA;AACf,YAAM,IAAI,MAAM,8BAA8B,cAAc,MAAM,EAAE;AAAA,EAExE,SAAS,KAAK;AACZ,QAAI,IAAI,SAAS,UAAU;AAEzB,YAAM,OACJ,cAAc,WAAW,kBAAkB,4CAA4C;AACzF,YAAM,IAAI,MAAM,0BAA0B,cAAc,MAAM,GAAG,IAAI,IAAI,EAAC,OAAO,IAAA,CAAI;AAAA,IACvF;AACA,UAAM;AAAA,EACR;AAEA,QAAM,aAAaC,KAAAA,WAAW,cAAc,SAAS,IACjD,cAAc,YACdC,KAAAA,KAAK,QAAQ,IAAA,GAAO,cAAc,SAAS,GACzC,YAAYC,KAAAA,QAAQ,UAAU;AACpC,QAAMC,GAAAA,MAAM,WAAW,EAAC,WAAW,IAAK;AACxC,QAAM,aAAa,MAAMC,UAAAA,iBAAi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R,YAAY,MAAM;AAAA,IAClB,cAAc,MAAM;AAAA,IACpB,kBAAkB,MAAM;AAAA,IACxB,iBAAiB,MAAM;AAAA,IACvB,iBAAiB,MAAM;AAAA,IACvB,oBAAoB,MAAM;AAAA,IAC1B,2BAA2B,MAAM;AAAA,IACjC,uBACE,MAAM,qBAAqB,IAAI,MAAM,4BAA4B,MAAM,qBAAqB;AAAA,IAC9F,8BAA8B,MAAM;AAAA,IACpC,6BAA6B,cAAc;AAAA,EAAA,CAC5C,GAED,MAAM,SAAA,GACF,MAAM,SAAS,KACjB,QAAQ,KAAK,yBAAyB,MAAM,MAAM,+BAA+B,GAGnF,QAAQ;AAAA,IACN,kCAAkC,MAAM,gBAAgB,qBAAqB,MAAM,YAAY,oBAAoB,MAAM,eAAe,gBAAgB,cAAc,SAAS;AAAA,EAAA;AAEnL;;"}
1
+ {"version":3,"file":"generateAction.js","sources":["../../src/actions/typegen/generate.telemetry.ts","../../src/actions/typegen/generateAction.ts"],"sourcesContent":["import {defineTrace} from '@sanity/telemetry'\n\ninterface TypesGeneratedTraceAttrubutes {\n outputSize: number\n queriesCount: number\n schemaTypesCount: number\n queryFilesCount: number\n filesWithErrors: number\n typeNodesGenerated: number\n unknownTypeNodesGenerated: number\n unknownTypeNodesRatio: number\n emptyUnionTypeNodesGenerated: number\n configOverloadClientMethods: boolean\n configMethod: 'legacy' | 'cli'\n}\n\nexport const TypesGeneratedTrace = defineTrace<TypesGeneratedTraceAttrubutes>({\n name: 'Types Generated',\n version: 0,\n description: 'Trace emitted when generating TypeScript types for queries',\n})\n","import {constants, mkdir, open, stat} from 'node:fs/promises'\nimport {dirname, isAbsolute, join} from 'node:path'\nimport {Worker} from 'node:worker_threads'\n\nimport {type CodegenConfig, configDefinition, readConfig} from '@sanity/codegen'\nimport chalk from 'chalk'\nimport {format as prettierFormat, resolveConfig as resolvePrettierConfig} from 'prettier'\n\nimport {type CliCommandArguments, type CliCommandContext} from '../../types'\nimport {getCliWorkerPath} from '../../util/cliWorker'\nimport {getCliConfig} from '../../util/getCliConfig'\nimport {\n type TypegenGenerateTypesWorkerData,\n type TypegenGenerateTypesWorkerMessage,\n} from '../../workers/typegenGenerate'\nimport {TypesGeneratedTrace} from './generate.telemetry'\n\nexport interface TypegenGenerateTypesCommandFlags {\n 'config-path'?: string\n}\n\nconst generatedFileWarning = `/**\n * ---------------------------------------------------------------------------------\n * This file has been generated by Sanity TypeGen.\n * Command: \\`sanity typegen generate\\`\n *\n * Any modifications made directly to this file will be overwritten the next time\n * the TypeScript definitions are generated. Please make changes to the Sanity\n * schema definitions and/or GROQ queries if you need to update these types.\n *\n * For more information on how to use Sanity TypeGen, visit the official documentation:\n * https://www.sanity.io/docs/sanity-typegen\n * ---------------------------------------------------------------------------------\n */\\n\\n`\n\nasync function getConfig(\n workDir: string,\n configPath?: string,\n): Promise<{config: CodegenConfig; type: 'legacy' | 'cli'}> {\n const config = await getCliConfig(workDir)\n\n // check if the legacy config exist\n const legacyConfigPath = configPath || 'sanity-typegen.json'\n let hasLegacyConfig = false\n try {\n const file = await stat(legacyConfigPath)\n hasLegacyConfig = file.isFile()\n } catch (err) {\n if (err.code === 'ENOENT' && configPath) {\n throw new Error(`Typegen config file not found: ${configPath}`, {cause: err})\n }\n\n if (err.code !== 'ENOENT') {\n throw new Error(`Error when checking if typegen config file exists: ${legacyConfigPath}`, {\n cause: err,\n })\n }\n }\n\n // we have both legacy and cli config with typegen\n if (config?.config?.typegen && hasLegacyConfig) {\n console.warn(\n chalk.yellow(\n `You've specified typegen in your Sanity CLI config, but also have a typegen config.\n\nThe config from the Sanity CLI config is used.\n`,\n ),\n )\n\n return {\n config: configDefinition.parse(config.config.typegen || {}),\n type: 'cli',\n }\n }\n\n // we only have legacy typegen config\n if (hasLegacyConfig) {\n console.warn(\n chalk.yellow(\n `The separate typegen config has been deprecated. Use \\`typegen\\` in the sanity CLI config instead.\n\nSee: https://www.sanity.io/docs/help/configuring-typegen-in-sanity-cli-config`,\n ),\n )\n return {\n config: await readConfig(legacyConfigPath),\n type: 'legacy',\n }\n }\n\n // we only have cli config\n return {\n config: configDefinition.parse(config?.config?.typegen || {}),\n type: 'cli',\n }\n}\n\nexport default async function typegenGenerateAction(\n args: CliCommandArguments<TypegenGenerateTypesCommandFlags>,\n context: CliCommandContext,\n): Promise<void> {\n const flags = args.extOptions\n const {output, workDir, telemetry} = context\n\n const trace = telemetry.trace(TypesGeneratedTrace)\n trace.start()\n\n const {config: codegenConfig, type: codegenConfigMethod} = await getConfig(\n workDir,\n flags['config-path'],\n )\n\n try {\n const schemaStats = await stat(codegenConfig.schema)\n if (!schemaStats.isFile()) {\n throw new Error(`Schema path is not a file: ${codegenConfig.schema}`)\n }\n } catch (err) {\n if (err.code === 'ENOENT') {\n // If the user has not provided a specific schema path (eg we're using the default), give some help\n const hint =\n codegenConfig.schema === './schema.json' ? ` - did you run \"sanity schema extract\"?` : ''\n throw new Error(`Schema file not found: ${codegenConfig.schema}${hint}`, {cause: err})\n }\n throw err\n }\n\n const outputPath = isAbsolute(codegenConfig.generates)\n ? codegenConfig.generates\n : join(process.cwd(), codegenConfig.generates)\n const outputDir = dirname(outputPath)\n await mkdir(outputDir, {recursive: true})\n const workerPath = await getCliWorkerPath('typegenGenerate')\n\n const spinner = output.spinner({}).start('Generating types')\n\n const worker = new Worker(workerPath, {\n workerData: {\n workDir,\n schemaPath: codegenConfig.schema,\n searchPath: codegenConfig.path,\n overloadClientMethods: codegenConfig.overloadClientMethods,\n } satisfies TypegenGenerateTypesWorkerData,\n env: process.env,\n })\n\n const typeFile = await open(\n outputPath,\n // eslint-disable-next-line no-bitwise\n constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY,\n )\n\n void typeFile.write(generatedFileWarning)\n\n const stats = {\n queryFilesCount: 0,\n errors: 0,\n queriesCount: 0,\n schemaTypesCount: 0,\n unknownTypeNodesGenerated: 0,\n typeNodesGenerated: 0,\n emptyUnionTypeNodesGenerated: 0,\n size: 0,\n }\n\n await new Promise<void>((resolve, reject) => {\n worker.addListener('message', (msg: TypegenGenerateTypesWorkerMessage) => {\n if (msg.type === 'error') {\n if (msg.fatal) {\n trace.error(msg.error)\n reject(msg.error)\n return\n }\n const errorMessage = msg.filename\n ? `${msg.error.message} in \"${msg.filename}\"`\n : msg.error.message\n spinner.fail(errorMessage)\n stats.errors++\n return\n }\n if (msg.type === 'complete') {\n resolve()\n return\n }\n\n if (msg.type === 'typemap') {\n let typeMapStr = `// Query TypeMap\\n`\n typeMapStr += msg.typeMap\n void typeFile.write(typeMapStr)\n stats.size += Buffer.byteLength(typeMapStr)\n return\n }\n\n let fileTypeString = `// Source: ${msg.filename}\\n`\n\n if (msg.type === 'schema') {\n stats.schemaTypesCount += msg.length\n fileTypeString += msg.schema\n void typeFile.write(fileTypeString)\n return\n }\n\n if (msg.type === 'types') {\n stats.queryFilesCount++\n for (const {\n queryName,\n query,\n type,\n typeNodesGenerated,\n unknownTypeNodesGenerated,\n emptyUnionTypeNodesGenerated,\n } of msg.types) {\n fileTypeString += `// Variable: ${queryName}\\n`\n fileTypeString += `// Query: ${query.replace(/(\\r\\n|\\n|\\r)/gm, '').trim()}\\n`\n fileTypeString += type\n stats.queriesCount++\n stats.typeNodesGenerated += typeNodesGenerated\n stats.unknownTypeNodesGenerated += unknownTypeNodesGenerated\n stats.emptyUnionTypeNodesGenerated += emptyUnionTypeNodesGenerated\n }\n void typeFile.write(`${fileTypeString}\\n`)\n stats.size += Buffer.byteLength(fileTypeString)\n }\n })\n worker.addListener('error', reject)\n })\n\n await typeFile.close()\n\n const prettierConfig = codegenConfig.formatGeneratedCode\n ? await resolvePrettierConfig(outputPath).catch((err) => {\n output.warn(`Failed to load prettier config: ${err.message}`)\n return null\n })\n : null\n\n if (prettierConfig) {\n const formatFile = await open(outputPath, constants.O_RDWR)\n try {\n const code = await formatFile.readFile()\n const formattedCode = await prettierFormat(code.toString(), {\n ...prettierConfig,\n parser: 'typescript' as const,\n })\n await formatFile.truncate()\n await formatFile.write(formattedCode, 0)\n\n spinner.info('Formatted generated types with Prettier')\n } catch (err) {\n output.warn(`Failed to format generated types with Prettier: ${err.message}`)\n } finally {\n await formatFile.close()\n }\n }\n\n trace.log({\n outputSize: stats.size,\n queriesCount: stats.queriesCount,\n schemaTypesCount: stats.schemaTypesCount,\n queryFilesCount: stats.queryFilesCount,\n filesWithErrors: stats.errors,\n configMethod: codegenConfigMethod,\n typeNodesGenerated: stats.typeNodesGenerated,\n unknownTypeNodesGenerated: stats.unknownTypeNodesGenerated,\n unknownTypeNodesRatio:\n stats.typeNodesGenerated > 0 ? stats.unknownTypeNodesGenerated / stats.typeNodesGenerated : 0,\n emptyUnionTypeNodesGenerated: stats.emptyUnionTypeNodesGenerated,\n configOverloadClientMethods: codegenConfig.overloadClientMethods,\n })\n\n trace.complete()\n if (stats.errors > 0) {\n spinner.warn(`Encountered errors in ${stats.errors} files while generating types`)\n }\n\n spinner.succeed(\n `Generated TypeScript types for ${stats.schemaTypesCount} schema types and ${stats.queriesCount} GROQ queries in ${stats.queryFilesCount} files into: ${codegenConfig.generates}`,\n )\n}\n"],"names":["defineTrace","getCliConfig","stat","chalk","configDefinition","readConfig","telemetry","isAbsolute","join","dirname","mkdir","getCliWorkerPath","Worker","open","constants","resolvePrettierConfig","prettierFormat"],"mappings":";;;;;;AAgBO,MAAM,sBAAsBA,UAAAA,YAA2C;AAAA,EAC5E,MAAM;AAAA,EACN,SAAS;AAAA,EACT,aAAa;AACf,CAAC,GCCK,uBAAuB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAc7B,eAAe,UACb,SACA,YAC0D;AAC1D,QAAM,SAAS,MAAMC,aAAAA,aAAa,OAAO,GAGnC,mBAAmB,cAAc;AACvC,MAAI,kBAAkB;AACtB,MAAI;AAEF,uBADa,MAAMC,GAAAA,KAAK,gBAAgB,GACjB,OAAA;AAAA,EACzB,SAAS,KAAK;AACZ,QAAI,IAAI,SAAS,Y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QAC1D,GAAG;AAAA,QACH,QAAQ;AAAA,MAAA,CACT;AACD,YAAM,WAAW,YACjB,MAAM,WAAW,MAAM,eAAe,CAAC,GAEvC,QAAQ,KAAK,yCAAyC;AAAA,IACxD,SAAS,KAAK;AACZ,aAAO,KAAK,mDAAmD,IAAI,OAAO,EAAE;AAAA,IAC9E,UAAA;AACE,YAAM,WAAW,MAAA;AAAA,IACnB;AAAA,EACF;AAEA,QAAM,IAAI;AAAA,IACR,YAAY,MAAM;AAAA,IAClB,cAAc,MAAM;AAAA,IACpB,kBAAkB,MAAM;AAAA,IACxB,iBAAiB,MAAM;AAAA,IACvB,iBAAiB,MAAM;AAAA,IACvB,cAAc;AAAA,IACd,oBAAoB,MAAM;AAAA,IAC1B,2BAA2B,MAAM;AAAA,IACjC,uBACE,MAAM,qBAAqB,IAAI,MAAM,4BAA4B,MAAM,qBAAqB;AAAA,IAC9F,8BAA8B,MAAM;AAAA,IACpC,6BAA6B,cAAc;AAAA,EAAA,CAC5C,GAED,MAAM,SAAA,GACF,MAAM,SAAS,KACjB,QAAQ,KAAK,yBAAyB,MAAM,MAAM,+BAA+B,GAGnF,QAAQ;AAAA,IACN,kCAAkC,MAAM,gBAAgB,qBAAqB,MAAM,YAAY,oBAAoB,MAAM,eAAe,gBAAgB,cAAc,SAAS;AAAA,EAAA;AAEnL;;"}
package/lib/index.d.mts CHANGED
@@ -10,6 +10,7 @@ import {PluginOptions} from 'babel-plugin-react-compiler'
10
10
  import {SanityClient} from '@sanity/client'
11
11
  import {Separator} from 'inquirer'
12
12
  import {TelemetryLogger} from '@sanity/telemetry'
13
+ import {TypeGenConfig} from '@sanity/codegen'
13
14
 
14
15
  declare interface AppConfig {
15
16
  /**
@@ -168,6 +169,10 @@ export declare interface CliConfig {
168
169
  */
169
170
  aspectsPath: string
170
171
  }
172
+ /**
173
+ * Configuration for Sanity typegen
174
+ */
175
+ typegen?: Partial<TypeGenConfig>
171
176
  }
172
177
 
173
178
  declare type CliConfigResult =
package/lib/index.d.ts CHANGED
@@ -10,6 +10,7 @@ import {PluginOptions} from 'babel-plugin-react-compiler'
10
10
  import {SanityClient} from '@sanity/client'
11
11
  import {Separator} from 'inquirer'
12
12
  import {TelemetryLogger} from '@sanity/telemetry'
13
+ import {TypeGenConfig} from '@sanity/codegen'
13
14
 
14
15
  declare interface AppConfig {
15
16
  /**
@@ -168,6 +169,10 @@ export declare interface CliConfig {
168
169
  */
169
170
  aspectsPath: string
170
171
  }
172
+ /**
173
+ * Configuration for Sanity typegen
174
+ */
175
+ typegen?: Partial<TypeGenConfig>
171
176
  }
172
177
 
173
178
  declare type CliConfigResult =
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/cli",
3
- "version": "4.18.1-next.9+99174013a7",
3
+ "version": "4.19.0-next.19+cfd2d9c268",
4
4
  "description": "Sanity CLI tool for managing Sanity installations, managing plugins, schemas and datasets",
5
5
  "keywords": [
6
6
  "sanity",
@@ -61,7 +61,7 @@
61
61
  "pkg-dir": "^5.0.0",
62
62
  "prettier": "^3.6.2",
63
63
  "semver": "^7.7.2",
64
- "@sanity/codegen": "4.18.1-next.9+99174013a7"
64
+ "@sanity/codegen": "4.19.0-next.19+cfd2d9c268"
65
65
  },
66
66
  "devDependencies": {
67
67
  "@rexxars/gitconfiglocal": "^3.0.1",
@@ -116,11 +116,11 @@
116
116
  "vitest": "^3.2.4",
117
117
  "which": "^2.0.2",
118
118
  "xdg-basedir": "^4.0.0",
119
- "@repo/eslint-config": "4.18.1-next.9+99174013a7",
120
- "@repo/test-config": "4.18.1-next.9+99174013a7",
121
- "@repo/package.config": "4.18.1-next.9+99174013a7",
122
- "@sanity/types": "4.18.1-next.9+99174013a7",
123
- "@repo/tsconfig": "4.18.1-next.9+99174013a7"
119
+ "@repo/package.config": "4.19.0-next.19+cfd2d9c268",
120
+ "@repo/test-config": "4.19.0-next.19+cfd2d9c268",
121
+ "@repo/eslint-config": "4.19.0-next.19+cfd2d9c268",
122
+ "@repo/tsconfig": "4.19.0-next.19+cfd2d9c268",
123
+ "@sanity/types": "4.19.0-next.19+cfd2d9c268"
124
124
  },
125
125
  "peerDependencies": {
126
126
  "babel-plugin-react-compiler": "*"