@sanity/codegen 3.86.2-experimental.0 → 3.87.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.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, typeEvaluate } from "groq-js";
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";
@@ -11,56 +11,30 @@ import { parse as parse$1, traverse as traverse$1 } from "@babel/core";
11
11
  import * as t from "@babel/types";
12
12
  import traverse, { Scope } from "@babel/traverse";
13
13
  import { loadConfig, createMatchPath } from "tsconfig-paths";
14
- import { CodeGenerator } from "@babel/generator";
15
14
  import register from "@babel/register";
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
- schemas: z.array(
28
- z.object({
29
- projectId: z.string().optional(),
30
- dataset: z.string().optional(),
31
- schemaPath: z.string()
32
- })
33
- ).optional()
34
- }).superRefine((data, ctx) => {
35
- data.schema !== void 0 && data.schemas !== void 0 && ctx.addIssue({
36
- code: z.ZodIssueCode.custom,
37
- message: 'Configuration cannot contain both "schema" and "schemas". Use one or the other.'
38
- });
39
- }).refine((d) => d.schemas === void 0 || d.schemas.length > 0, {
40
- message: '"schemas" array cannot be empty. Please provide at least one schema definition or use the "schema" property instead.'
41
- }), normalizedConfigSchema = rawConfigSchema.transform((d) => ({
42
- path: typeof d.path == "string" ? [d.path] : d.path ?? defaultPaths,
43
- generates: d.generates ?? "./sanity.types.ts",
44
- formatGeneratedCode: d.formatGeneratedCode ?? !0,
45
- overloadClientMethods: d.overloadClientMethods ?? !0,
46
- augmentGroqModule: d.augmentGroqModule ?? !0,
47
- schemas: d.schemas ? d.schemas.map((s) => ({
48
- projectId: s.projectId ?? "default",
49
- dataset: s.dataset ?? "default",
50
- schemaPath: s.schemaPath
51
- })) : [{ projectId: "default", dataset: "default", schemaPath: d.schema ?? "./schema.json" }]
52
- }));
15
+ import { CodeGenerator } from "@babel/generator";
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
+ });
53
27
  async function readConfig(path2) {
54
28
  try {
55
29
  const content = await readFile(path2, "utf-8"), json = json5.parse(content);
56
- return normalizedConfigSchema.parse(json);
30
+ return configDefintion.parseAsync(json);
57
31
  } catch (error) {
58
32
  if (error instanceof z.ZodError)
59
33
  throw new Error(`Error in config file
60
34
  ${error.errors.map((err) => err.message).join(`
61
35
  `)}`);
62
36
  if (typeof error == "object" && error !== null && "code" in error && error.code === "ENOENT")
63
- return normalizedConfigSchema.parse({});
37
+ return configDefintion.parse({});
64
38
  throw error;
65
39
  }
66
40
  }
