@sanity/codegen 7.0.3 → 8.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_exports/index.d.ts +39 -25
- package/dist/_exports/index.js +0 -1
- package/dist/_exports/index.js.map +1 -1
- package/dist/actions/streamProcessor.js +40 -43
- package/dist/actions/streamProcessor.js.map +1 -1
- package/dist/actions/typegenGenerate.js +3 -3
- package/dist/actions/typegenGenerate.js.map +1 -1
- package/dist/actions/types.js +1 -1
- package/dist/actions/types.js.map +1 -1
- package/dist/safeParseQuery.js.map +1 -1
- package/dist/utils/debug.js +2 -2
- package/dist/utils/debug.js.map +1 -1
- package/package.json +3 -11
- package/dist/commands/typegen/generate.js +0 -185
- package/dist/commands/typegen/generate.js.map +0 -1
- package/dist/utils/count.js +0 -6
- package/dist/utils/count.js.map +0 -1
- package/dist/utils/percent.js +0 -8
- package/dist/utils/percent.js.map +0 -1
- package/dist/utils/test/testLongRunning.js +0 -67
- package/dist/utils/test/testLongRunning.js.map +0 -1
- package/oclif.config.js +0 -11
- package/oclif.manifest.json +0 -45
package/dist/_exports/index.d.ts
CHANGED
|
@@ -1,12 +1,7 @@
|
|
|
1
|
-
import {BooleanFlag} from '@oclif/core/interfaces'
|
|
2
|
-
import {CustomOptions} from '@oclif/core/interfaces'
|
|
3
1
|
import {DefinedTelemetryTrace} from '@sanity/telemetry'
|
|
4
2
|
import {ExprNode} from 'groq-js'
|
|
5
3
|
import {FSWatcher} from 'chokidar'
|
|
6
|
-
import {OptionFlag} from '@oclif/core/interfaces'
|
|
7
|
-
import {SanityCommand} from '@sanity/cli-core'
|
|
8
4
|
import {SchemaType} from 'groq-js'
|
|
9
|
-
import {spinner} from '@sanity/cli-core/ux'
|
|
10
5
|
import * as t from '@babel/types'
|
|
11
6
|
import {TransformOptions} from '@babel/core'
|
|
12
7
|
import {WorkerChannel} from '@sanity/worker-channels'
|
|
@@ -387,7 +382,7 @@ export declare function registerBabel(babelOptions?: TransformOptions): void
|
|
|
387
382
|
* Runs a single typegen generation.
|
|
388
383
|
*
|
|
389
384
|
* This is the programmatic API for generating TypeScript types from GROQ queries.
|
|
390
|
-
* It spawns a worker thread to perform the generation and
|
|
385
|
+
* It spawns a worker thread to perform the generation and reports progress via the optional `onProgress` callback.
|
|
391
386
|
*
|
|
392
387
|
* @param options - Configuration options including typegen config and working directory
|
|
393
388
|
* @returns Generation result containing the generated code and statistics
|
|
@@ -397,7 +392,6 @@ export declare function runTypegenGenerate(options: RunTypegenOptions): Promise<
|
|
|
397
392
|
|
|
398
393
|
/**
|
|
399
394
|
* Options for running a single typegen generation.
|
|
400
|
-
* This is the programmatic API for one-off generation without file watching.
|
|
401
395
|
* @public
|
|
402
396
|
*/
|
|
403
397
|
export declare interface RunTypegenOptions {
|
|
@@ -405,8 +399,8 @@ export declare interface RunTypegenOptions {
|
|
|
405
399
|
workDir: string
|
|
406
400
|
/** Typegen configuration */
|
|
407
401
|
config?: Partial<TypeGenConfig>
|
|
408
|
-
/** Optional
|
|
409
|
-
|
|
402
|
+
/** Optional progress reporter. Called synchronously as generation proceeds. */
|
|
403
|
+
onProgress?: (event: TypegenProgressEvent) => void
|
|
410
404
|
}
|
|
411
405
|
|
|
412
406
|
/**
|
|
@@ -467,23 +461,43 @@ export declare class TypeGenerator {
|
|
|
467
461
|
}
|
|
468
462
|
|
|
469
463
|
/**
|
|
470
|
-
*
|
|
464
|
+
* A progress event emitted during a single typegen run.
|
|
465
|
+
* Consumers (e.g. the Sanity CLI) render these; the library performs no terminal output.
|
|
466
|
+
* @public
|
|
471
467
|
*/
|
|
472
|
-
export declare
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
468
|
+
export declare type TypegenProgressEvent =
|
|
469
|
+
| {
|
|
470
|
+
type: 'schemaLoaded'
|
|
471
|
+
}
|
|
472
|
+
| {
|
|
473
|
+
type: 'typegenStarted'
|
|
474
|
+
expectedFileCount: number
|
|
475
|
+
}
|
|
476
|
+
| {
|
|
477
|
+
type: 'schemaTypesGenerated'
|
|
478
|
+
schemaTypesCount: number
|
|
479
|
+
}
|
|
480
|
+
| {
|
|
481
|
+
type: 'moduleEvaluated'
|
|
482
|
+
evaluatedFiles: number
|
|
483
|
+
expectedFileCount: number
|
|
484
|
+
queriesCount: number
|
|
485
|
+
queryFilesCount: number
|
|
486
|
+
errors: string[]
|
|
487
|
+
}
|
|
488
|
+
| {
|
|
489
|
+
type: 'formatting'
|
|
490
|
+
formatterName: string
|
|
491
|
+
}
|
|
492
|
+
| {
|
|
493
|
+
type: 'formatFailed'
|
|
494
|
+
formatterName: string
|
|
495
|
+
message: string
|
|
496
|
+
}
|
|
497
|
+
| {
|
|
498
|
+
type: 'complete'
|
|
499
|
+
result: GenerationResult
|
|
500
|
+
}
|
|
487
501
|
|
|
488
502
|
/** @public */
|
|
489
503
|
export declare const TypegenWatchModeTrace: DefinedTelemetryTrace<
|
package/dist/_exports/index.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
export { runTypegenGenerate } from '../actions/typegenGenerate.js';
|
|
2
2
|
export { runTypegenWatcher } from '../actions/typegenWatch.js';
|
|
3
|
-
export { TypegenGenerateCommand } from '../commands/typegen/generate.js';
|
|
4
3
|
export { configDefinition, readConfig } from '../readConfig.js';
|
|
5
4
|
export { readSchema } from '../readSchema.js';
|
|
6
5
|
export { safeParseQuery } from '../safeParseQuery.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/_exports/index.ts"],"sourcesContent":["export {runTypegenGenerate} from '../actions/typegenGenerate.js'\nexport {runTypegenWatcher} from '../actions/typegenWatch.js'\nexport {type GenerationResult
|
|
1
|
+
{"version":3,"sources":["../../src/_exports/index.ts"],"sourcesContent":["export {runTypegenGenerate} from '../actions/typegenGenerate.js'\nexport {runTypegenWatcher} from '../actions/typegenWatch.js'\nexport {\n type GenerationResult,\n type RunTypegenOptions,\n type TypegenProgressEvent,\n} from '../actions/types.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","configDefinition","readConfig","readSchema","safeParseQuery","TypegenWatchModeTrace","TypesGeneratedTrace","findQueriesInPath","findQueriesInSource","getResolver","registerBabel","TypeGenerator","QueryExtractionError"],"mappings":"AAAA,SAAQA,kBAAkB,QAAO,gCAA+B;AAChE,SAAQC,iBAAiB,QAAO,6BAA4B;AAM5D,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"}
|
|
@@ -1,33 +1,33 @@
|
|
|
1
1
|
import { writeFile } from 'node:fs/promises';
|
|
2
|
-
import { spinner } from '@sanity/cli-core/ux';
|
|
3
|
-
import { count } from '../utils/count.js';
|
|
4
2
|
import { debug } from '../utils/debug.js';
|
|
5
|
-
import { formatPath } from '../utils/formatPath.js';
|
|
6
3
|
import { getMessage } from '../utils/getMessage.js';
|
|
7
|
-
import { percent } from '../utils/percent.js';
|
|
8
4
|
import { defineFormatter } from '../utils/resolveFormatter.js';
|
|
9
5
|
import { generatedFileWarning } from './generatedFileWarning.js';
|
|
6
|
+
const noopProgress = (_event)=>{};
|
|
10
7
|
/**
|
|
11
8
|
* Processes the event stream from a typegen worker thread.
|
|
12
9
|
*
|
|
13
|
-
*
|
|
14
|
-
* writes
|
|
15
|
-
|
|
16
|
-
* @param receiver - Worker channel receiver for typegen events
|
|
17
|
-
* @param options - Typegen configuration options
|
|
18
|
-
* @returns Generation result containing the generated code and statistics
|
|
19
|
-
*/ export async function processTypegenWorkerStream(receiver, options) {
|
|
10
|
+
* Consumes worker channel events, reports progress via `onProgress`,
|
|
11
|
+
* writes generated types to disk, and optionally formats them.
|
|
12
|
+
*/ export async function processTypegenWorkerStream(receiver, options, onProgress = noopProgress) {
|
|
20
13
|
const start = Date.now();
|
|
21
|
-
const { formatGeneratedCode, generates
|
|
22
|
-
const spin = spinner().start(`Loading schema…`);
|
|
14
|
+
const { formatGeneratedCode, generates } = options;
|
|
23
15
|
try {
|
|
24
16
|
await receiver.event.loadedSchema();
|
|
25
|
-
|
|
26
|
-
|
|
17
|
+
onProgress({
|
|
18
|
+
type: 'schemaLoaded'
|
|
19
|
+
});
|
|
27
20
|
const { expectedFileCount } = await receiver.event.typegenStarted();
|
|
21
|
+
onProgress({
|
|
22
|
+
expectedFileCount,
|
|
23
|
+
type: 'typegenStarted'
|
|
24
|
+
});
|
|
28
25
|
const { schemaTypeDeclarations } = await receiver.event.generatedSchemaTypes();
|
|
29
26
|
const schemaTypesCount = schemaTypeDeclarations.length;
|
|
30
|
-
|
|
27
|
+
onProgress({
|
|
28
|
+
schemaTypesCount,
|
|
29
|
+
type: 'schemaTypesGenerated'
|
|
30
|
+
});
|
|
31
31
|
let queriesCount = 0;
|
|
32
32
|
let evaluatedFiles = 0;
|
|
33
33
|
let filesWithErrors = 0;
|
|
@@ -45,40 +45,42 @@ import { generatedFileWarning } from './generatedFileWarning.js';
|
|
|
45
45
|
unknownTypeNodesGenerated += stats.unknownTypes;
|
|
46
46
|
emptyUnionTypeNodesGenerated += stats.emptyUnions;
|
|
47
47
|
}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
48
|
+
onProgress({
|
|
49
|
+
errors: errors.map((error)=>getMessage(error)),
|
|
50
|
+
evaluatedFiles,
|
|
51
|
+
expectedFileCount,
|
|
52
|
+
queriesCount,
|
|
53
|
+
queryFilesCount,
|
|
54
|
+
type: 'moduleEvaluated'
|
|
55
|
+
});
|
|
55
56
|
}
|
|
56
57
|
const result = await receiver.event.typegenComplete();
|
|
57
58
|
const code = `${generatedFileWarning}${result.code}`;
|
|
58
59
|
await writeFile(generates, code);
|
|
59
|
-
let formattingError = false;
|
|
60
|
-
let formatterName;
|
|
61
60
|
if (formatGeneratedCode !== false) {
|
|
62
61
|
const formatter = defineFormatter(formatGeneratedCode);
|
|
63
62
|
if (formatter) {
|
|
64
|
-
formatterName = formatter.name;
|
|
65
63
|
try {
|
|
66
64
|
const { format } = await formatter.resolve();
|
|
67
65
|
if (format) {
|
|
68
|
-
|
|
66
|
+
onProgress({
|
|
67
|
+
formatterName: formatter.name,
|
|
68
|
+
type: 'formatting'
|
|
69
|
+
});
|
|
69
70
|
const formattedCode = await format(generates, code);
|
|
70
71
|
await writeFile(generates, formattedCode);
|
|
71
72
|
}
|
|
72
73
|
} catch (err) {
|
|
73
|
-
|
|
74
|
-
|
|
74
|
+
onProgress({
|
|
75
|
+
formatterName: formatter.name,
|
|
76
|
+
message: getMessage(err),
|
|
77
|
+
type: 'formatFailed'
|
|
78
|
+
});
|
|
75
79
|
}
|
|
76
80
|
}
|
|
77
81
|
}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
}
|
|
81
|
-
const stats = {
|
|
82
|
+
const generationResult = {
|
|
83
|
+
code,
|
|
82
84
|
duration: Date.now() - start,
|
|
83
85
|
emptyUnionTypeNodesGenerated,
|
|
84
86
|
filesWithErrors,
|
|
@@ -90,17 +92,12 @@ import { generatedFileWarning } from './generatedFileWarning.js';
|
|
|
90
92
|
unknownTypeNodesGenerated,
|
|
91
93
|
unknownTypeNodesRatio: typeNodesGenerated > 0 ? unknownTypeNodesGenerated / typeNodesGenerated : 0
|
|
92
94
|
};
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
return {
|
|
99
|
-
...stats,
|
|
100
|
-
code
|
|
101
|
-
};
|
|
95
|
+
onProgress({
|
|
96
|
+
result: generationResult,
|
|
97
|
+
type: 'complete'
|
|
98
|
+
});
|
|
99
|
+
return generationResult;
|
|
102
100
|
} catch (err) {
|
|
103
|
-
spin.fail();
|
|
104
101
|
debug('error generating types', err);
|
|
105
102
|
throw err;
|
|
106
103
|
} finally{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/actions/streamProcessor.ts"],"sourcesContent":["import {writeFile} from 'node:fs/promises'\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../../src/actions/streamProcessor.ts"],"sourcesContent":["import {writeFile} from 'node:fs/promises'\n\nimport {WorkerChannelReceiver} from '@sanity/worker-channels'\n\nimport {TypeGenConfig} from '../readConfig.js'\nimport {debug} from '../utils/debug.js'\nimport {getMessage} from '../utils/getMessage.js'\nimport {defineFormatter} from '../utils/resolveFormatter.js'\nimport {generatedFileWarning} from './generatedFileWarning.js'\nimport {type TypegenProgressEvent, TypegenWorkerChannel} from './types.js'\n\nconst noopProgress = (_event: TypegenProgressEvent): void => {}\n\n/**\n * Processes the event stream from a typegen worker thread.\n *\n * Consumes worker channel events, reports progress via `onProgress`,\n * writes generated types to disk, and optionally formats them.\n */\nexport async function processTypegenWorkerStream(\n receiver: WorkerChannelReceiver<TypegenWorkerChannel>,\n options: TypeGenConfig,\n onProgress: (event: TypegenProgressEvent) => void = noopProgress,\n) {\n const start = Date.now()\n const {formatGeneratedCode, generates} = options\n\n try {\n await receiver.event.loadedSchema()\n onProgress({type: 'schemaLoaded'})\n\n const {expectedFileCount} = await receiver.event.typegenStarted()\n onProgress({expectedFileCount, type: 'typegenStarted'})\n\n const {schemaTypeDeclarations} = await receiver.event.generatedSchemaTypes()\n const schemaTypesCount = schemaTypeDeclarations.length\n onProgress({schemaTypesCount, type: 'schemaTypesGenerated'})\n\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 onProgress({\n errors: errors.map((error) => getMessage(error)),\n evaluatedFiles,\n expectedFileCount,\n queriesCount,\n queryFilesCount,\n type: 'moduleEvaluated',\n })\n }\n\n const result = await receiver.event.typegenComplete()\n const code = `${generatedFileWarning}${result.code}`\n await writeFile(generates, code)\n\n if (formatGeneratedCode !== false) {\n const formatter = defineFormatter(formatGeneratedCode)\n if (formatter) {\n try {\n const {format} = await formatter.resolve()\n if (format) {\n onProgress({formatterName: formatter.name, type: 'formatting'})\n const formattedCode = await format(generates, code)\n await writeFile(generates, formattedCode)\n }\n } catch (err) {\n onProgress({\n formatterName: formatter.name,\n message: getMessage(err),\n type: 'formatFailed',\n })\n }\n }\n }\n\n const generationResult = {\n code,\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 onProgress({result: generationResult, type: 'complete'})\n\n return generationResult\n } catch (err) {\n debug('error generating types', err)\n throw err\n } finally {\n receiver.unsubscribe()\n }\n}\n"],"names":["writeFile","debug","getMessage","defineFormatter","generatedFileWarning","noopProgress","_event","processTypegenWorkerStream","receiver","options","onProgress","start","Date","now","formatGeneratedCode","generates","event","loadedSchema","type","expectedFileCount","typegenStarted","schemaTypeDeclarations","generatedSchemaTypes","schemaTypesCount","length","queriesCount","evaluatedFiles","filesWithErrors","queryFilesCount","typeNodesGenerated","unknownTypeNodesGenerated","emptyUnionTypeNodesGenerated","errors","queries","stream","evaluatedModules","stats","allTypes","unknownTypes","emptyUnions","map","error","result","typegenComplete","code","formatter","format","resolve","formatterName","name","formattedCode","err","message","generationResult","duration","outputSize","Buffer","byteLength","unknownTypeNodesRatio","unsubscribe"],"mappings":"AAAA,SAAQA,SAAS,QAAO,mBAAkB;AAK1C,SAAQC,KAAK,QAAO,oBAAmB;AACvC,SAAQC,UAAU,QAAO,yBAAwB;AACjD,SAAQC,eAAe,QAAO,+BAA8B;AAC5D,SAAQC,oBAAoB,QAAO,4BAA2B;AAG9D,MAAMC,eAAe,CAACC,UAAwC;AAE9D;;;;;CAKC,GACD,OAAO,eAAeC,2BACpBC,QAAqD,EACrDC,OAAsB,EACtBC,aAAoDL,YAAY;IAEhE,MAAMM,QAAQC,KAAKC,GAAG;IACtB,MAAM,EAACC,mBAAmB,EAAEC,SAAS,EAAC,GAAGN;IAEzC,IAAI;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AAI;oBACF,MAAM,EAACC,MAAM,EAAC,GAAG,MAAMD,UAAUE,OAAO;oBACxC,IAAID,QAAQ;wBACVpC,WAAW;4BAACsC,eAAeH,UAAUI,IAAI;4BAAE/B,MAAM;wBAAY;wBAC7D,MAAMgC,gBAAgB,MAAMJ,OAAO/B,WAAW6B;wBAC9C,MAAM5C,UAAUe,WAAWmC;oBAC7B;gBACF,EAAE,OAAOC,KAAK;oBACZzC,WAAW;wBACTsC,eAAeH,UAAUI,IAAI;wBAC7BG,SAASlD,WAAWiD;wBACpBjC,MAAM;oBACR;gBACF;YACF;QACF;QAEA,MAAMmC,mBAAmB;YACvBT;YACAU,UAAU1C,KAAKC,GAAG,KAAKF;YACvBoB;YACAJ;YACA4B,YAAYC,OAAOC,UAAU,CAACb;YAC9BnB;YACAG;YACAL;YACAM;YACAC;YACA4B,uBACE7B,qBAAqB,IAAIC,4BAA4BD,qBAAqB;QAC9E;QAEAnB,WAAW;YAACgC,QAAQW;YAAkBnC,MAAM;QAAU;QAEtD,OAAOmC;IACT,EAAE,OAAOF,KAAK;QACZlD,MAAM,0BAA0BkD;QAChC,MAAMA;IACR,SAAU;QACR3C,SAASmD,WAAW;IACtB;AACF"}
|
|
@@ -10,13 +10,13 @@ import { processTypegenWorkerStream } from './streamProcessor.js';
|
|
|
10
10
|
* Runs a single typegen generation.
|
|
11
11
|
*
|
|
12
12
|
* This is the programmatic API for generating TypeScript types from GROQ queries.
|
|
13
|
-
* It spawns a worker thread to perform the generation and
|
|
13
|
+
* It spawns a worker thread to perform the generation and reports progress via the optional `onProgress` callback.
|
|
14
14
|
*
|
|
15
15
|
* @param options - Configuration options including typegen config and working directory
|
|
16
16
|
* @returns Generation result containing the generated code and statistics
|
|
17
17
|
* @public
|
|
18
18
|
*/ export async function runTypegenGenerate(options) {
|
|
19
|
-
const { config, workDir } = options;
|
|
19
|
+
const { config, workDir, onProgress } = options;
|
|
20
20
|
const { formatGeneratedCode, generates, overloadClientMethods, path, schema } = prepareConfig(config);
|
|
21
21
|
const outputPath = isAbsolute(generates) ? generates : join(workDir, generates);
|
|
22
22
|
// create output dir if it isn't there
|
|
@@ -43,7 +43,7 @@ import { processTypegenWorkerStream } from './streamProcessor.js';
|
|
|
43
43
|
overloadClientMethods,
|
|
44
44
|
path,
|
|
45
45
|
schema
|
|
46
|
-
});
|
|
46
|
+
}, onProgress);
|
|
47
47
|
return result;
|
|
48
48
|
} catch (err) {
|
|
49
49
|
debug('error generating types', err);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/actions/typegenGenerate.ts"],"sourcesContent":["import {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 {prepareConfig} from '../utils/config.js'\nimport {debug} from '../utils/debug.js'\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
|
|
1
|
+
{"version":3,"sources":["../../src/actions/typegenGenerate.ts"],"sourcesContent":["import {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 {prepareConfig} from '../utils/config.js'\nimport {debug} from '../utils/debug.js'\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 reports progress via the optional `onProgress` callback.\n *\n * @param options - Configuration options including typegen config and working directory\n * @returns Generation result containing the generated code and statistics\n * @public\n */\nexport async function runTypegenGenerate(options: RunTypegenOptions): Promise<GenerationResult> {\n const {config, workDir, onProgress} = options\n\n const {formatGeneratedCode, generates, overloadClientMethods, path, schema} =\n prepareConfig(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 onProgress,\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":["mkdir","dirname","isAbsolute","join","env","Worker","WorkerChannelReceiver","prepareConfig","debug","processTypegenWorkerStream","runTypegenGenerate","options","config","workDir","onProgress","formatGeneratedCode","generates","overloadClientMethods","path","schema","outputPath","outputDir","recursive","workerPath","URL","url","workerData","schemaPath","searchPath","worker","result","from","err","terminate"],"mappings":"AAAA,SAAQA,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,aAAa,QAAO,qBAAoB;AAChD,SAAQC,KAAK,QAAO,oBAAmB;AACvC,SAAQC,0BAA0B,QAAO,uBAAsB;AAQ/D;;;;;;;;;CASC,GACD,OAAO,eAAeC,mBAAmBC,OAA0B;IACjE,MAAM,EAACC,MAAM,EAAEC,OAAO,EAAEC,UAAU,EAAC,GAAGH;IAEtC,MAAM,EAACI,mBAAmB,EAAEC,SAAS,EAAEC,qBAAqB,EAAEC,IAAI,EAAEC,MAAM,EAAC,GACzEZ,cAAcK;IAEhB,MAAMQ,aAAalB,WAAWc,aAAaA,YAAYb,KAAKU,SAASG;IAErE,sCAAsC;IACtC,MAAMK,YAAYpB,QAAQmB;IAC1B,MAAMpB,MAAMqB,WAAW;QAACC,WAAW;IAAI;IAEvC,gBAAgB;IAChB,MAAMC,aAAa,IAAIC,IAAI,wCAAwC,YAAYC,GAAG;IAClF,MAAMC,aAA6C;QACjDT;QACAU,YAAYR;QACZS,YAAYV;QACZL;IACF;IACA,MAAMgB,SAAS,IAAIxB,OAAOkB,YAAY;QAACnB;QAAKsB;IAAU;IAEtD,IAAI;QACF,MAAMI,SAAS,MAAMrB,2BACnBH,sBAAsByB,IAAI,CAAuBF,SACjD;YACEd;YACAC,WAAWI;YACXH;YACAC;YACAC;QACF,GACAL;QAGF,OAAOgB;IACT,EAAE,OAAOE,KAAK;QACZxB,MAAM,0BAA0BwB;QAChC,MAAMA;IACR,SAAU;QACRH,OAAOI,SAAS;IAClB;AACF"}
|
package/dist/actions/types.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/actions/types.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../src/actions/types.ts"],"sourcesContent":["import {WorkerChannel} from '@sanity/worker-channels'\n\nimport {TypeGenConfig} from '../readConfig.js'\nimport {type TypegenWorkerChannel as CodegenTypegenWorkerChannel} from '../typescript/typeGenerator.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 * Result from a single generation run.\n * @public\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\n/**\n * A progress event emitted during a single typegen run.\n * Consumers (e.g. the Sanity CLI) render these; the library performs no terminal output.\n * @public\n */\nexport type TypegenProgressEvent =\n | {type: 'schemaLoaded'}\n | {type: 'typegenStarted'; expectedFileCount: number}\n | {type: 'schemaTypesGenerated'; schemaTypesCount: number}\n | {\n type: 'moduleEvaluated'\n evaluatedFiles: number\n expectedFileCount: number\n queriesCount: number\n queryFilesCount: number\n errors: string[]\n }\n | {type: 'formatting'; formatterName: string}\n | {type: 'formatFailed'; formatterName: string; message: string}\n | {type: 'complete'; result: GenerationResult}\n\n/**\n * Options for running a single typegen generation.\n * @public\n */\nexport interface RunTypegenOptions {\n /** Working directory (usually project root) */\n workDir: string\n\n /** Typegen configuration */\n config?: Partial<TypeGenConfig>\n\n /** Optional progress reporter. Called synchronously as generation proceeds. */\n onProgress?: (event: TypegenProgressEvent) => void\n}\n"],"names":[],"mappings":"AAyEA;;;CAGC,GACD,WASC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/safeParseQuery.ts"],"sourcesContent":["import {parse} from 'groq-js'\n\n/**\n * safeParseQuery parses a GROQ query string, but first attempts to extract any parameters used in slices. This method is _only_\n * intended for use in type generation where we don't actually execute the parsed AST on a dataset, and should not be used elsewhere.\n * @internal\n */\nexport function safeParseQuery(query: string) {\n const params: Record<string, unknown> = {}\n\n for (const param of extractSliceParams(query)) {\n params[param] = 0 // we don't care about the value, just the type\n }\n return parse(query, {params})\n}\n\n/**\n * Finds occurences of `[($start|{number})..($end|{number})]` in a query string and returns the start and end values, and return\n * the names of the start and end variables.\n * @internal\n */\nexport function* extractSliceParams(query: string): Generator<string> {\n const sliceRegex = /\\[(\\$(\\w+)|\\d)\\.\\.\\.?(\\$(\\w+)|\\d)\\]/g\n const matches = query.matchAll(sliceRegex)\n if (!matches) {\n return\n }\n for (const match of matches) {\n const start = match[1] === `$${match[2]}` ? match[2] : null\n if (start !== null) {\n yield start!\n }\n const end = match[3] === `$${match[4]}` ? match[4] : null\n if (end !== null) {\n yield end!\n }\n }\n}\n"],"names":["parse","safeParseQuery","query","params","param","extractSliceParams","sliceRegex","matches","matchAll","match","start","end"],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"sources":["../src/safeParseQuery.ts"],"sourcesContent":["import {type ExprNode, parse} from 'groq-js'\n\n/**\n * safeParseQuery parses a GROQ query string, but first attempts to extract any parameters used in slices. This method is _only_\n * intended for use in type generation where we don't actually execute the parsed AST on a dataset, and should not be used elsewhere.\n * @internal\n */\nexport function safeParseQuery(query: string): ExprNode {\n const params: Record<string, unknown> = {}\n\n for (const param of extractSliceParams(query)) {\n params[param] = 0 // we don't care about the value, just the type\n }\n return parse(query, {params})\n}\n\n/**\n * Finds occurences of `[($start|{number})..($end|{number})]` in a query string and returns the start and end values, and return\n * the names of the start and end variables.\n * @internal\n */\nexport function* extractSliceParams(query: string): Generator<string> {\n const sliceRegex = /\\[(\\$(\\w+)|\\d)\\.\\.\\.?(\\$(\\w+)|\\d)\\]/g\n const matches = query.matchAll(sliceRegex)\n if (!matches) {\n return\n }\n for (const match of matches) {\n const start = match[1] === `$${match[2]}` ? match[2] : null\n if (start !== null) {\n yield start!\n }\n const end = match[3] === `$${match[4]}` ? match[4] : null\n if (end !== null) {\n yield end!\n }\n }\n}\n"],"names":["parse","safeParseQuery","query","params","param","extractSliceParams","sliceRegex","matches","matchAll","match","start","end"],"mappings":"AAAA,SAAuBA,KAAK,QAAO,UAAS;AAE5C;;;;CAIC,GACD,OAAO,SAASC,eAAeC,KAAa;IAC1C,MAAMC,SAAkC,CAAC;IAEzC,KAAK,MAAMC,SAASC,mBAAmBH,OAAQ;QAC7CC,MAAM,CAACC,MAAM,GAAG,GAAE,+CAA+C;IACnE;IACA,OAAOJ,MAAME,OAAO;QAACC;IAAM;AAC7B;AAEA;;;;CAIC,GACD,OAAO,UAAUE,mBAAmBH,KAAa;IAC/C,MAAMI,aAAa;IACnB,MAAMC,UAAUL,MAAMM,QAAQ,CAACF;IAC/B,IAAI,CAACC,SAAS;QACZ;IACF;IACA,KAAK,MAAME,SAASF,QAAS;QAC3B,MAAMG,QAAQD,KAAK,CAAC,EAAE,KAAK,CAAC,CAAC,EAAEA,KAAK,CAAC,EAAE,EAAE,GAAGA,KAAK,CAAC,EAAE,GAAG;QACvD,IAAIC,UAAU,MAAM;YAClB,MAAMA;QACR;QACA,MAAMC,MAAMF,KAAK,CAAC,EAAE,KAAK,CAAC,CAAC,EAAEA,KAAK,CAAC,EAAE,EAAE,GAAGA,KAAK,CAAC,EAAE,GAAG;QACrD,IAAIE,QAAQ,MAAM;YAChB,MAAMA;QACR;IACF;AACF"}
|
package/dist/utils/debug.js
CHANGED
package/dist/utils/debug.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/debug.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"sources":["../../src/utils/debug.ts"],"sourcesContent":["import createDebug from 'debug'\n\nexport const debug = createDebug('sanity:typegen:generate')\n"],"names":["createDebug","debug"],"mappings":"AAAA,OAAOA,iBAAiB,QAAO;AAE/B,OAAO,MAAMC,QAAQD,YAAY,2BAA0B"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/codegen",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "8.0.0",
|
|
4
4
|
"description": "Codegen toolkit for Sanity.io",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sanity",
|
|
@@ -33,8 +33,6 @@
|
|
|
33
33
|
"types": "./dist/_exports/index.d.ts",
|
|
34
34
|
"files": [
|
|
35
35
|
"dist",
|
|
36
|
-
"oclif.manifest.json",
|
|
37
|
-
"oclif.config.js",
|
|
38
36
|
"babel.config.json"
|
|
39
37
|
],
|
|
40
38
|
"dependencies": {
|
|
@@ -52,7 +50,7 @@
|
|
|
52
50
|
"debug": "^4.4.3",
|
|
53
51
|
"globby": "^11.1.0",
|
|
54
52
|
"groq": "^6.0.0",
|
|
55
|
-
"groq-js": "^
|
|
53
|
+
"groq-js": "^2.0.0",
|
|
56
54
|
"json5": "^2.2.3",
|
|
57
55
|
"lodash-es": "^4.18.1",
|
|
58
56
|
"prettier": "^3.8.3",
|
|
@@ -62,8 +60,6 @@
|
|
|
62
60
|
},
|
|
63
61
|
"devDependencies": {
|
|
64
62
|
"@eslint/compat": "^2.1.0",
|
|
65
|
-
"@sanity/cli-core": "^2.0.1",
|
|
66
|
-
"@sanity/cli-test": "^1.0.1",
|
|
67
63
|
"@sanity/eslint-config-cli": "^1.1.2",
|
|
68
64
|
"@sanity/pkg-utils": "^10.5.5",
|
|
69
65
|
"@swc/cli": "^0.8.1",
|
|
@@ -79,7 +75,6 @@
|
|
|
79
75
|
"eslint": "^9.39.4",
|
|
80
76
|
"husky": "^9.1.7",
|
|
81
77
|
"lint-staged": "^16.4.0",
|
|
82
|
-
"oclif": "^4.23.10",
|
|
83
78
|
"oxfmt": "^0.53.0",
|
|
84
79
|
"pkg-pr-new": "^0.0.75",
|
|
85
80
|
"prettier-plugin-packagejson": "^3.0.2",
|
|
@@ -90,8 +85,6 @@
|
|
|
90
85
|
"vitest": "^4.1.8"
|
|
91
86
|
},
|
|
92
87
|
"peerDependencies": {
|
|
93
|
-
"@oclif/core": "^4.8.0",
|
|
94
|
-
"@sanity/cli-core": "^2",
|
|
95
88
|
"oxfmt": "*"
|
|
96
89
|
},
|
|
97
90
|
"peerDependenciesMeta": {
|
|
@@ -100,14 +93,13 @@
|
|
|
100
93
|
}
|
|
101
94
|
},
|
|
102
95
|
"engines": {
|
|
103
|
-
"node": ">=
|
|
96
|
+
"node": ">=22.12"
|
|
104
97
|
},
|
|
105
98
|
"publishConfig": {
|
|
106
99
|
"access": "public"
|
|
107
100
|
},
|
|
108
101
|
"scripts": {
|
|
109
102
|
"build": "swc --delete-dir-on-start src -d dist --strip-leading-paths --ignore '**/__tests__/**' && pnpm run build:types",
|
|
110
|
-
"postbuild": "oclif manifest",
|
|
111
103
|
"build:types": "pkg-utils build --emitDeclarationOnly",
|
|
112
104
|
"clean": "rimraf dist coverage",
|
|
113
105
|
"lint": "eslint . --fix",
|
|
@@ -1,185 +0,0 @@
|
|
|
1
|
-
import { stat } from 'node:fs/promises';
|
|
2
|
-
import { styleText } from 'node:util';
|
|
3
|
-
import { Flags } from '@oclif/core';
|
|
4
|
-
import { SanityCommand } from '@sanity/cli-core';
|
|
5
|
-
import { spinner } from '@sanity/cli-core/ux';
|
|
6
|
-
import omit from 'lodash-es/omit.js';
|
|
7
|
-
import once from 'lodash-es/once.js';
|
|
8
|
-
import { runTypegenGenerate } from '../../actions/typegenGenerate.js';
|
|
9
|
-
import { runTypegenWatcher } from '../../actions/typegenWatch.js';
|
|
10
|
-
import { configDefinition, readConfig } from '../../readConfig.js';
|
|
11
|
-
import { TypegenWatchModeTrace, TypesGeneratedTrace } from '../../typegen.telemetry.js';
|
|
12
|
-
import { debug } from '../../utils/debug.js';
|
|
13
|
-
import { promiseWithResolvers } from '../../utils/promiseWithResolvers.js';
|
|
14
|
-
const description = `Sanity TypeGen
|
|
15
|
-
|
|
16
|
-
${styleText('bold', 'Configuration:')}
|
|
17
|
-
This command can utilize configuration settings defined in a \`sanity-typegen.json\` file. These settings include:
|
|
18
|
-
|
|
19
|
-
- "path": Specifies a glob pattern to locate your TypeScript or JavaScript files.
|
|
20
|
-
Default: "./src/**/*.{ts,tsx,js,jsx}"
|
|
21
|
-
|
|
22
|
-
- "schema": Defines the path to your Sanity schema file. This file should be generated using the \`sanity schema extract\` command.
|
|
23
|
-
Default: "schema.json"
|
|
24
|
-
|
|
25
|
-
- "generates": Indicates the path where the generated TypeScript type definitions will be saved.
|
|
26
|
-
Default: "./sanity.types.ts"
|
|
27
|
-
|
|
28
|
-
The 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.
|
|
29
|
-
|
|
30
|
-
${styleText('bold', 'Note:')}
|
|
31
|
-
- 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.`.trim();
|
|
32
|
-
/**
|
|
33
|
-
* @internal
|
|
34
|
-
*/ export class TypegenGenerateCommand extends SanityCommand {
|
|
35
|
-
static description = description;
|
|
36
|
-
static examples = [
|
|
37
|
-
{
|
|
38
|
-
command: '<%= config.bin %> <%= command.id %>',
|
|
39
|
-
description: `Generate TypeScript type definitions from a Sanity Studio schema extracted using the \`sanity schema extract\` command.`
|
|
40
|
-
}
|
|
41
|
-
];
|
|
42
|
-
static flags = {
|
|
43
|
-
'config-path': Flags.string({
|
|
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
|
-
default: false,
|
|
48
|
-
description: '[Default: false] Run the typegen in watch mode'
|
|
49
|
-
})
|
|
50
|
-
};
|
|
51
|
-
async run() {
|
|
52
|
-
const { flags } = await this.parse(TypegenGenerateCommand);
|
|
53
|
-
if (flags.watch) {
|
|
54
|
-
await this.runWatcher();
|
|
55
|
-
return;
|
|
56
|
-
}
|
|
57
|
-
await this.runSingle();
|
|
58
|
-
}
|
|
59
|
-
async getConfig() {
|
|
60
|
-
const spin = spinner({}).start('Loading config…');
|
|
61
|
-
try {
|
|
62
|
-
const { flags } = await this.parse(TypegenGenerateCommand);
|
|
63
|
-
const rootDir = await this.getProjectRoot();
|
|
64
|
-
const config = await this.getCliConfig();
|
|
65
|
-
const configPath = flags['config-path'];
|
|
66
|
-
const workDir = rootDir.directory;
|
|
67
|
-
// check if the legacy config exist
|
|
68
|
-
const legacyConfigPath = configPath || 'sanity-typegen.json';
|
|
69
|
-
let hasLegacyConfig = false;
|
|
70
|
-
try {
|
|
71
|
-
const file = await stat(legacyConfigPath);
|
|
72
|
-
hasLegacyConfig = file.isFile();
|
|
73
|
-
} catch (err) {
|
|
74
|
-
if (err instanceof Error && 'code' in err && err.code === 'ENOENT' && configPath) {
|
|
75
|
-
spin.fail();
|
|
76
|
-
this.error(`Typegen config file not found: ${configPath}`, {
|
|
77
|
-
exit: 1
|
|
78
|
-
});
|
|
79
|
-
}
|
|
80
|
-
if (err instanceof Error && 'code' in err && err.code !== 'ENOENT') {
|
|
81
|
-
spin.fail();
|
|
82
|
-
this.error(`Error when checking if typegen config file exists: ${legacyConfigPath}`, {
|
|
83
|
-
exit: 1
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
// we have both legacy and cli config with typegen
|
|
88
|
-
if (config?.typegen && hasLegacyConfig) {
|
|
89
|
-
spin.warn(styleText('yellow', `You've specified typegen in your Sanity CLI config, but also have a typegen config.
|
|
90
|
-
|
|
91
|
-
The config from the Sanity CLI config is used.
|
|
92
|
-
`));
|
|
93
|
-
return {
|
|
94
|
-
config: configDefinition.parse(config.typegen || {}),
|
|
95
|
-
path: rootDir.path,
|
|
96
|
-
type: 'cli',
|
|
97
|
-
workDir
|
|
98
|
-
};
|
|
99
|
-
}
|
|
100
|
-
// we only have legacy typegen config
|
|
101
|
-
if (hasLegacyConfig) {
|
|
102
|
-
spin.warn(styleText('yellow', `The separate typegen config has been deprecated. Use \`typegen\` in the sanity CLI config instead.
|
|
103
|
-
|
|
104
|
-
See: https://www.sanity.io/docs/help/configuring-typegen-in-sanity-cli-config`));
|
|
105
|
-
return {
|
|
106
|
-
config: await readConfig(legacyConfigPath),
|
|
107
|
-
path: legacyConfigPath,
|
|
108
|
-
type: 'legacy',
|
|
109
|
-
workDir
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
spin.succeed(`Config loaded from sanity.cli.ts`);
|
|
113
|
-
// we only have cli config
|
|
114
|
-
return {
|
|
115
|
-
config: configDefinition.parse(config.typegen || {}),
|
|
116
|
-
path: rootDir.path,
|
|
117
|
-
type: 'cli',
|
|
118
|
-
workDir
|
|
119
|
-
};
|
|
120
|
-
} catch (err) {
|
|
121
|
-
spin.fail();
|
|
122
|
-
this.error(`An error occured during config loading ${err}`, {
|
|
123
|
-
exit: 1
|
|
124
|
-
});
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
async runSingle() {
|
|
128
|
-
const trace = this.telemetry.trace(TypesGeneratedTrace);
|
|
129
|
-
try {
|
|
130
|
-
const { config: typegenConfig, type: typegenConfigMethod, workDir } = await this.getConfig();
|
|
131
|
-
trace.start();
|
|
132
|
-
const result = await runTypegenGenerate({
|
|
133
|
-
config: typegenConfig,
|
|
134
|
-
workDir
|
|
135
|
-
});
|
|
136
|
-
const traceStats = omit(result, 'code', 'duration');
|
|
137
|
-
trace.log({
|
|
138
|
-
configMethod: typegenConfigMethod,
|
|
139
|
-
configOverloadClientMethods: typegenConfig.overloadClientMethods,
|
|
140
|
-
...traceStats
|
|
141
|
-
});
|
|
142
|
-
trace.complete();
|
|
143
|
-
} catch (error) {
|
|
144
|
-
debug(error);
|
|
145
|
-
trace.error(error);
|
|
146
|
-
this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {
|
|
147
|
-
exit: 1
|
|
148
|
-
});
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
async runWatcher() {
|
|
152
|
-
const trace = this.telemetry.trace(TypegenWatchModeTrace);
|
|
153
|
-
try {
|
|
154
|
-
const { config: typegenConfig, workDir } = await this.getConfig();
|
|
155
|
-
trace.start();
|
|
156
|
-
const { promise, resolve } = promiseWithResolvers();
|
|
157
|
-
const typegenWatcher = runTypegenWatcher({
|
|
158
|
-
config: typegenConfig,
|
|
159
|
-
workDir
|
|
160
|
-
});
|
|
161
|
-
const stop = once(async ()=>{
|
|
162
|
-
process.off('SIGINT', stop);
|
|
163
|
-
process.off('SIGTERM', stop);
|
|
164
|
-
trace.log({
|
|
165
|
-
step: 'stopped',
|
|
166
|
-
...typegenWatcher.getStats()
|
|
167
|
-
});
|
|
168
|
-
trace.complete();
|
|
169
|
-
await typegenWatcher.stop();
|
|
170
|
-
resolve();
|
|
171
|
-
});
|
|
172
|
-
process.on('SIGINT', stop);
|
|
173
|
-
process.on('SIGTERM', stop);
|
|
174
|
-
await promise;
|
|
175
|
-
} catch (error) {
|
|
176
|
-
debug(error);
|
|
177
|
-
trace.error(error);
|
|
178
|
-
this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {
|
|
179
|
-
exit: 1
|
|
180
|
-
});
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
//# sourceMappingURL=generate.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/commands/typegen/generate.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport {styleText} from 'node:util'\n\nimport {Flags} from '@oclif/core'\nimport {SanityCommand} from '@sanity/cli-core'\nimport {spinner} from '@sanity/cli-core/ux'\nimport omit from 'lodash-es/omit.js'\nimport once from 'lodash-es/once.js'\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 {debug} from '../../utils/debug.js'\nimport {promiseWithResolvers} from '../../utils/promiseWithResolvers.js'\n\nconst description = `Sanity TypeGen\n\n${styleText('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${styleText('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.`.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 default: false,\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 try {\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\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 spin.fail()\n this.error(`Typegen config file not found: ${configPath}`, {exit: 1})\n }\n\n if (err instanceof Error && 'code' in err && err.code !== 'ENOENT') {\n spin.fail()\n this.error(`Error when checking if typegen config file exists: ${legacyConfigPath}`, {\n exit: 1,\n })\n }\n }\n\n // we have both legacy and cli config with typegen\n if (config?.typegen && hasLegacyConfig) {\n spin.warn(\n styleText(\n '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 styleText(\n '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 } catch (err) {\n spin.fail()\n this.error(`An error occured during config loading ${err}`, {exit: 1})\n }\n }\n\n private async runSingle() {\n const trace = this.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 debug(error)\n trace.error(error as Error)\n this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {\n exit: 1,\n })\n }\n }\n\n private async runWatcher() {\n const trace = this.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 trace.complete()\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 debug(error)\n trace.error(error as Error)\n this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {\n exit: 1,\n })\n }\n }\n}\n"],"names":["stat","styleText","Flags","SanityCommand","spinner","omit","once","runTypegenGenerate","runTypegenWatcher","configDefinition","readConfig","TypegenWatchModeTrace","TypesGeneratedTrace","debug","promiseWithResolvers","description","trim","TypegenGenerateCommand","examples","command","flags","string","watch","boolean","default","run","parse","runWatcher","runSingle","getConfig","spin","start","rootDir","getProjectRoot","config","getCliConfig","configPath","workDir","directory","legacyConfigPath","hasLegacyConfig","file","isFile","err","Error","code","fail","error","exit","typegen","warn","path","type","succeed","trace","telemetry","typegenConfig","typegenConfigMethod","result","traceStats","log","configMethod","configOverloadClientMethods","overloadClientMethods","complete","message","promise","resolve","typegenWatcher","stop","process","off","step","getStats","on"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AACrC,SAAQC,SAAS,QAAO,YAAW;AAEnC,SAAQC,KAAK,QAAO,cAAa;AACjC,SAAQC,aAAa,QAAO,mBAAkB;AAC9C,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,OAAOC,UAAU,oBAAmB;AACpC,OAAOC,UAAU,oBAAmB;AAEpC,SAAQ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AEd,MAAMI,eAAeC,IAAI;gBACzBF;YACF;YAEAG,QAAQI,EAAE,CAAC,UAAUL;YACrBC,QAAQI,EAAE,CAAC,WAAWL;YAEtB,MAAMH;QACR,EAAE,OAAOnB,OAAO;YACdlC,MAAMkC;YACNO,MAAMP,KAAK,CAACA;YACZ,IAAI,CAACA,KAAK,CAAC,GAAGA,iBAAiBH,QAAQG,MAAMkB,OAAO,GAAG,iBAAiB,EAAE;gBACxEjB,MAAM;YACR;QACF;IACF;AACF"}
|
package/dist/utils/count.js
DELETED
package/dist/utils/count.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/count.ts"],"sourcesContent":["export const count = (\n amount: number,\n plural: string = '',\n singular: string = plural.slice(0, Math.max(0, plural.length - 1)),\n): string =>\n [amount.toLocaleString('en-US'), amount === 1 ? singular : plural].filter(Boolean).join(' ')\n"],"names":["count","amount","plural","singular","slice","Math","max","length","toLocaleString","filter","Boolean","join"],"mappings":"AAAA,OAAO,MAAMA,QAAQ,CACnBC,QACAC,SAAiB,EAAE,EACnBC,WAAmBD,OAAOE,KAAK,CAAC,GAAGC,KAAKC,GAAG,CAAC,GAAGJ,OAAOK,MAAM,GAAG,GAAG,GAElE;QAACN,OAAOO,cAAc,CAAC;QAAUP,WAAW,IAAIE,WAAWD;KAAO,CAACO,MAAM,CAACC,SAASC,IAAI,CAAC,KAAI"}
|
package/dist/utils/percent.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/percent.ts"],"sourcesContent":["const formatter = new Intl.NumberFormat('en-US', {\n maximumFractionDigits: 1,\n minimumFractionDigits: 1,\n style: 'percent',\n})\n\nexport const percent = (value: number): string => formatter.format(Math.min(value, 1))\n"],"names":["formatter","Intl","NumberFormat","maximumFractionDigits","minimumFractionDigits","style","percent","value","format","Math","min"],"mappings":"AAAA,MAAMA,YAAY,IAAIC,KAAKC,YAAY,CAAC,SAAS;IAC/CC,uBAAuB;IACvBC,uBAAuB;IACvBC,OAAO;AACT;AAEA,OAAO,MAAMC,UAAU,CAACC,QAA0BP,UAAUQ,MAAM,CAACC,KAAKC,GAAG,CAACH,OAAO,IAAG"}
|
|
@@ -1,67 +0,0 @@
|
|
|
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/once.js';
|
|
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
|
|
@@ -1 +0,0 @@
|
|
|
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/once.js'\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,OAAOC,UAAU,oBAAmB;AAEpC,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"}
|
package/oclif.config.js
DELETED
package/oclif.manifest.json
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"commands": {
|
|
3
|
-
"typegen:generate": {
|
|
4
|
-
"aliases": [],
|
|
5
|
-
"args": {},
|
|
6
|
-
"description": "Sanity TypeGen\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.",
|
|
7
|
-
"examples": [
|
|
8
|
-
{
|
|
9
|
-
"command": "<%= config.bin %> <%= command.id %>",
|
|
10
|
-
"description": "Generate TypeScript type definitions from a Sanity Studio schema extracted using the `sanity schema extract` command."
|
|
11
|
-
}
|
|
12
|
-
],
|
|
13
|
-
"flags": {
|
|
14
|
-
"config-path": {
|
|
15
|
-
"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.",
|
|
16
|
-
"name": "config-path",
|
|
17
|
-
"hasDynamicHelp": false,
|
|
18
|
-
"multiple": false,
|
|
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"
|
|
26
|
-
}
|
|
27
|
-
},
|
|
28
|
-
"hasDynamicHelp": false,
|
|
29
|
-
"hiddenAliases": [],
|
|
30
|
-
"id": "typegen:generate",
|
|
31
|
-
"pluginAlias": "@sanity/codegen",
|
|
32
|
-
"pluginName": "@sanity/codegen",
|
|
33
|
-
"pluginType": "core",
|
|
34
|
-
"strict": true,
|
|
35
|
-
"isESM": true,
|
|
36
|
-
"relativePath": [
|
|
37
|
-
"dist",
|
|
38
|
-
"commands",
|
|
39
|
-
"typegen",
|
|
40
|
-
"generate.js"
|
|
41
|
-
]
|
|
42
|
-
}
|
|
43
|
-
},
|
|
44
|
-
"version": "7.0.3"
|
|
45
|
-
}
|