@sanity/codegen 5.7.0 → 5.7.2-watch-mode

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,6 +1,10 @@
1
+ export { runTypegenGenerate } from '../actions/typegenGenerate.js';
2
+ export { runTypegenWatcher } from '../actions/typegenWatch.js';
3
+ export { TypegenGenerateCommand } from '../commands/typegen/generate.js';
1
4
  export { configDefinition, readConfig } from '../readConfig.js';
2
5
  export { readSchema } from '../readSchema.js';
3
6
  export { safeParseQuery } from '../safeParseQuery.js';
7
+ export { TypegenWatchModeTrace, TypesGeneratedTrace } from '../typegen.telemetry.js';
4
8
  export { findQueriesInPath } from '../typescript/findQueriesInPath.js';
5
9
  export { findQueriesInSource } from '../typescript/findQueriesInSource.js';
6
10
  export { getResolver } from '../typescript/moduleResolver.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/_exports/index.ts"],"sourcesContent":["export {\n type CodegenConfig,\n configDefinition,\n readConfig,\n type TypeGenConfig,\n} from '../readConfig.js'\nexport {readSchema} from '../readSchema.js'\nexport {safeParseQuery} from '../safeParseQuery.js'\nexport {findQueriesInPath} from '../typescript/findQueriesInPath.js'\nexport {findQueriesInSource} from '../typescript/findQueriesInSource.js'\nexport {getResolver} from '../typescript/moduleResolver.js'\nexport {registerBabel} from '../typescript/registerBabel.js'\nexport {\n type GenerateTypesOptions,\n TypeGenerator,\n type TypegenWorkerChannel,\n} from '../typescript/typeGenerator.js'\nexport {\n type EvaluatedModule,\n type EvaluatedQuery,\n type ExtractedModule,\n type ExtractedQuery,\n QueryExtractionError,\n} from '../typescript/types.js'\nexport {type FilterByType, type Get} from '../typeUtils.js'\n"],"names":["configDefinition","readConfig","readSchema","safeParseQuery","findQueriesInPath","findQueriesInSource","getResolver","registerBabel","TypeGenerator","QueryExtractionError"],"mappings":"AAAA,SAEEA,gBAAgB,EAChBC,UAAU,QAEL,mBAAkB;AACzB,SAAQC,UAAU,QAAO,mBAAkB;AAC3C,SAAQC,cAAc,QAAO,uBAAsB;AACnD,SAAQC,iBAAiB,QAAO,qCAAoC;AACpE,SAAQC,mBAAmB,QAAO,uCAAsC;AACxE,SAAQC,WAAW,QAAO,kCAAiC;AAC3D,SAAQC,aAAa,QAAO,iCAAgC;AAC5D,SAEEC,aAAa,QAER,iCAAgC;AACvC,SAKEC,oBAAoB,QACf,yBAAwB"}
