@sanity/codegen 8.1.0 → 8.2.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/README.md +53 -0
- package/dist/_exports/index.d.ts +123 -18
- package/dist/_exports/index.js.map +1 -1
- package/dist/actions/typegenGenerate.js +4 -1
- package/dist/actions/typegenGenerate.js.map +1 -1
- package/dist/actions/typegenGenerate.worker.js +9 -4
- package/dist/actions/typegenGenerate.worker.js.map +1 -1
- package/dist/actions/typegenWatch.js +3 -2
- package/dist/actions/typegenWatch.js.map +1 -1
- package/dist/actions/types.js.map +1 -1
- package/dist/typescript/constants.js +3 -0
- package/dist/typescript/constants.js.map +1 -1
- package/dist/typescript/expressionResolvers.js +1 -1
- package/dist/typescript/expressionResolvers.js.map +1 -1
- package/dist/typescript/findQueriesInPath.js +1 -1
- package/dist/typescript/findQueriesInPath.js.map +1 -1
- package/dist/typescript/findQueriesInSource.js +48 -0
- package/dist/typescript/findQueriesInSource.js.map +1 -1
- package/dist/typescript/helpers.js +2 -6
- package/dist/typescript/helpers.js.map +1 -1
- package/dist/typescript/moduleResolver.js +1 -1
- package/dist/typescript/moduleResolver.js.map +1 -1
- package/dist/typescript/schemaTypeGenerator.js +22 -0
- package/dist/typescript/schemaTypeGenerator.js.map +1 -1
- package/dist/typescript/typeGenerator.js +220 -26
- package/dist/typescript/typeGenerator.js.map +1 -1
- package/dist/typescript/types.js.map +1 -1
- package/dist/utils/debug.js +1 -1
- package/dist/utils/debug.js.map +1 -1
- package/package.json +2 -3
package/README.md
CHANGED
|
@@ -27,3 +27,56 @@ The two blocks serve different `@sanity/client` releases, and the same generated
|
|
|
27
27
|
The bridge is the only line that resolves `@sanity/client`. When the client cannot be resolved from the generated file, TypeScript reports `TS2664: Invalid module name in augmentation` for it in a `.ts` file, while in a declaration file an augmentation whose module cannot be found is skipped silently. Pointing `generates` at a `.d.ts` path therefore keeps the file valid in such a layout, and the global registry still types the client that is installed.
|
|
28
28
|
|
|
29
29
|
The earlier output, a `declare module '@sanity/client'` block that carried the whole map, keeps working with every `@sanity/client` release that accepts the new one.
|
|
30
|
+
|
|
31
|
+
## Types per dataset
|
|
32
|
+
|
|
33
|
+
Pass `resource: {projectId, dataset}` to a generation run and the generated file also registers its schema and query result types under that resource, keyed `projectId.dataset`:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
// Resource TypeMap: abc123.production
|
|
37
|
+
declare global {
|
|
38
|
+
interface SanitySchemasByResource {
|
|
39
|
+
'abc123.production': AllSanitySchemaTypes
|
|
40
|
+
}
|
|
41
|
+
interface SanityQueriesByResource {
|
|
42
|
+
'abc123.production': {
|
|
43
|
+
'*[_type == "post"]': PostsQueryResult
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
interface SanityProjectionsByResource {
|
|
47
|
+
'abc123.production': {
|
|
48
|
+
post: {
|
|
49
|
+
'{title}': PostTitleResult
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
An app that reads more than one dataset generates one file per dataset, and the same query text then resolves to a different type for each. `@sanity/client` 8.7.0 and later declare these interfaces, and the App SDK's hooks read them. The key is the same string the App SDK uses for its runtime cache.
|
|
57
|
+
|
|
58
|
+
This block has no `declare module '@sanity/client'` bridge. The registries first shipped as globals, so no client release needs one, and without it the block never resolves `@sanity/client`. That matters when the client is only a dependency of another package, as with the App SDK under pnpm. The flat query type map's bridge still resolves it, so in that layout also set `overloadClientMethods: false` (it defaults to `true`), or point `generates` at a `.d.ts` path as described above.
|
|
59
|
+
|
|
60
|
+
The flat query type map above is still controlled by `overloadClientMethods`, independently. When generating more than one resource into one TypeScript program, set `overloadClientMethods: false` for all of them: each file would declare the same query text in `SanityQueries` with a different type, which TypeScript rejects. For the same reason, generate one file per resource. Two files registering the same resource conflict.
|
|
61
|
+
|
|
62
|
+
Without `resource`, the generated file is unchanged.
|
|
63
|
+
|
|
64
|
+
### Projections
|
|
65
|
+
|
|
66
|
+
Projections passed to the App SDK's `defineProjection`, imported from `@sanity/sdk` or `@sanity/sdk-react`, are typed too:
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import {defineProjection} from '@sanity/sdk-react'
|
|
70
|
+
|
|
71
|
+
// Evaluated for `post` documents only
|
|
72
|
+
export const postTitle = defineProjection('post', '{title}')
|
|
73
|
+
|
|
74
|
+
// Evaluated for every document type in the schema
|
|
75
|
+
export const anyTitle = defineProjection('{title}')
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Each projection is evaluated as `*[_type == TYPE][0]PROJECTION` for its document type, and its result type is the object without `null`, since the SDK only projects documents it has found. A projection without a document type is evaluated for every document type in the schema. Document types with the same result share one type alias; the others get an alias named after the document type, such as `AnyTitleAuthorResult`. Passing the document type keeps the generated file smaller.
|
|
79
|
+
|
|
80
|
+
With `resource` set, results are registered in `SanityProjectionsByResource` by document type and then by the exact projection text, which is what `useDocumentProjection` looks up. Without `resource`, only the result type aliases are generated. As with `defineQuery`, only calls assigned to a variable are found, and the arguments must be resolvable without running the code. With `resource` set, a projection naming a document type the schema does not have is skipped, because another dataset scanning the same files can have it. A name that is an object type in the schema, or any unknown name in a run without `resource`, is reported as an error.
|
|
81
|
+
|
|
82
|
+
`runTypegenGenerate` also accepts `extractedSchema`, a schema already in memory in the shape `sanity schema extract` writes, so a caller that fetched and compiled a schema does not have to write it to a temporary file first. The file then has no `// Source:` line naming a schema file, since there is none.
|
package/dist/_exports/index.d.ts
CHANGED
|
@@ -52,6 +52,26 @@ export declare interface EvaluatedModule {
|
|
|
52
52
|
errors: (QueryEvaluationError | QueryExtractionError)[]
|
|
53
53
|
filename: string
|
|
54
54
|
queries: EvaluatedQuery[]
|
|
55
|
+
/** @beta */
|
|
56
|
+
projections?: EvaluatedProjection[]
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* An `ExtractedProjection` evaluated against the document types it applies to.
|
|
61
|
+
* @beta
|
|
62
|
+
*/
|
|
63
|
+
export declare interface EvaluatedProjection extends ExtractedProjection {
|
|
64
|
+
/** One result type alias per distinct result. */
|
|
65
|
+
declarations: {
|
|
66
|
+
ast: t.ExportNamedDeclaration
|
|
67
|
+
code: string
|
|
68
|
+
id: t.Identifier
|
|
69
|
+
}[]
|
|
70
|
+
/** The result alias for each document type the projection was evaluated against. */
|
|
71
|
+
resultsByDocumentType: {
|
|
72
|
+
[documentType: string]: t.Identifier
|
|
73
|
+
}
|
|
74
|
+
stats: TypeEvaluationStats
|
|
55
75
|
}
|
|
56
76
|
|
|
57
77
|
/**
|
|
@@ -74,6 +94,24 @@ export declare interface ExtractedModule {
|
|
|
74
94
|
errors: QueryExtractionError[]
|
|
75
95
|
filename: string
|
|
76
96
|
queries: ExtractedQuery[]
|
|
97
|
+
/** @beta */
|
|
98
|
+
projections?: ExtractedProjection[]
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* A projection extracted from a `defineProjection` call in a source file.
|
|
103
|
+
* @beta
|
|
104
|
+
*/
|
|
105
|
+
export declare interface ExtractedProjection {
|
|
106
|
+
filename: string
|
|
107
|
+
/** The exact projection string, which is also its lookup key. */
|
|
108
|
+
projection: string
|
|
109
|
+
variable: QueryVariable
|
|
110
|
+
/**
|
|
111
|
+
* The document type the projection is written for, when passed as the first argument.
|
|
112
|
+
* Without it, the projection is evaluated against every document type.
|
|
113
|
+
*/
|
|
114
|
+
documentType?: string
|
|
77
115
|
}
|
|
78
116
|
|
|
79
117
|
/**
|
|
@@ -178,9 +216,30 @@ export declare function findQueriesInSource(
|
|
|
178
216
|
/** @public */
|
|
179
217
|
export declare interface GenerateTypesOptions {
|
|
180
218
|
schema: SchemaType
|
|
219
|
+
/**
|
|
220
|
+
* Generate the client's flat `SanityQueries` map, which types `client.fetch`. Independent of
|
|
221
|
+
* `resource`. When an app generates types for more than one resource into one TypeScript
|
|
222
|
+
* program, set this to `false` for all of them: each file would declare the same query text
|
|
223
|
+
* in the flat map with a different type, and TypeScript rejects that merge.
|
|
224
|
+
*/
|
|
181
225
|
overloadClientMethods?: boolean
|
|
182
226
|
queries?: AsyncIterable<ExtractedModule>
|
|
183
227
|
reporter?: WorkerChannelReporter<TypegenWorkerChannel>
|
|
228
|
+
/**
|
|
229
|
+
* Also register the schema and query result types under this project and dataset, so one
|
|
230
|
+
* app can read more than one dataset and resolve the same query text to a different type for
|
|
231
|
+
* each. Types go into the global `SanitySchemasByResource` and `SanityQueriesByResource`
|
|
232
|
+
* interfaces that `@sanity/client` 8.7.0 and later declare, keyed `projectId.dataset`, the
|
|
233
|
+
* same string the App SDK uses for its runtime cache.
|
|
234
|
+
*
|
|
235
|
+
* The registration is a plain global declaration and never resolves `@sanity/client`, so it
|
|
236
|
+
* works when the client is only a dependency of another package, as with the App SDK under
|
|
237
|
+
* pnpm. The flat map's bridge does resolve it, so in that layout also set
|
|
238
|
+
* `overloadClientMethods: false`. Generate one file per resource per TypeScript program: two
|
|
239
|
+
* files registering the same resource conflict.
|
|
240
|
+
* @beta
|
|
241
|
+
*/
|
|
242
|
+
resource?: TypegenResource
|
|
184
243
|
root?: string
|
|
185
244
|
schemaPath?: string
|
|
186
245
|
}
|
|
@@ -403,13 +462,28 @@ export declare interface RunTypegenOptions {
|
|
|
403
462
|
workDir: string
|
|
404
463
|
/** Typegen configuration */
|
|
405
464
|
config?: Partial<TypeGenConfig>
|
|
465
|
+
/**
|
|
466
|
+
* An extracted schema to generate from, used instead of reading `config.schema` from disk.
|
|
467
|
+
* Same shape as the output of `sanity schema extract`. Pass this when the schema is extracted
|
|
468
|
+
* in memory, for example after fetching and compiling a dataset's schema, so it does not have
|
|
469
|
+
* to be written to a temporary file first. The watcher then watches query files only.
|
|
470
|
+
* @beta
|
|
471
|
+
*/
|
|
472
|
+
extractedSchema?: SchemaType
|
|
406
473
|
/** Optional progress reporter. Called synchronously as generation proceeds. */
|
|
407
474
|
onProgress?: (event: TypegenProgressEvent) => void
|
|
475
|
+
/**
|
|
476
|
+
* Also register the generated types under this project and dataset. See
|
|
477
|
+
* `GenerateTypesOptions.resource`.
|
|
478
|
+
* @beta
|
|
479
|
+
*/
|
|
480
|
+
resource?: TypegenResource
|
|
408
481
|
}
|
|
409
482
|
|
|
410
483
|
/**
|
|
411
484
|
* Starts a file watcher that triggers typegen on changes.
|
|
412
|
-
* Watches
|
|
485
|
+
* Watches query files (via patterns) and the schema JSON file. With `extractedSchema`, the
|
|
486
|
+
* schema is fixed for the life of the watcher, so only query files are watched.
|
|
413
487
|
* Implements debouncing and concurrency control to prevent multiple generations.
|
|
414
488
|
* @public
|
|
415
489
|
*/
|
|
@@ -456,8 +530,30 @@ export declare class TypeGenerator {
|
|
|
456
530
|
private getAllSanitySchemaTypesDeclaration
|
|
457
531
|
private getArrayOfDeclaration
|
|
458
532
|
private getInternalReferenceSymbolDeclaration
|
|
533
|
+
/**
|
|
534
|
+
* Evaluates a projection against its document type, or against every document type when it
|
|
535
|
+
* names none. Document types with the same result share one group, so a projection that does
|
|
536
|
+
* not apply to most types does not repeat the same type once per document type.
|
|
537
|
+
*
|
|
538
|
+
* Returns `undefined` for a document type this schema does not have when generating for a
|
|
539
|
+
* resource: datasets of one app can scan the same files, and the type can belong to another.
|
|
540
|
+
*/
|
|
541
|
+
private static evaluateProjection
|
|
459
542
|
private static getEvaluatedModules
|
|
543
|
+
/**
|
|
544
|
+
* One property per document type, each holding one property per distinct projection string,
|
|
545
|
+
* typed as the union of every result alias generated for that pair.
|
|
546
|
+
*/
|
|
547
|
+
private static getProjectionResultProperties
|
|
460
548
|
private static getQueryMapDeclaration
|
|
549
|
+
/**
|
|
550
|
+
* One property per distinct query string, typed as the union of every result type generated
|
|
551
|
+
* for it. Two variables holding the same query text share a key.
|
|
552
|
+
*/
|
|
553
|
+
private static getQueryResultProperties
|
|
554
|
+
private static getResourceRegistryDeclaration
|
|
555
|
+
/** Declares one result alias per group, with names not yet in `currentIdentifiers`. */
|
|
556
|
+
private static nameProjection
|
|
461
557
|
generateTypes(options: GenerateTypesOptions): Promise<{
|
|
462
558
|
ast: t.Program
|
|
463
559
|
code: string
|
|
@@ -471,37 +567,46 @@ export declare class TypeGenerator {
|
|
|
471
567
|
*/
|
|
472
568
|
export declare type TypegenProgressEvent =
|
|
473
569
|
| {
|
|
474
|
-
|
|
475
|
-
}
|
|
476
|
-
| {
|
|
477
|
-
type: 'typegenStarted'
|
|
478
|
-
expectedFileCount: number
|
|
479
|
-
}
|
|
480
|
-
| {
|
|
481
|
-
type: 'schemaTypesGenerated'
|
|
482
|
-
schemaTypesCount: number
|
|
483
|
-
}
|
|
484
|
-
| {
|
|
485
|
-
type: 'moduleEvaluated'
|
|
570
|
+
errors: string[]
|
|
486
571
|
evaluatedFiles: number
|
|
487
572
|
expectedFileCount: number
|
|
488
573
|
queriesCount: number
|
|
489
574
|
queryFilesCount: number
|
|
490
|
-
|
|
575
|
+
type: 'moduleEvaluated'
|
|
491
576
|
}
|
|
492
577
|
| {
|
|
493
|
-
|
|
494
|
-
|
|
578
|
+
expectedFileCount: number
|
|
579
|
+
type: 'typegenStarted'
|
|
495
580
|
}
|
|
496
581
|
| {
|
|
497
|
-
type: 'formatFailed'
|
|
498
582
|
formatterName: string
|
|
499
583
|
message: string
|
|
584
|
+
type: 'formatFailed'
|
|
585
|
+
}
|
|
586
|
+
| {
|
|
587
|
+
formatterName: string
|
|
588
|
+
type: 'formatting'
|
|
500
589
|
}
|
|
501
590
|
| {
|
|
502
|
-
type: 'complete'
|
|
503
591
|
result: GenerationResult
|
|
592
|
+
type: 'complete'
|
|
504
593
|
}
|
|
594
|
+
| {
|
|
595
|
+
schemaTypesCount: number
|
|
596
|
+
type: 'schemaTypesGenerated'
|
|
597
|
+
}
|
|
598
|
+
| {
|
|
599
|
+
type: 'schemaLoaded'
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* The project and dataset a schema belongs to.
|
|
604
|
+
* @beta
|
|
605
|
+
*/
|
|
606
|
+
export declare interface TypegenResource {
|
|
607
|
+
dataset: string
|
|
608
|
+
projectId: string
|
|
609
|
+
}
|
|
505
610
|
|
|
506
611
|
/** @public */
|
|
507
612
|
export declare const TypegenWatchModeTrace: DefinedTelemetryTrace<
|
|
@@ -1 +1 @@
|
|
|
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,
|
|
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 TypegenResource,\n type TypegenWorkerChannel,\n} from '../typescript/typeGenerator.js'\nexport {\n type EvaluatedModule,\n type EvaluatedProjection,\n type EvaluatedQuery,\n type ExtractedModule,\n type ExtractedProjection,\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,QAGR,iCAAgC;AACvC,SAOEC,oBAAoB,QACf,yBAAwB"}
|
|
@@ -16,7 +16,7 @@ import { processTypegenWorkerStream } from './streamProcessor.js';
|
|
|
16
16
|
* @returns Generation result containing the generated code and statistics
|
|
17
17
|
* @public
|
|
18
18
|
*/ export async function runTypegenGenerate(options) {
|
|
19
|
-
const { config,
|
|
19
|
+
const { config, extractedSchema, onProgress, resource, workDir } = 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
|
|
@@ -27,7 +27,10 @@ import { processTypegenWorkerStream } from './streamProcessor.js';
|
|
|
27
27
|
// set up worker
|
|
28
28
|
const workerPath = new URL('../actions/typegenGenerate.worker.js', import.meta.url);
|
|
29
29
|
const workerData = {
|
|
30
|
+
// Structured-cloned into the worker. An extracted schema is plain JSON, so it survives.
|
|
31
|
+
extractedSchema,
|
|
30
32
|
overloadClientMethods,
|
|
33
|
+
resource,
|
|
31
34
|
schemaPath: schema,
|
|
32
35
|
searchPath: path,
|
|
33
36
|
workDir
|
|
@@ -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 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,
|
|
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, extractedSchema, onProgress, resource, workDir} = 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 // Structured-cloned into the worker. An extracted schema is plain JSON, so it survives.\n extractedSchema,\n overloadClientMethods,\n resource,\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","extractedSchema","onProgress","resource","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,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,eAAe,EAAEC,UAAU,EAAEC,QAAQ,EAAEC,OAAO,EAAC,GAAGL;IAEjE,MAAM,EAACM,mBAAmB,EAAEC,SAAS,EAAEC,qBAAqB,EAAEC,IAAI,EAAEC,MAAM,EAAC,GACzEd,cAAcK;IAEhB,MAAMU,aAAapB,WAAWgB,aAAaA,YAAYf,KAAKa,SAASE;IAErE,sCAAsC;IACtC,MAAMK,YAAYtB,QAAQqB;IAC1B,MAAMtB,MAAMuB,WAAW;QAACC,WAAW;IAAI;IAEvC,gBAAgB;IAChB,MAAMC,aAAa,IAAIC,IAAI,wCAAwC,YAAYC,GAAG;IAClF,MAAMC,aAA6C;QACjD,wFAAwF;QACxFf;QACAM;QACAJ;QACAc,YAAYR;QACZS,YAAYV;QACZJ;IACF;IACA,MAAMe,SAAS,IAAI1B,OAAOoB,YAAY;QAACrB;QAAKwB;IAAU;IAEtD,IAAI;QACF,MAAMI,SAAS,MAAMvB,2BACnBH,sBAAsB2B,IAAI,CAAuBF,SACjD;YACEd;YACAC,WAAWI;YACXH;YACAC;YACAC;QACF,GACAP;QAGF,OAAOkB;IACT,EAAE,OAAOE,KAAK;QACZ1B,MAAM,0BAA0B0B;QAChC,MAAMA;IACR,SAAU;QACRH,OAAOI,SAAS;IAClB;AACF"}
|
|
@@ -11,8 +11,7 @@ if (isMainThread || !parentPort) {
|
|
|
11
11
|
throw new Error('This module must be run as a worker thread');
|
|
12
12
|
}
|
|
13
13
|
registerBabel();
|
|
14
|
-
async function
|
|
15
|
-
const report = WorkerChannelReporter.from(parentPort);
|
|
14
|
+
async function loadSchema(schemaPath, workDir) {
|
|
16
15
|
const fullPath = isAbsolute(schemaPath) ? schemaPath : join(workDir, schemaPath);
|
|
17
16
|
try {
|
|
18
17
|
const schemaStats = await stat(fullPath);
|
|
@@ -29,7 +28,11 @@ async function main({ overloadClientMethods, schemaPath, searchPath, workDir })
|
|
|
29
28
|
}
|
|
30
29
|
throw err;
|
|
31
30
|
}
|
|
32
|
-
|
|
31
|
+
return readSchema(fullPath);
|
|
32
|
+
}
|
|
33
|
+
async function main({ extractedSchema, overloadClientMethods, resource, schemaPath, searchPath, workDir }) {
|
|
34
|
+
const report = WorkerChannelReporter.from(parentPort);
|
|
35
|
+
const schema = extractedSchema ?? await loadSchema(schemaPath, workDir);
|
|
33
36
|
report.event.loadedSchema();
|
|
34
37
|
const typeGenerator = new TypeGenerator();
|
|
35
38
|
const { files, queries } = findQueriesInPath({
|
|
@@ -43,9 +46,11 @@ async function main({ overloadClientMethods, schemaPath, searchPath, workDir })
|
|
|
43
46
|
overloadClientMethods,
|
|
44
47
|
queries,
|
|
45
48
|
reporter: report,
|
|
49
|
+
resource,
|
|
46
50
|
root: workDir,
|
|
47
51
|
schema,
|
|
48
|
-
|
|
52
|
+
// Only a schema read from disk has a path worth naming in the output.
|
|
53
|
+
schemaPath: extractedSchema ? undefined : schemaPath
|
|
49
54
|
});
|
|
50
55
|
report.event.typegenComplete(result);
|
|
51
56
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/actions/typegenGenerate.worker.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport {isAbsolute, join} from 'node:path'\nimport {isMainThread, parentPort, workerData} from 'node:worker_threads'\n\nimport {WorkerChannelReporter} from '@sanity/worker-channels'\n\nimport {readSchema} from '../readSchema.js'\nimport {findQueriesInPath} from '../typescript/findQueriesInPath.js'\nimport {getResolver} from '../typescript/moduleResolver.js'\nimport {registerBabel} from '../typescript/registerBabel.js'\nimport {TypeGenerator} from '../typescript/typeGenerator.js'\nimport {TypegenGenerateTypesWorkerData, TypegenWorkerChannel} from './types.js'\n\nif (isMainThread || !parentPort) {\n throw new Error('This module must be run as a worker thread')\n}\n\nregisterBabel()\n\nasync function
|
|
1
|
+
{"version":3,"sources":["../../src/actions/typegenGenerate.worker.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport {isAbsolute, join} from 'node:path'\nimport {isMainThread, parentPort, workerData} from 'node:worker_threads'\n\nimport {WorkerChannelReporter} from '@sanity/worker-channels'\n\nimport {readSchema} from '../readSchema.js'\nimport {findQueriesInPath} from '../typescript/findQueriesInPath.js'\nimport {getResolver} from '../typescript/moduleResolver.js'\nimport {registerBabel} from '../typescript/registerBabel.js'\nimport {TypeGenerator} from '../typescript/typeGenerator.js'\nimport {TypegenGenerateTypesWorkerData, TypegenWorkerChannel} from './types.js'\n\nif (isMainThread || !parentPort) {\n throw new Error('This module must be run as a worker thread')\n}\n\nregisterBabel()\n\nasync function loadSchema(schemaPath: string, workDir: string) {\n const fullPath = isAbsolute(schemaPath) ? schemaPath : join(workDir, schemaPath)\n\n try {\n const schemaStats = await stat(fullPath)\n if (!schemaStats.isFile()) {\n throw new Error(`Schema path is not a file: ${schemaPath}`)\n }\n } catch (err) {\n if (err instanceof Error && 'code' in err && err.code === 'ENOENT') {\n // If the user has not provided a specific schema path (eg we're using the default), give some help\n const hint = schemaPath === './schema.json' ? ` - did you run \"sanity schema extract\"?` : ''\n throw new Error(`Schema file not found: ${fullPath}${hint}`, {cause: err})\n }\n throw err\n }\n\n return readSchema(fullPath)\n}\n\nasync function main({\n extractedSchema,\n overloadClientMethods,\n resource,\n schemaPath,\n searchPath,\n workDir,\n}: TypegenGenerateTypesWorkerData) {\n const report = WorkerChannelReporter.from<TypegenWorkerChannel>(parentPort)\n\n const schema = extractedSchema ?? (await loadSchema(schemaPath, workDir))\n\n report.event.loadedSchema()\n\n const typeGenerator = new TypeGenerator()\n\n const {files, queries} = findQueriesInPath({\n path: searchPath,\n resolver: getResolver(workDir),\n })\n report.event.typegenStarted({expectedFileCount: files.length})\n\n const result = await typeGenerator.generateTypes({\n overloadClientMethods,\n queries,\n reporter: report,\n resource,\n root: workDir,\n schema,\n // Only a schema read from disk has a path worth naming in the output.\n schemaPath: extractedSchema ? undefined : schemaPath,\n })\n report.event.typegenComplete(result)\n}\n\nawait main(workerData)\n"],"names":["stat","isAbsolute","join","isMainThread","parentPort","workerData","WorkerChannelReporter","readSchema","findQueriesInPath","getResolver","registerBabel","TypeGenerator","Error","loadSchema","schemaPath","workDir","fullPath","schemaStats","isFile","err","code","hint","cause","main","extractedSchema","overloadClientMethods","resource","searchPath","report","from","schema","event","loadedSchema","typeGenerator","files","queries","path","resolver","typegenStarted","expectedFileCount","length","result","generateTypes","reporter","root","undefined","typegenComplete"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AACrC,SAAQC,UAAU,EA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AAC,GAAG3B,kBAAkB;QACzC4B,MAAMT;QACNU,UAAU5B,YAAYM;IACxB;IACAa,OAAOG,KAAK,CAACO,cAAc,CAAC;QAACC,mBAAmBL,MAAMM,MAAM;IAAA;IAE5D,MAAMC,SAAS,MAAMR,cAAcS,aAAa,CAAC;QAC/CjB;QACAU;QACAQ,UAAUf;QACVF;QACAkB,MAAM7B;QACNe;QACA,sEAAsE;QACtEhB,YAAYU,kBAAkBqB,YAAY/B;IAC5C;IACAc,OAAOG,KAAK,CAACe,eAAe,CAACL;AAC/B;AAEA,MAAMlB,KAAKlB"}
|
|
@@ -47,7 +47,8 @@ const IGNORED_PATTERNS = [
|
|
|
47
47
|
}
|
|
48
48
|
/**
|
|
49
49
|
* Starts a file watcher that triggers typegen on changes.
|
|
50
|
-
* Watches
|
|
50
|
+
* Watches query files (via patterns) and the schema JSON file. With `extractedSchema`, the
|
|
51
|
+
* schema is fixed for the life of the watcher, so only query files are watched.
|
|
51
52
|
* Implements debouncing and concurrency control to prevent multiple generations.
|
|
52
53
|
* @public
|
|
53
54
|
*/ export function runTypegenWatcher(options) {
|
|
@@ -78,7 +79,7 @@ const IGNORED_PATTERNS = [
|
|
|
78
79
|
];
|
|
79
80
|
const absoluteQueryPatterns = paths.map((pattern)=>isAbsolute(pattern) ? pattern : join(workDir, pattern));
|
|
80
81
|
const absoluteSchemaPath = isAbsolute(schema) ? schema : join(workDir, schema);
|
|
81
|
-
const watchTargets = [
|
|
82
|
+
const watchTargets = options.extractedSchema ? absoluteQueryPatterns : [
|
|
82
83
|
...absoluteQueryPatterns,
|
|
83
84
|
absoluteSchemaPath
|
|
84
85
|
];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/actions/typegenWatch.ts"],"sourcesContent":["import {error, log} from 'node:console'\nimport {isAbsolute, join, relative} from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {type FSWatcher, watch} from 'chokidar'\nimport debounce from 'lodash-es/debounce.js'\nimport mean from 'lodash-es/mean.js'\n\nimport {TypegenWatchModeTraceAttributes} from '../typegen.telemetry.js'\nimport {prepareConfig} from '../utils/config.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 */\ninterface 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 */\nfunction 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
|
|
1
|
+
{"version":3,"sources":["../../src/actions/typegenWatch.ts"],"sourcesContent":["import {error, log} from 'node:console'\nimport {isAbsolute, join, relative} from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {type FSWatcher, watch} from 'chokidar'\nimport debounce from 'lodash-es/debounce.js'\nimport mean from 'lodash-es/mean.js'\n\nimport {TypegenWatchModeTraceAttributes} from '../typegen.telemetry.js'\nimport {prepareConfig} from '../utils/config.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 */\ninterface 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 */\nfunction 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 query files (via patterns) and the schema JSON file. With `extractedSchema`, the\n * schema is fixed for the life of the watcher, so only query files are watched.\n * Implements debouncing and concurrency control to prevent multiple generations.\n * @public\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} = prepareConfig(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 (err) {\n const errorMessage = err instanceof Error ? err.message : err\n error(` ${styleText('red', '›')} ${errorMessage}`)\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 = options.extractedSchema\n ? absoluteQueryPatterns\n : [...absoluteQueryPatterns, absoluteSchemaPath]\n\n // perform initial generation\n debouncedGenerate()\n\n // set up watcher\n const watcher = 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 log(`[${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":["error","log","isAbsolute","join","relative","styleText","watch","debounce","mean","prepareConfig","runTypegenGenerate","IGNORED_PATTERNS","createTypegenRunner","onGenerate","state","isGenerating","pendingGeneration","runGeneration","runTypegenWatcher","options","config","workDir","path","schema","stats","failedCount","startTime","Date","now","successfulDurations","duration","push","err","errorMessage","Error","message","debouncedGenerate","paths","Array","isArray","absoluteQueryPatterns","map","pattern","absoluteSchemaPath","watchTargets","extractedSchema","watcher","cwd","ignored","ignoreInitial","on","event","filePath","timestamp","toLocaleTimeString","relativePath","getStats","averageGenerationDuration","generationFailedCount","generationSuccessfulCount","length","watcherDuration","stop","close"],"mappings":"AAAA,SAAQA,KAAK,EAAEC,GAAG,QAAO,eAAc;AACvC,SAAQC,UAAU,EAAEC,IAAI,EAAEC,QAAQ,QAAO,YAAW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+1 @@
|
|
|
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 | {
|
|
1
|
+
{"version":3,"sources":["../../src/actions/types.ts"],"sourcesContent":["import {WorkerChannel} from '@sanity/worker-channels'\nimport {type SchemaType} from 'groq-js'\n\nimport {TypeGenConfig} from '../readConfig.js'\nimport {\n type TypegenWorkerChannel as CodegenTypegenWorkerChannel,\n type TypegenResource,\n} 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 /** An extracted schema to use instead of reading `schemaPath`. */\n extractedSchema?: SchemaType\n /** Whether to generate client method overloads */\n overloadClientMethods?: boolean\n /** Register output under this resource. See `GenerateTypesOptions.resource`. */\n resource?: TypegenResource\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 | {\n errors: string[]\n evaluatedFiles: number\n expectedFileCount: number\n queriesCount: number\n queryFilesCount: number\n type: 'moduleEvaluated'\n }\n | {expectedFileCount: number; type: 'typegenStarted'}\n | {formatterName: string; message: string; type: 'formatFailed'}\n | {formatterName: string; type: 'formatting'}\n | {result: GenerationResult; type: 'complete'}\n | {schemaTypesCount: number; type: 'schemaTypesGenerated'}\n | {type: 'schemaLoaded'}\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 /**\n * An extracted schema to generate from, used instead of reading `config.schema` from disk.\n * Same shape as the output of `sanity schema extract`. Pass this when the schema is extracted\n * in memory, for example after fetching and compiling a dataset's schema, so it does not have\n * to be written to a temporary file first. The watcher then watches query files only.\n * @beta\n */\n extractedSchema?: SchemaType\n\n /** Optional progress reporter. Called synchronously as generation proceeds. */\n onProgress?: (event: TypegenProgressEvent) => void\n\n /**\n * Also register the generated types under this project and dataset. See\n * `GenerateTypesOptions.resource`.\n * @beta\n */\n resource?: TypegenResource\n}\n"],"names":[],"mappings":"AAiFA;;;CAGC,GACD,WAyBC"}
|
|
@@ -2,6 +2,9 @@ import * as t from '@babel/types';
|
|
|
2
2
|
export const INTERNAL_REFERENCE_SYMBOL = t.identifier('internalGroqTypeReferenceTo');
|
|
3
3
|
export const ALL_SANITY_SCHEMA_TYPES = t.identifier('AllSanitySchemaTypes');
|
|
4
4
|
export const SANITY_QUERIES = t.identifier('SanityQueries');
|
|
5
|
+
export const SANITY_SCHEMAS_BY_RESOURCE = t.identifier('SanitySchemasByResource');
|
|
6
|
+
export const SANITY_QUERIES_BY_RESOURCE = t.identifier('SanityQueriesByResource');
|
|
7
|
+
export const SANITY_PROJECTIONS_BY_RESOURCE = t.identifier('SanityProjectionsByResource');
|
|
5
8
|
export const ARRAY_OF = t.identifier('ArrayOf');
|
|
6
9
|
export const RESERVED_IDENTIFIERS = new Set();
|
|
7
10
|
RESERVED_IDENTIFIERS.add(SANITY_QUERIES.name);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/typescript/constants.ts"],"sourcesContent":["import * as t from '@babel/types'\n\nexport const INTERNAL_REFERENCE_SYMBOL = t.identifier('internalGroqTypeReferenceTo')\nexport const ALL_SANITY_SCHEMA_TYPES = t.identifier('AllSanitySchemaTypes')\nexport const SANITY_QUERIES = t.identifier('SanityQueries')\nexport const ARRAY_OF = t.identifier('ArrayOf')\n\nexport const RESERVED_IDENTIFIERS = new Set<string>()\nRESERVED_IDENTIFIERS.add(SANITY_QUERIES.name)\nRESERVED_IDENTIFIERS.add(ALL_SANITY_SCHEMA_TYPES.name)\nRESERVED_IDENTIFIERS.add(INTERNAL_REFERENCE_SYMBOL.name)\nRESERVED_IDENTIFIERS.add(ARRAY_OF.name)\n"],"names":["t","INTERNAL_REFERENCE_SYMBOL","identifier","ALL_SANITY_SCHEMA_TYPES","SANITY_QUERIES","ARRAY_OF","RESERVED_IDENTIFIERS","Set","add","name"],"mappings":"AAAA,YAAYA,OAAO,eAAc;AAEjC,OAAO,MAAMC,4BAA4BD,EAAEE,UAAU,CAAC,+BAA8B;AACpF,OAAO,MAAMC,0BAA0BH,EAAEE,UAAU,CAAC,wBAAuB;AAC3E,OAAO,MAAME,iBAAiBJ,EAAEE,UAAU,CAAC,iBAAgB;AAC3D,OAAO,MAAMG,
|
|
1
|
+
{"version":3,"sources":["../../src/typescript/constants.ts"],"sourcesContent":["import * as t from '@babel/types'\n\nexport const INTERNAL_REFERENCE_SYMBOL = t.identifier('internalGroqTypeReferenceTo')\nexport const ALL_SANITY_SCHEMA_TYPES = t.identifier('AllSanitySchemaTypes')\nexport const SANITY_QUERIES = t.identifier('SanityQueries')\nexport const SANITY_SCHEMAS_BY_RESOURCE = t.identifier('SanitySchemasByResource')\nexport const SANITY_QUERIES_BY_RESOURCE = t.identifier('SanityQueriesByResource')\nexport const SANITY_PROJECTIONS_BY_RESOURCE = t.identifier('SanityProjectionsByResource')\nexport const ARRAY_OF = t.identifier('ArrayOf')\n\nexport const RESERVED_IDENTIFIERS = new Set<string>()\nRESERVED_IDENTIFIERS.add(SANITY_QUERIES.name)\nRESERVED_IDENTIFIERS.add(ALL_SANITY_SCHEMA_TYPES.name)\nRESERVED_IDENTIFIERS.add(INTERNAL_REFERENCE_SYMBOL.name)\nRESERVED_IDENTIFIERS.add(ARRAY_OF.name)\n"],"names":["t","INTERNAL_REFERENCE_SYMBOL","identifier","ALL_SANITY_SCHEMA_TYPES","SANITY_QUERIES","SANITY_SCHEMAS_BY_RESOURCE","SANITY_QUERIES_BY_RESOURCE","SANITY_PROJECTIONS_BY_RESOURCE","ARRAY_OF","RESERVED_IDENTIFIERS","Set","add","name"],"mappings":"AAAA,YAAYA,OAAO,eAAc;AAEjC,OAAO,MAAMC,4BAA4BD,EAAEE,UAAU,CAAC,+BAA8B;AACpF,OAAO,MAAMC,0BAA0BH,EAAEE,UAAU,CAAC,wBAAuB;AAC3E,OAAO,MAAME,iBAAiBJ,EAAEE,UAAU,CAAC,iBAAgB;AAC3D,OAAO,MAAMG,6BAA6BL,EAAEE,UAAU,CAAC,2BAA0B;AACjF,OAAO,MAAMI,6BAA6BN,EAAEE,UAAU,CAAC,2BAA0B;AACjF,OAAO,MAAMK,iCAAiCP,EAAEE,UAAU,CAAC,+BAA8B;AACzF,OAAO,MAAMM,WAAWR,EAAEE,UAAU,CAAC,WAAU;AAE/C,OAAO,MAAMO,uBAAuB,IAAIC,MAAa;AACrDD,qBAAqBE,GAAG,CAACP,eAAeQ,IAAI;AAC5CH,qBAAqBE,GAAG,CAACR,wBAAwBS,IAAI;AACrDH,qBAAqBE,GAAG,CAACV,0BAA0BW,IAAI;AACvDH,qBAAqBE,GAAG,CAACH,SAASI,IAAI"}
|
|
@@ -3,7 +3,7 @@ import path from 'node:path';
|
|
|
3
3
|
import { traverse } from '@babel/core';
|
|
4
4
|
import { Scope } from '@babel/traverse';
|
|
5
5
|
import * as babelTypes from '@babel/types';
|
|
6
|
-
import createDebug from '
|
|
6
|
+
import { createDebug } from 'obug';
|
|
7
7
|
import { formatPath } from '../utils/formatPath.js';
|
|
8
8
|
import { parseSourceFile } from './parseSource.js';
|
|
9
9
|
const debug = createDebug('sanity:codegen:findQueries:debug');
|