@sanity/codegen 3.88.1-typegen-experimental.0 → 3.88.1
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 +85 -282
- package/lib/index.d.ts +85 -282
- package/lib/index.js +172 -537
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +173 -538
- package/lib/index.mjs.map +1 -1
- package/package.json +17 -15
- package/src/_exports/index.ts +3 -14
- package/src/readConfig.ts +23 -71
- package/src/readSchema.ts +1 -0
- package/src/typescript/expressionResolvers.ts +3 -4
- package/src/typescript/findQueriesInPath.ts +2 -9
- package/src/typescript/findQueriesInSource.ts +6 -22
- package/src/typescript/typeGenerator.ts +306 -445
- package/src/typescript/asyncQueue.ts +0 -100
- package/src/typescript/schemaTypeGenerator.ts +0 -381
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
|
|
4
|
+
import { parse } from "groq-js";
|
|
5
5
|
import createDebug from "debug";
|
|
6
6
|
import glob from "globby";
|
|
7
7
|
import fs, { existsSync } from "node:fs";
|
|
@@ -13,44 +13,29 @@ 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
|
-
|
|
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({});
|
|
16
|
+
const configDefintion = z.object({
|
|
17
|
+
path: z.string().or(z.array(z.string())).default([
|
|
18
|
+
"./src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro}",
|
|
19
|
+
"./app/**/*.{ts,tsx,js,jsx,mjs,cjs}",
|
|
20
|
+
"./sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}"
|
|
21
|
+
]),
|
|
22
|
+
schema: z.string().default("./schema.json"),
|
|
23
|
+
generates: z.string().default("./sanity.types.ts"),
|
|
24
|
+
formatGeneratedCode: z.boolean().default(!0),
|
|
25
|
+
overloadClientMethods: z.boolean().default(!0)
|
|
26
|
+
});
|
|
46
27
|
async function readConfig(path2) {
|
|
47
28
|
try {
|
|
48
29
|
const content = await readFile(path2, "utf-8"), json = json5.parse(content);
|
|
49
|
-
return
|
|
30
|
+
return configDefintion.parseAsync(json);
|
|
50
31
|
} catch (error) {
|
|
51
|
-
|
|
32
|
+
if (error instanceof z.ZodError)
|
|
33
|
+
throw new Error(`Error in config file
|
|
52
34
|
${error.errors.map((err) => err.message).join(`
|
|
53
|
-
`)}`)
|
|
35
|
+
`)}`);
|
|
36
|
+
if (typeof error == "object" && error !== null && "code" in error && error.code === "ENOENT")
|
|
37
|
+
return configDefintion.parse({});
|
|
38
|
+
throw error;
|
|
54
39
|
}
|
|
55
40
|
}
|
|
56
41
|
async function readSchema(path2) {
|
|
@@ -103,7 +88,7 @@ function parseAstro(source) {
|
|
|
103
88
|
`)).join(`
|
|
104
89
|
`) : "";
|
|
105
90
|
}
|
|
106
|
-
const debug$2 = createDebug("sanity:codegen:findQueries:debug"), TAGGED_TEMPLATE_ALLOW_LIST = ["groq"], FUNCTION_WRAPPER_ALLOW_LIST = ["defineQuery"
|
|
91
|
+
const debug$2 = createDebug("sanity:codegen:findQueries:debug"), TAGGED_TEMPLATE_ALLOW_LIST = ["groq"], FUNCTION_WRAPPER_ALLOW_LIST = ["defineQuery"];
|
|
107
92
|
function resolveExpression({
|
|
108
93
|
node,
|
|
109
94
|
file,
|
|
@@ -413,22 +398,19 @@ function resolveExportSpecifier({
|
|
|
413
398
|
cause: `noBinding:${importName}`
|
|
414
399
|
});
|
|
415
400
|
}
|
|
416
|
-
const require$1 = createRequire(__filename), groqTagName = "groq", defineQueryFunctionName = "defineQuery",
|
|
401
|
+
const require$1 = createRequire(__filename), groqTagName = "groq", defineQueryFunctionName = "defineQuery", groqModuleName = "groq", nextSanityModuleName = "next-sanity", ignoreValue = "@sanity-typegen-ignore";
|
|
417
402
|
function findQueriesInSource(source, filename, babelConfig = getBabelConfig(), resolver = require$1.resolve) {
|
|
418
403
|
const queries = [], file = parseSourceFile(source, filename, babelConfig);
|
|
419
404
|
return traverse$1(file, {
|
|
420
405
|
// Look for variable declarations, e.g. `const myQuery = groq`... and extract the query.
|
|
421
406
|
// The variable name is used as the name of the query result type
|
|
422
407
|
VariableDeclarator(path2) {
|
|
423
|
-
const { node, scope } = path2, init = node.init, isGroqTemplateTag = t.isTaggedTemplateExpression(init) && t.isIdentifier(init.tag) && init.tag.name === groqTagName,
|
|
424
|
-
if (t.isIdentifier(node.id) && (isGroqTemplateTag ||
|
|
408
|
+
const { node, scope } = path2, init = node.init, isGroqTemplateTag = t.isTaggedTemplateExpression(init) && t.isIdentifier(init.tag) && init.tag.name === groqTagName, isDefineQueryCall = t.isCallExpression(init) && (isImportFrom(groqModuleName, defineQueryFunctionName, scope, init.callee) || isImportFrom(nextSanityModuleName, defineQueryFunctionName, scope, init.callee));
|
|
409
|
+
if (t.isIdentifier(node.id) && (isGroqTemplateTag || isDefineQueryCall)) {
|
|
425
410
|
if (declarationLeadingCommentContains(path2, ignoreValue))
|
|
426
411
|
return;
|
|
427
|
-
const queryName = `${node.id.name}
|
|
428
|
-
|
|
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,
|
|
412
|
+
const queryName = `${node.id.name}`, queryResult = resolveExpression({
|
|
413
|
+
node: init,
|
|
432
414
|
file,
|
|
433
415
|
scope,
|
|
434
416
|
babelConfig,
|
|
@@ -442,7 +424,7 @@ function findQueriesInSource(source, filename, babelConfig = getBabelConfig(), r
|
|
|
442
424
|
...node.loc?.end
|
|
443
425
|
}
|
|
444
426
|
} : {};
|
|
445
|
-
queries.push({ name: queryName, result: queryResult,
|
|
427
|
+
queries.push({ name: queryName, result: queryResult, location });
|
|
446
428
|
}
|
|
447
429
|
}
|
|
448
430
|
}), queries;
|
|
@@ -510,7 +492,6 @@ async function* findQueriesInPath({
|
|
|
510
492
|
// we never want to look in node_modules
|
|
511
493
|
onlyFiles: !0
|
|
512
494
|
}).sort();
|
|
513
|
-
yield { type: "files", fileCount: files.length };
|
|
514
495
|
for (const filename of files)
|
|
515
496
|
if (typeof filename == "string") {
|
|
516
497
|
debug(`Found file "${filename}"`);
|
|
@@ -533,100 +514,118 @@ function registerBabel(babelOptions) {
|
|
|
533
514
|
const options = babelOptions || getBabelConfig();
|
|
534
515
|
register({ ...options, extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"] });
|
|
535
516
|
}
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
//
|
|
539
|
-
|
|
540
|
-
//
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
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);
|
|
517
|
+
const REFERENCE_SYMBOL_NAME = "internalGroqTypeReferenceTo", ALL_SCHEMA_TYPES = "AllSanitySchemaTypes";
|
|
518
|
+
class TypeGenerator {
|
|
519
|
+
// Simple set to keep track of generated type names, to avoid conflicts
|
|
520
|
+
generatedTypeName = /* @__PURE__ */ new Set();
|
|
521
|
+
// Map between type names and their generated type names, used to resolve the correct generated type name
|
|
522
|
+
typeNameMap = /* @__PURE__ */ new Map();
|
|
523
|
+
// Map between type nodes and their generated type names, used for query mapping
|
|
524
|
+
typeNodeNameMap = /* @__PURE__ */ new Map();
|
|
525
|
+
schema;
|
|
526
|
+
constructor(schema) {
|
|
527
|
+
this.schema = schema, this.schema.forEach((s) => {
|
|
528
|
+
this.getTypeName(s.name, s);
|
|
529
|
+
});
|
|
553
530
|
}
|
|
554
531
|
/**
|
|
555
|
-
*
|
|
532
|
+
* Generate TypeScript types for the given schema
|
|
533
|
+
* @returns string
|
|
534
|
+
* @internal
|
|
535
|
+
* @beta
|
|
556
536
|
*/
|
|
557
|
-
|
|
558
|
-
|
|
537
|
+
generateSchemaTypes() {
|
|
538
|
+
const typeDeclarations = [], schemaNames = /* @__PURE__ */ new Set();
|
|
539
|
+
return this.schema.forEach((schema) => {
|
|
540
|
+
const typeLiteral = this.getTypeNodeType(schema), schemaName = this.typeNodeNameMap.get(schema);
|
|
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
|
+
`);
|
|
559
559
|
}
|
|
560
560
|
/**
|
|
561
|
-
*
|
|
561
|
+
* Takes a identifier and a type node and generates a type alias for the type node.
|
|
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
|
|
562
567
|
*/
|
|
563
|
-
|
|
564
|
-
|
|
568
|
+
generateTypeNodeTypes(identifierName, typeNode) {
|
|
569
|
+
const type = this.getTypeNodeType(typeNode), typeName = this.getTypeName(identifierName, typeNode), typeAlias = t.tsTypeAliasDeclaration(t.identifier(typeName), null, type);
|
|
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();
|
|
565
579
|
}
|
|
566
580
|
/**
|
|
567
|
-
*
|
|
568
|
-
*
|
|
581
|
+
* Takes a list of queries from the codebase and generates a type declaration
|
|
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
|
|
569
591
|
*/
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
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;
|
|
592
|
+
generateQueryMap(queries) {
|
|
593
|
+
const typesByQuerystring = {};
|
|
594
|
+
for (const query of queries) {
|
|
595
|
+
const name = this.typeNodeNameMap.get(query.typeNode);
|
|
596
|
+
name && (typesByQuerystring[query.query] ??= [], typesByQuerystring[query.query].push(name));
|
|
582
597
|
}
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
return
|
|
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");
|
|
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();
|
|
628
615
|
}
|
|
629
|
-
|
|
616
|
+
/**
|
|
617
|
+
* Since we are sanitizing identifiers we migt end up with collisions. Ie there might be a type mux.video and muxVideo, both these
|
|
618
|
+
* types would be sanityized into MuxVideo. To avoid this we keep track of the generated type names and add a index to the name.
|
|
619
|
+
* When we reference a type we also keep track of the original name so we can reference the correct type later.
|
|
620
|
+
*/
|
|
621
|
+
getTypeName(name, typeNode) {
|
|
622
|
+
const desiredName = uppercaseFirstLetter(sanitizeIdentifier(name));
|
|
623
|
+
let generatedName = desiredName, i = 2;
|
|
624
|
+
for (; this.generatedTypeName.has(generatedName); )
|
|
625
|
+
generatedName = `${desiredName}_${i++}`;
|
|
626
|
+
return this.generatedTypeName.add(generatedName), this.typeNameMap.set(name, generatedName), typeNode && this.typeNodeNameMap.set(typeNode, generatedName), generatedName;
|
|
627
|
+
}
|
|
628
|
+
getTypeNodeType(typeNode) {
|
|
630
629
|
switch (typeNode.type) {
|
|
631
630
|
case "string":
|
|
632
631
|
return typeNode.value !== void 0 ? t.tsLiteralType(t.stringLiteral(typeNode.value)) : t.tsStringKeyword();
|
|
@@ -637,9 +636,9 @@ class SchemaTypeGenerator {
|
|
|
637
636
|
case "unknown":
|
|
638
637
|
return t.tsUnknownKeyword();
|
|
639
638
|
case "document":
|
|
640
|
-
return this.
|
|
639
|
+
return this.generateDocumentType(typeNode);
|
|
641
640
|
case "type":
|
|
642
|
-
return this.
|
|
641
|
+
return this.getTypeNodeType(typeNode.value);
|
|
643
642
|
case "array":
|
|
644
643
|
return this.generateArrayTsType(typeNode);
|
|
645
644
|
case "object":
|
|
@@ -651,21 +650,21 @@ class SchemaTypeGenerator {
|
|
|
651
650
|
case "null":
|
|
652
651
|
return t.tsNullKeyword();
|
|
653
652
|
default:
|
|
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
|
-
);
|
|
653
|
+
throw new Error(`Type "${typeNode.type}" not found in schema`);
|
|
658
654
|
}
|
|
659
655
|
}
|
|
660
656
|
// Helper function used to generate TS types for array type nodes.
|
|
661
657
|
generateArrayTsType(typeNode) {
|
|
662
|
-
const typeNodes = this.
|
|
663
|
-
return t.tsTypeReference(
|
|
658
|
+
const typeNodes = this.getTypeNodeType(typeNode.of);
|
|
659
|
+
return t.tsTypeReference(
|
|
660
|
+
t.identifier("Array"),
|
|
661
|
+
t.tsTypeParameterInstantiation([typeNodes])
|
|
662
|
+
);
|
|
664
663
|
}
|
|
665
664
|
// Helper function used to generate TS types for object properties.
|
|
666
|
-
|
|
667
|
-
const type = this.
|
|
668
|
-
t.identifier(
|
|
665
|
+
generateObjectProperty(key, attribute) {
|
|
666
|
+
const type = this.getTypeNodeType(attribute.value), propertySignature = t.tsPropertySignature(
|
|
667
|
+
t.identifier(sanitizeIdentifier(key)),
|
|
669
668
|
t.tsTypeAnnotation(type)
|
|
670
669
|
);
|
|
671
670
|
return propertySignature.optional = attribute.optional, propertySignature;
|
|
@@ -674,16 +673,16 @@ class SchemaTypeGenerator {
|
|
|
674
673
|
generateObjectTsType(typeNode) {
|
|
675
674
|
const props = [];
|
|
676
675
|
Object.entries(typeNode.attributes).forEach(([key, attribute]) => {
|
|
677
|
-
props.push(this.
|
|
676
|
+
props.push(this.generateObjectProperty(key, attribute));
|
|
678
677
|
});
|
|
679
678
|
const rest = typeNode.rest;
|
|
680
|
-
if (rest)
|
|
679
|
+
if (rest !== void 0)
|
|
681
680
|
switch (rest.type) {
|
|
682
681
|
case "unknown":
|
|
683
682
|
return t.tsUnknownKeyword();
|
|
684
683
|
case "object": {
|
|
685
684
|
Object.entries(rest.attributes).forEach(([key, attribute]) => {
|
|
686
|
-
props.push(this.
|
|
685
|
+
props.push(this.generateObjectProperty(key, attribute));
|
|
687
686
|
});
|
|
688
687
|
break;
|
|
689
688
|
}
|
|
@@ -694,420 +693,56 @@ class SchemaTypeGenerator {
|
|
|
694
693
|
default:
|
|
695
694
|
throw new Error(`Type "${rest.type}" not found in schema`);
|
|
696
695
|
}
|
|
697
|
-
if (typeNode.dereferencesTo) {
|
|
698
|
-
const derefType =
|
|
699
|
-
t.
|
|
700
|
-
|
|
701
|
-
t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo)))
|
|
702
|
-
),
|
|
703
|
-
{ computed: !0, optional: !0 }
|
|
696
|
+
if (typeNode.dereferencesTo !== void 0) {
|
|
697
|
+
const derefType = t.tsPropertySignature(
|
|
698
|
+
t.identifier(REFERENCE_SYMBOL_NAME),
|
|
699
|
+
t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo)))
|
|
704
700
|
);
|
|
705
|
-
props.push(derefType);
|
|
701
|
+
derefType.computed = !0, derefType.optional = !0, props.push(derefType);
|
|
706
702
|
}
|
|
707
703
|
return t.tsTypeLiteral(props);
|
|
708
704
|
}
|
|
709
705
|
generateInlineTsType(typeNode) {
|
|
710
|
-
const
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
706
|
+
const referencedTypeNode = this.schema.find((schema) => schema.name === typeNode.name);
|
|
707
|
+
if (referencedTypeNode === void 0) {
|
|
708
|
+
const generatedName2 = this.typeNameMap.get(typeNode.name);
|
|
709
|
+
if (generatedName2)
|
|
710
|
+
return t.tsTypeReference(t.identifier(generatedName2));
|
|
711
|
+
const missing = t.tsUnknownKeyword();
|
|
712
|
+
return missing.trailingComments = [
|
|
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();
|
|
717
721
|
}
|
|
718
722
|
// Helper function used to generate TS types for union type nodes.
|
|
719
723
|
generateUnionTsType(typeNode) {
|
|
720
|
-
|
|
724
|
+
if (typeNode.of.length === 0)
|
|
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);
|
|
721
730
|
}
|
|
722
731
|
// Helper function used to generate TS types for document type nodes.
|
|
723
|
-
|
|
732
|
+
generateDocumentType(document) {
|
|
724
733
|
const props = Object.entries(document.attributes).map(
|
|
725
|
-
([key, node]) => this.
|
|
734
|
+
([key, node]) => this.generateObjectProperty(key, node)
|
|
726
735
|
);
|
|
727
736
|
return t.tsTypeLiteral(props);
|
|
728
737
|
}
|
|
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;
|
|
1079
738
|
}
|
|
1080
|
-
function
|
|
1081
|
-
|
|
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
|
-
`;
|
|
739
|
+
function uppercaseFirstLetter(input) {
|
|
740
|
+
return input.charAt(0).toUpperCase() + input.slice(1);
|
|
1102
741
|
}
|
|
1103
|
-
function
|
|
1104
|
-
|
|
1105
|
-
return { promise: new Promise((thisResolve, thisReject) => {
|
|
1106
|
-
resolve2 = thisResolve, reject = thisReject;
|
|
1107
|
-
}), resolve: resolve2, reject };
|
|
742
|
+
function sanitizeIdentifier(input) {
|
|
743
|
+
return `${input.replace(/^\d/, "_").replace(/[^$\w]+(.)/g, (_, char) => char.toUpperCase())}`;
|
|
1108
744
|
}
|
|
1109
745
|
export {
|
|
1110
|
-
DEFAULT_CONFIG,
|
|
1111
746
|
TypeGenerator,
|
|
1112
747
|
findQueriesInPath,
|
|
1113
748
|
findQueriesInSource,
|