@sanity/codegen 3.86.0 → 3.86.2-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.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: !0 });
3
- var fs = require("node:fs/promises"), json5 = require("json5"), z = require("zod"), groqJs = require("groq-js"), createDebug = require("debug"), glob = require("globby"), fs$1 = require("node:fs"), path = require("node:path"), node_module = require("node:module"), core = require("@babel/core"), t = require("@babel/types"), traverse = require("@babel/traverse"), tsconfigPaths = require("tsconfig-paths"), register = require("@babel/register"), generator = require("@babel/generator");
3
+ var fs = require("node:fs/promises"), json5 = require("json5"), z = require("zod"), groqJs = require("groq-js"), createDebug = require("debug"), glob = require("globby"), fs$1 = require("node:fs"), path = require("node:path"), node_module = require("node:module"), core = require("@babel/core"), t = require("@babel/types"), traverse = require("@babel/traverse"), tsconfigPaths = require("tsconfig-paths"), generator = require("@babel/generator"), register = require("@babel/register");
4
4
  function _interopDefaultCompat(e) {
5
5
  return e && typeof e == "object" && "default" in e ? e : { default: e };
6
6
  }
@@ -20,28 +20,54 @@ function _interopNamespaceCompat(e) {
20
20
  }), n.default = e, Object.freeze(n);
21
21
  }
22
22
  var fs__default$1 = /* @__PURE__ */ _interopDefaultCompat(fs), json5__namespace = /* @__PURE__ */ _interopNamespaceCompat(json5), z__namespace = /* @__PURE__ */ _interopNamespaceCompat(z), createDebug__default = /* @__PURE__ */ _interopDefaultCompat(createDebug), glob__default = /* @__PURE__ */ _interopDefaultCompat(glob), fs__default = /* @__PURE__ */ _interopDefaultCompat(fs$1), path__default = /* @__PURE__ */ _interopDefaultCompat(path), t__namespace = /* @__PURE__ */ _interopNamespaceCompat(t), traverse__default = /* @__PURE__ */ _interopDefaultCompat(traverse), register__default = /* @__PURE__ */ _interopDefaultCompat(register);
23
- const configDefintion = z__namespace.object({
24
- path: z__namespace.string().or(z__namespace.array(z__namespace.string())).default([
25
- "./src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro}",
26
- "./app/**/*.{ts,tsx,js,jsx,mjs,cjs}",
27
- "./sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}"
28
- ]),
29
- schema: z__namespace.string().default("./schema.json"),
30
- generates: z__namespace.string().default("./sanity.types.ts"),
31
- formatGeneratedCode: z__namespace.boolean().default(!0),
32
- overloadClientMethods: z__namespace.boolean().default(!0)
33
- });
23
+ const defaultPaths = [
24
+ "./src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro}",
25
+ "./app/**/*.{ts,tsx,js,jsx,mjs,cjs}",
26
+ "./sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}"
27
+ ], rawConfigSchema = z__namespace.object({
28
+ path: z__namespace.union([z__namespace.string(), z__namespace.array(z__namespace.string())]).optional(),
29
+ generates: z__namespace.string().optional(),
30
+ formatGeneratedCode: z__namespace.boolean().optional(),
31
+ overloadClientMethods: z__namespace.boolean().optional(),
32
+ augmentGroqModule: z__namespace.boolean().optional(),
33
+ schema: z__namespace.string().optional(),
34
+ schemas: z__namespace.array(
35
+ z__namespace.object({
36
+ projectId: z__namespace.string().optional(),
37
+ dataset: z__namespace.string().optional(),
38
+ schemaPath: z__namespace.string()
39
+ })
40
+ ).optional()
41
+ }).superRefine((data, ctx) => {
42
+ data.schema !== void 0 && data.schemas !== void 0 && ctx.addIssue({
43
+ code: z__namespace.ZodIssueCode.custom,
44
+ message: 'Configuration cannot contain both "schema" and "schemas". Use one or the other.'
45
+ });
46
+ }).refine((d) => d.schemas === void 0 || d.schemas.length > 0, {
47
+ message: '"schemas" array cannot be empty. Please provide at least one schema definition or use the "schema" property instead.'
48
+ }), normalizedConfigSchema = rawConfigSchema.transform((d) => ({
49
+ path: typeof d.path == "string" ? [d.path] : d.path ?? defaultPaths,
50
+ generates: d.generates ?? "./sanity.types.ts",
51
+ formatGeneratedCode: d.formatGeneratedCode ?? !0,
52
+ overloadClientMethods: d.overloadClientMethods ?? !0,
53
+ augmentGroqModule: d.augmentGroqModule ?? !0,
54
+ schemas: d.schemas ? d.schemas.map((s) => ({
55
+ projectId: s.projectId ?? "default",
56
+ dataset: s.dataset ?? "default",
57
+ schemaPath: s.schemaPath
58
+ })) : [{ projectId: "default", dataset: "default", schemaPath: d.schema ?? "./schema.json" }]
59
+ }));
34
60
  async function readConfig(path2) {
35
61
  try {
36
62
  const content = await fs.readFile(path2, "utf-8"), json = json5__namespace.parse(content);
37
- return configDefintion.parseAsync(json);
63
+ return normalizedConfigSchema.parse(json);
38
64
  } catch (error) {
39
65
  if (error instanceof z__namespace.ZodError)
40
66
  throw new Error(`Error in config file
41
67
  ${error.errors.map((err) => err.message).join(`
42
68
  `)}`);
43
69
  if (typeof error == "object" && error !== null && "code" in error && error.code === "ENOENT")
44
- return configDefintion.parse({});
70
+ return normalizedConfigSchema.parse({});
45
71
  throw error;
46
72
  }
47
73
  }
