nitro-graphql 2.0.0-beta.7 → 2.0.0-beta.72

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 (242) hide show
  1. package/README.md +31 -1196
  2. package/dist/cli/adapter.d.mts +13 -0
  3. package/dist/cli/adapter.mjs +67 -0
  4. package/dist/cli/commands/build.d.mts +21 -0
  5. package/dist/cli/commands/build.mjs +50 -0
  6. package/dist/cli/commands/dev.d.mts +40 -0
  7. package/dist/cli/commands/dev.mjs +74 -0
  8. package/dist/cli/commands/generate.d.mts +25 -0
  9. package/dist/cli/commands/generate.mjs +198 -0
  10. package/dist/cli/commands/index.d.mts +5 -0
  11. package/dist/cli/commands/index.mjs +5 -0
  12. package/dist/cli/commands/init.d.mts +45 -0
  13. package/dist/cli/commands/init.mjs +195 -0
  14. package/dist/cli/commands/validate.d.mts +9 -0
  15. package/dist/cli/commands/validate.mjs +65 -0
  16. package/dist/cli/completions.d.mts +6 -0
  17. package/dist/cli/completions.mjs +32 -0
  18. package/dist/cli/config.d.mts +18 -0
  19. package/dist/cli/config.mjs +19 -0
  20. package/dist/cli/index.d.mts +26 -0
  21. package/dist/cli/index.mjs +315 -0
  22. package/dist/cli/server/debug-handler.d.mts +9 -0
  23. package/dist/cli/server/debug-handler.mjs +68 -0
  24. package/dist/cli/server/dev-server.d.mts +29 -0
  25. package/dist/cli/server/dev-server.mjs +62 -0
  26. package/dist/cli/server/graphql-handler.d.mts +21 -0
  27. package/dist/cli/server/graphql-handler.mjs +43 -0
  28. package/dist/cli/server/health-handler.d.mts +12 -0
  29. package/dist/cli/server/health-handler.mjs +29 -0
  30. package/dist/cli/server/loader.d.mts +33 -0
  31. package/dist/cli/server/loader.mjs +144 -0
  32. package/dist/cli/server/sandbox-handler.d.mts +12 -0
  33. package/dist/cli/server/sandbox-handler.mjs +17 -0
  34. package/dist/cli/server/watcher.d.mts +20 -0
  35. package/dist/cli/server/watcher.mjs +64 -0
  36. package/dist/cli/server/ws-handler.d.mts +28 -0
  37. package/dist/cli/server/ws-handler.mjs +48 -0
  38. package/dist/config.d.mts +2 -0
  39. package/dist/config.mjs +2 -0
  40. package/dist/core/codegen/client.d.mts +42 -0
  41. package/dist/core/codegen/client.mjs +551 -0
  42. package/dist/core/codegen/document-loader.d.mts +9 -0
  43. package/dist/core/codegen/document-loader.mjs +16 -0
  44. package/dist/core/codegen/index.d.mts +8 -0
  45. package/dist/core/codegen/index.mjs +8 -0
  46. package/dist/core/codegen/plugin.d.mts +19 -0
  47. package/dist/core/codegen/plugin.mjs +29 -0
  48. package/dist/core/codegen/runtime.d.mts +17 -0
  49. package/dist/core/codegen/runtime.mjs +61 -0
  50. package/dist/core/codegen/schema-loader.d.mts +27 -0
  51. package/dist/core/codegen/schema-loader.mjs +126 -0
  52. package/dist/core/codegen/server.d.mts +27 -0
  53. package/dist/core/codegen/server.mjs +142 -0
  54. package/dist/core/codegen/validation.d.mts +17 -0
  55. package/dist/core/codegen/validation.mjs +33 -0
  56. package/dist/core/config.d.mts +45 -0
  57. package/dist/core/config.mjs +76 -0
  58. package/dist/core/constants.d.mts +188 -0
  59. package/dist/core/constants.mjs +208 -0
  60. package/dist/core/debug/index.d.mts +2 -0
  61. package/dist/core/debug/index.mjs +2 -0
  62. package/dist/core/debug/template.d.mts +52 -0
  63. package/dist/core/debug/template.mjs +384 -0
  64. package/dist/core/extend/index.d.mts +2 -0
  65. package/dist/core/extend/index.mjs +2 -0
  66. package/dist/core/extend/loader.d.mts +40 -0
  67. package/dist/core/extend/loader.mjs +196 -0
  68. package/dist/core/index.d.mts +33 -0
  69. package/dist/core/index.mjs +28 -0
  70. package/dist/core/manifest.d.mts +56 -0
  71. package/dist/core/manifest.mjs +100 -0
  72. package/dist/core/pubsub/index.d.mts +109 -0
  73. package/dist/core/pubsub/index.mjs +146 -0
  74. package/dist/core/scanning/ast-scanner.d.mts +27 -0
  75. package/dist/core/scanning/ast-scanner.mjs +114 -0
  76. package/dist/core/scanning/common.d.mts +25 -0
  77. package/dist/core/scanning/common.mjs +57 -0
  78. package/dist/core/scanning/directives.d.mts +13 -0
  79. package/dist/core/scanning/directives.mjs +28 -0
  80. package/dist/core/scanning/documents.d.mts +20 -0
  81. package/dist/core/scanning/documents.mjs +36 -0
  82. package/dist/core/scanning/index.d.mts +7 -0
  83. package/dist/core/scanning/index.mjs +7 -0
  84. package/dist/core/scanning/resolvers.d.mts +14 -0
  85. package/dist/core/scanning/resolvers.mjs +58 -0
  86. package/dist/core/scanning/schemas.d.mts +13 -0
  87. package/dist/core/scanning/schemas.mjs +50 -0
  88. package/dist/core/schema/builder.d.mts +59 -0
  89. package/dist/core/schema/builder.mjs +76 -0
  90. package/dist/core/schema/federation.d.mts +33 -0
  91. package/dist/core/schema/federation.mjs +38 -0
  92. package/dist/core/schema/index.d.mts +3 -0
  93. package/dist/core/schema/index.mjs +3 -0
  94. package/dist/core/server/index.d.mts +4 -0
  95. package/dist/core/server/index.mjs +3 -0
  96. package/dist/core/server/sandbox.d.mts +18 -0
  97. package/dist/core/server/sandbox.mjs +38 -0
  98. package/dist/core/server/types.d.mts +54 -0
  99. package/dist/core/server/types.mjs +1 -0
  100. package/dist/core/server/yoga.d.mts +42 -0
  101. package/dist/core/server/yoga.mjs +87 -0
  102. package/dist/core/types/adapter.d.mts +55 -0
  103. package/dist/core/types/adapter.mjs +1 -0
  104. package/dist/core/types/codegen.d.mts +136 -0
  105. package/dist/core/types/codegen.mjs +1 -0
  106. package/dist/core/types/config.d.mts +188 -0
  107. package/dist/core/types/config.mjs +1 -0
  108. package/dist/{utils/define.d.ts → core/types/define.d.mts} +2 -30
  109. package/dist/core/types/define.mjs +1 -0
  110. package/dist/core/types/index.d.mts +5 -0
  111. package/dist/core/types/index.mjs +1 -0
  112. package/dist/core/types/scanning.d.mts +64 -0
  113. package/dist/core/types/scanning.mjs +1 -0
  114. package/dist/{utils/directive-parser.d.ts → core/utils/directive-parser.d.mts} +18 -4
  115. package/dist/{utils/directive-parser.js → core/utils/directive-parser.mjs} +29 -36
  116. package/dist/core/utils/errors.d.mts +77 -0
  117. package/dist/core/utils/errors.mjs +91 -0
  118. package/dist/core/utils/file-io.d.mts +24 -0
  119. package/dist/core/utils/file-io.mjs +45 -0
  120. package/dist/core/utils/imports.d.mts +15 -0
  121. package/dist/core/utils/imports.mjs +24 -0
  122. package/dist/core/utils/index.d.mts +7 -0
  123. package/dist/core/utils/index.mjs +7 -0
  124. package/dist/core/utils/logger.d.mts +18 -0
  125. package/dist/core/utils/logger.mjs +36 -0
  126. package/dist/core/utils/ofetch-templates.d.mts +30 -0
  127. package/dist/core/utils/ofetch-templates.mjs +134 -0
  128. package/dist/core/utils/runtime.d.mts +74 -0
  129. package/dist/core/utils/runtime.mjs +109 -0
  130. package/dist/core/utils/subscribe-templates.d.mts +8 -0
  131. package/dist/core/utils/subscribe-templates.mjs +58 -0
  132. package/dist/core/validation/external-services.d.mts +11 -0
  133. package/dist/core/validation/external-services.mjs +33 -0
  134. package/dist/core/validation/index.d.mts +2 -0
  135. package/dist/core/validation/index.mjs +2 -0
  136. package/dist/core/watcher/index.d.mts +107 -0
  137. package/dist/core/watcher/index.mjs +140 -0
  138. package/dist/define.d.mts +294 -0
  139. package/dist/define.mjs +323 -0
  140. package/dist/index.d.mts +6 -0
  141. package/dist/index.mjs +5 -0
  142. package/dist/nitro/adapter.d.mts +28 -0
  143. package/dist/nitro/adapter.mjs +90 -0
  144. package/dist/{utils/apollo.d.ts → nitro/apollo.d.mts} +3 -3
  145. package/dist/nitro/apollo.mjs +57 -0
  146. package/dist/nitro/codegen.d.mts +18 -0
  147. package/dist/nitro/codegen.mjs +171 -0
  148. package/dist/nitro/config.d.mts +50 -0
  149. package/dist/nitro/config.mjs +55 -0
  150. package/dist/nitro/index.d.mts +45 -0
  151. package/dist/nitro/index.mjs +63 -0
  152. package/dist/{utils/path-resolver.d.ts → nitro/paths.d.mts} +8 -25
  153. package/dist/nitro/paths.mjs +97 -0
  154. package/dist/nitro/rollup.d.mts +6 -0
  155. package/dist/nitro/rollup.mjs +52 -0
  156. package/dist/nitro/routes/apollo-sandbox-script.d.mts +6 -0
  157. package/dist/nitro/routes/apollo-sandbox-script.mjs +12 -0
  158. package/dist/nitro/routes/apollo-server-ws.d.mts +15 -0
  159. package/dist/nitro/routes/apollo-server-ws.mjs +50 -0
  160. package/dist/nitro/routes/apollo-server.d.mts +6 -0
  161. package/dist/nitro/routes/apollo-server.mjs +69 -0
  162. package/dist/{routes/debug.d.ts → nitro/routes/debug.d.mts} +12 -19
  163. package/dist/nitro/routes/debug.mjs +98 -0
  164. package/dist/nitro/routes/graphql-yoga-ws.d.mts +12 -0
  165. package/dist/nitro/routes/graphql-yoga-ws.mjs +50 -0
  166. package/dist/nitro/routes/graphql-yoga.d.mts +12 -0
  167. package/dist/nitro/routes/graphql-yoga.mjs +39 -0
  168. package/dist/nitro/routes/health.d.mts +10 -0
  169. package/dist/{routes/health.js → nitro/routes/health.mjs} +5 -6
  170. package/dist/nitro/setup/extend-loader.d.mts +16 -0
  171. package/dist/nitro/setup/extend-loader.mjs +80 -0
  172. package/dist/nitro/setup/file-watcher.d.mts +18 -0
  173. package/dist/nitro/setup/file-watcher.mjs +62 -0
  174. package/dist/nitro/setup/logging.d.mts +16 -0
  175. package/dist/nitro/setup/logging.mjs +64 -0
  176. package/dist/nitro/setup/rollup-integration.d.mts +24 -0
  177. package/dist/nitro/setup/rollup-integration.mjs +64 -0
  178. package/dist/nitro/setup/routes.d.mts +13 -0
  179. package/dist/nitro/setup/routes.mjs +69 -0
  180. package/dist/nitro/setup/scanner.d.mts +59 -0
  181. package/dist/nitro/setup/scanner.mjs +118 -0
  182. package/dist/nitro/setup/ts-config.d.mts +10 -0
  183. package/dist/nitro/setup/ts-config.mjs +67 -0
  184. package/dist/nitro/setup.d.mts +11 -0
  185. package/dist/nitro/setup.mjs +189 -0
  186. package/dist/nitro/types.d.mts +549 -0
  187. package/dist/nitro/types.mjs +1 -0
  188. package/dist/nitro/virtual/generators.d.mts +38 -0
  189. package/dist/nitro/virtual/generators.mjs +190 -0
  190. package/dist/nitro/virtual/stubs.d.mts +21 -0
  191. package/dist/nitro/virtual/stubs.mjs +31 -0
  192. package/dist/{ecosystem/nuxt.d.ts → nuxt.d.mts} +1 -1
  193. package/dist/nuxt.mjs +111 -0
  194. package/dist/{graphql/server.d.ts → stubs/index.d.mts} +5 -1
  195. package/dist/stubs/index.mjs +1 -0
  196. package/dist/subscribe/index.d.mts +78 -0
  197. package/dist/subscribe/index.mjs +205 -0
  198. package/native/index.d.ts +20 -0
  199. package/native/index.js +585 -0
  200. package/package.json +202 -112
  201. package/dist/ecosystem/nuxt.js +0 -67
  202. package/dist/graphql/index.d.ts +0 -5
  203. package/dist/graphql/index.js +0 -1
  204. package/dist/graphql/server.js +0 -1
  205. package/dist/index.d.ts +0 -8
  206. package/dist/index.js +0 -318
  207. package/dist/rollup.js +0 -277
  208. package/dist/routes/apollo-server.d.ts +0 -6
  209. package/dist/routes/apollo-server.js +0 -89
  210. package/dist/routes/debug.js +0 -449
  211. package/dist/routes/graphql-yoga.d.ts +0 -6
  212. package/dist/routes/graphql-yoga.js +0 -91
  213. package/dist/routes/health.d.ts +0 -10
  214. package/dist/types/index.d.ts +0 -246
  215. package/dist/types/standard-schema.d.ts +0 -59
  216. package/dist/utils/apollo.js +0 -61
  217. package/dist/utils/client-codegen.d.ts +0 -38
  218. package/dist/utils/client-codegen.js +0 -290
  219. package/dist/utils/define.js +0 -57
  220. package/dist/utils/file-generator.d.ts +0 -37
  221. package/dist/utils/file-generator.js +0 -72
  222. package/dist/utils/index.d.ts +0 -39
  223. package/dist/utils/index.js +0 -278
  224. package/dist/utils/path-resolver.js +0 -127
  225. package/dist/utils/server-codegen.d.ts +0 -7
  226. package/dist/utils/server-codegen.js +0 -136
  227. package/dist/utils/type-generation.d.ts +0 -7
  228. package/dist/utils/type-generation.js +0 -360
  229. package/dist/virtual/debug-info.d.ts +0 -9
  230. package/dist/virtual/debug-info.js +0 -26
  231. package/dist/virtual/graphql-config.d.ts +0 -9
  232. package/dist/virtual/graphql-config.js +0 -10
  233. package/dist/virtual/module-config.d.ts +0 -9
  234. package/dist/virtual/module-config.js +0 -10
  235. package/dist/virtual/server-directives.d.ts +0 -11
  236. package/dist/virtual/server-directives.js +0 -10
  237. package/dist/virtual/server-resolvers.d.ts +0 -11
  238. package/dist/virtual/server-resolvers.js +0 -10
  239. package/dist/virtual/server-schemas.d.ts +0 -11
  240. package/dist/virtual/server-schemas.js +0 -10
  241. package/dist/vite.d.ts +0 -25
  242. package/dist/vite.js +0 -40