@@ -114,7 +88,7 @@ function parseAstro(source) {
114
88
  `)).join(`
115
89
  `) : "";
116
90
  }
117
- const debug$2 = createDebug("sanity:codegen:findQueries:debug"), TAGGED_TEMPLATE_ALLOW_LIST = ["groq"], FUNCTION_WRAPPER_ALLOW_LIST = ["defineQuery", "defineProjection"];
91
+ const debug$2 = createDebug("sanity:codegen:findQueries:debug"), TAGGED_TEMPLATE_ALLOW_LIST = ["groq"], FUNCTION_WRAPPER_ALLOW_LIST = ["defineQuery"];
118
92
  function resolveExpression({
119
93
  node,
120
94
  file,
@@ -424,23 +398,19 @@ function resolveExportSpecifier({
424
398
  cause: `noBinding:${importName}`
425
399
  });
426
400
  }
427
- const require$1 = createRequire(__filename), groqTagName = "groq", defineQueryFunctionName = "defineQuery", defineProjectionFunctionName = "defineProjection", groqModuleName = "groq", nextSanityModuleName = "next-sanity", ignoreValue = "@sanity-typegen-ignore";
401
+ const require$1 = createRequire(__filename), groqTagName = "groq", defineQueryFunctionName = "defineQuery", groqModuleName = "groq", nextSanityModuleName = "next-sanity", ignoreValue = "@sanity-typegen-ignore";
428
402
  function findQueriesInSource(source, filename, babelConfig = getBabelConfig(), resolver = require$1.resolve) {
429
403
  const queries = [], file = parseSourceFile(source, filename, babelConfig);
430
404
  return traverse$1(file, {
431
405
  // Look for variable declarations, e.g. `const myQuery = groq`... and extract the query.
432
406
  // The variable name is used as the name of the query result type
433
407
  VariableDeclarator(path2) {
434
- 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));
435
- if (t.isIdentifier(node.id) && (isGroqTemplateTag || isDefineCall)) {
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)) {
436
410
  if (declarationLeadingCommentContains(path2, ignoreValue))
437
411
  return;
438
- const queryName = `${node.id.name}`;
439
- let resultType = "query", expressionToResolve = init;
440
- isDefineCall && (init.arguments.length > 0 && t.isExpression(init.arguments[0]) && (expressionToResolve = init.arguments[0]), isImportFrom(groqModuleName, defineProjectionFunctionName, scope, init.callee) && (resultType = "projection"));
441
- const queryResult = resolveExpression({
442
- node: expressionToResolve,
443
- // Use the potentially updated expression node
412
+ const queryName = `${node.id.name}`, queryResult = resolveExpression({
413
+ node: init,
444
414
  file,
445
415
  scope,
446
416
  babelConfig,
@@ -454,7 +424,7 @@ function findQueriesInSource(source, filename, babelConfig = getBabelConfig(), r
454
424
  ...node.loc?.end
455
425
  }
456
426
  } : {};
457
- queries.push({ name: queryName, result: queryResult, type: resultType, location });
427
+ queries.push({ name: queryName, result: queryResult, location });
458
428
  }
459
429
  }
460
430
  }), queries;
@@ -540,142 +510,120 @@ async function* findQueriesInPath({
540
510
  }
541
511
  }
542
512
  }
543
- class AsyncQueue {
544
- // Internal state:
545
- // `queue`: Holds items yet to be consumed.
546
- // `resume`: A callback to signal the consumer when new items arrive or the queue finishes/errors.
547
- // `finished`: Flag indicating if the producer is done adding items (via `finish` or `throwError`).
548
- // `pendingError`: Stores an error passed to `throwError`, to be thrown by the consumer.
549
- queue = [];
550
- resume = null;
551
- finished = !1;
552
- pendingError = null;
553
- /**
554
- * Enqueues an item. Throws if `finish` or `throwError` has been called.
555
- */
556
- enqueue(item) {
557
- if (this.finished)
558
- throw new Error("Cannot enqueue items to a finished AsyncQueue.");
559
- this.queue.push(item), this.resume && (this.resume(), this.resume = null);
513
+ function registerBabel(babelOptions) {
514
+ const options = babelOptions || getBabelConfig();
515
+ register({ ...options, extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"] });
516
+ }
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
+ });
560
530
  }
561
531
  /**
562
- * Signals that no more items will be enqueued. Idempotent.
532
+ * Generate TypeScript types for the given schema
533
+ * @returns string
534
+ * @internal
535
+ * @beta
563
536
  */
564
- finish() {
565
- this.finished || (this.finished = !0, this.resume && (this.resume(), this.resume = null));
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
+ `);
566
559
  }
567
560
  /**
568
- * Signals an error occurred during production. Finishes the queue. Idempotent.
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
569
567
  */
570
- throwError(error) {
571
- this.finished || (this.pendingError = error, this.finished = !0, this.resume && (this.resume(), this.resume = null));
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();
572
579
  }
573
580
  /**
574
- * Async iterator to consume enqueued items.
575
- * Throws if `throwError` was called.
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
576
591
  */
577
- async *[Symbol.asyncIterator]() {
578
- for (; ; ) {
579
- if (this.pendingError)
580
- throw this.pendingError;
581
- if (this.queue.length === 0 && !this.finished && (await new Promise((resolve2) => {
582
- this.resume = resolve2;
583
- }), this.pendingError))
584
- throw this.pendingError;
585
- for (; this.queue.length > 0; )
586
- yield this.queue.shift();
587
- if (this.finished && this.queue.length === 0)
588
- 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));
589
597
  }
