@znight/graphql 0.0.0-stage → 0.2.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.
Files changed (62) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1062 -2
  3. package/dist/compiler.d.mts +93 -0
  4. package/dist/compiler.mjs +2832 -0
  5. package/dist/compiler.mjs.map +1 -0
  6. package/dist/index.d.mts +542 -0
  7. package/dist/index.mjs +128 -0
  8. package/dist/index.mjs.map +1 -0
  9. package/dist/names-BlzDM5cF.mjs +111 -0
  10. package/dist/names-BlzDM5cF.mjs.map +1 -0
  11. package/dist/plugin-BdBxr5NQ.mjs +3222 -0
  12. package/dist/plugin-BdBxr5NQ.mjs.map +1 -0
  13. package/dist/testing.d.mts +101 -0
  14. package/dist/testing.mjs +306 -0
  15. package/dist/testing.mjs.map +1 -0
  16. package/dist/types-CgbV9LjD.d.mts +234 -0
  17. package/package.json +95 -4
  18. package/src/compiler/analyze.ts +608 -0
  19. package/src/compiler/builder.ts +1640 -0
  20. package/src/compiler/constants.ts +74 -0
  21. package/src/compiler/data.ts +73 -0
  22. package/src/compiler/defaults.ts +92 -0
  23. package/src/compiler/discriminators.ts +53 -0
  24. package/src/compiler/docs.ts +55 -0
  25. package/src/compiler/generate.ts +405 -0
  26. package/src/compiler/ids.ts +128 -0
  27. package/src/compiler/index.ts +93 -0
  28. package/src/compiler/locate.ts +44 -0
  29. package/src/compiler/model.ts +122 -0
  30. package/src/compiler/options.ts +54 -0
  31. package/src/compiler/scalars.ts +138 -0
  32. package/src/compiler/sdl-view.ts +59 -0
  33. package/src/context.ts +181 -0
  34. package/src/decisions.ts +169 -0
  35. package/src/decorators.ts +196 -0
  36. package/src/errors.ts +89 -0
  37. package/src/execution.ts +1064 -0
  38. package/src/format.ts +285 -0
  39. package/src/index.ts +84 -0
  40. package/src/limits.ts +177 -0
  41. package/src/loaders.ts +149 -0
  42. package/src/memory-pubsub.ts +133 -0
  43. package/src/metadata.ts +195 -0
  44. package/src/names.ts +47 -0
  45. package/src/options.ts +309 -0
  46. package/src/pipeline.ts +277 -0
  47. package/src/plugin.ts +557 -0
  48. package/src/pubsub.ts +36 -0
  49. package/src/scalars.ts +131 -0
  50. package/src/schema-hash.ts +18 -0
  51. package/src/schema.ts +557 -0
  52. package/src/sdl.ts +515 -0
  53. package/src/testing.ts +454 -0
  54. package/src/tokens.ts +22 -0
  55. package/src/transport/abort.ts +80 -0
  56. package/src/transport/accept.ts +155 -0
  57. package/src/transport/graphiql.ts +106 -0
  58. package/src/transport/http.ts +373 -0
  59. package/src/transport/sse.ts +45 -0
  60. package/src/type-ref.ts +89 -0
  61. package/src/types.ts +190 -0
  62. package/src/validate-args.ts +48 -0