@@ -95,7 +121,7 @@ function parseAstro(source) {
95
121
  `)).join(`
96
122
  `) : "";
97
123
  }
98
- const debug$2 = createDebug__default.default("sanity:codegen:findQueries:debug"), TAGGED_TEMPLATE_ALLOW_LIST = ["groq"], FUNCTION_WRAPPER_ALLOW_LIST = ["defineQuery"];
124
+ const debug$2 = createDebug__default.default("sanity:codegen:findQueries:debug"), TAGGED_TEMPLATE_ALLOW_LIST = ["groq"], FUNCTION_WRAPPER_ALLOW_LIST = ["defineQuery", "defineProjection"];
99
125
  function resolveExpression({
100
126
  node,
101
127
  file,
@@ -405,19 +431,23 @@ function resolveExportSpecifier({
405
431
  cause: `noBinding:${importName}`
406
432
  });
407
433
  }
408
- const require$1 = node_module.createRequire(__filename), groqTagName = "groq", defineQueryFunctionName = "defineQuery", groqModuleName = "groq", nextSanityModuleName = "next-sanity", ignoreValue = "@sanity-typegen-ignore";
434
+ const require$1 = node_module.createRequire(__filename), groqTagName = "groq", defineQueryFunctionName = "defineQuery", defineProjectionFunctionName = "defineProjection", groqModuleName = "groq", nextSanityModuleName = "next-sanity", ignoreValue = "@sanity-typegen-ignore";
409
435
  function findQueriesInSource(source, filename, babelConfig = getBabelConfig(), resolver = require$1.resolve) {
410
436
  const queries = [], file = parseSourceFile(source, filename, babelConfig);
411
437
  return core.traverse(file, {
412
438
  // Look for variable declarations, e.g. `const myQuery = groq`... and extract the query.
413
439
  // The variable name is used as the name of the query result type
414
440
  VariableDeclarator(path2) {
415
- const { node, scope } = path2, init = node.init, isGroqTemplateTag = t__namespace.isTaggedTemplateExpression(init) && t__namespace.isIdentifier(init.tag) && init.tag.name === groqTagName, isDefineQueryCall = t__namespace.isCallExpression(init) && (isImportFrom(groqModuleName, defineQueryFunctionName, scope, init.callee) || isImportFrom(nextSanityModuleName, defineQueryFunctionName, scope, init.callee));
416
- if (t__namespace.isIdentifier(node.id) && (isGroqTemplateTag || isDefineQueryCall)) {
441
+ const { node, scope } = path2, init = node.init, isGroqTemplateTag = t__namespace.isTaggedTemplateExpression(init) && t__namespace.isIdentifier(init.tag) && init.tag.name === groqTagName, isDefineCall = t__namespace.isCallExpression(init) && (isImportFrom(groqModuleName, defineQueryFunctionName, scope, init.callee) || isImportFrom(groqModuleName, defineProjectionFunctionName, scope, init.callee) || isImportFrom(nextSanityModuleName, defineQueryFunctionName, scope, init.callee));
442
+ if (t__namespace.isIdentifier(node.id) && (isGroqTemplateTag || isDefineCall)) {
417
443
  if (declarationLeadingCommentContains(path2, ignoreValue))
418
444
  return;
419
- const queryName = `${node.id.name}`, queryResult = resolveExpression({
420
- node: init,
445
+ const queryName = `${node.id.name}`;
446
+ let resultType = "query", expressionToResolve = init;
447
+ isDefineCall && (init.arguments.length > 0 && t__namespace.isExpression(init.arguments[0]) && (expressionToResolve = init.arguments[0]), isImportFrom(groqModuleName, defineProjectionFunctionName, scope, init.callee) && (resultType = "projection"));
448
+ const queryResult = resolveExpression({
449
+ node: expressionToResolve,
450
+ // Use the potentially updated expression node
421
451
  file,
422
452
  scope,
423
453
  babelConfig,
@@ -431,7 +461,7 @@ function findQueriesInSource(source, filename, babelConfig = getBabelConfig(), r
431
461
  ...node.loc?.end
432
462
  }
433
463
  } : {};
434
- queries.push({ name: queryName, result: queryResult, location });
464
+ queries.push({ name: queryName, result: queryResult, type: resultType, location });
435
465
  }
436
466
  }
437
467
  }), queries;
@@ -517,120 +547,142 @@ async function* findQueriesInPath({
517
547
  }
518
548
  }
519
549
  }
520
- function registerBabel(babelOptions) {
521
- const options = babelOptions || getBabelConfig();
522
- register__default.default({ ...options, extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"] });
523
- }
524
- const REFERENCE_SYMBOL_NAME = "internalGroqTypeReferenceTo", ALL_SCHEMA_TYPES = "AllSanitySchemaTypes";
525
- class TypeGenerator {
526
- // Simple set to keep track of generated type names, to avoid conflicts
527
- generatedTypeName = /* @__PURE__ */ new Set();
528
- // Map between type names and their generated type names, used to resolve the correct generated type name
529
- typeNameMap = /* @__PURE__ */ new Map();
530
- // Map between type nodes and their generated type names, used for query mapping
531
- typeNodeNameMap = /* @__PURE__ */ new Map();
532
- schema;
533
- constructor(schema) {
534
- this.schema = schema, this.schema.forEach((s) => {
535
- this.getTypeName(s.name, s);
536
- });
537
- }
550
+ class AsyncQueue {
551
+ // Internal state:
552
+ // `queue`: Holds items yet to be consumed.
553
+ // `resume`: A callback to signal the consumer when new items arrive or the queue finishes/errors.
554
+ // `finished`: Flag indicating if the producer is done adding items (via `finish` or `throwError`).
555
+ // `pendingError`: Stores an error passed to `throwError`, to be thrown by the consumer.
556
+ queue = [];
557
+ resume = null;
558
+ finished = !1;
559
+ pendingError = null;
538
560
  /**
539
- * Generate TypeScript types for the given schema
540
- * @returns string
541
- * @internal
542
- * @beta
561
+ * Enqueues an item. Throws if `finish` or `throwError` has been called.
543
562
  */
544
- generateSchemaTypes() {
545
- const typeDeclarations = [], schemaNames = /* @__PURE__ */ new Set();
546
- return this.schema.forEach((schema) => {
547
- const typeLiteral = this.getTypeNodeType(schema), schemaName = this.typeNodeNameMap.get(schema);
548
- if (!schemaName)
549
- throw new Error(`Schema name not found for schema ${schema.name}`);
550
- schemaNames.add(schemaName);
551
- const typeAlias = t__namespace.tsTypeAliasDeclaration(t__namespace.identifier(schemaName), null, typeLiteral);
552
- typeDeclarations.push(t__namespace.exportNamedDeclaration(typeAlias));
553
- }), typeDeclarations.push(
554
- t__namespace.exportNamedDeclaration(
555
- t__namespace.tsTypeAliasDeclaration(
556
- t__namespace.identifier(this.getTypeName(ALL_SCHEMA_TYPES)),
557
- null,
558
- t__namespace.tsUnionType(
559
- [...schemaNames].map((typeName) => t__namespace.tsTypeReference(t__namespace.identifier(typeName)))
560
- )
561
- )
562
- )
563
- ), typeDeclarations.map((decl) => new generator.CodeGenerator(decl).generate().code).join(`
564
-
565
- `);
563
+ enqueue(item) {
564
+ if (this.finished)
565
+ throw new Error("Cannot enqueue items to a finished AsyncQueue.");
566
+ this.queue.push(item), this.resume && (this.resume(), this.resume = null);
566
567
  }
567
568
  /**
568
- * Takes a identifier and a type node and generates a type alias for the type node.
569
- * @param identifierName - The name of the type to generated
570
- * @param typeNode - The type node to generate the type for
571
- * @returns
572
- * @internal
573
- * @beta
569
+ * Signals that no more items will be enqueued. Idempotent.
574
570
  */
575
- generateTypeNodeTypes(identifierName, typeNode) {
576
- const type = this.getTypeNodeType(typeNode), typeName = this.getTypeName(identifierName, typeNode), typeAlias = t__namespace.tsTypeAliasDeclaration(t__namespace.identifier(typeName), null, type);
577
- return new generator.CodeGenerator(t__namespace.exportNamedDeclaration(typeAlias)).generate().code.trim();
578
- }
579
- static generateKnownTypes() {
580
- const typeOperator = t__namespace.tsTypeOperator(t__namespace.tsSymbolKeyword());
581
- typeOperator.operator = "unique";
582
- const identifier = t__namespace.identifier(REFERENCE_SYMBOL_NAME);
583
- identifier.typeAnnotation = t__namespace.tsTypeAnnotation(typeOperator);
584
- const decleration = t__namespace.variableDeclaration("const", [t__namespace.variableDeclarator(identifier)]);
585
- return decleration.declare = !0, new generator.CodeGenerator(t__namespace.exportNamedDeclaration(decleration)).generate().code.trim();
571
+ finish() {
572
+ this.finished || (this.finished = !0, this.resume && (this.resume(), this.resume = null));
586
573
  }
587
574
  /**
588
- * Takes a list of queries from the codebase and generates a type declaration
589
- * for SanityClient to consume.
590
- *
591
- * Note: only types that have previously been generated with `generateTypeNodeTypes`
592
- * will be included in the query map.
593
- *
594
- * @param queries - A list of queries to generate a type declaration for
595
- * @returns
596
- * @internal
597
- * @beta
575
+ * Signals an error occurred during production. Finishes the queue. Idempotent.
598
576
  */
599
- generateQueryMap(queries) {
600
- const typesByQuerystring = {};
601
- for (const query of queries) {
602
- const name = this.typeNodeNameMap.get(query.typeNode);
603
- name && (typesByQuerystring[query.query] ??= [], typesByQuerystring[query.query].push(name));
604
- }
605
- const queryReturnInterface = t__namespace.tsInterfaceDeclaration(
606
- t__namespace.identifier("SanityQueries"),
607
- null,
608
- [],
609
- t__namespace.tsInterfaceBody(
610
- Object.entries(typesByQuerystring).map(([query, types]) => t__namespace.tsPropertySignature(
611
- t__namespace.stringLiteral(query),
612
- t__namespace.tsTypeAnnotation(
613
- t__namespace.tsUnionType(types.map((type) => t__namespace.tsTypeReference(t__namespace.identifier(type))))
614
- )
615
- ))
616
- )
617
- ), declareModule = t__namespace.declareModule(
618
- t__namespace.stringLiteral("@sanity/client"),
619
- t__namespace.blockStatement([queryReturnInterface])
620
- ), clientImport = t__namespace.importDeclaration([], t__namespace.stringLiteral("@sanity/client"));
621
- return new generator.CodeGenerator(t__namespace.program([clientImport, declareModule])).generate().code.trim();
577
+ throwError(error) {
578
+ this.finished || (this.pendingError = error, this.finished = !0, this.resume && (this.resume(), this.resume = null));
622
579
  }
623
580
  /**
624
- * Since we are sanitizing identifiers we migt end up with collisions. Ie there might be a type mux.video and muxVideo, both these
625
- * types would be sanityized into MuxVideo. To avoid this we keep track of the generated type names and add a index to the name.
626
- * When we reference a type we also keep track of the original name so we can reference the correct type later.
581
+ * Async iterator to consume enqueued items.
582
+ * Throws if `throwError` was called.
627
583
  */
628
- getTypeName(name, typeNode) {
629
- const desiredName = uppercaseFirstLetter(sanitizeIdentifier(name));
630
- let generatedName = desiredName, i = 2;
631
- for (; this.generatedTypeName.has(generatedName); )
632
- generatedName = `${desiredName}_${i++}`;
633
- return this.generatedTypeName.add(generatedName), this.typeNameMap.set(name, generatedName), typeNode && this.typeNodeNameMap.set(typeNode, generatedName), generatedName;
584
+ async *[Symbol.asyncIterator]() {
585
+ for (; ; ) {
586
+ if (this.pendingError)
587
+ throw this.pendingError;
588
+ if (this.queue.length === 0 && !this.finished && (await new Promise((resolve) => {
589
+ this.resume = resolve;
590
+ }), this.pendingError))
591
+ throw this.pendingError;
592
+ for (; this.queue.length > 0; )
593
+ yield this.queue.shift();
594
+ if (this.finished && this.queue.length === 0)
595
+ break;
596
+ }
597
+ if (this.pendingError)
598
+ throw this.pendingError;
599
+ }
600
+ }
601
+ function uppercaseFirstLetter(input) {
602
+ return input.charAt(0).toUpperCase() + input.slice(1);
603
+ }
604
+ function sanitizeIdentifier(input) {
605
+ return `${input.replace(/^\d/, "_").replace(/[^$\w]+(.)/g, (_, char) => char.toUpperCase())}`;
606
+ }
607
+ class SchemaTypeGenerator {
608
+ tsTypes;
609
+ documentTypeNames;
610
+ identifiers;
611
+ schema;
612
+ projectId;
613
+ dataset;
614
+ static REFERENCE_SYMBOL_NAME = "internalGroqTypeReferenceTo";
615
+ static sanitizeIdentifier(input) {
616
+ return uppercaseFirstLetter(sanitizeIdentifier(input));
617
+ }
618
+ constructor({ dataset, projectId, schema }) {
619
+ this.dataset = dataset, this.projectId = projectId, this.schema = schema;
620
+ const sanitizedCounts = {};
621
+ this.identifiers = this.schema.reduce((acc, { name }) => {
622
+ const base = SchemaTypeGenerator.sanitizeIdentifier(name), count = (sanitizedCounts[base] || 0) + 1;
623
+ sanitizedCounts[base] = count;
624
+ const uniqueName = count === 1 ? base : `${base}_${count}`;
625
+ return acc.set(name, t__namespace.identifier(uniqueName)), acc;
626
+ }, /* @__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());
627
+ }
628
+ getTypeNames() {
629
+ return Array.from(this.tsTypes.keys());
630
+ }
631
+ getDocumentTypeNames() {
632
+ return Array.from(this.documentTypeNames);
633
+ }
634
+ getTsType(name) {
635
+ return this.tsTypes.get(name);
636
+ }
637
+ getIdentifier(name) {
638
+ return this.identifiers.get(name);
639
+ }
640
+ evaluateQuery(query) {
641
+ const ast = safeParseQuery(query), typeNode = groqJs.typeEvaluate(ast, this.schema), tsType = this.getTypeNodeType(typeNode), stats = SchemaTypeGenerator.calculateTypeStats(typeNode);
642
+ return { tsType, stats };
643
+ }
644
+ evaluateProjection(projection) {
645
+ const results = this.getDocumentTypeNames().map((typeName) => {
646
+ const ast = safeParseQuery(`* [_type==${JSON.stringify(typeName)}] ${projection} [0]`);
647
+ let typeNode = groqJs.typeEvaluate(ast, this.schema);
648
+ if (typeNode.type === "union") {
649
+ const nonNullMembers = typeNode.of.filter((member) => member.type !== "null");
650
+ if (nonNullMembers.length === 0)
651
+ return null;
652
+ nonNullMembers.length === 1 ? typeNode = nonNullMembers[0] : typeNode = { ...typeNode, of: nonNullMembers };
653
+ }
654
+ if (typeNode.type === "object") {
655
+ const attributeValues = Object.values(typeNode.attributes), allAttributesNull = attributeValues.every((attr) => attr.value.type === "null"), hasMeaningfulRest = typeNode.rest && typeNode.rest.type !== "unknown";
656
+ if (attributeValues.length > 0 && allAttributesNull && !hasMeaningfulRest)
657
+ return null;
658
+ }
659
+ if (typeNode.type === "null")
660
+ return null;
661
+ const stats = SchemaTypeGenerator.calculateTypeStats(typeNode);
662
+ return { tsType: t__namespace.tsTypeReference(
663
+ t__namespace.identifier("DocumentTypeScoped"),
664
+ t__namespace.tsTypeParameterInstantiation([
665
+ this.getTypeNodeType(typeNode),
666
+ t__namespace.tsLiteralType(t__namespace.stringLiteral(typeName))
667
+ ])
668
+ ), stats };
669
+ }).filter((i) => !!i);
670
+ if (!results.length)
671
+ return {
672
+ tsType: t__namespace.tsNeverKeyword(),
673
+ // emptyUnions is 1 because the union type has no members, resulting in a `never` type
674
+ stats: { totalTypeNodes: 0, unknownTypeCount: 0, emptyUnionCount: 1 }
675
+ };
676
+ if (results.length === 1) return results[0];
677
+ const combinedTsType = t__namespace.tsUnionType(results.map((i) => i.tsType)), accumulatedStats = results.reduce(
678
+ (acc, { stats }) => ({
679
+ totalTypeNodes: acc.totalTypeNodes + stats.totalTypeNodes,
680
+ emptyUnionCount: acc.emptyUnionCount + stats.emptyUnionCount,
681
+ unknownTypeCount: acc.unknownTypeCount + stats.unknownTypeCount
682
+ }),
683
+ { totalTypeNodes: 0, unknownTypeCount: 0, emptyUnionCount: 0 }
684
+ );
685
+ return accumulatedStats.totalTypeNodes += 1, { tsType: combinedTsType, stats: accumulatedStats };
634
686
  }
635
687
  getTypeNodeType(typeNode) {
636
688
  switch (typeNode.type) {
@@ -652,8 +704,11 @@ class TypeGenerator {
652
704
  return this.generateObjectTsType(typeNode);
653
705
  case "union":
654
706
  return this.generateUnionTsType(typeNode);
655
- case "inline":
656
- return this.generateInlineTsType(typeNode);
707
+ case "inline": {
708
+ const identifier = this.getIdentifier(typeNode.name);
709
+ if (!identifier) throw new Error(`Type "${typeNode.name}" not found in schema`);
710
+ return t__namespace.tsTypeReference(identifier);
711
+ }
657
712
  case "null":
658
713
  return t__namespace.tsNullKeyword();
659
714
  default:
@@ -694,38 +749,30 @@ class TypeGenerator {
694
749
  break;
695
750
  }
696
751
  case "inline": {
697
- const resolved = this.generateInlineTsType(rest);
698
- return t__namespace.isTSUnknownKeyword(resolved) ? resolved : t__namespace.tsIntersectionType([t__namespace.tsTypeLiteral(props), resolved]);
752
+ const identifier = this.getIdentifier(rest.name);
753
+ if (!identifier) {
754
+ const missing = t__namespace.tsUnknownKeyword();
755
+ return missing.trailingComments = [
756
+ {
757
+ type: "CommentLine",
758
+ value: ` Unable to locate the referenced type "${rest.name}" in schema`
759
+ }
760
+ ], missing;
761
+ }
762
+ return t__namespace.tsIntersectionType([t__namespace.tsTypeLiteral(props), t__namespace.tsTypeReference(identifier)]);
699
763
  }
700
764
  default:
701
765
  throw new Error(`Type "${rest.type}" not found in schema`);
702
766
  }
703
767
  if (typeNode.dereferencesTo !== void 0) {
704
768
  const derefType = t__namespace.tsPropertySignature(
705
- t__namespace.identifier(REFERENCE_SYMBOL_NAME),
769
+ t__namespace.identifier(SchemaTypeGenerator.REFERENCE_SYMBOL_NAME),
706
770
  t__namespace.tsTypeAnnotation(t__namespace.tsLiteralType(t__namespace.stringLiteral(typeNode.dereferencesTo)))
707
771
  );
708
772
  derefType.computed = !0, derefType.optional = !0, props.push(derefType);
709
773
  }
710
774
  return t__namespace.tsTypeLiteral(props);
711
775
  }
712
- generateInlineTsType(typeNode) {
713
- const referencedTypeNode = this.schema.find((schema) => schema.name === typeNode.name);
714
- if (referencedTypeNode === void 0) {
715
- const generatedName2 = this.typeNameMap.get(typeNode.name);
716
- if (generatedName2)
717
- return t__namespace.tsTypeReference(t__namespace.identifier(generatedName2));
718
- const missing = t__namespace.tsUnknownKeyword();
719
- return missing.trailingComments = [
720
- {
721
- type: "CommentLine",
722
- value: ` Unable to locate the referenced type "${typeNode.name}" in schema`
723
- }
724
- ], missing;
725
- }
726
- const generatedName = this.typeNameMap.get(referencedTypeNode.name);
727
- return generatedName ? t__namespace.tsTypeReference(t__namespace.identifier(generatedName)) : t__namespace.tsUnknownKeyword();
728
- }
729
776
  // Helper function used to generate TS types for union type nodes.
730
777
  generateUnionTsType(typeNode) {
731
778
  if (typeNode.of.length === 0)
@@ -742,16 +789,310 @@ class TypeGenerator {
742
789
  );
743
790
  return t__namespace.tsTypeLiteral(props);
744
791
  }
792
+ // Helper function to calculate statistics for a TypeNode
793
+ static calculateTypeStats(typeNode) {
794
+ switch (typeNode.type) {
795
+ case "unknown":
796
+ return { totalTypeNodes: 1, unknownTypeCount: 1, emptyUnionCount: 0 };
797
+ case "array": {
798
+ const stats = SchemaTypeGenerator.calculateTypeStats(typeNode.of);
799
+ return stats.totalTypeNodes += 1, stats;
800
+ }
801
+ case "object": {
802
+ const initialStats = {
803
+ totalTypeNodes: 1,
804
+ unknownTypeCount: 0,
805
+ emptyUnionCount: 0
806
+ }, restStats = typeNode.rest ? SchemaTypeGenerator.calculateTypeStats(typeNode.rest) : null;
807
+ return restStats && (initialStats.totalTypeNodes += restStats.totalTypeNodes, initialStats.unknownTypeCount += restStats.unknownTypeCount, initialStats.emptyUnionCount += restStats.emptyUnionCount), Object.values(typeNode.attributes).reduce((acc, attribute) => {
808
+ const stats = SchemaTypeGenerator.calculateTypeStats(attribute.value);
809
+ return acc.totalTypeNodes += stats.totalTypeNodes, acc.unknownTypeCount += stats.unknownTypeCount, acc.emptyUnionCount += stats.emptyUnionCount, acc;
810
+ }, initialStats);
811
+ }
812
+ case "union":
813
+ return typeNode.of.length === 0 ? { totalTypeNodes: 1, unknownTypeCount: 0, emptyUnionCount: 1 } : typeNode.of.reduce(
814
+ (acc, type) => {
815
+ const stats = SchemaTypeGenerator.calculateTypeStats(type);
816
+ return acc.totalTypeNodes += stats.totalTypeNodes, acc.unknownTypeCount += stats.unknownTypeCount, acc.emptyUnionCount += stats.emptyUnionCount, acc;
817
+ },
818
+ { totalTypeNodes: 1, unknownTypeCount: 0, emptyUnionCount: 0 }
819
+ // count the union type itself
820
+ );
821
+ case "type":
822
+ return SchemaTypeGenerator.calculateTypeStats(typeNode.value);
823
+ case "document": {
824
+ const initialStats = {
825
+ totalTypeNodes: 1,
826
+ unknownTypeCount: 0,
827
+ emptyUnionCount: 0
828
+ };
829
+ return Object.values(typeNode.attributes).reduce((acc, attribute) => {
830
+ const stats = SchemaTypeGenerator.calculateTypeStats(attribute.value);
831
+ return acc.totalTypeNodes += stats.totalTypeNodes, acc.unknownTypeCount += stats.unknownTypeCount, acc.emptyUnionCount += stats.emptyUnionCount, acc;
832
+ }, initialStats);
833
+ }
834
+ // Base types
835
+ case "string":
836
+ case "number":
837
+ case "boolean":
838
+ case "null":
839
+ case "inline":
840
+ default:
841
+ return { totalTypeNodes: 1, unknownTypeCount: 0, emptyUnionCount: 0 };
842
+ }
843
+ }
745
844
  }
746
- function uppercaseFirstLetter(input) {
747
- return input.charAt(0).toUpperCase() + input.slice(1);
845
+ const SanityQueries = t__namespace.identifier("SanityQueries"), SanityProjections = t__namespace.identifier("SanityProjections"), SanitySchemas = t__namespace.identifier("SanitySchemas"), DocumentTypeScoped = t__namespace.identifier("DocumentTypeScoped"), DatasetScoped = t__namespace.identifier("DatasetScoped"), ExtractDataset = t__namespace.identifier("ExtractDataset"), AllSchemaTypes = t__namespace.identifier("AllSanitySchemaTypes"), ReferenceSymbol = Object.assign(t__namespace.identifier(SchemaTypeGenerator.REFERENCE_SYMBOL_NAME), {
846
+ typeAnnotation: t__namespace.tsTypeAnnotation(
847
+ Object.assign(t__namespace.tsTypeOperator(t__namespace.tsSymbolKeyword()), { operator: "unique" })
848
+ )
849
+ });
850
+ function generateCode(node) {
851
+ return `${new generator.CodeGenerator(node).generate().code.trim()}
852
+
853
+ `;
748
854
  }
749
- function sanitizeIdentifier(input) {
750
- return `${input.replace(/^\d/, "_").replace(/[^$\w]+(.)/g, (_, char) => char.toUpperCase())}`;
855
+ function scopeByDataset(tsType, options) {
856
+ return t__namespace.tsTypeReference(
857
+ DatasetScoped,
858
+ t__namespace.tsTypeParameterInstantiation([
859
+ tsType,
860
+ t__namespace.tsLiteralType(t__namespace.stringLiteral(options.dataset)),
861
+ t__namespace.tsLiteralType(t__namespace.stringLiteral(options.projectId))
862
+ ])
863
+ );
864
+ }
865
+ function PromiseWithResolvers() {
866
+ let resolve, reject;
867
+ return { promise: new Promise((thisResolve, thisReject) => {
868
+ resolve = thisResolve, reject = thisReject;
869
+ }), resolve, reject };
870
+ }
871
+ function generateTypes({
872
+ schemas,
873
+ queriesByFile,
874
+ augmentGroqModule,
875
+ overloadClientMethods
876
+ }) {
877
+ const globalIdentifiers = /* @__PURE__ */ new Set();
878
+ 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);
879
+ const generatedQueries = new AsyncQueue(), {
880
+ promise: generatedSchema,
881
+ resolve: resolveGeneratedSchema,
882
+ reject: rejectGeneratedSchema
883
+ } = PromiseWithResolvers(), {
884
+ promise: generatedTypemap,
885
+ resolve: resolveGeneratedTypemap,
886
+ reject: rejectGeneratedTypemap
887
+ } = PromiseWithResolvers();
888
+ return (async () => {
889
+ const schemaGenerators = schemas.map((options) => new SchemaTypeGenerator(options)), typeNames = new Set(schemaGenerators.flatMap((i) => i.getTypeNames()));
890
+ let schemaCode = "";
891
+ overloadClientMethods && (schemaCode += generateCode(t__namespace.importDeclaration([], t__namespace.stringLiteral("@sanity/client")))), schemaCode += generateCode(
892
+ Object.assign(
893
+ t__namespace.importDeclaration(
894
+ [
895
+ t__namespace.importSpecifier(DocumentTypeScoped, DocumentTypeScoped),
896
+ t__namespace.importSpecifier(ExtractDataset, ExtractDataset),
897
+ t__namespace.importSpecifier(DatasetScoped, DatasetScoped)
898
+ ],
899
+ t__namespace.stringLiteral("groq")
900
+ ),
901
+ { importKind: "type" }
902
+ )
903
+ ), schemaCode += generateCode(
904
+ t__namespace.exportNamedDeclaration(
905
+ Object.assign(t__namespace.variableDeclaration("const", [t__namespace.variableDeclarator(ReferenceSymbol)]), {
906
+ declare: !0
907
+ })
908
+ )
909
+ );
910
+ const schemaIdentifiers = /* @__PURE__ */ new Set();
911
+ for (const typeName of typeNames) {
912
+ const identifiers = new Set(
913
+ schemaGenerators.map((i) => i.getIdentifier(typeName)?.name).filter((i) => typeof i == "string")
914
+ );
915
+ for (const identifier of identifiers) {
916
+ globalIdentifiers.add(identifier);
917
+ const tsTypes = schemaGenerators.filter((i) => i.getIdentifier(typeName)?.name === identifier).map((i) => {
918
+ const tsType2 = i.getTsType(typeName);
919
+ return tsType2 && schemaGenerators.length > 1 ? scopeByDataset(tsType2, i) : tsType2;
920
+ }).filter((i) => i !== void 0), tsType = tsTypes.length === 1 ? tsTypes[0] : t__namespace.tsUnionType(tsTypes), typeAlias = t__namespace.tsTypeAliasDeclaration(t__namespace.identifier(identifier), null, tsType), code = generateCode(t__namespace.exportNamedDeclaration(typeAlias));
921
+ schemaIdentifiers.add(identifier), schemaCode += code;
922
+ }
923
+ }
924
+ const allSchemaTypesDeclaration = generateCode(
925
+ t__namespace.exportNamedDeclaration(
926
+ t__namespace.tsTypeAliasDeclaration(
927
+ AllSchemaTypes,
928
+ null,
929
+ t__namespace.tsUnionType(
930
+ Array.from(schemaIdentifiers).map(
931
+ (identifier) => t__namespace.tsTypeReference(t__namespace.identifier(identifier))
932
+ )
933
+ )
934
+ )
935
+ )
936
+ );
937
+ if (schemaCode += allSchemaTypesDeclaration, augmentGroqModule) {
938
+ const sanitySchemasProperties = schemas.map(
939
+ ({ dataset, projectId }) => t__namespace.tsPropertySignature(
940
+ t__namespace.stringLiteral(`${projectId}:${dataset}`),
941
+ t__namespace.tsTypeAnnotation(
942
+ t__namespace.tsTypeReference(
943
+ ExtractDataset,
944
+ t__namespace.tsTypeParameterInstantiation([
945
+ t__namespace.tsTypeReference(AllSchemaTypes),
946
+ t__namespace.tsLiteralType(t__namespace.stringLiteral(dataset)),
947
+ t__namespace.tsLiteralType(t__namespace.stringLiteral(projectId))
948
+ ])
949
+ )
950
+ )
951
+ )
952
+ ), sanitySchemasDeclaration = generateCode(
953
+ t__namespace.declareModule(
954
+ t__namespace.stringLiteral("groq"),
955
+ t__namespace.blockStatement([
956
+ t__namespace.tsInterfaceDeclaration(
957
+ SanitySchemas,
958
+ null,
959
+ [],
960
+ t__namespace.tsInterfaceBody(sanitySchemasProperties)
961
+ )
962
+ ])
963
+ )
964
+ );
965
+ schemaCode += sanitySchemasDeclaration;
966
+ }
967
+ resolveGeneratedSchema({
968
+ code: schemaCode,
969
+ schemas: schemas.map(({ schema, ...rest }) => ({
970
+ ...rest,
971
+ typeCount: schema.length
972
+ }))
973
+ });
974
+ const queryIdentifiers = /* @__PURE__ */ new Map(), projectionIdentifiers = /* @__PURE__ */ new Map(), totalStats = {
975
+ totalTypeNodes: 0,
976
+ unknownTypeCount: 0,
977
+ emptyUnionCount: 0
978
+ };
979
+ for await (const input of queriesByFile)
980
+ try {
981
+ if (input.type === "error") throw input.error;
982
+ const results = [];
983
+ for (const query of input.queries) {
984
+ const desiredName = SchemaTypeGenerator.sanitizeIdentifier(
985
+ query.type === "projection" ? `${query.name}ProjectionResult` : `${query.name}Result`
986
+ );
987
+ let resultingName = desiredName, index = 2;
988
+ for (; globalIdentifiers.has(resultingName); )
989
+ resultingName = `${desiredName}_${index}`, index++;
990
+ const identifier = t__namespace.identifier(resultingName);
991
+ let identifiers = query.type === "projection" ? projectionIdentifiers.get(query.result) : queryIdentifiers.get(query.result);
992
+ identifiers || (identifiers = [], query.type === "projection" ? projectionIdentifiers.set(query.result, identifiers) : queryIdentifiers.set(query.result, identifiers)), identifiers.push(identifier);
993
+ const evaluationResults = schemaGenerators.map((i) => query.type === "projection" ? i.evaluateProjection(query.result) : i.evaluateQuery(query.result)), aggregatedQueryStats = evaluationResults.reduce(
994
+ (acc, { stats }) => ({
995
+ totalTypeNodes: acc.totalTypeNodes + stats.totalTypeNodes,
996
+ unknownTypeCount: acc.unknownTypeCount + stats.unknownTypeCount,
997
+ emptyUnionCount: acc.emptyUnionCount + stats.emptyUnionCount
998
+ }),
999
+ { totalTypeNodes: 0, unknownTypeCount: 0, emptyUnionCount: 0 }
1000
+ );
1001
+ totalStats.totalTypeNodes += aggregatedQueryStats.totalTypeNodes, totalStats.unknownTypeCount += aggregatedQueryStats.unknownTypeCount, totalStats.emptyUnionCount += aggregatedQueryStats.emptyUnionCount;
1002
+ const tsTypes = evaluationResults.map(({ tsType: tsType2 }, resultIndex) => schemas.length === 1 ? tsType2 : scopeByDataset(tsType2, schemaGenerators[resultIndex])), tsType = tsTypes.length === 1 ? tsTypes[0] : t__namespace.tsUnionType(tsTypes), typeAlias = t__namespace.tsTypeAliasDeclaration(identifier, null, tsType), code = generateCode(
1003
+ t__namespace.addComments(t__namespace.exportNamedDeclaration(typeAlias), "leading", [
1004
+ { type: "CommentLine", value: ` Source: ${input.filename}` },
1005
+ { type: "CommentLine", value: ` Variable: ${query.name}` },
1006
+ {
1007
+ type: "CommentLine",
1008
+ value: ` ${query.type === "projection" ? "Projection" : "Query"}: ${query.result.replace(/(\r\n|\n|\r)/gm, "").trim()}`
1009
+ }
1010
+ ])
1011
+ );
1012
+ results.push({
1013
+ name: query.name,
1014
+ query: query.result,
1015
+ type: query.type,
1016
+ code,
1017
+ stats: aggregatedQueryStats
1018
+ });
1019
+ }
1020
+ generatedQueries.enqueue({ filename: input.filename, results });
1021
+ } catch (error) {
1022
+ generatedQueries.enqueue({ filename: input.filename, results: [], error });
1023
+ }
1024
+ generatedQueries.finish();
1025
+ let typemapCode = "";
1026
+ const clientModuleBlockStatement = [], groqModuleBlockStatement = [];
1027
+ if (queryIdentifiers.size > 0) {
1028
+ const sanityQueriesInterfaceDeclaration = t__namespace.tsInterfaceDeclaration(
1029
+ SanityQueries,
1030
+ null,
1031
+ [],
1032
+ t__namespace.tsInterfaceBody(
1033
+ Array.from(queryIdentifiers).map(
1034
+ ([query, identifiers]) => t__namespace.tsPropertySignature(
1035
+ t__namespace.stringLiteral(query),
1036
+ t__namespace.tsTypeAnnotation(
1037
+ identifiers.length === 1 ? t__namespace.tsTypeReference(identifiers[0]) : t__namespace.tsUnionType(identifiers.map((i) => t__namespace.tsTypeReference(i)))
1038
+ )
1039
+ )
1040
+ )
1041
+ )
1042
+ );
1043
+ clientModuleBlockStatement.push(sanityQueriesInterfaceDeclaration), groqModuleBlockStatement.push(sanityQueriesInterfaceDeclaration);
1044
+ }
1045
+ if (projectionIdentifiers.size > 0) {
1046
+ const sanityProjectionsInterfaceDeclaration = t__namespace.tsInterfaceDeclaration(
1047
+ SanityProjections,
1048
+ null,
1049
+ [],
1050
+ t__namespace.tsInterfaceBody(
1051
+ Array.from(projectionIdentifiers).map(
1052
+ ([projection, identifiers]) => t__namespace.tsPropertySignature(
1053
+ t__namespace.stringLiteral(projection),
1054
+ t__namespace.tsTypeAnnotation(
1055
+ identifiers.length === 1 ? t__namespace.tsTypeReference(identifiers[0]) : t__namespace.tsUnionType(identifiers.map((i) => t__namespace.tsTypeReference(i)))
1056
+ )
1057
+ )
1058
+ )
1059
+ )
1060
+ );
1061
+ groqModuleBlockStatement.push(sanityProjectionsInterfaceDeclaration);
1062
+ }
1063
+ if (overloadClientMethods && clientModuleBlockStatement.length > 0) {
1064
+ const clientModuleDeclaration = t__namespace.declareModule(
1065
+ t__namespace.stringLiteral("@sanity/client"),
1066
+ t__namespace.blockStatement(clientModuleBlockStatement)
1067
+ );
1068
+ typemapCode += generateCode(clientModuleDeclaration);
1069
+ }
1070
+ if (augmentGroqModule && groqModuleBlockStatement.length > 0) {
1071
+ const groqModuleDeclaration = t__namespace.declareModule(
1072
+ t__namespace.stringLiteral("groq"),
1073
+ t__namespace.blockStatement(groqModuleBlockStatement)
1074
+ );
1075
+ typemapCode += generateCode(groqModuleDeclaration);
1076
+ }
1077
+ resolveGeneratedTypemap({
1078
+ code: typemapCode,
1079
+ stats: totalStats
1080
+ });
1081
+ })().catch((err) => {
1082
+ generatedQueries.throwError(err), rejectGeneratedSchema(err), rejectGeneratedTypemap(err);
1083
+ }), {
1084
+ generatedSchema: () => generatedSchema,
1085
+ generatedQueries: () => generatedQueries,
1086
+ generatedTypemap: () => generatedTypemap
1087
+ };
1088
+ }
1089
+ function registerBabel(babelOptions) {
1090
+ const options = babelOptions || getBabelConfig();
1091
+ register__default.default({ ...options, extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"] });
751
1092
  }
752
- exports.TypeGenerator = TypeGenerator;
753
1093
  exports.findQueriesInPath = findQueriesInPath;
754
1094
  exports.findQueriesInSource = findQueriesInSource;
1095
+ exports.generateTypes = generateTypes;
755
1096
  exports.getResolver = getResolver;
756
1097
  exports.readConfig = readConfig;
757
1098
  exports.readSchema = readSchema;