@ptdgrp/typedgql 1.0.0-beta.16 → 1.0.0-beta.20

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.
Files changed (49) hide show
  1. package/README.md +55 -2
  2. package/README.zh-CN.md +57 -4
  3. package/dist/cli.cjs +47 -0
  4. package/dist/cli.d.cts +1 -0
  5. package/dist/cli.d.mts +1 -0
  6. package/dist/cli.mjs +49 -0
  7. package/dist/cli.mjs.map +1 -0
  8. package/dist/{schema-loader-BIP51DZO.cjs → config-loader-Bxj44SGD.cjs} +348 -41
  9. package/dist/{schema-loader-CsabdnfI.mjs → config-loader-DZ7d_CWR.mjs} +342 -47
  10. package/dist/config-loader-DZ7d_CWR.mjs.map +1 -0
  11. package/dist/cyrb53-B2tdX6NT.mjs +921 -0
  12. package/dist/cyrb53-B2tdX6NT.mjs.map +1 -0
  13. package/dist/cyrb53-BTzxwvXR.cjs +1010 -0
  14. package/dist/cyrb53-DWYFRdWZ.d.mts +333 -0
  15. package/dist/cyrb53-DWYFRdWZ.d.mts.map +1 -0
  16. package/dist/cyrb53-FbY3n_2r.d.cts +333 -0
  17. package/dist/cyrb53-FbY3n_2r.d.cts.map +1 -0
  18. package/dist/index.cjs +18 -935
  19. package/dist/index.d.cts +2 -333
  20. package/dist/index.d.mts +2 -333
  21. package/dist/index.mjs +3 -920
  22. package/dist/node.cjs +6 -4
  23. package/dist/node.d.cts +63 -2
  24. package/dist/node.d.cts.map +1 -1
  25. package/dist/node.d.mts +63 -2
  26. package/dist/node.d.mts.map +1 -1
  27. package/dist/node.mjs +2 -2
  28. package/dist/{options-CgrZ2der.d.cts → options-B6mcYDIz.d.cts} +10 -1
  29. package/dist/options-B6mcYDIz.d.cts.map +1 -0
  30. package/dist/{options-BWcHrC-1.d.mts → options-T07dJfbz.d.mts} +10 -1
  31. package/dist/options-T07dJfbz.d.mts.map +1 -0
  32. package/dist/runtime.cjs +18 -0
  33. package/dist/runtime.d.cts +2 -0
  34. package/dist/runtime.d.mts +2 -0
  35. package/dist/runtime.mjs +3 -0
  36. package/dist/vite.cjs +48 -29
  37. package/dist/vite.d.cts +13 -3
  38. package/dist/vite.d.cts.map +1 -1
  39. package/dist/vite.d.mts +13 -3
  40. package/dist/vite.d.mts.map +1 -1
  41. package/dist/vite.mjs +46 -27
  42. package/dist/vite.mjs.map +1 -1
  43. package/package.json +23 -4
  44. package/dist/index.d.cts.map +0 -1
  45. package/dist/index.d.mts.map +0 -1
  46. package/dist/index.mjs.map +0 -1
  47. package/dist/options-BWcHrC-1.d.mts.map +0 -1
  48. package/dist/options-CgrZ2der.d.cts.map +0 -1
  49. package/dist/schema-loader-CsabdnfI.mjs.map +0 -1
@@ -1,8 +1,11 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { normalize, resolve } from "node:path";
1
3
  import { GraphQLEnumType, GraphQLInputObjectType, GraphQLInterfaceType, GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLScalarType, GraphQLUnionType, buildClientSchema, buildSchema, getIntrospectionQuery } from "graphql";
2
- import { mkdir, readFile, rm, writeFile } from "fs/promises";
4
+ import { mkdir, readFile as readFile$1, rm, writeFile } from "fs/promises";
3
5
  import { createWriteStream } from "fs";
4
- import { join, resolve } from "path";
6
+ import { join, normalize as normalize$1, resolve as resolve$1 } from "path";
5
7
  import ts from "typescript";
8
+ import { parse } from "smol-toml";
6
9
 
7
10
  //#region src/codegen/utils.ts