1
+ {"version":3,"sources":["../../src/_exports/index.ts"],"sourcesContent":["export {runTypegenGenerate} from '../actions/typegenGenerate.js'\nexport {runTypegenWatcher} from '../actions/typegenWatch.js'\nexport {type GenerationResult, type RunTypegenOptions} from '../actions/types.js'\nexport {TypegenGenerateCommand} from '../commands/typegen/generate.js'\nexport {\n type CodegenConfig,\n configDefinition,\n readConfig,\n type TypeGenConfig,\n} from '../readConfig.js'\nexport {readSchema} from '../readSchema.js'\nexport {safeParseQuery} from '../safeParseQuery.js'\nexport {TypegenWatchModeTrace, TypesGeneratedTrace} from '../typegen.telemetry.js'\nexport {findQueriesInPath} from '../typescript/findQueriesInPath.js'\nexport {findQueriesInSource} from '../typescript/findQueriesInSource.js'\nexport {getResolver} from '../typescript/moduleResolver.js'\nexport {registerBabel} from '../typescript/registerBabel.js'\nexport {\n type GenerateTypesOptions,\n TypeGenerator,\n type TypegenWorkerChannel,\n} from '../typescript/typeGenerator.js'\nexport {\n type EvaluatedModule,\n type EvaluatedQuery,\n type ExtractedModule,\n type ExtractedQuery,\n QueryExtractionError,\n} from '../typescript/types.js'\nexport {type FilterByType, type Get} from '../typeUtils.js'\n"],"names":["runTypegenGenerate","runTypegenWatcher","TypegenGenerateCommand","configDefinition","readConfig","readSchema","safeParseQuery","TypegenWatchModeTrace","TypesGeneratedTrace","findQueriesInPath","findQueriesInSource","getResolver","registerBabel","TypeGenerator","QueryExtractionError"],"mappings":"AAAA,SAAQA,kBAAkB,QAAO,gCAA+B;AAChE,SAAQC,iBAAiB,QAAO,6BAA4B;AAE5D,SAAQC,sBAAsB,QAAO,kCAAiC;AACtE,SAEEC,gBAAgB,EAChBC,UAAU,QAEL,mBAAkB;AACzB,SAAQC,UAAU,QAAO,mBAAkB;AAC3C,SAAQC,cAAc,QAAO,uBAAsB;AACnD,SAAQC,qBAAqB,EAAEC,mBAAmB,QAAO,0BAAyB;AAClF,SAAQC,iBAAiB,QAAO,qCAAoC;AACpE,SAAQC,mBAAmB,QAAO,uCAAsC;AACxE,SAAQC,WAAW,QAAO,kCAAiC;AAC3D,SAAQC,aAAa,QAAO,iCAAgC;AAC5D,SAEEC,aAAa,QAER,iCAAgC;AACvC,SAKEC,oBAAoB,QACf,yBAAwB"}
@@ -0,0 +1,107 @@
1
+ import { debug } from 'node:console';
2
+ import { writeFile } from 'node:fs/promises';
3
+ import { spinner } from '@sanity/cli-core/ux';
4
+ import { count } from '../utils/count.js';
5
+ import { formatPath } from '../utils/formatPath.js';
6
+ import { getMessage } from '../utils/getMessage.js';
7
+ import { percent } from '../utils/percent.js';
8
+ import { generatedFileWarning } from './generatedFileWarning.js';
9
+ /**
10
+ * Processes the event stream from a typegen worker thread.
11
+ *
12
+ * Listens to worker channel events, displays progress via CLI spinners,
13
+ * writes the generated types to disk, and optionally formats with prettier.
14
+ *
15
+ * @param receiver - Worker channel receiver for typegen events
16
+ * @param options - Typegen configuration options
17
+ * @returns Generation result containing the generated code and statistics
18
+ */ export async function processTypegenWorkerStream(receiver, options) {
19
+ const start = Date.now();
20
+ const { formatGeneratedCode, generates, schema } = options;
21
+ let code = '';
22
+ try {
23
+ const spin = spinner().start(`Loading schema…`);
24
+ await receiver.event.loadedSchema();
25
+ spin.succeed(`Schema loaded from ${formatPath(schema ?? '')}`);
26
+ spin.start('Generating schema types…');
27
+ const { expectedFileCount } = await receiver.event.typegenStarted();
28
+ const { schemaTypeDeclarations } = await receiver.event.generatedSchemaTypes();
29
+ const schemaTypesCount = schemaTypeDeclarations.length;
30
+ spin.text = 'Generating query types…';
31
+ let queriesCount = 0;
32
+ let evaluatedFiles = 0;
33
+ let filesWithErrors = 0;
34
+ let queryFilesCount = 0;
35
+ let typeNodesGenerated = 0;
36
+ let unknownTypeNodesGenerated = 0;
37
+ let emptyUnionTypeNodesGenerated = 0;
38
+ for await (const { errors, queries } of receiver.stream.evaluatedModules()){
39
+ evaluatedFiles++;
40
+ queriesCount += queries.length;
41
+ queryFilesCount += queries.length > 0 ? 1 : 0;
42
+ filesWithErrors += errors.length > 0 ? 1 : 0;
43
+ for (const { stats } of queries){
44
+ typeNodesGenerated += stats.allTypes;
45
+ unknownTypeNodesGenerated += stats.unknownTypes;
46
+ emptyUnionTypeNodesGenerated += stats.emptyUnions;
47
+ }
48
+ for (const error of errors){
49
+ spin.fail(getMessage(error));
50
+ }
51
+ if (!spin.isSpinning) {
52
+ spin.start();
53
+ }
54
+ spin.text = `Generating query types… (${percent(evaluatedFiles / expectedFileCount)})\n` + ` └─ Processed ${count(evaluatedFiles)} of ${count(expectedFileCount, 'files')}. ` + `Found ${count(queriesCount, 'queries', 'query')} from ${count(queryFilesCount, 'files')}.`;
55
+ }
56
+ const result = await receiver.event.typegenComplete();
57
+ code = `${generatedFileWarning}${result.code}`;
58
+ await writeFile(generates, code);
59
+ let formattingError = false;
60
+ if (formatGeneratedCode) {
61
+ spin.text = `Formatting generated types with prettier…`;
62
+ try {
63
+ const prettier = await import('prettier');
64
+ const prettierConfig = await prettier.resolveConfig(generates);
65
+ const formattedCode = await prettier.format(code, {
66
+ ...prettierConfig,
67
+ parser: 'typescript'
68
+ });
69
+ await writeFile(generates, formattedCode);
70
+ } catch (err) {
71
+ formattingError = true;
72
+ spin.warn(`Failed to format generated types with prettier: ${getMessage(err)}`);
73
+ }
74
+ }
75
+ if (filesWithErrors > 0) {
76
+ spin.warn(`Encountered errors in ${count(filesWithErrors, 'files')} while generating types`);
77
+ }
78
+ const stats = {
79
+ duration: Date.now() - start,
80
+ emptyUnionTypeNodesGenerated,
81
+ filesWithErrors,
82
+ outputSize: Buffer.byteLength(code),
83
+ queriesCount,
84
+ queryFilesCount,
85
+ schemaTypesCount,
86
+ typeNodesGenerated,
87
+ unknownTypeNodesGenerated,
88
+ unknownTypeNodesRatio: typeNodesGenerated > 0 ? unknownTypeNodesGenerated / typeNodesGenerated : 0
89
+ };
90
+ let successText = `Successfully generated types to ${formatPath(generates)} in ${Number(stats.duration).toFixed(0)}ms` + `\n └─ ${count(queriesCount, 'queries', 'query')} and ${count(schemaTypesCount, 'schema types', 'schema type')}` + `\n └─ found queries in ${count(queryFilesCount, 'files', 'file')} after evaluating ${count(evaluatedFiles, 'files', 'file')}`;
91
+ if (formatGeneratedCode) {
92
+ successText += `\n └─ ${formattingError ? 'an error occured during formatting' : 'formatted the generated code with prettier'}`;
93
+ }
94
+ spin.succeed(successText);
95
+ return {
96
+ ...stats,
97
+ code
98
+ };
99
+ } catch (err) {
100
+ debug('error generating types', err);
101
+ throw err;
102
+ } finally{
103
+ receiver.unsubscribe();
104
+ }
105
+ }
106
+
107
+ //# sourceMappingURL=streamProcessor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/actions/streamProcessor.ts"],"sourcesContent":["import {debug} from 'node:console'\nimport {writeFile} from 'node:fs/promises'\n\nimport {spinner} from '@sanity/cli-core/ux'\nimport {WorkerChannelReceiver} from '@sanity/worker-channels'\n\nimport {count} from '../utils/count.js'\nimport {formatPath} from '../utils/formatPath.js'\nimport {getMessage} from '../utils/getMessage.js'\nimport {percent} from '../utils/percent.js'\nimport {generatedFileWarning} from './generatedFileWarning.js'\nimport {type RunTypegenOptions, TypegenWorkerChannel} from './types.js'\n\n/**\n * Processes the event stream from a typegen worker thread.\n *\n * Listens to worker channel events, displays progress via CLI spinners,\n * writes the generated types to disk, and optionally formats with prettier.\n *\n * @param receiver - Worker channel receiver for typegen events\n * @param options - Typegen configuration options\n * @returns Generation result containing the generated code and statistics\n */\nexport async function processTypegenWorkerStream(\n receiver: WorkerChannelReceiver<TypegenWorkerChannel>,\n options: RunTypegenOptions['config'],\n) {\n const start = Date.now()\n const {formatGeneratedCode, generates, schema} = options\n let code = ''\n\n try {\n const spin = spinner().start(`Loading schema…`)\n\n await receiver.event.loadedSchema()\n spin.succeed(`Schema loaded from ${formatPath(schema ?? '')}`)\n\n spin.start('Generating schema types…')\n const {expectedFileCount} = await receiver.event.typegenStarted()\n const {schemaTypeDeclarations} = await receiver.event.generatedSchemaTypes()\n const schemaTypesCount = schemaTypeDeclarations.length\n\n spin.text = 'Generating query types…'\n let queriesCount = 0\n let evaluatedFiles = 0\n let filesWithErrors = 0\n let queryFilesCount = 0\n let typeNodesGenerated = 0\n let unknownTypeNodesGenerated = 0\n let emptyUnionTypeNodesGenerated = 0\n\n for await (const {errors, queries} of receiver.stream.evaluatedModules()) {\n evaluatedFiles++\n queriesCount += queries.length\n queryFilesCount += queries.length > 0 ? 1 : 0\n filesWithErrors += errors.length > 0 ? 1 : 0\n\n for (const {stats} of queries) {\n typeNodesGenerated += stats.allTypes\n unknownTypeNodesGenerated += stats.unknownTypes\n emptyUnionTypeNodesGenerated += stats.emptyUnions\n }\n\n for (const error of errors) {\n spin.fail(getMessage(error))\n }\n\n if (!spin.isSpinning) {\n spin.start()\n }\n\n spin.text =\n `Generating query types… (${percent(evaluatedFiles / expectedFileCount)})\\n` +\n ` └─ Processed ${count(evaluatedFiles)} of ${count(expectedFileCount, 'files')}. ` +\n `Found ${count(queriesCount, 'queries', 'query')} from ${count(queryFilesCount, 'files')}.`\n }\n\n const result = await receiver.event.typegenComplete()\n code = `${generatedFileWarning}${result.code}`\n await writeFile(generates, code)\n\n let formattingError = false\n if (formatGeneratedCode) {\n spin.text = `Formatting generated types with prettier…`\n\n try {\n const prettier = await import('prettier')\n const prettierConfig = await prettier.resolveConfig(generates)\n const formattedCode = await prettier.format(code, {\n ...prettierConfig,\n parser: 'typescript' as const,\n })\n await writeFile(generates, formattedCode)\n } catch (err) {\n formattingError = true\n spin.warn(`Failed to format generated types with prettier: ${getMessage(err)}`)\n }\n }\n\n if (filesWithErrors > 0) {\n spin.warn(`Encountered errors in ${count(filesWithErrors, 'files')} while generating types`)\n }\n\n const stats = {\n duration: Date.now() - start,\n emptyUnionTypeNodesGenerated,\n filesWithErrors,\n outputSize: Buffer.byteLength(code),\n queriesCount,\n queryFilesCount,\n schemaTypesCount,\n typeNodesGenerated,\n unknownTypeNodesGenerated,\n unknownTypeNodesRatio:\n typeNodesGenerated > 0 ? unknownTypeNodesGenerated / typeNodesGenerated : 0,\n }\n\n let successText =\n `Successfully generated types to ${formatPath(generates)} in ${Number(stats.duration).toFixed(0)}ms` +\n `\\n └─ ${count(queriesCount, 'queries', 'query')} and ${count(schemaTypesCount, 'schema types', 'schema type')}` +\n `\\n └─ found queries in ${count(queryFilesCount, 'files', 'file')} after evaluating ${count(evaluatedFiles, 'files', 'file')}`\n\n if (formatGeneratedCode) {\n successText += `\\n └─ ${formattingError ? 'an error occured during formatting' : 'formatted the generated code with prettier'}`\n }\n\n spin.succeed(successText)\n\n return {\n ...stats,\n code,\n }\n } catch (err) {\n debug('error generating types', err)\n throw err\n } finally {\n receiver.unsubscribe()\n }\n}\n"],"names":["debug","writeFile","spinner","count","formatPath","getMessage","percent","generatedFileWarning","processTypegenWorkerStream","receiver","options","start","Date","now","formatGeneratedCode","generates","schema","code","spin","event","loadedSchema","succeed","expectedFileCount","typegenStarted","schemaTypeDeclarations","generatedSchemaTypes","schemaTypesCount","length","text","queriesCount","evaluatedFiles","filesWithErrors","queryFilesCount","typeNodesGenerated","unknownTypeNodesGenerated","emptyUnionTypeNodesGenerated","errors","queries","stream","evaluatedModules","stats","allTypes","unknownTypes","emptyUnions","error","fail","isSpinning","result","typegenComplete","formattingError","prettier","prettierConfig","resolveConfig","formattedCode","format","parser","err","warn","duration","outputSize","Buffer","byteLength","unknownTypeNodesRatio","successText","Number","toFixed","unsubscribe"],"mappings":"AAAA,SAAQA,KAAK,QAAO,eAAc;AAClC,SAAQC,SAAS,QAAO,mBAAkB;AAE1C,SAAQC,OAAO,QAAO,sBAAqB;AAG3C,SAAQ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ACZkB,UAAU9C,KAAKC,GAAG,KAAKF;YACvBwB;YACAJ;YACA4B,YAAYC,OAAOC,UAAU,CAAC5C;YAC9BY;YACAG;YACAN;YACAO;YACAC;YACA4B,uBACE7B,qBAAqB,IAAIC,4BAA4BD,qBAAqB;QAC9E;QAEA,IAAI8B,cACF,CAAC,gCAAgC,EAAE3D,WAAWW,WAAW,IAAI,EAAEiD,OAAOxB,MAAMkB,QAAQ,EAAEO,OAAO,CAAC,GAAG,EAAE,CAAC,GACpG,CAAC,OAAO,EAAE9D,MAAM0B,cAAc,WAAW,SAAS,KAAK,EAAE1B,MAAMuB,kBAAkB,gBAAgB,gBAAgB,GACjH,CAAC,wBAAwB,EAAEvB,MAAM6B,iBAAiB,SAAS,QAAQ,kBAAkB,EAAE7B,MAAM2B,gBAAgB,SAAS,SAAS;QAEjI,IAAIhB,qBAAqB;YACvBiD,eAAe,CAAC,OAAO,EAAEd,kBAAkB,uCAAuC,8CAA8C;QAClI;QAEA/B,KAAKG,OAAO,CAAC0C;QAEb,OAAO;YACL,GAAGvB,KAAK;YACRvB;QACF;IACF,EAAE,OAAOuC,KAAK;QACZxD,MAAM,0BAA0BwD;QAChC,MAAMA;IACR,SAAU;QACR/C,SAASyD,WAAW;IACtB;AACF"}
@@ -0,0 +1,54 @@
1
+ import { debug } from 'node:console';
2
+ import { mkdir } from 'node:fs/promises';
3
+ import { dirname, isAbsolute, join } from 'node:path';
4
+ import { env } from 'node:process';
5
+ import { Worker } from 'node:worker_threads';
6
+ import { WorkerChannelReceiver } from '@sanity/worker-channels';
7
+ import { processTypegenWorkerStream } from './streamProcessor.js';
8
+ /**
9
+ * Runs a single typegen generation.
10
+ *
11
+ * This is the programmatic API for generating TypeScript types from GROQ queries.
12
+ * It spawns a worker thread to perform the generation and displays progress via CLI spinners.
13
+ *
14
+ * @param options - Configuration options including typegen config and working directory
15
+ * @returns Generation result containing the generated code and statistics
16
+ */ export async function runTypegenGenerate(options) {
17
+ const { config, workDir } = options;
18
+ const { formatGeneratedCode, generates, overloadClientMethods, path, schema } = config;
19
+ const outputPath = isAbsolute(generates) ? generates : join(workDir, generates);
20
+ // create output dir if it isn't there
21
+ const outputDir = dirname(outputPath);
22
+ await mkdir(outputDir, {
23
+ recursive: true
24
+ });
25
+ // set up worker
26
+ const workerPath = new URL('../actions/typegenGenerate.worker.js', import.meta.url);
27
+ const workerData = {
28
+ overloadClientMethods,
29
+ schemaPath: schema,
30
+ searchPath: path,
31
+ workDir
32
+ };
33
+ const worker = new Worker(workerPath, {
34
+ env,
35
+ workerData
36
+ });
37
+ try {
38
+ const result = await processTypegenWorkerStream(WorkerChannelReceiver.from(worker), {
39
+ formatGeneratedCode,
40
+ generates: outputPath,
41
+ overloadClientMethods,
42
+ path,
43
+ schema
44
+ });
45
+ return result;
46
+ } catch (err) {
47
+ debug('error generating types', err);
48
+ throw err;
49
+ } finally{
50
+ worker.terminate();
51
+ }
52
+ }
53
+
54
+ //# sourceMappingURL=typegenGenerate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/actions/typegenGenerate.ts"],"sourcesContent":["import {debug} from 'node:console'\nimport {mkdir} from 'node:fs/promises'\nimport {dirname, isAbsolute, join} from 'node:path'\nimport {env} from 'node:process'\nimport {Worker} from 'node:worker_threads'\n\nimport {WorkerChannelReceiver} from '@sanity/worker-channels'\n\nimport {processTypegenWorkerStream} from './streamProcessor.js'\nimport {\n type GenerationResult,\n type RunTypegenOptions,\n TypegenGenerateTypesWorkerData,\n TypegenWorkerChannel,\n} from './types.js'\n\n/**\n * Runs a single typegen generation.\n *\n * This is the programmatic API for generating TypeScript types from GROQ queries.\n * It spawns a worker thread to perform the generation and displays progress via CLI spinners.\n *\n * @param options - Configuration options including typegen config and working directory\n * @returns Generation result containing the generated code and statistics\n */\nexport async function runTypegenGenerate(options: RunTypegenOptions): Promise<GenerationResult> {\n const {config, workDir} = options\n\n const {formatGeneratedCode, generates, overloadClientMethods, path, schema} = config\n\n const outputPath = isAbsolute(generates) ? generates : join(workDir, generates)\n\n // create output dir if it isn't there\n const outputDir = dirname(outputPath)\n await mkdir(outputDir, {recursive: true})\n\n // set up worker\n const workerPath = new URL('../actions/typegenGenerate.worker.js', import.meta.url)\n const workerData: TypegenGenerateTypesWorkerData = {\n overloadClientMethods,\n schemaPath: schema,\n searchPath: path,\n workDir,\n }\n const worker = new Worker(workerPath, {env, workerData})\n\n try {\n const result = await processTypegenWorkerStream(\n WorkerChannelReceiver.from<TypegenWorkerChannel>(worker),\n {\n formatGeneratedCode,\n generates: outputPath,\n overloadClientMethods,\n path,\n schema,\n },\n )\n\n return result\n } catch (err) {\n debug('error generating types', err)\n throw err\n } finally {\n worker.terminate()\n }\n}\n"],"names":["debug","mkdir","dirname","isAbsolute","join","env","Worker","WorkerChannelReceiver","processTypegenWorkerStream","runTypegenGenerate","options","config","workDir","formatGeneratedCode","generates","overloadClientMethods","path","schema","outputPath","outputDir","recursive","workerPath","URL","url","workerData","schemaPath","searchPath","worker","result","from","err","terminate"],"mappings":"AAAA,SAAQA,KAAK,QAAO,eAAc;AAClC,SAAQC,KAAK,QAAO,mBAAkB;AACtC,SAAQC,OAAO,EAAEC,UAAU,EAAEC,IAAI,QAAO,YAAW;AACnD,SAAQC,GAAG,QAAO,eAAc;AAChC,SAAQC,MAAM,QAAO,sBAAqB;AAE1C,SAAQC,qBAAqB,QAAO,0BAAyB;AAE7D,SAAQC,0BAA0B,QAAO,uBAAsB;AAQ/D;;;;;;;;CAQC,GACD,OAAO,eAAeC,mBAAmBC,OAA0B;IACjE,MAAM,EAACC,MAAM,EAAEC,OAAO,EAAC,GAAGF;IAE1B,MAAM,EAACG,mBAAmB,EAAEC,SAAS,EAAEC,qBAAqB,EAAEC,IAAI,EAAEC,MAAM,EAAC,GAAGN;IAE9E,MAAMO,aAAaf,WAAWW,aAAaA,YAAYV,KAAKQ,SAASE;IAErE,sCAAsC;IACtC,MAAMK,YAAYjB,QAAQgB;IAC1B,MAAMjB,MAAMkB,WAAW;QAACC,WAAW;IAAI;IAEvC,gBAAgB;IAChB,MAAMC,aAAa,IAAIC,IAAI,wCAAwC,YAAYC,GAAG;IAClF,MAAMC,aAA6C;QACjDT;QACAU,YAAYR;QACZS,YAAYV;QACZJ;IACF;IACA,MAAMe,SAAS,IAAIrB,OAAOe,YAAY;QAAChB;QAAKmB;IAAU;IAEtD,IAAI;QACF,MAAMI,SAAS,MAAMpB,2BACnBD,sBAAsBsB,IAAI,CAAuBF,SACjD;YACEd;YACAC,WAAWI;YACXH;YACAC;YACAC;QACF;QAGF,OAAOW;IACT,EAAE,OAAOE,KAAK;QACZ9B,MAAM,0BAA0B8B;QAChC,MAAMA;IACR,SAAU;QACRH,OAAOI,SAAS;IAClB;AACF"}
@@ -0,0 +1,108 @@
1
+ import { debug, error } from 'node:console';
2
+ import { isAbsolute, join, relative } from 'node:path';
3
+ import chokidar from 'chokidar';
4
+ import { debounce, mean } from 'lodash-es';
5
+ import { runTypegenGenerate } from './typegenGenerate.js';
6
+ const IGNORED_PATTERNS = [
7
+ '**/node_modules/**',
8
+ '**/.git/**',
9
+ '**/dist/**',
10
+ '**/lib/**',
11
+ '**/.sanity/**'
12
+ ];
13
+ /**
14
+ * Creates a typegen runner with concurrency control.
15
+ * If generation is already running, queues one more generation to run after completion.
16
+ * Multiple queued requests are coalesced into a single pending generation.
17
+ */ export function createTypegenRunner(onGenerate) {
18
+ const state = {
19
+ isGenerating: false,
20
+ pendingGeneration: false
21
+ };
22
+ async function runGeneration() {
23
+ if (state.isGenerating) {
24
+ state.pendingGeneration = true;
25
+ return;
26
+ }
27
+ state.isGenerating = true;
28
+ state.pendingGeneration = false;
29
+ try {
30
+ await onGenerate();
31
+ } finally{
32
+ state.isGenerating = false;
33
+ // If a change came in during generation, run again
34
+ if (state.pendingGeneration) {
35
+ state.pendingGeneration = false;
36
+ await runGeneration();
37
+ }
38
+ }
39
+ }
40
+ return {
41
+ runGeneration,
42
+ state
43
+ };
44
+ }
45
+ /**
46
+ * Starts a file watcher that triggers typegen on changes.
47
+ * Watches both query files (via patterns) and the schema JSON file.
48
+ * Implements debouncing and concurrency control to prevent multiple generations.
49
+ */ export function runTypegenWatcher(options) {
50
+ const { config, workDir } = options;
51
+ const { path, schema } = config;
52
+ const stats = {
53
+ failedCount: 0,
54
+ startTime: Date.now(),
55
+ successfulDurations: []
56
+ };
57
+ const { runGeneration } = createTypegenRunner(async ()=>{
58
+ try {
59
+ const { duration } = await runTypegenGenerate(options);
60
+ stats.successfulDurations.push(duration);
61
+ } catch {
62
+ stats.failedCount++;
63
+ }
64
+ });
65
+ // Debounced generation trigger
66
+ const debouncedGenerate = debounce(runGeneration, 1000);
67
+ // Build absolute patterns for query files and schema file
68
+ const paths = Array.isArray(path) ? path : [
69
+ path
70
+ ];
71
+ const absoluteQueryPatterns = paths.map((pattern)=>isAbsolute(pattern) ? pattern : join(workDir, pattern));
72
+ const absoluteSchemaPath = isAbsolute(schema) ? schema : join(workDir, schema);
73
+ const watchTargets = [
74
+ ...absoluteQueryPatterns,
75
+ absoluteSchemaPath
76
+ ];
77
+ // perform initial generation
78
+ debouncedGenerate();
79
+ // set up watcher
80
+ const watcher = chokidar.watch(watchTargets, {
81
+ cwd: workDir,
82
+ ignored: IGNORED_PATTERNS,
83
+ ignoreInitial: true
84
+ });
85
+ watcher.on('all', (event, filePath)=>{
86
+ const timestamp = new Date().toLocaleTimeString();
87
+ const relativePath = isAbsolute(filePath) ? relative(workDir, filePath) : filePath;
88
+ debug(`[${timestamp}] ${event}: ${relativePath}`);
89
+ debouncedGenerate();
90
+ });
91
+ watcher.on('error', (err)=>{
92
+ error(`Watcher error: ${err.message}`);
93
+ });
94
+ return {
95
+ getStats: ()=>({
96
+ averageGenerationDuration: mean(stats.successfulDurations) || 0,
97
+ generationFailedCount: stats.failedCount,
98
+ generationSuccessfulCount: stats.successfulDurations.length,
99
+ watcherDuration: Date.now() - stats.startTime
100
+ }),
101
+ stop: async ()=>{
102
+ await watcher.close();
103
+ },
104
+ watcher
105
+ };
106
+ }
107
+
108
+ //# sourceMappingURL=typegenWatch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/actions/typegenWatch.ts"],"sourcesContent":["import {debug, error} from 'node:console'\nimport {isAbsolute, join, relative} from 'node:path'\n\nimport chokidar, {FSWatcher} from 'chokidar'\nimport {debounce, mean} from 'lodash-es'\n\nimport {TypegenWatchModeTraceAttributes} from '../typegen.telemetry.js'\nimport {runTypegenGenerate} from './typegenGenerate.js'\nimport {type RunTypegenOptions} from './types.js'\n\nconst IGNORED_PATTERNS = [\n '**/node_modules/**',\n '**/.git/**',\n '**/dist/**',\n '**/lib/**',\n '**/.sanity/**',\n]\n\n/** State for tracking generation status */\nexport interface WatchState {\n isGenerating: boolean\n pendingGeneration: boolean\n}\n\n/** Return type for createTypegenRunner */\ninterface TypegenRunner {\n runGeneration: () => Promise<void>\n state: WatchState\n}\n\ntype WatcherStats = Omit<Extract<TypegenWatchModeTraceAttributes, {step: 'stopped'}>, 'step'>\n\n/**\n * Creates a typegen runner with concurrency control.\n * If generation is already running, queues one more generation to run after completion.\n * Multiple queued requests are coalesced into a single pending generation.\n */\nexport function createTypegenRunner(onGenerate: () => Promise<unknown>): TypegenRunner {\n const state: WatchState = {\n isGenerating: false,\n pendingGeneration: false,\n }\n\n async function runGeneration(): Promise<void> {\n if (state.isGenerating) {\n state.pendingGeneration = true\n return\n }\n\n state.isGenerating = true\n state.pendingGeneration = false\n\n try {\n await onGenerate()\n } finally {\n state.isGenerating = false\n\n // If a change came in during generation, run again\n if (state.pendingGeneration) {\n state.pendingGeneration = false\n await runGeneration()\n }\n }\n }\n\n return {runGeneration, state}\n}\n\n/**\n * Starts a file watcher that triggers typegen on changes.\n * Watches both query files (via patterns) and the schema JSON file.\n * Implements debouncing and concurrency control to prevent multiple generations.\n */\nexport function runTypegenWatcher(options: RunTypegenOptions): {\n getStats: () => WatcherStats\n stop: () => Promise<void>\n watcher: FSWatcher\n} {\n const {config, workDir} = options\n const {path, schema} = config\n\n const stats = {\n failedCount: 0,\n startTime: Date.now(),\n successfulDurations: [] as number[],\n }\n\n const {runGeneration} = createTypegenRunner(async () => {\n try {\n const {duration} = await runTypegenGenerate(options)\n stats.successfulDurations.push(duration)\n } catch {\n stats.failedCount++\n }\n })\n\n // Debounced generation trigger\n const debouncedGenerate = debounce(runGeneration, 1000)\n\n // Build absolute patterns for query files and schema file\n const paths = Array.isArray(path) ? path : [path]\n const absoluteQueryPatterns = paths.map((pattern) =>\n isAbsolute(pattern) ? pattern : join(workDir, pattern),\n )\n const absoluteSchemaPath = isAbsolute(schema) ? schema : join(workDir, schema)\n const watchTargets = [...absoluteQueryPatterns, absoluteSchemaPath]\n\n // perform initial generation\n debouncedGenerate()\n\n // set up watcher\n const watcher = chokidar.watch(watchTargets, {\n cwd: workDir,\n ignored: IGNORED_PATTERNS,\n ignoreInitial: true,\n })\n\n watcher.on('all', (event: string, filePath: string) => {\n const timestamp = new Date().toLocaleTimeString()\n const relativePath = isAbsolute(filePath) ? relative(workDir, filePath) : filePath\n debug(`[${timestamp}] ${event}: ${relativePath}`)\n debouncedGenerate()\n })\n\n watcher.on('error', (err: Error) => {\n error(`Watcher error: ${err.message}`)\n })\n\n return {\n getStats: () => ({\n averageGenerationDuration: mean(stats.successfulDurations) || 0,\n generationFailedCount: stats.failedCount,\n generationSuccessfulCount: stats.successfulDurations.length,\n watcherDuration: Date.now() - stats.startTime,\n }),\n stop: async () => {\n await watcher.close()\n },\n watcher,\n }\n}\n"],"names":["debug","error","isAbsolute","join","relative","chokidar","debounce","mean","runTypegenGenerate","IGNORED_PATTERNS","createTypegenRunner","onGenerate","state","isGenerating","pendingGeneration","runGeneration","runTypegenWatcher","options","config","workDir","path","schema","stats","failedCount","startTime","Date","now","successfulDurations","duration","push","debouncedGenerate","paths","Array","isArray","absoluteQueryPatterns","map","pattern","absoluteSchemaPath","watchTargets","watcher","watch","cwd","ignored","ignoreInitial","on","event","filePath","timestamp","toLocaleTimeString","relativePath","err","message","getStats","averageGenerationDuration","generationFailedCount","generationSuccessfulCount","length","watcherDuration","stop","close"],"mappings":"AAAA,SAAQA,KAAK,EAAEC,KAAK,QAAO,eAAc;AACzC,SAAQC,UAAU,EAAEC,IAAI,EAAEC,QAAQ,QAAO,YAAW;AAEpD,OAAOC,cAA2B,WAAU;AAC5C,SAAQC,QAAQ,EAAEC,IAAI,QAAO,YAAW;AAGxC,SAAQC,kBAAkB,QAAO,uBAAsB;AAGvD,MAAMC,mBAAmB;IACvB;IACA;IACA;IACA;IACA;CACD;AAgBD;;;;CAIC,GACD,OAAO,SAASC,oBAAoBC,UAAkC;IACpE,MAAMC,QAAoB;QACxBC,cAAc;QACdC,mBAAmB;IACrB;IAEA,eAAeC;QACb,IAAIH,MAAMC,YAAY,EAAE;YACtBD,MAAME,iBAAiB,GAAG;YAC1B;QACF;QAEAF,MAAMC,YAAY,GAAG;QACrBD,MAAME,iBAAiB,GAAG;QAE1B,IAAI;YACF,MAAMH;QACR,SAAU;YACRC,MAAMC,YAAY,GAAG;YAErB,mDAAmD;YACnD,IAAID,MAAME,iBAAiB,EAAE;gBAC3BF,MAAME,iBAAiB,GAAG;gBAC1B,MAAMC;YACR;QACF;IACF;IAEA,OAAO;QAACA;QAAeH;IAAK;AAC9B;AAEA;;;;CAIC,GACD,OAAO,SAASI,kBAAkBC,OAA0B;IAK1D,MAAM,EAACC,MAAM,EAAEC,OAAO,EAAC,GAAGF;IAC1B,MAAM,EAACG,IAAI,EAAEC,MAAM,EAAC,GAAGH;IAEvB,MAAMI,QAAQ;QACZC,aAAa;QACbC,WAAWC,KAAKC,GAAG;QACnBC,qBAAqB,EAAE;IACzB;IAEA,MAAM,EAACZ,aAAa,EAAC,GAAGL,oBAAoB;QAC1C,IAAI;YACF,MAAM,EAACkB,QAAQ,EAAC,GAAG,MAAMpB,mBAAmBS;YAC5CK,MAAMK,mBAAmB,CAACE,IAAI,CAACD;QACjC,EAAE,OAAM;YACNN,MAAMC,WAAW;QACnB;IACF;IAEA,+BAA+B;IAC/B,MAAMO,oBAAoBxB,SAASS,eAAe;IAElD,0DAA0D;IAC1D,MAAMgB,QAAQC,MAAMC,OAAO,CAACb,QAAQA,OAAO;QAACA;KAAK;IACjD,MAAMc,wBAAwBH,MAAMI,GAAG,CAAC,CAACC,UACvClC,WAAWkC,WAAWA,UAAUjC,KAAKgB,SAASiB;IAEhD,MAAMC,qBAAqBnC,WAAWmB,UAAUA,SAASlB,KAAKgB,SAASE;IACvE,MAAMiB,eAAe;WAAIJ;QAAuBG;KAAmB;IAEnE,6BAA6B;IAC7BP;IAEA,iBAAiB;IACjB,MAAMS,UAAUlC,SAASmC,KAAK,CAACF,cAAc;QAC3CG,KAAKtB;QACLuB,SAASjC;QACTkC,eAAe;IACjB;IAEAJ,QAAQK,EAAE,CAAC,OAAO,CAACC,OAAeC;QAChC,MAAMC,YAAY,IAAItB,OAAOuB,kBAAkB;QAC/C,MAAMC,eAAe/C,WAAW4C,YAAY1C,SAASe,SAAS2B,YAAYA;QAC1E9C,MAAM,CAAC,CAAC,EAAE+C,UAAU,EAAE,EAAEF,MAAM,EAAE,EAAEI,cAAc;QAChDnB;IACF;IAEAS,QAAQK,EAAE,CAAC,SAAS,CAACM;QACnBjD,MAAM,CAAC,eAAe,EAAEiD,IAAIC,OAAO,EAAE;IACvC;IAEA,OAAO;QACLC,UAAU,IAAO,CAAA;gBACfC,2BAA2B9C,KAAKe,MAAMK,mBAAmB,KAAK;gBAC9D2B,uBAAuBhC,MAAMC,WAAW;gBACxCgC,2BAA2BjC,MAAMK,mBAAmB,CAAC6B,MAAM;gBAC3DC,iBAAiBhC,KAAKC,GAAG,KAAKJ,MAAME,SAAS;YAC/C,CAAA;QACAkC,MAAM;YACJ,MAAMnB,QAAQoB,KAAK;QACrB;QACApB;IACF;AACF"}
@@ -1,3 +1,6 @@
1
- export { };
1
+ /**
2
+ * Result from a single generation run.
3
+ * @internal
4
+ */ export { };
2
5
 