@@ -1,136 +0,0 @@
1
- import consola from "consola";
2
- import { defu as defu$1 } from "defu";
3
- import { parse } from "graphql";
4
- import { printSchemaWithDirectives } from "@graphql-tools/utils";
5
- import { codegen } from "@graphql-codegen/core";
6
- import * as typescriptPlugin from "@graphql-codegen/typescript";
7
- import { CurrencyResolver, DateTimeISOResolver, DateTimeResolver, JSONObjectResolver, JSONResolver, NonEmptyStringResolver, UUIDResolver } from "graphql-scalars";
8
- import * as typescriptResolversPlugin from "@graphql-codegen/typescript-resolvers";
9
-
10
- //#region src/utils/server-codegen.ts
11
- function pluginContent(_schema, _documents, _config, _info) {
12
- return {
13
- prepend: [
14
- "// THIS FILE IS GENERATED, DO NOT EDIT!",
15
- "/* eslint-disable eslint-comments/no-unlimited-disable */",
16
- "/* tslint:disable */",
17
- "/* eslint-disable */",
18
- "/* prettier-ignore */"
19
- ],
20
- content: ""
21
- };
22
- }
23
- async function generateTypes(selectFremework, schema, config = {}, outputPath) {
24
- const mergedConfig = defu$1({
25
- scalars: {
26
- DateTime: DateTimeResolver.extensions.codegenScalarType,
27
- DateTimeISO: DateTimeISOResolver.extensions.codegenScalarType,
28
- UUID: UUIDResolver.extensions.codegenScalarType,
29
- JSON: JSONResolver.extensions.codegenScalarType,
30
- JSONObject: JSONObjectResolver.extensions.codegenScalarType,
31
- NonEmptyString: NonEmptyStringResolver.extensions.codegenScalarType,
32
- Currency: CurrencyResolver.extensions.codegenScalarType,
33
- File: {
34
- input: "File",
35
- output: "File"
36
- }
37
- },
38
- defaultScalarType: "unknown",
39
- defaultMapper: `ResolverReturnType<{T}>`,
40
- contextType: "h3#H3Event",
41
- maybeValue: "T | null | undefined",
42
- inputMaybeValue: "T | undefined",
43
- declarationKind: "interface",
44
- enumsAsTypes: true,
45
- ...config.federation?.enabled && { federation: true }
46
- }, config.codegen?.server);
47
- return await codegen({
48
- filename: outputPath || "types.generated.ts",
49
- schema: parse(printSchemaWithDirectives(schema)),
50
- documents: [],
51
- config: mergedConfig,
52
- plugins: [
53
- { imports: {} },
54
- { pluginContent: {} },
55
- { typescript: {} },
56
- { typescriptResolvers: {} }
57
- ],
58
- pluginMap: {
59
- pluginContent: { plugin: pluginContent },
60
- imports: { plugin: () => {
61
- return {
62
- prepend: [
63
- `import schemas from '#graphql/schema'`,
64
- `import type { StandardSchemaV1 } from 'nitro-graphql'`,
65
- `
66
- export interface NPMConfig {
67
- framework: '${selectFremework || "graphql-yoga"}';
68
- }
69
-
70
- export type SchemaType = Partial<Record<Partial<keyof ResolversTypes>, StandardSchemaV1>>
71
-
72
- // Check if schemas is empty object, return never if so
73
- type SafeSchemaKeys<T> = T extends Record<PropertyKey, never>
74
- ? never
75
- : keyof T extends string | number | symbol
76
- ? keyof T extends never
77
- ? never
78
- : keyof T
79
- : never;
80
-
81
-
82
- type SchemaKeys = SafeSchemaKeys<typeof schemas>;
83
-
84
- type InferInput<T> = T extends StandardSchemaV1 ? StandardSchemaV1.InferInput<T> : unknown;
85
- type InferOutput<T> = T extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<T> : unknown;
86
-
87
- type InferInputFromSchema<T extends SchemaKeys> = InferInput<(typeof schemas)[T]>;
88
- type InferOutputFromSchema<T extends SchemaKeys> = InferOutput<(typeof schemas)[T]>;
89
-
90
- type Primitive =
91
- | null
92
- | undefined
93
- | string
94
- | number
95
- | boolean
96
- | symbol
97
- | bigint;
98
-
99
- type BuiltIns = Primitive | void | Date | RegExp;
100
-
101
-
102
- type ResolverReturnType<T> = T extends BuiltIns
103
- ? T
104
- : T extends (...args: any[]) => unknown
105
- ? T | undefined
106
- : T extends object
107
- ? T extends Array<infer ItemType> // Test for arrays/tuples, per https://github.com/microsoft/TypeScript/issues/35156
108
- ? ItemType[] extends T // Test for arrays (non-tuples) specifically
109
- ? Array<ResolverReturnType<ItemType>>
110
- : ResolverReturnTypeObject<T> // Tuples behave properly
111
- : ResolverReturnTypeObject<T>
112
- : unknown;
113
-
114
- type ResolverReturnTypeObject<T extends object> =
115
- T extends { __typename?: infer TTypename }
116
- ? TTypename extends SchemaKeys
117
- ? InferOutputFromSchema<TTypename>
118
- : { [K in keyof T]: ResolverReturnType<T[K]> }
119
- : { [K in keyof T]: ResolverReturnType<T[K]> };
120
- `,
121
- ""
122
- ],
123
- content: ""
124
- };
125
- } },
126
- typescript: typescriptPlugin,
127
- typescriptResolvers: typescriptResolversPlugin
128
- }
129
- }).catch((e) => {
130
- consola.withTag("graphql").error("Error generating types:", e);
131
- return "";
132
- });
133
- }
134
-
135
- //#endregion
136
- export { generateTypes };
@@ -1,7 +0,0 @@
1
- import { Nitro } from "nitro/types";
2
-
3
- //#region src/utils/type-generation.d.ts
4
- declare function serverTypeGeneration(app: Nitro): Promise<void>;
5
- declare function clientTypeGeneration(nitro: Nitro): Promise<void>;
6
- //#endregion
7
- export { clientTypeGeneration, serverTypeGeneration };
@@ -1,360 +0,0 @@
1
- import { downloadAndSaveSchema, generateClientTypes, generateExternalClientTypes, loadExternalSchema, loadGraphQLDocuments } from "./client-codegen.js";
2
- import { writeFileIfNotExists } from "./file-generator.js";
3
- import { getClientUtilsConfig, getDefaultPaths, getSdkConfig, getTypesConfig, resolveFilePath, shouldGenerateClientUtils, shouldGenerateTypes } from "./path-resolver.js";
4
- import { generateTypes } from "./server-codegen.js";
5
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
- import consola from "consola";
7
- import { basename, dirname, join, resolve } from "pathe";
8
- import { buildSchema, parse } from "graphql";
9
- import { buildSubgraphSchema } from "@apollo/subgraph";
10
- import { loadFilesSync } from "@graphql-tools/load-files";
11
- import { mergeTypeDefs } from "@graphql-tools/merge";
12
- import { printSchemaWithDirectives } from "@graphql-tools/utils";
13
-
14
- //#region src/utils/type-generation.ts
15
- function generateGraphQLIndexFile(nitro, clientDir, externalServices = []) {
16
- if (!shouldGenerateClientUtils(nitro)) return;
17
- const placeholders = getDefaultPaths(nitro);
18
- const clientUtilsConfig = getClientUtilsConfig(nitro);
19
- const indexPath = resolveFilePath(clientUtilsConfig.index, clientUtilsConfig.enabled, true, "{clientGraphql}/index.ts", placeholders);
20
- if (!indexPath) return;
21
- if (!existsSync(indexPath)) {
22
- let indexContent = `// This file is auto-generated once by nitro-graphql for quick start
23
- // You can modify this file according to your needs
24
- //
25
- // Export your main GraphQL service (auto-generated)
26
- export * from './default/ofetch'
27
-
28
- // Export external GraphQL services (auto-generated for existing services)
29
- // When you add new external services, don't forget to add their exports here:
30
- // export * from './yourServiceName/ofetch'
31
- `;
32
- for (const service of externalServices) indexContent += `export * from './${service.name}/ofetch'\n`;
33
- writeFileIfNotExists(indexPath, indexContent, "client index.ts");
34
- }
35
- }
36
- function generateNuxtOfetchClient(nitro, clientDir, serviceName = "default") {
37
- if (!shouldGenerateClientUtils(nitro)) return;
38
- const placeholders = {
39
- ...getDefaultPaths(nitro),
40
- serviceName
41
- };
42
- const clientUtilsConfig = getClientUtilsConfig(nitro);
43
- const ofetchPath = resolveFilePath(clientUtilsConfig.ofetch, clientUtilsConfig.enabled, true, "{clientGraphql}/{serviceName}/ofetch.ts", placeholders);
44
- if (!ofetchPath) return;
45
- const serviceDir = dirname(ofetchPath);
46
- if (!existsSync(serviceDir)) mkdirSync(serviceDir, { recursive: true });
47
- if (existsSync(ofetchPath)) return;
48
- writeFileIfNotExists(ofetchPath, `// This file is auto-generated once by nitro-graphql for quick start
49
- // You can modify this file according to your needs
50
- import type { Requester } from './sdk'
51
- import { getSdk } from './sdk'
52
-
53
- export function createGraphQLClient(endpoint: string): Requester {
54
- return async <R>(doc: string, vars?: any): Promise<R> => {
55
- const headers = import.meta.server ? useRequestHeaders() : undefined
56
-
57
- const result = await $fetch(endpoint, {
58
- method: 'POST',
59
- body: { query: doc, variables: vars },
60
- headers: {
61
- 'Content-Type': 'application/json',
62
- ...headers,
63
- },
64
- })
65
-
66
- return result as R
67
- }
68
- }
69
-
70
- export const $sdk = getSdk(createGraphQLClient('/api/graphql'))`, `${serviceName} ofetch.ts`);
71
- }
72
- function generateExternalOfetchClient(nitro, service, endpoint) {
73
- if (!shouldGenerateClientUtils(nitro)) return;
74
- const serviceName = service.name;
75
- const placeholders = {
76
- ...getDefaultPaths(nitro),
77
- serviceName
78
- };
79
- const clientUtilsConfig = getClientUtilsConfig(nitro);
80
- const ofetchPath = resolveFilePath(service.paths?.ofetch ?? clientUtilsConfig.ofetch, clientUtilsConfig.enabled, true, "{clientGraphql}/{serviceName}/ofetch.ts", placeholders);
81
- if (!ofetchPath) return;
82
- const serviceDir = dirname(ofetchPath);
83
- if (!existsSync(serviceDir)) mkdirSync(serviceDir, { recursive: true });
84
- if (!existsSync(ofetchPath)) {
85
- const capitalizedServiceName = serviceName.charAt(0).toUpperCase() + serviceName.slice(1);
86
- writeFileIfNotExists(ofetchPath, `// This file is auto-generated once by nitro-graphql for quick start
87
- // You can modify this file according to your needs
88
- import type { Sdk, Requester } from './sdk'
89
- import { getSdk } from './sdk'
90
-
91
- export function create${capitalizedServiceName}GraphQLClient(endpoint: string = '${endpoint}'): Requester {
92
- return async <R>(doc: string, vars?: any): Promise<R> => {
93
- const headers = import.meta.server ? useRequestHeaders() : undefined
94
-
95
- const result = await $fetch(endpoint, {
96
- method: 'POST',
97
- body: { query: doc, variables: vars },
98
- headers: {
99
- 'Content-Type': 'application/json',
100
- ...headers,
101
- },
102
- })
103
-
104
- return result as R
105
- }
106
- }
107
-
108
- export const $${serviceName}Sdk: Sdk = getSdk(create${capitalizedServiceName}GraphQLClient())`, `${serviceName} external ofetch.ts`);
109
- }
110
- }
111
- /**
112
- * Check for duplicate type definitions using a simpler approach
113
- * Try to build each schema individually - if that succeeds but merging fails, we have duplicates
114
- * @returns true if validation passes, false if duplicates found
115
- */
116
- function validateNoDuplicateTypes(schemas, schemaStrings) {
117
- const individualSchemasByFile = /* @__PURE__ */ new Map();
118
- schemaStrings.forEach((schemaContent, index) => {
119
- const schemaPath = schemas[index];
120
- const fileName = basename(schemaPath);
121
- try {
122
- parse(schemaContent);
123
- individualSchemasByFile.set(fileName, schemaContent);
124
- } catch (error) {
125
- consola.warn(`Invalid GraphQL syntax in ${fileName}:`, error);
126
- throw error;
127
- }
128
- });
129
- try {
130
- mergeTypeDefs([schemaStrings.join("\n\n")], {
131
- throwOnConflict: false,
132
- commentDescriptions: true,
133
- sort: true
134
- });
135
- mergeTypeDefs([schemaStrings.join("\n\n")], {
136
- throwOnConflict: true,
137
- commentDescriptions: true,
138
- sort: true
139
- });
140
- } catch (conflictError) {
141
- if (conflictError?.message?.includes("already defined with a different type")) throw conflictError;
142
- }
143
- const typeNames = /* @__PURE__ */ new Set();
144
- const duplicateTypes = [];
145
- schemaStrings.forEach((schemaContent, index) => {
146
- const fileName = basename(schemas[index]);
147
- try {
148
- parse(schemaContent).definitions.forEach((def) => {
149
- if (def.kind === "ObjectTypeDefinition" || def.kind === "InterfaceTypeDefinition" || def.kind === "UnionTypeDefinition" || def.kind === "EnumTypeDefinition" || def.kind === "InputObjectTypeDefinition" || def.kind === "ScalarTypeDefinition") {
150
- const typeName = def.name.value;
151
- if ([
152
- "String",
153
- "Int",
154
- "Float",
155
- "Boolean",
156
- "ID",
157
- "DateTime",
158
- "JSON"
159
- ].includes(typeName)) return;
160
- if (typeNames.has(typeName)) {
161
- const existing = duplicateTypes.find((d) => d.type === typeName);
162
- if (existing) existing.files.push(fileName);
163
- else {
164
- const firstFile = schemas.find((_, i) => {
165
- const content = schemaStrings[i];
166
- if (!content) return false;
167
- try {
168
- return parse(content).definitions.some((d) => (d.kind === "ObjectTypeDefinition" || d.kind === "InterfaceTypeDefinition" || d.kind === "UnionTypeDefinition" || d.kind === "EnumTypeDefinition" || d.kind === "InputObjectTypeDefinition" || d.kind === "ScalarTypeDefinition") && d.name.value === typeName);
169
- } catch {
170
- return false;
171
- }
172
- });
173
- duplicateTypes.push({
174
- type: typeName,
175
- files: [basename(firstFile || ""), fileName]
176
- });
177
- }
178
- } else typeNames.add(typeName);
179
- }
180
- });
181
- } catch {}
182
- });
183
- if (duplicateTypes.length > 0) {
184
- let errorMessage = "⚠️ DUPLICATE TYPE DEFINITIONS DETECTED!\n\n";
185
- duplicateTypes.forEach(({ type, files }) => {
186
- errorMessage += `❌ Type "${type}" is defined in multiple files:\n`;
187
- files.forEach((fileName) => {
188
- const fullPath = schemas.find((path) => basename(path) === fileName) || fileName;
189
- errorMessage += ` • ${fullPath}\n`;
190
- });
191
- errorMessage += "\n";
192
- });
193
- errorMessage += "💡 Each GraphQL type should only be defined once.\n";
194
- errorMessage += " Consider using \"extend type\" syntax instead of duplicate definitions.\n";
195
- errorMessage += `\n🔍 Found ${duplicateTypes.length} duplicate type(s): ${duplicateTypes.map((d) => d.type).join(", ")}`;
196
- consola.error(errorMessage);
197
- return false;
198
- }
199
- return true;
200
- }
201
- async function serverTypeGeneration(app) {
202
- try {
203
- if (!shouldGenerateTypes(app)) {
204
- consola.debug("[nitro-graphql] Server type generation is disabled");
205
- return;
206
- }
207
- const schemas = app.scanSchemas || [];
208
- if (!schemas.length) {
209
- consola.info("No GraphQL definitions found for server type generation.");
210
- return;
211
- }
212
- const schemaStrings = loadFilesSync(schemas).map((schema$1) => typeof schema$1 === "string" ? schema$1 : schema$1.loc?.source?.body || "").filter(Boolean);
213
- if (!validateNoDuplicateTypes(schemas, schemaStrings)) return;
214
- const federationEnabled = app.options.graphql?.federation?.enabled === true;
215
- const mergedSchemas = mergeTypeDefs([schemaStrings.join("\n\n")], {
216
- throwOnConflict: true,
217
- commentDescriptions: true,
218
- sort: true
219
- });
220
- const schema = federationEnabled ? buildSubgraphSchema([{ typeDefs: parse(mergedSchemas) }]) : buildSchema(mergedSchemas);
221
- const data = await generateTypes(app.options.graphql?.framework || "graphql-yoga", schema, app.options.graphql ?? {});
222
- const printSchema = printSchemaWithDirectives(schema);
223
- const schemaPath = resolve(app.graphql.buildDir, "schema.graphql");
224
- mkdirSync(dirname(schemaPath), { recursive: true });
225
- writeFileSync(schemaPath, printSchema, "utf-8");
226
- const placeholders = getDefaultPaths(app);
227
- const typesConfig = getTypesConfig(app);
228
- const serverTypesPath = resolveFilePath(typesConfig.server, typesConfig.enabled, true, "{typesDir}/nitro-graphql-server.d.ts", placeholders);
229
- if (serverTypesPath) {
230
- mkdirSync(dirname(serverTypesPath), { recursive: true });
231
- writeFileSync(serverTypesPath, data, "utf-8");
232
- consola.success(`[nitro-graphql] Generated server types at: ${serverTypesPath}`);
233
- }
234
- } catch (error) {
235
- consola.error("Server schema generation error:", error);
236
- }
237
- }
238
- async function clientTypeGeneration(nitro) {
239
- try {
240
- if (nitro.scanSchemas && nitro.scanSchemas.length > 0) await generateMainClientTypes(nitro);
241
- if (nitro.options.graphql?.externalServices?.length) await generateExternalServicesTypes(nitro);
242
- } catch (error) {
243
- consola.error("Client schema generation error:", error);
244
- }
245
- }
246
- /**
247
- * Check for old structure files and warn user about manual migration
248
- */
249
- function checkOldStructure(clientDir) {
250
- const oldOfetchPath = resolve(clientDir, "ofetch.ts");
251
- const oldSdkPath = resolve(clientDir, "sdk.ts");
252
- if (existsSync(oldOfetchPath) || existsSync(oldSdkPath)) {
253
- const foundFiles = [];
254
- if (existsSync(oldOfetchPath)) foundFiles.push("app/graphql/ofetch.ts");
255
- if (existsSync(oldSdkPath)) foundFiles.push("app/graphql/sdk.ts");
256
- consola.error(`⚠️ OLD GRAPHQL STRUCTURE DETECTED!
257
-
258
- 📁 Found old files in app/graphql/ directory that need to be moved:
259
- • ${foundFiles.join("\n • ")}
260
-
261
- 🔄 Please manually move these files to the new structure:
262
- • app/graphql/ofetch.ts → app/graphql/default/ofetch.ts
263
- • app/graphql/sdk.ts → app/graphql/default/sdk.ts
264
-
265
- 📝 Also update your app/graphql/index.ts to include:
266
- export * from './default/ofetch'
267
-
268
- 💡 After moving, update your imports to use:
269
- import { $sdk } from "#graphql/client"
270
-
271
- 🚫 The old files will cause import conflicts until moved!`);
272
- }
273
- }
274
- async function generateMainClientTypes(nitro) {
275
- checkOldStructure(nitro.graphql.clientDir);
276
- const docs = nitro.scanDocuments;
277
- const loadDocs = await loadGraphQLDocuments(docs);
278
- const schemaFilePath = join(nitro.graphql.buildDir, "schema.graphql");
279
- if (!existsSync(schemaFilePath)) {
280
- consola.info("Schema file not ready yet for client type generation. Server types need to be generated first.");
281
- return;
282
- }
283
- const graphqlString = readFileSync(schemaFilePath, "utf-8");
284
- const types = await generateClientTypes(nitro.options.graphql?.federation?.enabled === true ? buildSubgraphSchema([{ typeDefs: parse(graphqlString) }]) : buildSchema(graphqlString), loadDocs, nitro.options.graphql?.codegen?.client ?? {}, nitro.options.graphql?.codegen?.clientSDK ?? {});
285
- if (types === false) return;
286
- const placeholders = getDefaultPaths(nitro);
287
- const typesConfig = getTypesConfig(nitro);
288
- const sdkConfig = getSdkConfig(nitro);
289
- const clientTypesPath = resolveFilePath(typesConfig.client, typesConfig.enabled, true, "{typesDir}/nitro-graphql-client.d.ts", placeholders);
290
- if (clientTypesPath) {
291
- mkdirSync(dirname(clientTypesPath), { recursive: true });
292
- writeFileSync(clientTypesPath, types.types, "utf-8");
293
- consola.success(`[nitro-graphql] Generated client types at: ${clientTypesPath}`);
294
- }
295
- const sdkPath = resolveFilePath(sdkConfig.main, sdkConfig.enabled, true, "{clientGraphql}/default/sdk.ts", placeholders);
296
- if (sdkPath) {
297
- mkdirSync(dirname(sdkPath), { recursive: true });
298
- writeFileSync(sdkPath, types.sdk, "utf-8");
299
- consola.success(`[nitro-graphql] Generated SDK at: ${sdkPath}`);
300
- }
301
- if (nitro.options.framework?.name === "nuxt") {
302
- generateNuxtOfetchClient(nitro, nitro.graphql.clientDir, "default");
303
- const externalServices = nitro.options.graphql?.externalServices || [];
304
- generateGraphQLIndexFile(nitro, nitro.graphql.clientDir, externalServices);
305
- }
306
- }
307
- async function generateExternalServicesTypes(nitro) {
308
- const externalServices = nitro.options.graphql?.externalServices || [];
309
- for (const service of externalServices) try {
310
- consola.info(`[graphql:${service.name}] Processing external service`);
311
- await downloadAndSaveSchema(service, nitro.options.buildDir);
312
- const schema = await loadExternalSchema(service, nitro.options.buildDir);
313
- if (!schema) {
314
- consola.warn(`[graphql:${service.name}] Failed to load schema, skipping`);
315
- continue;
316
- }
317
- const documentPatterns = service.documents || [];
318
- let loadDocs = [];
319
- if (documentPatterns.length > 0) try {
320
- loadDocs = await loadGraphQLDocuments(documentPatterns);
321
- if (!loadDocs || loadDocs.length === 0) {
322
- consola.warn(`[graphql:${service.name}] No GraphQL documents found, skipping service generation`);
323
- continue;
324
- }
325
- } catch (error) {
326
- consola.warn(`[graphql:${service.name}] No documents found, skipping service generation:`, error);
327
- continue;
328
- }
329
- const types = await generateExternalClientTypes(service, schema, loadDocs);
330
- if (types === false) {
331
- consola.warn(`[graphql:${service.name}] Type generation failed`);
332
- continue;
333
- }
334
- const placeholders = {
335
- ...getDefaultPaths(nitro),
336
- serviceName: service.name
337
- };
338
- const typesConfig = getTypesConfig(nitro);
339
- const sdkConfig = getSdkConfig(nitro);
340
- const serviceTypesPath = resolveFilePath(service.paths?.types ?? typesConfig.external, typesConfig.enabled, true, "{typesDir}/nitro-graphql-client-{serviceName}.d.ts", placeholders);
341
- if (serviceTypesPath) {
342
- mkdirSync(dirname(serviceTypesPath), { recursive: true });
343
- writeFileSync(serviceTypesPath, types.types, "utf-8");
344
- consola.success(`[graphql:${service.name}] Generated types at: ${serviceTypesPath}`);
345
- }
346
- const serviceSdkPath = resolveFilePath(service.paths?.sdk ?? sdkConfig.external, sdkConfig.enabled, true, "{clientGraphql}/{serviceName}/sdk.ts", placeholders);
347
- if (serviceSdkPath) {
348
- mkdirSync(dirname(serviceSdkPath), { recursive: true });
349
- writeFileSync(serviceSdkPath, types.sdk, "utf-8");
350
- consola.success(`[graphql:${service.name}] Generated SDK at: ${serviceSdkPath}`);
351
- }
352
- if (nitro.options.framework?.name === "nuxt") generateExternalOfetchClient(nitro, service, service.endpoint);
353
- consola.success(`[graphql:${service.name}] External service types generated successfully`);
354
- } catch (error) {
355
- consola.error(`[graphql:${service.name}] External service generation failed:`, error);
356
- }
357
- }
358
-
359
- //#endregion
360
- export { clientTypeGeneration, serverTypeGeneration };
@@ -1,9 +0,0 @@
1
- //#region src/virtual/debug-info.d.ts
2
- /**
3
- * Virtual module stub for #nitro-graphql/debug-info
4
- * This file is only used during build/bundling to prevent import resolution errors.
5
- * At runtime, Nitro will override this with the actual virtual module.
6
- */
7
- declare const debugInfo: Record<string, any>;
8
- //#endregion
9
- export { debugInfo };
@@ -1,26 +0,0 @@
1
- //#region src/virtual/debug-info.ts
2
- /**
3
- * Virtual module stub for #nitro-graphql/debug-info
4
- * This file is only used during build/bundling to prevent import resolution errors.
5
- * At runtime, Nitro will override this with the actual virtual module.
6
- */
7
- const debugInfo = {
8
- isDev: false,
9
- framework: "",
10
- graphqlFramework: "",
11
- federation: {},
12
- scanned: {
13
- schemas: 0,
14
- schemaFiles: [],
15
- resolvers: 0,
16
- resolverFiles: [],
17
- directives: 0,
18
- directiveFiles: [],
19
- documents: 0,
20
- documentFiles: []
21
- },
22
- virtualModules: {}
23
- };
24
-
25
- //#endregion
26
- export { debugInfo };
@@ -1,9 +0,0 @@
1
- //#region src/virtual/graphql-config.d.ts
2
- /**
3
- * Virtual module stub for #nitro-graphql/graphql-config
4
- * This file is only used during build/bundling to prevent import resolution errors.
5
- * At runtime, Nitro will override this with the actual virtual module.
6
- */
7
- declare const importedConfig: {};
8
- //#endregion
9
- export { importedConfig };
@@ -1,10 +0,0 @@
1
- //#region src/virtual/graphql-config.ts
2
- /**
3
- * Virtual module stub for #nitro-graphql/graphql-config
4
- * This file is only used during build/bundling to prevent import resolution errors.
5
- * At runtime, Nitro will override this with the actual virtual module.
6
- */
7
- const importedConfig = {};
8
-
9
- //#endregion
10
- export { importedConfig };
@@ -1,9 +0,0 @@
1
- //#region src/virtual/module-config.d.ts
2
- /**
3
- * Virtual module stub for #nitro-graphql/module-config
4
- * This file is only used during build/bundling to prevent import resolution errors.
5
- * At runtime, Nitro will override this with the actual virtual module.
6
- */
7
- declare const moduleConfig: Record<string, any>;
8
- //#endregion
9
- export { moduleConfig };
@@ -1,10 +0,0 @@
1
- //#region src/virtual/module-config.ts
2
- /**
3
- * Virtual module stub for #nitro-graphql/module-config
4
- * This file is only used during build/bundling to prevent import resolution errors.
5
- * At runtime, Nitro will override this with the actual virtual module.
6
- */
7
- const moduleConfig = {};
8
-
9
- //#endregion
10
- export { moduleConfig };
@@ -1,11 +0,0 @@
1
- //#region src/virtual/server-directives.d.ts
2
- /**
3
- * Virtual module stub for #nitro-graphql/server-directives
4
- * This file is only used during build/bundling to prevent import resolution errors.
5
- * At runtime, Nitro will override this with the actual virtual module.
6
- */
7
- declare const directives: Array<{
8
- directive: any;
9
- }>;
10
- //#endregion
11
- export { directives };
@@ -1,10 +0,0 @@
1
- //#region src/virtual/server-directives.ts
2
- /**
3
- * Virtual module stub for #nitro-graphql/server-directives
4
- * This file is only used during build/bundling to prevent import resolution errors.
5
- * At runtime, Nitro will override this with the actual virtual module.
6
- */
7
- const directives = [];
8
-
9
- //#endregion
10
- export { directives };
@@ -1,11 +0,0 @@
1
- //#region src/virtual/server-resolvers.d.ts
2
- /**
3
- * Virtual module stub for #nitro-graphql/server-resolvers
4
- * This file is only used during build/bundling to prevent import resolution errors.
5
- * At runtime, Nitro will override this with the actual virtual module.
6
- */
7
- declare const resolvers: Array<{
8
- resolver: any;
9
- }>;
10
- //#endregion
11
- export { resolvers };
@@ -1,10 +0,0 @@
1
- //#region src/virtual/server-resolvers.ts
2
- /**
3
- * Virtual module stub for #nitro-graphql/server-resolvers
4
- * This file is only used during build/bundling to prevent import resolution errors.
5
- * At runtime, Nitro will override this with the actual virtual module.
6
- */
7
- const resolvers = [];
8
-
9
- //#endregion
10
- export { resolvers };
@@ -1,11 +0,0 @@
1
- //#region src/virtual/server-schemas.d.ts
2
- /**
3
- * Virtual module stub for #nitro-graphql/server-schemas
4
- * This file is only used during build/bundling to prevent import resolution errors.
5
- * At runtime, Nitro will override this with the actual virtual module.
6
- */
7
- declare const schemas: Array<{
8
- def: string;
9
- }>;
10
- //#endregion
11
- export { schemas };
@@ -1,10 +0,0 @@
1
- //#region src/virtual/server-schemas.ts
2
- /**
3
- * Virtual module stub for #nitro-graphql/server-schemas
4
- * This file is only used during build/bundling to prevent import resolution errors.
5
- * At runtime, Nitro will override this with the actual virtual module.
6
- */
7
- const schemas = [];
8
-
9
- //#endregion
10
- export { schemas };