8
11
  /**
@@ -83,62 +86,63 @@ var JSImportCollector = class {
83
86
  return Array.from(map.entries()).sort((a, b) => a[0].localeCompare(b[0]));
84
87
  }
85
88
  };
86
- const RUNTIME_ENTRY_SOURCE = "../../dist/index.mjs";
89
+ const DEFAULT_RUNTIME_ENTRY_SOURCE = "../../dist/index.mjs";
90
+ const DEFAULT_ROOT_RUNTIME_ENTRY_SOURCE = "../dist/index.mjs";
87
91
  const TYPE_HIERARCHY_SOURCE = "../type-hierarchy";
88
92
  const ENUM_INPUT_METADATA_SOURCE = "../enum-input-metadata";
89
93
  const SCALAR_TYPES_SOURCE = "../scalar-types";
90
94
  const SCALAR_TYPES_NAMESPACE = "UserScalarTypes";
91
95
  const CODEGEN_IMPORT_SOURCE_MAP = {
92
96
  AcceptableVariables: {
93
- source: RUNTIME_ENTRY_SOURCE,
97
+ source: DEFAULT_RUNTIME_ENTRY_SOURCE,
94
98
  kind: "type"
95
99
  },
96
100
  UnresolvedVariables: {
97
- source: RUNTIME_ENTRY_SOURCE,
101
+ source: DEFAULT_RUNTIME_ENTRY_SOURCE,
98
102
  kind: "type"
99
103
  },
100
104
  DirectiveArgs: {
101
- source: RUNTIME_ENTRY_SOURCE,
105
+ source: DEFAULT_RUNTIME_ENTRY_SOURCE,
102
106
  kind: "type"
103
107
  },
104
108
  Selection: {
105
- source: RUNTIME_ENTRY_SOURCE,
109
+ source: DEFAULT_RUNTIME_ENTRY_SOURCE,
106
110
  kind: "type"
107
111
  },
108
112
  ShapeOf: {
109
- source: RUNTIME_ENTRY_SOURCE,
113
+ source: DEFAULT_RUNTIME_ENTRY_SOURCE,
110
114
  kind: "type"
111
115
  },
112
116
  VariablesOf: {
113
- source: RUNTIME_ENTRY_SOURCE,
117
+ source: DEFAULT_RUNTIME_ENTRY_SOURCE,
114
118
  kind: "type"
115
119
  },
116
120
  ValueOrThunk: {
117
- source: RUNTIME_ENTRY_SOURCE,
121
+ source: DEFAULT_RUNTIME_ENTRY_SOURCE,
118
122
  kind: "type"
119
123
  },
120
124
  FragmentSpread: {
121
- source: RUNTIME_ENTRY_SOURCE,
125
+ source: DEFAULT_RUNTIME_ENTRY_SOURCE,
122
126
  kind: "type"
123
127
  },
124
128
  createSelection: {
125
- source: RUNTIME_ENTRY_SOURCE,
129
+ source: DEFAULT_RUNTIME_ENTRY_SOURCE,
126
130
  kind: "value"
127
131
  },
128
132
  withOperationName: {
129
- source: RUNTIME_ENTRY_SOURCE,
133
+ source: DEFAULT_RUNTIME_ENTRY_SOURCE,
130
134
  kind: "value"
131
135
  },
132
136
  createSchemaType: {
133
- source: RUNTIME_ENTRY_SOURCE,
137
+ source: DEFAULT_RUNTIME_ENTRY_SOURCE,
134
138
  kind: "value"
135
139
  },
136
140
  registerSchemaTypeFactory: {
137
- source: RUNTIME_ENTRY_SOURCE,
141
+ source: DEFAULT_RUNTIME_ENTRY_SOURCE,
138
142
  kind: "value"
139
143
  },
140
144
  resolveRegisteredSchemaType: {
141
- source: RUNTIME_ENTRY_SOURCE,
145
+ source: DEFAULT_RUNTIME_ENTRY_SOURCE,
142
146
  kind: "value"
143
147
  },
144
148
  ENUM_INPUT_METADATA: {
@@ -158,10 +162,73 @@ const CODEGEN_IMPORT_SOURCE_MAP = {
158
162
  kind: "type"
159
163
  },
160
164
  EnumInputMetadataBuilder: {
161
- source: "../dist/index.mjs",
165
+ source: DEFAULT_ROOT_RUNTIME_ENTRY_SOURCE,
162
166
  kind: "value"
163
167
  }
164
168
  };
169
+ function createCodegenImportSourceMap(options) {
170
+ const runtimeEntrySource = options.runtimeEntrySource ?? DEFAULT_RUNTIME_ENTRY_SOURCE;
171
+ const rootRuntimeEntrySource = options.rootRuntimeEntrySource ?? DEFAULT_ROOT_RUNTIME_ENTRY_SOURCE;
172
+ return {
173
+ ...CODEGEN_IMPORT_SOURCE_MAP,
174
+ AcceptableVariables: {
175
+ source: runtimeEntrySource,
176
+ kind: "type"
177
+ },
178
+ UnresolvedVariables: {
179
+ source: runtimeEntrySource,
180
+ kind: "type"
181
+ },
182
+ DirectiveArgs: {
183
+ source: runtimeEntrySource,
184
+ kind: "type"
185
+ },
186
+ Selection: {
187
+ source: runtimeEntrySource,
188
+ kind: "type"
189
+ },
190
+ ShapeOf: {
191
+ source: runtimeEntrySource,
192
+ kind: "type"
193
+ },
194
+ VariablesOf: {
195
+ source: runtimeEntrySource,
196
+ kind: "type"
197
+ },
198
+ ValueOrThunk: {
199
+ source: runtimeEntrySource,
200
+ kind: "type"
201
+ },
202
+ FragmentSpread: {
203
+ source: runtimeEntrySource,
204
+ kind: "type"
205
+ },
206
+ createSelection: {
207
+ source: runtimeEntrySource,
208
+ kind: "value"
209
+ },
210
+ withOperationName: {
211
+ source: runtimeEntrySource,
212
+ kind: "value"
213
+ },
214
+ createSchemaType: {
215
+ source: runtimeEntrySource,
216
+ kind: "value"
217
+ },
218
+ registerSchemaTypeFactory: {
219
+ source: runtimeEntrySource,
220
+ kind: "value"
221
+ },
222
+ resolveRegisteredSchemaType: {
223
+ source: runtimeEntrySource,
224
+ kind: "value"
225
+ },
226
+ EnumInputMetadataBuilder: {
227
+ source: rootRuntimeEntrySource,
228
+ kind: "value"
229
+ }
230
+ };
231
+ }
165
232
 
166
233
  //#endregion
167
234
  //#region src/codegen/writer.ts
@@ -203,9 +270,10 @@ var Writer = class {
203
270
  importedTypes = /* @__PURE__ */ new Set();