3
6
  //# sourceMappingURL=types.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/actions/types.ts"],"sourcesContent":["import {WorkerChannel} from '@sanity/worker-channels'\n\nimport {type TypegenWorkerChannel as CodegenTypegenWorkerChannel} from '../typescript/typeGenerator.js'\n\nexport interface TypegenGenerateTypesWorkerData {\n schemaPath: string\n searchPath: string | string[]\n workDir: string\n\n overloadClientMethods?: boolean\n}\n\nexport type TypegenWorkerChannel = WorkerChannel.Definition<\n CodegenTypegenWorkerChannel['__definition'] & {\n loadedSchema: WorkerChannel.Event\n typegenComplete: WorkerChannel.Event<{code: string}>\n typegenStarted: WorkerChannel.Event<{expectedFileCount: number}>\n }\n>\n"],"names":[],"mappings":"AAYA,WAMC"}
1
+ {"version":3,"sources":["../../src/actions/types.ts"],"sourcesContent":["import {spinner} from '@sanity/cli-core/ux'\nimport {WorkerChannel} from '@sanity/worker-channels'\n\nimport {TypeGenConfig} from '../readConfig.js'\nimport {type TypegenWorkerChannel as CodegenTypegenWorkerChannel} from '../typescript/typeGenerator.js'\nimport {telemetry} from '../utils/telemetryLogger.js'\n\n/**\n * Data passed to the typegen worker thread.\n * @internal\n */\nexport interface TypegenGenerateTypesWorkerData {\n /** Path to the schema JSON file */\n schemaPath: string\n /** Glob pattern(s) for finding query files */\n searchPath: string | string[]\n /** Working directory (project root) */\n workDir: string\n\n /** Whether to generate client method overloads */\n overloadClientMethods?: boolean\n}\n\n/**\n * Worker channel definition for typegen worker communication.\n * Extends the base TypegenWorkerChannel with additional events for progress tracking.\n * @internal\n */\nexport type TypegenWorkerChannel = WorkerChannel.Definition<\n CodegenTypegenWorkerChannel['__definition'] & {\n loadedSchema: WorkerChannel.Event\n typegenComplete: WorkerChannel.Event<{code: string}>\n typegenStarted: WorkerChannel.Event<{expectedFileCount: number}>\n }\n>\n\n/**\n * Options for running a single typegen generation.\n * This is the programmatic API for one-off generation without file watching.\n */\nexport interface RunTypegenOptions {\n /** Typegen configuration */\n config: TypeGenConfig\n\n /** Working directory (usually project root) */\n workDir: string\n\n /** Optional spinner instance for progress display */\n spin?: ReturnType<typeof spinner>\n\n /** Optional telemetry instance for tracking usage */\n telemetry?: typeof telemetry\n}\n\n/**\n * Result from a single generation run.\n * @internal\n */\nexport interface GenerationResult {\n code: string\n duration: number\n emptyUnionTypeNodesGenerated: number\n filesWithErrors: number\n outputSize: number\n queriesCount: number\n queryFilesCount: number\n schemaTypesCount: number\n typeNodesGenerated: number\n unknownTypeNodesGenerated: number\n unknownTypeNodesRatio: number\n}\n"],"names":[],"mappings":"AAsDA;;;CAGC,GACD,WAYC"}
@@ -1,17 +1,14 @@
1
- import { mkdir, stat, writeFile } from 'node:fs/promises';
2
- import { dirname, isAbsolute, join } from 'node:path';
3
- import { env } from 'node:process';
4
- import { Worker } from 'node:worker_threads';
1
+ import { stat } from 'node:fs/promises';
5
2
  import { Flags } from '@oclif/core';
