@sanity/codegen 3.87.1 → 3.88.1-typegen-experimental.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -20,29 +20,44 @@ 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
+ unstable_schemas: z__namespace.array(z__namespace.object({ schemaPath: z__namespace.string(), schemaId: z__namespace.string() })).optional()
35
+ }).superRefine((data, ctx) => {
36
+ data.schema !== void 0 && data.unstable_schemas !== void 0 && ctx.addIssue({
37
+ code: z__namespace.ZodIssueCode.custom,
38
+ message: 'Configuration cannot contain both "schema" and "unstable_schemas". Use one or the other.'
39
+ });
40
+ }).refine((d) => d.unstable_schemas === void 0 || d.unstable_schemas.length > 0, {
41
+ message: '"unstable_schemas" array cannot be empty. Please provide at least one schema definition or use the "schema" property instead.'
42
+ }), normalizedConfigSchema = rawConfigSchema.transform((d) => ({
43
+ path: typeof d.path == "string" ? [d.path] : d.path ?? defaultPaths,
44
+ generates: d.generates ?? "./sanity.types.ts",
45
+ formatGeneratedCode: d.formatGeneratedCode ?? !0,
46
+ overloadClientMethods: d.overloadClientMethods ?? !0,
47
+ augmentGroqModule: d.augmentGroqModule ?? !0,
48
+ schemas: d.unstable_schemas ? d.unstable_schemas.map((s) => ({
49
+ schemaPath: s.schemaPath,
50
+ schemaId: s.schemaId
51
+ })) : [{ schemaId: "default", schemaPath: d.schema ?? "./schema.json" }]
52
+ })), DEFAULT_CONFIG = normalizedConfigSchema.parse({});
34
53
  async function readConfig(path2) {
35
54
  try {
36
55
  const content = await fs.readFile(path2, "utf-8"), json = json5__namespace.parse(content);
37
- return configDefintion.parseAsync(json);
56
+ return normalizedConfigSchema.parse(json);
38
57
  } catch (error) {
39
- if (error instanceof z__namespace.ZodError)
40
- throw new Error(`Error in config file
58
+ throw error instanceof z__namespace.ZodError ? new Error(`Error in config file
41
59
  ${error.errors.map((err) => err.message).join(`
42
- `)}`);
43
- if (typeof error == "object" && error !== null && "code" in error && error.code === "ENOENT")
44
- return configDefintion.parse({});
45
- throw error;
60
+ `)}`) : error;
46
61
  }
47
62
  }
48
63
  async function readSchema(path2) {
@@ -95,7 +110,7 @@ function parseAstro(source) {
95
110
  `)).join(`
96
111
  `) : "";
97
112
  }