590
- if (this.pendingError)
591
- throw this.pendingError;
592
- }
593
- }
594
- function uppercaseFirstLetter(input) {
595
- return input.charAt(0).toUpperCase() + input.slice(1);
596
- }
597
- function sanitizeIdentifier(input) {
598
- return `${input.replace(/^\d/, "_").replace(/[^$\w]+(.)/g, (_, char) => char.toUpperCase())}`;
599
- }
600
- class SchemaTypeGenerator {
601
- tsTypes;
602
- documentTypeNames;
603
- identifiers;
604
- schema;
605
- projectId;
606
- dataset;
607
- static REFERENCE_SYMBOL_NAME = "internalGroqTypeReferenceTo";
608
- static sanitizeIdentifier(input) {
609
- return uppercaseFirstLetter(sanitizeIdentifier(input));
610
- }
611
- constructor({ dataset, projectId, schema }) {
612
- this.dataset = dataset, this.projectId = projectId, this.schema = schema;
613
- const sanitizedCounts = {};
614
- this.identifiers = this.schema.reduce((acc, { name }) => {
615
- const base = SchemaTypeGenerator.sanitizeIdentifier(name), count = (sanitizedCounts[base] || 0) + 1;
616
- sanitizedCounts[base] = count;
617
- const uniqueName = count === 1 ? base : `${base}_${count}`;
618
- return acc.set(name, t.identifier(uniqueName)), acc;
619
- }, /* @__PURE__ */ new Map()), this.documentTypeNames = new Set(schema.filter((i) => i.type === "document").map((i) => i.name)), this.tsTypes = schema.reduce((acc, i) => (acc.set(i.name, this.getTypeNodeType(i)), acc), /* @__PURE__ */ new Map());
620
- }
621
- getTypeNames() {
622
- return Array.from(this.tsTypes.keys());
623
- }
624
- getDocumentTypeNames() {
625
- return Array.from(this.documentTypeNames);
626
- }
627
- getTsType(name) {
628
- return this.tsTypes.get(name);
629
- }
630
- getIdentifier(name) {
631
- return this.identifiers.get(name);
632
- }
633
- evaluateQuery(query) {
634
- const ast = safeParseQuery(query), typeNode = typeEvaluate(ast, this.schema), tsType = this.getTypeNodeType(typeNode), stats = SchemaTypeGenerator.calculateTypeStats(typeNode);
635
- return { tsType, stats };
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();
636
615
  }
637
- evaluateProjection(projection) {
638
- const results = this.getDocumentTypeNames().map((typeName) => {
639
- const ast = safeParseQuery(`* [_type==${JSON.stringify(typeName)}] ${projection} [0]`);
640
- let typeNode = typeEvaluate(ast, this.schema);
641
- if (typeNode.type === "union") {
642
- const nonNullMembers = typeNode.of.filter((member) => member.type !== "null");
643
- if (nonNullMembers.length === 0)
644
- return null;
645
- nonNullMembers.length === 1 ? typeNode = nonNullMembers[0] : typeNode = { ...typeNode, of: nonNullMembers };
646
- }
647
- if (typeNode.type === "object") {
648
- const attributeValues = Object.values(typeNode.attributes), allAttributesNull = attributeValues.every((attr) => attr.value.type === "null"), hasMeaningfulRest = typeNode.rest && typeNode.rest.type !== "unknown";
649
- if (attributeValues.length > 0 && allAttributesNull && !hasMeaningfulRest)
650
- return null;
651
- }
652
- if (typeNode.type === "null")
653
- return null;
654
- const stats = SchemaTypeGenerator.calculateTypeStats(typeNode);
655
- return { tsType: t.tsTypeReference(
656
- t.identifier("DocumentTypeScoped"),
657
- t.tsTypeParameterInstantiation([
658
- this.getTypeNodeType(typeNode),
659
- t.tsLiteralType(t.stringLiteral(typeName))
660
- ])
661
- ), stats };
662
- }).filter((i) => !!i);
663
- if (!results.length)
664
- return {
665
- tsType: t.tsNeverKeyword(),
666
- // emptyUnions is 1 because the union type has no members, resulting in a `never` type
667
- stats: { totalTypeNodes: 0, unknownTypeCount: 0, emptyUnionCount: 1 }
668
- };
669
- if (results.length === 1) return results[0];
670
- const combinedTsType = t.tsUnionType(results.map((i) => i.tsType)), accumulatedStats = results.reduce(
671
- (acc, { stats }) => ({
672
- totalTypeNodes: acc.totalTypeNodes + stats.totalTypeNodes,
673
- emptyUnionCount: acc.emptyUnionCount + stats.emptyUnionCount,
674
- unknownTypeCount: acc.unknownTypeCount + stats.unknownTypeCount
675
- }),
676
- { totalTypeNodes: 0, unknownTypeCount: 0, emptyUnionCount: 0 }
677
- );
678
- return accumulatedStats.totalTypeNodes += 1, { tsType: combinedTsType, stats: accumulatedStats };
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;
679
627
  }
680
628
  getTypeNodeType(typeNode) {
681
629
  switch (typeNode.type) {
@@ -697,11 +645,8 @@ class SchemaTypeGenerator {
697
645
  return this.generateObjectTsType(typeNode);
698
646
  case "union":
699
647
  return this.generateUnionTsType(typeNode);
700
- case "inline": {
701
- const identifier = this.getIdentifier(typeNode.name);
702
- if (!identifier) throw new Error(`Type "${typeNode.name}" not found in schema`);
703
- return t.tsTypeReference(identifier);
704
- }
648
+ case "inline":
649
+ return this.generateInlineTsType(typeNode);
705
650
  case "null":
706
651
  return t.tsNullKeyword();
707
652
  default:
@@ -742,30 +687,38 @@ class SchemaTypeGenerator {
742
687
  break;
743
688
  }
744
689
  case "inline": {
745
- const identifier = this.getIdentifier(rest.name);
746
- if (!identifier) {
747
- const missing = t.tsUnknownKeyword();
748
- return missing.trailingComments = [
749
- {
750
- type: "CommentLine",
751
- value: ` Unable to locate the referenced type "${rest.name}" in schema`
752
- }
753
- ], missing;
754
- }
755
- return t.tsIntersectionType([t.tsTypeLiteral(props), t.tsTypeReference(identifier)]);
690
+ const resolved = this.generateInlineTsType(rest);
691
+ return t.isTSUnknownKeyword(resolved) ? resolved : t.tsIntersectionType([t.tsTypeLiteral(props), resolved]);
756
692
  }
757
693
  default:
758
694
  throw new Error(`Type "${rest.type}" not found in schema`);
759
695
  }
760
696
  if (typeNode.dereferencesTo !== void 0) {
761
697
  const derefType = t.tsPropertySignature(
762
- t.identifier(SchemaTypeGenerator.REFERENCE_SYMBOL_NAME),
698
+ t.identifier(REFERENCE_SYMBOL_NAME),
763
699
  t.tsTypeAnnotation(t.tsLiteralType(t.stringLiteral(typeNode.dereferencesTo)))
764
700
  );
765
701
  derefType.computed = !0, derefType.optional = !0, props.push(derefType);
766
702
  }
767
703
  return t.tsTypeLiteral(props);
768
704
  }
705
+ generateInlineTsType(typeNode) {
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();
721
+ }
769
722
  // Helper function used to generate TS types for union type nodes.
770
723
  generateUnionTsType(typeNode) {
771
724
  if (typeNode.of.length === 0)
@@ -782,311 +735,17 @@ class SchemaTypeGenerator {
782
735
  );
783
736
  return t.tsTypeLiteral(props);
784
737
  }
785
- // Helper function to calculate statistics for a TypeNode
786
- static calculateTypeStats(typeNode) {
787
- switch (typeNode.type) {
788
- case "unknown":
789
- return { totalTypeNodes: 1, unknownTypeCount: 1, emptyUnionCount: 0 };
790
- case "array": {
791
- const stats = SchemaTypeGenerator.calculateTypeStats(typeNode.of);
792
- return stats.totalTypeNodes += 1, stats;
793
- }
794
- case "object": {
795
- const initialStats = {
796
- totalTypeNodes: 1,
797
- unknownTypeCount: 0,
798
- emptyUnionCount: 0
799
- }, restStats = typeNode.rest ? SchemaTypeGenerator.calculateTypeStats(typeNode.rest) : null;
800
- return restStats && (initialStats.totalTypeNodes += restStats.totalTypeNodes, initialStats.unknownTypeCount += restStats.unknownTypeCount, initialStats.emptyUnionCount += restStats.emptyUnionCount), Object.values(typeNode.attributes).reduce((acc, attribute) => {
801
- const stats = SchemaTypeGenerator.calculateTypeStats(attribute.value);
802
- return acc.totalTypeNodes += stats.totalTypeNodes, acc.unknownTypeCount += stats.unknownTypeCount, acc.emptyUnionCount += stats.emptyUnionCount, acc;
803
- }, initialStats);
804
- }
805
- case "union":
806
- return typeNode.of.length === 0 ? { totalTypeNodes: 1, unknownTypeCount: 0, emptyUnionCount: 1 } : typeNode.of.reduce(
807
- (acc, type) => {
808
- const stats = SchemaTypeGenerator.calculateTypeStats(type);
809
- return acc.totalTypeNodes += stats.totalTypeNodes, acc.unknownTypeCount += stats.unknownTypeCount, acc.emptyUnionCount += stats.emptyUnionCount, acc;
810
- },
811
- { totalTypeNodes: 1, unknownTypeCount: 0, emptyUnionCount: 0 }
812
- // count the union type itself
813
- );
814
- case "type":
815
- return SchemaTypeGenerator.calculateTypeStats(typeNode.value);
816
- case "document": {
817
- const initialStats = {
818
- totalTypeNodes: 1,
819
- unknownTypeCount: 0,
820
- emptyUnionCount: 0
821
- };
822
- return Object.values(typeNode.attributes).reduce((acc, attribute) => {
823
- const stats = SchemaTypeGenerator.calculateTypeStats(attribute.value);
824
- return acc.totalTypeNodes += stats.totalTypeNodes, acc.unknownTypeCount += stats.unknownTypeCount, acc.emptyUnionCount += stats.emptyUnionCount, acc;
825
- }, initialStats);
826
- }
827
- // Base types
828
- case "string":
829
- case "number":
830
- case "boolean":
831
- case "null":
832
- case "inline":
833
- default:
834
- return { totalTypeNodes: 1, unknownTypeCount: 0, emptyUnionCount: 0 };
835
- }
836
- }
837
- }
838
- const SanityQueries = t.identifier("SanityQueries"), SanityProjections = t.identifier("SanityProjections"), SanitySchemas = t.identifier("SanitySchemas"), DocumentTypeScoped = t.identifier("DocumentTypeScoped"), DatasetScoped = t.identifier("DatasetScoped"), ExtractDataset = t.identifier("ExtractDataset"), AllSchemaTypes = t.identifier("AllSanitySchemaTypes"), ReferenceSymbol = Object.assign(t.identifier(SchemaTypeGenerator.REFERENCE_SYMBOL_NAME), {
839
- typeAnnotation: t.tsTypeAnnotation(
840
- Object.assign(t.tsTypeOperator(t.tsSymbolKeyword()), { operator: "unique" })
841
- )
842
- });
843
- function generateCode(node) {
844
- return `${new CodeGenerator(node).generate().code.trim()}
845
-
846
- `;
847
738
  }
848
- function scopeByDataset(tsType, options) {
849
- return t.tsTypeReference(
850
- DatasetScoped,
851
- t.tsTypeParameterInstantiation([
852
- tsType,
853
- t.tsLiteralType(t.stringLiteral(options.dataset)),
854
- t.tsLiteralType(t.stringLiteral(options.projectId))
855
- ])
856
- );
857
- }
858
- function PromiseWithResolvers() {
859
- let resolve2, reject;
860
- return { promise: new Promise((thisResolve, thisReject) => {
861
- resolve2 = thisResolve, reject = thisReject;
862
- }), resolve: resolve2, reject };
863
- }
864
- function generateTypes({
865
- schemas,
866
- queriesByFile,
867
- augmentGroqModule,
868
- overloadClientMethods
869
- }) {
870
- const globalIdentifiers = /* @__PURE__ */ new Set();
871
- globalIdentifiers.add(SanityQueries.name), globalIdentifiers.add(SanityProjections.name), globalIdentifiers.add(SanitySchemas.name), globalIdentifiers.add(DocumentTypeScoped.name), globalIdentifiers.add(DatasetScoped.name), globalIdentifiers.add(ExtractDataset.name), globalIdentifiers.add(AllSchemaTypes.name), globalIdentifiers.add(ReferenceSymbol.name);
872
- const generatedQueries = new AsyncQueue(), {
873
- promise: generatedSchema,
874
- resolve: resolveGeneratedSchema,
875
- reject: rejectGeneratedSchema
876
- } = PromiseWithResolvers(), {
877
- promise: generatedTypemap,
878
- resolve: resolveGeneratedTypemap,
879
- reject: rejectGeneratedTypemap
880
- } = PromiseWithResolvers();
881
- return (async () => {
882
- const schemaGenerators = schemas.map((options) => new SchemaTypeGenerator(options)), typeNames = new Set(schemaGenerators.flatMap((i) => i.getTypeNames()));
883
- let schemaCode = "";
884
- overloadClientMethods && (schemaCode += generateCode(t.importDeclaration([], t.stringLiteral("@sanity/client")))), schemaCode += generateCode(
885
- Object.assign(
886
- t.importDeclaration(
887
- [
888
- t.importSpecifier(DocumentTypeScoped, DocumentTypeScoped),
889
- t.importSpecifier(ExtractDataset, ExtractDataset),
890
- t.importSpecifier(DatasetScoped, DatasetScoped)
891
- ],
892
- t.stringLiteral("groq")
893
- ),
894
- { importKind: "type" }
895
- )
896
- ), schemaCode += generateCode(
897
- t.exportNamedDeclaration(
898
- Object.assign(t.variableDeclaration("const", [t.variableDeclarator(ReferenceSymbol)]), {
899
- declare: !0
900
- })
901
- )
902
- );
903
- const schemaIdentifiers = /* @__PURE__ */ new Set();
904
- for (const typeName of typeNames) {
905
- const identifiers = new Set(
906
- schemaGenerators.map((i) => i.getIdentifier(typeName)?.name).filter((i) => typeof i == "string")
907
- );
908
- for (const identifier of identifiers) {
909
- globalIdentifiers.add(identifier);
910
- const tsTypes = schemaGenerators.filter((i) => i.getIdentifier(typeName)?.name === identifier).map((i) => {
911
- const tsType2 = i.getTsType(typeName);
912
- return tsType2 && schemaGenerators.length > 1 ? scopeByDataset(tsType2, i) : tsType2;
913
- }).filter((i) => i !== void 0), tsType = tsTypes.length === 1 ? tsTypes[0] : t.tsUnionType(tsTypes), typeAlias = t.tsTypeAliasDeclaration(t.identifier(identifier), null, tsType), code = generateCode(t.exportNamedDeclaration(typeAlias));
914
- schemaIdentifiers.add(identifier), schemaCode += code;
915
- }
916
- }
917
- const allSchemaTypesDeclaration = generateCode(
918
- t.exportNamedDeclaration(
919
- t.tsTypeAliasDeclaration(
920
- AllSchemaTypes,
921
- null,
922
- t.tsUnionType(
923
- Array.from(schemaIdentifiers).map(
924
- (identifier) => t.tsTypeReference(t.identifier(identifier))
925
- )
926
- )
927
- )
928
- )
929
- );
930
- if (schemaCode += allSchemaTypesDeclaration, augmentGroqModule) {
931
- const sanitySchemasProperties = schemas.map(
932
- ({ dataset, projectId }) => t.tsPropertySignature(
933
- t.stringLiteral(`${projectId}:${dataset}`),
934
- t.tsTypeAnnotation(
935
- t.tsTypeReference(
936
- ExtractDataset,
937
- t.tsTypeParameterInstantiation([
938
- t.tsTypeReference(AllSchemaTypes),
939
- t.tsLiteralType(t.stringLiteral(dataset)),
940
- t.tsLiteralType(t.stringLiteral(projectId))
941
- ])
942
- )
943
- )
944
- )
945
- ), sanitySchemasDeclaration = generateCode(
946
- t.declareModule(
947
- t.stringLiteral("groq"),
948
- t.blockStatement([
949
- t.tsInterfaceDeclaration(
950
- SanitySchemas,
951
- null,
952
- [],
953
- t.tsInterfaceBody(sanitySchemasProperties)
954
- )
955
- ])
956
- )
957
- );
958
- schemaCode += sanitySchemasDeclaration;
959
- }
960
- resolveGeneratedSchema({
961
- code: schemaCode,
962
- schemas: schemas.map(({ schema, ...rest }) => ({
963
- ...rest,
964
- typeCount: schema.length
965
- }))
966
- });
967
- const queryIdentifiers = /* @__PURE__ */ new Map(), projectionIdentifiers = /* @__PURE__ */ new Map(), totalStats = {
968
- totalTypeNodes: 0,
969
- unknownTypeCount: 0,
970
- emptyUnionCount: 0
971
- };
972
- for await (const input of queriesByFile)
973
- try {
974
- if (input.type === "error") throw input.error;
975
- const results = [];
976
- for (const query of input.queries) {
977
- const desiredName = SchemaTypeGenerator.sanitizeIdentifier(
978
- query.type === "projection" ? `${query.name}ProjectionResult` : `${query.name}Result`
979
- );
980
- let resultingName = desiredName, index = 2;
981
- for (; globalIdentifiers.has(resultingName); )
982
- resultingName = `${desiredName}_${index}`, index++;
983
- const identifier = t.identifier(resultingName);
984
- let identifiers = query.type === "projection" ? projectionIdentifiers.get(query.result) : queryIdentifiers.get(query.result);
985
- identifiers || (identifiers = [], query.type === "projection" ? projectionIdentifiers.set(query.result, identifiers) : queryIdentifiers.set(query.result, identifiers)), identifiers.push(identifier);
986
- const evaluationResults = schemaGenerators.map((i) => query.type === "projection" ? i.evaluateProjection(query.result) : i.evaluateQuery(query.result)), aggregatedQueryStats = evaluationResults.reduce(
987
- (acc, { stats }) => ({
988
- totalTypeNodes: acc.totalTypeNodes + stats.totalTypeNodes,
989
- unknownTypeCount: acc.unknownTypeCount + stats.unknownTypeCount,
990
- emptyUnionCount: acc.emptyUnionCount + stats.emptyUnionCount
991
- }),
992
- { totalTypeNodes: 0, unknownTypeCount: 0, emptyUnionCount: 0 }
993
- );
994
- totalStats.totalTypeNodes += aggregatedQueryStats.totalTypeNodes, totalStats.unknownTypeCount += aggregatedQueryStats.unknownTypeCount, totalStats.emptyUnionCount += aggregatedQueryStats.emptyUnionCount;
995
- const tsTypes = evaluationResults.map(({ tsType: tsType2 }, resultIndex) => schemas.length === 1 ? tsType2 : scopeByDataset(tsType2, schemaGenerators[resultIndex])), tsType = tsTypes.length === 1 ? tsTypes[0] : t.tsUnionType(tsTypes), typeAlias = t.tsTypeAliasDeclaration(identifier, null, tsType), code = generateCode(
996
- t.addComments(t.exportNamedDeclaration(typeAlias), "leading", [
997
- { type: "CommentLine", value: ` Source: ${input.filename}` },
998
- { type: "CommentLine", value: ` Variable: ${query.name}` },
999
- {
1000
- type: "CommentLine",
1001
- value: ` ${query.type === "projection" ? "Projection" : "Query"}: ${query.result.replace(/(\r\n|\n|\r)/gm, "").trim()}`
1002
- }
1003
- ])
1004
- );
1005
- results.push({
1006
- name: query.name,
1007
- query: query.result,
1008
- type: query.type,
1009
- code,
1010
- stats: aggregatedQueryStats
1011
- });
1012
- }
1013
- generatedQueries.enqueue({ filename: input.filename, results });
1014
- } catch (error) {
1015
- generatedQueries.enqueue({ filename: input.filename, results: [], error });
1016
- }
1017
- generatedQueries.finish();
1018
- let typemapCode = "";
1019
- const clientModuleBlockStatement = [], groqModuleBlockStatement = [];
1020
- if (queryIdentifiers.size > 0) {
1021
- const sanityQueriesInterfaceDeclaration = t.tsInterfaceDeclaration(
1022
- SanityQueries,
1023
- null,
1024
- [],
1025
- t.tsInterfaceBody(
1026
- Array.from(queryIdentifiers).map(
1027
- ([query, identifiers]) => t.tsPropertySignature(
1028
- t.stringLiteral(query),
1029
- t.tsTypeAnnotation(
1030
- identifiers.length === 1 ? t.tsTypeReference(identifiers[0]) : t.tsUnionType(identifiers.map((i) => t.tsTypeReference(i)))
1031
- )
1032
- )
1033
- )
1034
- )
1035
- );
1036
- clientModuleBlockStatement.push(sanityQueriesInterfaceDeclaration), groqModuleBlockStatement.push(sanityQueriesInterfaceDeclaration);
1037
- }
1038
- if (projectionIdentifiers.size > 0) {
1039
- const sanityProjectionsInterfaceDeclaration = t.tsInterfaceDeclaration(
1040
- SanityProjections,
1041
- null,
1042
- [],
1043
- t.tsInterfaceBody(
1044
- Array.from(projectionIdentifiers).map(
1045
- ([projection, identifiers]) => t.tsPropertySignature(
1046
- t.stringLiteral(projection),
1047
- t.tsTypeAnnotation(
1048
- identifiers.length === 1 ? t.tsTypeReference(identifiers[0]) : t.tsUnionType(identifiers.map((i) => t.tsTypeReference(i)))
1049
- )
1050
- )
1051
- )
1052
- )
1053
- );
1054
- groqModuleBlockStatement.push(sanityProjectionsInterfaceDeclaration);
1055
- }
1056
- if (overloadClientMethods && clientModuleBlockStatement.length > 0) {
1057
- const clientModuleDeclaration = t.declareModule(
1058
- t.stringLiteral("@sanity/client"),
1059
- t.blockStatement(clientModuleBlockStatement)
1060
- );
1061
- typemapCode += generateCode(clientModuleDeclaration);
1062
- }
1063
- if (augmentGroqModule && groqModuleBlockStatement.length > 0) {
1064
- const groqModuleDeclaration = t.declareModule(
1065
- t.stringLiteral("groq"),
1066
- t.blockStatement(groqModuleBlockStatement)
1067
- );
1068
- typemapCode += generateCode(groqModuleDeclaration);
1069
- }
1070
- resolveGeneratedTypemap({
1071
- code: typemapCode,
1072
- stats: totalStats
1073
- });
1074
- })().catch((err) => {
1075
- generatedQueries.throwError(err), rejectGeneratedSchema(err), rejectGeneratedTypemap(err);
1076
- }), {
1077
- generatedSchema: () => generatedSchema,
1078
- generatedQueries: () => generatedQueries,
1079
- generatedTypemap: () => generatedTypemap
1080
- };
739
+ function uppercaseFirstLetter(input) {
740
+ return input.charAt(0).toUpperCase() + input.slice(1);
1081
741
  }
1082
- function registerBabel(babelOptions) {
1083
- const options = babelOptions || getBabelConfig();
1084
- register({ ...options, extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"] });
742
+ function sanitizeIdentifier(input) {
743
+ return `${input.replace(/^\d/, "_").replace(/[^$\w]+(.)/g, (_, char) => char.toUpperCase())}`;
1085
744
  }
1086
745
  export {
746
+ TypeGenerator,
1087
747
  findQueriesInPath,
1088
748
  findQueriesInSource,
1089
- generateTypes,
1090
749
  getResolver,
1091
750
  readConfig,
1092
751
  readSchema,