6
- import { SanityCommand, subdebug } from '@sanity/cli-core';
3
+ import { SanityCommand } from '@sanity/cli-core';
7
4
  import { chalk, spinner } from '@sanity/cli-core/ux';
8
- import { WorkerChannelReceiver } from '@sanity/worker-channels';
9
- import { generatedFileWarning } from '../../actions/generatedFileWarning.js';
5
+ import { omit, once } from 'lodash-es';
6
+ import { runTypegenGenerate } from '../../actions/typegenGenerate.js';
7
+ import { runTypegenWatcher } from '../../actions/typegenWatch.js';
10
8
  import { configDefinition, readConfig } from '../../readConfig.js';
11
- import { count } from '../../utils/count.js';
12
- import { formatPath } from '../../utils/formatPath.js';
13
- import { getMessage } from '../../utils/getMessage.js';
14
- import { percent } from '../../utils/percent.js';
9
+ import { TypegenWatchModeTrace, TypesGeneratedTrace } from '../../typegen.telemetry.js';
10
+ import { promiseWithResolvers } from '../../utils/promiseWithResolvers.js';
11
+ import { telemetry } from '../../utils/telemetryLogger.js';
15
12
  const description = `Sanity TypeGen (Beta)
16
13
  This command is currently in beta and may undergo significant changes. Feedback is welcome!
17
14
 
@@ -32,8 +29,9 @@ The default configuration values listed above are used if not overridden in your
32
29
  ${chalk.bold('Note:')}
33
30
  - The \`sanity schema extract\` command is a prerequisite for extracting your Sanity Studio schema into a \`schema.json\` file, which is then used by the \`sanity typegen generate\` command to generate type definitions.
34
31
  - While this tool is in beta, we encourage you to experiment with these configurations and provide feedback to help improve its functionality and usability.`.trim();