98
- const debug$2 = createDebug__default.default("sanity:codegen:findQueries:debug"), TAGGED_TEMPLATE_ALLOW_LIST = ["groq"], FUNCTION_WRAPPER_ALLOW_LIST = ["defineQuery"];
113
+ const debug$2 = createDebug__default.default("sanity:codegen:findQueries:debug"), TAGGED_TEMPLATE_ALLOW_LIST = ["groq"], FUNCTION_WRAPPER_ALLOW_LIST = ["defineQuery", "defineProjection"];
99
114
  function resolveExpression({
100
115
  node,
101
116
  file,
@@ -405,19 +420,22 @@ function resolveExportSpecifier({
405
420
  cause: `noBinding:${importName}`
406
421
  });
407
422
  }
408
- const require$1 = node_module.createRequire(__filename), groqTagName = "groq", defineQueryFunctionName = "defineQuery", groqModuleName = "groq", nextSanityModuleName = "next-sanity", ignoreValue = "@sanity-typegen-ignore";
423
+ const require$1 = node_module.createRequire(__filename), groqTagName = "groq", defineQueryFunctionName = "defineQuery", defineProjectionFunctionName = "defineProjection", groqModuleName = "groq", nextSanityModuleName = "next-sanity", ignoreValue = "@sanity-typegen-ignore";
409
424
  function findQueriesInSource(source, filename, babelConfig = getBabelConfig(), resolver = require$1.resolve) {
410
425
  const queries = [], file = parseSourceFile(source, filename, babelConfig);
411
426
  return core.traverse(file, {
412
427
  // Look for variable declarations, e.g. `const myQuery = groq`... and extract the query.
413
428
  // The variable name is used as the name of the query result type
414
429
  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)) {
430
+ 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));
431
+ if (t__namespace.isIdentifier(node.id) && (isGroqTemplateTag || isDefineCall)) {
417
432
  if (declarationLeadingCommentContains(path2, ignoreValue))
418
433
  return;
419
- const queryName = `${node.id.name}`, queryResult = resolveExpression({
420
- node: init,
434
+ const queryName = `${node.id.name}`;
435
+ let resultType = "query", expressionToResolve = init;
436
+ isDefineCall && (init.arguments.length > 0 && t__namespace.isExpression(init.arguments[0]) && (expressionToResolve = init.arguments[0]), isImportFrom(groqModuleName, defineProjectionFunctionName, scope, init.callee) && (resultType = "projection"));
437
+ const queryResult = resolveExpression({
438
+ node: expressionToResolve,
421
439
  file,
422
440
  scope,
423
441
  babelConfig,
@@ -431,7 +449,7 @@ function findQueriesInSource(source, filename, babelConfig = getBabelConfig(), r
431
449
  ...node.loc?.end
432
450
  }
433
451
  } : {};
434
- queries.push({ name: queryName, result: queryResult, location });
452
+ queries.push({ name: queryName, result: queryResult, type: resultType, location });
435
453
  }
436
454
  }
437
455
  }), queries;
@@ -499,6 +517,7 @@ async function* findQueriesInPath({
499
517
  // we never want to look in node_modules
500
518
  onlyFiles: !0
501
519
  }).sort();
520
+ yield { type: "files", fileCount: files.length };
502
521
  for (const filename of files)
503
522
  if (typeof filename == "string") {
504
523
  debug(`Found file "${filename}"`);
@@ -521,118 +540,100 @@ function registerBabel(babelOptions) {
521
540
  const options = babelOptions || getBabelConfig();
522
541
  register__default.default({ ...options, extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"] });
523
542
  }
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
- }
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;
538
553
  /**
539
- * Generate TypeScript types for the given schema
540
- * @returns string
541
- * @internal
542
- * @beta
554
+ * Enqueues an item. Throws if `finish` or `throwError` has been called.
543
555
  */
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
- `);
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);
566
560
  }
567
561
  /**
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
562
+ * Signals that no more items will be enqueued. Idempotent.
574
563
  */
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();
564
+ finish() {
565
+ this.finished || (this.finished = !0, this.resume && (this.resume(), this.resume = null));
586
566
  }
587
567
  /**
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
568
+ * Signals an error occurred during production. Finishes the queue. Idempotent.
598
569
  */
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();
570
+ throwError(error) {
571
+ this.finished || (this.pendingError = error, this.finished = !0, this.resume && (this.resume(), this.resume = null));
622
572
  }
623
573
  /**
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.
574
+ * Async iterator to consume enqueued items.
575
+ * Throws if `throwError` was called.
627
576
  */
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;
634
- }
635
- getTypeNodeType(typeNode) {
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((resolve) => {
582
+ this.resume = resolve;
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;
589
+ }
590
+ if (this.pendingError)
591
+ throw this.pendingError;
592
+ }
593
+ }
594
+ class SchemaTypeGenerator {
595
+ static ProjectionBase = t__namespace.identifier("ProjectionBase");
596
+ static InternalReferenceSymbol = Object.assign(t__namespace.identifier("internalGroqTypeReferenceTo"), {
597
+ typeAnnotation: t__namespace.tsTypeAnnotation(
598
+ Object.assign(t__namespace.tsTypeOperator(t__namespace.tsSymbolKeyword()), { operator: "unique" })
599
+ )
600
+ });
601
+ static sanitizeIdentifier(input) {
602
+ return `${input.replace(/^\d/, "_").replace(/[^$\w]+(.)/g, (_, char) => char.toUpperCase())}`;
603
+ }
604
+ static normalizeIdentifier(input) {
605
+ const sanitized = SchemaTypeGenerator.sanitizeIdentifier(input);
606
+ return `${sanitized.charAt(0).toUpperCase()}${sanitized.slice(1)}`;
607
+ }
608
+ schema;
609
+ schemaId;
610
+ typeNames = /* @__PURE__ */ new Set();
611
+ tsTypes = /* @__PURE__ */ new Map();
612
+ identifiers = /* @__PURE__ */ new Map();
613
+ constructor({ schema, schemaId }) {
614
+ this.schemaId = schemaId, this.schema = schema;
615
+ for (const type of schema) {
616
+ if (this.typeNames.has(type.name))
617
+ throw new Error(
618
+ `Duplicate type name "${type.name}" in schema "${schemaId}". Type names must be unique within the same schema.`
619
+ );
620
+ this.typeNames.add(type.name);
621
+ }
622
+ const uniqueIdentifiers = /* @__PURE__ */ new Set();
623
+ for (const type of schema) {
624
+ const desiredName = SchemaTypeGenerator.normalizeIdentifier(type.name);
625
+ let resultingName = desiredName, index = 2;
626
+ for (; uniqueIdentifiers.has(resultingName); )
627
+ resultingName = `${desiredName}_${index}`, index++;
628
+ uniqueIdentifiers.add(resultingName), this.identifiers.set(type.name, t__namespace.identifier(resultingName));
629
+ }
630
+ for (const type of schema)
631
+ this.tsTypes.set(type.name, this.generateTsType(type));
632
+ }
633
+ shouldOmitProjection({ rest, attributes }) {
634
+ return rest?.type === "unknown" || rest?.type === "object" && this.shouldOmitProjection(rest) ? !0 : Object.values(attributes).every((attr) => attr.value.type === "null");
635
+ }
636
+ generateTsType(typeNode) {
636
637
  switch (typeNode.type) {
637
638
  case "string":
638
639
  return typeNode.value !== void 0 ? t__namespace.tsLiteralType(t__namespace.stringLiteral(typeNode.value)) : t__namespace.tsStringKeyword();
@@ -643,9 +644,9 @@ class TypeGenerator {
643
644
  case "unknown":
644
645
  return t__namespace.tsUnknownKeyword();
645
646
  case "document":
646
- return this.generateDocumentType(typeNode);
647
+ return this.generateDocumentTsType(typeNode);
647
648
  case "type":
648
- return this.getTypeNodeType(typeNode.value);
649
+ return this.generateTsType(typeNode.value);
649
650
  case "array":
650
651
  return this.generateArrayTsType(typeNode);
651
652
  case "object":
@@ -657,21 +658,21 @@ class TypeGenerator {
657
658
  case "null":
658
659
  return t__namespace.tsNullKeyword();
659
660
  default:
660
- throw new Error(`Type "${typeNode.type}" not found in schema`);
661
+ throw new Error(
662
+ `Encountered unsupported node type "${// @ts-expect-error This should never happen
663
+ typeNode.type}" while generating schema types for schema "${this.schemaId}"`
664
+ );
661
665
  }