@@ -0,0 +1,2832 @@
1
+ import { a as SPECIFIED_SCALARS, c as printTypeRef, i as ROOT_TYPE_NAMES, n as DEFAULT_DEPRECATION_REASON, o as isGraphQLName, r as RESERVED_ENUM_VALUES, s as parseTypeRef, t as BUILTIN_SCALARS } from "./names-BlzDM5cF.mjs";
2
+ import { createHash } from "node:crypto";
3
+ import { effectiveRouteMeta, readRouteMeta, requiredRouteGroups } from "@znight/http/compiler";
4
+ // src/compiler/ids.ts
5
+ /** Name of the extension, also the key of `metadata.extensions.graphql`. */
6
+ const EXTENSION_NAME = "graphql";
7
+ /** Module the generated code imports its runtime helpers and types from. */
8
+ const RUNTIME_MODULE = "@znight/graphql";
9
+ /** Canonical identities of the exports of `@znight/graphql` the compiler reads. */
10
+ const GraphQLIds = Object.freeze({
11
+ Resolver: "@znight/graphql#Resolver",
12
+ Query: "@znight/graphql#Query",
13
+ Mutation: "@znight/graphql#Mutation",
14
+ Subscription: "@znight/graphql#Subscription",
15
+ ResolveField: "@znight/graphql#ResolveField",
16
+ Args: "@znight/graphql#Args",
17
+ Parent: "@znight/graphql#Parent",
18
+ Ctx: "@znight/graphql#Ctx",
19
+ Info: "@znight/graphql#Info",
20
+ Loader: "@znight/graphql#Loader",
21
+ UseGuard: "@znight/graphql#UseGuard",
22
+ scalar: "@znight/graphql#scalar",
23
+ ID: "@znight/graphql#ID",
24
+ Int: "@znight/graphql#Int",
25
+ Float: "@znight/graphql#Float",
26
+ JSONValue: "@znight/graphql#JSONValue",
27
+ BatchLoad: "@znight/graphql#BatchLoad",
28
+ GraphQLContext: "@znight/graphql#GraphQLContext",
29
+ ResolverContext: "@znight/graphql#ResolverContext",
30
+ PubSub: "@znight/graphql#PubSub",
31
+ GraphQLPlugin: "@znight/graphql#GraphQLPlugin"
32
+ });
33
+ /** Field decorators → the kind of field they declare (`GraphQLResolverBinding.operation`). */
34
+ const FIELD_DECORATORS = /* @__PURE__ */ new Map([
35
+ [GraphQLIds.Query, "query"],
36
+ [GraphQLIds.Mutation, "mutation"],
37
+ [GraphQLIds.Subscription, "subscription"],
38
+ [GraphQLIds.ResolveField, "field"]
39
+ ]);
40
+ /** Parameter decorators → what the generated `invoke` passes (§7.3). */
41
+ const PARAMETER_DECORATORS = /* @__PURE__ */ new Map([
42
+ [GraphQLIds.Args, "args"],
43
+ [GraphQLIds.Parent, "parent"],
44
+ [GraphQLIds.Ctx, "ctx"],
45
+ [GraphQLIds.Info, "info"],
46
+ [GraphQLIds.Loader, "loader"]
47
+ ]);
48
+ /** Scalar aliases of `@znight/graphql` → their GraphQL scalar (§6.2). */
49
+ const SCALAR_ALIASES = /* @__PURE__ */ new Map([
50
+ [GraphQLIds.ID, "ID"],
51
+ [GraphQLIds.Int, "Int"],
52
+ [GraphQLIds.Float, "Float"],
53
+ [GraphQLIds.JSONValue, "JSON"]
54
+ ]);
55
+ /**
56
+ * Decorators of `@znight/http` that look like GraphQL ones, on a resolver: ZNIGHT005 with the
57
+ * `@znight/graphql` decorator to import instead (§6.5).
58
+ */
59
+ const HTTP_LOOK_ALIKES = /* @__PURE__ */ new Map([
60
+ ["@znight/http#Ctx", GraphQLIds.Ctx],
61
+ ["@znight/http#Query", GraphQLIds.Args],
62
+ ["@znight/http#Param", GraphQLIds.Args],
63
+ ["@znight/http#Body", GraphQLIds.Args],
64
+ ["@znight/http#UseGuard", GraphQLIds.UseGuard]
65
+ ]);
66
+ /** `@Controller` of `@znight/http`: a class cannot be both a controller and a resolver (ZNIGHT005). */
67
+ const HTTP_CONTROLLER = "@znight/http#Controller";
68
+ // src/compiler/constants.ts
69
+ /** Diagnostic codes the extension reports (RFC 0005 §6.6 and the reused framework codes). */
70
+ const Codes = Object.freeze({
71
+ InvalidDecorator: "ZNIGHT005",
72
+ MissingRouteDecision: "ZNIGHT023",
73
+ InvalidType: "ZNIGHT060",
74
+ NameConflict: "ZNIGHT061",
75
+ InvalidResolver: "ZNIGHT062",
76
+ InvalidInput: "ZNIGHT063",
77
+ UnresolvableAbstractType: "ZNIGHT064",
78
+ InvalidLoader: "ZNIGHT065"
79
+ });
80
+ /** Root reason given to `AnalyzeContext.addRoot()`. */
81
+ const ROOT_REASON = "GraphQL resolver";
82
+ /** Async iterables: the return type of `@Subscription` methods (§6.2). */
83
+ const ASYNC_ITERABLES = /* @__PURE__ */ new Set([
84
+ "globalThis#AsyncIterable",
85
+ "globalThis#AsyncIterableIterator",
86
+ "globalThis#AsyncGenerator"
87
+ ]);
88
+ /** Iterables mapped to lists in output position (§6.2). */
89
+ const OUTPUT_ITERABLES = /* @__PURE__ */ new Set([
90
+ "globalThis#Set",
91
+ "globalThis#ReadonlySet",
92
+ "globalThis#Iterable"
93
+ ]);
94
+ /**
95
+ * Identities the shapes keep as references (`ShapeOptions.keep`), before the identities of the
96
+ * `scalar<T>()` declarations of the application.
97
+ */
98
+ const BASE_KEEP = Object.freeze([
99
+ ...ASYNC_ITERABLES,
100
+ ...OUTPUT_ITERABLES,
101
+ GraphQLIds.ID,
102
+ GraphQLIds.Int,
103
+ GraphQLIds.Float,
104
+ GraphQLIds.JSONValue,
105
+ GraphQLIds.Loader
106
+ ]);
107
+ /** Deterministic string comparison (code-unit order, never `localeCompare`). */
108
+ function compareStrings(a, b) {
109
+ if (a === b) return 0;
110
+ return a < b ? -1 : 1;
111
+ }
112
+ // src/compiler/analyze.ts
113
+ const SCOPES = [
114
+ "singleton",
115
+ "request",
116
+ "transient"
117
+ ];
118
+ /** Shape options reading `Loader<L>` parameters: the alias is kept, `L` stays a named shape. */
119
+ const LOADER_SHAPE = Object.freeze({
120
+ keep: Object.freeze([GraphQLIds.Loader]),
121
+ jsdoc: false
122
+ });
123
+ /** Analyses a class carrying at least one graphql decorator (class, method or parameter). */
124
+ function analyzeGraphQLClass(cls, ctx) {
125
+ const resolvers = cls.decorators.filter((decorator) => decorator.identity === GraphQLIds.Resolver);
126
+ const resolver = resolvers[0];
127
+ if (resolver === void 0) {
128
+ reportOutsideResolver(cls, ctx);
129
+ return;
130
+ }
131
+ for (const extra of resolvers.slice(1)) error(ctx, Codes.InvalidDecorator, extra.location, `@Resolver is applied twice to ${cls.displayName}`, ["Apply it once"]);
132
+ const controller = cls.decorators.find((decorator) => decorator.identity === HTTP_CONTROLLER);
133
+ if (controller !== void 0) {
134
+ error(ctx, Codes.InvalidDecorator, resolver.location, `${cls.displayName} cannot be both a @Resolver and a @Controller`, ["A class is the provider of one extension: move the GraphQL fields to their own @Resolver() class (both may call the same service)"], [{
135
+ message: "@Controller is applied here",
136
+ location: controller.location
137
+ }]);
138
+ return;
139
+ }
140
+ if (ctx.options.library) {
141
+ error(ctx, Codes.InvalidResolver, resolver.location, `${cls.displayName} is a @Resolver in a compiled provider library: the schema is derived from the sources`, ["Publish the package as a source library (without library: true), so that applications compile its resolvers"]);
142
+ return;
143
+ }
144
+ if (cls.abstract || cls.typeParameters.length > 0) {
145
+ error(ctx, Codes.InvalidDecorator, resolver.location, cls.abstract ? `@Resolver cannot be applied to the abstract class ${cls.displayName}` : `@Resolver cannot be applied to the generic class ${cls.displayName}<${cls.typeParameters.join(", ")}>`, [cls.abstract ? "Resolvers are instantiated: remove `abstract`" : "Remove the type parameters of the resolver"]);
146
+ return;
147
+ }
148
+ const scope = resolverScope(ctx, resolver);
149
+ ctx.registerProvider(cls, { scope });
150
+ ctx.addRoot(cls, {
151
+ reason: ROOT_REASON,
152
+ location: resolver.location
153
+ });
154
+ const classGuards = guardsOf(ctx, cls, cls.decorators);
155
+ const classMeta = readRouteMeta(ctx, cls);
156
+ const fields = [];
157
+ for (const method of cls.methods) {
158
+ const decorators = method.decorators.filter(isFieldDecorator);
159
+ if (decorators.length === 0) {
160
+ reportStrayMethodDecorators(cls, method, ctx);
161
+ continue;
162
+ }
163
+ fields.push(...analyzeMethod(ctx, cls, method, decorators, classMeta));
164
+ }
165
+ ctx.store({
166
+ kind: "resolver",
167
+ host: cls,
168
+ scope,
169
+ location: resolver.location,
170
+ guards: classGuards,
171
+ fields
172
+ });
173
+ }
174
+ function isFieldDecorator(decorator) {
175
+ return decorator.identity !== void 0 && FIELD_DECORATORS.has(decorator.identity);
176
+ }
177
+ function isParameterDecorator(decorator) {
178
+ return decorator.identity !== void 0 && PARAMETER_DECORATORS.has(decorator.identity);
179
+ }
180
+ /** `@Resolver({ scope })`. */
181
+ function resolverScope(ctx, decorator) {
182
+ const arg = decorator.args[0];
183
+ if (arg === void 0 || !arg.evaluated || arg.value === void 0) return "singleton";
184
+ const value = arg.value;
185
+ if (!isRecord(value)) {
186
+ error(ctx, Codes.InvalidDecorator, arg.location, `@Resolver expects { scope? }, got ${describe$1(value)}`, ["@Resolver() or @Resolver({ scope: 'request' })"]);
187
+ return "singleton";
188
+ }
189
+ let scope = "singleton";
190
+ for (const [key, option] of Object.entries(value)) if (key !== "scope") error(ctx, Codes.InvalidDecorator, arg.location, `@Resolver: unknown option "${key}"`, ["Options: { scope? }"]);
191
+ else if (SCOPES.includes(option)) scope = option;
192
+ else if (option !== void 0) error(ctx, Codes.InvalidDecorator, arg.location, `@Resolver: invalid scope ${describe$1(option)}`, [`Use one of ${SCOPES.map((candidate) => `'${candidate}'`).join(", ")}`]);
193
+ return scope;
194
+ }
195
+ /** `@UseGuard(A, B)` decorators of a target: guard classes bound with lazy edges (C3). */
196
+ function guardsOf(ctx, cls, decorators) {
197
+ const guards = [];
198
+ for (const decorator of decorators) {
199
+ if (decorator.identity !== GraphQLIds.UseGuard) continue;
200
+ if (decorator.args.length === 0) error(ctx, Codes.InvalidDecorator, decorator.location, "@UseGuard needs at least one guard class", ["@UseGuard(AccessGuard)"]);
201
+ for (const arg of decorator.args) {
202
+ const ref = ctx.resolveClassRef(arg, {
203
+ from: cls,
204
+ role: "guard",
205
+ lazy: true
206
+ });
207
+ if (ref !== void 0) guards.push(ref);
208
+ }
209
+ }
210
+ return guards;
211
+ }
212
+ function analyzeMethod(ctx, cls, method, decorators, classMeta) {
213
+ const where = `${cls.displayName}.${method.name}`;
214
+ const primary = decorators[0];
215
+ let complete = checkMethodShape(ctx, method, primary, where);
216
+ complete = checkForeignHandler(ctx, method, primary, where) && complete;
217
+ const params = [];
218
+ for (const param of method.params) {
219
+ const data = analyzeParameter(ctx, cls, param, where);
220
+ params.push(data);
221
+ if (data === void 0) complete = false;
222
+ }
223
+ const parents = params.filter((param) => param?.kind === "parent");
224
+ for (const extra of parents.slice(1)) {
225
+ error(ctx, Codes.InvalidResolver, extra.location, `${where} has several @Parent() parameters`, ["Declare the parent object once"]);
226
+ complete = false;
227
+ }
228
+ const guards = guardsOf(ctx, cls, method.decorators);
229
+ const meta = effectiveRouteMeta(classMeta, readRouteMeta(ctx, cls, method));
230
+ const fields = [];
231
+ const seen = /* @__PURE__ */ new Set();
232
+ for (const decorator of decorators) {
233
+ const operation = FIELD_DECORATORS.get(decorator.identity);
234
+ const explicit = fieldName(ctx, decorator, method, where);
235
+ const name = explicit ?? method.name;
236
+ const key = `${operation}\0${name}`;
237
+ if (seen.has(key)) {
238
+ error(ctx, Codes.InvalidDecorator, decorator.location, `@${decorator.name}('${name}') is applied twice to ${where}`, ["Apply each field decorator once"]);
239
+ continue;
240
+ }
241
+ seen.add(key);
242
+ let fieldComplete = complete && explicit !== void 0;
243
+ if (operation === "field" && parents.length === 0) {
244
+ error(ctx, Codes.InvalidResolver, decorator.location, `@ResolveField ${where} has no @Parent() parameter`, [`Declare the parent object first: ${method.name}(@Parent() parent: ParentType, ...)`]);
245
+ fieldComplete = false;
246
+ } else if (operation !== "field" && parents.length > 0) {
247
+ error(ctx, Codes.InvalidResolver, parents[0].location, `@Parent() is only available in @ResolveField methods, not in the @${decorator.name} ${where}`, ["Root fields have no parent object: remove the parameter"]);
248
+ fieldComplete = false;
249
+ }
250
+ fields.push({
251
+ method: method.name,
252
+ operation,
253
+ name,
254
+ location: decorator.location,
255
+ methodLocation: method.location,
256
+ guards,
257
+ meta,
258
+ params,
259
+ complete: fieldComplete
260
+ });
261
+ }
262
+ return fields;
263
+ }
264
+ /** The field name: the static decorator argument, or the method name. */
265
+ function fieldName(ctx, decorator, method, where) {
266
+ const arg = decorator.args[0];
267
+ if (arg === void 0 || arg.evaluated && arg.value === void 0) {
268
+ if (isGraphQLName(method.name)) return method.name;
269
+ error(ctx, Codes.NameConflict, decorator.location, `'${method.name}' is not a valid GraphQL field name (${where}): name the field in the decorator`, ["GraphQL names match /^[_A-Za-z][_0-9A-Za-z]*$/ and do not start with __", `@${decorator.name}('validName')`]);
270
+ return;
271
+ }
272
+ if (!arg.evaluated) return void 0;
273
+ const value = arg.value;
274
+ if (typeof value !== "string") {
275
+ error(ctx, Codes.InvalidDecorator, arg.location, `@${decorator.name} on ${where} expects a field name, got ${describe$1(value)}`, [`@${decorator.name}('${method.name}') or @${decorator.name}()`]);
276
+ return;
277
+ }
278
+ if (!isGraphQLName(value)) {
279
+ error(ctx, Codes.NameConflict, arg.location, `'${value}' is not a valid GraphQL field name (${where})`, ["GraphQL names match /^[_A-Za-z][_0-9A-Za-z]*$/ and do not start with __"]);
280
+ return;
281
+ }
282
+ return value;
283
+ }
284
+ /** Resolver methods are called by the generated code: `resolver.method(...)`. */
285
+ function checkMethodShape(ctx, method, decorator, where) {
286
+ const name = `@${decorator.name}`;
287
+ let problem;
288
+ if (method.kind !== "method") problem = {
289
+ message: `${name} cannot be applied to the accessor ${where}`,
290
+ hint: "Use a regular method"
291
+ };
292
+ else if (method.static) problem = {
293
+ message: `${name} cannot be applied to the static method ${where}`,
294
+ hint: "Fields are resolved on the resolver instance: remove `static`"
295
+ };
296
+ else if (method.privateName) problem = {
297
+ message: `${name} cannot be applied to the #private method ${where}`,
298
+ hint: "Use a public method: the generated code calls it"
299
+ };
300
+ else if (method.visibility !== "public") problem = {
301
+ message: `${where} must be public: ${name} methods are called by the generated code`,
302
+ hint: `Remove the '${method.visibility}' modifier`
303
+ };
304
+ else if (method.computed) problem = {
305
+ message: `${name} cannot be applied to ${where}: computed method names are not supported`,
306
+ hint: "Use a plain method name"
307
+ };
308
+ else if (method.typeParameters.length > 0) problem = {
309
+ message: `${name} cannot be applied to the generic method ${where}<${method.typeParameters.join(", ")}>`,
310
+ hint: "The schema is derived from the signature: remove the type parameters"
311
+ };
312
+ if (problem === void 0) return true;
313
+ error(ctx, Codes.InvalidDecorator, decorator.location, problem.message, [problem.hint]);
314
+ return false;
315
+ }
316
+ /** A resolver method cannot also be handled by another extension (`@Get`, `@OnMessage`, `@Cron`). */
317
+ function checkForeignHandler(ctx, method, decorator, where) {
318
+ for (const other of method.decorators) {
319
+ const owner = other.owner;
320
+ if (owner === void 0 || owner === "graphql" || owner === "core" || owner === "manifest") continue;
321
+ error(ctx, Codes.InvalidDecorator, other.location, `${where} cannot be both a GraphQL field (@${decorator.name}) and a @${other.name} handler`, ["A class is the provider of one extension: let both handlers call a shared service"]);
322
+ return false;
323
+ }
324
+ return true;
325
+ }
326
+ /**
327
+ * Graphql parameter decorators of a parameter, de-duplicated by position (the compiler reports the
328
+ * decorators of a parameter with a default value twice).
329
+ */
330
+ function parameterDecorators(param) {
331
+ const seen = /* @__PURE__ */ new Set();
332
+ return param.decorators.filter((decorator) => {
333
+ if (!isParameterDecorator(decorator) || seen.has(decorator.location.start)) return false;
334
+ seen.add(decorator.location.start);
335
+ return true;
336
+ });
337
+ }
338
+ function analyzeParameter(ctx, cls, param, where) {
339
+ const decorators = parameterDecorators(param);
340
+ const decorator = decorators[0];
341
+ if (decorator === void 0) {
342
+ const lookAlike = param.decorators.find((found) => found.identity !== void 0 && HTTP_LOOK_ALIKES.has(found.identity));
343
+ if (lookAlike !== void 0) {
344
+ const replacement = HTTP_LOOK_ALIKES.get(lookAlike.identity).split("#")[1];
345
+ error(ctx, Codes.InvalidDecorator, lookAlike.location, `@${lookAlike.name} on parameter '${param.name}' of ${where} is imported from '@znight/http': resolver parameters use @${replacement}() from '${RUNTIME_MODULE}'`, [`Import it from '${RUNTIME_MODULE}': import { ${replacement} } from '${RUNTIME_MODULE}'`]);
346
+ return;
347
+ }
348
+ error(ctx, Codes.InvalidDecorator, param.location, `Parameter '${param.name}' of ${where} has no @Args(), @Parent(), @Ctx(), @Info() or @Loader() decorator`, ["Every resolver parameter is filled by GraphQL: @Args(name?, schema?) for arguments, @Parent() for the parent object, @Ctx() for the GraphQLContext, @Info() for the GraphQLResolveInfo, @Loader() for a DataLoader"]);
349
+ return;
350
+ }
351
+ if (decorators.length > 1) {
352
+ error(ctx, Codes.InvalidDecorator, decorators[1].location, `Parameter '${param.name}' of ${where} has several GraphQL decorators (${decorators.map((found) => `@${found.name}`).join(", ")})`, ["Keep a single one"]);
353
+ return;
354
+ }
355
+ if (param.rest) {
356
+ error(ctx, Codes.InvalidDecorator, decorator.location, `@${decorator.name} cannot be applied to the rest parameter '...${param.name}' of ${where}`);
357
+ return;
358
+ }
359
+ switch (PARAMETER_DECORATORS.get(decorator.identity)) {
360
+ case "args": return argsParameter(ctx, decorator, param, where);
361
+ case "parent": return {
362
+ kind: "parent",
363
+ location: decorator.location
364
+ };
365
+ case "ctx": return { kind: "ctx" };
366
+ case "info": return { kind: "info" };
367
+ default: return loaderParameter(ctx, cls, param, where);
368
+ }
369
+ }
370
+ /** `@Args()`, `@Args('name')`, `@Args('name', Schema)`, `@Args(Schema)`. */
371
+ function argsParameter(ctx, decorator, param, where) {
372
+ const [first, second, ...extra] = decorator.args;
373
+ if (extra.length > 0) {
374
+ error(ctx, Codes.InvalidDecorator, decorator.location, `@Args takes at most two arguments (${where})`, ["@Args(), @Args('name'), @Args('name', Schema) or @Args(Schema)"]);
375
+ return;
376
+ }
377
+ let name;
378
+ let schemaArg = second;
379
+ if (first !== void 0) {
380
+ if (!first.evaluated && first.ref === void 0) return void 0;
381
+ if (typeof first.value === "string") {
382
+ if (!isGraphQLName(first.value)) {
383
+ error(ctx, Codes.NameConflict, first.location, `'${first.value}' is not a valid GraphQL argument name (parameter '${param.name}' of ${where})`, ["GraphQL names match /^[_A-Za-z][_0-9A-Za-z]*$/ and do not start with __"]);
384
+ return;
385
+ }
386
+ name = first.value;
387
+ } else if (first.ref !== void 0) {
388
+ if (second !== void 0) {
389
+ error(ctx, Codes.InvalidDecorator, second.location, `@Args(Schema) takes no second argument (${where})`, ["@Args('name', Schema) validates one argument, @Args(Schema) every argument"]);
390
+ return;
391
+ }
392
+ schemaArg = first;
393
+ } else if (first.value !== void 0) {
394
+ error(ctx, Codes.InvalidDecorator, first.location, `@Args on parameter '${param.name}' of ${where} expects an argument name or a schema, got ${describe$1(first.value)}`, ["@Args('id'), @Args() or @Args('input', Schema)"]);
395
+ return;
396
+ }
397
+ }
398
+ if (schemaArg !== void 0 && !(schemaArg.evaluated && schemaArg.value === void 0)) {
399
+ if (schemaArg.ref === void 0) {
400
+ if (schemaArg.evaluated) error(ctx, Codes.InvalidDecorator, schemaArg.location, `The schema of @Args on parameter '${param.name}' of ${where} must be a reference to an exported schema`, ["Declare it with `export const Schema = z.object(...)` and pass Schema: the generated module imports it"]);
401
+ return;
402
+ }
403
+ return {
404
+ kind: "args",
405
+ name,
406
+ schema: schemaArg.ref,
407
+ location: decorator.location
408
+ };
409
+ }
410
+ return {
411
+ kind: "args",
412
+ name,
413
+ schema: void 0,
414
+ location: decorator.location
415
+ };
416
+ }
417
+ /** `@Loader() authors: Loader<AuthorsById>`: binds `AuthorsById` with a lazy edge. */
418
+ function loaderParameter(ctx, cls, param, where) {
419
+ const root = ctx.types.shape({ parameter: param }, LOADER_SHAPE);
420
+ const shape = root.root;
421
+ const argument = shape.kind === "reference" && shape.identity === GraphQLIds.Loader ? shape.typeArgs[0] : void 0;
422
+ const identity = argument?.kind === "named" ? root.named.get(argument.key)?.identity : void 0;
423
+ if (identity === void 0) {
424
+ error(ctx, Codes.InvalidLoader, param.typeLocation, `@Loader() parameter '${param.name}' of ${where} must be typed Loader<L>, with L a loader class`, [`${param.name}: Loader<AuthorsById>, where AuthorsById is a provider implementing BatchLoad<K, V> (import type { Loader } from '${RUNTIME_MODULE}')`]);
425
+ return;
426
+ }
427
+ return {
428
+ kind: "loader",
429
+ binding: ctx.bindInjection({
430
+ type: identity,
431
+ location: param.typeLocation,
432
+ label: `loader '${param.name}' of ${where}()`
433
+ }, {
434
+ from: cls,
435
+ lazy: true
436
+ }),
437
+ identity,
438
+ location: param.typeLocation
439
+ };
440
+ }
441
+ /**
442
+ * Graphql decorators on a class without `@Resolver`: field methods are not inherited (a base
443
+ * class), and parameter or guard decorators have no effect.
444
+ */
445
+ function reportOutsideResolver(cls, ctx) {
446
+ for (const decorator of cls.decorators) if (decorator.identity === GraphQLIds.UseGuard) error(ctx, Codes.InvalidDecorator, decorator.location, `@UseGuard has no effect: ${cls.displayName} is not a @Resolver`, [`Add @Resolver() to ${cls.displayName}`]);
447
+ for (const method of cls.methods) {
448
+ const fields = method.decorators.filter(isFieldDecorator);
449
+ for (const field of fields) error(ctx, Codes.InvalidResolver, field.location, `@${field.name} ${cls.displayName}.${method.name} is declared on a class that is not a @Resolver`, [cls.abstract ? `Resolver methods are not inherited: declare the field on the concrete @Resolver() class (it may call ${method.name} of the base class)` : `Add @Resolver() to ${cls.displayName} (resolver methods are not inherited from base classes)`]);
450
+ if (fields.length === 0) reportStrayMethodDecorators(cls, method, ctx);
451
+ }
452
+ }
453
+ /** `@UseGuard` or parameter decorators on a method that is not a field. */
454
+ function reportStrayMethodDecorators(cls, method, ctx) {
455
+ const where = `${cls.displayName}.${method.name}`;
456
+ for (const decorator of method.decorators) if (decorator.identity === GraphQLIds.UseGuard) error(ctx, Codes.InvalidDecorator, decorator.location, `@UseGuard has no effect: ${where} is not a GraphQL field`, ["Add @Query(), @Mutation(), @Subscription() or @ResolveField() to the method"]);
457
+ for (const param of method.params) for (const decorator of parameterDecorators(param)) error(ctx, Codes.InvalidDecorator, decorator.location, `@${decorator.name} has no effect: ${where} is not a GraphQL field`, ["Add @Query(), @Mutation(), @Subscription() or @ResolveField() to the method"]);
458
+ }
459
+ function error(ctx, code, location, message, hints = [], related = []) {
460
+ ctx.report({
461
+ code,
462
+ severity: "error",
463
+ message,
464
+ location,
465
+ ...hints.length === 0 ? {} : { hints },
466
+ ...related.length === 0 ? {} : { related }
467
+ });
468
+ }
469
+ /** An evaluated object literal (not an array, not a reference). */
470
+ function isRecord(value) {
471
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
472
+ const prototype = Object.getPrototypeOf(value);
473
+ return prototype === Object.prototype || prototype === null;
474
+ }
475
+ /** Short description of a value for messages. */
476
+ function describe$1(value) {
477
+ if (value === void 0) return "undefined";
478
+ if (value === null) return "null";
479
+ if (typeof value === "string") return JSON.stringify(value);
480
+ if (typeof value === "bigint") return `${value}n`;
481
+ if (typeof value !== "object") return String(value);
482
+ if (Array.isArray(value)) return "an array";
483
+ return isRecord(value) ? "an object" : "a reference";
484
+ }
485
+ /** First 16 hexadecimal characters of the SHA-256 of `sdl` (UTF-8). */
486
+ function schemaHash(sdl) {
487
+ return createHash("sha256").update(sdl, "utf8").digest("hex").slice(0, 16);
488
+ }
489
+ // src/sdl.ts
490
+ /**
491
+ * Deterministic SDL printer (RFC 0005 §6.7, §7.3).
492
+ *
493
+ * Prints a schema model (the data of `metadata.extensions.graphql`, without its functions) exactly
494
+ * like graphql-js 17 `printSchema()` prints the `GraphQLSchema` the runtime builds from it: same
495
+ * order, same block strings, same default value literals, byte for byte. The compiler hashes this
496
+ * output (`schemaHash`) and writes it as the optional SDL artifact; the runtime can print without
497
+ * graphql-js.
498
+ *
499
+ * Import-free (types and constants of import-free modules only): shared by the compiler extension
500
+ * and the runtime. Equivalence holds when the runtime builds the schema the way this module
501
+ * assumes:
502
+ *
503
+ * - every type of the model passed to `new GraphQLSchema({ types })` in model order (metadata types
504
+ * are sorted by name), so the type map, hence `printSchema`, follows that order;
505
+ * - default values passed as `default: { value }` (external values: enum values by name), printed
506
+ * by graphql-js through `valueToLiteral`;
507
+ * - built-in scalars (`names.ts`) without description, with their `specifiedByURL`, and no scalar
508
+ * with a custom `valueToLiteral` used in a default value.
509
+ */
510
+ /**
511
+ * Prints the SDL of a schema, without a trailing newline (like `printSchema`). Throws an `Error` on
512
+ * a malformed type reference or a default value that does not match its type (the compiler reports
513
+ * these as diagnostics before printing).
514
+ */
515
+ function printSdl(schema) {
516
+ const types = /* @__PURE__ */ new Map();
517
+ for (const type of schema.types) types.set(type.name, type);
518
+ const printer = new SdlPrinter(types);
519
+ const parts = [];
520
+ const definition = printSchemaDefinition(schema.roots, types);
521
+ if (definition !== void 0) parts.push(definition);
522
+ for (const type of schema.types) if (!SPECIFIED_SCALARS.has(type.name)) parts.push(printer.type(type));
523
+ return parts.join("\n\n");
524
+ }
525
+ /** `schema { ... }`, only when the root types do not have their default names (as graphql-js). */
526
+ function printSchemaDefinition(roots, types) {
527
+ const isDefault = (root, name) => root === void 0 ? !types.has(name) : root === name;
528
+ if (isDefault(roots.query, ROOT_TYPE_NAMES.query) && isDefault(roots.mutation, ROOT_TYPE_NAMES.mutation) && isDefault(roots.subscription, ROOT_TYPE_NAMES.subscription)) return;
529
+ return `schema {
530
+ query: ${roots.query}\n` + (roots.mutation === void 0 ? "" : ` mutation: ${roots.mutation}\n`) + (roots.subscription === void 0 ? "" : ` subscription: ${roots.subscription}\n`) + "}";
531
+ }
532
+ const GRAPHQL_MAX_INT = 2147483647;
533
+ const GRAPHQL_MIN_INT = -2147483648;
534
+ const INTEGER_STRING = /^-?(?:0|[1-9][0-9]*)$/;
535
+ /** graphql-js `print()` breaks lists and objects longer than this. */
536
+ const MAX_LINE_LENGTH = 80;
537
+ var SdlPrinter = class {
538
+ #types;
539
+ constructor(types) {
540
+ this.#types = types;
541
+ }
542
+ type(type) {
543
+ const head = printDescription(type.description, "", true);
544
+ switch (type.kind) {
545
+ case "object": return `${head}type ${type.name}${printBlock(type.fields.map((field, i) => this.#field(type.name, field, i)))}`;
546
+ case "input": return `${head}input ${type.name}${printBlock(type.fields.map((field, i) => `${printDescription(field.description, " ", i === 0)} ${this.#inputValue(field, `${type.name}.${field.name}`)}`))}`;
547
+ case "enum": return `${head}enum ${type.name}${printBlock(type.values.map((value, i) => `${printDescription(value.description, " ", i === 0)} ${value.name}${printDeprecated(value.deprecationReason)}`))}`;
548
+ case "union": return `${head}union ${type.name}${type.members.length === 0 ? "" : ` = ${type.members.join(" | ")}`}`;
549
+ case "scalar": {
550
+ const url = type.specifiedByURL ?? (type.builtin === true ? BUILTIN_SCALARS.get(type.name)?.specifiedByURL : void 0);
551
+ return `${head}scalar ${type.name}${url === void 0 ? "" : ` @specifiedBy(url: ${printString(url)})`}`;
552
+ }
553
+ }
554
+ }
555
+ #field(typeName, field, index) {
556
+ const coordinate = `${typeName}.${field.name}`;
557
+ return `${printDescription(field.description, " ", index === 0)} ${field.name}` + this.#args(coordinate, field.args ?? []) + `: ${checkedTypeRef(field.type, coordinate)}${printDeprecated(field.deprecationReason)}`;
558
+ }
559
+ #args(coordinate, args) {
560
+ if (args.length === 0) return "";
561
+ if (args.every((arg) => arg.description === void 0)) return `(${args.map((arg) => this.#inputValue(arg, `${coordinate}(${arg.name}:)`)).join(", ")})`;
562
+ return `(\n${args.map((arg, i) => `${printDescription(arg.description, " ", i === 0)} ${this.#inputValue(arg, `${coordinate}(${arg.name}:)`)}`).join("\n")}\n )`;
563
+ }
564
+ #inputValue(value, coordinate) {
565
+ const ref = parseTypeRef(value.type);
566
+ if (ref === void 0) throw new Error(`Invalid type reference '${value.type}' (${coordinate})`);
567
+ let declaration = `${value.name}: ${value.type}`;
568
+ if (value.defaultValue !== void 0) {
569
+ const literal = this.#literal(value.defaultValue, ref);
570
+ if (literal === void 0) throw new Error(`Invalid default value for ${coordinate}: ${describe(value.defaultValue)}`);
571
+ declaration += ` = ${printLiteral(literal)}`;
572
+ }
573
+ return declaration + printDeprecated(value.deprecationReason);
574
+ }
575
+ /** graphql-js `valueToLiteral(value, type)`: `undefined` when the value does not fit the type. */
576
+ #literal(value, ref) {
577
+ if (ref.nonNull && value == null) return void 0;
578
+ if (value == null) return { kind: "NullValue" };
579
+ if (ref.kind === "list") {
580
+ const item = ref.of;
581
+ if (!isIterableObject(value)) return this.#literal(value, item);
582
+ const values = [];
583
+ for (const entry of value) {
584
+ const literal = this.#literal(entry, item);
585
+ if (literal === void 0) return void 0;
586
+ values.push(literal);
587
+ }
588
+ return {
589
+ kind: "ListValue",
590
+ values
591
+ };
592
+ }
593
+ const type = this.#types.get(ref.name);
594
+ if (type?.kind === "input") return this.#inputLiteral(value, type);
595
+ if (type?.kind === "enum") return typeof value === "string" && type.values.some((entry) => entry.name === value) ? {
596
+ kind: "EnumValue",
597
+ value
598
+ } : void 0;
599
+ return scalarLiteral(value, ref.name);
600
+ }
601
+ #inputLiteral(value, type) {
602
+ if (typeof value !== "object" || value === null) return void 0;
603
+ const record = value;
604
+ for (const key of Object.keys(record)) if (record[key] !== void 0 && !type.fields.some((field) => field.name === key)) return void 0;
605
+ const fields = [];
606
+ for (const field of type.fields) {
607
+ const fieldValue = Object.hasOwn(record, field.name) ? record[field.name] : void 0;
608
+ const ref = parseTypeRef(field.type);
609
+ if (ref === void 0) return void 0;
610
+ if (fieldValue === void 0) {
611
+ if (ref.nonNull && field.defaultValue === void 0) return void 0;
612
+ continue;
613
+ }
614
+ const literal = this.#literal(fieldValue, ref);
615
+ if (literal === void 0) return void 0;
616
+ fields.push([field.name, literal]);
617
+ }
618
+ return {
619
+ kind: "ObjectValue",
620
+ fields
621
+ };
622
+ }
623
+ };
624
+ /** The `valueToLiteral` of the specified scalars, and graphql-js' default one for the others. */
625
+ function scalarLiteral(value, name) {
626
+ switch (name) {
627
+ case "Int": return (typeof value === "number" && Number.isInteger(value) || typeof value === "bigint") && value <= GRAPHQL_MAX_INT && value >= GRAPHQL_MIN_INT ? {
628
+ kind: "IntValue",
629
+ value: String(value)
630
+ } : void 0;
631
+ case "Float": try {
632
+ const literal = defaultScalarLiteral(value);
633
+ return literal.kind === "FloatValue" || literal.kind === "IntValue" ? literal : void 0;
634
+ } catch {
635
+ return;
636
+ }
637
+ case "String": return typeof value === "string" ? {
638
+ kind: "StringValue",
639
+ value
640
+ } : void 0;
641
+ case "Boolean": return typeof value === "boolean" ? {
642
+ kind: "BooleanValue",
643
+ value
644
+ } : void 0;
645
+ case "ID":
646
+ if (typeof value === "string") return INTEGER_STRING.test(value) ? {
647
+ kind: "IntValue",
648
+ value
649
+ } : {
650
+ kind: "StringValue",
651
+ value
652
+ };
653
+ if (typeof value === "number") return Number.isInteger(value) ? {
654
+ kind: "IntValue",
655
+ value: String(value)
656
+ } : void 0;
657
+ return typeof value === "bigint" ? {
658
+ kind: "IntValue",
659
+ value: String(value)
660
+ } : void 0;
661
+ default: return defaultScalarLiteral(value);
662
+ }
663
+ }
664
+ /** graphql-js `defaultScalarValueToLiteral`. */
665
+ function defaultScalarLiteral(value) {
666
+ if (value == null) return { kind: "NullValue" };
667
+ switch (typeof value) {
668
+ case "boolean": return {
669
+ kind: "BooleanValue",
670
+ value
671
+ };
672
+ case "string": return {
673
+ kind: "StringValue",
674
+ value
675
+ };
676
+ case "bigint": return {
677
+ kind: "IntValue",
678
+ value: value.toString()
679
+ };
680
+ case "number": {
681
+ if (!Number.isFinite(value)) return { kind: "NullValue" };
682
+ const text = String(value);
683
+ return INTEGER_STRING.test(text) ? {
684
+ kind: "IntValue",
685
+ value: text
686
+ } : {
687
+ kind: "FloatValue",
688
+ value: text
689
+ };
690
+ }
691
+ case "object": {
692
+ if (isIterableObject(value)) return {
693
+ kind: "ListValue",
694
+ values: Array.from(value, defaultScalarLiteral)
695
+ };
696
+ const record = value;
697
+ const fields = [];
698
+ for (const key of Object.keys(record)) if (record[key] !== void 0) fields.push([key, defaultScalarLiteral(record[key])]);
699
+ return {
700
+ kind: "ObjectValue",
701
+ fields
702
+ };
703
+ }
704
+ default: throw new TypeError(`Cannot convert value to AST: ${describe(value)}.`);
705
+ }
706
+ }
707
+ function isIterableObject(value) {
708
+ return typeof value === "object" && value !== null && typeof value[Symbol.iterator] === "function";
709
+ }
710
+ /** graphql-js `print()` of a value literal. */
711
+ function printLiteral(literal) {
712
+ switch (literal.kind) {
713
+ case "IntValue":
714
+ case "FloatValue":
715
+ case "EnumValue": return literal.value;
716
+ case "StringValue": return printString(literal.value);
717
+ case "BooleanValue": return literal.value ? "true" : "false";
718
+ case "NullValue": return "null";
719
+ case "ListValue": {
720
+ const values = literal.values.map(printLiteral);
721
+ const line = `[${values.join(", ")}]`;
722
+ return line.length > MAX_LINE_LENGTH ? `[\n${indent(values.join("\n"))}\n]` : line;
723
+ }
724
+ case "ObjectValue": {
725
+ const fields = literal.fields.map(([name, value]) => `${name}: ${printLiteral(value)}`);
726
+ const line = `{ ${fields.join(", ")} }`;
727
+ if (line.length <= MAX_LINE_LENGTH) return line;
728
+ const body = indent(fields.join("\n"));
729
+ return body === "" ? "" : `{\n${body}\n}`;
730
+ }
731
+ }
732
+ }
733
+ /** graphql-js `indent()` of the printer. */
734
+ function indent(text) {
735
+ return text === "" ? "" : ` ${text.replaceAll("\n", "\n ")}`;
736
+ }
737
+ function printBlock(items) {
738
+ return items.length === 0 ? "" : ` {\n${items.join("\n")}\n}`;
739
+ }
740
+ function printDeprecated(reason) {
741
+ if (reason === void 0) return "";
742
+ return reason === "No longer supported" ? " @deprecated" : ` @deprecated(reason: ${printString(reason)})`;
743
+ }
744
+ /** graphql-js `printDescription()` of `printSchema`. */
745
+ function printDescription(description, indentation, firstInBlock) {
746
+ if (description === void 0) return "";
747
+ const text = isPrintableAsBlockString(description) ? printBlockString(description) : printString(description);
748
+ return `${indentation !== "" && !firstInBlock ? `\n${indentation}` : indentation}${text.replaceAll("\n", `\n${indentation}`)}\n`;
749
+ }
750
+ function checkedTypeRef(type, coordinate) {
751
+ if (parseTypeRef(type) === void 0) throw new Error(`Invalid type reference '${type}' (${coordinate})`);
752
+ return type;
753
+ }
754
+ function describe(value) {
755
+ if (value === void 0) return "undefined";
756
+ if (typeof value === "bigint") return `${value}n`;
757
+ if (typeof value === "number" && !Number.isFinite(value)) return String(value);
758
+ try {
759
+ return JSON.stringify(value) ?? String(value);
760
+ } catch {
761
+ return String(value);
762
+ }
763
+ }
764
+ /** `\t` and space: the GraphQL `WhiteSpace` characters. */
765
+ function isWhiteSpace(code) {
766
+ return code === 9 || code === 32;
767
+ }
768
+ /** Escape sequence of each code unit graphql-js escapes in a string value. */
769
+ const ESCAPES = Array.from({ length: 160 }, (_, code) => {
770
+ switch (code) {
771
+ case 8: return "\\b";
772
+ case 9: return "\\t";
773
+ case 10: return "\\n";
774
+ case 12: return "\\f";
775
+ case 13: return "\\r";
776
+ case 34: return "\\\"";
777
+ case 92: return "\\\\";
778
+ default: return code < 32 || code >= 127 ? `\\u${code.toString(16).toUpperCase().padStart(4, "0")}` : "";
779
+ }
780
+ });
781
+ const ESCAPED = /[\x00-\x1f\x22\x5c\x7f-\x9f]/g;
782
+ /** A GraphQL string value (`"..."`), escaped like graphql-js `printString`. */
783
+ function printString(value) {
784
+ return `"${value.replace(ESCAPED, (char) => ESCAPES[char.charCodeAt(0)] ?? char)}"`;
785
+ }
786
+ /** graphql-js `isPrintableAsBlockString`. */
787
+ function isPrintableAsBlockString(value) {
788
+ if (value === "") return true;
789
+ let isEmptyLine = true;
790
+ let hasIndent = false;
791
+ let hasCommonIndent = true;
792
+ let seenNonEmptyLine = false;
793
+ for (let i = 0; i < value.length; ++i) switch (value.codePointAt(i)) {
794
+ case 0:
795
+ case 1:
796
+ case 2:
797
+ case 3:
798
+ case 4:
799
+ case 5:
800
+ case 6:
801
+ case 7:
802
+ case 8:
803
+ case 11:
804
+ case 12:
805
+ case 14:
806
+ case 15:
807
+ case 13: return false;
808
+ case 10:
809
+ if (isEmptyLine && !seenNonEmptyLine) return false;
810
+ seenNonEmptyLine = true;
811
+ isEmptyLine = true;
812
+ hasIndent = false;
813
+ break;
814
+ case 9:
815
+ case 32:
816
+ hasIndent ||= isEmptyLine;
817
+ break;
818
+ default:
819
+ hasCommonIndent &&= hasIndent;
820
+ isEmptyLine = false;
821
+ }
822
+ if (isEmptyLine) return false;
823
+ if (hasCommonIndent && seenNonEmptyLine) return false;
824
+ return true;
825
+ }
826
+ /** A GraphQL block string (`"""..."""`), laid out like graphql-js `printBlockString`. */
827
+ function printBlockString(value) {
828
+ const escaped = value.replaceAll("\"\"\"", "\\\"\"\"");
829
+ const lines = escaped.split(/\r\n|[\n\r]/g);
830
+ const isSingleLine = lines.length === 1;
831
+ const forceLeadingNewLine = lines.length > 1 && lines.slice(1).every((line) => line.length === 0 || isWhiteSpace(line.charCodeAt(0)));
832
+ const hasTrailingTripleQuotes = escaped.endsWith("\\\"\"\"");
833
+ const hasTrailingQuote = value.endsWith("\"") && !hasTrailingTripleQuotes;
834
+ const hasTrailingSlash = value.endsWith("\\");
835
+ const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash;
836
+ const printAsMultipleLines = !isSingleLine || value.length > 70 || forceTrailingNewline || forceLeadingNewLine || hasTrailingTripleQuotes;
837
+ let result = "";
838
+ const skipLeadingNewLine = isSingleLine && isWhiteSpace(value.charCodeAt(0));
839
+ if (printAsMultipleLines && !skipLeadingNewLine || forceLeadingNewLine) result += "\n";
840
+ result += escaped;
841
+ if (printAsMultipleLines || forceTrailingNewline) result += "\n";
842
+ return `"""${result}"""`;
843
+ }
844
+ // src/compiler/defaults.ts
845
+ const GRAPHQL_INT_MAX = 2147483647;
846
+ const GRAPHQL_INT_MIN = -2147483648;
847
+ /** `value` (an internal value) as a GraphQL external value of `ref`; `types` resolves enums and inputs. */
848
+ function externalValue(value, ref, types) {
849
+ if (value === null) return ref.nonNull ? { error: "null for a non-null type" } : { value: null };
850
+ if (value === void 0) return { error: "undefined" };
851
+ if (ref.kind === "list") {
852
+ if (!Array.isArray(value)) return externalValue(value, ref.of, types);
853
+ const items = [];
854
+ for (const item of value) {
855
+ const converted = externalValue(item, ref.of, types);
856
+ if ("error" in converted) return converted;
857
+ items.push(converted.value);
858
+ }
859
+ return { value: items };
860
+ }
861
+ switch (ref.name) {
862
+ case "String": return typeof value === "string" ? { value } : { error: "expected a string" };
863
+ case "ID": return typeof value === "string" || typeof value === "number" && Number.isInteger(value) ? { value } : { error: "expected a string or an integer" };
864
+ case "Int": return typeof value === "number" && Number.isInteger(value) && value <= GRAPHQL_INT_MAX && value >= GRAPHQL_INT_MIN ? { value } : { error: "expected a 32-bit integer" };
865
+ case "Float": return typeof value === "number" && Number.isFinite(value) ? { value } : { error: "expected a finite number" };
866
+ case "Boolean": return typeof value === "boolean" ? { value } : { error: "expected a boolean" };
867
+ case "JSON": return isJson(value) ? { value } : { error: "expected a JSON value" };
868
+ }
869
+ const type = types.get(ref.name);
870
+ if (type?.kind === "enum") {
871
+ const found = type.values.find((entry) => entry.value === value) ?? (typeof value === "string" ? type.values.find((entry) => entry.name === value) : void 0);
872
+ return found === void 0 ? { error: `expected one of ${type.values.map((entry) => entry.name).join(", ")}` } : { value: found.name };
873
+ }
874
+ if (type?.kind === "input") {
875
+ if (typeof value !== "object" || Array.isArray(value)) return { error: `expected an object of type ${type.name}` };
876
+ const record = value;
877
+ for (const key of Object.keys(record)) if (!type.fields.some((field) => field.name === key)) return { error: `${type.name} has no field '${key}'` };
878
+ const result = {};
879
+ for (const field of type.fields) {
880
+ if (!Object.hasOwn(record, field.name) || record[field.name] === void 0) {
881
+ if (field.ref.nonNull && field.defaultValue === void 0) return { error: `${type.name}.${field.name} is required` };
882
+ continue;
883
+ }
884
+ const converted = externalValue(record[field.name], field.ref, types);
885
+ if ("error" in converted) return { error: `${type.name}.${field.name}: ${converted.error}` };
886
+ result[field.name] = converted.value;
887
+ }
888
+ return { value: result };
889
+ }
890
+ return { error: `defaults of the scalar ${ref.name} are not supported` };
891
+ }
892
+ /** A JSON-compatible value (the `JSON` scalar). */
893
+ function isJson(value) {
894
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
895
+ if (typeof value === "number") return Number.isFinite(value);
896
+ if (Array.isArray(value)) return value.every(isJson);
897
+ if (typeof value !== "object") return false;
898
+ return Object.values(value).every(isJson);
899
+ }
900
+ // src/compiler/discriminators.ts
901
+ /**
902
+ * `instanceof` when every member is an exported class (subclasses first), `__typename` when every
903
+ * member declares it, else the first property of the first member whose literal value differs in
904
+ * every member; `undefined` when none applies (ZNIGHT064).
905
+ */
906
+ function discriminatorOf(members, classInfo) {
907
+ if (members.every((member) => member.classIdentity !== void 0 && classInfo(member.classIdentity)?.exported)) {
908
+ const depth = (identity) => classInfo(identity)?.heritage.length ?? 0;
909
+ return {
910
+ by: "class",
911
+ classes: members.map((member) => ({
912
+ identity: member.classIdentity,
913
+ name: member.name
914
+ })).sort((a, b) => depth(b.identity) - depth(a.identity) || compareStrings(a.name, b.name))
915
+ };
916
+ }
917
+ if (members.every((member) => member.properties.some((property) => property.name === "__typename"))) return { by: "typename" };
918
+ for (const candidate of members[0]?.properties ?? []) {
919
+ if (candidate.optional || candidate.literal === void 0) continue;
920
+ const values = literalValues(members, candidate.name);
921
+ if (values !== void 0) return {
922
+ by: "property",
923
+ property: candidate.name,
924
+ values
925
+ };
926
+ }
927
+ }
928
+ /** Literal value → member name when `property` is a required literal with a distinct value in every member. */
929
+ function literalValues(members, property) {
930
+ const values = /* @__PURE__ */ new Map();
931
+ for (const member of members) {
932
+ const found = member.properties.find((entry) => entry.name === property);
933
+ if (found === void 0 || found.optional || found.literal === void 0) return void 0;
934
+ const key = String(found.literal);
935
+ if (values.has(key)) return void 0;
936
+ values.set(key, member.name);
937
+ }
938
+ const sorted = {};
939
+ for (const key of [...values.keys()].sort(compareStrings)) sorted[key] = values.get(key);
940
+ return sorted;
941
+ }
942
+ // src/compiler/docs.ts
943
+ /** The comment text (before the first tag), `undefined` when empty. */
944
+ function descriptionOf(doc) {
945
+ return doc === void 0 || doc.text === "" ? void 0 : doc.text;
946
+ }
947
+ /** The first tag named `name`. */
948
+ function tagOf(doc, name) {
949
+ return doc?.tags.find((tag) => tag.name === name);
950
+ }
951
+ /** `@deprecated reason`: the reason (graphql-js' default one without text), `undefined` without the tag. */
952
+ function deprecationOf(doc) {
953
+ const tag = tagOf(doc, "deprecated");
954
+ if (tag === void 0) return void 0;
955
+ const reason = tag.text.trim();
956
+ return reason === "" ? DEFAULT_DEPRECATION_REASON : reason;
957
+ }
958
+ /** `true` with a `@gqlHidden` tag. */
959
+ function isHidden(doc) {
960
+ return tagOf(doc, "gqlHidden") !== void 0;
961
+ }
962
+ /**
963
+ * The text of `@param name text` (also `@param {Type} name - text`), `undefined` when there is no
964
+ * such tag or it has no text.
965
+ */
966
+ function paramDescription(doc, name) {
967
+ for (const tag of doc?.tags ?? []) {
968
+ if (tag.name !== "param") continue;
969
+ const match = /^(?:\{[^}]*\}\s*)?\[?([\w$]+)(?:=[^\]]*)?\]?(?:\s+-)?(?:\s+([\s\S]*))?$/.exec(tag.text.trim());
970
+ if (match?.[1] !== name) continue;
971
+ const text = match[2]?.trim();
972
+ return text === void 0 || text === "" ? void 0 : text;
973
+ }
974
+ }
975
+ /** A `@default` value: JSON when it parses, the text otherwise (`@default title`). */
976
+ function defaultTagValue(tag) {
977
+ const text = tag.text.trim();
978
+ try {
979
+ return JSON.parse(text);
980
+ } catch {
981
+ return text;
982
+ }
983
+ }
984
+ // src/compiler/locate.ts
985
+ /** From the member name: `name?: ` or `name(): ` (a getter), up to the annotation. */
986
+ const MEMBER_HEAD = /^(?:[\w$]+|'[^']*'|"[^"]*")\s*\??\s*(?:\(\s*\))?\s*:\s*/;
987
+ const OPENING = /* @__PURE__ */ new Set([
988
+ "(",
989
+ "[",
990
+ "{",
991
+ "<"
992
+ ]);
993
+ const CLOSING = /* @__PURE__ */ new Set([
994
+ ")",
995
+ "]",
996
+ "}",
997
+ ">"
998
+ ]);
999
+ /**
1000
+ * The type annotation of a property, a property signature or a getter (`get x(): T`), from the
1001
+ * location of the member (its name); the member itself when the annotation cannot be found.
1002
+ */
1003
+ function annotationLocation(project, member) {
1004
+ if (member === void 0) return void 0;
1005
+ const file = project.getFile(member.file);
1006
+ if (file === void 0) return member;
1007
+ const text = file.text;
1008
+ const head = MEMBER_HEAD.exec(text.slice(member.start, member.start + 256));
1009
+ if (head === null) return member;
1010
+ const start = member.start + head[0].length;
1011
+ let depth = 0;
1012
+ let end = start;
1013
+ for (let index = start; index < text.length; index++) {
1014
+ const char = text[index];
1015
+ if (char === "=" && text[index + 1] === ">") {
1016
+ index++;
1017
+ continue;
1018
+ }
1019
+ if (depth === 0 && end > start && (char === "{" || char === "=")) break;
1020
+ if (OPENING.has(char)) depth++;
1021
+ else if (CLOSING.has(char)) {
1022
+ if (depth === 0) break;
1023
+ depth--;
1024
+ } else if (depth === 0 && (char === ";" || char === ",")) break;
1025
+ else if (depth === 0 && char === "\n" && !/^\s*[|&]/.test(text.slice(index + 1, index + 64))) break;
1026
+ if (!/\s/.test(char)) end = index + 1;
1027
+ }
1028
+ return end > start ? file.location({
1029
+ start,
1030
+ end
1031
+ }) : member;
1032
+ }
1033
+ // src/compiler/scalars.ts
1034
+ /** Valid declarations by the identity of their type; invalid ones are reported. */
1035
+ function readScalars(ctx, report) {
1036
+ const byType = /* @__PURE__ */ new Map();
1037
+ const byName = /* @__PURE__ */ new Map();
1038
+ for (const definition of ctx.definitionsOf(GraphQLIds.scalar)) {
1039
+ const fail = (message, hints, related = []) => report({
1040
+ code: Codes.InvalidDecorator,
1041
+ severity: "error",
1042
+ message,
1043
+ location: definition.call,
1044
+ hints,
1045
+ related
1046
+ });
1047
+ const [nameArg, definitionArg] = definition.args;
1048
+ const name = nameArg?.evaluated === true ? nameArg.value : void 0;
1049
+ if (typeof name !== "string") {
1050
+ fail(`scalar() of ${definition.name} needs a static name`, [`scalar<T>('Name', { ... })`]);
1051
+ continue;
1052
+ }
1053
+ if (!isGraphQLName(name) || SPECIFIED_SCALARS.has(name)) {
1054
+ report({
1055
+ code: Codes.NameConflict,
1056
+ severity: "error",
1057
+ message: SPECIFIED_SCALARS.has(name) ? `'${name}' is a specified GraphQL scalar: scalar() cannot redefine it (${definition.name})` : `'${name}' is not a valid GraphQL scalar name (${definition.name})`,
1058
+ location: nameArg?.location ?? definition.call,
1059
+ hints: ["GraphQL names match /^[_A-Za-z][_0-9A-Za-z]*$/ and do not start with __"]
1060
+ });
1061
+ continue;
1062
+ }
1063
+ const type = definition.typeArgIdentities?.[0];
1064
+ if (type === void 0) {
1065
+ report({
1066
+ code: Codes.InvalidType,
1067
+ severity: "error",
1068
+ message: `scalar('${name}') of ${definition.name} needs a named type argument: scalar<T>('${name}', ...)`,
1069
+ location: definition.call,
1070
+ hints: [`Name the TypeScript type of the scalar: export type ${name} = string & { readonly __brand: '${name}' }, then scalar<${name}>('${name}', ...)`]
1071
+ });
1072
+ continue;
1073
+ }
1074
+ if (SCALAR_ALIASES.has(type)) {
1075
+ fail(`scalar('${name}') of ${definition.name} cannot map ${type.slice(type.indexOf("#") + 1)}: it is a built-in scalar alias`, ["Declare a branded type for the scalar: export type Name = string & { readonly __brand: \"Name\" }"]);
1076
+ continue;
1077
+ }
1078
+ if (!definition.exported) {
1079
+ fail(`The scalar ${definition.name} must be exported: the generated module imports it`, [`export const ${definition.name} = scalar<...>('${name}', ...)`]);
1080
+ continue;
1081
+ }
1082
+ const declaration = {
1083
+ name,
1084
+ identity: definition.identity,
1085
+ type,
1086
+ description: staticProperty(ctx, definitionArg, "description"),
1087
+ specifiedByURL: staticProperty(ctx, definitionArg, "specifiedByURL"),
1088
+ location: definition.location
1089
+ };
1090
+ const sameType = byType.get(type);
1091
+ if (sameType !== void 0) {
1092
+ report({
1093
+ code: Codes.NameConflict,
1094
+ severity: "error",
1095
+ message: `${definition.name} and ${sameType.identity} both map ${type.slice(type.indexOf("#") + 1)} to a scalar`,
1096
+ location: definition.location,
1097
+ related: [{
1098
+ message: "the other scalar",
1099
+ location: sameType.location
1100
+ }],
1101
+ hints: ["Keep one scalar per TypeScript type"]
1102
+ });
1103
+ continue;
1104
+ }
1105
+ const sameName = byName.get(name);
1106
+ if (sameName !== void 0) {
1107
+ report({
1108
+ code: Codes.NameConflict,
1109
+ severity: "error",
1110
+ message: `Two scalars are named '${name}': ${definition.identity} and ${sameName.identity}`,
1111
+ location: definition.location,
1112
+ related: [{
1113
+ message: "the other scalar",
1114
+ location: sameName.location
1115
+ }],
1116
+ hints: ["Rename one of them"]
1117
+ });
1118
+ continue;
1119
+ }
1120
+ byType.set(type, declaration);
1121
+ byName.set(name, declaration);
1122
+ }
1123
+ return byType;
1124
+ }
1125
+ /** A string property of an object literal argument, when statically evaluable. */
1126
+ function staticProperty(ctx, arg, key) {
1127
+ if (arg === void 0) return void 0;
1128
+ if (arg.evaluated && typeof arg.value === "object" && arg.value !== null && !Array.isArray(arg.value)) {
1129
+ const value = arg.value[key];
1130
+ return typeof value === "string" ? value : void 0;
1131
+ }
1132
+ const node = arg.node;
1133
+ if (node.type !== "ObjectExpression") return void 0;
1134
+ for (const property of node.properties) {
1135
+ if (property.type !== "Property" || property.computed) continue;
1136
+ if ((property.key.type === "Identifier" ? property.key.name : void 0) !== key) continue;
1137
+ const result = ctx.project.evaluate(arg.location.file, property.value, { refs: "none" });
1138
+ return result.kind === "value" && typeof result.value === "string" ? result.value : void 0;
1139
+ }
1140
+ }
1141
+ // src/compiler/sdl-view.ts
1142
+ /** The SDL view of a model type. */
1143
+ function sdlType(model) {
1144
+ const base = model.description === void 0 ? {} : { description: model.description };
1145
+ switch (model.kind) {
1146
+ case "object": return {
1147
+ kind: "object",
1148
+ name: model.name,
1149
+ ...base,
1150
+ fields: model.fields.map((field) => ({
1151
+ name: field.name,
1152
+ type: field.type,
1153
+ ...field.description === void 0 ? {} : { description: field.description },
1154
+ ...field.deprecationReason === void 0 ? {} : { deprecationReason: field.deprecationReason },
1155
+ ...field.args.length === 0 ? {} : { args: field.args.map(sdlInputValue) }
1156
+ }))
1157
+ };
1158
+ case "input": return {
1159
+ kind: "input",
1160
+ name: model.name,
1161
+ ...base,
1162
+ fields: model.fields.map(sdlInputValue)
1163
+ };
1164
+ case "enum": return {
1165
+ kind: "enum",
1166
+ name: model.name,
1167
+ ...base,
1168
+ values: model.values.map((value) => ({
1169
+ name: value.name,
1170
+ ...value.description === void 0 ? {} : { description: value.description },
1171
+ ...value.deprecationReason === void 0 ? {} : { deprecationReason: value.deprecationReason }
1172
+ }))
1173
+ };
1174
+ case "union": return {
1175
+ kind: "union",
1176
+ name: model.name,
1177
+ ...base,
1178
+ members: model.members
1179
+ };
1180
+ case "scalar": return {
1181
+ kind: "scalar",
1182
+ name: model.name,
1183
+ ...base,
1184
+ ...model.definition === void 0 ? { builtin: true } : {},
1185
+ ...model.specifiedByURL === void 0 ? {} : { specifiedByURL: model.specifiedByURL }
1186
+ };
1187
+ }
1188
+ }
1189
+ function sdlInputValue(arg) {
1190
+ return {
1191
+ name: arg.name,
1192
+ type: arg.type,
1193
+ ...arg.description === void 0 ? {} : { description: arg.description },
1194
+ ...arg.deprecationReason === void 0 ? {} : { deprecationReason: arg.deprecationReason },
1195
+ ...arg.defaultValue === void 0 ? {} : { defaultValue: arg.defaultValue }
1196
+ };
1197
+ }
1198
+ // src/compiler/builder.ts
1199
+ const NAME_HINT = "GraphQL names match /^[_A-Za-z][_0-9A-Za-z]*$/ and do not start with __";
1200
+ const RECORD_HINT = "GraphQL objects have fixed fields: declare an interface, or use JSONValue (import type { JSONValue } from '@znight/graphql')";
1201
+ const ROOT_NAMES = new Set(Object.values(ROOT_TYPE_NAMES));
1202
+ /** Builds the model; `undefined` when the application has no resolver. */
1203
+ function buildModel(ctx, options) {
1204
+ const resolvers = [...ctx.stored].sort((a, b) => compareStrings(a.host.identity, b.host.identity));
1205
+ if (resolvers.length === 0) return void 0;
1206
+ return new SchemaBuilder(ctx, options).build(resolvers);
1207
+ }
1208
+ var SchemaBuilder = class {
1209
+ #ctx;
1210
+ #number;
1211
+ #shapeOptions;
1212
+ /** `scalar<T>()` declarations by the identity of `T`. */
1213
+ #scalars;
1214
+ /** Every named shape seen, by key. */
1215
+ #named = /* @__PURE__ */ new Map();
1216
+ /** Models by GraphQL name (the first claimant). */
1217
+ #types = /* @__PURE__ */ new Map();
1218
+ /** Models by declaration key. */
1219
+ #models = /* @__PURE__ */ new Map();
1220
+ /** GraphQL names by declaration key. */
1221
+ #names = /* @__PURE__ */ new Map();
1222
+ #positions = /* @__PURE__ */ new Map();
1223
+ #reported = /* @__PURE__ */ new Set();
1224
+ #fieldResolvers = /* @__PURE__ */ new Map();
1225
+ #defaults = [];
1226
+ #methods = /* @__PURE__ */ new Map();
1227
+ #errors = 0;
1228
+ constructor(ctx, options) {
1229
+ this.#ctx = ctx;
1230
+ this.#number = options.number;
1231
+ const declarations = readScalars(ctx, (diagnostic) => this.#report(diagnostic));
1232
+ this.#scalars = declarations;
1233
+ const keep = [.../* @__PURE__ */ new Set([...BASE_KEEP, ...declarations.keys()])].sort(compareStrings);
1234
+ this.#shapeOptions = Object.freeze({
1235
+ keep: Object.freeze(keep),
1236
+ members: "instance",
1237
+ jsdoc: true
1238
+ });
1239
+ }
1240
+ build(resolvers) {
1241
+ this.#checkLoaders(resolvers);
1242
+ this.#indexFieldResolvers(resolvers);
1243
+ const roots = /* @__PURE__ */ new Map();
1244
+ const rootFields = /* @__PURE__ */ new Map();
1245
+ let hasQuery = false;
1246
+ for (const resolver of resolvers) for (const field of resolver.fields) {
1247
+ if (field.operation === "field") continue;
1248
+ if (field.operation === "query") hasQuery = true;
1249
+ if (!field.complete) continue;
1250
+ const method = this.#method(resolver, field);
1251
+ if (method === void 0) continue;
1252
+ const root = this.#rootModel(roots, field.operation);
1253
+ const coordinate = `${root.name}.${field.name}`;
1254
+ const previous = rootFields.get(coordinate);
1255
+ if (previous !== void 0) {
1256
+ this.#report({
1257
+ code: Codes.NameConflict,
1258
+ severity: "error",
1259
+ message: `Two root fields are named ${coordinate}: ${resolver.host.displayName}.${field.method} and ${previous.resolver.host.displayName}.${previous.field.method}`,
1260
+ location: field.location,
1261
+ related: [{
1262
+ message: "the other field",
1263
+ location: previous.field.location
1264
+ }],
1265
+ hints: [`Rename one of them: @${decoratorName(field.operation)}('otherName')`]
1266
+ });
1267
+ continue;
1268
+ }
1269
+ rootFields.set(coordinate, {
1270
+ field,
1271
+ resolver
1272
+ });
1273
+ root.fields.push(this.#resolverField(root, resolver, field, method));
1274
+ }
1275
+ if (!hasQuery) {
1276
+ const first = resolvers[0];
1277
+ this.#report({
1278
+ code: Codes.InvalidResolver,
1279
+ severity: "error",
1280
+ message: "The application has GraphQL resolvers but no @Query field: GraphQL requires a query root type",
1281
+ location: first.location,
1282
+ hints: [`Add a @Query() method to a resolver (${first.host.displayName}, for instance)`]
1283
+ });
1284
+ }
1285
+ this.#reportUnreachableFieldResolvers();
1286
+ this.#checkDefaults();
1287
+ this.#checkInputCycles();
1288
+ this.#checkDecisions(resolvers);
1289
+ if (this.#errors > 0 || !hasQuery) return void 0;
1290
+ return this.#assemble(roots, resolvers);
1291
+ }
1292
+ #report(diagnostic) {
1293
+ if (diagnostic.severity === "error") this.#errors++;
1294
+ this.#ctx.report(diagnostic);
1295
+ }
1296
+ /** Reports once per `key`. */
1297
+ #reportOnce(key, diagnostic) {
1298
+ if (this.#reported.has(key)) return;
1299
+ this.#reported.add(key);
1300
+ this.#report(diagnostic);
1301
+ }
1302
+ #fail(code, use, message, hints) {
1303
+ const location = use.locate();
1304
+ this.#report({
1305
+ code,
1306
+ severity: "error",
1307
+ message,
1308
+ ...location === void 0 ? {} : { location },
1309
+ ...hints.length === 0 ? {} : { hints },
1310
+ related: reachedFrom(use)
1311
+ });
1312
+ }
1313
+ #method(resolver, field) {
1314
+ const key = `${resolver.host.identity}#${field.method}`;
1315
+ if (!this.#methods.has(key)) {
1316
+ const cls = this.#ctx.classInfo(resolver.host.identity);
1317
+ this.#methods.set(key, cls?.methods.find((method) => method.name === field.method && method.kind === "method"));
1318
+ }
1319
+ return this.#methods.get(key);
1320
+ }
1321
+ #shape(target) {
1322
+ const result = this.#ctx.types.shape(target, this.#shapeOptions);
1323
+ for (const named of result.named.values()) this.#named.set(named.key, named);
1324
+ return result;
1325
+ }
1326
+ #rootModel(roots, operation) {
1327
+ let root = roots.get(operation);
1328
+ if (root === void 0) {
1329
+ const name = ROOT_TYPE_NAMES[operation];
1330
+ root = {
1331
+ kind: "object",
1332
+ name,
1333
+ key: `#root:${operation}`,
1334
+ description: void 0,
1335
+ location: void 0,
1336
+ fields: [],
1337
+ trail: name,
1338
+ root: void 0,
1339
+ classIdentity: void 0,
1340
+ properties: []
1341
+ };
1342
+ roots.set(operation, root);
1343
+ this.#claim(root, void 0);
1344
+ }
1345
+ return root;
1346
+ }
1347
+ /** A field backed by a resolver method (root field or field resolver). */
1348
+ #resolverField(owner, resolver, field, method) {
1349
+ const coordinate = `${owner.name}.${field.name}`;
1350
+ const isRoot = field.operation !== "field";
1351
+ const use = {
1352
+ position: "output",
1353
+ coordinate,
1354
+ trail: isRoot ? coordinate : `${owner.trail}.${field.name}`,
1355
+ reached: isRoot ? void 0 : owner.trail,
1356
+ root: isRoot ? method.location : owner.root,
1357
+ locate: () => method.location
1358
+ };
1359
+ const type = this.#returnType(resolver, field, method, use);
1360
+ return {
1361
+ name: field.name,
1362
+ type: type === void 0 ? "String" : printTypeRef(type.ref),
1363
+ description: descriptionOf(method.doc),
1364
+ deprecationReason: deprecationOf(method.doc),
1365
+ args: this.#arguments(field, method, use),
1366
+ binding: {
1367
+ resolver,
1368
+ field
1369
+ },
1370
+ location: field.location
1371
+ };
1372
+ }
1373
+ #returnType(resolver, field, method, use) {
1374
+ const where = `${resolver.host.displayName}.${field.method}`;
1375
+ if (method.returnType === void 0) return this.#fail(Codes.InvalidType, use, `${where} has no return type annotation (${use.coordinate})`, [`Annotate the return type: the schema is derived from it (${field.method}(...): Promise<Book>)`]);
1376
+ const result = this.#shape({ returnOf: method });
1377
+ const rootIssue = result.issues.find((issue) => issue.named === void 0);
1378
+ const located = {
1379
+ ...use,
1380
+ locate: () => rootIssue?.location ?? method.location
1381
+ };
1382
+ const root = result.root;
1383
+ const iterable = root.kind === "reference" && ASYNC_ITERABLES.has(root.identity) ? root : void 0;
1384
+ if (field.operation === "subscription") {
1385
+ if (iterable === void 0) {
1386
+ this.#report({
1387
+ code: Codes.InvalidResolver,
1388
+ severity: "error",
1389
+ message: `@Subscription ${where} must return an async iterable, not ${describeShape(root)}`,
1390
+ location: method.location,
1391
+ hints: [`Declare it as an async generator (async *${field.method}(): AsyncGenerator<Event>) or return pubsub.subscribe(...) (AsyncIterable<Event>)`]
1392
+ });
1393
+ return;
1394
+ }
1395
+ const item = iterable.typeArgs[0];
1396
+ if (item === void 0) return this.#fail(Codes.InvalidType, located, `${where} must declare the type of its events (${use.coordinate})`, ["AsyncIterable<Event>"]);
1397
+ return this.#convert(item, false, located);
1398
+ }
1399
+ if (iterable !== void 0) return this.#fail(Codes.InvalidType, located, `${where} returns an async iterable: only @Subscription fields stream values (${use.coordinate})`, ["Use @Subscription() for a stream of events, or return a list (Promise<readonly Book[]>)"]);
1400
+ if (root.kind === "undefined") return this.#fail(Codes.InvalidType, located, `${where} returns void: GraphQL fields must return a value (${use.coordinate})`, ["Return a payload type (the changed object) or a boolean"]);
1401
+ return this.#convert(root, false, located);
1402
+ }
1403
+ /** Arguments of a resolver field: `@Args('name')` parameters and the properties of `@Args()` types. */
1404
+ #arguments(field, method, owner) {
1405
+ const args = [];
1406
+ const seen = /* @__PURE__ */ new Map();
1407
+ const add = (arg, location) => {
1408
+ if (seen.has(arg.name)) {
1409
+ const first = seen.get(arg.name);
1410
+ this.#report({
1411
+ code: Codes.NameConflict,
1412
+ severity: "error",
1413
+ message: `Argument '${arg.name}' of ${owner.coordinate} is declared twice`,
1414
+ ...location === void 0 ? {} : { location },
1415
+ ...first === void 0 ? {} : { related: [{
1416
+ message: "first declared here",
1417
+ location: first
1418
+ }] },
1419
+ hints: ["Argument names must be unique: rename one of them"]
1420
+ });
1421
+ return;
1422
+ }
1423
+ seen.set(arg.name, location);
1424
+ args.push(arg);
1425
+ };
1426
+ field.params.forEach((data, index) => {
1427
+ if (data?.kind !== "args") return;
1428
+ const param = method.params[index];
1429
+ const result = this.#shape({ parameter: param });
1430
+ if (data.name !== void 0) {
1431
+ const use = {
1432
+ position: "input",
1433
+ coordinate: `${owner.coordinate}(${data.name}:)`,
1434
+ trail: `${owner.trail}(${data.name})`,
1435
+ reached: owner.reached,
1436
+ root: owner.root,
1437
+ locate: () => param.typeLocation
1438
+ };
1439
+ const arg = this.#parameterArgument(data.name, param, method, result, use);
1440
+ if (arg !== void 0) add(arg, param.location);
1441
+ return;
1442
+ }
1443
+ const properties = this.#propertiesOf(result.root);
1444
+ if (properties === "record") {
1445
+ this.#fail(Codes.InvalidType, {
1446
+ ...owner,
1447
+ locate: () => param.typeLocation
1448
+ }, `@Args() parameter '${param.name}' of ${owner.coordinate} cannot be a record or an index signature: GraphQL arguments are fixed`, [RECORD_HINT, `@Args('${param.name}') declares one argument named '${param.name}'`]);
1449
+ return;
1450
+ }
1451
+ if (properties === void 0) {
1452
+ this.#fail(Codes.InvalidType, {
1453
+ ...owner,
1454
+ locate: () => param.typeLocation
1455
+ }, `@Args() parameter '${param.name}' of ${owner.coordinate} must have an object type: its properties are the arguments`, [`@Args('${param.name}') declares one argument named '${param.name}'`]);
1456
+ return;
1457
+ }
1458
+ for (const property of properties) {
1459
+ if (isHidden(property.doc)) continue;
1460
+ const use = {
1461
+ position: "input",
1462
+ coordinate: `${owner.coordinate}(${property.name}:)`,
1463
+ trail: `${owner.trail}(${property.name})`,
1464
+ reached: owner.reached,
1465
+ root: owner.root,
1466
+ locate: () => annotationLocation(this.#ctx.project, property.location) ?? param.typeLocation
1467
+ };
1468
+ const arg = this.#inputValue(property, use);
1469
+ if (arg !== void 0) add(arg, property.location ?? param.location);
1470
+ }
1471
+ });
1472
+ return args;
1473
+ }
1474
+ /** `@Args('limit') limit: Int = 20`. */
1475
+ #parameterArgument(name, param, method, result, use) {
1476
+ if (!isGraphQLName(name)) {
1477
+ this.#fail(Codes.NameConflict, use, `'${name}' is not a valid GraphQL argument name (${use.coordinate})`, [NAME_HINT]);
1478
+ return;
1479
+ }
1480
+ const converted = this.#convert(result.root, param.optional, use);
1481
+ if (converted === void 0) return void 0;
1482
+ let ref = converted.ref;
1483
+ const arg = {
1484
+ name,
1485
+ type: "",
1486
+ ref,
1487
+ description: descriptionOf(param.doc) ?? paramDescription(method.doc, param.name),
1488
+ deprecationReason: deprecationOf(param.doc),
1489
+ defaultValue: void 0,
1490
+ nullAsUndefined: false,
1491
+ location: param.location
1492
+ };
1493
+ const initializer = param.initializer;
1494
+ let hasDefault = false;
1495
+ if (param.hasDefault) {
1496
+ if (initializer?.evaluated === true && initializer.ref === void 0 && !containsRef(initializer.value)) {
1497
+ this.#defaults.push({
1498
+ target: arg,
1499
+ value: initializer.value,
1500
+ use,
1501
+ location: initializer.location
1502
+ });
1503
+ hasDefault = true;
1504
+ } else ref = {
1505
+ ...ref,
1506
+ nonNull: false
1507
+ };
1508
+ }
1509
+ arg.ref = ref;
1510
+ arg.type = printTypeRef(ref);
1511
+ arg.nullAsUndefined = !ref.nonNull && !converted.acceptsNull;
1512
+ this.#checkDeprecatedInput(arg, hasDefault, use);
1513
+ return arg;
1514
+ }
1515
+ /** A property as an argument or an input field (§6.3): `@default`, `@deprecated`, null handling. */
1516
+ #inputValue(property, use) {
1517
+ if (!isGraphQLName(property.name)) {
1518
+ this.#fail(Codes.NameConflict, {
1519
+ ...use,
1520
+ locate: () => property.location
1521
+ }, `'${property.name}' is not a valid GraphQL name (${use.coordinate})`, [NAME_HINT, "Hide the property with /** @gqlHidden */"]);
1522
+ return;
1523
+ }
1524
+ if (property.kind === "getter") {
1525
+ this.#fail(Codes.InvalidInput, use, `${use.coordinate} is a getter: input values are plain data`, ["Declare a property instead, or hide the getter with /** @gqlHidden */"]);
1526
+ return;
1527
+ }
1528
+ const converted = this.#convert(property.shape, property.optional, use);
1529
+ if (converted === void 0) return void 0;
1530
+ const arg = {
1531
+ name: property.name,
1532
+ type: printTypeRef(converted.ref),
1533
+ ref: converted.ref,
1534
+ description: descriptionOf(property.doc),
1535
+ deprecationReason: deprecationOf(property.doc),
1536
+ defaultValue: void 0,
1537
+ nullAsUndefined: !converted.ref.nonNull && !converted.acceptsNull,
1538
+ location: property.location
1539
+ };
1540
+ const tag = tagOf(property.doc, "default");
1541
+ if (tag !== void 0) this.#defaults.push({
1542
+ target: arg,
1543
+ value: defaultTagValue(tag),
1544
+ use,
1545
+ location: tag.location
1546
+ });
1547
+ this.#checkDeprecatedInput(arg, tag !== void 0, use);
1548
+ return arg;
1549
+ }
1550
+ /** graphql-js rejects a deprecated argument or input field that is required. */
1551
+ #checkDeprecatedInput(arg, hasDefault, use) {
1552
+ if (arg.deprecationReason === void 0 || !arg.ref.nonNull || hasDefault) return;
1553
+ this.#fail(Codes.InvalidInput, use, `${use.coordinate} is required and cannot be deprecated`, ["Make it optional (?: T or T | undefined) or give it a default value before deprecating it"]);
1554
+ }
1555
+ /** `Loader<L>`: `L` must be a loader provider, implementing `BatchLoad<K, V>` (ZNIGHT065). */
1556
+ #checkLoaders(resolvers) {
1557
+ const seen = /* @__PURE__ */ new Set();
1558
+ for (const resolver of resolvers) for (const field of resolver.fields) for (const param of field.params) {
1559
+ if (param?.kind !== "loader" || seen.has(param.binding.id)) continue;
1560
+ seen.add(param.binding.id);
1561
+ const token = tokenOfRef(this.#ctx.binding(param.binding));
1562
+ const provider = token === void 0 ? void 0 : this.#ctx.provider(token);
1563
+ if (provider === void 0 || provider.heritage.some((type) => type.identity === GraphQLIds.BatchLoad)) continue;
1564
+ if (provider.kind !== "class" || hasLoadMethod(this.#ctx, provider.classIdentity)) continue;
1565
+ this.#report({
1566
+ code: Codes.InvalidLoader,
1567
+ severity: "error",
1568
+ message: `${provider.displayName} is not a loader: Loader<${provider.displayName}> needs a provider implementing BatchLoad<K, V> (${resolver.host.displayName}.${field.method})`,
1569
+ location: param.location,
1570
+ hints: [`export class ${provider.displayName} implements BatchLoad<ID, Value> { async load(keys: readonly ID[]): Promise<readonly (Value | Error)[]> { ... } }`]
1571
+ });
1572
+ }
1573
+ }
1574
+ #indexFieldResolvers(resolvers) {
1575
+ for (const resolver of resolvers) for (const field of resolver.fields) {
1576
+ if (field.operation !== "field" || !field.complete) continue;
1577
+ const method = this.#method(resolver, field);
1578
+ if (method === void 0) continue;
1579
+ const index = field.params.findIndex((param) => param?.kind === "parent");
1580
+ const param = method.params[index];
1581
+ if (param === void 0) continue;
1582
+ const result = this.#shape({ parameter: param });
1583
+ const key = this.#objectKeyOf(result.root);
1584
+ if (key === void 0) {
1585
+ this.#report({
1586
+ code: Codes.InvalidResolver,
1587
+ severity: "error",
1588
+ message: `The @Parent() parameter '${param.name}' of ${resolver.host.displayName}.${field.method} must have an object type, not ${describeShape(result.root)}`,
1589
+ location: param.typeLocation,
1590
+ hints: ["The parent type is the object type the field is added to: an interface, a class or a named alias of an object type"]
1591
+ });
1592
+ continue;
1593
+ }
1594
+ let list = this.#fieldResolvers.get(key);
1595
+ if (list === void 0) {
1596
+ list = [];
1597
+ this.#fieldResolvers.set(key, list);
1598
+ }
1599
+ list.push({
1600
+ resolver,
1601
+ field,
1602
+ method,
1603
+ attached: false
1604
+ });
1605
+ }
1606
+ for (const list of this.#fieldResolvers.values()) list.sort((a, b) => compareStrings(a.resolver.host.identity, b.resolver.host.identity) || a.field.location.start - b.field.location.start);
1607
+ }
1608
+ #attachFieldResolvers(model) {
1609
+ const pending = this.#fieldResolvers.get(model.key);
1610
+ if (pending === void 0) return;
1611
+ for (const entry of pending) {
1612
+ entry.attached = true;
1613
+ const field = this.#resolverField(model, entry.resolver, entry.field, entry.method);
1614
+ const index = model.fields.findIndex((existing) => existing.name === field.name);
1615
+ if (index === -1) {
1616
+ model.fields.push(field);
1617
+ continue;
1618
+ }
1619
+ const existing = model.fields[index];
1620
+ const where = `${entry.resolver.host.displayName}.${entry.field.method}`;
1621
+ if (existing.binding !== void 0) {
1622
+ this.#report({
1623
+ code: Codes.NameConflict,
1624
+ severity: "error",
1625
+ message: `Two field resolvers add ${model.name}.${field.name}: ${where} and ${existing.binding.resolver.host.displayName}.${existing.binding.field.method}`,
1626
+ location: entry.field.location,
1627
+ related: [{
1628
+ message: "the other field resolver",
1629
+ location: existing.binding.field.location
1630
+ }],
1631
+ hints: ["Keep one of them, or rename one: @ResolveField('otherName')"]
1632
+ });
1633
+ continue;
1634
+ }
1635
+ if (existing.type !== field.type) {
1636
+ this.#report({
1637
+ code: Codes.NameConflict,
1638
+ severity: "error",
1639
+ message: `@ResolveField ${where} returns ${field.type}, but the property ${model.name}.${field.name} is ${existing.type}`,
1640
+ location: entry.field.location,
1641
+ ...existing.location === void 0 ? {} : { related: [{
1642
+ message: "the property",
1643
+ location: existing.location
1644
+ }] },
1645
+ hints: ["A field resolver replacing a property must resolve the same GraphQL type: change its return type, or rename the field"]
1646
+ });
1647
+ continue;
1648
+ }
1649
+ model.fields[index] = {
1650
+ ...field,
1651
+ description: field.description ?? existing.description,
1652
+ deprecationReason: field.deprecationReason ?? existing.deprecationReason
1653
+ };
1654
+ }
1655
+ }
1656
+ #reportUnreachableFieldResolvers() {
1657
+ for (const [key, list] of this.#fieldResolvers) for (const entry of list) {
1658
+ if (entry.attached) continue;
1659
+ const name = this.#named.get(key)?.name ?? key;
1660
+ this.#report({
1661
+ code: Codes.InvalidResolver,
1662
+ severity: "warning",
1663
+ message: `@ResolveField ${entry.resolver.host.displayName}.${entry.field.method} adds a field to ${name}, which no root field reaches as an output type: it is not part of the schema`,
1664
+ location: entry.field.location,
1665
+ hints: [`Return ${name} from a @Query (or another reachable field), or remove the field resolver`]
1666
+ });
1667
+ }
1668
+ }
1669
+ /**
1670
+ * The GraphQL type of a shape: `null`, `undefined` and `optional` make it nullable, everything
1671
+ * else is non-null (§6.2).
1672
+ */
1673
+ #convert(shape, optional, use) {
1674
+ let nullable = optional;
1675
+ let acceptsNull = false;
1676
+ let inner = shape;
1677
+ if (shape.kind === "union") {
1678
+ const rest = shape.members.filter((member) => member.kind !== "null" && member.kind !== "undefined");
1679
+ if (rest.length !== shape.members.length) {
1680
+ nullable = true;
1681
+ acceptsNull = shape.members.some((member) => member.kind === "null");
1682
+ }
1683
+ if (rest.length === 0) return this.#fail(Codes.InvalidType, use, `${use.coordinate} is always null or undefined`, ["Declare the type of the value"]);
1684
+ inner = rest.length === 1 ? rest[0] : {
1685
+ kind: "union",
1686
+ members: rest
1687
+ };
1688
+ }
1689
+ const converted = this.#inner(inner, use);
1690
+ if (converted === void 0) return void 0;
1691
+ const isNullable = nullable || converted.nullable;
1692
+ return {
1693
+ ref: {
1694
+ ...converted.ref,
1695
+ nonNull: !isNullable
1696
+ },
1697
+ acceptsNull: acceptsNull || converted.nullable
1698
+ };
1699
+ }
1700
+ #inner(shape, use) {
1701
+ switch (shape.kind) {
1702
+ case "string": return refTo("String");
1703
+ case "number": return refTo(this.#number);
1704
+ case "boolean": return refTo("Boolean");
1705
+ case "literal":
1706
+ if (typeof shape.value === "string") return refTo("String");
1707
+ return refTo(typeof shape.value === "number" ? this.#number : "Boolean");
1708
+ case "date": return this.#builtin("DateTime", use);
1709
+ case "bigint": return this.#builtin("BigInt", use);
1710
+ case "array": {
1711
+ const item = this.#convert(shape.items, false, use);
1712
+ return item === void 0 ? void 0 : {
1713
+ ref: {
1714
+ kind: "list",
1715
+ of: item.ref,
1716
+ nonNull: false
1717
+ },
1718
+ nullable: false
1719
+ };
1720
+ }
1721
+ case "named": return this.#namedType(shape.key, use);
1722
+ case "reference": return this.#reference(shape, use);
1723
+ case "url": return this.#fail(Codes.InvalidType, use, `Cannot map 'URL' to a GraphQL type (${use.coordinate})`, ["Expose a string (url.href), or declare a scalar: export const UrlScalar = scalar<URL>('URL', { ... })"]);
1724
+ case "binary": return this.#fail(Codes.InvalidType, use, `Cannot map binary data to a GraphQL type (${use.coordinate})`, ["Expose a URL (coverUrl: string), hide the property with /** @gqlHidden */, or declare a scalar: export const Base64 = scalar<Uint8Array>('Base64', { ... })"]);
1725
+ case "unknown": return this.#fail(Codes.InvalidType, use, `Cannot map 'unknown' or 'any' to a GraphQL type (${use.coordinate})`, ["Declare the type, or use JSONValue (import type { JSONValue } from '@znight/graphql') for arbitrary JSON"]);
1726
+ case "never":
1727
+ case "null":
1728
+ case "undefined": return this.#fail(Codes.InvalidType, use, `Cannot map '${shape.kind}' to a GraphQL type (${use.coordinate})`, ["Declare the type of the value"]);
1729
+ case "tuple": return this.#fail(Codes.InvalidType, use, `Cannot map a tuple to a GraphQL type (${use.coordinate})`, ["Use an array (readonly T[]) or a named object type"]);
1730
+ case "object":
1731
+ if (shape.additional !== void 0) return this.#fail(Codes.InvalidType, use, `Cannot map a record or an index signature to a GraphQL type (${use.coordinate})`, [RECORD_HINT]);
1732
+ return this.#fail(Codes.InvalidType, use, `Cannot map an anonymous object type to a GraphQL type (${use.coordinate})`, ["GraphQL types have names: declare it (export interface BookStats { ... }) and use it"]);
1733
+ case "intersection": return this.#fail(Codes.InvalidType, use, `Cannot map an anonymous intersection to a GraphQL type (${use.coordinate})`, ["Name it: export type BookWithAuthor = Book & { readonly author: Author }"]);
1734
+ case "union": return this.#anonymousUnion(shape.members, use);
1735
+ case "schema": return this.#fail(Codes.InvalidType, use, `Cannot map a schema type to a GraphQL type (${use.coordinate})`, ["Declare the TypeScript type: the annotation is the GraphQL type"]);
1736
+ case "opaque": return this.#opaque(shape, use);
1737
+ }
1738
+ }
1739
+ #anonymousUnion(members, use) {
1740
+ if (members.every((member) => member.kind === "literal" && typeof member.value === "string")) {
1741
+ const values = members.map((member) => `'${member.value}'`).join(" | ");
1742
+ return this.#fail(Codes.InvalidType, use, `Cannot map the anonymous union ${values} to a GraphQL type (${use.coordinate})`, [`Name it to make it an enum: export type Sort = ${values}`]);
1743
+ }
1744
+ if (members.every((member) => member.kind === "named")) return this.#fail(Codes.InvalidType, use, `Cannot map an anonymous union to a GraphQL type (${use.coordinate})`, [`GraphQL unions have names: export type SearchResult = ${members.map((member) => this.#named.get(member.key)?.name ?? "?").join(" | ")}`]);
1745
+ return this.#fail(Codes.InvalidType, use, `Cannot map the union ${members.map(describeShape).join(" | ")} to a GraphQL type (${use.coordinate})`, ["GraphQL unions only contain object types: declare one type, or an object type per case"]);
1746
+ }
1747
+ #opaque(shape, use) {
1748
+ const text = shape.text;
1749
+ let hints;
1750
+ switch (shape.reason) {
1751
+ case "non-json":
1752
+ if (text.startsWith("Promise")) hints = ["A Promise is only unwrapped at the top of a resolver return type: declare the resolved type"];
1753
+ else if (text.startsWith("Map") || text.startsWith("WeakMap")) hints = ["Use an array of entries, a named object type, or JSONValue (import type { JSONValue } from '@znight/graphql')"];
1754
+ else hints = ["Declare a plain data type (an interface, an array, a scalar)"];
1755
+ break;
1756
+ case "missing-annotation":
1757
+ hints = ["Annotate the type: the compiler reads annotations only"];
1758
+ break;
1759
+ case "function":
1760
+ hints = ["Functions are not data: return the value, or hide the member with /** @gqlHidden */"];
1761
+ break;
1762
+ case "type-parameter":
1763
+ hints = ["Give the type arguments explicitly"];
1764
+ break;
1765
+ default: hints = ["Declare the structure with an interface or a named alias"];
1766
+ }
1767
+ return this.#fail(Codes.InvalidType, use, `Cannot map '${text}' to a GraphQL type (${use.coordinate})`, hints);
1768
+ }
1769
+ #reference(shape, use) {
1770
+ const alias = SCALAR_ALIASES.get(shape.identity);
1771
+ if (alias === "JSON") {
1772
+ const json = this.#builtin("JSON", use);
1773
+ return json === void 0 ? void 0 : {
1774
+ ref: json.ref,
1775
+ nullable: true
1776
+ };
1777
+ }
1778
+ if (alias !== void 0) return refTo(alias === "Float" ? "Float" : alias);
1779
+ const scalar = this.#scalars.get(shape.identity);
1780
+ if (scalar !== void 0) return this.#customScalar(scalar, use);
1781
+ if (OUTPUT_ITERABLES.has(shape.identity)) {
1782
+ if (use.position === "input") return this.#fail(Codes.InvalidInput, use, `${use.coordinate} is a ${shape.name}: input lists are arrays`, ["Declare an array (readonly T[]) for input values"]);
1783
+ const item = shape.typeArgs[0];
1784
+ if (item === void 0) return this.#fail(Codes.InvalidType, use, `${use.coordinate}: ${shape.name} needs a type argument`, []);
1785
+ const converted = this.#convert(item, false, use);
1786
+ return converted === void 0 ? void 0 : {
1787
+ ref: {
1788
+ kind: "list",
1789
+ of: converted.ref,
1790
+ nonNull: false
1791
+ },
1792
+ nullable: false
1793
+ };
1794
+ }
1795
+ if (ASYNC_ITERABLES.has(shape.identity)) return this.#fail(Codes.InvalidType, use, `Cannot map '${shape.name}' to a GraphQL type (${use.coordinate})`, ["Async iterables are only the return type of @Subscription methods"]);
1796
+ return this.#fail(Codes.InvalidType, use, `Cannot map '${shape.name}' to a GraphQL type (${use.coordinate})`, ["Declare a plain data type (an interface, an array, a scalar)"]);
1797
+ }
1798
+ #builtin(name, use) {
1799
+ const key = `#builtin:${name}`;
1800
+ if (!this.#models.has(key)) {
1801
+ const model = {
1802
+ kind: "scalar",
1803
+ name,
1804
+ key,
1805
+ description: void 0,
1806
+ location: void 0,
1807
+ definition: void 0,
1808
+ specifiedByURL: void 0
1809
+ };
1810
+ this.#models.set(key, model);
1811
+ if (!this.#claim(model, use)) return void 0;
1812
+ }
1813
+ return refTo(name);
1814
+ }
1815
+ #customScalar(scalar, use) {
1816
+ const key = `#scalar:${scalar.identity}`;
1817
+ if (!this.#models.has(key)) {
1818
+ const model = {
1819
+ kind: "scalar",
1820
+ name: scalar.name,
1821
+ key,
1822
+ description: scalar.description,
1823
+ location: scalar.location,
1824
+ definition: scalar.identity,
1825
+ specifiedByURL: scalar.specifiedByURL
1826
+ };
1827
+ this.#models.set(key, model);
1828
+ if (!this.#claim(model, use)) return void 0;
1829
+ }
1830
+ return refTo(scalar.name);
1831
+ }
1832
+ #namedType(key, use) {
1833
+ const named = this.#named.get(key);
1834
+ if (named === void 0) return this.#fail(Codes.InvalidType, use, `Cannot resolve the type of ${use.coordinate}`, []);
1835
+ switch (named.declaration) {
1836
+ case "enum": return this.#enum(named, use);
1837
+ case "alias": return this.#alias(named, use);
1838
+ default: return this.#object(named, named, use);
1839
+ }
1840
+ }
1841
+ /**
1842
+ * A named alias: an object type (object literal, intersection, utility type, generic instance),
1843
+ * an enum (string literals), a union (object types), or transparent (`type Email = string`,
1844
+ * `type Books = Book[]`, `type Author = Person`).
1845
+ */
1846
+ #alias(alias, use) {
1847
+ const shape = alias.shape;
1848
+ switch (shape.kind) {
1849
+ case "object":
1850
+ case "intersection": return this.#object(alias, alias, use);
1851
+ case "named": {
1852
+ const target = this.#named.get(shape.key);
1853
+ if (target !== void 0 && target.declaration !== "alias" && target.declaration !== "enum" && target.typeArgs.length > 0) return this.#object(alias, target, use);
1854
+ return this.#namedType(shape.key, use);
1855
+ }
1856
+ case "union": {
1857
+ const rest = shape.members.filter((member) => member.kind !== "null" && member.kind !== "undefined");
1858
+ const nullable = rest.length !== shape.members.length;
1859
+ if (rest.length === 1) {
1860
+ const inner = this.#inner(rest[0], use);
1861
+ return inner === void 0 ? void 0 : {
1862
+ ref: inner.ref,
1863
+ nullable: inner.nullable || nullable
1864
+ };
1865
+ }
1866
+ let converted;
1867
+ if (rest.every((member) => member.kind === "literal")) converted = this.#literalEnum(alias, rest, use);
1868
+ else if (rest.length > 0 && rest.every((member) => member.kind === "named")) converted = this.#union(alias, rest, use);
1869
+ else converted = this.#anonymousUnion(rest, use);
1870
+ return converted === void 0 ? void 0 : {
1871
+ ref: converted.ref,
1872
+ nullable
1873
+ };
1874
+ }
1875
+ default: return this.#inner(shape, use);
1876
+ }
1877
+ }
1878
+ /**
1879
+ * The declaration key of the object type a shape maps to in output position (the parent of a
1880
+ * field resolver), `undefined` when it is not an object type. Mirrors {@link #alias}.
1881
+ */
1882
+ #objectKeyOf(shape) {
1883
+ if (shape.kind === "union") {
1884
+ const rest = shape.members.filter((member) => member.kind !== "null" && member.kind !== "undefined");
1885
+ return rest.length === 1 ? this.#objectKeyOf(rest[0]) : void 0;
1886
+ }
1887
+ if (shape.kind !== "named") return void 0;
1888
+ const named = this.#named.get(shape.key);
1889
+ if (named === void 0 || named.declaration === "enum") return void 0;
1890
+ if (named.declaration !== "alias") return named.key;
1891
+ const target = named.shape;
1892
+ if (target.kind === "object" || target.kind === "intersection") return named.key;
1893
+ if (target.kind === "named") {
1894
+ const instance = this.#named.get(target.key);
1895
+ if (instance !== void 0 && instance.declaration !== "alias" && instance.declaration !== "enum" && instance.typeArgs.length > 0) return named.key;
1896
+ }
1897
+ return this.#objectKeyOf(target);
1898
+ }
1899
+ /** An object type (output) or an input object type (input) for `named`, structured as `structure`. */
1900
+ #object(named, structure, use) {
1901
+ const key = named.key;
1902
+ if (!this.#checkPosition(named, use)) return void 0;
1903
+ const existing = this.#models.get(key);
1904
+ if (existing !== void 0) return this.#known(existing);
1905
+ const name = this.#typeName(named, use);
1906
+ if (name === void 0) return void 0;
1907
+ const properties = this.#propertiesOf(structure.shape);
1908
+ if (properties === "record") return this.#fail(Codes.InvalidType, use, `Cannot map ${named.name}, a record or an index signature, to a GraphQL type (${use.coordinate})`, [RECORD_HINT]);
1909
+ if (properties === void 0) return this.#fail(Codes.InvalidType, use, `Cannot map ${named.name} to a GraphQL object type (${use.coordinate})`, ["Declare an interface, a class or a named object type"]);
1910
+ const description = descriptionOf(named.doc) ?? (structure === named ? void 0 : descriptionOf(structure.doc));
1911
+ const trail = `${use.trail} → ${name}`;
1912
+ if (use.position === "input") {
1913
+ const model = {
1914
+ kind: "input",
1915
+ name,
1916
+ key,
1917
+ description,
1918
+ location: named.location,
1919
+ fields: []
1920
+ };
1921
+ this.#models.set(key, model);
1922
+ if (!this.#claim(model, use)) return void 0;
1923
+ for (const property of properties) {
1924
+ if (isHidden(property.doc)) continue;
1925
+ const fieldUse = {
1926
+ position: "input",
1927
+ coordinate: `${name}.${property.name}`,
1928
+ trail: `${trail}.${property.name}`,
1929
+ reached: trail,
1930
+ root: use.root,
1931
+ locate: () => annotationLocation(this.#ctx.project, property.location)
1932
+ };
1933
+ const field = this.#inputValue(property, fieldUse);
1934
+ if (field !== void 0) model.fields.push(field);
1935
+ }
1936
+ return refTo(name);
1937
+ }
1938
+ const model = {
1939
+ kind: "object",
1940
+ name,
1941
+ key,
1942
+ description,
1943
+ location: named.location,
1944
+ fields: [],
1945
+ trail,
1946
+ root: use.root,
1947
+ classIdentity: structure.declaration === "class" && structure.typeArgs.length === 0 && structure === named ? structure.identity : void 0,
1948
+ properties: properties.map((property) => this.#discriminant(property))
1949
+ };
1950
+ this.#models.set(key, model);
1951
+ if (!this.#claim(model, use)) return void 0;
1952
+ for (const property of properties) {
1953
+ const field = this.#outputField(model, property);
1954
+ if (field !== void 0) model.fields.push(field);
1955
+ }
1956
+ this.#attachFieldResolvers(model);
1957
+ return refTo(name);
1958
+ }
1959
+ /** A property as a union discriminator candidate: its literal value, through aliases (`kind: BookKind`). */
1960
+ #discriminant(property) {
1961
+ let shape = property.shape;
1962
+ for (let depth = 0; shape.kind === "named" && depth < 32; depth++) {
1963
+ const named = this.#named.get(shape.key);
1964
+ if (named?.declaration !== "alias") break;
1965
+ shape = named.shape;
1966
+ }
1967
+ return {
1968
+ name: property.name,
1969
+ optional: property.optional,
1970
+ literal: shape.kind === "literal" ? shape.value : void 0
1971
+ };
1972
+ }
1973
+ #outputField(model, property) {
1974
+ if (isHidden(property.doc) || property.name === "__typename") return void 0;
1975
+ if (property.shape.kind === "opaque" && property.shape.reason === "function") return void 0;
1976
+ const use = {
1977
+ position: "output",
1978
+ coordinate: `${model.name}.${property.name}`,
1979
+ trail: `${model.trail}.${property.name}`,
1980
+ reached: model.trail,
1981
+ root: model.root,
1982
+ locate: () => annotationLocation(this.#ctx.project, property.location)
1983
+ };
1984
+ if (!isGraphQLName(property.name)) return this.#fail(Codes.NameConflict, {
1985
+ ...use,
1986
+ locate: () => property.location
1987
+ }, `'${property.name}' is not a valid GraphQL field name (${use.coordinate})`, [NAME_HINT, "Hide the property with /** @gqlHidden */"]);
1988
+ const converted = this.#convert(property.shape, property.optional, use);
1989
+ if (converted === void 0) return void 0;
1990
+ return {
1991
+ name: property.name,
1992
+ type: printTypeRef(converted.ref),
1993
+ description: descriptionOf(property.doc),
1994
+ deprecationReason: deprecationOf(property.doc),
1995
+ args: [],
1996
+ binding: void 0,
1997
+ location: property.location
1998
+ };
1999
+ }
2000
+ /**
2001
+ * The properties of an object structure (intersections merged, later members win), `'record'` for
2002
+ * a record or an index signature (ZNIGHT060: GraphQL objects have fixed fields).
2003
+ */
2004
+ #propertiesOf(shape) {
2005
+ switch (shape.kind) {
2006
+ case "object": return shape.additional === void 0 ? shape.properties : "record";
2007
+ case "named": {
2008
+ const named = this.#named.get(shape.key);
2009
+ return named === void 0 || named.declaration === "enum" ? void 0 : this.#propertiesOf(named.shape);
2010
+ }
2011
+ case "intersection": {
2012
+ const merged = /* @__PURE__ */ new Map();
2013
+ for (const member of shape.members) {
2014
+ const properties = this.#propertiesOf(member);
2015
+ if (properties === void 0 || properties === "record") return properties;
2016
+ for (const property of properties) {
2017
+ merged.delete(property.name);
2018
+ merged.set(property.name, property);
2019
+ }
2020
+ }
2021
+ return [...merged.values()];
2022
+ }
2023
+ default: return;
2024
+ }
2025
+ }
2026
+ /** A declaration is used in one position: input or output (ZNIGHT063 otherwise). */
2027
+ #checkPosition(named, use) {
2028
+ let uses = this.#positions.get(named.key);
2029
+ if (uses === void 0) {
2030
+ uses = {};
2031
+ this.#positions.set(named.key, uses);
2032
+ }
2033
+ const other = use.position === "input" ? uses.output : uses.input;
2034
+ if (uses[use.position] === void 0) uses[use.position] = {
2035
+ coordinate: use.coordinate,
2036
+ location: use.locate()
2037
+ };
2038
+ if (other === void 0) return true;
2039
+ const output = use.position === "output" ? use.coordinate : other.coordinate;
2040
+ const input = use.position === "input" ? use.coordinate : other.coordinate;
2041
+ const inputOwner = input.includes("(") ? input.slice(0, input.indexOf("(")) : input.split(".")[0];
2042
+ this.#reportOnce(`position\0${named.key}`, {
2043
+ code: Codes.InvalidInput,
2044
+ severity: "error",
2045
+ message: `'${named.name}' is used as an output type (${output}) and as an input type (${input})`,
2046
+ location: named.location,
2047
+ hints: [`GraphQL needs two types: declare \`export interface ${named.name}Input extends ${named.name} {}\` and use it in ${inputOwner}`],
2048
+ related: [...uses.output?.location === void 0 ? [] : [{
2049
+ message: `used as output: ${output}`,
2050
+ location: uses.output.location
2051
+ }], ...uses.input?.location === void 0 ? [] : [{
2052
+ message: `used as input: ${input}`,
2053
+ location: uses.input.location
2054
+ }]]
2055
+ });
2056
+ return false;
2057
+ }
2058
+ /**
2059
+ * The GraphQL name of a declaration (§6.4): `@gqlName`, the declaration name, or for a generic
2060
+ * instance the names of its type arguments followed by the declaration name (`BookPage`).
2061
+ */
2062
+ #typeName(named, use) {
2063
+ if (this.#names.has(named.key)) return this.#names.get(named.key);
2064
+ let name;
2065
+ const explicit = tagOf(named.doc, "gqlName")?.text.trim();
2066
+ if (explicit !== void 0 && explicit !== "") name = explicit;
2067
+ else if (named.typeArgs.length === 0) name = named.name;
2068
+ else {
2069
+ const args = named.typeArgs.map((arg) => this.#argumentName(arg));
2070
+ const missing = args.findIndex((arg) => arg === void 0);
2071
+ if (missing === -1) name = `${args.join("")}${named.name}`;
2072
+ else this.#reportOnce(`argument\0${named.key}`, {
2073
+ code: Codes.InvalidType,
2074
+ severity: "error",
2075
+ message: `Cannot name the GraphQL type of ${named.name}<...> (${use.coordinate}): its type argument ${describeShape(named.typeArgs[missing])} has no GraphQL name`,
2076
+ location: named.location,
2077
+ related: reachedFrom(use),
2078
+ hints: [`Name the instance with an alias (export type BookPages = ${named.name}<...>) or with /** @gqlName Name */`]
2079
+ });
2080
+ }
2081
+ this.#names.set(named.key, name);
2082
+ return name;
2083
+ }
2084
+ /** The GraphQL name a type argument contributes to a generic instance name. */
2085
+ #argumentName(shape) {
2086
+ switch (shape.kind) {
2087
+ case "string": return "String";
2088
+ case "number": return this.#number;
2089
+ case "boolean": return "Boolean";
2090
+ case "date": return "DateTime";
2091
+ case "bigint": return "BigInt";
2092
+ case "reference": {
2093
+ const alias = SCALAR_ALIASES.get(shape.identity);
2094
+ if (alias !== void 0) return alias;
2095
+ return this.#scalars.get(shape.identity)?.name;
2096
+ }
2097
+ case "union": {
2098
+ const rest = shape.members.filter((member) => member.kind !== "null" && member.kind !== "undefined");
2099
+ return rest.length === 1 ? this.#argumentName(rest[0]) : void 0;
2100
+ }
2101
+ case "named": {
2102
+ const named = this.#named.get(shape.key);
2103
+ if (named === void 0) return void 0;
2104
+ if (named.declaration === "alias") {
2105
+ const target = named.shape;
2106
+ const instance = target.kind === "named" ? this.#named.get(target.key) : void 0;
2107
+ const isObject = target.kind === "object" || target.kind === "intersection" || instance !== void 0 && instance.declaration !== "alias" && instance.declaration !== "enum" && instance.typeArgs.length > 0;
2108
+ const isEnum = target.kind === "union" && target.members.every((member) => member.kind === "literal");
2109
+ const isUnion = target.kind === "union" && target.members.filter((member) => member.kind === "named").length > 1;
2110
+ if (!isObject && !isEnum && !isUnion) return this.#argumentName(target);
2111
+ }
2112
+ return this.#typeName(named, {
2113
+ position: "output",
2114
+ coordinate: named.name,
2115
+ trail: named.name,
2116
+ reached: void 0,
2117
+ root: void 0,
2118
+ locate: () => named.location
2119
+ });
2120
+ }
2121
+ default: return;
2122
+ }
2123
+ }
2124
+ /**
2125
+ * Registers a model under its GraphQL name: the name must be valid, not reserved, and not taken
2126
+ * by another declaration (ZNIGHT061).
2127
+ */
2128
+ #claim(model, use) {
2129
+ const name = model.name;
2130
+ const isRoot = model.key.startsWith("#root:");
2131
+ const location = model.location ?? use?.locate();
2132
+ let problem;
2133
+ if (!isGraphQLName(name)) problem = `'${name}' is not a valid GraphQL type name`;
2134
+ else if (!isRoot && ROOT_NAMES.has(name)) problem = `'${name}' is the name of a root operation type`;
2135
+ else if (SPECIFIED_SCALARS.has(name)) problem = `'${name}' is the name of a specified GraphQL scalar`;
2136
+ if (problem !== void 0) {
2137
+ this.#reportOnce(`name\0${model.key}`, {
2138
+ code: Codes.NameConflict,
2139
+ severity: "error",
2140
+ message: `${problem} (${model.key.startsWith("#") ? name : model.key})`,
2141
+ ...location === void 0 ? {} : { location },
2142
+ related: use === void 0 ? [] : reachedFrom(use),
2143
+ hints: [isGraphQLName(name) ? "Rename the declaration, or name it with /** @gqlName OtherName */" : NAME_HINT]
2144
+ });
2145
+ return false;
2146
+ }
2147
+ const existing = this.#types.get(name);
2148
+ if (existing === void 0) {
2149
+ this.#types.set(name, model);
2150
+ return true;
2151
+ }
2152
+ if (existing === model) return true;
2153
+ const pair = [existing.key, model.key].sort(compareStrings).join("\0");
2154
+ this.#reportOnce(`conflict\0${pair}`, {
2155
+ code: Codes.NameConflict,
2156
+ severity: "error",
2157
+ message: `Two types are named '${name}' in the GraphQL schema: ${describeKey(model)} and ${describeKey(existing)}`,
2158
+ ...location === void 0 ? {} : { location },
2159
+ related: [...existing.location === void 0 ? [] : [{
2160
+ message: "the other declaration",
2161
+ location: existing.location
2162
+ }], ...use === void 0 ? [] : reachedFrom(use)],
2163
+ hints: ["Rename one of them, or name one with /** @gqlName OtherName */"]
2164
+ });
2165
+ return false;
2166
+ }
2167
+ /** A model met again: its reference, unless its name was refused (already reported). */
2168
+ #known(model) {
2169
+ return this.#types.get(model.name) === model ? refTo(model.name) : void 0;
2170
+ }
2171
+ /** A TypeScript `enum`: names = member names, internal values = member values. */
2172
+ #enum(named, use) {
2173
+ const existing = this.#models.get(named.key);
2174
+ if (existing !== void 0) return this.#known(existing);
2175
+ const name = this.#typeName(named, use);
2176
+ if (name === void 0) return void 0;
2177
+ const members = named.enumMembers;
2178
+ if (members === void 0 || members.length === 0) return this.#fail(Codes.InvalidType, use, `The values of the enum ${named.name} cannot be evaluated (${use.coordinate})`, ["Use literal member values (A = \"a\", B = 1)"]);
2179
+ const values = [];
2180
+ for (const member of members) {
2181
+ if (!this.#checkEnumValueName(member.name, named, member.location, use)) continue;
2182
+ values.push({
2183
+ name: member.name,
2184
+ value: member.value,
2185
+ description: descriptionOf(member.doc),
2186
+ deprecationReason: deprecationOf(member.doc)
2187
+ });
2188
+ }
2189
+ return this.#registerEnum(named, name, values, use);
2190
+ }
2191
+ /** A named alias of a union of string literals: names = values = the literals, in source order. */
2192
+ #literalEnum(named, members, use) {
2193
+ const existing = this.#models.get(named.key);
2194
+ if (existing !== void 0) return this.#known(existing);
2195
+ const literals = named.literals ?? members.map((member) => member.value);
2196
+ if (!literals.every((value) => typeof value === "string")) return this.#fail(Codes.InvalidType, use, `Cannot map ${named.name} (${literals.map((value) => JSON.stringify(value)).join(" | ")}) to a GraphQL type (${use.coordinate}): only unions of string literals are enums`, ["Declare a TypeScript enum (enum Level { Low = 1, High = 2 }), or use Int"]);
2197
+ const name = this.#typeName(named, use);
2198
+ if (name === void 0) return void 0;
2199
+ const values = [];
2200
+ for (const literal of literals) {
2201
+ if (!this.#checkEnumValueName(literal, named, named.location, use)) continue;
2202
+ values.push({
2203
+ name: literal,
2204
+ value: literal,
2205
+ description: void 0,
2206
+ deprecationReason: void 0
2207
+ });
2208
+ }
2209
+ return this.#registerEnum(named, name, values, use);
2210
+ }
2211
+ #checkEnumValueName(value, named, location, use) {
2212
+ if (isGraphQLName(value) && !RESERVED_ENUM_VALUES.has(value)) return true;
2213
+ this.#reportOnce(`enum\0${named.key}\0${value}`, {
2214
+ code: Codes.NameConflict,
2215
+ severity: "error",
2216
+ message: `'${value}' of ${named.name} is not a valid GraphQL enum value`,
2217
+ location,
2218
+ related: reachedFrom(use),
2219
+ hints: [`${NAME_HINT}; true, false and null are reserved`]
2220
+ });
2221
+ return false;
2222
+ }
2223
+ #registerEnum(named, name, values, use) {
2224
+ const model = {
2225
+ kind: "enum",
2226
+ name,
2227
+ key: named.key,
2228
+ description: descriptionOf(named.doc),
2229
+ location: named.location,
2230
+ values
2231
+ };
2232
+ this.#models.set(named.key, model);
2233
+ if (!this.#claim(model, use)) return void 0;
2234
+ return refTo(name);
2235
+ }
2236
+ /** A named alias of a union of object types (output only), with its runtime discriminator. */
2237
+ #union(alias, members, use) {
2238
+ if (use.position === "input") return this.#fail(Codes.InvalidInput, use, `${use.coordinate} is the union ${alias.name}: unions cannot be input values`, ["Declare one input type with optional fields, or one argument per case"]);
2239
+ const existing = this.#models.get(alias.key);
2240
+ if (existing !== void 0) return this.#known(existing);
2241
+ const name = this.#typeName(alias, use);
2242
+ if (name === void 0) return void 0;
2243
+ const model = {
2244
+ kind: "union",
2245
+ name,
2246
+ key: alias.key,
2247
+ description: descriptionOf(alias.doc),
2248
+ location: alias.location,
2249
+ members: [],
2250
+ discriminator: void 0
2251
+ };
2252
+ this.#models.set(alias.key, model);
2253
+ if (!this.#claim(model, use)) return void 0;
2254
+ const trail = `${use.trail} → ${name}`;
2255
+ const objects = [];
2256
+ let failed = false;
2257
+ for (const member of members) {
2258
+ const memberUse = {
2259
+ ...use,
2260
+ coordinate: name,
2261
+ trail,
2262
+ reached: trail,
2263
+ locate: () => alias.location
2264
+ };
2265
+ const converted = this.#inner(member, memberUse);
2266
+ if (converted === void 0) {
2267
+ failed = true;
2268
+ continue;
2269
+ }
2270
+ const target = converted.ref.kind === "named" ? this.#types.get(converted.ref.name) : void 0;
2271
+ if (target?.kind !== "object") {
2272
+ failed = true;
2273
+ this.#fail(Codes.InvalidType, memberUse, `The union ${name} contains ${describeShape(member)}, which is not an object type`, ["GraphQL unions only contain object types"]);
2274
+ continue;
2275
+ }
2276
+ if (!objects.includes(target)) objects.push(target);
2277
+ }
2278
+ objects.sort((a, b) => compareStrings(a.name, b.name));
2279
+ model.members = objects.map((object) => object.name);
2280
+ if (!failed) model.discriminator = this.#discriminator(model, objects);
2281
+ return refTo(name);
2282
+ }
2283
+ /**
2284
+ * How the runtime tells the members apart (§5.7): `instanceof` when every member is an exported
2285
+ * class, a `__typename` property, a literal property with a distinct value per member, else
2286
+ * ZNIGHT064.
2287
+ */
2288
+ #discriminator(union, members) {
2289
+ const found = discriminatorOf(members, (identity) => this.#ctx.classInfo(identity));
2290
+ if (found !== void 0) return found;
2291
+ const names = members.map((member) => member.name);
2292
+ const one = names.length === 1;
2293
+ const listed = one ? names[0] : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;
2294
+ const allClasses = members.every((member) => member.classIdentity !== void 0);
2295
+ let why;
2296
+ if (allClasses) why = one ? "is a class that is not exported" : "are classes that are not all exported";
2297
+ else why = one ? "has no literal property" : "have no common literal property";
2298
+ this.#report({
2299
+ code: Codes.UnresolvableAbstractType,
2300
+ severity: "error",
2301
+ message: `The members of union ${union.name} cannot be told apart at runtime: ${listed} ${why}`,
2302
+ ...union.location === void 0 ? {} : { location: union.location },
2303
+ hints: [allClasses ? "Export the member classes: the generated module imports them for instanceof" : `Add a literal property to each member (${members.map((member) => `readonly kind: '${lowerFirst(member.name)}'`).join(" / ")}), or make the members classes`]
2304
+ });
2305
+ }
2306
+ /** Defaults (`@default`, parameter defaults) against their types (ZNIGHT063), as external values. */
2307
+ #checkDefaults() {
2308
+ for (const pending of this.#defaults) {
2309
+ const result = externalValue(pending.value, pending.target.ref, this.#types);
2310
+ if ("error" in result) {
2311
+ const location = pending.location ?? pending.use.locate();
2312
+ this.#report({
2313
+ code: Codes.InvalidInput,
2314
+ severity: "error",
2315
+ message: `Invalid default value ${describeValue(pending.value)} for ${pending.use.coordinate} (${pending.target.type}): ${result.error}`,
2316
+ ...location === void 0 ? {} : { location },
2317
+ related: reachedFrom(pending.use),
2318
+ hints: ["Defaults are JSON values of the argument type (enum values as their member value or name)"]
2319
+ });
2320
+ continue;
2321
+ }
2322
+ pending.target.defaultValue = result.value;
2323
+ if (pending.target.ref.nonNull) pending.target.nullAsUndefined = false;
2324
+ }
2325
+ }
2326
+ /** GraphQL forbids a cycle of non-null input fields (ZNIGHT063). */
2327
+ #checkInputCycles() {
2328
+ const inputs = [...this.#models.values()].filter((model) => model.kind === "input").sort((a, b) => compareStrings(a.name, b.name));
2329
+ const state = /* @__PURE__ */ new Map();
2330
+ const stack = [];
2331
+ const visit = (model) => {
2332
+ state.set(model.name, "visiting");
2333
+ stack.push(model.name);
2334
+ for (const field of model.fields) {
2335
+ if (field.ref.kind !== "named" || !field.ref.nonNull) continue;
2336
+ const target = this.#types.get(field.ref.name);
2337
+ if (target?.kind !== "input") continue;
2338
+ const status = state.get(target.name);
2339
+ if (status === "visiting") {
2340
+ const cycle = [...stack.slice(stack.indexOf(target.name)), target.name];
2341
+ this.#report({
2342
+ code: Codes.InvalidInput,
2343
+ severity: "error",
2344
+ message: `The input types ${cycle.join(" → ")} reference each other through non-null fields: no value can be written`,
2345
+ ...target.location === void 0 ? {} : { location: target.location },
2346
+ hints: ["Make one of the fields of the cycle optional (?: T) or a list"]
2347
+ });
2348
+ } else if (status === void 0) visit(target);
2349
+ }
2350
+ stack.pop();
2351
+ state.set(model.name, "done");
2352
+ };
2353
+ for (const model of inputs) if (!state.has(model.name)) visit(model);
2354
+ }
2355
+ /** RFC 0001: every root field decides every required route decorator group (ZNIGHT023). */
2356
+ #checkDecisions(resolvers) {
2357
+ const applied = [];
2358
+ for (const resolver of resolvers) for (const field of resolver.fields) applied.push(...field.meta);
2359
+ const required = requiredRouteGroups(this.#ctx, applied);
2360
+ if (required.length === 0) return;
2361
+ for (const resolver of resolvers) for (const field of resolver.fields) {
2362
+ if (field.operation === "field") continue;
2363
+ const decided = new Set(field.meta.map((entry) => entry.group));
2364
+ for (const group of required) {
2365
+ if (decided.has(group.group)) continue;
2366
+ const root = ROOT_TYPE_NAMES[field.operation];
2367
+ this.#report({
2368
+ code: Codes.MissingRouteDecision,
2369
+ severity: "error",
2370
+ message: `Root field ${root}.${field.name} (${resolver.host.displayName}.${field.method}) has no "${group.group}" decision`,
2371
+ location: field.methodLocation,
2372
+ hints: [`Add ${group.suggestion} to the method or to ${resolver.host.displayName}`],
2373
+ related: [{
2374
+ message: `The "${group.group}" group is required`,
2375
+ location: group.decorators[0].definition
2376
+ }]
2377
+ });
2378
+ }
2379
+ }
2380
+ }
2381
+ #assemble(roots, resolvers) {
2382
+ const types = [...this.#types.values()].sort((a, b) => compareStrings(a.name, b.name));
2383
+ const meta = [];
2384
+ for (const resolver of resolvers) for (const field of resolver.fields) meta.push(...field.meta);
2385
+ const rootNames = {
2386
+ query: ROOT_TYPE_NAMES.query,
2387
+ ...roots.has("mutation") ? { mutation: ROOT_TYPE_NAMES.mutation } : {},
2388
+ ...roots.has("subscription") ? { subscription: ROOT_TYPE_NAMES.subscription } : {}
2389
+ };
2390
+ const sdl = printSdl({
2391
+ roots: rootNames,
2392
+ types: types.map(sdlType)
2393
+ });
2394
+ return {
2395
+ roots: rootNames,
2396
+ types,
2397
+ meta,
2398
+ sdl,
2399
+ schemaHash: schemaHash(sdl)
2400
+ };
2401
+ }
2402
+ };
2403
+ /** The class (or one of its base classes) declares an instance `load` method. */
2404
+ function hasLoadMethod(ctx, identity) {
2405
+ const seen = /* @__PURE__ */ new Set();
2406
+ let current = identity;
2407
+ while (current !== void 0 && !seen.has(current)) {
2408
+ seen.add(current);
2409
+ const cls = ctx.classInfo(current);
2410
+ if (cls === void 0) return true;
2411
+ if (cls.methods.some((method) => method.name === "load" && method.kind === "method" && !method.static)) return true;
2412
+ if (cls.properties.some((property) => property.name === "load" && !property.static)) return true;
2413
+ current = cls.superClass?.identity;
2414
+ }
2415
+ return false;
2416
+ }
2417
+ /** A (nullable, until `#convert` decides) reference to a named type. */
2418
+ function refTo(name) {
2419
+ return {
2420
+ ref: {
2421
+ kind: "named",
2422
+ name,
2423
+ nonNull: false
2424
+ },
2425
+ nullable: false
2426
+ };
2427
+ }
2428
+ function reachedFrom(use) {
2429
+ return use.reached === void 0 || use.root === void 0 ? [] : [{
2430
+ message: `reached from ${use.reached}`,
2431
+ location: use.root
2432
+ }];
2433
+ }
2434
+ function decoratorName(operation) {
2435
+ return ROOT_TYPE_NAMES[operation];
2436
+ }
2437
+ /** The token of a binding result (`undefined` when binding failed). */
2438
+ function tokenOfRef(ref) {
2439
+ if (typeof ref === "string") return ref;
2440
+ return ref !== void 0 && "token" in ref ? ref.token : void 0;
2441
+ }
2442
+ function describeKey(model) {
2443
+ return model.key.startsWith("#") ? `the ${model.kind} ${model.name}` : model.key;
2444
+ }
2445
+ /** Short description of a shape for messages (`string`, `Book`, `Map<string, number>`). */
2446
+ function describeShape(shape) {
2447
+ switch (shape.kind) {
2448
+ case "literal": return JSON.stringify(shape.value);
2449
+ case "named": return shape.key.slice(shape.key.indexOf("#") + 1);
2450
+ case "reference": return shape.name;
2451
+ case "opaque": return shape.text;
2452
+ case "array": return `${describeShape(shape.items)}[]`;
2453
+ case "union": return shape.members.map(describeShape).join(" | ");
2454
+ case "object": return "an object literal type";
2455
+ default: return shape.kind;
2456
+ }
2457
+ }
2458
+ function describeValue(value) {
2459
+ try {
2460
+ return JSON.stringify(value) ?? String(value);
2461
+ } catch {
2462
+ return String(value);
2463
+ }
2464
+ }
2465
+ function containsRef(value) {
2466
+ if (typeof value !== "object" || value === null) return false;
2467
+ if (Array.isArray(value)) return value.some(containsRef);
2468
+ const prototype = Object.getPrototypeOf(value);
2469
+ if (prototype !== Object.prototype && prototype !== null) return true;
2470
+ return Object.values(value).some(containsRef);
2471
+ }
2472
+ function lowerFirst(text) {
2473
+ return `${text.charAt(0).toLowerCase()}${text.slice(1)}`;
2474
+ }
2475
+ // src/compiler/generate.ts
2476
+ /** Module of `isThenable` (a required peer of `@znight/graphql`). */
2477
+ const HTTP_MODULE = "@znight/http";
2478
+ /** Builds the graphql section; `undefined` (no section) when the application has no resolver. */
2479
+ function generateGraphQL(ctx, model, options) {
2480
+ if (model === void 0) return void 0;
2481
+ if (options.sdl !== false) ctx.emitFile(options.sdl, `${model.sdl}\n`);
2482
+ const imports = createImports(ctx);
2483
+ const entries = [
2484
+ ["version", ctx.lit(1)],
2485
+ ["schemaHash", model.schemaHash],
2486
+ ["roots", ctx.obj(Object.entries(model.roots))],
2487
+ ["types", ctx.arr(model.types.map((type) => typeNode(ctx, imports, type)))]
2488
+ ];
2489
+ const groups = groupsNode(ctx, model.meta);
2490
+ if (groups !== void 0) entries.push(["groups", groups]);
2491
+ return ctx.obj(entries);
2492
+ }
2493
+ function createImports(ctx) {
2494
+ let args;
2495
+ let context;
2496
+ let info;
2497
+ let validateArgs;
2498
+ let isThenable;
2499
+ const hosts = /* @__PURE__ */ new Map();
2500
+ return {
2501
+ argsType: () => {
2502
+ args ??= ctx.importFrom(RUNTIME_MODULE, "GraphQLArgs", { type: true });
2503
+ return args;
2504
+ },
2505
+ contextType: () => {
2506
+ context ??= ctx.importFrom(RUNTIME_MODULE, "GraphQLContext", { type: true });
2507
+ return context;
2508
+ },
2509
+ infoType: () => {
2510
+ info ??= ctx.importFrom("graphql", "GraphQLResolveInfo", { type: true });
2511
+ return info;
2512
+ },
2513
+ validateArgs: () => {
2514
+ validateArgs ??= ctx.importFrom(RUNTIME_MODULE, "validateArgs");
2515
+ return validateArgs;
2516
+ },
2517
+ isThenable: () => {
2518
+ isThenable ??= ctx.importFrom(HTTP_MODULE, "isThenable");
2519
+ return isThenable;
2520
+ },
2521
+ hostType: (identity) => {
2522
+ let node = hosts.get(identity);
2523
+ if (node === void 0) {
2524
+ node = ctx.importType(identity);
2525
+ hosts.set(identity, node);
2526
+ }
2527
+ return node;
2528
+ }
2529
+ };
2530
+ }
2531
+ function typeNode(ctx, imports, type) {
2532
+ const head = [["kind", type.kind], ["name", type.name]];
2533
+ if (type.description !== void 0 && type.kind !== "scalar") head.push(["description", type.description]);
2534
+ switch (type.kind) {
2535
+ case "object": return ctx.obj([...head, ["fields", ctx.arr(type.fields.map((field) => fieldNode(ctx, imports, field)))]]);
2536
+ case "input": return ctx.obj([...head, ["fields", ctx.arr(type.fields.map((field) => inputValueNode(ctx, field)))]]);
2537
+ case "enum": return ctx.obj([...head, ["values", ctx.arr(type.values.map((value) => {
2538
+ const entries = [["name", value.name], ["value", value.value]];
2539
+ if (value.description !== void 0) entries.push(["description", value.description]);
2540
+ if (value.deprecationReason !== void 0) entries.push(["deprecationReason", value.deprecationReason]);
2541
+ return ctx.obj(entries);
2542
+ }))]]);
2543
+ case "union": {
2544
+ const discriminator = type.discriminator;
2545
+ let node;
2546
+ if (discriminator === void 0 || discriminator.by === "typename") node = ctx.obj([["by", "typename"]]);
2547
+ else if (discriminator.by === "property") node = ctx.obj([
2548
+ ["by", "property"],
2549
+ ["property", discriminator.property],
2550
+ ["values", ctx.obj(Object.entries(discriminator.values))]
2551
+ ]);
2552
+ else node = ctx.obj([["by", "class"], ["classes", ctx.arr(discriminator.classes.map((entry) => ctx.arr([ctx.importValue(entry.identity), entry.name])))]]);
2553
+ return ctx.obj([
2554
+ ...head,
2555
+ ["members", ctx.lit([...type.members])],
2556
+ ["discriminator", node]
2557
+ ]);
2558
+ }
2559
+ case "scalar": return type.definition === void 0 ? ctx.obj([...head, ["builtin", ctx.lit(true)]]) : ctx.obj([...head, ["scalar", ctx.importValue(type.definition)]]);
2560
+ }
2561
+ }
2562
+ function fieldNode(ctx, imports, field) {
2563
+ const entries = [["name", field.name], ["type", field.type]];
2564
+ if (field.description !== void 0) entries.push(["description", field.description]);
2565
+ if (field.deprecationReason !== void 0) entries.push(["deprecationReason", field.deprecationReason]);
2566
+ if (field.args.length > 0) entries.push(["args", ctx.arr(field.args.map((arg) => inputValueNode(ctx, arg)))]);
2567
+ if (field.binding !== void 0) entries.push(["resolver", resolverNode(ctx, imports, field.binding.resolver, field.binding.field)]);
2568
+ return ctx.obj(entries);
2569
+ }
2570
+ function inputValueNode(ctx, arg) {
2571
+ const entries = [["name", arg.name], ["type", arg.type]];
2572
+ if (arg.description !== void 0) entries.push(["description", arg.description]);
2573
+ if (arg.deprecationReason !== void 0) entries.push(["deprecationReason", arg.deprecationReason]);
2574
+ if (arg.defaultValue !== void 0) entries.push(["defaultValue", ctx.lit(arg.defaultValue)]);
2575
+ if (arg.nullAsUndefined) entries.push(["nullAsUndefined", ctx.lit(true)]);
2576
+ return ctx.obj(entries);
2577
+ }
2578
+ function resolverNode(ctx, imports, resolver, field) {
2579
+ const guards = [...resolver.guards, ...field.guards].map((ref) => ctx.tokenOf(ref) ?? ref.token);
2580
+ const entries = [
2581
+ ["token", ctx.tokenOf(resolver.host) ?? resolver.host.identity],
2582
+ ["method", field.method],
2583
+ ["operation", field.operation],
2584
+ ["guards", ctx.lit(guards)],
2585
+ ["meta", ctx.obj(field.meta.map((entry) => [entry.key, ctx.lit(entry.value)]))]
2586
+ ];
2587
+ const loaders = field.params.flatMap((param) => param?.kind === "loader" ? [loaderToken(ctx, param)] : []);
2588
+ if (loaders.length > 0) entries.push(["loaders", ctx.lit(loaders)]);
2589
+ entries.push(["invoke", invokeNode(ctx, imports, resolver, field)]);
2590
+ return ctx.obj(entries);
2591
+ }
2592
+ /** The provider token a loader parameter is bound to. */
2593
+ function loaderToken(ctx, param) {
2594
+ const ref = ctx.binding(param.binding);
2595
+ if (typeof ref === "string") return ref;
2596
+ if (ref !== void 0 && "token" in ref) return ref.token;
2597
+ return param.identity;
2598
+ }
2599
+ /** Which `invoke` parameters a field uses: `(r, p, a, c, i)`. */
2600
+ function usedParameters(field) {
2601
+ let p = false;
2602
+ let a = false;
2603
+ let c = false;
2604
+ let i = false;
2605
+ for (const param of field.params) switch (param?.kind) {
2606
+ case "parent":
2607
+ p = true;
2608
+ break;
2609
+ case "args":
2610
+ a = true;
2611
+ break;
2612
+ case "ctx":
2613
+ case "loader":
2614
+ c = true;
2615
+ break;
2616
+ case "info": i = true;
2617
+ }
2618
+ return [
2619
+ p,
2620
+ a,
2621
+ c,
2622
+ i
2623
+ ];
2624
+ }
2625
+ /**
2626
+ * `(r: Resolver, p: unknown, a: GraphQLArgs, c: GraphQLContext, i: GraphQLResolveInfo) => r.m(...)`:
2627
+ * unused middle parameters are `_`-prefixed, trailing ones omitted (`noUnusedParameters`).
2628
+ */
2629
+ function invokeNode(ctx, imports, resolver, field) {
2630
+ const used = usedParameters(field);
2631
+ const last = used.lastIndexOf(true);
2632
+ const types = [
2633
+ () => ctx.code`unknown`,
2634
+ imports.argsType,
2635
+ imports.contextType,
2636
+ imports.infoType
2637
+ ];
2638
+ const names = [
2639
+ "p",
2640
+ "a",
2641
+ "c",
2642
+ "i"
2643
+ ];
2644
+ const params = [["r", imports.hostType(resolver.host.identity)]];
2645
+ for (let index = 0; index <= last; index++) params.push([`${used[index] ? "" : "_"}${names[index]}`, types[index]()]);
2646
+ const validated = field.params.flatMap((param, index) => param?.kind === "args" && param.schema !== void 0 ? [index] : []);
2647
+ return ctx.arrow(params, (r, ...rest) => {
2648
+ const [p, a, c, i] = rest;
2649
+ const scope = {
2650
+ p,
2651
+ a,
2652
+ c,
2653
+ i
2654
+ };
2655
+ if (validated.length === 0) return call(ctx, r, field, (index) => argument(ctx, scope, field, index));
2656
+ return validatingBlock(ctx, imports, r, scope, field, validated);
2657
+ });
2658
+ }
2659
+ /** `r.method(args)`. */
2660
+ function call(ctx, r, field, argumentOf) {
2661
+ return ctx.call(ctx.member(r, field.method), field.params.map((_, index) => argumentOf(index)));
2662
+ }
2663
+ /** The expression passed for the parameter `index` (validation not applied). */
2664
+ function argument(ctx, scope, field, index) {
2665
+ const param = field.params[index];
2666
+ switch (param?.kind) {
2667
+ case "parent": return ctx.code`${scope.p} as never`;
2668
+ case "ctx": return scope.c;
2669
+ case "info": return scope.i;
2670
+ case "loader": return ctx.code`${ctx.call(ctx.member(scope.c, "loader"), [loaderToken(ctx, param)])} as never`;
2671
+ case "args": return ctx.code`${argsValue(ctx, scope, param.name)} as never`;
2672
+ default: return ctx.lit(void 0);
2673
+ }
2674
+ }
2675
+ /** `a['name']`, or `a` for `@Args()`. */
2676
+ function argsValue(ctx, scope, name) {
2677
+ const a = scope.a;
2678
+ return name === void 0 ? a : ctx.code`${a}[${name}]`;
2679
+ }
2680
+ /** `validateArgs(Schema, a['input'], 'input')`. */
2681
+ function validation(ctx, imports, scope, param) {
2682
+ return ctx.call(imports.validateArgs(), [
2683
+ ctx.ref(param.schema),
2684
+ argsValue(ctx, scope, param.name),
2685
+ param.name ?? "args"
2686
+ ]);
2687
+ }
2688
+ /**
2689
+ * The body of the `invoke` of a field validating arguments: each validation is evaluated in order
2690
+ * into a `const`; while they return values the method is called synchronously, the first thenable
2691
+ * resumes in an `async` arrow that awaits it and the later validations (the order of evaluation and
2692
+ * the error reported first are those of an `async` invoke awaiting every validation).
2693
+ *
2694
+ * ```ts
2695
+ * (r: BookResolver, _p: unknown, a: GraphQLArgs) => {
2696
+ * const v0 = validateArgs(NewBookInput, a['input'], 'input')
2697
+ * if (isThenable(v0)) return (async () => r.addBook(await v0 as never))()
2698
+ * return r.addBook(v0 as never)
2699
+ * }
2700
+ * ```
2701
+ */
2702
+ function validatingBlock(ctx, imports, r, scope, field, validated) {
2703
+ return ctx.block(validated.map((index) => `v${index}`), (...locals) => {
2704
+ const local = new Map(validated.map((index, position) => [index, locals[position]]));
2705
+ const statements = [];
2706
+ for (const index of validated) {
2707
+ const name = local.get(index);
2708
+ const param = field.params[index];
2709
+ statements.push(ctx.code`const ${name} = ${validation(ctx, imports, scope, param)}`);
2710
+ const resume = ctx.arrow([], () => call(ctx, r, field, (position) => {
2711
+ const value = local.get(position);
2712
+ if (value === void 0) return argument(ctx, scope, field, position);
2713
+ if (position < index) return ctx.code`${value} as never`;
2714
+ if (position === index) return ctx.code`await ${value} as never`;
2715
+ const later = field.params[position];
2716
+ return ctx.code`await ${validation(ctx, imports, scope, later)} as never`;
2717
+ }), { async: true });
2718
+ statements.push(ctx.code`if (${ctx.call(imports.isThenable(), [name])}) return (${resume})()`);
2719
+ }
2720
+ statements.push(ctx.code`return ${call(ctx, r, field, (position) => {
2721
+ const value = local.get(position);
2722
+ return value === void 0 ? argument(ctx, scope, field, position) : ctx.code`${value} as never`;
2723
+ })}`);
2724
+ return statements;
2725
+ });
2726
+ }
2727
+ /**
2728
+ * `groups`: the route decorator groups the runtime needs (required, holding several keys, or named
2729
+ * differently from their key), sorted; `undefined` when there is none (RFC 0001, as `extensions.http`).
2730
+ */
2731
+ function groupsNode(ctx, meta) {
2732
+ const groups = /* @__PURE__ */ new Map();
2733
+ for (const entry of meta) {
2734
+ const group = groups.get(entry.group);
2735
+ if (group === void 0) groups.set(entry.group, {
2736
+ keys: /* @__PURE__ */ new Set([entry.key]),
2737
+ required: entry.required
2738
+ });
2739
+ else {
2740
+ group.keys.add(entry.key);
2741
+ group.required ||= entry.required;
2742
+ }
2743
+ }
2744
+ const needed = [...groups].filter(([name, group]) => group.required || group.keys.size > 1 || !group.keys.has(name)).sort(([a], [b]) => compareStrings(a, b));
2745
+ if (needed.length === 0) return void 0;
2746
+ return ctx.obj(needed.map(([name, group]) => [name, ctx.obj([["keys", ctx.lit([...group.keys].sort(compareStrings))], ["required", group.required]])]));
2747
+ }
2748
+ // src/compiler/options.ts
2749
+ /** The defaults. */
2750
+ const DEFAULT_OPTIONS = Object.freeze({
2751
+ sdl: false,
2752
+ number: "Float"
2753
+ });
2754
+ const KNOWN = /* @__PURE__ */ new Set(["sdl", "number"]);
2755
+ /**
2756
+ * Merges `options` onto `base`. Throws a `TypeError` naming the option on an invalid value: options
2757
+ * are written in `znight.config.ts`, the error surfaces when the configuration is loaded.
2758
+ */
2759
+ function resolveOptions(base, options) {
2760
+ if (typeof options !== "object" || options === null || Array.isArray(options)) throw new TypeError("[znight] graphql.configure() expects an options object: { sdl?, number? }");
2761
+ for (const key of Object.keys(options)) if (!KNOWN.has(key)) throw new TypeError(`[znight] graphql.configure(): unknown option "${key}" (options: sdl, number)`);
2762
+ const sdl = options.sdl === void 0 ? base.sdl : options.sdl;
2763
+ if (sdl !== false && (typeof sdl !== "string" || sdl.trim() === "")) throw new TypeError("[znight] graphql.configure(): \"sdl\" must be a path relative to the project root ('schema.graphql') or false");
2764
+ const number = options.number === void 0 ? base.number : options.number;
2765
+ if (number !== "Float" && number !== "Int") throw new TypeError(`[znight] graphql.configure(): "number" must be 'Float' or 'Int'`);
2766
+ return Object.freeze({
2767
+ sdl,
2768
+ number
2769
+ });
2770
+ }
2771
+ // src/compiler/index.ts
2772
+ const FIELD = {
2773
+ targets: ["method"],
2774
+ params: ["static"]
2775
+ };
2776
+ const NO_ARGUMENT = {
2777
+ targets: ["parameter"],
2778
+ params: []
2779
+ };
2780
+ /** Decorators owned by the extension, by canonical identity (static / value arguments, §4.6). */
2781
+ const decorators = Object.freeze({
2782
+ [GraphQLIds.Resolver]: {
2783
+ targets: ["class"],
2784
+ params: ["static"]
2785
+ },
2786
+ [GraphQLIds.Query]: FIELD,
2787
+ [GraphQLIds.Mutation]: FIELD,
2788
+ [GraphQLIds.Subscription]: FIELD,
2789
+ [GraphQLIds.ResolveField]: FIELD,
2790
+ [GraphQLIds.Args]: {
2791
+ targets: ["parameter"],
2792
+ params: ["value", "value"]
2793
+ },
2794
+ [GraphQLIds.Parent]: NO_ARGUMENT,
2795
+ [GraphQLIds.Ctx]: NO_ARGUMENT,
2796
+ [GraphQLIds.Info]: NO_ARGUMENT,
2797
+ [GraphQLIds.Loader]: NO_ARGUMENT,
2798
+ [GraphQLIds.UseGuard]: {
2799
+ targets: ["class", "method"],
2800
+ params: [],
2801
+ rest: "value"
2802
+ }
2803
+ });
2804
+ function createExtension(options) {
2805
+ /**
2806
+ * Models by compile, built by `validate`, read by `generate`. The key is `graph.extensions`: the
2807
+ * validate and generate contexts of one compile get different graph objects sharing this array.
2808
+ */
2809
+ const models = /* @__PURE__ */ new WeakMap();
2810
+ const modelOf = (graph) => models.get(graph.extensions);
2811
+ return Object.freeze({
2812
+ apiVersion: 1,
2813
+ name: EXTENSION_NAME,
2814
+ decorators,
2815
+ options,
2816
+ analyzeClass: analyzeGraphQLClass,
2817
+ validate(ctx) {
2818
+ models.set(ctx.graph.extensions, buildModel(ctx, options));
2819
+ },
2820
+ generate(ctx) {
2821
+ return generateGraphQL(ctx, modelOf(ctx.graph), options);
2822
+ },
2823
+ configure(next) {
2824
+ return createExtension(resolveOptions(options, next));
2825
+ }
2826
+ });
2827
+ }
2828
+ /** The `@znight/graphql` compiler extension with its default options. */
2829
+ const graphqlCompilerExtension = createExtension(DEFAULT_OPTIONS);
2830
+ export { graphqlCompilerExtension as default, graphqlCompilerExtension };
2831
+
2832
+ //# sourceMappingURL=compiler.mjs.map