35
- const debug = subdebug('typegen:generate');
36
- export class TypegenGenerateCommand extends SanityCommand {
32
+ /**
33
+ * @internal
34
+ */ export class TypegenGenerateCommand extends SanityCommand {
37
35
  static description = description;
38
36
  static examples = [
39
37
  {
@@ -44,146 +42,26 @@ export class TypegenGenerateCommand extends SanityCommand {
44
42
  static flags = {
45
43
  'config-path': Flags.string({
46
44
  description: '[Default: sanity-typegen.json] Specifies the path to the typegen configuration file. This file should be a JSON file that contains settings for the type generation process.'
45
+ }),
46
+ watch: Flags.boolean({
47
+ description: '[Default: false] Run the typegen in watch mode'
47
48
  })
48
49
  };
49
50
  async run() {
50
51
  const { flags } = await this.parse(TypegenGenerateCommand);
51
- const workDir = (await this.getProjectRoot()).directory;
52
- // TODO: Add telemetry
53
- // const trace = telemetry.trace(TypesGeneratedTrace)
54
- // trace.start()
55
- const spin = spinner({}).start('Loading config…');
56
- let typegenConfig;
57
- let configPath;
58
- let typegenConfigMethod;
59
- try {
60
- const result = await this.getConfig(spin, flags['config-path']);
61
- typegenConfig = result.config;
62
- configPath = result.path;
63
- typegenConfigMethod = result.type;
64
- spin.succeed(`Config loaded from ${formatPath(configPath?.replace(workDir, '.') ?? '')}`);
65
- } catch (error) {
66
- debug('error loading config', error);
67
- spin.fail();
68
- this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {
69
- exit: 1
70
- });
71
- }
72
- const { formatGeneratedCode, generates, overloadClientMethods, path: searchPath, schema: schemaPath } = typegenConfig;
73
- const outputPath = isAbsolute(typegenConfig.generates) ? typegenConfig.generates : join(workDir, typegenConfig.generates);
74
- const outputDir = dirname(outputPath);
75
- await mkdir(outputDir, {
76
- recursive: true
77
- });
78
- const workerPath = new URL('../../actions/typegenGenerate.worker.js', import.meta.url);
79
- const workerData = {
80
- overloadClientMethods,
81
- schemaPath,
82
- searchPath,
83
- workDir
84
- };
85
- const worker = new Worker(workerPath, {
86
- env,
87
- workerData
88
- });
89
- const receiver = WorkerChannelReceiver.from(worker);
90
- try {
91
- spin.start(`Loading schema…`);
92
- await receiver.event.loadedSchema();
93
- spin.succeed(`Schema loaded from ${formatPath(schemaPath ?? '')}`);
94
- spin.start('Generating schema types…');
95
- const { expectedFileCount } = await receiver.event.typegenStarted();
96
- const { schemaTypeDeclarations } = await receiver.event.generatedSchemaTypes();
97
- const schemaTypesCount = schemaTypeDeclarations.length;
98
- spin.succeed(`Generated ${count(schemaTypesCount, 'schema types')}`);
99
- spin.start('Generating query types…');
100
- let queriesCount = 0;
101
- let evaluatedFiles = 0;
102
- let filesWithErrors = 0;
103
- let queryFilesCount = 0;
104
- let typeNodesGenerated = 0;
105
- let unknownTypeNodesGenerated = 0;
106
- let emptyUnionTypeNodesGenerated = 0;
107
- for await (const { errors, queries } of receiver.stream.evaluatedModules()){
108
- evaluatedFiles++;
109
- queriesCount += queries.length;
110
- queryFilesCount += queries.length > 0 ? 1 : 0;
111
- filesWithErrors += errors.length > 0 ? 1 : 0;
112
- for (const { stats } of queries){
113
- typeNodesGenerated += stats.allTypes;
114
- unknownTypeNodesGenerated += stats.unknownTypes;
115
- emptyUnionTypeNodesGenerated += stats.emptyUnions;
116
- }
117
- for (const error of errors){
118
- spin.fail(getMessage(error));
119
- }
120
- spin.text = `Generating query types… (${percent(evaluatedFiles / expectedFileCount)})\n` + ` └─ Processed ${count(evaluatedFiles)} of ${count(expectedFileCount, 'files')}. ` + `Found ${count(queriesCount, 'queries', 'query')} from ${count(queryFilesCount, 'files')}.`;
121
- }
122
- const result = await receiver.event.typegenComplete();
123
- const code = `${generatedFileWarning}${result.code}`;
124
- await writeFile(outputPath, code);
125
- spin.succeed(`Generated ${count(queriesCount, 'query types')} from ${count(queryFilesCount, 'files')} out of ${count(evaluatedFiles, 'scanned files')}`);
126
- if (formatGeneratedCode) {
127
- spin.start(`Formatting generated types with prettier…`);
128
- try {
129
- const prettier = await import('prettier');
130
- const prettierConfig = await prettier.resolveConfig(outputPath);
131
- const formattedCode = await prettier.format(code, {
132
- ...prettierConfig,
133
- parser: 'typescript'
134
- });
135
- await writeFile(outputPath, formattedCode);
136
- spin.succeed('Formatted generated types with prettier');
137
- } catch (err) {
138
- spin.warn(`Failed to format generated types with prettier: ${getMessage(err)}`);
139
- }
140
- }
141
- debug('trace', {
142
- configMethod: typegenConfigMethod,
143
- configOverloadClientMethods: overloadClientMethods,
144
- emptyUnionTypeNodesGenerated,
145
- filesWithErrors,
146
- outputSize: Buffer.byteLength(result.code),
147
- queriesCount,
148
- queryFilesCount,
149
- schemaTypesCount,
150
- typeNodesGenerated,
151
- unknownTypeNodesGenerated,
152
- unknownTypeNodesRatio: typeNodesGenerated > 0 ? unknownTypeNodesGenerated / typeNodesGenerated : 0
153
- });
154
- // trace.log({
155
- // configMethod: typegenConfigMethod,
156
- // configOverloadClientMethods: overloadClientMethods,
157
- // emptyUnionTypeNodesGenerated,
158
- // filesWithErrors,
159
- // outputSize: Buffer.byteLength(result.code),
160
- // queriesCount,
161
- // queryFilesCount,
162
- // schemaTypesCount,
163
- // typeNodesGenerated,
164
- // unknownTypeNodesGenerated,
165
- // unknownTypeNodesRatio:
166
- // typeNodesGenerated > 0 ? unknownTypeNodesGenerated / typeNodesGenerated : 0,
167
- // })
168
- if (filesWithErrors > 0) {
169
- spin.warn(`Encountered errors in ${count(filesWithErrors, 'files')} while generating types`);
170
- }
171
- spin.succeed(`Successfully generated types to ${formatPath(generates)}`);
172
- } catch (err) {
173
- // trace.error(err)
174
- debug('error generating types', err);
175
- this.error(err instanceof Error ? err.message : 'Unknown error', {
176
- exit: 1
177
- });
178
- } finally{
179
- receiver.unsubscribe();
180
- // trace.complete()
181
- await worker.terminate();
52
+ if (flags.watch) {
53
+ await this.runWatcher();
54
+ return;
182
55
  }
56
+ await this.runSingle();
183
57
  }
184
- async getConfig(spin, configPath) {
58
+ async getConfig() {
59
+ const spin = spinner({}).start('Loading config…');
60
+ const { flags } = await this.parse(TypegenGenerateCommand);
185
61
  const rootDir = await this.getProjectRoot();
186
62
  const config = await this.getCliConfig();
63
+ const configPath = flags['config-path'];
64
+ const workDir = rootDir.directory;
187
65
  // check if the legacy config exist
188
66
  const legacyConfigPath = configPath || 'sanity-typegen.json';
189
67
  let hasLegacyConfig = false;
@@ -211,7 +89,8 @@ export class TypegenGenerateCommand extends SanityCommand {
211
89
  return {
212
90
  config: configDefinition.parse(config.typegen || {}),
213
91
  path: rootDir.path,
214
- type: 'cli'
92
+ type: 'cli',
93
+ workDir
215
94
  };
216
95
  }
217
96
  // we only have legacy typegen config
@@ -222,16 +101,74 @@ export class TypegenGenerateCommand extends SanityCommand {
222
101
  return {
223
102
  config: await readConfig(legacyConfigPath),
224
103
  path: legacyConfigPath,
225
- type: 'legacy'
104
+ type: 'legacy',
105
+ workDir
226
106
  };
227
107
  }
108
+ spin.succeed(`Config loaded from sanity.cli.ts`);
228
109
  // we only have cli config
229
110
  return {
230
111
  config: configDefinition.parse(config.typegen || {}),
231
112
  path: rootDir.path,
232
- type: 'cli'
113
+ type: 'cli',
114
+ workDir
233
115
  };
234
116
  }
117
+ async runSingle() {
118
+ const trace = telemetry.trace(TypesGeneratedTrace);
119
+ try {
120
+ const { config: typegenConfig, type: typegenConfigMethod, workDir } = await this.getConfig();
121
+ trace.start();
122
+ const result = await runTypegenGenerate({
123
+ config: typegenConfig,
124
+ workDir
125
+ });
126
+ const traceStats = omit(result, 'code', 'duration');
127
+ trace.log({
128
+ configMethod: typegenConfigMethod,
129
+ configOverloadClientMethods: typegenConfig.overloadClientMethods,
130
+ ...traceStats
131
+ });
132
+ trace.complete();
133
+ } catch (error) {
134
+ trace.error(error);
135
+ trace.complete();
136
+ this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {
137
+ exit: 1
138
+ });
139
+ }
140
+ }
141
+ async runWatcher() {
142
+ const trace = telemetry.trace(TypegenWatchModeTrace);
143
+ try {
144
+ const { config: typegenConfig, workDir } = await this.getConfig();
145
+ trace.start();
146
+ const { promise, resolve } = promiseWithResolvers();
147
+ const typegenWatcher = runTypegenWatcher({
148
+ config: typegenConfig,
149
+ workDir
150
+ });
151
+ const stop = once(async ()=>{
152
+ process.off('SIGINT', stop);
153
+ process.off('SIGTERM', stop);
154
+ trace.log({
155
+ step: 'stopped',
156
+ ...typegenWatcher.getStats()
157
+ });
158
+ await typegenWatcher.stop();
159
+ resolve();
160
+ });
161
+ process.on('SIGINT', stop);
162
+ process.on('SIGTERM', stop);
163
+ await promise;
164
+ } catch (error) {
165
+ trace.error(error);
166
+ trace.complete();
167
+ this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {
168
+ exit: 1
169
+ });
170
+ }
171
+ }
235
172
  }
236
173
 
237
174
  //# sourceMappingURL=generate.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/typegen/generate.ts"],"sourcesContent":["import {mkdir, stat, writeFile} from 'node:fs/promises'\nimport {dirname, isAbsolute, join} from 'node:path'\nimport {env} from 'node:process'\nimport {Worker} from 'node:worker_threads'\n\nimport {Flags} from '@oclif/core'\nimport {SanityCommand, subdebug} from '@sanity/cli-core'\nimport {chalk, spinner} from '@sanity/cli-core/ux'\nimport {WorkerChannelReceiver} from '@sanity/worker-channels'\n\nimport {generatedFileWarning} from '../../actions/generatedFileWarning.js'\nimport {\n type TypegenGenerateTypesWorkerData,\n type TypegenWorkerChannel,\n} from '../../actions/types.js'\nimport {configDefinition, readConfig, type TypeGenConfig} from '../../readConfig.js'\nimport {count} from '../../utils/count.js'\nimport {formatPath} from '../../utils/formatPath.js'\nimport {getMessage} from '../../utils/getMessage.js'\nimport {percent} from '../../utils/percent.js'\n\nconst description = `Sanity TypeGen (Beta)\nThis command is currently in beta and may undergo significant changes. Feedback is welcome!\n\n${chalk.bold('Configuration:')}\nThis command can utilize configuration settings defined in a \\`sanity-typegen.json\\` file. These settings include:\n\n- \"path\": Specifies a glob pattern to locate your TypeScript or JavaScript files.\n Default: \"./src/**/*.{ts,tsx,js,jsx}\"\n\n- \"schema\": Defines the path to your Sanity schema file. This file should be generated using the \\`sanity schema extract\\` command.\n Default: \"schema.json\"\n\n- \"generates\": Indicates the path where the generated TypeScript type definitions will be saved.\n Default: \"./sanity.types.ts\"\n\nThe default configuration values listed above are used if not overridden in your \\`sanity-typegen.json\\` configuration file. To customize the behavior of the type generation, adjust these properties in the configuration file according to your project's needs.\n\n${chalk.bold('Note:')}\n- The \\`sanity schema extract\\` command is a prerequisite for extracting your Sanity Studio schema into a \\`schema.json\\` file, which is then used by the \\`sanity typegen generate\\` command to generate type definitions.\n- While this tool is in beta, we encourage you to experiment with these configurations and provide feedback to help improve its functionality and usability.`.trim()\n\nconst debug = subdebug('typegen:generate')\n\nexport class TypegenGenerateCommand extends SanityCommand<typeof TypegenGenerateCommand> {\n static override description = description\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: `Generate TypeScript type definitions from a Sanity Studio schema extracted using the \\`sanity schema extract\\` command.`,\n },\n ]\n\n static override flags = {\n 'config-path': Flags.string({\n description:\n '[Default: sanity-typegen.json] Specifies the path to the typegen configuration file. This file should be a JSON file that contains settings for the type generation process.',\n }),\n }\n\n public async run() {\n const {flags} = await this.parse(TypegenGenerateCommand)\n const workDir = (await this.getProjectRoot()).directory\n\n // TODO: Add telemetry\n // const trace = telemetry.trace(TypesGeneratedTrace)\n // trace.start()\n\n const spin = spinner({}).start('Loading config…')\n\n let typegenConfig: TypeGenConfig\n let configPath: string | undefined\n let typegenConfigMethod: 'cli' | 'legacy'\n\n try {\n const result = await this.getConfig(spin, flags['config-path'])\n typegenConfig = result.config\n configPath = result.path\n typegenConfigMethod = result.type\n\n spin.succeed(`Config loaded from ${formatPath(configPath?.replace(workDir, '.') ?? '')}`)\n } catch (error) {\n debug('error loading config', error)\n spin.fail()\n this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {\n exit: 1,\n })\n }\n\n const {\n formatGeneratedCode,\n generates,\n overloadClientMethods,\n path: searchPath,\n schema: schemaPath,\n } = typegenConfig\n\n const outputPath = isAbsolute(typegenConfig.generates)\n ? typegenConfig.generates\n : join(workDir, typegenConfig.generates)\n\n const outputDir = dirname(outputPath)\n await mkdir(outputDir, {recursive: true})\n\n const workerPath = new URL('../../actions/typegenGenerate.worker.js', import.meta.url)\n const workerData: TypegenGenerateTypesWorkerData = {\n overloadClientMethods,\n schemaPath,\n searchPath,\n workDir,\n }\n\n const worker = new Worker(workerPath, {env, workerData})\n const receiver = WorkerChannelReceiver.from<TypegenWorkerChannel>(worker)\n\n try {\n spin.start(`Loading schema…`)\n await receiver.event.loadedSchema()\n spin.succeed(`Schema loaded from ${formatPath(schemaPath ?? '')}`)\n\n spin.start('Generating schema types…')\n const {expectedFileCount} = await receiver.event.typegenStarted()\n const {schemaTypeDeclarations} = await receiver.event.generatedSchemaTypes()\n const schemaTypesCount = schemaTypeDeclarations.length\n spin.succeed(`Generated ${count(schemaTypesCount, 'schema types')}`)\n\n spin.start('Generating query types…')\n let queriesCount = 0\n let evaluatedFiles = 0\n let filesWithErrors = 0\n let queryFilesCount = 0\n let typeNodesGenerated = 0\n let unknownTypeNodesGenerated = 0\n let emptyUnionTypeNodesGenerated = 0\n\n for await (const {errors, queries} of receiver.stream.evaluatedModules()) {\n evaluatedFiles++\n queriesCount += queries.length\n queryFilesCount += queries.length > 0 ? 1 : 0\n filesWithErrors += errors.length > 0 ? 1 : 0\n\n for (const {stats} of queries) {\n typeNodesGenerated += stats.allTypes\n unknownTypeNodesGenerated += stats.unknownTypes\n emptyUnionTypeNodesGenerated += stats.emptyUnions\n }\n\n for (const error of errors) {\n spin.fail(getMessage(error))\n }\n\n spin.text =\n `Generating query types… (${percent(evaluatedFiles / expectedFileCount)})\\n` +\n ` └─ Processed ${count(evaluatedFiles)} of ${count(expectedFileCount, 'files')}. ` +\n `Found ${count(queriesCount, 'queries', 'query')} from ${count(queryFilesCount, 'files')}.`\n }\n\n const result = await receiver.event.typegenComplete()\n const code = `${generatedFileWarning}${result.code}`\n await writeFile(outputPath, code)\n\n spin.succeed(\n `Generated ${count(queriesCount, 'query types')} from ${count(queryFilesCount, 'files')} out of ${count(evaluatedFiles, 'scanned files')}`,\n )\n\n if (formatGeneratedCode) {\n spin.start(`Formatting generated types with prettier…`)\n\n try {\n const prettier = await import('prettier')\n const prettierConfig = await prettier.resolveConfig(outputPath)\n const formattedCode = await prettier.format(code, {\n ...prettierConfig,\n parser: 'typescript' as const,\n })\n await writeFile(outputPath, formattedCode)\n\n spin.succeed('Formatted generated types with prettier')\n } catch (err) {\n spin.warn(`Failed to format generated types with prettier: ${getMessage(err)}`)\n }\n }\n\n debug('trace', {\n configMethod: typegenConfigMethod,\n configOverloadClientMethods: overloadClientMethods,\n emptyUnionTypeNodesGenerated,\n filesWithErrors,\n outputSize: Buffer.byteLength(result.code),\n queriesCount,\n queryFilesCount,\n schemaTypesCount,\n typeNodesGenerated,\n unknownTypeNodesGenerated,\n unknownTypeNodesRatio:\n typeNodesGenerated > 0 ? unknownTypeNodesGenerated / typeNodesGenerated : 0,\n })\n // trace.log({\n // configMethod: typegenConfigMethod,\n // configOverloadClientMethods: overloadClientMethods,\n // emptyUnionTypeNodesGenerated,\n // filesWithErrors,\n // outputSize: Buffer.byteLength(result.code),\n // queriesCount,\n // queryFilesCount,\n // schemaTypesCount,\n // typeNodesGenerated,\n // unknownTypeNodesGenerated,\n // unknownTypeNodesRatio:\n // typeNodesGenerated > 0 ? unknownTypeNodesGenerated / typeNodesGenerated : 0,\n // })\n\n if (filesWithErrors > 0) {\n spin.warn(`Encountered errors in ${count(filesWithErrors, 'files')} while generating types`)\n }\n\n spin.succeed(`Successfully generated types to ${formatPath(generates)}`)\n } catch (err) {\n // trace.error(err)\n debug('error generating types', err)\n this.error(err instanceof Error ? err.message : 'Unknown error', {exit: 1})\n } finally {\n receiver.unsubscribe()\n // trace.complete()\n await worker.terminate()\n }\n }\n\n private async getConfig(\n spin: ReturnType<typeof spinner>,\n configPath?: string,\n ): Promise<{config: TypeGenConfig; path?: string; type: 'cli' | 'legacy'}> {\n const rootDir = await this.getProjectRoot()\n const config = await this.getCliConfig()\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 instanceof Error && 'code' in err && err.code === 'ENOENT' && configPath) {\n throw new Error(`Typegen config file not found: ${configPath}`, {cause: err})\n }\n\n if (err instanceof Error && 'code' in err && 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?.typegen && hasLegacyConfig) {\n spin.warn(\n chalk.yellow(\n `You've specified typegen in your Sanity CLI config, but also have a typegen config.\n\n The config from the Sanity CLI config is used.\n `,\n ),\n )\n\n return {\n config: configDefinition.parse(config.typegen || {}),\n path: rootDir.path,\n type: 'cli',\n }\n }\n\n // we only have legacy typegen config\n if (hasLegacyConfig) {\n spin.warn(\n chalk.yellow(\n `The separate typegen config has been deprecated. Use \\`typegen\\` in the sanity CLI config instead.\n\n See: https://www.sanity.io/docs/help/configuring-typegen-in-sanity-cli-config`,\n ),\n )\n return {\n config: await readConfig(legacyConfigPath),\n path: legacyConfigPath,\n type: 'legacy',\n }\n }\n\n // we only have cli config\n return {\n config: configDefinition.parse(config.typegen || {}),\n path: rootDir.path,\n type: 'cli',\n }\n }\n}\n"],"names":["mkdir","stat","writeFile","dirname","isAbsolute","join","env","Worker","Flags","SanityCommand","subdebug","chalk","spinner","WorkerChannelReceiver","generatedFileWarning","configDefinition","readConfig","count","formatPath","getMessage","percent","description","bold","trim","debug","TypegenGenerateCommand","examples","command","flags","string","run","parse","workDir","getProjectRoot","directory","spin","start","typegenConfig","configPath","typegenConfigMethod","result","getConfig","config","path","type","succeed","replace","error","fail","Error","message","exit","formatGeneratedCode","generates","overloadClientMethods","searchPath","schema","schemaPath","outputPath","outputDir","recursive","workerPath","URL","url","workerData","worker","receiver","from","event","loadedSchema","expectedFileCount","typegenStarted","schemaTypeDeclarations","generatedSchemaTypes","schemaTypesCount","length","queriesCount","evaluatedFiles","filesWithErrors","queryFilesCount","typeNodesGenerated","unknownTypeNodesGenerated","emptyUnionTypeNodesGenerated","errors","queries","stream","evaluatedModules","stats","allTypes","unknownTypes","emptyUnions","text","typegenComplete","code","prettier","prettierConfig","resolveConfig","formattedCode","format","parser","err","warn","configMethod","configOverloadClientMethods","outputSize","Buffer","byteLength","unknownTypeNodesRatio","unsubscribe","terminate","rootDir","getCliConfig","legacyConfigPath","hasLegacyConfig","file","isFile","cause","typegen","yellow"],"mappings":"AAAA,SAAQA,KAAK,EAAEC,IAAI,EAAEC,SAAS,QAAO,mBAAkB;AACvD,SAAQC,OAAO,EAAEC,UAAU,EAAEC,IAAI,QAAO,YAAW;AACnD,SAAQC,GAAG,QAAO,eAAc;AAChC,SAAQC,MAAM,QAAO,sBAAqB;AAE1C,SAAQC,KAAK,QAAO,cAAa;AACjC,SAAQC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AACxD,SAAQC,KAAK,EAAEC,OAAO,QAAO,sBAAqB;AAClD,SAAQC,qBAAqB,QAAO,0BAAyB;AAE7D,SAAQC,oBAAoB,QAAO,wCAAuC;AAK1E,SAAQC,gBAAgB,EAAEC,UAAU,QAA2B,sBAAqB;AACpF,SAAQC,KAAK,QAAO,uBAAsB;AAC1C,SAAQC,UAAU,QAAO,4BAA2B;AACpD,SAAQC,UAAU,QAAO,4BAA2B;AACpD,SAAQC,OAAO,QAAO,yBAAwB;AAE9C,MAAMC,cAAc,CAAC;;;AAGrB,EAAEV,MAAMW,IAAI,CAAC,kBAAkB;;;;;;;;;;;;;;AAc/B,EAAEX,MAAMW,IAAI,CAAC,SAAS;;4JAEsI,CAAC,CAACC,IAAI;AAEl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AC,+BAA+B,EAAEX,YAAY,EAAE;oBAAC8E,OAAOhB;gBAAG;YAC7E;YAEA,IAAIA,eAAenD,SAAS,UAAUmD,OAAOA,IAAIP,IAAI,KAAK,UAAU;gBAClE,MAAM,IAAI5C,MAAM,CAAC,mDAAmD,EAAE+D,kBAAkB,EAAE;oBACxFI,OAAOhB;gBACT;YACF;QACF;QAEA,kDAAkD;QAClD,IAAI1D,QAAQ2E,WAAWJ,iBAAiB;YACtC9E,KAAKkE,IAAI,CACP1F,MAAM2G,MAAM,CACV,CAAC;;;EAGT,CAAC;YAIG,OAAO;gBACL5E,QAAQ3B,iBAAiBgB,KAAK,CAACW,OAAO2E,OAAO,IAAI,CAAC;gBAClD1E,MAAMmE,QAAQnE,IAAI;gBAClBC,MAAM;YACR;QACF;QAEA,qCAAqC;QACrC,IAAIqE,iBAAiB;YACnB9E,KAAKkE,IAAI,CACP1F,MAAM2G,MAAM,CACV,CAAC;;+EAEoE,CAAC;YAG1E,OAAO;gBACL5E,QAAQ,MAAM1B,WAAWgG;gBACzBrE,MAAMqE;gBACNpE,MAAM;YACR;QACF;QAEA,0BAA0B;QAC1B,OAAO;YACLF,QAAQ3B,iBAAiBgB,KAAK,CAACW,OAAO2E,OAAO,IAAI,CAAC;YAClD1E,MAAMmE,QAAQnE,IAAI;YAClBC,MAAM;QACR;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/commands/typegen/generate.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\n\nimport {Flags} from '@oclif/core'\nimport {SanityCommand} from '@sanity/cli-core'\nimport {chalk, spinner} from '@sanity/cli-core/ux'\nimport {omit, once} from 'lodash-es'\n\nimport {runTypegenGenerate} from '../../actions/typegenGenerate.js'\nimport {runTypegenWatcher} from '../../actions/typegenWatch.js'\nimport {configDefinition, readConfig, type TypeGenConfig} from '../../readConfig.js'\nimport {TypegenWatchModeTrace, TypesGeneratedTrace} from '../../typegen.telemetry.js'\nimport {promiseWithResolvers} from '../../utils/promiseWithResolvers.js'\nimport {telemetry} from '../../utils/telemetryLogger.js'\n\nconst description = `Sanity TypeGen (Beta)\nThis command is currently in beta and may undergo significant changes. Feedback is welcome!\n\n${chalk.bold('Configuration:')}\nThis command can utilize configuration settings defined in a \\`sanity-typegen.json\\` file. These settings include:\n\n- \"path\": Specifies a glob pattern to locate your TypeScript or JavaScript files.\n Default: \"./src/**/*.{ts,tsx,js,jsx}\"\n\n- \"schema\": Defines the path to your Sanity schema file. This file should be generated using the \\`sanity schema extract\\` command.\n Default: \"schema.json\"\n\n- \"generates\": Indicates the path where the generated TypeScript type definitions will be saved.\n Default: \"./sanity.types.ts\"\n\nThe default configuration values listed above are used if not overridden in your \\`sanity-typegen.json\\` configuration file. To customize the behavior of the type generation, adjust these properties in the configuration file according to your project's needs.\n\n${chalk.bold('Note:')}\n- The \\`sanity schema extract\\` command is a prerequisite for extracting your Sanity Studio schema into a \\`schema.json\\` file, which is then used by the \\`sanity typegen generate\\` command to generate type definitions.\n- While this tool is in beta, we encourage you to experiment with these configurations and provide feedback to help improve its functionality and usability.`.trim()\n\n/**\n * @internal\n */\nexport class TypegenGenerateCommand extends SanityCommand<typeof TypegenGenerateCommand> {\n static override description = description\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: `Generate TypeScript type definitions from a Sanity Studio schema extracted using the \\`sanity schema extract\\` command.`,\n },\n ]\n\n static override flags = {\n 'config-path': Flags.string({\n description:\n '[Default: sanity-typegen.json] Specifies the path to the typegen configuration file. This file should be a JSON file that contains settings for the type generation process.',\n }),\n watch: Flags.boolean({\n description: '[Default: false] Run the typegen in watch mode',\n }),\n }\n\n public async run() {\n const {flags} = await this.parse(TypegenGenerateCommand)\n\n if (flags.watch) {\n await this.runWatcher()\n return\n }\n\n await this.runSingle()\n }\n\n private async getConfig(): Promise<{\n config: TypeGenConfig\n path?: string\n type: 'cli' | 'legacy'\n workDir: string\n }> {\n const spin = spinner({}).start('Loading config…')\n\n const {flags} = await this.parse(TypegenGenerateCommand)\n const rootDir = await this.getProjectRoot()\n const config = await this.getCliConfig()\n\n const configPath = flags['config-path']\n const workDir = rootDir.directory\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 instanceof Error && 'code' in err && err.code === 'ENOENT' && configPath) {\n throw new Error(`Typegen config file not found: ${configPath}`, {cause: err})\n }\n\n if (err instanceof Error && 'code' in err && 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?.typegen && hasLegacyConfig) {\n spin.warn(\n chalk.yellow(\n `You've specified typegen in your Sanity CLI config, but also have a typegen config.\n\n The config from the Sanity CLI config is used.\n `,\n ),\n )\n\n return {\n config: configDefinition.parse(config.typegen || {}),\n path: rootDir.path,\n type: 'cli',\n workDir,\n }\n }\n\n // we only have legacy typegen config\n if (hasLegacyConfig) {\n spin.warn(\n chalk.yellow(\n `The separate typegen config has been deprecated. Use \\`typegen\\` in the sanity CLI config instead.\n\n See: https://www.sanity.io/docs/help/configuring-typegen-in-sanity-cli-config`,\n ),\n )\n return {\n config: await readConfig(legacyConfigPath),\n path: legacyConfigPath,\n type: 'legacy',\n workDir,\n }\n }\n\n spin.succeed(`Config loaded from sanity.cli.ts`)\n\n // we only have cli config\n return {\n config: configDefinition.parse(config.typegen || {}),\n path: rootDir.path,\n type: 'cli',\n workDir,\n }\n }\n\n private async runSingle() {\n const trace = telemetry.trace(TypesGeneratedTrace)\n\n try {\n const {config: typegenConfig, type: typegenConfigMethod, workDir} = await this.getConfig()\n trace.start()\n\n const result = await runTypegenGenerate({\n config: typegenConfig,\n workDir,\n })\n\n const traceStats = omit(result, 'code', 'duration')\n\n trace.log({\n configMethod: typegenConfigMethod,\n configOverloadClientMethods: typegenConfig.overloadClientMethods,\n ...traceStats,\n })\n trace.complete()\n } catch (error) {\n trace.error(error as Error)\n trace.complete()\n\n this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {\n exit: 1,\n })\n }\n }\n\n private async runWatcher() {\n const trace = telemetry.trace(TypegenWatchModeTrace)\n\n try {\n const {config: typegenConfig, workDir} = await this.getConfig()\n trace.start()\n\n const {promise, resolve} = promiseWithResolvers()\n\n const typegenWatcher = runTypegenWatcher({\n config: typegenConfig,\n workDir,\n })\n\n const stop = once(async () => {\n process.off('SIGINT', stop)\n process.off('SIGTERM', stop)\n\n trace.log({\n step: 'stopped',\n ...typegenWatcher.getStats(),\n })\n\n await typegenWatcher.stop()\n resolve()\n })\n\n process.on('SIGINT', stop)\n process.on('SIGTERM', stop)\n\n await promise\n } catch (error) {\n trace.error(error as Error)\n trace.complete()\n\n this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {\n exit: 1,\n })\n }\n }\n}\n"],"names":["stat","Flags","SanityCommand","chalk","spinner","omit","once","runTypegenGenerate","runTypegenWatcher","configDefinition","readConfig","TypegenWatchModeTrace","TypesGeneratedTrace","promiseWithResolvers","telemetry","description","bold","trim","TypegenGenerateCommand","examples","command","flags","string","watch","boolean","run","parse","runWatcher","runSingle","getConfig","spin","start","rootDir","getProjectRoot","config","getCliConfig","configPath","workDir","directory","legacyConfigPath","hasLegacyConfig","file","isFile","err","Error","code","cause","typegen","warn","yellow","path","type","succeed","trace","typegenConfig","typegenConfigMethod","result","traceStats","log","configMethod","configOverloadClientMethods","overloadClientMethods","complete","error","message","exit","promise","resolve","typegenWatcher","stop","process","off","step","getStats","on"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AAErC,SAAQC,KAAK,QAAO,cAAa;AACjC,SAAQC,aAAa,QAAO,mBAAkB;AAC9C,SAAQC,KAAK,EAAEC,OAAO,QAAO,sBAAqB;AAClD,SAAQC,IAAI,EAAEC,IAAI,QAAO,YAAW;AAEpC,SAAQC,kBAAkB,QAAO,mCAAkC;AACnE,SAAQC,i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C,MAAM;YACR;QACF;IACF;AACF"}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,14 @@
1
+ import { BooleanFlag } from '@oclif/core/interfaces';
2
+ import { CustomOptions } from '@oclif/core/interfaces';
3
+ import { DefinedTelemetryTrace } from '@sanity/telemetry';
1
4
  import { ExprNode } from 'groq-js';
5
+ import { FSWatcher } from 'chokidar';
6
+ import { OptionFlag } from '@oclif/core/interfaces';
7
+ import { SanityCommand } from '@sanity/cli-core';
2
8
  import { SchemaType } from 'groq-js';
9
+ import { spinner } from '@sanity/cli-core/ux';
3
10
  import * as t from '@babel/types';
11
+ import { TelemetryLogger } from '@sanity/telemetry';
4
12
  import { TransformOptions } from '@babel/core';
5
13
  import { WorkerChannel } from '@sanity/worker-channels';
6
14
  import { WorkerChannelReporter } from '@sanity/worker-channels';
@@ -18,21 +26,9 @@ export declare const configDefinition: z.ZodObject<{
18
26
  formatGeneratedCode: z.ZodDefault<z.ZodBoolean>;
19
27
  generates: z.ZodDefault<z.ZodString>;
20
28
  overloadClientMethods: z.ZodDefault<z.ZodBoolean>;
21
- path: z.ZodDefault<z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString, "many">]>>;
29
+ path: z.ZodDefault<z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString>]>>;
22
30
  schema: z.ZodDefault<z.ZodString>;
23
- }, "strip", z.ZodTypeAny, {
24
- formatGeneratedCode: boolean;
25
- generates: string;
26
- overloadClientMethods: boolean;
27
- path: string | string[];
28
- schema: string;
29
- }, {
30
- formatGeneratedCode?: boolean | undefined;
31
- generates?: string | undefined;
32
- overloadClientMethods?: boolean | undefined;
33
- path?: string | string[] | undefined;
34
- schema?: string | undefined;
35
- }>;
31
+ }, z.core.$strip>;
36
32
 
