@sanity/codegen 7.0.3 → 8.1.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 +26 -0
- package/dist/_exports/index.d.ts +62 -44
- 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/readConfig.js +15 -15
- package/dist/readConfig.js.map +1 -1
- package/dist/safeParseQuery.js.map +1 -1
- package/dist/typescript/helpers.js +19 -0
- package/dist/typescript/helpers.js.map +1 -1
- package/dist/typescript/typeGenerator.js +28 -7
- package/dist/typescript/typeGenerator.js.map +1 -1
- package/dist/utils/debug.js +2 -2
- package/dist/utils/debug.js.map +1 -1
- package/package.json +12 -16
- 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/README.md
CHANGED
|
@@ -1,3 +1,29 @@
|
|
|
1
1
|
# @sanity/codegen
|
|
2
2
|
|
|
3
3
|
Codegen toolkit for Sanity.io, used to generate Typescript types for a Sanity Schema & GROQ queries.
|
|
4
|
+
|
|
5
|
+
## Typed `client.fetch` results
|
|
6
|
+
|
|
7
|
+
With `overloadClientMethods` enabled (the default), the generated file ends with a query type map that registers every query it found, so `client.fetch(query)` in `@sanity/client`, and `sanityFetch({query})` in `next-sanity`, return the generated result type without a generic:
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
// Query TypeMap
|
|
11
|
+
declare global {
|
|
12
|
+
interface SanityQueries {
|
|
13
|
+
'*[_type == "post"]': PostsQueryResult
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
// Lets @sanity/client releases that predate the global registry read it too
|
|
17
|
+
declare module '@sanity/client' {
|
|
18
|
+
interface SanityQueries extends globalThis.SanityQueries {}
|
|
19
|
+
}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The two blocks serve different `@sanity/client` releases, and the same generated file works with all of them:
|
|
23
|
+
|
|
24
|
+
- The `declare global` block is the registry. `@sanity/client` releases that know about it read it directly, and because it is a global interface rather than a module augmentation, it does not depend on module resolution: it is seen whether or not `@sanity/client` is a direct dependency of the project that holds the generated file, however many copies of the client are installed (a copy nested inside `next-sanity` reads the same registry), and from every entry point, `@sanity/client/stega` included.
|
|
25
|
+
- The `declare module '@sanity/client'` block is a bridge for releases that only read the `SanityQueries` interface exported from `@sanity/client`, which is every release since 6.21.0. Interface merging unions the `extends` clauses of an interface's declarations, so the bridge makes that interface inherit the global registry. On releases that already inherit it, the bridge is a duplicate `extends` of the same type, which TypeScript accepts.
|
|
26
|
+
|
|
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
|
+
|
|
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.
|
package/dist/_exports/index.d.ts
CHANGED
|
@@ -1,17 +1,12 @@
|
|
|
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'
|
|
7
|
+
import * as v from 'valibot'
|
|
12
8
|
import {WorkerChannel} from '@sanity/worker-channels'
|
|
13
9
|
import {WorkerChannelReporter} from '@sanity/worker-channels'
|
|
14
|
-
import * as z from 'zod/mini'
|
|
15
10
|
|
|
16
11
|
/**
|
|
17
12
|
* @deprecated use TypeGenConfig
|
|
@@ -22,27 +17,31 @@ export declare type CodegenConfig = TypeGenConfig
|
|
|
22
17
|
/**
|
|
23
18
|
* @public
|
|
24
19
|
*/
|
|
25
|
-
export declare const configDefinition:
|
|
20
|
+
export declare const configDefinition: v.ObjectSchema<
|
|
26
21
|
{
|
|
27
|
-
formatGeneratedCode:
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
prettier: 'prettier'
|
|
34
|
-
}>,
|
|
35
|
-
]
|
|
36
|
-
>
|
|
22
|
+
readonly formatGeneratedCode: v.OptionalSchema<
|
|
23
|
+
v.UnionSchema<
|
|
24
|
+
[v.BooleanSchema<undefined>, v.PicklistSchema<['oxfmt', 'prettier'], undefined>],
|
|
25
|
+
undefined
|
|
26
|
+
>,
|
|
27
|
+
true
|
|
37
28
|
>
|
|
38
|
-
generates:
|
|
39
|
-
overloadClientMethods:
|
|
40
|
-
path:
|
|
41
|
-
|
|
29
|
+
readonly generates: v.OptionalSchema<v.StringSchema<undefined>, './sanity.types.ts'>
|
|
30
|
+
readonly overloadClientMethods: v.OptionalSchema<v.BooleanSchema<undefined>, true>
|
|
31
|
+
readonly path: v.OptionalSchema<
|
|
32
|
+
v.UnionSchema<
|
|
33
|
+
[v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>],
|
|
34
|
+
undefined
|
|
35
|
+
>,
|
|
36
|
+
readonly [
|
|
37
|
+
'./src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',
|
|
38
|
+
'./app/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',
|
|
39
|
+
'./sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',
|
|
40
|
+
]
|
|
42
41
|
>
|
|
43
|
-
schema:
|
|
42
|
+
readonly schema: v.OptionalSchema<v.StringSchema<undefined>, './schema.json'>
|
|
44
43
|
},
|
|
45
|
-
|
|
44
|
+
undefined
|
|
46
45
|
>
|
|
47
46
|
|
|
48
47
|
/**
|
|
@@ -387,7 +386,7 @@ export declare function registerBabel(babelOptions?: TransformOptions): void
|
|
|
387
386
|
* Runs a single typegen generation.
|
|
388
387
|
*
|
|
389
388
|
* This is the programmatic API for generating TypeScript types from GROQ queries.
|
|
390
|
-
* It spawns a worker thread to perform the generation and
|
|
389
|
+
* It spawns a worker thread to perform the generation and reports progress via the optional `onProgress` callback.
|
|
391
390
|
*
|
|
392
391
|
* @param options - Configuration options including typegen config and working directory
|
|
393
392
|
* @returns Generation result containing the generated code and statistics
|
|
@@ -397,7 +396,6 @@ export declare function runTypegenGenerate(options: RunTypegenOptions): Promise<
|
|
|
397
396
|
|
|
398
397
|
/**
|
|
399
398
|
* Options for running a single typegen generation.
|
|
400
|
-
* This is the programmatic API for one-off generation without file watching.
|
|
401
399
|
* @public
|
|
402
400
|
*/
|
|
403
401
|
export declare interface RunTypegenOptions {
|
|
@@ -405,8 +403,8 @@ export declare interface RunTypegenOptions {
|
|
|
405
403
|
workDir: string
|
|
406
404
|
/** Typegen configuration */
|
|
407
405
|
config?: Partial<TypeGenConfig>
|
|
408
|
-
/** Optional
|
|
409
|
-
|
|
406
|
+
/** Optional progress reporter. Called synchronously as generation proceeds. */
|
|
407
|
+
onProgress?: (event: TypegenProgressEvent) => void
|
|
410
408
|
}
|
|
411
409
|
|
|
412
410
|
/**
|
|
@@ -446,7 +444,7 @@ declare interface TypeEvaluationStats {
|
|
|
446
444
|
}
|
|
447
445
|
|
|
448
446
|
/** @public */
|
|
449
|
-
export declare type TypeGenConfig =
|
|
447
|
+
export declare type TypeGenConfig = v.InferOutput<typeof configDefinition>
|
|
450
448
|
|
|
451
449
|
/**
|
|
452
450
|
* A class used to generate TypeScript types from a given schema
|
|
@@ -467,23 +465,43 @@ export declare class TypeGenerator {
|
|
|
467
465
|
}
|
|
468
466
|
|
|
469
467
|
/**
|
|
470
|
-
*
|
|
468
|
+
* A progress event emitted during a single typegen run.
|
|
469
|
+
* Consumers (e.g. the Sanity CLI) render these; the library performs no terminal output.
|
|
470
|
+
* @public
|
|
471
471
|
*/
|
|
472
|
-
export declare
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
472
|
+
export declare type TypegenProgressEvent =
|
|
473
|
+
| {
|
|
474
|
+
type: 'schemaLoaded'
|
|
475
|
+
}
|
|
476
|
+
| {
|
|
477
|
+
type: 'typegenStarted'
|
|
478
|
+
expectedFileCount: number
|
|
479
|
+
}
|
|
480
|
+
| {
|
|
481
|
+
type: 'schemaTypesGenerated'
|
|
482
|
+
schemaTypesCount: number
|
|
483
|
+
}
|
|
484
|
+
| {
|
|
485
|
+
type: 'moduleEvaluated'
|
|
486
|
+
evaluatedFiles: number
|
|
487
|
+
expectedFileCount: number
|
|
488
|
+
queriesCount: number
|
|
489
|
+
queryFilesCount: number
|
|
490
|
+
errors: string[]
|
|
491
|
+
}
|
|
492
|
+
| {
|
|
493
|
+
type: 'formatting'
|
|
494
|
+
formatterName: string
|
|
495
|
+
}
|
|
496
|
+
| {
|
|
497
|
+
type: 'formatFailed'
|
|
498
|
+
formatterName: string
|
|
499
|
+
message: string
|
|
500
|
+
}
|
|
501
|
+
| {
|
|
502
|
+
type: 'complete'
|
|
503
|
+
result: GenerationResult
|
|
504
|
+
}
|
|
487
505
|
|
|
488
506
|
/** @public */
|
|
489
507
|
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":"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"}
|
|
@@ -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"}
|
package/dist/readConfig.js
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises';
|
|
2
2
|
import json5 from 'json5';
|
|
3
|
-
import * as
|
|
3
|
+
import * as v from 'valibot';
|
|
4
4
|
/**
|
|
5
5
|
* @public
|
|
6
|
-
*/ export const configDefinition =
|
|
7
|
-
formatGeneratedCode:
|
|
8
|
-
|
|
9
|
-
|
|
6
|
+
*/ export const configDefinition = v.object({
|
|
7
|
+
formatGeneratedCode: v.optional(v.union([
|
|
8
|
+
v.boolean(),
|
|
9
|
+
v.picklist([
|
|
10
10
|
'oxfmt',
|
|
11
11
|
'prettier'
|
|
12
12
|
])
|
|
13
13
|
]), true),
|
|
14
|
-
generates:
|
|
15
|
-
overloadClientMethods:
|
|
16
|
-
path:
|
|
17
|
-
|
|
18
|
-
|
|
14
|
+
generates: v.optional(v.string(), './sanity.types.ts'),
|
|
15
|
+
overloadClientMethods: v.optional(v.boolean(), true),
|
|
16
|
+
path: v.optional(v.union([
|
|
17
|
+
v.string(),
|
|
18
|
+
v.array(v.string())
|
|
19
19
|
]), [
|
|
20
20
|
'./src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',
|
|
21
21
|
'./app/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',
|
|
22
22
|
'./sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}'
|
|
23
23
|
]),
|
|
24
|
-
schema:
|
|
24
|
+
schema: v.optional(v.string(), './schema.json')
|
|
25
25
|
});
|
|
26
26
|
/**
|
|
27
27
|
* Read, parse and process a config file
|
|
@@ -31,15 +31,15 @@ import * as z from 'zod/mini';
|
|
|
31
31
|
const content = await readFile(path, 'utf8');
|
|
32
32
|
// eslint-disable-next-line import-x/no-named-as-default-member -- json5 is CJS and doesn't support named exports
|
|
33
33
|
const json = json5.parse(content);
|
|
34
|
-
return
|
|
34
|
+
return v.parseAsync(configDefinition, json);
|
|
35
35
|
} catch (error) {
|
|
36
|
-
if (
|
|
37
|
-
throw new TypeError(`Error in config file\n ${error.issues.map((
|
|
36
|
+
if (v.isValiError(error)) {
|
|
37
|
+
throw new TypeError(`Error in config file\n ${error.issues.map((issue)=>issue.message).join('\n')}`, {
|
|
38
38
|
cause: error
|
|
39
39
|
});
|
|
40
40
|
}
|
|
41
41
|
if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {
|
|
42
|
-
return
|
|
42
|
+
return v.parse(configDefinition, {});
|
|
43
43
|
}
|
|
44
44
|
throw error;
|
|
45
45
|
}
|
package/dist/readConfig.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/readConfig.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport json5 from 'json5'\nimport * as
|
|
1
|
+
{"version":3,"sources":["../src/readConfig.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport json5 from 'json5'\nimport * as v from 'valibot'\n\n/**\n * The formatter to use for generated code.\n * - `false` - Do not format generated code.\n * - `true` | `'prettier'` - Format with prettier.\n * - `'oxfmt'` - Format with oxfmt. Throws if oxfmt is not installed.\n * @public\n */\nexport type FormatGeneratedCode = 'oxfmt' | 'prettier' | boolean\n\n/**\n * @public\n */\nexport const configDefinition = v.object({\n formatGeneratedCode: v.optional(v.union([v.boolean(), v.picklist(['oxfmt', 'prettier'])]), true),\n generates: v.optional(v.string(), './sanity.types.ts'),\n overloadClientMethods: v.optional(v.boolean(), true),\n path: v.optional(v.union([v.string(), v.array(v.string())]), [\n './src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',\n './app/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',\n './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n ]),\n schema: v.optional(v.string(), './schema.json'),\n})\n\n/** @public */\nexport type TypeGenConfig = v.InferOutput<typeof configDefinition>\n\n/**\n * @deprecated use TypeGenConfig\n * @public\n */\nexport type CodegenConfig = TypeGenConfig\n\n/**\n * Read, parse and process a config file\n * @internal\n */\nexport async function readConfig(path: string): Promise<TypeGenConfig> {\n try {\n const content = await readFile(path, 'utf8')\n // eslint-disable-next-line import-x/no-named-as-default-member -- json5 is CJS and doesn't support named exports\n const json = json5.parse(content)\n return v.parseAsync(configDefinition, json)\n } catch (error) {\n if (v.isValiError(error)) {\n throw new TypeError(\n `Error in config file\\n ${error.issues.map((issue) => issue.message).join('\\n')}`,\n {cause: error},\n )\n }\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return v.parse(configDefinition, {})\n }\n\n throw error\n }\n}\n"],"names":["readFile","json5","v","configDefinition","object","formatGeneratedCode","optional","union","boolean","picklist","generates","string","overloadClientMethods","path","array","schema","readConfig","content","json","parse","parseAsync","error","isValiError","TypeError","issues","map","issue","message","join","cause","code"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAEzC,OAAOC,WAAW,QAAO;AACzB,YAAYC,OAAO,UAAS;AAW5B;;CAEC,GACD,OAAO,MAAMC,mBAAmBD,EAAEE,MAAM,CAAC;IACvCC,qBAAqBH,EAAEI,QAAQ,CAACJ,EAAEK,KAAK,CAAC;QAACL,EAAEM,OAAO;QAAIN,EAAEO,QAAQ,CAAC;YAAC;YAAS;SAAW;KAAE,GAAG;IAC3FC,WAAWR,EAAEI,QAAQ,CAACJ,EAAES,MAAM,IAAI;IAClCC,uBAAuBV,EAAEI,QAAQ,CAACJ,EAAEM,OAAO,IAAI;IAC/CK,MAAMX,EAAEI,QAAQ,CAACJ,EAAEK,KAAK,CAAC;QAACL,EAAES,MAAM;QAAIT,EAAEY,KAAK,CAACZ,EAAES,MAAM;KAAI,GAAG;QAC3D;QACA;QACA;KACD;IACDI,QAAQb,EAAEI,QAAQ,CAACJ,EAAES,MAAM,IAAI;AACjC,GAAE;AAWF;;;CAGC,GACD,OAAO,eAAeK,WAAWH,IAAY;IAC3C,IAAI;QACF,MAAMI,UAAU,MAAMjB,SAASa,MAAM;QACrC,iHAAiH;QACjH,MAAMK,OAAOjB,MAAMkB,KAAK,CAACF;QACzB,OAAOf,EAAEkB,UAAU,CAACjB,kBAAkBe;IACxC,EAAE,OAAOG,OAAO;QACd,IAAInB,EAAEoB,WAAW,CAACD,QAAQ;YACxB,MAAM,IAAIE,UACR,CAAC,uBAAuB,EAAEF,MAAMG,MAAM,CAACC,GAAG,CAAC,CAACC,QAAUA,MAAMC,OAAO,EAAEC,IAAI,CAAC,OAAO,EACjF;gBAACC,OAAOR;YAAK;QAEjB;QACA,IAAI,OAAOA,UAAU,YAAYA,UAAU,QAAQ,UAAUA,SAASA,MAAMS,IAAI,KAAK,UAAU;YAC7F,OAAO5B,EAAEiB,KAAK,CAAChB,kBAAkB,CAAC;QACpC;QAEA,MAAMkB;IACR;AACF"}
|
|
@@ -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"}
|
|
@@ -70,6 +70,25 @@ export function weakMapMemo(fn) {
|
|
|
70
70
|
export function generateCode(node) {
|
|
71
71
|
return `${new CodeGenerator(node).generate().code.trim()}\n\n`;
|
|
72
72
|
}
|
|
73
|
+
/**
|
|
74
|
+
* Builds a `declare global { … }` block.
|
|
75
|
+
*/ export function tsDeclareGlobal(body) {
|
|
76
|
+
const declaration = t.tsModuleDeclaration(t.identifier('global'), t.tsModuleBlock(body));
|
|
77
|
+
declaration.declare = true;
|
|
78
|
+
// Babel 7's generator reads the keyword from `global`, Babel 8's from `kind`; set both so the
|
|
79
|
+
// output is `declare global {` on either.
|
|
80
|
+
declaration.global = true;
|
|
81
|
+
declaration.kind = 'global';
|
|
82
|
+
return declaration;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Builds a `declare module "<name>" { … }` block.
|
|
86
|
+
*/ export function tsDeclareModule(name, body) {
|
|
87
|
+
const declaration = t.tsModuleDeclaration(t.stringLiteral(name), t.tsModuleBlock(body));
|
|
88
|
+
declaration.declare = true;
|
|
89
|
+
declaration.kind = 'module';
|
|
90
|
+
return declaration;
|
|
91
|
+
}
|
|
73
92
|
export function getFilterArrayUnionType(typeNode, predicate) {
|
|
74
93
|
if (typeNode.of.type !== 'union') {
|
|
75
94
|
return typeNode;
|