204
271
  usesScalarTypeNamespaceImport = false;
205
272
  importFinalized = false;
206
- constructor(stream, options) {
273
+ constructor(stream, options, importSourceMap = CODEGEN_IMPORT_SOURCE_MAP) {
207
274
  this.stream = stream;
208
275
  this.options = options;
276
+ this.importSourceMap = importSourceMap;
209
277
  this.indent = options.indent ?? " ";
210
278
  }
211
279
  /**
@@ -387,7 +455,7 @@ var Writer = class {
387
455
  }
388
456
  writeMappedScalarImports() {
389
457
  if (!this.usesScalarTypeNamespaceImport) return;
390
- const source = CODEGEN_IMPORT_SOURCE_MAP.SCALAR_TYPE_NAMESPACE.source;
458
+ const source = this.importSourceMap.SCALAR_TYPE_NAMESPACE.source;
391
459
  const importSource = this.isUnderGlobalDir() ? source.replace(/^\.\.\//, "./") : source;
392
460
  this.stream.write(`import type { ${SCALAR_TYPES_NAMESPACE} } from '${importSource}';\n`);
393
461
  }
@@ -468,8 +536,8 @@ var SelectionWriter = class extends Writer {
468
536
  fieldCategoryMap;
469
537
  hasArgs;
470
538
  _declaredFieldNames;
471
- constructor(modelType, ctx, stream, options) {
472
- super(stream, options);
539
+ constructor(modelType, ctx, stream, options, importSourceMap) {
540
+ super(stream, options, importSourceMap);
473
541
  this.modelType = modelType;
474
542
  this.ctx = ctx;
475
543
  this.selectionTypeName = `${this.modelType.name}${options.selectionSuffix ?? "Selection"}`;
@@ -549,7 +617,7 @@ var SelectionWriter = class extends Writer {
549
617
  return "SCALAR";
550
618
  }
551
619
  prepareImports() {
552
- const imports = new JSImportCollector((stmt) => this.importStatement(stmt), CODEGEN_IMPORT_SOURCE_MAP);
620
+ const imports = new JSImportCollector((stmt) => this.importStatement(stmt), this.importSourceMap);
553
621
  imports.useMapped("DirectiveArgs");
554
622
  imports.useMapped("Selection");
555
623
  if (this.hasArgs) {
@@ -1175,7 +1243,7 @@ const COMMENT$1 = `/*
1175
1243
  * Any instance of this interface is immutable,
1176
1244
  * all the properties and functions can only be used to create new instances,
1177
1245
  * they cannot modify the current instance.
1178
- *
1246
+ *
1179
1247
  * So any instance of this interface is reuseable.
1180
1248
  */
1181
1249
  `;
@@ -1503,12 +1571,12 @@ var TypeHierarchyGraph = class {
1503
1571
  //#endregion
1504
1572
  //#region src/codegen/writers/enum-input-metadata.ts
1505
1573
  var EnumInputMetadataWriter = class EnumInputMetadataWriter extends Writer {
1506
- constructor(schema, stream, options) {
1507
- super(stream, options);
1574
+ constructor(schema, stream, options, importSourceMap) {
1575
+ super(stream, options, importSourceMap);
1508
1576
  this.schema = schema;
1509
1577
  }
1510
1578
  prepareImports() {
1511
- const imports = new JSImportCollector((stmt) => this.importStatement(stmt), CODEGEN_IMPORT_SOURCE_MAP);
1579
+ const imports = new JSImportCollector((stmt) => this.importStatement(stmt), this.importSourceMap);
1512
1580
  imports.useMapped("EnumInputMetadataBuilder");
1513
1581
  imports.emit();
1514
1582
  }
@@ -1610,12 +1678,123 @@ function analyzeScalarTypeDeclarations(source) {
1610
1678
  return { exportedNames };
1611
1679
  }
1612
1680
 
1681
+ //#endregion
1682
+ //#region src/codegen/prettier-formatter.ts
1683
+ let prettierInstance = void 0;
1684
+ let prettierDetected = false;
1685
+ /**
1686
+ * Detect and dynamically import prettier if available.
1687
+ * Returns null if prettier is not installed.
1688
+ */
1689
+ async function detectPrettier() {
1690
+ if (prettierDetected) return prettierInstance ?? null;
1691
+ prettierDetected = true;
1692
+ try {
1693
+ prettierInstance = await import("prettier");
1694
+ return prettierInstance;
1695
+ } catch {
1696
+ prettierInstance = null;
1697
+ return null;
1698
+ }
1699
+ }
1700
+ /**
1701
+ * Format TypeScript code using prettier if available.
1702
+ * Returns the original code if prettier is not installed or formatting fails.
1703
+ *
1704
+ * @param code - TypeScript code to format
1705
+ * @param filePath - File path for prettier config resolution
1706
+ * @returns Formatted code or original code if formatting fails
1707
+ */
1708
+ async function formatWithPrettier(code, filePath) {
1709
+ const prettier = await detectPrettier();
1710
+ if (!prettier) return code;
1711
+ try {
1712
+ const config = await prettier.resolveConfig(filePath);
1713
+ return await prettier.format(code, {
1714
+ ...config,
1715
+ parser: "typescript",
1716
+ filepath: filePath
1717
+ });
1718
+ } catch (error) {
1719
+ console.warn(`[typedgql] Failed to format ${filePath} with prettier: ${error.message}`);
1720
+ return code;
1721
+ }
1722
+ }
1723
+ /**
1724
+ * Check if prettier is available.
1725
+ * This is a lightweight check that doesn't actually import prettier.
1726
+ */
1727
+ async function isPrettierAvailable() {
1728
+ return await detectPrettier() !== null;
1729
+ }
1730
+
1731
+ //#endregion
1732
+ //#region src/codegen/buffered-stream.ts
1733
+ /**
1734
+ * A buffered write stream that collects content in memory
1735
+ * instead of writing directly to disk.
1736
+ * This allows post-processing (like prettier formatting) before writing.
1737
+ */
1738
+ var BufferedStream = class {
1739
+ buffer = [];
1740
+ ended = false;
1741
+ path;
1742
+ constructor(path) {
1743
+ this.path = path;
1744
+ }
1745
+ /**
1746
+ * Write content to the buffer.
1747
+ */
1748
+ write(chunk) {
1749
+ if (this.ended) throw new Error("Cannot write to ended stream");
1750
+ this.buffer.push(chunk);
1751
+ return true;
1752
+ }
1753
+ /**
1754
+ * Mark the stream as ended.
1755
+ * Returns a promise that resolves when the stream is closed.
1756
+ */
1757
+ end(callback) {
1758
+ this.ended = true;
1759
+ if (callback) callback();
1760
+ return Promise.resolve();
1761
+ }
1762
+ /**
1763
+ * Get the buffered content as a string.
1764
+ */
1765
+ getContent() {
1766
+ return this.buffer.join("");
1767
+ }
1768
+ /**
1769
+ * Write the buffered content to disk.
1770
+ */
1771
+ async flush(formatter) {
1772
+ let content = this.getContent();
1773
+ if (formatter) content = await formatter(content, this.path);
1774
+ await writeFile(this.path, content, "utf-8");
1775
+ }
1776
+ /**
1777
+ * Create a WriteStream-compatible interface for this buffered stream.
1778
+ * This allows it to be used with existing writer classes.
1779
+ */
1780
+ toWriteStream() {
1781
+ return {
1782
+ write: (chunk) => this.write(chunk),
1783
+ end: (callback) => {
1784
+ this.end(callback);
1785
+ }
1786
+ };
1787
+ }
1788
+ };
1789
+
1613
1790
  //#endregion
1614
1791
  //#region src/codegen/generator.ts
1615
1792
  /** Default output directory: node_modules/@ptdgrp/typedgql/__generated */
1616
- const DEFAULT_TARGET_DIR = resolve(process.cwd(), "node_modules/@ptdgrp/typedgql/__generated");
1793
+ const DEFAULT_TARGET_DIR = resolve$1(process.cwd(), "node_modules/@ptdgrp/typedgql/__generated");
1617
1794
  /** Parent package dir: node_modules/@ptdgrp/typedgql */
1618
- const PACKAGE_DIR = resolve(process.cwd(), "node_modules/@ptdgrp/typedgql");
1795
+ const PACKAGE_DIR = resolve$1(process.cwd(), "node_modules/@ptdgrp/typedgql");
1796
+ const RUNTIME_PACKAGE_NAME = "@ptdgrp/typedgql/runtime";
1797
+ const GENERATED_FILE_BANNER = "/* eslint-disable */\n// This file was generated by @ptdgrp/typedgql. Do not edit it manually.\n\n";
1619
1798
  /** Field names reserved by the runtime SelectionNode implementation. */
1620
1799
  const RESERVED_FIELDS = new Set([
1621
1800
  "constructor",
@@ -1635,6 +1814,9 @@ const RESERVED_FIELDS = new Set([
1635
1814
  "toFragmentString"
1636
1815
  ]);
1637
1816
  var Generator = class {
1817
+ usePrettier = false;
1818
+ isCustomOutputDir = false;
1819
+ bufferedStreams = [];
1638
1820
  constructor(options) {
1639
1821
  this.options = options;
1640
1822
  }
@@ -1642,6 +1824,62 @@ var Generator = class {
1642
1824
  get targetDir() {
1643
1825
  return this.options.targetDir ?? DEFAULT_TARGET_DIR;
1644
1826
  }
1827
+ /**
1828
+ * Check if we should use prettier formatting.
1829
+ * Only enabled when using custom outputDir (not in node_modules).
1830
+ */
1831
+ async initializePrettier() {
1832
+ const targetDir = this.targetDir;
1833
+ this.isCustomOutputDir = !normalize$1(targetDir).includes("node_modules");
1834
+ if (this.options.prettier === false) {
1835
+ this.usePrettier = false;
1836
+ return;
1837
+ }
1838
+ if (this.options.prettier === true || this.isCustomOutputDir) {
1839
+ this.usePrettier = await isPrettierAvailable();
1840
+ if (this.usePrettier) console.log("[typedgql] Prettier detected, will format generated files");
1841
+ }
1842
+ }
1843
+ /**
1844
+ * Create a stream for writing generated code.
1845
+ * Uses BufferedStream when prettier formatting is enabled.
1846
+ */
1847
+ createCodeStream(path) {
1848
+ const writeBanner = (stream) => {
1849
+ stream.write(GENERATED_FILE_BANNER);
1850
+ return stream;
1851
+ };
1852
+ if (this.usePrettier) {
1853
+ const buffered = new BufferedStream(path);
1854
+ this.bufferedStreams.push(buffered);
1855
+ return writeBanner(buffered.toWriteStream());
1856
+ }
1857
+ return writeBanner(createWriteStream(path));
1858
+ }
1859
+ get rootRuntimeImportSource() {
1860
+ return this.usesPackageInternalRuntimeImports ? "../dist/index.mjs" : RUNTIME_PACKAGE_NAME;
1861
+ }
1862
+ get nestedRuntimeImportSource() {
1863
+ return this.usesPackageInternalRuntimeImports ? "../../dist/index.mjs" : RUNTIME_PACKAGE_NAME;
1864
+ }
1865
+ get usesPackageInternalRuntimeImports() {
1866
+ return normalize$1(this.targetDir) === normalize$1(DEFAULT_TARGET_DIR);
1867
+ }
1868
+ get generatedImportSourceMap() {
1869
+ return createCodegenImportSourceMap({
1870
+ runtimeEntrySource: this.nestedRuntimeImportSource,
1871
+ rootRuntimeEntrySource: this.rootRuntimeImportSource
1872
+ });
1873
+ }
1874
+ /**
1875
+ * Flush all buffered streams with prettier formatting.
1876
+ */
1877
+ async flushBufferedStreams() {
1878
+ if (this.bufferedStreams.length === 0) return;
1879
+ console.log(`[typedgql] Formatting ${this.bufferedStreams.length} files with prettier...`);
1880
+ await Promise.all(this.bufferedStreams.map((stream) => stream.flush(this.usePrettier ? formatWithPrettier : void 0)));
1881
+ this.bufferedStreams = [];
1882
+ }
1645
1883
  async generate() {
1646
1884
  const schema = await this.options.schemaLoader();
1647
1885
  this.validateSchema(schema);
@@ -1651,6 +1889,7 @@ var Generator = class {
1651
1889
  force: true
1652
1890
  });
1653
1891
  await mkdir(this.targetDir, { recursive: true });
1892
+ await this.initializePrettier();
1654
1893
  const typeHierarchy = new TypeHierarchyGraph(schema);
1655
1894
  const selectionTypes = [];
1656
1895
  const inputTypes = [];
@@ -1728,10 +1967,11 @@ var Generator = class {
1728
1967
  if (this.hasScalarTypes()) promises.push(this.generateScalarTypes());
1729
1968
  promises.push(this.writeIndex(schema, ctx));
1730
1969
  await Promise.all(promises);
1970
+ await this.flushBufferedStreams();
1731
1971
  if (this.options.targetDir === void 0) await this.writePackageEntrypoint(schema, ctx);
1732
1972
  }
1733
1973
  createSelectionWriter(modelType, ctx, stream, options) {
1734
- return new SelectionWriter(modelType, ctx, stream, options);
1974
+ return new SelectionWriter(modelType, ctx, stream, options, this.generatedImportSourceMap);
1735
1975
  }
1736
1976
  additionalExportedTypeNamesForSelection(_modelType, _ctx) {
1737
1977
  return [];
@@ -1742,7 +1982,8 @@ var Generator = class {
1742
1982
  const defaultSelectionNameMap = /* @__PURE__ */ new Map();
1743
1983
  const suffix = this.options?.selectionSuffix ?? "Selection";
1744
1984
  const promises = ctx.selectionTypes.map(async (type) => {
1745
- const stream = createStream(join(dir, `${toKebabCase(`${type.name}${suffix}`)}.ts`));
1985
+ const selectionTypeName = `${type.name}${suffix}`;
1986
+ const stream = this.createCodeStream(join(dir, `${toKebabCase(selectionTypeName)}.ts`));
1746
1987
  const writer = this.createSelectionWriter(type, ctx, stream, this.options);
1747
1988
  emptySelectionNameMap.set(type, writer.emptySelectionName);
1748
1989
  if (writer.defaultSelectionName !== void 0) defaultSelectionNameMap.set(type, writer.defaultSelectionName);
@@ -1750,7 +1991,7 @@ var Generator = class {
1750
1991
  await endStream(stream);
1751
1992
  });
1752
1993
  await Promise.all([...promises, (async () => {
1753
- const stream = createStream(join(dir, "index.ts"));
1994
+ const stream = this.createCodeStream(join(dir, "index.ts"));
1754
1995
  for (const type of ctx.selectionTypes) {
1755
1996
  const selectionTypeName = `${type.name}${suffix}`;
1756
1997
  const selectionFileName = toKebabCase(selectionTypeName);
@@ -1770,7 +2011,7 @@ var Generator = class {
1770
2011
  async generateInputTypes(inputTypes) {
1771
2012
  const dir = join(this.targetDir, "inputs");
1772
2013
  const promises = inputTypes.map(async (type) => {
1773
- const stream = createStream(join(dir, `${toKebabCase(type.name)}.ts`));
2014
+ const stream = this.createCodeStream(join(dir, `${toKebabCase(type.name)}.ts`));
1774
2015
  new InputWriter(type, stream, this.options).write();
1775
2016
  await stream.end();
1776
2017
  });
@@ -1779,35 +2020,35 @@ var Generator = class {
1779
2020
  async generateEnumTypes(enumTypes) {
1780
2021
  const dir = join(this.targetDir, "enums");
1781
2022
  const promises = enumTypes.map(async (type) => {
1782
- const stream = createStream(join(dir, `${toKebabCase(type.name)}.ts`));
2023
+ const stream = this.createCodeStream(join(dir, `${toKebabCase(type.name)}.ts`));
1783
2024
  new EnumWriter(type, stream, this.options).write();
1784
2025
  await stream.end();
1785
2026
  });
1786
2027
  await Promise.all([...promises, this.writeSimpleIndex(dir, enumTypes, true)]);
1787
2028
  }
1788
2029
  async generateTypeHierarchy(schema, typeHierarchy) {
1789
- const stream = createStream(join(this.targetDir, "type-hierarchy.ts"));
2030
+ const stream = this.createCodeStream(join(this.targetDir, "type-hierarchy.ts"));
1790
2031
  new TypeHierarchyWriter(schema, typeHierarchy, stream, this.options).write();
1791
2032
  await endStream(stream);
1792
2033
  }
1793
2034
  async generateEnumInputMetadata(schema) {
1794
- const stream = createStream(join(this.targetDir, "enum-input-metadata.ts"));
1795
- new EnumInputMetadataWriter(schema, stream, this.options).write();
2035
+ const stream = this.createCodeStream(join(this.targetDir, "enum-input-metadata.ts"));
2036
+ new EnumInputMetadataWriter(schema, stream, this.options, this.generatedImportSourceMap).write();
1796
2037
  await endStream(stream);
1797
2038
  }
1798
2039
  async writeSimpleIndex(dir, types, typeOnly = true) {
1799
- const stream = createStream(join(dir, "index.ts"));
2040
+ const stream = this.createCodeStream(join(dir, "index.ts"));
1800
2041
  const keyword = typeOnly ? "export type" : "export";
1801
2042
  for (const type of types) stream.write(`${keyword} {${type.name}} from './${toKebabCase(type.name)}';\n`);
1802
2043
  await stream.end();
1803
2044
  }
1804
2045
  async generateAsyncRuntime() {
1805
- const stream = createStream(join(this.targetDir, "client-runtime.ts"));
1806
- stream.write(async_runtime_default);
2046
+ const stream = this.createCodeStream(join(this.targetDir, "client-runtime.ts"));
2047
+ stream.write(async_runtime_default.replaceAll("../dist/index.mjs", this.rootRuntimeImportSource));
1807
2048
  await endStream(stream);
1808
2049
  }
1809
2050
  async generateScalarTypes() {
1810
- const stream = createStream(join(this.targetDir, "scalar-types.ts"));
2051
+ const stream = this.createCodeStream(join(this.targetDir, "scalar-types.ts"));
1811
2052
  const analysis = analyzeScalarTypeDeclarations(this.options.scalarTypeDeclarations);
1812
2053
  const code = this.options.scalarTypeDeclarations?.trim();
1813
2054
  if (code && code.length !== 0) {
@@ -1836,10 +2077,10 @@ var Generator = class {
1836
2077
  }
1837
2078
  }
1838
2079
  async writeIndex(schema, ctx) {
1839
- const stream = createStream(join(this.targetDir, "index.ts"));
2080
+ const stream = this.createCodeStream(join(this.targetDir, "index.ts"));
1840
2081
  const selectionSuffix = this.options.selectionSuffix ?? "Selection";
1841
- stream.write(`import type { Selection, ExecutableSelection, SchemaType, ShapeOf, VariablesOf } from "../dist/index.mjs";\n`);
1842
- stream.write(`import { FragmentRef, createSelection, resolveRegisteredSchemaType } from "../dist/index.mjs";\n`);
2082
+ stream.write(`import type { Selection, ExecutableSelection, SchemaType, ShapeOf, VariablesOf } from "${this.rootRuntimeImportSource}";\n`);
2083
+ stream.write(`import { FragmentRef, createSelection, resolveRegisteredSchemaType } from "${this.rootRuntimeImportSource}";\n`);
1843
2084
  for (const type of ctx.selectionTypes) {
1844
2085
  const selectionTypeName = `${type.name}${selectionSuffix}`;
1845
2086
  stream.write(`import type { ${selectionTypeName} } from "./selections/${toKebabCase(selectionTypeName)}";\n`);
@@ -1888,13 +2129,14 @@ var Generator = class {
1888
2129
  async writePackageEntrypoint(schema, ctx) {
1889
2130
  await mkdir(PACKAGE_DIR, { recursive: true });
1890
2131
  const indexStream = createStream(join(PACKAGE_DIR, "index.ts"));
2132
+ indexStream.write(GENERATED_FILE_BANNER);
1891
2133
  this.writePackageIndexCode(indexStream, schema, ctx);
1892
2134
  await endStream(indexStream);
1893
2135
  await this.patchPackageJsonForGeneratedEntrypoint();
1894
2136
  }
1895
2137
  async patchPackageJsonForGeneratedEntrypoint() {
1896
2138
  const packageJsonPath = join(PACKAGE_DIR, "package.json");
1897
- const raw = await readFile(packageJsonPath, "utf8");
2139
+ const raw = await readFile$1(packageJsonPath, "utf8");
1898
2140
  const pkg = JSON.parse(raw);
1899
2141
  const exportsMap = typeof pkg.exports === "object" && pkg.exports !== null ? pkg.exports : {};
1900
2142
  const rootExportRaw = exportsMap["."];
@@ -2022,9 +2264,62 @@ async function loadRemoteSchema(endpoint, headers) {
2022
2264
  return buildClientSchema(data);
2023
2265
  }
2024
2266
  async function loadLocalSchema(location) {
2025
- return buildSchema(await readFile(location, { encoding: "utf8" }));
2267
+ return buildSchema(await readFile$1(location, { encoding: "utf8" }));
2268
+ }
2269
+
2270
+ //#endregion
2271
+ //#region src/codegen/config-loader.ts
2272
+ /**
2273
+ * Validate that the output directory is not inside node_modules.
2274
+ * @throws Error if the path is inside node_modules
2275
+ */
2276
+ function validateOutputDir(outputDir) {
2277
+ if (normalize(outputDir).includes("node_modules")) throw new Error(`Invalid outputDir: "${outputDir}". Output directory cannot be inside node_modules. Please specify a path outside node_modules, such as './src/__generated' or './__generated'.`);
2278
+ }
2279
+ /**
2280
+ * Load configuration from .typedgqlrc.toml file.
2281
+ *
2282
+ * @param configPath - Path to the config file (defaults to .typedgqlrc.toml in cwd)
2283
+ * @returns Parsed configuration object or undefined if file doesn't exist
2284
+ */
2285
+ async function loadConfig(configPath) {
2286
+ const path = configPath ?? resolve(process.cwd(), ".typedgqlrc.toml");
2287
+ try {
2288
+ const config = parse(await readFile(path, "utf-8"));
2289
+ if (config.outputDir && !config.targetDir) config.targetDir = config.outputDir;
2290
+ const outputPath = config.outputDir || config.targetDir;
2291
+ if (outputPath) validateOutputDir(outputPath);
2292
+ return config;
2293
+ } catch (error) {
2294
+ if (error.code === "ENOENT") return;
2295
+ throw new Error(`Failed to load config from ${path}: ${error.message}`);
2296
+ }
2297
+ }
2298
+ /**
2299
+ * Merge configuration from file with programmatic options.
2300
+ * Programmatic options take precedence over file config.
2301
+ *
2302
+ * @param fileConfig - Configuration loaded from .typedgqlrc.toml
2303
+ * @param programmaticConfig - Configuration passed programmatically
2304
+ * @returns Merged configuration
2305
+ */
2306
+ function mergeConfig(fileConfig, programmaticConfig) {
2307
+ let merged;
2308
+ if (!fileConfig) merged = programmaticConfig;
2309
+ else merged = {
2310
+ ...fileConfig,
2311
+ ...programmaticConfig,
2312
+ schemaHeaders: {
2313
+ ...fileConfig.schemaHeaders,
2314
+ ...programmaticConfig.schemaHeaders
2315
+ }
2316
+ };
2317
+ if (merged.outputDir && !merged.targetDir) merged.targetDir = merged.outputDir;
2318
+ const outputPath = merged.outputDir || merged.targetDir;
2319
+ if (outputPath) validateOutputDir(outputPath);
2320
+ return merged;
2026
2321
  }
2027
2322
 
2028
2323
  //#endregion
2029
- export { loadRemoteSchema as n, Generator as r, loadLocalSchema as t };
2030
- //# sourceMappingURL=schema-loader-CsabdnfI.mjs.map
2324
+ export { Generator as a, loadRemoteSchema as i, mergeConfig as n, loadLocalSchema as r, loadConfig as t };
2325
+ //# sourceMappingURL=config-loader-DZ7d_CWR.mjs.map