37
33
  /**
38
34
  * A module containing queries that have been evaluated.
@@ -158,6 +154,24 @@ export declare interface GenerateTypesOptions {
158
154
  schemaPath?: string;
159
155
  }
160
156
 
157
+ /**
158
+ * Result from a single generation run.
159
+ * @internal
160
+ */
161
+ export declare interface GenerationResult {
162
+ code: string;
163
+ duration: number;
164
+ emptyUnionTypeNodesGenerated: number;
165
+ filesWithErrors: number;
166
+ outputSize: number;
167
+ queriesCount: number;
168
+ queryFilesCount: number;
169
+ schemaTypesCount: number;
170
+ typeNodesGenerated: number;
171
+ unknownTypeNodesGenerated: number;
172
+ unknownTypeNodesRatio: number;
173
+ }
174
+
161
175
  /**
162
176
  * Get a deeply nested property type from a complex type structure. Safely navigates
163
177
  * through nullable types (`T | null | undefined`) at each level, preserving the
@@ -387,6 +401,43 @@ export declare function readSchema(path: string): Promise<SchemaType>;
387
401
  */
388
402
  export declare function registerBabel(babelOptions?: TransformOptions): void;
389
403
 
404
+ /**
405
+ * Runs a single typegen generation.
406
+ *
407
+ * This is the programmatic API for generating TypeScript types from GROQ queries.
408
+ * It spawns a worker thread to perform the generation and displays progress via CLI spinners.
409
+ *
410
+ * @param options - Configuration options including typegen config and working directory
411
+ * @returns Generation result containing the generated code and statistics
412
+ */
413
+ export declare function runTypegenGenerate(options: RunTypegenOptions): Promise<GenerationResult>;
414
+
415
+ /**
416
+ * Options for running a single typegen generation.
417
+ * This is the programmatic API for one-off generation without file watching.
418
+ */
419
+ export declare interface RunTypegenOptions {
420
+ /** Typegen configuration */
421
+ config: TypeGenConfig;
422
+ /** Working directory (usually project root) */
423
+ workDir: string;
424
+ /** Optional spinner instance for progress display */
425
+ spin?: ReturnType<typeof spinner>;
426
+ /** Optional telemetry instance for tracking usage */
427
+ telemetry?: typeof telemetry;
428
+ }
429
+
430
+ /**
431
+ * Starts a file watcher that triggers typegen on changes.
432
+ * Watches both query files (via patterns) and the schema JSON file.
433
+ * Implements debouncing and concurrency control to prevent multiple generations.
434
+ */
435
+ export declare function runTypegenWatcher(options: RunTypegenOptions): {
436
+ getStats: () => WatcherStats;
437
+ stop: () => Promise<void>;
438
+ watcher: FSWatcher;
439
+ };
440
+
390
441
  /**
391
442
  * safeParseQuery parses a GROQ query string, but first attempts to extract any parameters used in slices. This method is _only_
392
443
  * intended for use in type generation where we don't actually execute the parsed AST on a dataset, and should not be used elsewhere.
@@ -397,6 +448,13 @@ export declare function safeParseQuery(query: string): ExprNode;
397
448
  /** Builds a tuple from elements, stopping at the first `never`. */
398
449
  declare type TakeUntilNever<T extends unknown[]> = T extends [infer H, ...infer Rest] ? [H] extends [never] ? [] : [H, ...TakeUntilNever<Rest>] : [];
399
450
 
