@sanity/codegen 3.87.1 → 3.88.1-typegen-experimental.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/lib/index.d.mts +282 -85
- package/lib/index.d.ts +282 -85
- package/lib/index.js +537 -172
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +538 -173
- package/lib/index.mjs.map +1 -1
- package/package.json +15 -17
- package/src/_exports/index.ts +14 -3
- package/src/readConfig.ts +71 -23
- package/src/readSchema.ts +0 -1
- package/src/typescript/asyncQueue.ts +100 -0
- package/src/typescript/expressionResolvers.ts +4 -3
- package/src/typescript/findQueriesInPath.ts +9 -2
- package/src/typescript/findQueriesInSource.ts +22 -6
- package/src/typescript/schemaTypeGenerator.ts +381 -0
- package/src/typescript/typeGenerator.ts +445 -306
package/lib/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import fs$1, { readFile } from "node:fs/promises";
|
|
2
2
|
import * as json5 from "json5";
|
|
3
3
|
import * as z from "zod";
|
|
4
|
-
import { parse } from "groq-js";
|
|
4
|
+
import { parse, typeEvaluate } from "groq-js";
|
|
5
5
|
import createDebug from "debug";
|
|
6
6
|
import glob from "globby";
|
|
7
7
|
import fs, { existsSync } from "node:fs";
|
|
@@ -13,29 +13,44 @@ import traverse, { Scope } from "@babel/traverse";
|
|
|
13
13
|
import { loadConfig, createMatchPath } from "tsconfig-paths";
|
|
14
14
|
import register from "@babel/register";
|
|
15
15
|
import { CodeGenerator } from "@babel/generator";
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
]),
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
16
|
+
const defaultPaths = [
|
|
17
|
+
"./src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro}",
|
|
18
|
+
"./app/**/*.{ts,tsx,js,jsx,mjs,cjs}",
|
|
19
|
+
"./sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}"
|
|
20
|
+
], rawConfigSchema = z.object({
|
|
21
|
+
path: z.union([z.string(), z.array(z.string())]).optional(),
|
|
22
|
+
generates: z.string().optional(),
|
|
23
|
+
formatGeneratedCode: z.boolean().optional(),
|
|
24
|
+
overloadClientMethods: z.boolean().optional(),
|
|
25
|
+
augmentGroqModule: z.boolean().optional(),
|
|
26
|
+
schema: z.string().optional(),
|
|
27
|
+
unstable_schemas: z.array(z.object({ schemaPath: z.string(), schemaId: z.string() })).optional()
|
|
28
|
+
}).superRefine((data, ctx) => {
|
|
29
|
+
data.schema !== void 0 && data.unstable_schemas !== void 0 && ctx.addIssue({
|
|
30
|
+
code: z.ZodIssueCode.custom,
|
|
31
|
+
message: 'Configuration cannot contain both "schema" and "unstable_schemas". Use one or the other.'
|
|
32
|
+
});
|
|
33
|
+
}).refine((d) => d.unstable_schemas === void 0 || d.unstable_schemas.length > 0, {
|
|
34
|
+
message: '"unstable_schemas" array cannot be empty. Please provide at least one schema definition or use the "schema" property instead.'
|
|
35
|
+
}), normalizedConfigSchema = rawConfigSchema.transform((d) => ({
|
|
36
|
+
path: typeof d.path == "string" ? [d.path] : d.path ?? defaultPaths,
|
|
37
|
+
generates: d.generates ?? "./sanity.types.ts",
|
|
38
|
+
formatGeneratedCode: d.formatGeneratedCode ?? !0,
|
|
39
|
+
overloadClientMethods: d.overloadClientMethods ?? !0,
|
|
40
|
+
augmentGroqModule: d.augmentGroqModule ?? !0,
|
|
41
|
+
schemas: d.unstable_schemas ? d.unstable_schemas.map((s) => ({
|
|
42
|
+
schemaPath: s.schemaPath,
|
|
43
|
+
schemaId: s.schemaId
|
|
44
|
+
})) : [{ schemaId: "default", schemaPath: d.schema ?? "./schema.json" }]
|
|
45
|
+
})), DEFAULT_CONFIG = normalizedConfigSchema.parse({});
|
|
27
46
|
async function readConfig(path2) {
|
|
28
47
|
try {
|
|
29
48
|
const content = await readFile(path2, "utf-8"), json = json5.parse(content);
|
|
30
|
-
return
|
|
49
|
+
return normalizedConfigSchema.parse(json);
|
|
31
50
|
} catch (error) {
|
|
32
|
-
|
|
33
|
-
throw new Error(`Error in config file
|
|
51
|
+
throw error instanceof z.ZodError ? new Error(`Error in config file
|
|
34
52
|
${error.errors.map((err) => err.message).join(`
|
|
35
|
-
`)}`);
|
|
36
|
-
if (typeof error == "object" && error !== null && "code" in error && error.code === "ENOENT")
|
|
37
|
-
return configDefintion.parse({});
|
|
38
|
-
throw error;
|
|
53
|
+
`)}`) : error;
|
|
39
54
|
}
|
|
40
55
|
}
|
|
41
56
|
async function readSchema(path2) {
|
|
@@ -88,7 +103,7 @@ function parseAstro(source) {
|
|
|
88
103
|
`)).join(`
|
|
89
104
|
`) : "";
|
|
90
105
|
}
|
|
91
|
-
const debug$2 = createDebug("sanity:codegen:findQueries:debug"), TAGGED_TEMPLATE_ALLOW_LIST = ["groq"], FUNCTION_WRAPPER_ALLOW_LIST = ["defineQuery"];
|
|
106
|
+
const debug$2 = createDebug("sanity:codegen:findQueries:debug"), TAGGED_TEMPLATE_ALLOW_LIST = ["groq"], FUNCTION_WRAPPER_ALLOW_LIST = ["defineQuery", "defineProjection"];
|
|
92
107
|
function resolveExpression({
|
|
93
108
|
node,
|
|
94
109
|
file,
|
|
@@ -398,19 +413,22 @@ function resolveExportSpecifier({
|
|
|
398
413
|
cause: `noBinding:${importName}`
|
|
399
414
|
});
|
|
400
415
|
}
|
|
401
|
-
const require$1 = createRequire(__filename), groqTagName = "groq", defineQueryFunctionName = "defineQuery", groqModuleName = "groq", nextSanityModuleName = "next-sanity", ignoreValue = "@sanity-typegen-ignore";
|
|
416
|
+
const require$1 = createRequire(__filename), groqTagName = "groq", defineQueryFunctionName = "defineQuery", defineProjectionFunctionName = "defineProjection", groqModuleName = "groq", nextSanityModuleName = "next-sanity", ignoreValue = "@sanity-typegen-ignore";
|
|
402
417
|
function findQueriesInSource(source, filename, babelConfig = getBabelConfig(), resolver = require$1.resolve) {
|
|
403
418
|
const queries = [], file = parseSourceFile(source, filename, babelConfig);
|
|
404
419
|
return traverse$1(file, {
|
|
405
420
|
// Look for variable declarations, e.g. `const myQuery = groq`... and extract the query.
|
|
406
421
|
// The variable name is used as the name of the query result type
|
|
407
422
|
VariableDeclarator(path2) {
|
|
408
|
-
const { node, scope } = path2, init = node.init, isGroqTemplateTag = t.isTaggedTemplateExpression(init) && t.isIdentifier(init.tag) && init.tag.name === groqTagName,
|
|
409
|
-
if (t.isIdentifier(node.id) && (isGroqTemplateTag ||
|
|
423
|
+
const { node, scope } = path2, init = node.init, isGroqTemplateTag = t.isTaggedTemplateExpression(init) && t.isIdentifier(init.tag) && init.tag.name === groqTagName, isDefineCall = t.isCallExpression(init) && (isImportFrom(groqModuleName, defineQueryFunctionName, scope, init.callee) || isImportFrom(groqModuleName, defineProjectionFunctionName, scope, init.callee) || isImportFrom(nextSanityModuleName, defineQueryFunctionName, scope, init.callee));
|
|
424
|
+
if (t.isIdentifier(node.id) && (isGroqTemplateTag || isDefineCall)) {
|
|
410
425
|
if (declarationLeadingCommentContains(path2, ignoreValue))
|
|
411
426
|
return;
|
|
412
|
-
const queryName = `${node.id.name}
|
|
413
|
-
|
|
427
|
+
const queryName = `${node.id.name}`;
|
|
428
|
+
let resultType = "query", expressionToResolve = init;
|
|
429
|
+
isDefineCall && (init.arguments.length > 0 && t.isExpression(init.arguments[0]) && (expressionToResolve = init.arguments[0]), isImportFrom(groqModuleName, defineProjectionFunctionName, scope, init.callee) && (resultType = "projection"));
|
|
430
|
+
const queryResult = resolveExpression({
|
|
431
|
+
node: expressionToResolve,
|
|
414
432
|
file,
|
|
415
433
|
scope,
|
|
416
434
|
babelConfig,
|
|
@@ -424,7 +442,7 @@ function findQueriesInSource(source, filename, babelConfig = getBabelConfig(), r
|
|
|
424
442
|
...node.loc?.end
|
|
425
443
|
}
|
|
426
444
|
} : {};
|
|
427
|
-
queries.push({ name: queryName, result: queryResult, location });
|
|
445
|
+
queries.push({ name: queryName, result: queryResult, type: resultType, location });
|
|
428
446
|
}
|
|
429
447
|
}
|
|
430
448
|
}), queries;
|
|
@@ -492,6 +510,7 @@ async function* findQueriesInPath({
|
|
|
492
510
|
// we never want to look in node_modules
|
|
493
511
|
onlyFiles: !0
|
|
494
512
|
}).sort();
|
|
513
|
+
yield { type: "files", fileCount: files.length };
|
|
495
514
|
for (const filename of files)
|
|
496
515
|
if (typeof filename == "string") {
|
|
497
516
|
debug(`Found file "${filename}"`);
|
|
@@ -514,118 +533,100 @@ function registerBabel(babelOptions) {
|
|
|
514
533
|
const options = babelOptions || getBabelConfig();
|
|
515
534
|
register({ ...options, extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"] });
|
|
516
535
|
}
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
//
|
|
520
|
-
|
|
521
|
-
//
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
this.schema = schema, this.schema.forEach((s) => {
|
|
528
|
-
this.getTypeName(s.name, s);
|
|
529
|
-
});
|
|
530
|
-
}
|
|
536
|
+
class AsyncQueue {
|
|
537
|
+
// Internal state:
|
|
538
|
+
// `queue`: Holds items yet to be consumed.
|
|
539
|
+
// `resume`: A callback to signal the consumer when new items arrive or the queue finishes/errors.
|
|
540
|
+
// `finished`: Flag indicating if the producer is done adding items (via `finish` or `throwError`).
|
|
541
|
+
// `pendingError`: Stores an error passed to `throwError`, to be thrown by the consumer.
|
|
542
|
+
queue = [];
|
|
543
|
+
resume = null;
|
|
544
|
+
finished = !1;
|
|
545
|
+
pendingError = null;
|
|
531
546
|
/**
|
|
532
|
-
*
|
|
533
|
-
* @returns string
|
|
534
|
-
* @internal
|
|
535
|
-
* @beta
|
|
547
|
+
* Enqueues an item. Throws if `finish` or `throwError` has been called.
|
|
536
548
|
*/
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
if (!schemaName)
|
|
542
|
-
throw new Error(`Schema name not found for schema ${schema.name}`);
|
|
543
|
-
schemaNames.add(schemaName);
|
|
544
|
-
const typeAlias = t.tsTypeAliasDeclaration(t.identifier(schemaName), null, typeLiteral);
|
|
545
|
-
typeDeclarations.push(t.exportNamedDeclaration(typeAlias));
|
|
546
|
-
}), typeDeclarations.push(
|
|
547
|
-
t.exportNamedDeclaration(
|
|
548
|
-
t.tsTypeAliasDeclaration(
|
|
549
|
-
t.identifier(this.getTypeName(ALL_SCHEMA_TYPES)),
|
|
550
|
-
null,
|
|
551
|
-
t.tsUnionType(
|
|
552
|
-
[...schemaNames].map((typeName) => t.tsTypeReference(t.identifier(typeName)))
|
|
553
|
-
)
|
|
554
|
-
)
|
|
555
|
-
)
|
|
556
|
-
), typeDeclarations.map((decl) => new CodeGenerator(decl).generate().code).join(`
|
|
557
|
-
|
|
558
|
-
`);
|
|
549
|
+
enqueue(item) {
|
|
550
|
+
if (this.finished)
|
|
551
|
+
throw new Error("Cannot enqueue items to a finished AsyncQueue.");
|
|
552
|
+
this.queue.push(item), this.resume && (this.resume(), this.resume = null);
|
|
559
553
|
}
|
|
560
554
|
/**
|
|
561
|
-
*
|
|
562
|
-
* @param identifierName - The name of the type to generated
|
|
563
|
-
* @param typeNode - The type node to generate the type for
|
|
564
|
-
* @returns
|
|
565
|
-
* @internal
|
|
566
|
-
* @beta
|
|
555
|
+
* Signals that no more items will be enqueued. Idempotent.
|
|
567
556
|
*/
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
return new CodeGenerator(t.exportNamedDeclaration(typeAlias)).generate().code.trim();
|
|
571
|
-
}
|
|
572
|
-
static generateKnownTypes() {
|
|
573
|
-
const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword());
|
|
574
|
-
typeOperator.operator = "unique";
|
|
575
|
-
const identifier = t.identifier(REFERENCE_SYMBOL_NAME);
|
|
576
|
-
identifier.typeAnnotation = t.tsTypeAnnotation(typeOperator);
|
|
577
|
-
const decleration = t.variableDeclaration("const", [t.variableDeclarator(identifier)]);
|
|
578
|
-
return decleration.declare = !0, new CodeGenerator(t.exportNamedDeclaration(decleration)).generate().code.trim();
|
|
557
|
+
finish() {
|
|
558
|
+
this.finished || (this.finished = !0, this.resume && (this.resume(), this.resume = null));
|
|
579
559
|
}
|
|
580
560
|
/**
|
|
581
|
-
*
|
|
582
|
-
* for SanityClient to consume.
|
|
583
|
-
*
|
|
584
|
-
* Note: only types that have previously been generated with `generateTypeNodeTypes`
|
|
585
|
-
* will be included in the query map.
|
|
586
|
-
*
|
|
587
|
-
* @param queries - A list of queries to generate a type declaration for
|
|
588
|
-
* @returns
|
|
589
|
-
* @internal
|
|
590
|
-
* @beta
|
|
561
|
+
* Signals an error occurred during production. Finishes the queue. Idempotent.
|
|
591
562
|
*/
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
for (const query of queries) {
|
|
595
|
-
const name = this.typeNodeNameMap.get(query.typeNode);
|
|
596
|
-
name && (typesByQuerystring[query.query] ??= [], typesByQuerystring[query.query].push(name));
|
|
597
|
-
}
|
|
598
|
-
const queryReturnInterface = t.tsInterfaceDeclaration(
|
|
599
|
-
t.identifier("SanityQueries"),
|
|
600
|
-
null,
|
|
601
|
-
[],
|
|
602
|
-
t.tsInterfaceBody(
|
|
603
|
-
Object.entries(typesByQuerystring).map(([query, types]) => t.tsPropertySignature(
|
|
604
|
-
t.stringLiteral(query),
|
|
605
|
-
t.tsTypeAnnotation(
|
|
606
|
-
t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type))))
|
|
607
|
-
)
|
|
608
|
-
))
|
|
609
|
-
)
|
|
610
|
-
), declareModule = t.declareModule(
|
|
611
|
-
t.stringLiteral("@sanity/client"),
|
|
612
|
-
t.blockStatement([queryReturnInterface])
|
|
613
|
-
), clientImport = t.importDeclaration([], t.stringLiteral("@sanity/client"));
|
|
614
|
-
return new CodeGenerator(t.program([clientImport, declareModule])).generate().code.trim();
|
|
563
|
+
throwError(error) {
|
|
564
|
+
this.finished || (this.pendingError = error, this.finished = !0, this.resume && (this.resume(), this.resume = null));
|
|
615
565
|
}
|
|
616
566
|
/**
|
|
617
|
-
*
|
|
618
|
-
*
|
|
619
|
-
* When we reference a type we also keep track of the original name so we can reference the correct type later.
|
|
567
|
+
* Async iterator to consume enqueued items.
|
|
568
|
+
* Throws if `throwError` was called.
|
|
620
569
|
*/
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
570
|
+
async *[Symbol.asyncIterator]() {
|
|
571
|
+
for (; ; ) {
|
|
572
|
+
if (this.pendingError)
|
|
573
|
+
throw this.pendingError;
|
|
574
|
+
if (this.queue.length === 0 && !this.finished && (await new Promise((resolve2) => {
|
|
575
|
+
this.resume = resolve2;
|
|
576
|
+
}), this.pendingError))
|
|
577
|
+
throw this.pendingError;
|
|
578
|
+
for (; this.queue.length > 0; )
|
|
579
|
+
yield this.queue.shift();
|
|
580
|
+
if (this.finished && this.queue.length === 0)
|
|
581
|
+
break;
|
|
582
|
+
}
|
|
583
|
+
if (this.pendingError)
|
|
584
|
+
throw this.pendingError;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
class SchemaTypeGenerator {
|
|
588
|
+
static ProjectionBase = t.identifier("ProjectionBase");
|
|
589
|
+
static InternalReferenceSymbol = Object.assign(t.identifier("internalGroqTypeReferenceTo"), {
|
|
590
|
+
typeAnnotation: t.tsTypeAnnotation(
|
|
591
|
+
Object.assign(t.tsTypeOperator(t.tsSymbolKeyword()), { operator: "unique" })
|
|
592
|
+
)
|
|
593
|
+
});
|
|
594
|
+
static sanitizeIdentifier(input) {
|
|
595
|
+
return `${input.replace(/^\d/, "_").replace(/[^$\w]+(.)/g, (_, char) => char.toUpperCase())}`;
|
|
596
|
+
}
|
|
597
|
+
static normalizeIdentifier(input) {
|
|
598
|
+
const sanitized = SchemaTypeGenerator.sanitizeIdentifier(input);
|
|
599
|
+
return `${sanitized.charAt(0).toUpperCase()}${sanitized.slice(1)}`;
|
|
600
|
+
}
|
|
601
|
+
schema;
|
|
602
|
+
schemaId;
|
|
603
|
+
typeNames = /* @__PURE__ */ new Set();
|
|
604
|
+
tsTypes = /* @__PURE__ */ new Map();
|
|
605
|
+
identifiers = /* @__PURE__ */ new Map();
|
|
606
|
+
constructor({ schema, schemaId }) {
|
|
607
|
+
this.schemaId = schemaId, this.schema = schema;
|
|
608
|
+
for (const type of schema) {
|
|
609
|
+
if (this.typeNames.has(type.name))
|
|
610
|
+
throw new Error(
|
|
611
|
+
`Duplicate type name "${type.name}" in schema "${schemaId}". Type names must be unique within the same schema.`
|
|
612
|
+
);
|
|
613
|
+
this.typeNames.add(type.name);
|
|
614
|
+
}
|
|
615
|
+
const uniqueIdentifiers = /* @__PURE__ */ new Set();
|
|
616
|
+
for (const type of schema) {
|
|
617
|
+
const desiredName = SchemaTypeGenerator.normalizeIdentifier(type.name);
|
|
618
|
+
let resultingName = desiredName, index = 2;
|
|
619
|
+
for (; uniqueIdentifiers.has(resultingName); )
|
|
620
|
+
resultingName = `${desiredName}_${index}`, index++;
|
|
621
|
+
uniqueIdentifiers.add(resultingName), this.identifiers.set(type.name, t.identifier(resultingName));
|
|
622
|
+
}
|
|
623
|
+
for (const type of schema)
|
|
624
|
+
this.tsTypes.set(type.name, this.generateTsType(type));
|
|
625
|
+
}
|
|
626
|
+
shouldOmitProjection({ rest, attributes }) {
|
|
627
|
+
return rest?.type === "unknown" || rest?.type === "object" && this.shouldOmitProjection(rest) ? !0 : Object.values(attributes).every((attr) => attr.value.type === "null");
|
|
628
|
+
}
|
|
629
|
+
generateTsType(typeNode) {
|
|
629
630
|
switch (typeNode.type) {
|
|
630
631
|
case "string":
|
|
631
632
|
return typeNode.value !== void 0 ? t.tsLiteralType(t.stringLiteral(typeNode.value)) : t.tsStringKeyword();
|
|
@@ -636,9 +637,9 @@ class TypeGenerator {
|
|
|
636
637
|
case "unknown":
|
|
637
638
|
return t.tsUnknownKeyword();
|
|
638
639
|
case "document":
|
|
639
|
-
return this.
|
|
640
|
+
return this.generateDocumentTsType(typeNode);
|
|
640
641
|
case "type":
|
|
641
|
-
return this.
|
|
642
|
+
return this.generateTsType(typeNode.value);
|
|
642
643
|
case "array":
|
|
643
644
|
return this.generateArrayTsType(typeNode);
|
|
644
645
|
case "object":
|
|
@@ -650,21 +651,21 @@ class TypeGenerator {
|
|
|
650
651
|
case "null":
|
|
651
652
|
return t.tsNullKeyword();
|
|
652
653
|
default:
|
|
653
|
-
throw new Error(
|
|
654
|
+
throw new Error(
|
|
655
|
+
`Encountered unsupported node type "${// @ts-expect-error This should never happen
|
|
656
|
+
typeNode.type}" while generating schema types for schema "${this.schemaId}"`
|
|
657
|
+
);
|
|
654
658
|
}
|
|
655
659
|
}
|
|
656
660
|
// Helper function used to generate TS types for array type nodes.
|
|
657
661
|
generateArrayTsType(typeNode) {
|
|
658
|
-
const typeNodes = this.
|
|
659
|
-
return t.tsTypeReference(
|
|
660
|
-
t.identifier("Array"),
|
|
661
|
-
t.tsTypeParameterInstantiation([typeNodes])
|
|
662
|
-
);
|
|
662
|
+
const typeNodes = this.generateTsType(typeNode.of);
|
|
663
|
+
return t.tsTypeReference(t.identifier("Array"), t.tsTypeParameterInstantiation([typeNodes]));
|
|
663
664
|
}
|
|
664
665
|
// Helper function used to generate TS types for object properties.
|
|
665
|
-
|
|
666
|
-
const type = this.
|
|
667
|
-
t.identifier(sanitizeIdentifier(key)),
|
|
666
|
+
generateTsObjectProperty(key, attribute) {
|
|
667
|
+
const type = this.generateTsType(attribute.value), propertySignature = t.tsPropertySignature(
|
|
668
|
+
t.identifier(SchemaTypeGenerator.sanitizeIdentifier(key)),
|
|
668
669
|
t.tsTypeAnnotation(type)
|
|
669
670
|
);
|
|
670
671
|
return propertySignature.optional = attribute.optional, propertySignature;
|
|
@@ -673,16 +674,16 @@ class TypeGenerator {
|
|
|
673
674
|
generateObjectTsType(typeNode) {
|
|
674
675
|
const props = [];
|
|
675
676
|
Object.entries(typeNode.attributes).forEach(([key, attribute]) => {
|
|
676
|
-
props.push(this.
|
|
677
|
+
props.push(this.generateTsObjectProperty(key, attribute));
|
|
677
678
|
});
|
|
678
679
|
const rest = typeNode.rest;
|
|
679
|
-
if (rest
|
|
680
|
+
if (rest)
|
|
680
681
|
switch (rest.type) {
|
|
681
682
|
case "unknown":
|
|
682
683
|
return t.tsUnknownKeyword();
|
|
683
684
|
case "object": {
|
|
684
685
|
Object.entries(rest.attributes).forEach(([key, attribute]) => {
|
|
685
|
-
props.push(this.
|
|
686
|
+
props.push(this.generateTsObjectProperty(key, attribute));
|
|
686
687
|
});
|
|
687
688
|
break;
|
|
688
689
|
}
|
|
@@ -693,56 +694,420 @@ class TypeGenerator {
|
|
|
693
694
|
default:
|
|
694
695
|
throw new Error(`Type "${rest.type}" not found in schema`);
|
|
695
696
|
}
|
|
696
|
-
if (typeNode.dereferencesTo
|
|
697
|
-
const derefType =
|
|
698
|
-
t.
|
|
699
|
-
|
|
697
|
+
if (typeNode.dereferencesTo) {
|
|
698
|
+
const derefType = Object.assign(
|
|
699
|
+
t.tsPropertySignature(
|
|
700
|
+
SchemaTypeGenerator.InternalReferenceSymbol,
|
|
701
|
+
t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo)))
|
|
702
|
+
),
|
|
703
|
+
{ computed: !0, optional: !0 }
|
|
700
704
|
);
|
|
701
|
-
|
|
705
|
+
props.push(derefType);
|
|
702
706
|
}
|
|
703
707
|
return t.tsTypeLiteral(props);
|
|
704
708
|
}
|
|
705
709
|
generateInlineTsType(typeNode) {
|
|
706
|
-
const
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
{
|
|
714
|
-
type: "CommentLine",
|
|
715
|
-
value: ` Unable to locate the referenced type "${typeNode.name}" in schema`
|
|
716
|
-
}
|
|
717
|
-
], missing;
|
|
718
|
-
}
|
|
719
|
-
const generatedName = this.typeNameMap.get(referencedTypeNode.name);
|
|
720
|
-
return generatedName ? t.tsTypeReference(t.identifier(generatedName)) : t.tsUnknownKeyword();
|
|
710
|
+
const identifier = this.getIdentifier(typeNode.name);
|
|
711
|
+
return identifier ? t.tsTypeReference(identifier) : t.addComment(
|
|
712
|
+
t.tsUnknownKeyword(),
|
|
713
|
+
"trailing",
|
|
714
|
+
` Unable to locate the referenced type "${typeNode.name}" in schema "${this.schemaId}"`,
|
|
715
|
+
!0
|
|
716
|
+
);
|
|
721
717
|
}
|
|
722
718
|
// Helper function used to generate TS types for union type nodes.
|
|
723
719
|
generateUnionTsType(typeNode) {
|
|
724
|
-
|
|
725
|
-
return t.tsNeverKeyword();
|
|
726
|
-
if (typeNode.of.length === 1)
|
|
727
|
-
return this.getTypeNodeType(typeNode.of[0]);
|
|
728
|
-
const typeNodes = typeNode.of.map((node) => this.getTypeNodeType(node));
|
|
729
|
-
return t.tsUnionType(typeNodes);
|
|
720
|
+
return typeNode.of.length === 0 ? t.tsNeverKeyword() : typeNode.of.length === 1 ? this.generateTsType(typeNode.of[0]) : t.tsUnionType(typeNode.of.map((node) => this.generateTsType(node)));
|
|
730
721
|
}
|
|
731
722
|
// Helper function used to generate TS types for document type nodes.
|
|
732
|
-
|
|
723
|
+
generateDocumentTsType(document) {
|
|
733
724
|
const props = Object.entries(document.attributes).map(
|
|
734
|
-
([key, node]) => this.
|
|
725
|
+
([key, node]) => this.generateTsObjectProperty(key, node)
|
|
735
726
|
);
|
|
736
727
|
return t.tsTypeLiteral(props);
|
|
737
728
|
}
|
|
729
|
+
getTypeNames() {
|
|
730
|
+
return Array.from(this.typeNames);
|
|
731
|
+
}
|
|
732
|
+
getTsType(typeName) {
|
|
733
|
+
return this.tsTypes.get(typeName);
|
|
734
|
+
}
|
|
735
|
+
getIdentifier(typeName) {
|
|
736
|
+
return this.identifiers.get(typeName);
|
|
737
|
+
}
|
|
738
|
+
evaluateQuery(query) {
|
|
739
|
+
const ast = safeParseQuery(query), typeNode = typeEvaluate(ast, this.schema), tsType = this.generateTsType(typeNode), stats = walkAndCountQueryTypeNodeStats(typeNode);
|
|
740
|
+
return { tsType, stats };
|
|
741
|
+
}
|
|
742
|
+
evaluateProjection(projection) {
|
|
743
|
+
const results = [];
|
|
744
|
+
for (const schemaType of this.schema) {
|
|
745
|
+
if (schemaType.type !== "document") continue;
|
|
746
|
+
if (safeParseQuery(projection).type !== "Object")
|
|
747
|
+
throw new Error(
|
|
748
|
+
`Invalid projection syntax: Projections must be enclosed in curly braces, (e.g., "{_id, title}"). Received: "${projection}"`
|
|
749
|
+
);
|
|
750
|
+
const ast = safeParseQuery(`* [_type==${JSON.stringify(schemaType.name)}] ${projection} [0]`), result = typeEvaluate(ast, this.schema);
|
|
751
|
+
if (result.type !== "union" || result.of.length !== 2) continue;
|
|
752
|
+
const projectionResult = result.of.find((node) => node.type !== "null");
|
|
753
|
+
if (projectionResult?.type !== "object" || this.shouldOmitProjection(projectionResult)) continue;
|
|
754
|
+
const stats = walkAndCountQueryTypeNodeStats(projectionResult), tsType = t.tsTypeReference(
|
|
755
|
+
SchemaTypeGenerator.ProjectionBase,
|
|
756
|
+
t.tsTypeParameterInstantiation([
|
|
757
|
+
this.generateTsType(projectionResult),
|
|
758
|
+
t.tsLiteralType(t.stringLiteral(schemaType.name))
|
|
759
|
+
])
|
|
760
|
+
);
|
|
761
|
+
results.push({ tsType, stats });
|
|
762
|
+
}
|
|
763
|
+
if (!results.length) return null;
|
|
764
|
+
if (results.length === 1) return results[0];
|
|
765
|
+
const combinedTsType = t.tsUnionType(results.map((i) => i.tsType)), accumulatedStats = results.reduce(
|
|
766
|
+
(acc, { stats }) => ({
|
|
767
|
+
allTypes: acc.allTypes + stats.allTypes,
|
|
768
|
+
emptyUnions: acc.emptyUnions + stats.emptyUnions,
|
|
769
|
+
unknownTypes: acc.unknownTypes + stats.unknownTypes
|
|
770
|
+
}),
|
|
771
|
+
{ allTypes: 0, unknownTypes: 0, emptyUnions: 0 }
|
|
772
|
+
);
|
|
773
|
+
return accumulatedStats.allTypes += 1, { tsType: combinedTsType, stats: accumulatedStats };
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
function walkAndCountQueryTypeNodeStats(typeNode) {
|
|
777
|
+
switch (typeNode.type) {
|
|
778
|
+
case "unknown":
|
|
779
|
+
return { allTypes: 1, unknownTypes: 1, emptyUnions: 0 };
|
|
780
|
+
case "array": {
|
|
781
|
+
const acc = walkAndCountQueryTypeNodeStats(typeNode.of);
|
|
782
|
+
return acc.allTypes += 1, acc;
|
|
783
|
+
}
|
|
784
|
+
case "object": {
|
|
785
|
+
if (typeNode.rest && typeNode.rest.type === "unknown")
|
|
786
|
+
return { allTypes: 2, unknownTypes: 1, emptyUnions: 0 };
|
|
787
|
+
const restStats = typeNode.rest ? walkAndCountQueryTypeNodeStats(typeNode.rest) : { allTypes: 0, unknownTypes: 0, emptyUnions: 0 };
|
|
788
|
+
return restStats.allTypes += 1, Object.values(typeNode.attributes).reduce((acc, attribute) => {
|
|
789
|
+
const { allTypes, unknownTypes, emptyUnions } = walkAndCountQueryTypeNodeStats(
|
|
790
|
+
attribute.value
|
|
791
|
+
);
|
|
792
|
+
return {
|
|
793
|
+
allTypes: acc.allTypes + allTypes,
|
|
794
|
+
unknownTypes: acc.unknownTypes + unknownTypes,
|
|
795
|
+
emptyUnions: acc.emptyUnions + emptyUnions
|
|
796
|
+
};
|
|
797
|
+
}, restStats);
|
|
798
|
+
}
|
|
799
|
+
case "union":
|
|
800
|
+
return typeNode.of.length === 0 ? { allTypes: 1, unknownTypes: 0, emptyUnions: 1 } : typeNode.of.reduce(
|
|
801
|
+
(acc, type) => {
|
|
802
|
+
const { allTypes, unknownTypes, emptyUnions } = walkAndCountQueryTypeNodeStats(type);
|
|
803
|
+
return {
|
|
804
|
+
allTypes: acc.allTypes + allTypes,
|
|
805
|
+
unknownTypes: acc.unknownTypes + unknownTypes,
|
|
806
|
+
emptyUnions: acc.emptyUnions + emptyUnions
|
|
807
|
+
};
|
|
808
|
+
},
|
|
809
|
+
{ allTypes: 1, unknownTypes: 0, emptyUnions: 0 }
|
|
810
|
+
// count the union type itself
|
|
811
|
+
);
|
|
812
|
+
default:
|
|
813
|
+
return { allTypes: 1, unknownTypes: 0, emptyUnions: 0 };
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
const SanityQueries = t.identifier("SanityQueries"), SanityProjections = t.identifier("SanityProjections"), SanitySchemas = t.identifier("SanitySchemas"), SchemaOrigin = t.identifier("SchemaOrigin"), PickSchema = t.identifier("PickSchema"), AllSanitySchemaTypes = t.identifier("AllSanitySchemaTypes");
|
|
817
|
+
class TypeGenerator {
|
|
818
|
+
schemas;
|
|
819
|
+
augmentGroqModule;
|
|
820
|
+
overloadClientMethods;
|
|
821
|
+
schemaFilenames = /* @__PURE__ */ new Map();
|
|
822
|
+
globalIdentifiers = /* @__PURE__ */ new Set();
|
|
823
|
+
identifiersByQuery = /* @__PURE__ */ new Map();
|
|
824
|
+
identifiersByProjection = /* @__PURE__ */ new Map();
|
|
825
|
+
queryResultsQueue = new AsyncQueue();
|
|
826
|
+
augmentedQueryResultsPromise = promiseWithResolvers();
|
|
827
|
+
queryFileCountPromise = promiseWithResolvers();
|
|
828
|
+
constructor({
|
|
829
|
+
schemas,
|
|
830
|
+
queriesByFile,
|
|
831
|
+
augmentGroqModule = !0,
|
|
832
|
+
overloadClientMethods = !0
|
|
833
|
+
}) {
|
|
834
|
+
this.globalIdentifiers.add(SanityQueries.name), this.globalIdentifiers.add(SanityProjections.name), this.globalIdentifiers.add(SanitySchemas.name), this.globalIdentifiers.add(SchemaOrigin.name), this.globalIdentifiers.add(PickSchema.name), this.globalIdentifiers.add(AllSanitySchemaTypes.name), this.globalIdentifiers.add(SchemaTypeGenerator.InternalReferenceSymbol.name), this.globalIdentifiers.add(SchemaTypeGenerator.ProjectionBase.name);
|
|
835
|
+
const schemaIds = /* @__PURE__ */ new Set();
|
|
836
|
+
for (const { schemaId, filename } of schemas) {
|
|
837
|
+
if (schemaIds.has(schemaId))
|
|
838
|
+
throw new Error(`Duplicate schema ID "${schemaId}". Schema IDs must be unique.`);
|
|
839
|
+
schemaIds.add(schemaId), filename && this.schemaFilenames.set(schemaId, filename);
|
|
840
|
+
}
|
|
841
|
+
this.schemas = schemas.map((opts) => new SchemaTypeGenerator(opts)), this.augmentGroqModule = augmentGroqModule, this.overloadClientMethods = overloadClientMethods, this.getSchemaTypeDeclarations(), this.getSchemaDeclarations(), queriesByFile ? this.handleQueries(queriesByFile).catch((error) => {
|
|
842
|
+
this.queryFileCountPromise.reject(error), this.queryResultsQueue.throwError(error), this.augmentedQueryResultsPromise.reject(error);
|
|
843
|
+
}) : this.queryFileCountPromise.resolve({ fileCount: 0 });
|
|
844
|
+
}
|
|
845
|
+
async handleQueries(queriesByFile) {
|
|
846
|
+
for await (const result of queriesByFile) {
|
|
847
|
+
if (result.type === "files") {
|
|
848
|
+
this.queryFileCountPromise.resolve({ fileCount: result.fileCount });
|
|
849
|
+
continue;
|
|
850
|
+
}
|
|
851
|
+
try {
|
|
852
|
+
if (result.type === "error") throw result.error;
|
|
853
|
+
const { filename, queries } = result, queryResultDeclarations = [];
|
|
854
|
+
for (const query of queries)
|
|
855
|
+
try {
|
|
856
|
+
queryResultDeclarations.push({
|
|
857
|
+
filename,
|
|
858
|
+
query: query.result,
|
|
859
|
+
...this.generateQueryResultType({ ...query, filename })
|
|
860
|
+
});
|
|
861
|
+
} catch (error) {
|
|
862
|
+
this.queryResultsQueue.enqueue({ type: "error", filename, error });
|
|
863
|
+
}
|
|
864
|
+
this.queryResultsQueue.enqueue({ type: "queries", filename, queryResultDeclarations });
|
|
865
|
+
} catch (error) {
|
|
866
|
+
this.queryResultsQueue.enqueue({ type: "error", filename: result.filename, error });
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
this.queryResultsQueue.finish();
|
|
870
|
+
let augmentedQueryResultsCode = "";
|
|
871
|
+
const clientModuleBlockStatement = [], groqModuleBlockStatement = [];
|
|
872
|
+
if (this.identifiersByQuery.size > 0) {
|
|
873
|
+
const sanityQueriesInterfaceDeclaration = t.tsInterfaceDeclaration(
|
|
874
|
+
SanityQueries,
|
|
875
|
+
null,
|
|
876
|
+
[],
|
|
877
|
+
t.tsInterfaceBody(
|
|
878
|
+
Array.from(this.identifiersByQuery).map(
|
|
879
|
+
([query, identifiers]) => t.tsPropertySignature(
|
|
880
|
+
t.stringLiteral(query),
|
|
881
|
+
t.tsTypeAnnotation(
|
|
882
|
+
identifiers.length === 1 ? t.tsTypeReference(identifiers[0]) : t.tsUnionType(identifiers.map((i) => t.tsTypeReference(i)))
|
|
883
|
+
)
|
|
884
|
+
)
|
|
885
|
+
)
|
|
886
|
+
)
|
|
887
|
+
);
|
|
888
|
+
clientModuleBlockStatement.push(sanityQueriesInterfaceDeclaration), groqModuleBlockStatement.push(sanityQueriesInterfaceDeclaration);
|
|
889
|
+
}
|
|
890
|
+
if (this.identifiersByProjection.size > 0) {
|
|
891
|
+
const sanityProjectionsInterfaceDeclaration = t.tsInterfaceDeclaration(
|
|
892
|
+
SanityProjections,
|
|
893
|
+
null,
|
|
894
|
+
[],
|
|
895
|
+
t.tsInterfaceBody(
|
|
896
|
+
Array.from(this.identifiersByProjection).map(
|
|
897
|
+
([projection, identifiers]) => t.tsPropertySignature(
|
|
898
|
+
t.stringLiteral(projection),
|
|
899
|
+
t.tsTypeAnnotation(
|
|
900
|
+
identifiers.length === 1 ? t.tsTypeReference(identifiers[0]) : t.tsUnionType(identifiers.map((i) => t.tsTypeReference(i)))
|
|
901
|
+
)
|
|
902
|
+
)
|
|
903
|
+
)
|
|
904
|
+
)
|
|
905
|
+
);
|
|
906
|
+
groqModuleBlockStatement.push(sanityProjectionsInterfaceDeclaration);
|
|
907
|
+
}
|
|
908
|
+
if (this.overloadClientMethods && clientModuleBlockStatement.length > 0) {
|
|
909
|
+
const clientModuleDeclaration = t.declareModule(
|
|
910
|
+
t.stringLiteral("@sanity/client"),
|
|
911
|
+
t.blockStatement(clientModuleBlockStatement)
|
|
912
|
+
);
|
|
913
|
+
augmentedQueryResultsCode += generateCode(clientModuleDeclaration);
|
|
914
|
+
}
|
|
915
|
+
if (this.augmentGroqModule && groqModuleBlockStatement.length > 0) {
|
|
916
|
+
const groqModuleDeclaration = t.declareModule(
|
|
917
|
+
t.stringLiteral("groq"),
|
|
918
|
+
t.blockStatement(groqModuleBlockStatement)
|
|
919
|
+
);
|
|
920
|
+
augmentedQueryResultsCode += generateCode(groqModuleDeclaration);
|
|
921
|
+
}
|
|
922
|
+
this.augmentedQueryResultsPromise.resolve({ code: augmentedQueryResultsCode });
|
|
923
|
+
}
|
|
924
|
+
generateQueryResultType({
|
|
925
|
+
name,
|
|
926
|
+
result,
|
|
927
|
+
type,
|
|
928
|
+
filename
|
|
929
|
+
}) {
|
|
930
|
+
const evaluationResults = [];
|
|
931
|
+
for (const schema of this.schemas) {
|
|
932
|
+
const { schemaId } = schema;
|
|
933
|
+
if (type === "projection") {
|
|
934
|
+
const projectionResult = schema.evaluateProjection(result);
|
|
935
|
+
if (!projectionResult) continue;
|
|
936
|
+
evaluationResults.push({ schemaId, ...projectionResult });
|
|
937
|
+
} else {
|
|
938
|
+
const queryResult = schema.evaluateQuery(result);
|
|
939
|
+
evaluationResults.push({ schemaId, ...queryResult });
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
const tsTypes = evaluationResults.map(({ tsType: tsType2, schemaId }) => this.schemas.length === 1 ? tsType2 : addSchemaOrigin(tsType2, schemaId)), tsType = tsTypes.length === 1 ? tsTypes[0] : t.tsUnionType(tsTypes), { code, id } = this.generateAndRegisterExportedTypeAlias(
|
|
943
|
+
`${name}${type === "projection" ? "ProjectionResult" : "Result"}`,
|
|
944
|
+
tsType,
|
|
945
|
+
[
|
|
946
|
+
{ type: "CommentLine", value: ` Source: ${filename}` },
|
|
947
|
+
{ type: "CommentLine", value: ` Variable: ${name}` },
|
|
948
|
+
{
|
|
949
|
+
type: "CommentLine",
|
|
950
|
+
value: ` ${type === "projection" ? "Projection" : "Query"}: ${result.replace(/(\r\n|\n|\r)/gm, "").trim()}`
|
|
951
|
+
}
|
|
952
|
+
]
|
|
953
|
+
), identifiersByProjectionOrQuery = type === "projection" ? this.identifiersByProjection : this.identifiersByQuery;
|
|
954
|
+
let identifiers = identifiersByProjectionOrQuery.get(result);
|
|
955
|
+
return identifiers || (identifiers = [], identifiersByProjectionOrQuery.set(result, identifiers)), identifiers.push(id), {
|
|
956
|
+
code,
|
|
957
|
+
id,
|
|
958
|
+
name,
|
|
959
|
+
type,
|
|
960
|
+
stats: evaluationResults.reduce(
|
|
961
|
+
(acc, { stats }) => ({
|
|
962
|
+
allTypes: acc.allTypes + stats.allTypes,
|
|
963
|
+
unknownTypes: acc.unknownTypes + stats.unknownTypes,
|
|
964
|
+
emptyUnions: acc.emptyUnions + stats.emptyUnions
|
|
965
|
+
}),
|
|
966
|
+
{ allTypes: 0, unknownTypes: 0, emptyUnions: 0 }
|
|
967
|
+
)
|
|
968
|
+
};
|
|
969
|
+
}
|
|
970
|
+
generateAndRegisterExportedTypeAlias(name, tsType, comments) {
|
|
971
|
+
const desiredName = SchemaTypeGenerator.normalizeIdentifier(name);
|
|
972
|
+
let resultingName = desiredName, index = 2;
|
|
973
|
+
for (; this.globalIdentifiers.has(resultingName); )
|
|
974
|
+
resultingName = `${desiredName}_${index}`, index++;
|
|
975
|
+
this.globalIdentifiers.add(resultingName);
|
|
976
|
+
const id = t.identifier(resultingName), typeAlias = t.tsTypeAliasDeclaration(id, null, tsType);
|
|
977
|
+
let exportDeclaration = t.exportNamedDeclaration(typeAlias);
|
|
978
|
+
comments && (exportDeclaration = t.addComments(exportDeclaration, "leading", comments));
|
|
979
|
+
const code = generateCode(exportDeclaration);
|
|
980
|
+
return { id, code };
|
|
981
|
+
}
|
|
982
|
+
getKnownTypes = computeOnce(() => {
|
|
983
|
+
let code = "";
|
|
984
|
+
this.overloadClientMethods && (code += generateCode(t.importDeclaration([], t.stringLiteral("@sanity/client"))));
|
|
985
|
+
const importSpecifiers = [
|
|
986
|
+
t.importSpecifier(SchemaTypeGenerator.ProjectionBase, SchemaTypeGenerator.ProjectionBase)
|
|
987
|
+
];
|
|
988
|
+
return this.schemas.length > 1 && (importSpecifiers.push(t.importSpecifier(PickSchema, PickSchema)), importSpecifiers.push(t.importSpecifier(SchemaOrigin, SchemaOrigin))), code += generateCode(
|
|
989
|
+
Object.assign(t.importDeclaration(importSpecifiers, t.stringLiteral("groq")), {
|
|
990
|
+
importKind: "type"
|
|
991
|
+
})
|
|
992
|
+
), code += generateCode(
|
|
993
|
+
t.exportNamedDeclaration(
|
|
994
|
+
Object.assign(
|
|
995
|
+
t.variableDeclaration("const", [
|
|
996
|
+
t.variableDeclarator(SchemaTypeGenerator.InternalReferenceSymbol)
|
|
997
|
+
]),
|
|
998
|
+
{ declare: !0 }
|
|
999
|
+
)
|
|
1000
|
+
)
|
|
1001
|
+
), { code };
|
|
1002
|
+
});
|
|
1003
|
+
getSchemaTypeDeclarations = computeOnce(() => {
|
|
1004
|
+
const typeNames = new Set(this.schemas.flatMap((schema) => schema.getTypeNames()));
|
|
1005
|
+
return Array.from(typeNames).flatMap((typeName) => {
|
|
1006
|
+
const identifiers = new Set(
|
|
1007
|
+
this.schemas.map((schema) => schema.getIdentifier(typeName)?.name).filter((i) => typeof i == "string")
|
|
1008
|
+
);
|
|
1009
|
+
return Array.from(identifiers).map((identifier) => {
|
|
1010
|
+
const types = this.schemas.filter(
|
|
1011
|
+
(schema) => schema.getIdentifier(typeName)?.name === identifier && !!schema.getTsType(typeName)
|
|
1012
|
+
).map((schema) => {
|
|
1013
|
+
const tsType2 = schema.getTsType(typeName), schemaId = schema.schemaId;
|
|
1014
|
+
return this.schemas.length < 2 ? { schemaId, tsType: tsType2 } : { schemaId, tsType: addSchemaOrigin(tsType2, schemaId) };
|
|
1015
|
+
}), schemaIds = types.map((i) => i.schemaId), tsType = types.length === 1 ? types[0].tsType : t.tsUnionType(types.map((i) => i.tsType)), { id, code } = this.generateAndRegisterExportedTypeAlias(identifier, tsType);
|
|
1016
|
+
return { id, code, schemaIds };
|
|
1017
|
+
});
|
|
1018
|
+
});
|
|
1019
|
+
});
|
|
1020
|
+
getAllSanitySchemaTypesDeclaration = computeOnce(() => {
|
|
1021
|
+
const schemaTypeDeclarations = this.getSchemaTypeDeclarations();
|
|
1022
|
+
return { code: generateCode(
|
|
1023
|
+
t.exportNamedDeclaration(
|
|
1024
|
+
t.tsTypeAliasDeclaration(
|
|
1025
|
+
AllSanitySchemaTypes,
|
|
1026
|
+
null,
|
|
1027
|
+
t.tsUnionType(schemaTypeDeclarations.map(({ id }) => t.tsTypeReference(id)))
|
|
1028
|
+
)
|
|
1029
|
+
)
|
|
1030
|
+
) };
|
|
1031
|
+
});
|
|
1032
|
+
getSchemaDeclarations = computeOnce(() => {
|
|
1033
|
+
const identifierUsageCountBySchemaId = this.getSchemaTypeDeclarations().reduce((acc, { schemaIds, id }) => {
|
|
1034
|
+
for (const schemaId of schemaIds)
|
|
1035
|
+
acc[schemaId] = acc[schemaId] ?? {}, acc[schemaId][id.name] = schemaIds.length;
|
|
1036
|
+
return acc;
|
|
1037
|
+
}, {});
|
|
1038
|
+
return this.schemas.map(({ schemaId }) => {
|
|
1039
|
+
const tsTypes = Object.entries(identifierUsageCountBySchemaId[schemaId]).map(
|
|
1040
|
+
([identifierName, schemaCount]) => {
|
|
1041
|
+
const schemaTypeReferencer = t.tsTypeReference(t.identifier(identifierName));
|
|
1042
|
+
return schemaCount > 1 ? addPickSchema(schemaTypeReferencer, schemaId) : schemaTypeReferencer;
|
|
1043
|
+
}
|
|
1044
|
+
), tsType = tsTypes.length === 1 ? tsTypes[0] : t.tsUnionType(tsTypes), comments = [], filename = this.schemaFilenames.get(schemaId);
|
|
1045
|
+
filename && comments.push({ type: "CommentLine", value: ` Source: ${filename}` }), comments.push({ type: "CommentLine", value: ` Schema ID: ${schemaId}` });
|
|
1046
|
+
const { id, code } = this.generateAndRegisterExportedTypeAlias(
|
|
1047
|
+
`${schemaId}Schema`,
|
|
1048
|
+
tsType,
|
|
1049
|
+
comments
|
|
1050
|
+
);
|
|
1051
|
+
return { id, code, schemaId };
|
|
1052
|
+
});
|
|
1053
|
+
});
|
|
1054
|
+
getAugmentedSchemasDeclarations = computeOnce(() => {
|
|
1055
|
+
if (!this.augmentGroqModule) return { code: "" };
|
|
1056
|
+
const schemaDeclarations = this.getSchemaDeclarations(), groqModuleDeclaration = t.declareModule(
|
|
1057
|
+
t.stringLiteral("groq"),
|
|
1058
|
+
t.blockStatement([
|
|
1059
|
+
t.tsInterfaceDeclaration(
|
|
1060
|
+
SanitySchemas,
|
|
1061
|
+
null,
|
|
1062
|
+
[],
|
|
1063
|
+
t.tsInterfaceBody(
|
|
1064
|
+
schemaDeclarations.map(
|
|
1065
|
+
({ id, schemaId }) => t.tsPropertySignature(
|
|
1066
|
+
t.stringLiteral(schemaId),
|
|
1067
|
+
t.tsTypeAnnotation(t.tsTypeReference(id))
|
|
1068
|
+
)
|
|
1069
|
+
)
|
|
1070
|
+
)
|
|
1071
|
+
)
|
|
1072
|
+
])
|
|
1073
|
+
);
|
|
1074
|
+
return { code: generateCode(groqModuleDeclaration) };
|
|
1075
|
+
});
|
|
1076
|
+
getQueryFileCount = () => this.queryFileCountPromise.promise;
|
|
1077
|
+
getQueryResultDeclarations = () => this.queryResultsQueue;
|
|
1078
|
+
getAugmentedQueryResultsDeclarations = () => this.augmentedQueryResultsPromise.promise;
|
|
738
1079
|
}
|
|
739
|
-
function
|
|
740
|
-
|
|
1080
|
+
function computeOnce(fn) {
|
|
1081
|
+
const ref = { current: void 0, computed: !1 };
|
|
1082
|
+
return function() {
|
|
1083
|
+
return ref.computed || (ref.current = fn.call(this), ref.computed = !0), ref.current;
|
|
1084
|
+
};
|
|
1085
|
+
}
|
|
1086
|
+
function addSchemaOrigin(tsType, schemaId) {
|
|
1087
|
+
return t.tsTypeReference(
|
|
1088
|
+
SchemaOrigin,
|
|
1089
|
+
t.tsTypeParameterInstantiation([tsType, t.tsLiteralType(t.stringLiteral(schemaId))])
|
|
1090
|
+
);
|
|
1091
|
+
}
|
|
1092
|
+
function addPickSchema(tsType, schemaId) {
|
|
1093
|
+
return t.tsTypeReference(
|
|
1094
|
+
PickSchema,
|
|
1095
|
+
t.tsTypeParameterInstantiation([tsType, t.tsLiteralType(t.stringLiteral(schemaId))])
|
|
1096
|
+
);
|
|
1097
|
+
}
|
|
1098
|
+
function generateCode(node) {
|
|
1099
|
+
return `${new CodeGenerator(node).generate().code.trim()}
|
|
1100
|
+
|
|
1101
|
+
`;
|
|
741
1102
|
}
|
|
742
|
-
function
|
|
743
|
-
|
|
1103
|
+
function promiseWithResolvers() {
|
|
1104
|
+
let resolve2, reject;
|
|
1105
|
+
return { promise: new Promise((thisResolve, thisReject) => {
|
|
1106
|
+
resolve2 = thisResolve, reject = thisReject;
|
|
1107
|
+
}), resolve: resolve2, reject };
|
|
744
1108
|
}
|
|
745
1109
|
export {
|
|
1110
|
+
DEFAULT_CONFIG,
|
|
746
1111
|
TypeGenerator,
|
|
747
1112
|
findQueriesInPath,
|
|
748
1113
|
findQueriesInSource,
|