662
666
  }
663
667
  // Helper function used to generate TS types for array type nodes.
664
668
  generateArrayTsType(typeNode) {
665
- const typeNodes = this.getTypeNodeType(typeNode.of);
666
- return t__namespace.tsTypeReference(
667
- t__namespace.identifier("Array"),
668
- t__namespace.tsTypeParameterInstantiation([typeNodes])
669
- );
669
+ const typeNodes = this.generateTsType(typeNode.of);
670
+ return t__namespace.tsTypeReference(t__namespace.identifier("Array"), t__namespace.tsTypeParameterInstantiation([typeNodes]));
670
671
  }
671
672
  // Helper function used to generate TS types for object properties.
672
- generateObjectProperty(key, attribute) {
673
- const type = this.getTypeNodeType(attribute.value), propertySignature = t__namespace.tsPropertySignature(
674
- t__namespace.identifier(sanitizeIdentifier(key)),
673
+ generateTsObjectProperty(key, attribute) {
674
+ const type = this.generateTsType(attribute.value), propertySignature = t__namespace.tsPropertySignature(
675
+ t__namespace.identifier(SchemaTypeGenerator.sanitizeIdentifier(key)),
675
676
  t__namespace.tsTypeAnnotation(type)
676
677
  );
677
678
  return propertySignature.optional = attribute.optional, propertySignature;
@@ -680,16 +681,16 @@ class TypeGenerator {
680
681
  generateObjectTsType(typeNode) {
681
682
  const props = [];
682
683
  Object.entries(typeNode.attributes).forEach(([key, attribute]) => {
683
- props.push(this.generateObjectProperty(key, attribute));
684
+ props.push(this.generateTsObjectProperty(key, attribute));
684
685
  });
685
686
  const rest = typeNode.rest;
686
- if (rest !== void 0)
687
+ if (rest)
687
688
  switch (rest.type) {
688
689
  case "unknown":
689
690
  return t__namespace.tsUnknownKeyword();
690
691
  case "object": {
691
692
  Object.entries(rest.attributes).forEach(([key, attribute]) => {
692
- props.push(this.generateObjectProperty(key, attribute));
693
+ props.push(this.generateTsObjectProperty(key, attribute));
693
694
  });
694
695
  break;
695
696
  }
@@ -700,55 +701,419 @@ class TypeGenerator {
700
701
  default:
701
702
  throw new Error(`Type "${rest.type}" not found in schema`);
702
703
  }
703
- if (typeNode.dereferencesTo !== void 0) {
704
- const derefType = t__namespace.tsPropertySignature(
705
- t__namespace.identifier(REFERENCE_SYMBOL_NAME),
706
- t__namespace.tsTypeAnnotation(t__namespace.tsLiteralType(t__namespace.stringLiteral(typeNode.dereferencesTo)))
704
+ if (typeNode.dereferencesTo) {
705
+ const derefType = Object.assign(
706
+ t__namespace.tsPropertySignature(
707
+ SchemaTypeGenerator.InternalReferenceSymbol,
708
+ t__namespace.tsTypeAnnotation(t__namespace.tsLiteralType(t__namespace.stringLiteral(typeNode.dereferencesTo)))
709
+ ),
710
+ { computed: !0, optional: !0 }
707
711
  );
708
- derefType.computed = !0, derefType.optional = !0, props.push(derefType);
712
+ props.push(derefType);
709
713
  }
710
714
  return t__namespace.tsTypeLiteral(props);
711
715
  }
712
716
  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();
717
+ const identifier = this.getIdentifier(typeNode.name);
718
+ return identifier ? t__namespace.tsTypeReference(identifier) : t__namespace.addComment(
719
+ t__namespace.tsUnknownKeyword(),
720
+ "trailing",
721
+ ` Unable to locate the referenced type "${typeNode.name}" in schema "${this.schemaId}"`,
722
+ !0
723
+ );
728
724
  }
729
725
  // Helper function used to generate TS types for union type nodes.
730
726
  generateUnionTsType(typeNode) {
731
- if (typeNode.of.length === 0)
732
- return t__namespace.tsNeverKeyword();
733
- if (typeNode.of.length === 1)
734
- return this.getTypeNodeType(typeNode.of[0]);
735
- const typeNodes = typeNode.of.map((node) => this.getTypeNodeType(node));
736
- return t__namespace.tsUnionType(typeNodes);
727
+ return typeNode.of.length === 0 ? t__namespace.tsNeverKeyword() : typeNode.of.length === 1 ? this.generateTsType(typeNode.of[0]) : t__namespace.tsUnionType(typeNode.of.map((node) => this.generateTsType(node)));
737
728
  }
738
729
  // Helper function used to generate TS types for document type nodes.
739
- generateDocumentType(document) {
730
+ generateDocumentTsType(document) {
740
731
  const props = Object.entries(document.attributes).map(
741
- ([key, node]) => this.generateObjectProperty(key, node)
732
+ ([key, node]) => this.generateTsObjectProperty(key, node)
742
733
  );
743
734
  return t__namespace.tsTypeLiteral(props);
744
735
  }
736
+ getTypeNames() {
737
+ return Array.from(this.typeNames);
738
+ }
739
+ getTsType(typeName) {
740
+ return this.tsTypes.get(typeName);
741
+ }
742
+ getIdentifier(typeName) {
743
+ return this.identifiers.get(typeName);
744
+ }
745
+ evaluateQuery(query) {
746
+ const ast = safeParseQuery(query), typeNode = groqJs.typeEvaluate(ast, this.schema), tsType = this.generateTsType(typeNode), stats = walkAndCountQueryTypeNodeStats(typeNode);
747
+ return { tsType, stats };
748
+ }
749
+ evaluateProjection(projection) {
750
+ const results = [];
751
+ for (const schemaType of this.schema) {
752
+ if (schemaType.type !== "document") continue;
753
+ if (safeParseQuery(projection).type !== "Object")
754
+ throw new Error(
755
+ `Invalid projection syntax: Projections must be enclosed in curly braces, (e.g., "{_id, title}"). Received: "${projection}"`
756
+ );
757
+ const ast = safeParseQuery(`* [_type==${JSON.stringify(schemaType.name)}] ${projection} [0]`), result = groqJs.typeEvaluate(ast, this.schema);
758
+ if (result.type !== "union" || result.of.length !== 2) continue;
759
+ const projectionResult = result.of.find((node) => node.type !== "null");
760
+ if (projectionResult?.type !== "object" || this.shouldOmitProjection(projectionResult)) continue;
761
+ const stats = walkAndCountQueryTypeNodeStats(projectionResult), tsType = t__namespace.tsTypeReference(
762
+ SchemaTypeGenerator.ProjectionBase,
763
+ t__namespace.tsTypeParameterInstantiation([
764
+ this.generateTsType(projectionResult),
765
+ t__namespace.tsLiteralType(t__namespace.stringLiteral(schemaType.name))
766
+ ])
767
+ );
768
+ results.push({ tsType, stats });
769
+ }
770
+ if (!results.length) return null;
771
+ if (results.length === 1) return results[0];
772
+ const combinedTsType = t__namespace.tsUnionType(results.map((i) => i.tsType)), accumulatedStats = results.reduce(
773
+ (acc, { stats }) => ({
774
+ allTypes: acc.allTypes + stats.allTypes,
775
+ emptyUnions: acc.emptyUnions + stats.emptyUnions,
776
+ unknownTypes: acc.unknownTypes + stats.unknownTypes
777
+ }),
778
+ { allTypes: 0, unknownTypes: 0, emptyUnions: 0 }
779
+ );
780
+ return accumulatedStats.allTypes += 1, { tsType: combinedTsType, stats: accumulatedStats };
781
+ }
782
+ }
783
+ function walkAndCountQueryTypeNodeStats(typeNode) {
784
+ switch (typeNode.type) {
785
+ case "unknown":
786
+ return { allTypes: 1, unknownTypes: 1, emptyUnions: 0 };
787
+ case "array": {
788
+ const acc = walkAndCountQueryTypeNodeStats(typeNode.of);
789
+ return acc.allTypes += 1, acc;
790
+ }
791
+ case "object": {
792
+ if (typeNode.rest && typeNode.rest.type === "unknown")
793
+ return { allTypes: 2, unknownTypes: 1, emptyUnions: 0 };
794
+ const restStats = typeNode.rest ? walkAndCountQueryTypeNodeStats(typeNode.rest) : { allTypes: 0, unknownTypes: 0, emptyUnions: 0 };
795
+ return restStats.allTypes += 1, Object.values(typeNode.attributes).reduce((acc, attribute) => {
796
+ const { allTypes, unknownTypes, emptyUnions } = walkAndCountQueryTypeNodeStats(
797
+ attribute.value
798
+ );
799
+ return {
800
+ allTypes: acc.allTypes + allTypes,
801
+ unknownTypes: acc.unknownTypes + unknownTypes,
802
+ emptyUnions: acc.emptyUnions + emptyUnions
803
+ };
804
+ }, restStats);
805
+ }
806
+ case "union":
807
+ return typeNode.of.length === 0 ? { allTypes: 1, unknownTypes: 0, emptyUnions: 1 } : typeNode.of.reduce(
808
+ (acc, type) => {
809
+ const { allTypes, unknownTypes, emptyUnions } = walkAndCountQueryTypeNodeStats(type);
810
+ return {
811
+ allTypes: acc.allTypes + allTypes,
812
+ unknownTypes: acc.unknownTypes + unknownTypes,
813
+ emptyUnions: acc.emptyUnions + emptyUnions
814
+ };
815
+ },
816
+ { allTypes: 1, unknownTypes: 0, emptyUnions: 0 }
817
+ // count the union type itself
818
+ );
819
+ default:
820
+ return { allTypes: 1, unknownTypes: 0, emptyUnions: 0 };
821
+ }
822
+ }
823
+ const SanityQueries = t__namespace.identifier("SanityQueries"), SanityProjections = t__namespace.identifier("SanityProjections"), SanitySchemas = t__namespace.identifier("SanitySchemas"), SchemaOrigin = t__namespace.identifier("SchemaOrigin"), PickSchema = t__namespace.identifier("PickSchema"), AllSanitySchemaTypes = t__namespace.identifier("AllSanitySchemaTypes");
824
+ class TypeGenerator {
825
+ schemas;
826
+ augmentGroqModule;
827
+ overloadClientMethods;
828
+ schemaFilenames = /* @__PURE__ */ new Map();
829
+ globalIdentifiers = /* @__PURE__ */ new Set();
830
+ identifiersByQuery = /* @__PURE__ */ new Map();
831
+ identifiersByProjection = /* @__PURE__ */ new Map();
832
+ queryResultsQueue = new AsyncQueue();
833
+ augmentedQueryResultsPromise = promiseWithResolvers();
834
+ queryFileCountPromise = promiseWithResolvers();
835
+ constructor({
836
+ schemas,
837
+ queriesByFile,
838
+ augmentGroqModule = !0,
839
+ overloadClientMethods = !0
840
+ }) {
841
+ 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);
842
+ const schemaIds = /* @__PURE__ */ new Set();
843
+ for (const { schemaId, filename } of schemas) {
844
+ if (schemaIds.has(schemaId))
845
+ throw new Error(`Duplicate schema ID "${schemaId}". Schema IDs must be unique.`);
846
+ schemaIds.add(schemaId), filename && this.schemaFilenames.set(schemaId, filename);
847
+ }
848
+ this.schemas = schemas.map((opts) => new SchemaTypeGenerator(opts)), this.augmentGroqModule = augmentGroqModule, this.overloadClientMethods = overloadClientMethods, this.getSchemaTypeDeclarations(), this.getSchemaDeclarations(), queriesByFile ? this.handleQueries(queriesByFile).catch((error) => {
849
+ this.queryFileCountPromise.reject(error), this.queryResultsQueue.throwError(error), this.augmentedQueryResultsPromise.reject(error);
850
+ }) : this.queryFileCountPromise.resolve({ fileCount: 0 });
851
+ }
852
+ async handleQueries(queriesByFile) {
853
+ for await (const result of queriesByFile) {
854
+ if (result.type === "files") {
855
+ this.queryFileCountPromise.resolve({ fileCount: result.fileCount });
856
+ continue;
857
+ }
858
+ try {
859
+ if (result.type === "error") throw result.error;
860
+ const { filename, queries } = result, queryResultDeclarations = [];
861
+ for (const query of queries)
862
+ try {
863
+ queryResultDeclarations.push({
864
+ filename,
865
+ query: query.result,
866
+ ...this.generateQueryResultType({ ...query, filename })
867
+ });
868
+ } catch (error) {
869
+ this.queryResultsQueue.enqueue({ type: "error", filename, error });
870
+ }
871
+ this.queryResultsQueue.enqueue({ type: "queries", filename, queryResultDeclarations });
872
+ } catch (error) {
873
+ this.queryResultsQueue.enqueue({ type: "error", filename: result.filename, error });
874
+ }
875
+ }
876
+ this.queryResultsQueue.finish();
877
+ let augmentedQueryResultsCode = "";
878
+ const clientModuleBlockStatement = [], groqModuleBlockStatement = [];
879
+ if (this.identifiersByQuery.size > 0) {
880
+ const sanityQueriesInterfaceDeclaration = t__namespace.tsInterfaceDeclaration(
881
+ SanityQueries,
882
+ null,
883
+ [],
884
+ t__namespace.tsInterfaceBody(
885
+ Array.from(this.identifiersByQuery).map(
886
+ ([query, identifiers]) => t__namespace.tsPropertySignature(
887
+ t__namespace.stringLiteral(query),
888
+ t__namespace.tsTypeAnnotation(
889
+ identifiers.length === 1 ? t__namespace.tsTypeReference(identifiers[0]) : t__namespace.tsUnionType(identifiers.map((i) => t__namespace.tsTypeReference(i)))
890
+ )
891
+ )
892
+ )
893
+ )
894
+ );
895
+ clientModuleBlockStatement.push(sanityQueriesInterfaceDeclaration), groqModuleBlockStatement.push(sanityQueriesInterfaceDeclaration);
896
+ }
897
+ if (this.identifiersByProjection.size > 0) {
898
+ const sanityProjectionsInterfaceDeclaration = t__namespace.tsInterfaceDeclaration(
899
+ SanityProjections,
900
+ null,
901
+ [],
902
+ t__namespace.tsInterfaceBody(
903
+ Array.from(this.identifiersByProjection).map(
904
+ ([projection, identifiers]) => t__namespace.tsPropertySignature(
905
+ t__namespace.stringLiteral(projection),
906
+ t__namespace.tsTypeAnnotation(
907
+ identifiers.length === 1 ? t__namespace.tsTypeReference(identifiers[0]) : t__namespace.tsUnionType(identifiers.map((i) => t__namespace.tsTypeReference(i)))
908
+ )
909
+ )
910
+ )
911
+ )
912
+ );
913
+ groqModuleBlockStatement.push(sanityProjectionsInterfaceDeclaration);
914
+ }
915
+ if (this.overloadClientMethods && clientModuleBlockStatement.length > 0) {
916
+ const clientModuleDeclaration = t__namespace.declareModule(
917
+ t__namespace.stringLiteral("@sanity/client"),
918
+ t__namespace.blockStatement(clientModuleBlockStatement)
919
+ );
920
+ augmentedQueryResultsCode += generateCode(clientModuleDeclaration);
921
+ }
922
+ if (this.augmentGroqModule && groqModuleBlockStatement.length > 0) {
923
+ const groqModuleDeclaration = t__namespace.declareModule(
924
+ t__namespace.stringLiteral("groq"),
925
+ t__namespace.blockStatement(groqModuleBlockStatement)
926
+ );
927
+ augmentedQueryResultsCode += generateCode(groqModuleDeclaration);
928
+ }
929
+ this.augmentedQueryResultsPromise.resolve({ code: augmentedQueryResultsCode });
930
+ }
931
+ generateQueryResultType({
932
+ name,
933
+ result,
934
+ type,
935
+ filename
936
+ }) {
937
+ const evaluationResults = [];
938
+ for (const schema of this.schemas) {
939
+ const { schemaId } = schema;
940
+ if (type === "projection") {
941
+ const projectionResult = schema.evaluateProjection(result);
942
+ if (!projectionResult) continue;
943
+ evaluationResults.push({ schemaId, ...projectionResult });
944
+ } else {
945
+ const queryResult = schema.evaluateQuery(result);
946
+ evaluationResults.push({ schemaId, ...queryResult });
947
+ }
948
+ }
949
+ const tsTypes = evaluationResults.map(({ tsType: tsType2, schemaId }) => this.schemas.length === 1 ? tsType2 : addSchemaOrigin(tsType2, schemaId)), tsType = tsTypes.length === 1 ? tsTypes[0] : t__namespace.tsUnionType(tsTypes), { code, id } = this.generateAndRegisterExportedTypeAlias(
950
+ `${name}${type === "projection" ? "ProjectionResult" : "Result"}`,
951
+ tsType,
952
+ [
953
+ { type: "CommentLine", value: ` Source: ${filename}` },
954
+ { type: "CommentLine", value: ` Variable: ${name}` },
955
+ {
956
+ type: "CommentLine",
957
+ value: ` ${type === "projection" ? "Projection" : "Query"}: ${result.replace(/(\r\n|\n|\r)/gm, "").trim()}`
958
+ }
959
+ ]
960
+ ), identifiersByProjectionOrQuery = type === "projection" ? this.identifiersByProjection : this.identifiersByQuery;
961
+ let identifiers = identifiersByProjectionOrQuery.get(result);
962
+ return identifiers || (identifiers = [], identifiersByProjectionOrQuery.set(result, identifiers)), identifiers.push(id), {
963
+ code,
964
+ id,
965
+ name,
966
+ type,
967
+ stats: evaluationResults.reduce(
968
+ (acc, { stats }) => ({
969
+ allTypes: acc.allTypes + stats.allTypes,
970
+ unknownTypes: acc.unknownTypes + stats.unknownTypes,
971
+ emptyUnions: acc.emptyUnions + stats.emptyUnions
972
+ }),
973
+ { allTypes: 0, unknownTypes: 0, emptyUnions: 0 }
974
+ )
975
+ };
976
+ }
977
+ generateAndRegisterExportedTypeAlias(name, tsType, comments) {
978
+ const desiredName = SchemaTypeGenerator.normalizeIdentifier(name);
979
+ let resultingName = desiredName, index = 2;
980
+ for (; this.globalIdentifiers.has(resultingName); )
981
+ resultingName = `${desiredName}_${index}`, index++;
982
+ this.globalIdentifiers.add(resultingName);
983
+ const id = t__namespace.identifier(resultingName), typeAlias = t__namespace.tsTypeAliasDeclaration(id, null, tsType);
984
+ let exportDeclaration = t__namespace.exportNamedDeclaration(typeAlias);
985
+ comments && (exportDeclaration = t__namespace.addComments(exportDeclaration, "leading", comments));
986
+ const code = generateCode(exportDeclaration);
987
+ return { id, code };
988
+ }
989
+ getKnownTypes = computeOnce(() => {
990
+ let code = "";
991
+ this.overloadClientMethods && (code += generateCode(t__namespace.importDeclaration([], t__namespace.stringLiteral("@sanity/client"))));
992
+ const importSpecifiers = [
993
+ t__namespace.importSpecifier(SchemaTypeGenerator.ProjectionBase, SchemaTypeGenerator.ProjectionBase)
994
+ ];
995
+ return this.schemas.length > 1 && (importSpecifiers.push(t__namespace.importSpecifier(PickSchema, PickSchema)), importSpecifiers.push(t__namespace.importSpecifier(SchemaOrigin, SchemaOrigin))), code += generateCode(
996
+ Object.assign(t__namespace.importDeclaration(importSpecifiers, t__namespace.stringLiteral("groq")), {
997
+ importKind: "type"
998
+ })
999
+ ), code += generateCode(
1000
+ t__namespace.exportNamedDeclaration(
1001
+ Object.assign(
1002
+ t__namespace.variableDeclaration("const", [
1003
+ t__namespace.variableDeclarator(SchemaTypeGenerator.InternalReferenceSymbol)
1004
+ ]),
1005
+ { declare: !0 }
1006
+ )
1007
+ )
1008
+ ), { code };
1009
+ });
1010
+ getSchemaTypeDeclarations = computeOnce(() => {
1011
+ const typeNames = new Set(this.schemas.flatMap((schema) => schema.getTypeNames()));
1012
+ return Array.from(typeNames).flatMap((typeName) => {
1013
+ const identifiers = new Set(
1014
+ this.schemas.map((schema) => schema.getIdentifier(typeName)?.name).filter((i) => typeof i == "string")
1015
+ );
1016
+ return Array.from(identifiers).map((identifier) => {
1017
+ const types = this.schemas.filter(
1018
+ (schema) => schema.getIdentifier(typeName)?.name === identifier && !!schema.getTsType(typeName)
1019
+ ).map((schema) => {
1020
+ const tsType2 = schema.getTsType(typeName), schemaId = schema.schemaId;
1021
+ return this.schemas.length < 2 ? { schemaId, tsType: tsType2 } : { schemaId, tsType: addSchemaOrigin(tsType2, schemaId) };
1022
+ }), schemaIds = types.map((i) => i.schemaId), tsType = types.length === 1 ? types[0].tsType : t__namespace.tsUnionType(types.map((i) => i.tsType)), { id, code } = this.generateAndRegisterExportedTypeAlias(identifier, tsType);
1023
+ return { id, code, schemaIds };
1024
+ });
1025
+ });
1026
+ });
1027
+ getAllSanitySchemaTypesDeclaration = computeOnce(() => {
1028
+ const schemaTypeDeclarations = this.getSchemaTypeDeclarations();
1029
+ return { code: generateCode(
1030
+ t__namespace.exportNamedDeclaration(
1031
+ t__namespace.tsTypeAliasDeclaration(
1032
+ AllSanitySchemaTypes,
1033
+ null,
1034
+ t__namespace.tsUnionType(schemaTypeDeclarations.map(({ id }) => t__namespace.tsTypeReference(id)))
1035
+ )
1036
+ )
1037
+ ) };
1038
+ });
1039
+ getSchemaDeclarations = computeOnce(() => {
1040
+ const identifierUsageCountBySchemaId = this.getSchemaTypeDeclarations().reduce((acc, { schemaIds, id }) => {
1041
+ for (const schemaId of schemaIds)
1042
+ acc[schemaId] = acc[schemaId] ?? {}, acc[schemaId][id.name] = schemaIds.length;
1043
+ return acc;
1044
+ }, {});
1045
+ return this.schemas.map(({ schemaId }) => {
1046
+ const tsTypes = Object.entries(identifierUsageCountBySchemaId[schemaId]).map(
1047
+ ([identifierName, schemaCount]) => {
1048
+ const schemaTypeReferencer = t__namespace.tsTypeReference(t__namespace.identifier(identifierName));
1049
+ return schemaCount > 1 ? addPickSchema(schemaTypeReferencer, schemaId) : schemaTypeReferencer;
1050
+ }
1051
+ ), tsType = tsTypes.length === 1 ? tsTypes[0] : t__namespace.tsUnionType(tsTypes), comments = [], filename = this.schemaFilenames.get(schemaId);
1052
+ filename && comments.push({ type: "CommentLine", value: ` Source: ${filename}` }), comments.push({ type: "CommentLine", value: ` Schema ID: ${schemaId}` });
1053
+ const { id, code } = this.generateAndRegisterExportedTypeAlias(
1054
+ `${schemaId}Schema`,
1055
+ tsType,
1056
+ comments
1057
+ );
1058
+ return { id, code, schemaId };
1059
+ });
1060
+ });
1061
+ getAugmentedSchemasDeclarations = computeOnce(() => {
1062
+ if (!this.augmentGroqModule) return { code: "" };
1063
+ const schemaDeclarations = this.getSchemaDeclarations(), groqModuleDeclaration = t__namespace.declareModule(
1064
+ t__namespace.stringLiteral("groq"),
1065
+ t__namespace.blockStatement([
1066
+ t__namespace.tsInterfaceDeclaration(
1067
+ SanitySchemas,
1068
+ null,
1069
+ [],
1070
+ t__namespace.tsInterfaceBody(
1071
+ schemaDeclarations.map(
1072
+ ({ id, schemaId }) => t__namespace.tsPropertySignature(
1073
+ t__namespace.stringLiteral(schemaId),
1074
+ t__namespace.tsTypeAnnotation(t__namespace.tsTypeReference(id))
1075
+ )
1076
+ )
1077
+ )
1078
+ )
1079
+ ])
1080
+ );
1081
+ return { code: generateCode(groqModuleDeclaration) };
1082
+ });
1083
+ getQueryFileCount = () => this.queryFileCountPromise.promise;
1084
+ getQueryResultDeclarations = () => this.queryResultsQueue;
1085
+ getAugmentedQueryResultsDeclarations = () => this.augmentedQueryResultsPromise.promise;
745
1086
  }
746
- function uppercaseFirstLetter(input) {
747
- return input.charAt(0).toUpperCase() + input.slice(1);
1087
+ function computeOnce(fn) {
1088
+ const ref = { current: void 0, computed: !1 };
1089
+ return function() {
1090
+ return ref.computed || (ref.current = fn.call(this), ref.computed = !0), ref.current;
1091
+ };
1092
+ }
1093
+ function addSchemaOrigin(tsType, schemaId) {
1094
+ return t__namespace.tsTypeReference(
1095
+ SchemaOrigin,
1096
+ t__namespace.tsTypeParameterInstantiation([tsType, t__namespace.tsLiteralType(t__namespace.stringLiteral(schemaId))])
1097
+ );
1098
+ }
1099
+ function addPickSchema(tsType, schemaId) {
1100
+ return t__namespace.tsTypeReference(
1101
+ PickSchema,
1102
+ t__namespace.tsTypeParameterInstantiation([tsType, t__namespace.tsLiteralType(t__namespace.stringLiteral(schemaId))])
1103
+ );
1104
+ }
1105
+ function generateCode(node) {
1106
+ return `${new generator.CodeGenerator(node).generate().code.trim()}
1107
+
1108
+ `;
748
1109
  }
749
- function sanitizeIdentifier(input) {
750
- return `${input.replace(/^\d/, "_").replace(/[^$\w]+(.)/g, (_, char) => char.toUpperCase())}`;
1110
+ function promiseWithResolvers() {
1111
+ let resolve, reject;
1112
+ return { promise: new Promise((thisResolve, thisReject) => {
1113
+ resolve = thisResolve, reject = thisReject;
1114
+ }), resolve, reject };
751
1115
  }
1116
+ exports.DEFAULT_CONFIG = DEFAULT_CONFIG;
752
1117
  exports.TypeGenerator = TypeGenerator;
753
1118
  exports.findQueriesInPath = findQueriesInPath;
754
1119
  exports.findQueriesInSource = findQueriesInSource;