451
+ /**
452
+ * TODO: Remove once we have a proper telemetry logger through the `@sanity/cli-core`
453
+ *
454
+ * This logger does nothing, except provide the interface to interact with
455
+ */
456
+ declare const telemetry: TelemetryLogger<unknown>;
457
+
400
458
  /**
401
459
  * Statistics from the query type evaluation process.
402
460
  * @public
@@ -427,6 +485,44 @@ export declare class TypeGenerator {
427
485
  }>;
428
486
  }
429
487
 
488
+ /**
489
+ * @internal
490
+ */
491
+ export declare class TypegenGenerateCommand extends SanityCommand<typeof TypegenGenerateCommand> {
492
+ static description: string;
493
+ static examples: {
494
+ command: string;
495
+ description: string;
496
+ }[];
497
+ static flags: {
498
+ 'config-path': OptionFlag<string | undefined, CustomOptions>;
499
+ watch: BooleanFlag<boolean>;
500
+ };
501
+ run(): Promise<void>;
502
+ private getConfig;
503
+ private runSingle;
504
+ private runWatcher;
505
+ }
506
+
507
+ /**
508
+ * @internal
509
+ */
510
+ export declare const TypegenWatchModeTrace: DefinedTelemetryTrace<TypegenWatchModeTraceAttributes, void>;
511
+
512
+ /**
513
+ * Attributes for typegen watch mode trace - tracks the start and stop of watch mode
514
+ * sessions with statistics about generation runs.
515
+ */
516
+ declare type TypegenWatchModeTraceAttributes = {
517
+ averageGenerationDuration: number;
518
+ generationFailedCount: number;
519
+ generationSuccessfulCount: number;
520
+ step: 'stopped';
521
+ watcherDuration: number;
522
+ } | {
523
+ step: 'started';
524
+ };
525
+
430
526
  export declare type TypegenWorkerChannel = WorkerChannel.Definition<{
431
527
  evaluatedModules: WorkerChannel.Stream<EvaluatedModule>;
432
528
  generatedQueryTypes: WorkerChannel.Event<{
@@ -456,4 +552,27 @@ export declare type TypegenWorkerChannel = WorkerChannel.Definition<{
456
552
  }>;
457
553
  }>;
458
554
 
555
+ /**
556
+ * @internal
557
+ */
558
+ export declare const TypesGeneratedTrace: DefinedTelemetryTrace<TypesGeneratedTraceAttributes, void>;
559
+
560
+ declare interface TypesGeneratedTraceAttributes {
561
+ configMethod: 'cli' | 'legacy';
562
+ configOverloadClientMethods: boolean;
563
+ emptyUnionTypeNodesGenerated: number;
564
+ filesWithErrors: number;
565
+ outputSize: number;
566
+ queriesCount: number;
567
+ queryFilesCount: number;
568
+ schemaTypesCount: number;
569
+ typeNodesGenerated: number;
570
+ unknownTypeNodesGenerated: number;
571
+ unknownTypeNodesRatio: number;
572
+ }
573
+
574
+ declare type WatcherStats = Omit<Extract<TypegenWatchModeTraceAttributes, {
575
+ step: 'stopped';
576
+ }>, 'step'>;
577
+
459
578
  export { }
@@ -24,7 +24,7 @@ import * as z from 'zod';
24
24
  return configDefinition.parseAsync(json);
25
25
  } catch (error) {
26
26
  if (error instanceof z.ZodError) {
27
- throw new Error(`Error in config file\n ${error.errors.map((err)=>err.message).join('\n')}`, {
27
+ throw new Error(`Error in config file\n ${error.issues.map((err)=>err.message).join('\n')}`, {
28
28
  cause: error
29
29
  });
30
30
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/readConfig.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport json5 from 'json5'\nimport * as z from 'zod'\n\n/**\n * @internal\n */\nexport const configDefinition = z.object({\n formatGeneratedCode: z.boolean().default(true),\n generates: z.string().default('./sanity.types.ts'),\n overloadClientMethods: z.boolean().default(true),\n path: z\n .string()\n .or(z.array(z.string()))\n .default([\n './src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',\n './app/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',\n './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n ]),\n schema: z.string().default('./schema.json'),\n})\n\nexport type TypeGenConfig = z.infer<typeof configDefinition>\n\n/**\n * @deprecated use TypeGenConfig\n */\nexport type CodegenConfig = TypeGenConfig\n\n/**\n * Read, parse and process a config file\n * @internal\n */\nexport async function readConfig(path: string): Promise<TypeGenConfig> {\n try {\n const content = await readFile(path, 'utf8')\n const json = json5.parse(content)\n return configDefinition.parseAsync(json)\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(\n `Error in config file\\n ${error.errors.map((err) => err.message).join('\\n')}`,\n {cause: error},\n )\n }\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return configDefinition.parse({})\n }\n\n throw error\n }\n}\n"],"names":["readFile","json5","z","configDefinition","object","formatGeneratedCode","boolean","default","generates","string","overloadClientMethods","path","or","array","schema","readConfig","content","json","parse","parseAsync","error","ZodError","Error","errors","map","err","message","join","cause","code"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAEzC,OAAOC,WAAW,QAAO;AACzB,YAAYC,OAAO,MAAK;AAExB;;CAEC,GACD,OAAO,MAAMC,mBAAmBD,EAAEE,MAAM,CAAC;IACvCC,qBAAqBH,EAAEI,OAAO,GAAGC,OAAO,CAAC;IACzCC,WAAWN,EAAEO,MAAM,GAAGF,OAAO,CAAC;IAC9BG,uBAAuBR,EAAEI,OAAO,GAAGC,OAAO,CAAC;IAC3CI,MAAMT,EACHO,MAAM,GACNG,EAAE,CAACV,EAAEW,KAAK,CAACX,EAAEO,MAAM,KACnBF,OAAO,CAAC;QACP;QACA;QACA;KACD;IACHO,QAAQZ,EAAEO,MAAM,GAAGF,OAAO,CAAC;AAC7B,GAAE;AASF;;;CAGC,GACD,OAAO,eAAeQ,WAAWJ,IAAY;IAC3C,IAAI;QACF,MAAMK,UAAU,MAAMhB,SAASW,MAAM;QACrC,MAAMM,OAAOhB,MAAMiB,KAAK,CAACF;QACzB,OAAOb,iBAAiBgB,UAAU,CAACF;IACrC,EAAE,OAAOG,OAAO;QACd,IAAIA,iBAAiBlB,EAAEmB,QAAQ,EAAE;YAC/B,MAAM,IAAIC,MACR,CAAC,uBAAuB,EAAEF,MAAMG,MAAM,CAACC,GAAG,CAAC,CAACC,MAAQA,IAAIC,OAAO,EAAEC,IAAI,CAAC,OAAO,EAC7E;gBAACC,OAAOR;YAAK;QAEjB;QACA,IAAI,OAAOA,UAAU,YAAYA,UAAU,QAAQ,UAAUA,SAASA,MAAMS,IAAI,KAAK,UAAU;YAC7F,OAAO1B,iBAAiBe,KAAK,CAAC,CAAC;QACjC;QAEA,MAAME;IACR;AACF"}
1
+ {"version":3,"sources":["../src/readConfig.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport json5 from 'json5'\nimport * as z from 'zod'\n\n/**\n * @internal\n */\nexport const configDefinition = z.object({\n formatGeneratedCode: z.boolean().default(true),\n generates: z.string().default('./sanity.types.ts'),\n overloadClientMethods: z.boolean().default(true),\n path: z\n .string()\n .or(z.array(z.string()))\n .default([\n './src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',\n './app/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',\n './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n ]),\n schema: z.string().default('./schema.json'),\n})\n\nexport type TypeGenConfig = z.infer<typeof configDefinition>\n\n/**\n * @deprecated use TypeGenConfig\n */\nexport type CodegenConfig = TypeGenConfig\n\n/**\n * Read, parse and process a config file\n * @internal\n */\nexport async function readConfig(path: string): Promise<TypeGenConfig> {\n try {\n const content = await readFile(path, 'utf8')\n const json = json5.parse(content)\n return configDefinition.parseAsync(json)\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(\n `Error in config file\\n ${error.issues.map((err) => err.message).join('\\n')}`,\n {cause: error},\n )\n }\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return configDefinition.parse({})\n }\n\n throw error\n }\n}\n"],"names":["readFile","json5","z","configDefinition","object","formatGeneratedCode","boolean","default","generates","string","overloadClientMethods","path","or","array","schema","readConfig","content","json","parse","parseAsync","error","ZodError","Error","issues","map","err","message","join","cause","code"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAEzC,OAAOC,WAAW,QAAO;AACzB,YAAYC,OAAO,MAAK;AAExB;;CAEC,GACD,OAAO,MAAMC,mBAAmBD,EAAEE,MAAM,CAAC;IACvCC,qBAAqBH,EAAEI,OAAO,GAAGC,OAAO,CAAC;IACzCC,WAAWN,EAAEO,MAAM,GAAGF,OAAO,CAAC;IAC9BG,uBAAuBR,EAAEI,OAAO,GAAGC,OAAO,CAAC;IAC3CI,MAAMT,EACHO,MAAM,GACNG,EAAE,CAACV,EAAEW,KAAK,CAACX,EAAEO,MAAM,KACnBF,OAAO,CAAC;QACP;QACA;QACA;KACD;IACHO,QAAQZ,EAAEO,MAAM,GAAGF,OAAO,CAAC;AAC7B,GAAE;AASF;;;CAGC,GACD,OAAO,eAAeQ,WAAWJ,IAAY;IAC3C,IAAI;QACF,MAAMK,UAAU,MAAMhB,SAASW,MAAM;QACrC,MAAMM,OAAOhB,MAAMiB,KAAK,CAACF;QACzB,OAAOb,iBAAiBgB,UAAU,CAACF;IACrC,EAAE,OAAOG,OAAO;QACd,IAAIA,iBAAiBlB,EAAEmB,QAAQ,EAAE;YAC/B,MAAM,IAAIC,MACR,CAAC,uBAAuB,EAAEF,MAAMG,MAAM,CAACC,GAAG,CAAC,CAACC,MAAQA,IAAIC,OAAO,EAAEC,IAAI,CAAC,OAAO,EAC7E;gBAACC,OAAOR;YAAK;QAEjB;QACA,IAAI,OAAOA,UAAU,YAAYA,UAAU,QAAQ,UAAUA,SAASA,MAAMS,IAAI,KAAK,UAAU;YAC7F,OAAO1B,iBAAiBe,KAAK,CAAC,CAAC;QACjC;QAEA,MAAME;IACR;AACF"}
@@ -0,0 +1,17 @@
1
+ import { defineTrace } from '@sanity/telemetry';
2
+ /**
3
+ * @internal
4
+ */ export const TypesGeneratedTrace = defineTrace({
5
+ description: 'Trace emitted when generating TypeScript types for queries',
6
+ name: 'Types Generated',
7
+ version: 0
8
+ });
9
+ /**
10
+ * @internal
11
+ */ export const TypegenWatchModeTrace = defineTrace({
12
+ description: 'Trace emitted when typegen watch mode is run',
13
+ name: 'Typegen Watch Mode Started',
14
+ version: 0
15
+ });
16
+
17
+ //# sourceMappingURL=typegen.telemetry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/typegen.telemetry.ts"],"sourcesContent":["import {defineTrace} from '@sanity/telemetry'\n\ninterface TypesGeneratedTraceAttributes {\n configMethod: 'cli' | 'legacy'\n configOverloadClientMethods: boolean\n emptyUnionTypeNodesGenerated: number\n filesWithErrors: number\n outputSize: number\n queriesCount: number\n queryFilesCount: number\n schemaTypesCount: number\n typeNodesGenerated: number\n unknownTypeNodesGenerated: number\n unknownTypeNodesRatio: number\n}\n\n/**\n * @internal\n */\nexport const TypesGeneratedTrace = defineTrace<TypesGeneratedTraceAttributes>({\n description: 'Trace emitted when generating TypeScript types for queries',\n name: 'Types Generated',\n version: 0,\n})\n\n/**\n * Attributes for typegen watch mode trace - tracks the start and stop of watch mode\n * sessions with statistics about generation runs.\n */\nexport type TypegenWatchModeTraceAttributes =\n | {\n averageGenerationDuration: number\n generationFailedCount: number\n generationSuccessfulCount: number\n step: 'stopped'\n watcherDuration: number\n }\n | {\n step: 'started'\n }\n\n/**\n * @internal\n */\nexport const TypegenWatchModeTrace = defineTrace<TypegenWatchModeTraceAttributes>({\n description: 'Trace emitted when typegen watch mode is run',\n name: 'Typegen Watch Mode Started',\n version: 0,\n})\n"],"names":["defineTrace","TypesGeneratedTrace","description","name","version","TypegenWatchModeTrace"],"mappings":"AAAA,SAAQA,WAAW,QAAO,oBAAmB;AAgB7C;;CAEC,GACD,OAAO,MAAMC,sBAAsBD,YAA2C;IAC5EE,aAAa;IACbC,MAAM;IACNC,SAAS;AACX,GAAE;AAkBF;;CAEC,GACD,OAAO,MAAMC,wBAAwBL,YAA6C;IAChFE,aAAa;IACbC,MAAM;IACNC,SAAS;AACX,GAAE"}
@@ -0,0 +1,16 @@
1
+ export const promiseWithResolvers = // @ts-expect-error TODO: replace with `Promise.withResolvers()` once it lands in node
2
+ Promise.withResolvers?.bind(Promise) || function promiseWithResolvers() {
3
+ let resolve;
4
+ let reject;
5
+ const promise = new Promise((res, rej)=>{
6
+ resolve = res;
7
+ reject = rej;
8
+ });
9
+ return {
10
+ promise,
11
+ reject,
12
+ resolve
13
+ };
14
+ };
15
+
16
+ //# sourceMappingURL=promiseWithResolvers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utils/promiseWithResolvers.ts"],"sourcesContent":["export const promiseWithResolvers =\n // @ts-expect-error TODO: replace with `Promise.withResolvers()` once it lands in node\n Promise.withResolvers?.bind(Promise) ||\n function promiseWithResolvers<T>() {\n let resolve!: (t: T) => void\n let reject!: (err: unknown) => void\n const promise = new Promise<T>((res, rej) => {\n resolve = res\n reject = rej\n })\n return {promise, reject, resolve}\n }\n"],"names":["promiseWithResolvers","Promise","withResolvers","bind","resolve","reject","promise","res","rej"],"mappings":"AAAA,OAAO,MAAMA,uBACX,sFAAsF;AACtFC,QAAQC,aAAa,EAAEC,KAAKF,YAC5B,SAASD;IACP,IAAII;IACJ,IAAIC;IACJ,MAAMC,UAAU,IAAIL,QAAW,CAACM,KAAKC;QACnCJ,UAAUG;QACVF,SAASG;IACX;IACA,OAAO;QAACF;QAASD;QAAQD;IAAO;AAClC,EAAC"}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * TODO: Remove once we have a proper telemetry logger through the `@sanity/cli-core`
3
+ *
4
+ * This logger does nothing, except provide the interface to interact with
5
+ */ import { createBatchedStore, createSessionId } from '@sanity/telemetry';
6
+ const session = createSessionId();
7
+ const store = createBatchedStore(session, {
8
+ async resolveConsent () {
9
+ return {
10
+ status: 'denied'
11
+ };
12
+ },
13
+ sendEvents: async ()=>{}
14
+ });
15
+ export const telemetry = store.logger;
16
+
17
+ //# sourceMappingURL=telemetryLogger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utils/telemetryLogger.ts"],"sourcesContent":["/**\n * TODO: Remove once we have a proper telemetry logger through the `@sanity/cli-core`\n *\n * This logger does nothing, except provide the interface to interact with\n */\n\nimport {createBatchedStore, createSessionId} from '@sanity/telemetry'\n\nconst session = createSessionId()\nconst store = createBatchedStore(session, {\n async resolveConsent() {\n return {status: 'denied'}\n },\n sendEvents: async () => {},\n})\n\nexport const telemetry = store.logger\n"],"names":["createBatchedStore","createSessionId","session","store","resolveConsent","status","sendEvents","telemetry","logger"],"mappings":"AAAA;;;;CAIC,GAED,SAAQA,kBAAkB,EAAEC,eAAe,QAAO,oBAAmB;AAErE,MAAMC,UAAUD;AAChB,MAAME,QAAQH,mBAAmBE,SAAS;IACxC,MAAME;QACJ,OAAO;YAACC,QAAQ;QAAQ;IAC1B;IACAC,YAAY,WAAa;AAC3B;AAEA,OAAO,MAAMC,YAAYJ,MAAMK,MAAM,CAAA"}
@@ -0,0 +1,67 @@
1
+ import { spawn } from 'node:child_process';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { once } from 'lodash-es';
5
+ const BIN = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../bin/run.js');
6
+ const isAssertionError = (e)=>e instanceof Error && e.name === 'AssertionError';
7
+ export async function testLongRunning(command, opts) {
8
+ const { cwd = process.cwd(), expect: assertion, interval = 150, timeout = 20_000 } = opts;
9
+ let stderr = '', stdout = '';
10
+ // spawn command in child process
11
+ const child = spawn('node', [
12
+ BIN,
13
+ ...command
14
+ ], {
15
+ cwd,
16
+ env: {
17
+ ...process.env,
18
+ NO_COLOR: '1'
19
+ },
20
+ stdio: [
21
+ 'pipe',
22
+ 'pipe',
23
+ 'pipe'
24
+ ]
25
+ });
26
+ // track err and out
27
+ child.stdout?.on('data', (d)=>stdout += d);
28
+ child.stderr?.on('data', (d)=>stderr += d);
29
+ const kill = once(()=>child.kill('SIGTERM'));
30
+ // track errors from the child process
31
+ let exitError = null;
32
+ child.on('exit', (code)=>{
33
+ if (code === 0) return;
34
+ exitError = new Error(`Process exited with code ${code}\nstderr: ${stderr}`);
35
+ });
36
+ child.on('error', (e)=>{
37
+ exitError = e;
38
+ });
39
+ // assert once every interval until expectation met, error or timeout
40
+ const start = Date.now();
41
+ async function assertExpectation() {
42
+ if (exitError) throw exitError;
43
+ try {
44
+ await assertion({
45
+ stderr,
46
+ stdout
47
+ });
48
+ return {
49
+ stderr,
50
+ stdout
51
+ };
52
+ } catch (e) {
53
+ if (!isAssertionError(e)) throw e;
54
+ if (Date.now() - start > timeout) throw e;
55
+ return new Promise((resolve)=>{
56
+ setTimeout(()=>resolve(assertExpectation()), interval);
57
+ });
58
+ }
59
+ }
60
+ try {
61
+ return await assertExpectation();
62
+ } finally{
63
+ kill();
64
+ }
65
+ }
66
+
67
+ //# sourceMappingURL=testLongRunning.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/utils/test/testLongRunning.ts"],"sourcesContent":["import {spawn} from 'node:child_process'\nimport path from 'node:path'\nimport {fileURLToPath} from 'node:url'\n\nimport {once} from 'lodash-es'\n\nconst BIN = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../bin/run.js')\n\ninterface Options {\n expect: (o: {stderr: string; stdout: string}) => Promise<void> | void\n\n cwd?: string\n interval?: number\n timeout?: number\n}\n\nconst isAssertionError = (e: unknown) => e instanceof Error && e.name === 'AssertionError'\n\nexport async function testLongRunning(\n command: string[],\n opts: Options,\n): Promise<{stderr: string; stdout: string}> {\n const {cwd = process.cwd(), expect: assertion, interval = 150, timeout = 20_000} = opts\n let stderr = '',\n stdout = ''\n\n // spawn command in child process\n const child = spawn('node', [BIN, ...command], {\n cwd,\n env: {...process.env, NO_COLOR: '1'},\n stdio: ['pipe', 'pipe', 'pipe'],\n })\n\n // track err and out\n child.stdout?.on('data', (d) => (stdout += d))\n child.stderr?.on('data', (d) => (stderr += d))\n\n const kill = once(() => child.kill('SIGTERM'))\n\n // track errors from the child process\n let exitError: Error | null = null\n child.on('exit', (code) => {\n if (code === 0) return\n exitError = new Error(`Process exited with code ${code}\\nstderr: ${stderr}`)\n })\n\n child.on('error', (e) => {\n exitError = e\n })\n\n // assert once every interval until expectation met, error or timeout\n const start = Date.now()\n async function assertExpectation(): Promise<{stderr: string; stdout: string}> {\n if (exitError) throw exitError\n\n try {\n await assertion({stderr, stdout})\n return {stderr, stdout}\n } catch (e) {\n if (!isAssertionError(e)) throw e\n if (Date.now() - start > timeout) throw e\n\n return new Promise((resolve) => {\n setTimeout(() => resolve(assertExpectation()), interval)\n })\n }\n }\n\n try {\n return await assertExpectation()\n } finally {\n kill()\n }\n}\n"],"names":["spawn","path","fileURLToPath","once","BIN","resolve","dirname","url","isAssertionError","e","Error","name","testLongRunning","command","opts","cwd","process","expect","assertion","interval","timeout","stderr","stdout","child","env","NO_COLOR","stdio","on","d","kill","exitError","code","start","Date","now","assertExpectation","Promise","setTimeout"],"mappings":"AAAA,SAAQA,KAAK,QAAO,qBAAoB;AACxC,OAAOC,UAAU,YAAW;AAC5B,SAAQC,aAAa,QAAO,WAAU;AAEtC,SAAQC,IAAI,QAAO,YAAW;AAE9B,MAAMC,MAAMH,KAAKI,OAAO,CAACJ,KAAKK,OAAO,CAACJ,cAAc,YAAYK,GAAG,IAAI;AAUvE,MAAMC,mBAAmB,CAACC,IAAeA,aAAaC,SAASD,EAAEE,IAAI,KAAK;AAE1E,OAAO,eAAeC,gBACpBC,OAAiB,EACjBC,IAAa;IAEb,MAAM,EAACC,MAAMC,QAAQD,GAAG,EAAE,EAAEE,QAAQC,SAAS,EAAEC,WAAW,GAAG,EAAEC,UAAU,MAAM,EAAC,GAAGN;IACnF,IAAIO,SAAS,IACXC,SAAS;IAEX,iCAAiC;IACjC,MAAMC,QAAQvB,MAAM,QAAQ;QAACI;WAAQS;KAAQ,EAAE;QAC7CE;QACAS,KAAK;YAAC,GAAGR,QAAQQ,GAAG;YAAEC,UAAU;QAAG;QACnCC,OAAO;YAAC;YAAQ;YAAQ;SAAO;IACjC;IAEA,oBAAoB;IACpBH,MAAMD,MAAM,EAAEK,GAAG,QAAQ,CAACC,IAAON,UAAUM;IAC3CL,MAAMF,MAAM,EAAEM,GAAG,QAAQ,CAACC,IAAOP,UAAUO;IAE3C,MAAMC,OAAO1B,KAAK,IAAMoB,MAAMM,IAAI,CAAC;IAEnC,sCAAsC;IACtC,IAAIC,YAA0B;IAC9BP,MAAMI,EAAE,CAAC,QAAQ,CAACI;QAChB,IAAIA,SAAS,GAAG;QAChBD,YAAY,IAAIpB,MAAM,CAAC,yBAAyB,EAAEqB,KAAK,UAAU,EAAEV,QAAQ;IAC7E;IAEAE,MAAMI,EAAE,CAAC,SAAS,CAAClB;QACjBqB,YAAYrB;IACd;IAEA,qEAAqE;IACrE,MAAMuB,QAAQC,KAAKC,GAAG;IACtB,eAAeC;QACb,IAAIL,WAAW,MAAMA;QAErB,IAAI;YACF,MAAMZ,UAAU;gBAACG;gBAAQC;YAAM;YAC/B,OAAO;gBAACD;gBAAQC;YAAM;QACxB,EAAE,OAAOb,GAAG;YACV,IAAI,CAACD,iBAAiBC,IAAI,MAAMA;YAChC,IAAIwB,KAAKC,GAAG,KAAKF,QAAQZ,SAAS,MAAMX;YAExC,OAAO,IAAI2B,QAAQ,CAAC/B;gBAClBgC,WAAW,IAAMhC,QAAQ8B,sBAAsBhB;YACjD;QACF;IACF;IAEA,IAAI;QACF,OAAO,MAAMgB;IACf,SAAU;QACRN;IACF;AACF"}
@@ -0,0 +1,12 @@
1
+ export default {
2
+ bin: 'sanity',
3
+ commands: './dist/commands',
4
+ dirname: 'sanity-typegen',
5
+ plugins: ['@oclif/plugin-help'],
6
+ topics: {
7
+ typegen: {
8
+ description: 'Beta: Generate TypeScript types for schema and GROQ',
9
+ },
10
+ },
11
+ topicSeparator: ' ',
12
+ }
@@ -3,7 +3,7 @@
3
3
  "typegen:generate": {
4
4
  "aliases": [],
5
5
  "args": {},
6
- "description": "Sanity TypeGen (Beta)\nThis command is currently in beta and may undergo significant changes. Feedback is welcome!\n\nConfiguration:\nThis command can utilize configuration settings defined in a `sanity-typegen.json` file. These settings include:\n\n- \"path\": Specifies a glob pattern to locate your TypeScript or JavaScript files.\n Default: \"./src/**/*.{ts,tsx,js,jsx}\"\n\n- \"schema\": Defines the path to your Sanity schema file. This file should be generated using the `sanity schema extract` command.\n Default: \"schema.json\"\n\n- \"generates\": Indicates the path where the generated TypeScript type definitions will be saved.\n Default: \"./sanity.types.ts\"\n\nThe default configuration values listed above are used if not overridden in your `sanity-typegen.json` configuration file. To customize the behavior of the type generation, adjust these properties in the configuration file according to your project's needs.\n\nNote:\n- The `sanity schema extract` command is a prerequisite for extracting your Sanity Studio schema into a `schema.json` file, which is then used by the `sanity typegen generate` command to generate type definitions.\n- While this tool is in beta, we encourage you to experiment with these configurations and provide feedback to help improve its functionality and usability.",
6
+ "description": "Sanity TypeGen (Beta)\nThis command is currently in beta and may undergo significant changes. Feedback is welcome!\n\n\u001b[1mConfiguration:\u001b[22m\nThis command can utilize configuration settings defined in a `sanity-typegen.json` file. These settings include:\n\n- \"path\": Specifies a glob pattern to locate your TypeScript or JavaScript files.\n Default: \"./src/**/*.{ts,tsx,js,jsx}\"\n\n- \"schema\": Defines the path to your Sanity schema file. This file should be generated using the `sanity schema extract` command.\n Default: \"schema.json\"\n\n- \"generates\": Indicates the path where the generated TypeScript type definitions will be saved.\n Default: \"./sanity.types.ts\"\n\nThe default configuration values listed above are used if not overridden in your `sanity-typegen.json` configuration file. To customize the behavior of the type generation, adjust these properties in the configuration file according to your project's needs.\n\n\u001b[1mNote:\u001b[22m\n- The `sanity schema extract` command is a prerequisite for extracting your Sanity Studio schema into a `schema.json` file, which is then used by the `sanity typegen generate` command to generate type definitions.\n- While this tool is in beta, we encourage you to experiment with these configurations and provide feedback to help improve its functionality and usability.",
7
7
  "examples": [
8
8
  {
9
9
  "command": "<%= config.bin %> <%= command.id %>",
@@ -17,6 +17,12 @@
17
17
  "hasDynamicHelp": false,
18
18
  "multiple": false,
19
19
  "type": "option"
20
+ },
21
+ "watch": {
22
+ "description": "[Default: false] Run the typegen in watch mode",
23
+ "name": "watch",
24
+ "allowNo": false,
25
+ "type": "boolean"
20
26
  }
21
27
  },
22
28
  "hasDynamicHelp": false,
@@ -35,5 +41,5 @@
35
41
  ]
36
42
  }
37
43
  },
38
- "version": "5.7.0"
44
+ "version": "5.7.2-watch-mode"
39
45
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/codegen",
3
- "version": "5.7.0",
3
+ "version": "5.7.2-watch-mode",
4
4
  "description": "Codegen toolkit for Sanity.io",
5
5
  "keywords": [
6
6
  "sanity",
@@ -24,12 +24,13 @@
24
24
  "type": "module",
25
25
  "exports": {
26
26
  ".": {
27
+ "types": "./dist/index.d.ts",
27
28
  "source": "./src/_exports/index.ts",
28
- "default": "./dist/index.js"
29
+ "default": "./dist/_exports/index.js"
29
30
  },
30
31
  "./package.json": "./package.json"
31
32
  },
32
- "main": "./dist/index.cjs",
33
+ "main": "./dist/_exports/index.js",
33
34
  "types": "./dist/index.d.ts",
34
35
  "bin": {
35
36
  "sanity-typegen": "./bin/run.js"
@@ -38,6 +39,7 @@
38
39
  "dist",
39
40
  "bin",
40
41
  "oclif.manifest.json",
42
+ "oclif.config.js",
41
43
  "babel.config.json"
42
44
  ],
43
45
  "dependencies": {
@@ -52,16 +54,19 @@
52
54
  "@oclif/core": "^4.8.0",
53
55
  "@oclif/plugin-help": "^6.2.36",
54
56
  "@sanity/cli-core": "^0.1.0-alpha.8",
57
+ "@sanity/telemetry": "^0.8.1",
55
58
  "@sanity/worker-channels": "^1.1.0",
56
59
  "debug": "^4.4.3",
57
60
  "globby": "^11.1.0",
58
61
  "groq": "^5.2.0",
59
62
  "groq-js": "^1.25.0",
60
63
  "json5": "^2.2.3",
64
+ "lodash-es": "^4.17.23",
61
65
  "prettier": "^3.7.4",
62
66
  "reselect": "^5.1.1",
63
67
  "tsconfig-paths": "^4.2.0",
64
- "zod": "^3.25.76"
68
+ "zod": "^4.3.6",
69
+ "chokidar": "^3.6.0"
65
70
  },
66
71
  "devDependencies": {
67
72
  "@eslint/compat": "^2.0.1",
@@ -76,9 +81,9 @@
76
81
  "@types/babel__register": "^7.17.3",
77
82
  "@types/babel__traverse": "^7.28.0",
78
83
  "@types/debug": "^4.1.12",
84
+ "@types/lodash-es": "^4.17.12",
79
85
  "@types/node": "^20.19.28",
80
86
  "@vitest/coverage-istanbul": "^4.0.17",
81
- "chokidar": "^5.0.0",
82
87
  "eslint": "^9.39.2",
83
88
  "husky": "^9.1.7",
84
89
  "lint-staged": "^16.2.7",