@effect-gql/core 0.1.0 → 1.1.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 (164) hide show
  1. package/README.md +100 -0
  2. package/builder/index.cjs +1446 -0
  3. package/builder/index.cjs.map +1 -0
  4. package/builder/index.d.cts +260 -0
  5. package/{dist/builder/pipe-api.d.ts → builder/index.d.ts} +50 -21
  6. package/builder/index.js +1405 -0
  7. package/builder/index.js.map +1 -0
  8. package/index.cjs +3469 -0
  9. package/index.cjs.map +1 -0
  10. package/index.d.cts +529 -0
  11. package/index.d.ts +529 -0
  12. package/index.js +3292 -0
  13. package/index.js.map +1 -0
  14. package/package.json +19 -28
  15. package/schema-builder-DKvkzU_M.d.cts +965 -0
  16. package/schema-builder-DKvkzU_M.d.ts +965 -0
  17. package/server/index.cjs +1579 -0
  18. package/server/index.cjs.map +1 -0
  19. package/server/index.d.cts +682 -0
  20. package/server/index.d.ts +682 -0
  21. package/server/index.js +1548 -0
  22. package/server/index.js.map +1 -0
  23. package/dist/analyzer-extension.d.ts +0 -105
  24. package/dist/analyzer-extension.d.ts.map +0 -1
  25. package/dist/analyzer-extension.js +0 -137
  26. package/dist/analyzer-extension.js.map +0 -1
  27. package/dist/builder/execute.d.ts +0 -26
  28. package/dist/builder/execute.d.ts.map +0 -1
  29. package/dist/builder/execute.js +0 -104
  30. package/dist/builder/execute.js.map +0 -1
  31. package/dist/builder/field-builders.d.ts +0 -30
  32. package/dist/builder/field-builders.d.ts.map +0 -1
  33. package/dist/builder/field-builders.js +0 -200
  34. package/dist/builder/field-builders.js.map +0 -1
  35. package/dist/builder/index.d.ts +0 -7
  36. package/dist/builder/index.d.ts.map +0 -1
  37. package/dist/builder/index.js +0 -31
  38. package/dist/builder/index.js.map +0 -1
  39. package/dist/builder/pipe-api.d.ts.map +0 -1
  40. package/dist/builder/pipe-api.js +0 -151
  41. package/dist/builder/pipe-api.js.map +0 -1
  42. package/dist/builder/schema-builder.d.ts +0 -301
  43. package/dist/builder/schema-builder.d.ts.map +0 -1
  44. package/dist/builder/schema-builder.js +0 -566
  45. package/dist/builder/schema-builder.js.map +0 -1
  46. package/dist/builder/type-registry.d.ts +0 -80
  47. package/dist/builder/type-registry.d.ts.map +0 -1
  48. package/dist/builder/type-registry.js +0 -505
  49. package/dist/builder/type-registry.js.map +0 -1
  50. package/dist/builder/types.d.ts +0 -283
  51. package/dist/builder/types.d.ts.map +0 -1
  52. package/dist/builder/types.js +0 -3
  53. package/dist/builder/types.js.map +0 -1
  54. package/dist/cli/generate-schema.d.ts +0 -29
  55. package/dist/cli/generate-schema.d.ts.map +0 -1
  56. package/dist/cli/generate-schema.js +0 -233
  57. package/dist/cli/generate-schema.js.map +0 -1
  58. package/dist/cli/index.d.ts +0 -19
  59. package/dist/cli/index.d.ts.map +0 -1
  60. package/dist/cli/index.js +0 -24
  61. package/dist/cli/index.js.map +0 -1
  62. package/dist/context.d.ts +0 -18
  63. package/dist/context.d.ts.map +0 -1
  64. package/dist/context.js +0 -11
  65. package/dist/context.js.map +0 -1
  66. package/dist/error.d.ts +0 -45
  67. package/dist/error.d.ts.map +0 -1
  68. package/dist/error.js +0 -29
  69. package/dist/error.js.map +0 -1
  70. package/dist/extensions.d.ts +0 -130
  71. package/dist/extensions.d.ts.map +0 -1
  72. package/dist/extensions.js +0 -78
  73. package/dist/extensions.js.map +0 -1
  74. package/dist/index.d.ts +0 -12
  75. package/dist/index.d.ts.map +0 -1
  76. package/dist/index.js +0 -47
  77. package/dist/index.js.map +0 -1
  78. package/dist/loader.d.ts +0 -169
  79. package/dist/loader.d.ts.map +0 -1
  80. package/dist/loader.js +0 -237
  81. package/dist/loader.js.map +0 -1
  82. package/dist/resolver-context.d.ts +0 -154
  83. package/dist/resolver-context.d.ts.map +0 -1
  84. package/dist/resolver-context.js +0 -184
  85. package/dist/resolver-context.js.map +0 -1
  86. package/dist/schema-mapping.d.ts +0 -30
  87. package/dist/schema-mapping.d.ts.map +0 -1
  88. package/dist/schema-mapping.js +0 -280
  89. package/dist/schema-mapping.js.map +0 -1
  90. package/dist/server/cache-control.d.ts +0 -96
  91. package/dist/server/cache-control.d.ts.map +0 -1
  92. package/dist/server/cache-control.js +0 -308
  93. package/dist/server/cache-control.js.map +0 -1
  94. package/dist/server/complexity.d.ts +0 -165
  95. package/dist/server/complexity.d.ts.map +0 -1
  96. package/dist/server/complexity.js +0 -433
  97. package/dist/server/complexity.js.map +0 -1
  98. package/dist/server/config.d.ts +0 -66
  99. package/dist/server/config.d.ts.map +0 -1
  100. package/dist/server/config.js +0 -104
  101. package/dist/server/config.js.map +0 -1
  102. package/dist/server/graphiql.d.ts +0 -5
  103. package/dist/server/graphiql.d.ts.map +0 -1
  104. package/dist/server/graphiql.js +0 -43
  105. package/dist/server/graphiql.js.map +0 -1
  106. package/dist/server/index.d.ts +0 -18
  107. package/dist/server/index.d.ts.map +0 -1
  108. package/dist/server/index.js +0 -48
  109. package/dist/server/index.js.map +0 -1
  110. package/dist/server/router.d.ts +0 -79
  111. package/dist/server/router.d.ts.map +0 -1
  112. package/dist/server/router.js +0 -232
  113. package/dist/server/router.js.map +0 -1
  114. package/dist/server/schema-builder-extensions.d.ts +0 -42
  115. package/dist/server/schema-builder-extensions.d.ts.map +0 -1
  116. package/dist/server/schema-builder-extensions.js +0 -48
  117. package/dist/server/schema-builder-extensions.js.map +0 -1
  118. package/dist/server/sse-adapter.d.ts +0 -64
  119. package/dist/server/sse-adapter.d.ts.map +0 -1
  120. package/dist/server/sse-adapter.js +0 -227
  121. package/dist/server/sse-adapter.js.map +0 -1
  122. package/dist/server/sse-types.d.ts +0 -192
  123. package/dist/server/sse-types.d.ts.map +0 -1
  124. package/dist/server/sse-types.js +0 -63
  125. package/dist/server/sse-types.js.map +0 -1
  126. package/dist/server/ws-adapter.d.ts +0 -39
  127. package/dist/server/ws-adapter.d.ts.map +0 -1
  128. package/dist/server/ws-adapter.js +0 -247
  129. package/dist/server/ws-adapter.js.map +0 -1
  130. package/dist/server/ws-types.d.ts +0 -169
  131. package/dist/server/ws-types.d.ts.map +0 -1
  132. package/dist/server/ws-types.js +0 -11
  133. package/dist/server/ws-types.js.map +0 -1
  134. package/dist/server/ws-utils.d.ts +0 -42
  135. package/dist/server/ws-utils.d.ts.map +0 -1
  136. package/dist/server/ws-utils.js +0 -99
  137. package/dist/server/ws-utils.js.map +0 -1
  138. package/src/analyzer-extension.ts +0 -254
  139. package/src/builder/execute.ts +0 -153
  140. package/src/builder/field-builders.ts +0 -322
  141. package/src/builder/index.ts +0 -48
  142. package/src/builder/pipe-api.ts +0 -312
  143. package/src/builder/schema-builder.ts +0 -970
  144. package/src/builder/type-registry.ts +0 -670
  145. package/src/builder/types.ts +0 -305
  146. package/src/context.ts +0 -23
  147. package/src/error.ts +0 -32
  148. package/src/extensions.ts +0 -240
  149. package/src/index.ts +0 -32
  150. package/src/loader.ts +0 -363
  151. package/src/resolver-context.ts +0 -253
  152. package/src/schema-mapping.ts +0 -307
  153. package/src/server/cache-control.ts +0 -590
  154. package/src/server/complexity.ts +0 -774
  155. package/src/server/config.ts +0 -174
  156. package/src/server/graphiql.ts +0 -38
  157. package/src/server/index.ts +0 -96
  158. package/src/server/router.ts +0 -432
  159. package/src/server/schema-builder-extensions.ts +0 -51
  160. package/src/server/sse-adapter.ts +0 -327
  161. package/src/server/sse-types.ts +0 -234
  162. package/src/server/ws-adapter.ts +0 -355
  163. package/src/server/ws-types.ts +0 -192
  164. package/src/server/ws-utils.ts +0 -136
package/index.cjs ADDED
@@ -0,0 +1,3469 @@
1
+ 'use strict';
2
+
3
+ var graphql = require('graphql');
4
+ var effect = require('effect');
5
+ var S2 = require('effect/Schema');
6
+ var AST = require('effect/SchemaAST');
7
+ var DataLoader = require('dataloader');
8
+ var platform = require('@effect/platform');
9
+ var graphqlWs = require('graphql-ws');
10
+
11
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
+
13
+ function _interopNamespace(e) {
14
+ if (e && e.__esModule) return e;
15
+ var n = Object.create(null);
16
+ if (e) {
17
+ Object.keys(e).forEach(function (k) {
18
+ if (k !== 'default') {
19
+ var d = Object.getOwnPropertyDescriptor(e, k);
20
+ Object.defineProperty(n, k, d.get ? d : {
21
+ enumerable: true,
22
+ get: function () { return e[k]; }
23
+ });
24
+ }
25
+ });
26
+ }
27
+ n.default = e;
28
+ return Object.freeze(n);
29
+ }
30
+
31
+ var S2__namespace = /*#__PURE__*/_interopNamespace(S2);
32
+ var AST__namespace = /*#__PURE__*/_interopNamespace(AST);
33
+ var DataLoader__default = /*#__PURE__*/_interopDefault(DataLoader);
34
+
35
+ // src/builder/index.ts
36
+ var isIntegerType = (ast) => {
37
+ if (ast._tag === "Refinement") {
38
+ const refinement = ast;
39
+ const annotations = refinement.annotations;
40
+ if (annotations) {
41
+ const identifier = AST__namespace.getIdentifierAnnotation(refinement);
42
+ if (identifier._tag === "Some" && identifier.value === "Int") {
43
+ return true;
44
+ }
45
+ }
46
+ return isIntegerType(refinement.from);
47
+ }
48
+ return false;
49
+ };
50
+ var toGraphQLType = (schema) => {
51
+ const ast = schema.ast;
52
+ if (ast._tag === "StringKeyword") return graphql.GraphQLString;
53
+ if (ast._tag === "NumberKeyword") return graphql.GraphQLFloat;
54
+ if (ast._tag === "BooleanKeyword") return graphql.GraphQLBoolean;
55
+ if (ast._tag === "Refinement") {
56
+ if (isIntegerType(ast)) {
57
+ return graphql.GraphQLInt;
58
+ }
59
+ return toGraphQLType(S2__namespace.make(ast.from));
60
+ }
61
+ if (ast._tag === "Literal") {
62
+ if (typeof ast.literal === "string") return graphql.GraphQLString;
63
+ if (typeof ast.literal === "number") {
64
+ return Number.isInteger(ast.literal) ? graphql.GraphQLInt : graphql.GraphQLFloat;
65
+ }
66
+ if (typeof ast.literal === "boolean") return graphql.GraphQLBoolean;
67
+ }
68
+ if (ast._tag === "TupleType") {
69
+ const elements = ast.elements;
70
+ if (elements.length > 0) {
71
+ const elementSchema = S2__namespace.make(elements[0].type);
72
+ return new graphql.GraphQLList(toGraphQLType(elementSchema));
73
+ }
74
+ }
75
+ if (ast._tag === "TypeLiteral") {
76
+ const fields = {};
77
+ for (const field2 of ast.propertySignatures) {
78
+ const fieldName = String(field2.name);
79
+ const fieldSchema = S2__namespace.make(field2.type);
80
+ let fieldType = toGraphQLType(fieldSchema);
81
+ if (!field2.isOptional) {
82
+ fieldType = new graphql.GraphQLNonNull(fieldType);
83
+ }
84
+ fields[fieldName] = { type: fieldType };
85
+ }
86
+ const typeName = schema.annotations?.identifier || `Object_${Math.random().toString(36).slice(2, 11)}`;
87
+ return new graphql.GraphQLObjectType({
88
+ name: typeName,
89
+ fields
90
+ });
91
+ }
92
+ if (ast._tag === "Transformation") {
93
+ return toGraphQLType(S2__namespace.make(ast.to));
94
+ }
95
+ if (ast._tag === "Union") {
96
+ const types = ast.types;
97
+ if (types.length > 0) {
98
+ return toGraphQLType(S2__namespace.make(types[0]));
99
+ }
100
+ }
101
+ if (ast._tag === "Suspend") {
102
+ const innerAst = ast.f();
103
+ return toGraphQLType(S2__namespace.make(innerAst));
104
+ }
105
+ return graphql.GraphQLString;
106
+ };
107
+ var toGraphQLInputType = (schema) => {
108
+ const ast = schema.ast;
109
+ if (ast._tag === "StringKeyword") return graphql.GraphQLString;
110
+ if (ast._tag === "NumberKeyword") return graphql.GraphQLFloat;
111
+ if (ast._tag === "BooleanKeyword") return graphql.GraphQLBoolean;
112
+ if (ast._tag === "Refinement") {
113
+ if (isIntegerType(ast)) {
114
+ return graphql.GraphQLInt;
115
+ }
116
+ return toGraphQLInputType(S2__namespace.make(ast.from));
117
+ }
118
+ if (ast._tag === "Literal") {
119
+ if (typeof ast.literal === "string") return graphql.GraphQLString;
120
+ if (typeof ast.literal === "number") {
121
+ return Number.isInteger(ast.literal) ? graphql.GraphQLInt : graphql.GraphQLFloat;
122
+ }
123
+ if (typeof ast.literal === "boolean") return graphql.GraphQLBoolean;
124
+ }
125
+ if (ast._tag === "TupleType") {
126
+ const elements = ast.elements;
127
+ if (elements.length > 0) {
128
+ const elementSchema = S2__namespace.make(elements[0].type);
129
+ return new graphql.GraphQLList(toGraphQLInputType(elementSchema));
130
+ }
131
+ }
132
+ if (ast._tag === "TypeLiteral") {
133
+ const fields = {};
134
+ for (const field2 of ast.propertySignatures) {
135
+ const fieldName = String(field2.name);
136
+ const fieldSchema = S2__namespace.make(field2.type);
137
+ let fieldType = toGraphQLInputType(fieldSchema);
138
+ if (!field2.isOptional) {
139
+ fieldType = new graphql.GraphQLNonNull(fieldType);
140
+ }
141
+ fields[fieldName] = { type: fieldType };
142
+ }
143
+ const typeName = schema.annotations?.identifier || `Input_${Math.random().toString(36).slice(2, 11)}`;
144
+ return new graphql.GraphQLInputObjectType({
145
+ name: typeName,
146
+ fields
147
+ });
148
+ }
149
+ if (ast._tag === "Transformation") {
150
+ return toGraphQLInputType(S2__namespace.make(ast.from));
151
+ }
152
+ if (ast._tag === "Union") {
153
+ const types = ast.types;
154
+ if (types.length > 0) {
155
+ return toGraphQLInputType(S2__namespace.make(types[0]));
156
+ }
157
+ }
158
+ if (ast._tag === "Suspend") {
159
+ const innerAst = ast.f();
160
+ return toGraphQLInputType(S2__namespace.make(innerAst));
161
+ }
162
+ return graphql.GraphQLString;
163
+ };
164
+ var toGraphQLObjectType = (name, schema, additionalFields) => {
165
+ const ast = schema.ast;
166
+ if (ast._tag === "TypeLiteral") {
167
+ const fields = {};
168
+ for (const field2 of ast.propertySignatures) {
169
+ const fieldName = String(field2.name);
170
+ const fieldSchema = S2__namespace.make(field2.type);
171
+ let fieldType = toGraphQLType(fieldSchema);
172
+ if (!field2.isOptional) {
173
+ fieldType = new graphql.GraphQLNonNull(fieldType);
174
+ }
175
+ fields[fieldName] = { type: fieldType };
176
+ }
177
+ if (additionalFields) {
178
+ for (const [fieldName, fieldConfig] of Object.entries(additionalFields)) {
179
+ fields[fieldName] = {
180
+ type: fieldConfig.type,
181
+ args: fieldConfig.args,
182
+ description: fieldConfig.description,
183
+ // Note: resolve will be set later when runtime is available
184
+ resolve: fieldConfig.resolve
185
+ };
186
+ }
187
+ }
188
+ return new graphql.GraphQLObjectType({
189
+ name,
190
+ fields
191
+ });
192
+ }
193
+ throw new Error(`Schema must be an object type to convert to GraphQLObjectType`);
194
+ };
195
+ var toGraphQLArgs = (schema) => {
196
+ const ast = schema.ast;
197
+ if (ast._tag === "TypeLiteral") {
198
+ const args = {};
199
+ for (const field2 of ast.propertySignatures) {
200
+ const fieldName = String(field2.name);
201
+ const fieldSchema = S2__namespace.make(field2.type);
202
+ let fieldType = toGraphQLInputType(fieldSchema);
203
+ if (!field2.isOptional) {
204
+ fieldType = new graphql.GraphQLNonNull(fieldType);
205
+ }
206
+ args[fieldName] = { type: fieldType };
207
+ }
208
+ return args;
209
+ }
210
+ throw new Error(`Schema must be an object type to convert to GraphQL arguments`);
211
+ };
212
+
213
+ // src/builder/type-registry.ts
214
+ function getSchemaName(schema) {
215
+ const ast = schema.ast;
216
+ if (ast._tag === "Transformation") {
217
+ const identifier = AST__namespace.getIdentifierAnnotation(ast.to);
218
+ if (identifier._tag === "Some") {
219
+ return identifier.value;
220
+ }
221
+ }
222
+ if (ast._tag === "TypeLiteral") {
223
+ const tagProp = ast.propertySignatures.find((p) => String(p.name) === "_tag");
224
+ if (tagProp && tagProp.type._tag === "Literal" && typeof tagProp.type.literal === "string") {
225
+ return tagProp.type.literal;
226
+ }
227
+ }
228
+ return void 0;
229
+ }
230
+ function buildReverseLookups(ctx) {
231
+ if (!ctx.schemaToTypeName) {
232
+ ctx.schemaToTypeName = /* @__PURE__ */ new Map();
233
+ ctx.astToTypeName = /* @__PURE__ */ new Map();
234
+ for (const [typeName, typeReg] of ctx.types) {
235
+ ctx.schemaToTypeName.set(typeReg.schema, typeName);
236
+ ctx.astToTypeName.set(typeReg.schema.ast, typeName);
237
+ }
238
+ }
239
+ if (!ctx.schemaToInterfaceName) {
240
+ ctx.schemaToInterfaceName = /* @__PURE__ */ new Map();
241
+ ctx.astToInterfaceName = /* @__PURE__ */ new Map();
242
+ for (const [interfaceName, interfaceReg] of ctx.interfaces) {
243
+ ctx.schemaToInterfaceName.set(interfaceReg.schema, interfaceName);
244
+ ctx.astToInterfaceName.set(interfaceReg.schema.ast, interfaceName);
245
+ }
246
+ }
247
+ if (!ctx.schemaToInputName) {
248
+ ctx.schemaToInputName = /* @__PURE__ */ new Map();
249
+ ctx.astToInputName = /* @__PURE__ */ new Map();
250
+ for (const [inputName, inputReg] of ctx.inputs) {
251
+ ctx.schemaToInputName.set(inputReg.schema, inputName);
252
+ ctx.astToInputName.set(inputReg.schema.ast, inputName);
253
+ }
254
+ }
255
+ if (!ctx.enumSortedValues) {
256
+ ctx.enumSortedValues = /* @__PURE__ */ new Map();
257
+ ctx.literalToEnumName = /* @__PURE__ */ new Map();
258
+ for (const [enumName, enumReg] of ctx.enums) {
259
+ ctx.enumSortedValues.set(enumName, [...enumReg.values].sort());
260
+ for (const value of enumReg.values) {
261
+ ctx.literalToEnumName.set(value, enumName);
262
+ }
263
+ }
264
+ }
265
+ if (!ctx.unionSortedTypes) {
266
+ ctx.unionSortedTypes = /* @__PURE__ */ new Map();
267
+ for (const [unionName, unionReg] of ctx.unions) {
268
+ ctx.unionSortedTypes.set(unionName, [...unionReg.types].sort());
269
+ }
270
+ }
271
+ }
272
+ var nonNullCache = /* @__PURE__ */ new WeakMap();
273
+ function getNonNull(type) {
274
+ let cached = nonNullCache.get(type);
275
+ if (!cached) {
276
+ cached = new graphql.GraphQLNonNull(type);
277
+ nonNullCache.set(type, cached);
278
+ }
279
+ return cached;
280
+ }
281
+ function toGraphQLTypeWithRegistry(schema, ctx) {
282
+ buildReverseLookups(ctx);
283
+ const ast = schema.ast;
284
+ const registeredType = findRegisteredType(schema, ast, ctx);
285
+ if (registeredType) return registeredType;
286
+ const registeredInterface = findRegisteredInterface(schema, ast, ctx);
287
+ if (registeredInterface) return registeredInterface;
288
+ if (ast._tag === "Transformation") {
289
+ return handleTransformationAST(ast, ctx);
290
+ }
291
+ if (ast._tag === "Union") {
292
+ return handleUnionAST(ast, ctx);
293
+ }
294
+ if (ast._tag === "Literal") {
295
+ const enumType2 = findEnumForLiteral(ast, ctx);
296
+ if (enumType2) return enumType2;
297
+ }
298
+ if (ast._tag === "TupleType") {
299
+ return handleTupleTypeAST(ast, ctx);
300
+ }
301
+ if (ast._tag === "Suspend") {
302
+ const innerAst = ast.f();
303
+ return toGraphQLTypeWithRegistry(S2__namespace.make(innerAst), ctx);
304
+ }
305
+ return toGraphQLType(schema);
306
+ }
307
+ function findRegisteredType(schema, ast, ctx) {
308
+ const typeName = ctx.schemaToTypeName?.get(schema) ?? ctx.astToTypeName?.get(ast);
309
+ if (typeName) {
310
+ return ctx.typeRegistry.get(typeName);
311
+ }
312
+ return void 0;
313
+ }
314
+ function findRegisteredInterface(schema, ast, ctx) {
315
+ const interfaceName = ctx.schemaToInterfaceName?.get(schema) ?? ctx.astToInterfaceName?.get(ast);
316
+ if (interfaceName) {
317
+ return ctx.interfaceRegistry.get(interfaceName);
318
+ }
319
+ return void 0;
320
+ }
321
+ function handleTransformationAST(ast, ctx) {
322
+ const toAst = ast.to;
323
+ if (toAst._tag === "TupleType") {
324
+ if (toAst.rest && toAst.rest.length > 0) {
325
+ const elementSchema = S2__namespace.make(toAst.rest[0].type);
326
+ const elementType = toGraphQLTypeWithRegistry(elementSchema, ctx);
327
+ return new graphql.GraphQLList(elementType);
328
+ } else if (toAst.elements.length > 0) {
329
+ const elementSchema = S2__namespace.make(toAst.elements[0].type);
330
+ const elementType = toGraphQLTypeWithRegistry(elementSchema, ctx);
331
+ return new graphql.GraphQLList(elementType);
332
+ }
333
+ }
334
+ return toGraphQLTypeWithRegistry(S2__namespace.make(ast.to), ctx);
335
+ }
336
+ function handleUnionAST(ast, ctx) {
337
+ const allLiterals = ast.types.every((t) => t._tag === "Literal");
338
+ if (allLiterals) {
339
+ const enumType2 = findEnumForLiteralUnion(ast.types, ctx);
340
+ if (enumType2) return enumType2;
341
+ } else {
342
+ const unionType2 = findRegisteredUnion(ast.types, ctx);
343
+ if (unionType2) return unionType2;
344
+ }
345
+ if (ast.types.length > 0) {
346
+ return toGraphQLTypeWithRegistry(S2__namespace.make(ast.types[0]), ctx);
347
+ }
348
+ return toGraphQLType(S2__namespace.make(ast));
349
+ }
350
+ function findEnumForLiteralUnion(types, ctx) {
351
+ const literalValues = types.map((t) => String(t.literal)).sort();
352
+ for (const [enumName] of ctx.enums) {
353
+ const enumValues = ctx.enumSortedValues?.get(enumName);
354
+ if (enumValues && literalValues.length === enumValues.length && literalValues.every((v, i) => v === enumValues[i])) {
355
+ return ctx.enumRegistry.get(enumName);
356
+ }
357
+ }
358
+ return void 0;
359
+ }
360
+ function findRegisteredUnion(types, ctx) {
361
+ const memberTags = [];
362
+ for (const memberAst of types) {
363
+ if (memberAst._tag === "TypeLiteral") {
364
+ const tagProp = memberAst.propertySignatures.find((p) => String(p.name) === "_tag");
365
+ if (tagProp && tagProp.type._tag === "Literal") {
366
+ memberTags.push(String(tagProp.type.literal));
367
+ }
368
+ }
369
+ }
370
+ if (memberTags.length === types.length) {
371
+ const sortedTags = memberTags.sort();
372
+ for (const [unionName] of ctx.unions) {
373
+ const unionTypes = ctx.unionSortedTypes?.get(unionName);
374
+ if (unionTypes && sortedTags.length === unionTypes.length && sortedTags.every((tag, i) => tag === unionTypes[i])) {
375
+ return ctx.unionRegistry.get(unionName);
376
+ }
377
+ }
378
+ }
379
+ return void 0;
380
+ }
381
+ function findEnumForLiteral(ast, ctx) {
382
+ const literalValue = String(ast.literal);
383
+ const enumName = ctx.literalToEnumName?.get(literalValue);
384
+ if (enumName) {
385
+ return ctx.enumRegistry.get(enumName);
386
+ }
387
+ return void 0;
388
+ }
389
+ function handleTupleTypeAST(ast, ctx) {
390
+ if (ast.rest && ast.rest.length > 0) {
391
+ const elementSchema = S2__namespace.make(ast.rest[0].type);
392
+ const elementType = toGraphQLTypeWithRegistry(elementSchema, ctx);
393
+ return new graphql.GraphQLList(elementType);
394
+ } else if (ast.elements && ast.elements.length > 0) {
395
+ const elementSchema = S2__namespace.make(ast.elements[0].type);
396
+ const elementType = toGraphQLTypeWithRegistry(elementSchema, ctx);
397
+ return new graphql.GraphQLList(elementType);
398
+ }
399
+ return toGraphQLType(S2__namespace.make(ast));
400
+ }
401
+ function schemaToFields(schema, ctx) {
402
+ let ast = schema.ast;
403
+ if (ast._tag === "Transformation") {
404
+ ast = ast.to;
405
+ }
406
+ if (ast._tag === "Declaration") {
407
+ const typeParams = ast.typeParameters;
408
+ if (typeParams && typeParams.length > 0 && typeParams[0]._tag === "TypeLiteral") {
409
+ ast = typeParams[0];
410
+ }
411
+ }
412
+ if (ast._tag === "TypeLiteral") {
413
+ const fields = {};
414
+ for (const field2 of ast.propertySignatures) {
415
+ const fieldName = String(field2.name);
416
+ const fieldSchema = S2__namespace.make(field2.type);
417
+ let fieldType = toGraphQLTypeWithRegistry(fieldSchema, ctx);
418
+ if (!field2.isOptional) {
419
+ fieldType = getNonNull(fieldType);
420
+ }
421
+ fields[fieldName] = { type: fieldType };
422
+ }
423
+ return fields;
424
+ }
425
+ return {};
426
+ }
427
+ function schemaToInputFields(schema, enumRegistry, inputRegistry, inputs, enums, cache) {
428
+ const ast = schema.ast;
429
+ if (ast._tag === "TypeLiteral") {
430
+ const fields = {};
431
+ for (const field2 of ast.propertySignatures) {
432
+ const fieldName = String(field2.name);
433
+ const fieldSchema = S2__namespace.make(field2.type);
434
+ let fieldType = toGraphQLInputTypeWithRegistry(
435
+ fieldSchema,
436
+ enumRegistry,
437
+ inputRegistry,
438
+ inputs,
439
+ enums,
440
+ cache
441
+ );
442
+ if (!field2.isOptional) {
443
+ fieldType = getNonNull(fieldType);
444
+ }
445
+ fields[fieldName] = { type: fieldType };
446
+ }
447
+ return fields;
448
+ }
449
+ return {};
450
+ }
451
+ function buildInputTypeLookupCache(inputs, enums) {
452
+ const cache = {
453
+ schemaToInputName: /* @__PURE__ */ new Map(),
454
+ astToInputName: /* @__PURE__ */ new Map(),
455
+ literalToEnumName: /* @__PURE__ */ new Map(),
456
+ enumSortedValues: /* @__PURE__ */ new Map()
457
+ };
458
+ for (const [inputName, inputReg] of inputs) {
459
+ cache.schemaToInputName.set(inputReg.schema, inputName);
460
+ cache.astToInputName.set(inputReg.schema.ast, inputName);
461
+ }
462
+ for (const [enumName, enumReg] of enums) {
463
+ cache.enumSortedValues.set(enumName, [...enumReg.values].sort());
464
+ for (const value of enumReg.values) {
465
+ cache.literalToEnumName.set(value, enumName);
466
+ }
467
+ }
468
+ return cache;
469
+ }
470
+ function toGraphQLInputTypeWithRegistry(schema, enumRegistry, inputRegistry, inputs, enums, cache) {
471
+ const ast = schema.ast;
472
+ if (ast._tag === "Transformation") {
473
+ const toAst = ast.to;
474
+ return toGraphQLInputTypeWithRegistry(
475
+ S2__namespace.make(toAst),
476
+ enumRegistry,
477
+ inputRegistry,
478
+ inputs,
479
+ enums,
480
+ cache
481
+ );
482
+ }
483
+ if (cache?.schemaToInputName || cache?.astToInputName) {
484
+ const inputName = cache.schemaToInputName?.get(schema) ?? cache.astToInputName?.get(ast);
485
+ if (inputName) {
486
+ const result = inputRegistry.get(inputName);
487
+ if (result) return result;
488
+ }
489
+ } else {
490
+ for (const [inputName, inputReg] of inputs) {
491
+ if (inputReg.schema.ast === ast || inputReg.schema === schema) {
492
+ const result = inputRegistry.get(inputName);
493
+ if (result) return result;
494
+ }
495
+ }
496
+ }
497
+ if (ast._tag === "Union") {
498
+ const unionAst = ast;
499
+ const nonUndefinedTypes = unionAst.types.filter((t) => t._tag !== "UndefinedKeyword");
500
+ if (nonUndefinedTypes.length === 1 && nonUndefinedTypes[0]._tag === "Union") {
501
+ return toGraphQLInputTypeWithRegistry(
502
+ S2__namespace.make(nonUndefinedTypes[0]),
503
+ enumRegistry,
504
+ inputRegistry,
505
+ inputs,
506
+ enums,
507
+ cache
508
+ );
509
+ }
510
+ if (nonUndefinedTypes.length === 1 && nonUndefinedTypes[0]._tag === "TypeLiteral") {
511
+ return toGraphQLInputTypeWithRegistry(
512
+ S2__namespace.make(nonUndefinedTypes[0]),
513
+ enumRegistry,
514
+ inputRegistry,
515
+ inputs,
516
+ enums,
517
+ cache
518
+ );
519
+ }
520
+ const allLiterals = unionAst.types.every((t) => t._tag === "Literal");
521
+ if (allLiterals) {
522
+ const literalValues = unionAst.types.map((t) => String(t.literal)).sort();
523
+ for (const [enumName] of enums) {
524
+ const enumValues = cache?.enumSortedValues?.get(enumName) ?? [...enums.get(enumName).values].sort();
525
+ if (literalValues.length === enumValues.length && literalValues.every((v, i) => v === enumValues[i])) {
526
+ const result = enumRegistry.get(enumName);
527
+ if (result) return result;
528
+ }
529
+ }
530
+ }
531
+ }
532
+ if (ast._tag === "Literal") {
533
+ const literalValue = String(ast.literal);
534
+ if (cache?.literalToEnumName) {
535
+ const enumName = cache.literalToEnumName.get(literalValue);
536
+ if (enumName) {
537
+ const result = enumRegistry.get(enumName);
538
+ if (result) return result;
539
+ }
540
+ } else {
541
+ for (const [enumName, enumReg] of enums) {
542
+ if (enumReg.values.includes(literalValue)) {
543
+ const result = enumRegistry.get(enumName);
544
+ if (result) return result;
545
+ }
546
+ }
547
+ }
548
+ }
549
+ if (ast._tag === "Suspend") {
550
+ const innerAst = ast.f();
551
+ return toGraphQLInputTypeWithRegistry(
552
+ S2__namespace.make(innerAst),
553
+ enumRegistry,
554
+ inputRegistry,
555
+ inputs,
556
+ enums,
557
+ cache
558
+ );
559
+ }
560
+ return toGraphQLInputType(schema);
561
+ }
562
+ function toGraphQLArgsWithRegistry(schema, enumRegistry, inputRegistry, inputs, enums, cache) {
563
+ const ast = schema.ast;
564
+ if (ast._tag === "TypeLiteral") {
565
+ const args = {};
566
+ for (const field2 of ast.propertySignatures) {
567
+ const fieldName = String(field2.name);
568
+ const fieldSchema = S2__namespace.make(field2.type);
569
+ let fieldType = toGraphQLInputTypeWithRegistry(
570
+ fieldSchema,
571
+ enumRegistry,
572
+ inputRegistry,
573
+ inputs,
574
+ enums,
575
+ cache
576
+ );
577
+ if (!field2.isOptional) {
578
+ fieldType = getNonNull(fieldType);
579
+ }
580
+ args[fieldName] = { type: fieldType };
581
+ }
582
+ return args;
583
+ }
584
+ return toGraphQLArgs(schema);
585
+ }
586
+ function applyDirectives(effect, directives, directiveRegistrations) {
587
+ if (!directives) return effect;
588
+ let wrapped = effect;
589
+ for (const directiveApp of directives) {
590
+ const directiveReg = directiveRegistrations.get(directiveApp.name);
591
+ if (directiveReg?.apply) {
592
+ wrapped = directiveReg.apply(directiveApp.args ?? {})(wrapped);
593
+ }
594
+ }
595
+ return wrapped;
596
+ }
597
+ function applyMiddleware(effect, context, middlewares) {
598
+ if (middlewares.length === 0) return effect;
599
+ let wrapped = effect;
600
+ for (let i = middlewares.length - 1; i >= 0; i--) {
601
+ const middleware2 = middlewares[i];
602
+ if (middleware2.match && !middleware2.match(context.info)) {
603
+ continue;
604
+ }
605
+ wrapped = middleware2.apply(wrapped, context);
606
+ }
607
+ return wrapped;
608
+ }
609
+ function buildField(config, ctx) {
610
+ const fieldConfig = {
611
+ type: toGraphQLTypeWithRegistry(config.type, ctx),
612
+ resolve: async (_parent, args, context, info) => {
613
+ let effect$1 = applyDirectives(
614
+ config.resolve(args),
615
+ config.directives,
616
+ ctx.directiveRegistrations
617
+ );
618
+ const middlewareContext = { parent: _parent, args, info };
619
+ effect$1 = applyMiddleware(effect$1, middlewareContext, ctx.middlewares);
620
+ return await effect.Runtime.runPromise(context.runtime)(effect$1);
621
+ }
622
+ };
623
+ if (config.args) {
624
+ fieldConfig.args = toGraphQLArgsWithRegistry(
625
+ config.args,
626
+ ctx.enumRegistry,
627
+ ctx.inputRegistry,
628
+ ctx.inputs,
629
+ ctx.enums,
630
+ ctx.inputTypeLookupCache
631
+ );
632
+ }
633
+ if (config.description) {
634
+ fieldConfig.description = config.description;
635
+ }
636
+ return fieldConfig;
637
+ }
638
+ function buildObjectField(config, ctx) {
639
+ const fieldConfig = {
640
+ type: toGraphQLTypeWithRegistry(config.type, ctx),
641
+ resolve: async (parent, args, context, info) => {
642
+ let effect$1 = applyDirectives(
643
+ config.resolve(parent, args),
644
+ config.directives,
645
+ ctx.directiveRegistrations
646
+ );
647
+ const middlewareContext = { parent, args, info };
648
+ effect$1 = applyMiddleware(effect$1, middlewareContext, ctx.middlewares);
649
+ return await effect.Runtime.runPromise(context.runtime)(effect$1);
650
+ }
651
+ };
652
+ if (config.args) {
653
+ fieldConfig.args = toGraphQLArgsWithRegistry(
654
+ config.args,
655
+ ctx.enumRegistry,
656
+ ctx.inputRegistry,
657
+ ctx.inputs,
658
+ ctx.enums,
659
+ ctx.inputTypeLookupCache
660
+ );
661
+ }
662
+ if (config.description) {
663
+ fieldConfig.description = config.description;
664
+ }
665
+ return fieldConfig;
666
+ }
667
+ function buildSubscriptionField(config, ctx) {
668
+ const fieldConfig = {
669
+ type: toGraphQLTypeWithRegistry(config.type, ctx),
670
+ // The subscribe function returns an AsyncIterator
671
+ subscribe: async (_parent, args, context, info) => {
672
+ let subscribeEffect = config.subscribe(args);
673
+ subscribeEffect = applyDirectives(
674
+ subscribeEffect,
675
+ config.directives,
676
+ ctx.directiveRegistrations
677
+ );
678
+ const middlewareContext = { parent: _parent, args, info };
679
+ subscribeEffect = applyMiddleware(subscribeEffect, middlewareContext, ctx.middlewares);
680
+ const stream = await effect.Runtime.runPromise(context.runtime)(subscribeEffect);
681
+ return streamToAsyncIterator(stream, context.runtime);
682
+ },
683
+ // The resolve function transforms each yielded value
684
+ // If no custom resolve is provided, return the payload directly
685
+ resolve: config.resolve ? async (value, args, context, info) => {
686
+ let effect$1 = config.resolve(value, args);
687
+ const middlewareContext = { parent: value, args, info };
688
+ effect$1 = applyMiddleware(effect$1, middlewareContext, ctx.middlewares);
689
+ return await effect.Runtime.runPromise(context.runtime)(effect$1);
690
+ } : (value) => value
691
+ };
692
+ if (config.args) {
693
+ fieldConfig.args = toGraphQLArgsWithRegistry(
694
+ config.args,
695
+ ctx.enumRegistry,
696
+ ctx.inputRegistry,
697
+ ctx.inputs,
698
+ ctx.enums,
699
+ ctx.inputTypeLookupCache
700
+ );
701
+ }
702
+ if (config.description) {
703
+ fieldConfig.description = config.description;
704
+ }
705
+ return fieldConfig;
706
+ }
707
+ function streamToAsyncIterator(stream, runtime) {
708
+ let queue;
709
+ let fiber;
710
+ let initialized = false;
711
+ let done = false;
712
+ const initialize = async () => {
713
+ if (initialized) return;
714
+ initialized = true;
715
+ queue = await effect.Runtime.runPromise(runtime)(effect.Queue.unbounded());
716
+ fiber = effect.Runtime.runFork(runtime)(
717
+ effect.Effect.ensuring(
718
+ effect.Stream.runForEach(stream, (value) => effect.Queue.offer(queue, effect.Option.some(value))),
719
+ // Signal completion by pushing None
720
+ effect.Queue.offer(queue, effect.Option.none())
721
+ )
722
+ );
723
+ };
724
+ return {
725
+ [Symbol.asyncIterator]() {
726
+ return this;
727
+ },
728
+ async next() {
729
+ await initialize();
730
+ if (done) {
731
+ return { done: true, value: void 0 };
732
+ }
733
+ try {
734
+ const optionValue = await effect.Runtime.runPromise(runtime)(effect.Queue.take(queue));
735
+ if (effect.Option.isNone(optionValue)) {
736
+ done = true;
737
+ return { done: true, value: void 0 };
738
+ }
739
+ return { done: false, value: optionValue.value };
740
+ } catch (error) {
741
+ done = true;
742
+ throw error;
743
+ }
744
+ },
745
+ async return() {
746
+ done = true;
747
+ if (initialized) {
748
+ try {
749
+ await effect.Runtime.runPromise(runtime)(
750
+ effect.Fiber.interrupt(fiber)
751
+ );
752
+ await effect.Runtime.runPromise(runtime)(effect.Queue.shutdown(queue));
753
+ } catch {
754
+ }
755
+ }
756
+ return { done: true, value: void 0 };
757
+ }
758
+ };
759
+ }
760
+
761
+ // src/builder/schema-builder.ts
762
+ function updateState(state, key, value) {
763
+ return { ...state, [key]: value };
764
+ }
765
+ var GraphQLSchemaBuilder = class _GraphQLSchemaBuilder {
766
+ constructor(state) {
767
+ this.state = state;
768
+ }
769
+ pipe() {
770
+ return effect.Pipeable.pipeArguments(this, arguments);
771
+ }
772
+ /**
773
+ * Create an empty schema builder
774
+ */
775
+ static empty = new _GraphQLSchemaBuilder({
776
+ types: /* @__PURE__ */ new Map(),
777
+ interfaces: /* @__PURE__ */ new Map(),
778
+ enums: /* @__PURE__ */ new Map(),
779
+ unions: /* @__PURE__ */ new Map(),
780
+ inputs: /* @__PURE__ */ new Map(),
781
+ directives: /* @__PURE__ */ new Map(),
782
+ middlewares: [],
783
+ extensions: [],
784
+ queries: /* @__PURE__ */ new Map(),
785
+ mutations: /* @__PURE__ */ new Map(),
786
+ subscriptions: /* @__PURE__ */ new Map(),
787
+ objectFields: /* @__PURE__ */ new Map()
788
+ });
789
+ /**
790
+ * Create a new builder with updated state
791
+ */
792
+ with(newState) {
793
+ return new _GraphQLSchemaBuilder(newState);
794
+ }
795
+ // ============================================================================
796
+ // Registration Methods
797
+ // ============================================================================
798
+ /**
799
+ * Add a query field
800
+ */
801
+ query(name, config) {
802
+ const newQueries = new Map(this.state.queries);
803
+ newQueries.set(name, config);
804
+ return this.with(updateState(this.state, "queries", newQueries));
805
+ }
806
+ /**
807
+ * Add a mutation field
808
+ */
809
+ mutation(name, config) {
810
+ const newMutations = new Map(this.state.mutations);
811
+ newMutations.set(name, config);
812
+ return this.with(updateState(this.state, "mutations", newMutations));
813
+ }
814
+ /**
815
+ * Add a subscription field
816
+ *
817
+ * Subscriptions return a Stream that yields values over time.
818
+ * The subscribe function returns an Effect that produces a Stream.
819
+ *
820
+ * @example
821
+ * ```typescript
822
+ * builder.subscription("userCreated", {
823
+ * type: User,
824
+ * subscribe: Effect.gen(function*() {
825
+ * const pubsub = yield* PubSubService
826
+ * return pubsub.subscribe("USER_CREATED")
827
+ * }),
828
+ * })
829
+ * ```
830
+ */
831
+ subscription(name, config) {
832
+ const newSubscriptions = new Map(this.state.subscriptions);
833
+ newSubscriptions.set(name, config);
834
+ return this.with(updateState(this.state, "subscriptions", newSubscriptions));
835
+ }
836
+ /**
837
+ * Register an object type from a schema
838
+ */
839
+ objectType(config) {
840
+ const {
841
+ schema,
842
+ description,
843
+ implements: implementsInterfaces,
844
+ directives,
845
+ cacheControl,
846
+ fields
847
+ } = config;
848
+ const name = config.name ?? getSchemaName(schema);
849
+ if (!name) {
850
+ throw new Error(
851
+ "objectType requires a name. Either provide one explicitly or use a TaggedStruct/TaggedClass/Schema.Class"
852
+ );
853
+ }
854
+ const newTypes = new Map(this.state.types);
855
+ newTypes.set(name, {
856
+ name,
857
+ schema,
858
+ description,
859
+ implements: implementsInterfaces,
860
+ directives,
861
+ cacheControl
862
+ });
863
+ let newObjectFields = this.state.objectFields;
864
+ if (fields) {
865
+ newObjectFields = new Map(this.state.objectFields);
866
+ const typeFields = /* @__PURE__ */ new Map();
867
+ for (const [fieldName, fieldConfig] of Object.entries(fields)) {
868
+ typeFields.set(fieldName, fieldConfig);
869
+ }
870
+ newObjectFields.set(name, typeFields);
871
+ }
872
+ return this.with({
873
+ ...this.state,
874
+ types: newTypes,
875
+ objectFields: newObjectFields
876
+ });
877
+ }
878
+ /**
879
+ * Register an interface type from a schema
880
+ */
881
+ interfaceType(config) {
882
+ const { schema, resolveType, directives } = config;
883
+ const name = config.name ?? getSchemaName(schema);
884
+ if (!name) {
885
+ throw new Error(
886
+ "interfaceType requires a name. Either provide one explicitly or use a TaggedStruct/TaggedClass/Schema.Class"
887
+ );
888
+ }
889
+ const newInterfaces = new Map(this.state.interfaces);
890
+ newInterfaces.set(name, {
891
+ name,
892
+ schema,
893
+ resolveType: resolveType ?? ((value) => value._tag),
894
+ directives
895
+ });
896
+ return this.with(updateState(this.state, "interfaces", newInterfaces));
897
+ }
898
+ /**
899
+ * Register an enum type
900
+ */
901
+ enumType(config) {
902
+ const { name, values, description, directives } = config;
903
+ const newEnums = new Map(this.state.enums);
904
+ newEnums.set(name, { name, values, description, directives });
905
+ return this.with(updateState(this.state, "enums", newEnums));
906
+ }
907
+ /**
908
+ * Register a union type
909
+ */
910
+ unionType(config) {
911
+ const { name, types, resolveType, directives } = config;
912
+ const newUnions = new Map(this.state.unions);
913
+ newUnions.set(name, {
914
+ name,
915
+ types,
916
+ resolveType: resolveType ?? ((value) => value._tag),
917
+ directives
918
+ });
919
+ return this.with(updateState(this.state, "unions", newUnions));
920
+ }
921
+ /**
922
+ * Register an input type
923
+ */
924
+ inputType(config) {
925
+ const { schema, description, directives } = config;
926
+ const name = config.name ?? getSchemaName(schema);
927
+ if (!name) {
928
+ throw new Error(
929
+ "inputType requires a name. Either provide one explicitly or use a TaggedStruct/TaggedClass/Schema.Class"
930
+ );
931
+ }
932
+ const newInputs = new Map(this.state.inputs);
933
+ newInputs.set(name, { name, schema, description, directives });
934
+ return this.with(updateState(this.state, "inputs", newInputs));
935
+ }
936
+ /**
937
+ * Register a directive
938
+ */
939
+ directive(config) {
940
+ const newDirectives = new Map(this.state.directives);
941
+ newDirectives.set(config.name, config);
942
+ return this.with(updateState(this.state, "directives", newDirectives));
943
+ }
944
+ /**
945
+ * Register a middleware
946
+ *
947
+ * Middleware wraps all resolvers (or those matching a pattern) and executes
948
+ * in an "onion" model - first registered middleware is the outermost layer.
949
+ *
950
+ * @param config.name - Middleware name (for debugging/logging)
951
+ * @param config.description - Optional description
952
+ * @param config.match - Optional predicate to filter which fields this applies to
953
+ * @param config.apply - Function that transforms the resolver Effect
954
+ *
955
+ * @example
956
+ * ```typescript
957
+ * builder.middleware({
958
+ * name: "logging",
959
+ * apply: (effect, ctx) => Effect.gen(function*() {
960
+ * yield* Effect.logInfo(`Resolving ${ctx.info.fieldName}`)
961
+ * const start = Date.now()
962
+ * const result = yield* effect
963
+ * yield* Effect.logInfo(`Resolved in ${Date.now() - start}ms`)
964
+ * return result
965
+ * })
966
+ * })
967
+ * ```
968
+ */
969
+ middleware(config) {
970
+ const newMiddlewares = [...this.state.middlewares, config];
971
+ return this.with({ ...this.state, middlewares: newMiddlewares });
972
+ }
973
+ /**
974
+ * Register an extension
975
+ *
976
+ * Extensions provide lifecycle hooks that run at each phase of request processing
977
+ * (parse, validate, execute) and can contribute data to the response's extensions field.
978
+ *
979
+ * @param config.name - Extension name (for debugging/logging)
980
+ * @param config.description - Optional description
981
+ * @param config.onParse - Called after query parsing
982
+ * @param config.onValidate - Called after validation
983
+ * @param config.onExecuteStart - Called before execution begins
984
+ * @param config.onExecuteEnd - Called after execution completes
985
+ *
986
+ * @example
987
+ * ```typescript
988
+ * builder.extension({
989
+ * name: "tracing",
990
+ * onExecuteStart: () => Effect.gen(function*() {
991
+ * const ext = yield* ExtensionsService
992
+ * yield* ext.set("tracing", { startTime: Date.now() })
993
+ * }),
994
+ * onExecuteEnd: () => Effect.gen(function*() {
995
+ * const ext = yield* ExtensionsService
996
+ * yield* ext.merge("tracing", { endTime: Date.now() })
997
+ * }),
998
+ * })
999
+ * ```
1000
+ */
1001
+ extension(config) {
1002
+ const newExtensions = [...this.state.extensions, config];
1003
+ return this.with({ ...this.state, extensions: newExtensions });
1004
+ }
1005
+ /**
1006
+ * Get the registered extensions for use by the execution layer
1007
+ */
1008
+ getExtensions() {
1009
+ return this.state.extensions;
1010
+ }
1011
+ /**
1012
+ * Add a computed/relational field to an object type
1013
+ */
1014
+ field(typeName, fieldName, config) {
1015
+ const newObjectFields = new Map(this.state.objectFields);
1016
+ const typeFields = newObjectFields.get(typeName) || /* @__PURE__ */ new Map();
1017
+ typeFields.set(fieldName, config);
1018
+ newObjectFields.set(typeName, typeFields);
1019
+ return this.with(updateState(this.state, "objectFields", newObjectFields));
1020
+ }
1021
+ // ============================================================================
1022
+ // Schema Building
1023
+ // ============================================================================
1024
+ /**
1025
+ * Get the field complexity map for use in complexity validation.
1026
+ * Maps "TypeName.fieldName" to the complexity value or function.
1027
+ */
1028
+ getFieldComplexities() {
1029
+ const complexities = /* @__PURE__ */ new Map();
1030
+ for (const [name, config] of this.state.queries) {
1031
+ if (config.complexity !== void 0) {
1032
+ complexities.set(`Query.${name}`, config.complexity);
1033
+ }
1034
+ }
1035
+ for (const [name, config] of this.state.mutations) {
1036
+ if (config.complexity !== void 0) {
1037
+ complexities.set(`Mutation.${name}`, config.complexity);
1038
+ }
1039
+ }
1040
+ for (const [name, config] of this.state.subscriptions) {
1041
+ if (config.complexity !== void 0) {
1042
+ complexities.set(`Subscription.${name}`, config.complexity);
1043
+ }
1044
+ }
1045
+ for (const [typeName, fields] of this.state.objectFields) {
1046
+ for (const [fieldName, config] of fields) {
1047
+ if (config.complexity !== void 0) {
1048
+ complexities.set(`${typeName}.${fieldName}`, config.complexity);
1049
+ }
1050
+ }
1051
+ }
1052
+ return complexities;
1053
+ }
1054
+ /**
1055
+ * Get the cache hint map for use in cache control calculation.
1056
+ * Maps "TypeName.fieldName" to the cache hint for field-level hints,
1057
+ * or "TypeName" to the cache hint for type-level hints.
1058
+ */
1059
+ getCacheHints() {
1060
+ const hints = /* @__PURE__ */ new Map();
1061
+ for (const [typeName, typeReg] of this.state.types) {
1062
+ if (typeReg.cacheControl !== void 0) {
1063
+ hints.set(typeName, typeReg.cacheControl);
1064
+ }
1065
+ }
1066
+ for (const [name, config] of this.state.queries) {
1067
+ if (config.cacheControl !== void 0) {
1068
+ hints.set(`Query.${name}`, config.cacheControl);
1069
+ }
1070
+ }
1071
+ for (const [name, config] of this.state.subscriptions) {
1072
+ if (config.cacheControl !== void 0) {
1073
+ hints.set(`Subscription.${name}`, config.cacheControl);
1074
+ }
1075
+ }
1076
+ for (const [typeName, fields] of this.state.objectFields) {
1077
+ for (const [fieldName, config] of fields) {
1078
+ if (config.cacheControl !== void 0) {
1079
+ hints.set(`${typeName}.${fieldName}`, config.cacheControl);
1080
+ }
1081
+ }
1082
+ }
1083
+ return hints;
1084
+ }
1085
+ /**
1086
+ * Build the GraphQL schema (no services required)
1087
+ */
1088
+ buildSchema() {
1089
+ const directiveRegistry = this.buildDirectiveRegistry();
1090
+ const enumRegistry = this.buildEnumRegistry();
1091
+ const inputRegistry = this.buildInputRegistry(enumRegistry);
1092
+ const interfaceRegistry = this.buildInterfaceRegistry(enumRegistry);
1093
+ const { typeRegistry, unionRegistry } = this.buildTypeAndUnionRegistries(
1094
+ enumRegistry,
1095
+ interfaceRegistry
1096
+ );
1097
+ const fieldCtx = this.createFieldBuilderContext(
1098
+ typeRegistry,
1099
+ interfaceRegistry,
1100
+ enumRegistry,
1101
+ unionRegistry,
1102
+ inputRegistry
1103
+ );
1104
+ const queryFields = this.buildQueryFields(fieldCtx);
1105
+ const mutationFields = this.buildMutationFields(fieldCtx);
1106
+ const subscriptionFields = this.buildSubscriptionFields(fieldCtx);
1107
+ return this.assembleSchema({
1108
+ directiveRegistry,
1109
+ enumRegistry,
1110
+ inputRegistry,
1111
+ interfaceRegistry,
1112
+ typeRegistry,
1113
+ unionRegistry,
1114
+ queryFields,
1115
+ mutationFields,
1116
+ subscriptionFields
1117
+ });
1118
+ }
1119
+ buildDirectiveRegistry() {
1120
+ const registry = /* @__PURE__ */ new Map();
1121
+ const cache = buildInputTypeLookupCache(this.state.inputs, this.state.enums);
1122
+ for (const [name, reg] of this.state.directives) {
1123
+ const graphqlDirective = new graphql.GraphQLDirective({
1124
+ name,
1125
+ description: reg.description,
1126
+ locations: [...reg.locations],
1127
+ args: reg.args ? toGraphQLArgsWithRegistry(
1128
+ reg.args,
1129
+ /* @__PURE__ */ new Map(),
1130
+ /* @__PURE__ */ new Map(),
1131
+ this.state.inputs,
1132
+ this.state.enums,
1133
+ cache
1134
+ ) : void 0
1135
+ });
1136
+ registry.set(name, graphqlDirective);
1137
+ }
1138
+ return registry;
1139
+ }
1140
+ buildEnumRegistry() {
1141
+ const registry = /* @__PURE__ */ new Map();
1142
+ for (const [name, reg] of this.state.enums) {
1143
+ const enumValues = {};
1144
+ for (const value of reg.values) {
1145
+ enumValues[value] = { value };
1146
+ }
1147
+ registry.set(
1148
+ name,
1149
+ new graphql.GraphQLEnumType({
1150
+ name,
1151
+ values: enumValues,
1152
+ description: reg.description,
1153
+ extensions: reg.directives ? { directives: reg.directives } : void 0
1154
+ })
1155
+ );
1156
+ }
1157
+ return registry;
1158
+ }
1159
+ buildInputRegistry(enumRegistry) {
1160
+ const registry = /* @__PURE__ */ new Map();
1161
+ const cache = buildInputTypeLookupCache(this.state.inputs, this.state.enums);
1162
+ for (const [name, reg] of this.state.inputs) {
1163
+ const inputType2 = new graphql.GraphQLInputObjectType({
1164
+ name,
1165
+ description: reg.description,
1166
+ fields: () => schemaToInputFields(
1167
+ reg.schema,
1168
+ enumRegistry,
1169
+ registry,
1170
+ this.state.inputs,
1171
+ this.state.enums,
1172
+ cache
1173
+ ),
1174
+ extensions: reg.directives ? { directives: reg.directives } : void 0
1175
+ });
1176
+ registry.set(name, inputType2);
1177
+ }
1178
+ return registry;
1179
+ }
1180
+ buildInterfaceRegistry(enumRegistry) {
1181
+ const registry = /* @__PURE__ */ new Map();
1182
+ const typeRegistry = /* @__PURE__ */ new Map();
1183
+ const unionRegistry = /* @__PURE__ */ new Map();
1184
+ const sharedCtx = {
1185
+ types: this.state.types,
1186
+ interfaces: this.state.interfaces,
1187
+ enums: this.state.enums,
1188
+ unions: this.state.unions,
1189
+ inputs: this.state.inputs,
1190
+ typeRegistry,
1191
+ interfaceRegistry: registry,
1192
+ enumRegistry,
1193
+ unionRegistry};
1194
+ buildReverseLookups(sharedCtx);
1195
+ for (const [name, reg] of this.state.interfaces) {
1196
+ const interfaceType2 = new graphql.GraphQLInterfaceType({
1197
+ name,
1198
+ fields: () => schemaToFields(reg.schema, sharedCtx),
1199
+ resolveType: reg.resolveType,
1200
+ extensions: reg.directives ? { directives: reg.directives } : void 0
1201
+ });
1202
+ registry.set(name, interfaceType2);
1203
+ }
1204
+ return registry;
1205
+ }
1206
+ buildTypeAndUnionRegistries(enumRegistry, interfaceRegistry) {
1207
+ const typeRegistry = /* @__PURE__ */ new Map();
1208
+ const unionRegistry = /* @__PURE__ */ new Map();
1209
+ const sharedCtx = {
1210
+ types: this.state.types,
1211
+ interfaces: this.state.interfaces,
1212
+ enums: this.state.enums,
1213
+ unions: this.state.unions,
1214
+ inputs: this.state.inputs,
1215
+ typeRegistry,
1216
+ interfaceRegistry,
1217
+ enumRegistry,
1218
+ unionRegistry};
1219
+ buildReverseLookups(sharedCtx);
1220
+ const sharedFieldCtx = this.createFieldBuilderContext(
1221
+ typeRegistry,
1222
+ interfaceRegistry,
1223
+ enumRegistry,
1224
+ unionRegistry,
1225
+ /* @__PURE__ */ new Map()
1226
+ );
1227
+ for (const [typeName, typeReg] of this.state.types) {
1228
+ const implementedInterfaces = typeReg.implements?.map((name) => interfaceRegistry.get(name)).filter(Boolean) ?? [];
1229
+ const graphqlType = new graphql.GraphQLObjectType({
1230
+ name: typeName,
1231
+ description: typeReg.description,
1232
+ fields: () => {
1233
+ const baseFields = schemaToFields(typeReg.schema, sharedCtx);
1234
+ const additionalFields = this.state.objectFields.get(typeName);
1235
+ if (additionalFields) {
1236
+ for (const [fieldName, fieldConfig] of additionalFields) {
1237
+ baseFields[fieldName] = buildObjectField(fieldConfig, sharedFieldCtx);
1238
+ }
1239
+ }
1240
+ return baseFields;
1241
+ },
1242
+ interfaces: implementedInterfaces.length > 0 ? implementedInterfaces : void 0,
1243
+ extensions: typeReg.directives ? { directives: typeReg.directives } : void 0
1244
+ });
1245
+ typeRegistry.set(typeName, graphqlType);
1246
+ }
1247
+ for (const [name, reg] of this.state.unions) {
1248
+ const unionType2 = new graphql.GraphQLUnionType({
1249
+ name,
1250
+ types: () => reg.types.map((typeName) => typeRegistry.get(typeName)).filter(Boolean),
1251
+ resolveType: reg.resolveType,
1252
+ extensions: reg.directives ? { directives: reg.directives } : void 0
1253
+ });
1254
+ unionRegistry.set(name, unionType2);
1255
+ }
1256
+ return { typeRegistry, unionRegistry };
1257
+ }
1258
+ createFieldBuilderContext(typeRegistry, interfaceRegistry, enumRegistry, unionRegistry, inputRegistry) {
1259
+ const inputTypeLookupCache = buildInputTypeLookupCache(this.state.inputs, this.state.enums);
1260
+ return {
1261
+ types: this.state.types,
1262
+ interfaces: this.state.interfaces,
1263
+ enums: this.state.enums,
1264
+ unions: this.state.unions,
1265
+ inputs: this.state.inputs,
1266
+ typeRegistry,
1267
+ interfaceRegistry,
1268
+ enumRegistry,
1269
+ unionRegistry,
1270
+ inputRegistry,
1271
+ directiveRegistrations: this.state.directives,
1272
+ middlewares: this.state.middlewares,
1273
+ inputTypeLookupCache
1274
+ };
1275
+ }
1276
+ buildQueryFields(ctx) {
1277
+ const fields = {};
1278
+ for (const [name, config] of this.state.queries) {
1279
+ fields[name] = buildField(config, ctx);
1280
+ }
1281
+ return fields;
1282
+ }
1283
+ buildMutationFields(ctx) {
1284
+ const fields = {};
1285
+ for (const [name, config] of this.state.mutations) {
1286
+ fields[name] = buildField(config, ctx);
1287
+ }
1288
+ return fields;
1289
+ }
1290
+ buildSubscriptionFields(ctx) {
1291
+ const fields = {};
1292
+ for (const [name, config] of this.state.subscriptions) {
1293
+ fields[name] = buildSubscriptionField(config, ctx);
1294
+ }
1295
+ return fields;
1296
+ }
1297
+ assembleSchema(registries) {
1298
+ const schemaConfig = {
1299
+ types: [
1300
+ ...Array.from(registries.enumRegistry.values()),
1301
+ ...Array.from(registries.inputRegistry.values()),
1302
+ ...Array.from(registries.interfaceRegistry.values()),
1303
+ ...Array.from(registries.typeRegistry.values()),
1304
+ ...Array.from(registries.unionRegistry.values())
1305
+ ],
1306
+ directives: registries.directiveRegistry.size > 0 ? [...Array.from(registries.directiveRegistry.values())] : void 0
1307
+ };
1308
+ if (Object.keys(registries.queryFields).length > 0) {
1309
+ schemaConfig.query = new graphql.GraphQLObjectType({
1310
+ name: "Query",
1311
+ fields: registries.queryFields
1312
+ });
1313
+ }
1314
+ if (Object.keys(registries.mutationFields).length > 0) {
1315
+ schemaConfig.mutation = new graphql.GraphQLObjectType({
1316
+ name: "Mutation",
1317
+ fields: registries.mutationFields
1318
+ });
1319
+ }
1320
+ if (Object.keys(registries.subscriptionFields).length > 0) {
1321
+ schemaConfig.subscription = new graphql.GraphQLObjectType({
1322
+ name: "Subscription",
1323
+ fields: registries.subscriptionFields
1324
+ });
1325
+ }
1326
+ return new graphql.GraphQLSchema(schemaConfig);
1327
+ }
1328
+ };
1329
+
1330
+ // src/builder/pipe-api.ts
1331
+ var objectType = (config) => (builder) => builder.objectType(config);
1332
+ var interfaceType = (config) => (builder) => builder.interfaceType(config);
1333
+ var enumType = (config) => (builder) => builder.enumType(config);
1334
+ var unionType = (config) => (builder) => builder.unionType(config);
1335
+ var inputType = (config) => (builder) => builder.inputType(config);
1336
+ var directive = (config) => (builder) => builder.directive(config);
1337
+ var middleware = (config) => (builder) => builder.middleware(config);
1338
+ var extension = (config) => (builder) => builder.extension(config);
1339
+ var query = (name, config) => (builder) => builder.query(name, config);
1340
+ var mutation = (name, config) => (builder) => builder.mutation(name, config);
1341
+ var subscription = (name, config) => (builder) => builder.subscription(name, config);
1342
+ var field = (typeName, fieldName, config) => (builder) => builder.field(typeName, fieldName, config);
1343
+ var compose = (...operations) => (builder) => operations.reduce((b, op) => op(b), builder);
1344
+ var ExtensionsService = effect.Context.GenericTag(
1345
+ "@effect-gql/ExtensionsService"
1346
+ );
1347
+ function deepMerge(target, source) {
1348
+ const result = { ...target };
1349
+ for (const key of Object.keys(source)) {
1350
+ const sourceValue = source[key];
1351
+ const targetValue = result[key];
1352
+ if (typeof sourceValue === "object" && sourceValue !== null && !Array.isArray(sourceValue) && typeof targetValue === "object" && targetValue !== null && !Array.isArray(targetValue)) {
1353
+ result[key] = deepMerge(
1354
+ targetValue,
1355
+ sourceValue
1356
+ );
1357
+ } else {
1358
+ result[key] = sourceValue;
1359
+ }
1360
+ }
1361
+ return result;
1362
+ }
1363
+ var makeExtensionsService = () => effect.Effect.gen(function* () {
1364
+ const ref = yield* effect.Ref.make({});
1365
+ return ExtensionsService.of({
1366
+ set: (key, value) => effect.Ref.update(ref, (current) => ({ ...current, [key]: value })),
1367
+ merge: (key, value) => effect.Ref.update(ref, (current) => {
1368
+ const existing = current[key];
1369
+ if (typeof existing === "object" && existing !== null && !Array.isArray(existing)) {
1370
+ return {
1371
+ ...current,
1372
+ [key]: deepMerge(existing, value)
1373
+ };
1374
+ }
1375
+ return { ...current, [key]: value };
1376
+ }),
1377
+ get: () => effect.Ref.get(ref)
1378
+ });
1379
+ });
1380
+ var runExtensionHooks = (extensions, hookName, getHookEffect) => effect.Effect.forEach(
1381
+ extensions.filter((ext) => ext[hookName] !== void 0),
1382
+ (ext) => getHookEffect(ext).pipe(
1383
+ effect.Effect.catchAllCause(
1384
+ (cause) => effect.Effect.logWarning(`Extension "${ext.name}" ${String(hookName)} hook failed`, cause)
1385
+ )
1386
+ ),
1387
+ { discard: true }
1388
+ );
1389
+ var runParseHooks = (extensions, source, document) => runExtensionHooks(extensions, "onParse", (ext) => ext.onParse(source, document));
1390
+ var runValidateHooks = (extensions, document, errors) => runExtensionHooks(extensions, "onValidate", (ext) => ext.onValidate(document, errors));
1391
+ var runExecuteStartHooks = (extensions, args) => runExtensionHooks(extensions, "onExecuteStart", (ext) => ext.onExecuteStart(args));
1392
+ var runExecuteEndHooks = (extensions, result) => runExtensionHooks(extensions, "onExecuteEnd", (ext) => ext.onExecuteEnd(result));
1393
+
1394
+ // src/builder/execute.ts
1395
+ var execute = (schema, layer, extensions = [], fieldComplexities = /* @__PURE__ */ new Map()) => (source, variableValues, operationName) => effect.Effect.gen(function* () {
1396
+ const extensionsService = yield* makeExtensionsService();
1397
+ const runtime = yield* effect.Effect.runtime();
1398
+ let document;
1399
+ try {
1400
+ document = graphql.parse(source);
1401
+ } catch (parseError) {
1402
+ const extensionData2 = yield* extensionsService.get();
1403
+ return {
1404
+ errors: [
1405
+ parseError instanceof graphql.GraphQLError ? parseError : new graphql.GraphQLError(String(parseError))
1406
+ ],
1407
+ extensions: Object.keys(extensionData2).length > 0 ? extensionData2 : void 0
1408
+ };
1409
+ }
1410
+ yield* runParseHooks(extensions, source, document).pipe(
1411
+ effect.Effect.provideService(ExtensionsService, extensionsService)
1412
+ );
1413
+ const validationErrors = graphql.validate(schema, document);
1414
+ yield* runValidateHooks(extensions, document, validationErrors).pipe(
1415
+ effect.Effect.provideService(ExtensionsService, extensionsService)
1416
+ );
1417
+ if (validationErrors.length > 0) {
1418
+ const extensionData2 = yield* extensionsService.get();
1419
+ return {
1420
+ errors: validationErrors,
1421
+ extensions: Object.keys(extensionData2).length > 0 ? extensionData2 : void 0
1422
+ };
1423
+ }
1424
+ const executionArgs = {
1425
+ source,
1426
+ document,
1427
+ variableValues,
1428
+ operationName,
1429
+ schema,
1430
+ fieldComplexities
1431
+ };
1432
+ yield* runExecuteStartHooks(extensions, executionArgs).pipe(
1433
+ effect.Effect.provideService(ExtensionsService, extensionsService)
1434
+ );
1435
+ const executeResult = yield* effect.Effect.try({
1436
+ try: () => graphql.execute({
1437
+ schema,
1438
+ document,
1439
+ variableValues,
1440
+ operationName,
1441
+ contextValue: { runtime }
1442
+ }),
1443
+ catch: (error) => new Error(String(error))
1444
+ });
1445
+ const resolvedResult = executeResult && typeof executeResult === "object" && "then" in executeResult ? yield* effect.Effect.promise(() => executeResult) : executeResult;
1446
+ yield* runExecuteEndHooks(extensions, resolvedResult).pipe(
1447
+ effect.Effect.provideService(ExtensionsService, extensionsService)
1448
+ );
1449
+ const extensionData = yield* extensionsService.get();
1450
+ if (Object.keys(extensionData).length > 0) {
1451
+ return {
1452
+ ...resolvedResult,
1453
+ extensions: {
1454
+ ...resolvedResult.extensions,
1455
+ ...extensionData
1456
+ }
1457
+ };
1458
+ }
1459
+ return resolvedResult;
1460
+ }).pipe(effect.Effect.provide(layer));
1461
+ var GraphQLError2 = class extends effect.Data.TaggedError("GraphQLError") {
1462
+ };
1463
+ var ValidationError = class extends effect.Data.TaggedError("ValidationError") {
1464
+ };
1465
+ var AuthorizationError = class extends effect.Data.TaggedError("AuthorizationError") {
1466
+ };
1467
+ var NotFoundError = class extends effect.Data.TaggedError("NotFoundError") {
1468
+ };
1469
+ var GraphQLRequestContext = effect.Context.GenericTag("GraphQLRequestContext");
1470
+ var makeRequestContextLayer = (context) => effect.Layer.succeed(GraphQLRequestContext, context);
1471
+ function single(config) {
1472
+ return {
1473
+ _tag: "single",
1474
+ batch: config.batch,
1475
+ key: config.key
1476
+ };
1477
+ }
1478
+ function grouped(config) {
1479
+ return {
1480
+ _tag: "grouped",
1481
+ batch: config.batch,
1482
+ groupBy: config.groupBy
1483
+ };
1484
+ }
1485
+ var LoaderRegistry = class {
1486
+ constructor(definitions) {
1487
+ this.definitions = definitions;
1488
+ this.Service = effect.Context.GenericTag(
1489
+ `DataLoaders(${Object.keys(definitions).join(", ")})`
1490
+ );
1491
+ }
1492
+ _tag = "LoaderRegistry";
1493
+ /**
1494
+ * The Effect service tag for this loader registry
1495
+ */
1496
+ Service;
1497
+ /**
1498
+ * Create a Layer that provides fresh DataLoader instances.
1499
+ * Call this once per request to get request-scoped loaders.
1500
+ */
1501
+ toLayer() {
1502
+ const self = this;
1503
+ return effect.Layer.effect(
1504
+ this.Service,
1505
+ effect.Effect.gen(function* () {
1506
+ const instances = {};
1507
+ for (const name of Object.keys(self.definitions)) {
1508
+ const def = self.definitions[name];
1509
+ instances[name] = yield* createDataLoader(def);
1510
+ }
1511
+ return instances;
1512
+ })
1513
+ );
1514
+ }
1515
+ /**
1516
+ * Helper to use loaders in a resolver with a callback.
1517
+ */
1518
+ use(fn) {
1519
+ const self = this;
1520
+ return effect.Effect.gen(function* () {
1521
+ const loaders = yield* self.Service;
1522
+ return yield* effect.Effect.promise(() => fn(loaders));
1523
+ });
1524
+ }
1525
+ /**
1526
+ * Load a single value by key.
1527
+ * This is the most common operation in resolvers.
1528
+ *
1529
+ * @internal The internal cast is safe because LoaderInstances<Defs> guarantees
1530
+ * that loaders[name] is a DataLoader with the correct key/value types.
1531
+ */
1532
+ load(name, key) {
1533
+ const self = this;
1534
+ return effect.Effect.gen(function* () {
1535
+ const loaders = yield* self.Service;
1536
+ const loader = loaders[name];
1537
+ return yield* effect.Effect.promise(() => loader.load(key));
1538
+ });
1539
+ }
1540
+ /**
1541
+ * Load multiple values by keys.
1542
+ * All keys are batched into a single request.
1543
+ *
1544
+ * @internal The internal cast is safe because LoaderInstances<Defs> guarantees
1545
+ * that loaders[name] is a DataLoader with the correct key/value types.
1546
+ */
1547
+ loadMany(name, keys) {
1548
+ const self = this;
1549
+ return effect.Effect.gen(function* () {
1550
+ const loaders = yield* self.Service;
1551
+ const loader = loaders[name];
1552
+ const results = yield* effect.Effect.promise(() => loader.loadMany(keys));
1553
+ for (const result of results) {
1554
+ if (result instanceof Error) {
1555
+ return yield* effect.Effect.fail(result);
1556
+ }
1557
+ }
1558
+ return results;
1559
+ });
1560
+ }
1561
+ };
1562
+ function createSingleDataLoader(def, context) {
1563
+ return new DataLoader__default.default(async (keys) => {
1564
+ const items = await effect.Effect.runPromise(def.batch(keys).pipe(effect.Effect.provide(context)));
1565
+ return keys.map((key) => {
1566
+ const item = items.find((i) => def.key(i) === key);
1567
+ if (!item) return new Error(`Not found: ${key}`);
1568
+ return item;
1569
+ });
1570
+ });
1571
+ }
1572
+ function createGroupedDataLoader(def, context) {
1573
+ return new DataLoader__default.default(async (keys) => {
1574
+ const items = await effect.Effect.runPromise(def.batch(keys).pipe(effect.Effect.provide(context)));
1575
+ const map = /* @__PURE__ */ new Map();
1576
+ for (const item of items) {
1577
+ const key = def.groupBy(item);
1578
+ let arr = map.get(key);
1579
+ if (!arr) {
1580
+ arr = [];
1581
+ map.set(key, arr);
1582
+ }
1583
+ arr.push(item);
1584
+ }
1585
+ return keys.map((key) => map.get(key) ?? []);
1586
+ });
1587
+ }
1588
+ function createDataLoader(def) {
1589
+ return effect.Effect.gen(function* () {
1590
+ const context = yield* effect.Effect.context();
1591
+ if (def._tag === "single") {
1592
+ return createSingleDataLoader(def, context);
1593
+ } else {
1594
+ return createGroupedDataLoader(def, context);
1595
+ }
1596
+ });
1597
+ }
1598
+ function define(definitions) {
1599
+ return new LoaderRegistry(definitions);
1600
+ }
1601
+ function mapByKey(keys, items, keyFn) {
1602
+ const map = /* @__PURE__ */ new Map();
1603
+ for (const item of items) {
1604
+ map.set(keyFn(item), item);
1605
+ }
1606
+ return keys.map((key) => map.get(key) ?? new Error(`Not found: ${key}`));
1607
+ }
1608
+ function groupByKey(keys, items, keyFn) {
1609
+ const map = /* @__PURE__ */ new Map();
1610
+ for (const key of keys) {
1611
+ map.set(key, []);
1612
+ }
1613
+ for (const item of items) {
1614
+ const key = keyFn(item);
1615
+ const arr = map.get(key);
1616
+ if (arr) arr.push(item);
1617
+ }
1618
+ return map;
1619
+ }
1620
+ var Loader = {
1621
+ define,
1622
+ single,
1623
+ grouped,
1624
+ mapByKey,
1625
+ groupByKey
1626
+ };
1627
+ var MissingResolverContextError = class extends Error {
1628
+ constructor(contextName) {
1629
+ super(
1630
+ `Resolver context "${contextName}" was not provided. Ensure a parent resolver or directive provides this context.`
1631
+ );
1632
+ this.contextName = contextName;
1633
+ this.name = "MissingResolverContextError";
1634
+ }
1635
+ _tag = "MissingResolverContextError";
1636
+ };
1637
+ var ResolverContextStore = effect.Context.GenericTag(
1638
+ "effect-gql/ResolverContextStore"
1639
+ );
1640
+ var makeStoreLayer = () => effect.Effect.map(
1641
+ effect.Ref.make(effect.HashMap.empty()),
1642
+ (ref) => effect.Layer.succeed(ResolverContextStore, { ref })
1643
+ );
1644
+ var storeLayer = effect.Layer.effect(
1645
+ ResolverContextStore,
1646
+ effect.Effect.map(effect.Ref.make(effect.HashMap.empty()), (ref) => ({ ref }))
1647
+ );
1648
+ var make3 = (name) => ({
1649
+ _tag: "ResolverContextSlot",
1650
+ name,
1651
+ _A: void 0
1652
+ });
1653
+ var get = (slot) => effect.Effect.flatMap(
1654
+ ResolverContextStore,
1655
+ (store) => effect.Effect.flatMap(effect.Ref.get(store.ref), (map) => {
1656
+ const value = effect.HashMap.get(map, slot.name);
1657
+ return effect.Option.match(value, {
1658
+ onNone: () => effect.Effect.fail(new MissingResolverContextError(slot.name)),
1659
+ onSome: (v) => effect.Effect.succeed(v)
1660
+ });
1661
+ })
1662
+ );
1663
+ var getOption = (slot) => effect.Effect.flatMap(
1664
+ ResolverContextStore,
1665
+ (store) => effect.Effect.map(effect.Ref.get(store.ref), (map) => effect.HashMap.get(map, slot.name))
1666
+ );
1667
+ var set = (slot, value) => effect.Effect.flatMap(
1668
+ ResolverContextStore,
1669
+ (store) => effect.Ref.update(store.ref, (map) => effect.HashMap.set(map, slot.name, value))
1670
+ );
1671
+ var setMany = (values) => effect.Effect.flatMap(
1672
+ ResolverContextStore,
1673
+ (store) => effect.Ref.update(store.ref, (map) => {
1674
+ let result = map;
1675
+ for (const [slot, value] of values) {
1676
+ result = effect.HashMap.set(result, slot.name, value);
1677
+ }
1678
+ return result;
1679
+ })
1680
+ );
1681
+ var has = (slot) => effect.Effect.flatMap(
1682
+ ResolverContextStore,
1683
+ (store) => effect.Effect.map(effect.Ref.get(store.ref), (map) => effect.HashMap.has(map, slot.name))
1684
+ );
1685
+ var getOrElse = (slot, orElse) => effect.Effect.flatMap(
1686
+ ResolverContextStore,
1687
+ (store) => effect.Effect.map(
1688
+ effect.Ref.get(store.ref),
1689
+ (map) => effect.Option.getOrElse(effect.HashMap.get(map, slot.name), orElse)
1690
+ )
1691
+ );
1692
+ var scoped = (slot, value) => (effect$1) => effect.Effect.flatMap(
1693
+ ResolverContextStore,
1694
+ (store) => effect.Effect.acquireUseRelease(
1695
+ // Acquire: save current value and set new one
1696
+ effect.Effect.flatMap(effect.Ref.get(store.ref), (map) => {
1697
+ const previous = effect.HashMap.get(map, slot.name);
1698
+ return effect.Effect.as(effect.Ref.set(store.ref, effect.HashMap.set(map, slot.name, value)), previous);
1699
+ }),
1700
+ // Use: run the effect
1701
+ () => effect$1,
1702
+ // Release: restore previous value
1703
+ (previous) => effect.Ref.update(
1704
+ store.ref,
1705
+ (map) => effect.Option.match(previous, {
1706
+ onNone: () => effect.HashMap.remove(map, slot.name),
1707
+ onSome: (v) => effect.HashMap.set(map, slot.name, v)
1708
+ })
1709
+ )
1710
+ )
1711
+ );
1712
+ var ResolverContext = {
1713
+ make: make3,
1714
+ get,
1715
+ getOption,
1716
+ set,
1717
+ setMany,
1718
+ has,
1719
+ getOrElse,
1720
+ scoped,
1721
+ storeLayer,
1722
+ makeStoreLayer,
1723
+ Store: ResolverContextStore,
1724
+ MissingResolverContextError
1725
+ };
1726
+ var defaultConfig = {
1727
+ path: "/graphql",
1728
+ graphiql: false,
1729
+ complexity: void 0,
1730
+ introspection: true,
1731
+ cacheControl: void 0
1732
+ };
1733
+ var normalizeConfig = (input = {}) => {
1734
+ const path = input.path ?? defaultConfig.path;
1735
+ let graphiql = false;
1736
+ if (input.graphiql === true) {
1737
+ graphiql = { path: "/graphiql", endpoint: path };
1738
+ } else if (input.graphiql && typeof input.graphiql === "object") {
1739
+ graphiql = {
1740
+ path: input.graphiql.path ?? "/graphiql",
1741
+ endpoint: input.graphiql.endpoint ?? path
1742
+ };
1743
+ }
1744
+ return {
1745
+ path,
1746
+ graphiql,
1747
+ complexity: input.complexity,
1748
+ introspection: input.introspection ?? true,
1749
+ cacheControl: input.cacheControl
1750
+ };
1751
+ };
1752
+ var GraphQLRouterConfigFromEnv = effect.Config.all({
1753
+ path: effect.Config.string("GRAPHQL_PATH").pipe(effect.Config.withDefault("/graphql")),
1754
+ introspection: effect.Config.boolean("GRAPHQL_INTROSPECTION").pipe(effect.Config.withDefault(true)),
1755
+ graphiqlEnabled: effect.Config.boolean("GRAPHIQL_ENABLED").pipe(effect.Config.withDefault(false)),
1756
+ graphiqlPath: effect.Config.string("GRAPHIQL_PATH").pipe(effect.Config.withDefault("/graphiql")),
1757
+ graphiqlEndpoint: effect.Config.string("GRAPHIQL_ENDPOINT").pipe(effect.Config.option),
1758
+ maxDepth: effect.Config.number("GRAPHQL_MAX_DEPTH").pipe(effect.Config.option),
1759
+ maxComplexity: effect.Config.number("GRAPHQL_MAX_COMPLEXITY").pipe(effect.Config.option),
1760
+ maxAliases: effect.Config.number("GRAPHQL_MAX_ALIASES").pipe(effect.Config.option),
1761
+ maxFields: effect.Config.number("GRAPHQL_MAX_FIELDS").pipe(effect.Config.option),
1762
+ defaultFieldComplexity: effect.Config.number("GRAPHQL_DEFAULT_FIELD_COMPLEXITY").pipe(
1763
+ effect.Config.withDefault(1)
1764
+ ),
1765
+ cacheControlEnabled: effect.Config.boolean("GRAPHQL_CACHE_CONTROL_ENABLED").pipe(
1766
+ effect.Config.withDefault(false)
1767
+ ),
1768
+ cacheControlDefaultMaxAge: effect.Config.number("GRAPHQL_CACHE_CONTROL_DEFAULT_MAX_AGE").pipe(
1769
+ effect.Config.withDefault(0)
1770
+ ),
1771
+ cacheControlDefaultScope: effect.Config.string("GRAPHQL_CACHE_CONTROL_DEFAULT_SCOPE").pipe(
1772
+ effect.Config.withDefault("PUBLIC")
1773
+ )
1774
+ }).pipe(
1775
+ effect.Config.map(
1776
+ ({
1777
+ path,
1778
+ introspection,
1779
+ graphiqlEnabled,
1780
+ graphiqlPath,
1781
+ graphiqlEndpoint,
1782
+ maxDepth,
1783
+ maxComplexity,
1784
+ maxAliases,
1785
+ maxFields,
1786
+ defaultFieldComplexity,
1787
+ cacheControlEnabled,
1788
+ cacheControlDefaultMaxAge,
1789
+ cacheControlDefaultScope
1790
+ }) => {
1791
+ const hasComplexity = effect.Option.isSome(maxDepth) || effect.Option.isSome(maxComplexity) || effect.Option.isSome(maxAliases) || effect.Option.isSome(maxFields);
1792
+ return {
1793
+ path,
1794
+ introspection,
1795
+ graphiql: graphiqlEnabled ? {
1796
+ path: graphiqlPath,
1797
+ endpoint: effect.Option.isSome(graphiqlEndpoint) ? graphiqlEndpoint.value : path
1798
+ } : false,
1799
+ complexity: hasComplexity ? {
1800
+ maxDepth: effect.Option.getOrUndefined(maxDepth),
1801
+ maxComplexity: effect.Option.getOrUndefined(maxComplexity),
1802
+ maxAliases: effect.Option.getOrUndefined(maxAliases),
1803
+ maxFields: effect.Option.getOrUndefined(maxFields),
1804
+ defaultFieldComplexity
1805
+ } : void 0,
1806
+ cacheControl: cacheControlEnabled ? {
1807
+ enabled: true,
1808
+ defaultMaxAge: cacheControlDefaultMaxAge,
1809
+ defaultScope: cacheControlDefaultScope === "PRIVATE" ? "PRIVATE" : "PUBLIC",
1810
+ calculateHttpHeaders: true
1811
+ } : void 0
1812
+ };
1813
+ }
1814
+ )
1815
+ );
1816
+
1817
+ // src/server/graphiql.ts
1818
+ var graphiqlHtml = (endpoint, subscriptionEndpoint) => `<!DOCTYPE html>
1819
+ <html lang="en">
1820
+ <head>
1821
+ <meta charset="utf-8" />
1822
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
1823
+ <title>GraphiQL</title>
1824
+ <link
1825
+ rel="stylesheet"
1826
+ href="https://unpkg.com/graphiql@3/graphiql.min.css"
1827
+ />
1828
+ </head>
1829
+ <body style="margin: 0; overflow: hidden;">
1830
+ <div id="graphiql" style="height: 100vh;"></div>
1831
+ <script
1832
+ crossorigin
1833
+ src="https://unpkg.com/react@18/umd/react.production.min.js"
1834
+ ></script>
1835
+ <script
1836
+ crossorigin
1837
+ src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"
1838
+ ></script>
1839
+ <script
1840
+ crossorigin
1841
+ src="https://unpkg.com/graphiql@3/graphiql.min.js"
1842
+ ></script>
1843
+ <script>
1844
+ const fetcher = GraphiQL.createFetcher({
1845
+ url: ${JSON.stringify(endpoint)},
1846
+ subscriptionUrl: ${JSON.stringify(subscriptionEndpoint ?? endpoint)},
1847
+ });
1848
+ ReactDOM.createRoot(document.getElementById('graphiql')).render(
1849
+ React.createElement(GraphiQL, { fetcher })
1850
+ );
1851
+ </script>
1852
+ </body>
1853
+ </html>`;
1854
+ var ComplexityLimitExceededError = class extends effect.Data.TaggedError("ComplexityLimitExceededError") {
1855
+ };
1856
+ var ComplexityAnalysisError = class extends effect.Data.TaggedError("ComplexityAnalysisError") {
1857
+ };
1858
+ var defaultComplexityCalculator = (defaultCost = 1) => {
1859
+ return (info) => effect.Effect.try({
1860
+ try: () => {
1861
+ const fragments = /* @__PURE__ */ new Map();
1862
+ for (const definition of info.document.definitions) {
1863
+ if (definition.kind === graphql.Kind.FRAGMENT_DEFINITION) {
1864
+ fragments.set(definition.name.value, definition);
1865
+ }
1866
+ }
1867
+ const rootType = getRootType(info.schema, info.operation.operation);
1868
+ if (!rootType) {
1869
+ throw new Error(`No root type found for operation: ${info.operation.operation}`);
1870
+ }
1871
+ const result = analyzeSelectionSet(
1872
+ info.operation.selectionSet,
1873
+ rootType,
1874
+ info.schema,
1875
+ fragments,
1876
+ info.fieldComplexities,
1877
+ info.variables ?? {},
1878
+ defaultCost,
1879
+ 1,
1880
+ // Starting depth
1881
+ /* @__PURE__ */ new Set()
1882
+ // Visited fragments to prevent infinite loops
1883
+ );
1884
+ return result;
1885
+ },
1886
+ catch: (error) => new ComplexityAnalysisError({
1887
+ message: `Failed to analyze query complexity: ${error}`,
1888
+ cause: error
1889
+ })
1890
+ });
1891
+ };
1892
+ function getRootType(schema, operation) {
1893
+ switch (operation) {
1894
+ case "query":
1895
+ return schema.getQueryType() ?? null;
1896
+ case "mutation":
1897
+ return schema.getMutationType() ?? null;
1898
+ case "subscription":
1899
+ return schema.getSubscriptionType() ?? null;
1900
+ }
1901
+ }
1902
+ function getNamedType(type) {
1903
+ if (type instanceof graphql.GraphQLNonNull || type instanceof graphql.GraphQLList) {
1904
+ return getNamedType(type.ofType);
1905
+ }
1906
+ if (type instanceof graphql.GraphQLObjectType) {
1907
+ return type;
1908
+ }
1909
+ return null;
1910
+ }
1911
+ function accumulateResult(acc, result) {
1912
+ acc.maxDepth = Math.max(acc.maxDepth, result.depth);
1913
+ acc.complexity += result.complexity;
1914
+ acc.fieldCount += result.fieldCount;
1915
+ acc.aliasCount += result.aliasCount;
1916
+ }
1917
+ function analyzeSelectionSet(selectionSet, parentType, schema, fragments, fieldComplexities, variables, defaultCost, currentDepth, visitedFragments) {
1918
+ const ctx = { schema, fragments, fieldComplexities, variables, defaultCost };
1919
+ const acc = { maxDepth: currentDepth, complexity: 0, fieldCount: 0, aliasCount: 0 };
1920
+ for (const selection of selectionSet.selections) {
1921
+ const result = analyzeSelection(selection, parentType, ctx, currentDepth, visitedFragments);
1922
+ accumulateResult(acc, result);
1923
+ }
1924
+ return {
1925
+ depth: acc.maxDepth,
1926
+ complexity: acc.complexity,
1927
+ fieldCount: acc.fieldCount,
1928
+ aliasCount: acc.aliasCount
1929
+ };
1930
+ }
1931
+ function analyzeSelection(selection, parentType, ctx, currentDepth, visitedFragments) {
1932
+ switch (selection.kind) {
1933
+ case graphql.Kind.FIELD:
1934
+ return analyzeField(selection, parentType, ctx, currentDepth, visitedFragments);
1935
+ case graphql.Kind.FRAGMENT_SPREAD:
1936
+ return analyzeFragmentSpread(selection, ctx, currentDepth, visitedFragments);
1937
+ case graphql.Kind.INLINE_FRAGMENT:
1938
+ return analyzeInlineFragment(selection, parentType, ctx, currentDepth, visitedFragments);
1939
+ }
1940
+ }
1941
+ function analyzeField(field2, parentType, ctx, currentDepth, visitedFragments) {
1942
+ const fieldName = field2.name.value;
1943
+ const aliasCount = field2.alias ? 1 : 0;
1944
+ if (fieldName.startsWith("__")) {
1945
+ return { depth: currentDepth, complexity: 0, fieldCount: 1, aliasCount };
1946
+ }
1947
+ const schemaField = parentType.getFields()[fieldName];
1948
+ if (!schemaField) {
1949
+ return { depth: currentDepth, complexity: ctx.defaultCost, fieldCount: 1, aliasCount };
1950
+ }
1951
+ const args = resolveFieldArguments(field2, ctx.variables);
1952
+ const complexityKey = `${parentType.name}.${fieldName}`;
1953
+ const fieldComplexity = ctx.fieldComplexities.get(complexityKey);
1954
+ const cost = fieldComplexity !== void 0 ? typeof fieldComplexity === "function" ? fieldComplexity(args) : fieldComplexity : ctx.defaultCost;
1955
+ if (field2.selectionSet) {
1956
+ const fieldType = getNamedType(schemaField.type);
1957
+ if (fieldType) {
1958
+ const nestedResult = analyzeSelectionSet(
1959
+ field2.selectionSet,
1960
+ fieldType,
1961
+ ctx.schema,
1962
+ ctx.fragments,
1963
+ ctx.fieldComplexities,
1964
+ ctx.variables,
1965
+ ctx.defaultCost,
1966
+ currentDepth + 1,
1967
+ visitedFragments
1968
+ );
1969
+ return {
1970
+ depth: nestedResult.depth,
1971
+ complexity: cost + nestedResult.complexity,
1972
+ fieldCount: 1 + nestedResult.fieldCount,
1973
+ aliasCount: aliasCount + nestedResult.aliasCount
1974
+ };
1975
+ }
1976
+ }
1977
+ return { depth: currentDepth, complexity: cost, fieldCount: 1, aliasCount };
1978
+ }
1979
+ function analyzeFragmentSpread(spread, ctx, currentDepth, visitedFragments) {
1980
+ const fragmentName = spread.name.value;
1981
+ if (visitedFragments.has(fragmentName)) {
1982
+ return { depth: currentDepth, complexity: 0, fieldCount: 0, aliasCount: 0 };
1983
+ }
1984
+ const fragment = ctx.fragments.get(fragmentName);
1985
+ if (!fragment) {
1986
+ return { depth: currentDepth, complexity: 0, fieldCount: 0, aliasCount: 0 };
1987
+ }
1988
+ const fragmentType = ctx.schema.getType(fragment.typeCondition.name.value);
1989
+ if (!(fragmentType instanceof graphql.GraphQLObjectType)) {
1990
+ return { depth: currentDepth, complexity: 0, fieldCount: 0, aliasCount: 0 };
1991
+ }
1992
+ const newVisited = new Set(visitedFragments);
1993
+ newVisited.add(fragmentName);
1994
+ return analyzeSelectionSet(
1995
+ fragment.selectionSet,
1996
+ fragmentType,
1997
+ ctx.schema,
1998
+ ctx.fragments,
1999
+ ctx.fieldComplexities,
2000
+ ctx.variables,
2001
+ ctx.defaultCost,
2002
+ currentDepth,
2003
+ newVisited
2004
+ );
2005
+ }
2006
+ function analyzeInlineFragment(fragment, parentType, ctx, currentDepth, visitedFragments) {
2007
+ let targetType = parentType;
2008
+ if (fragment.typeCondition) {
2009
+ const conditionType = ctx.schema.getType(fragment.typeCondition.name.value);
2010
+ if (conditionType instanceof graphql.GraphQLObjectType) {
2011
+ targetType = conditionType;
2012
+ }
2013
+ }
2014
+ return analyzeSelectionSet(
2015
+ fragment.selectionSet,
2016
+ targetType,
2017
+ ctx.schema,
2018
+ ctx.fragments,
2019
+ ctx.fieldComplexities,
2020
+ ctx.variables,
2021
+ ctx.defaultCost,
2022
+ currentDepth,
2023
+ visitedFragments
2024
+ );
2025
+ }
2026
+ function resolveFieldArguments(field2, variables) {
2027
+ const args = {};
2028
+ if (!field2.arguments) {
2029
+ return args;
2030
+ }
2031
+ for (const arg of field2.arguments) {
2032
+ const value = arg.value;
2033
+ switch (value.kind) {
2034
+ case graphql.Kind.VARIABLE:
2035
+ args[arg.name.value] = variables[value.name.value];
2036
+ break;
2037
+ case graphql.Kind.INT:
2038
+ args[arg.name.value] = parseInt(value.value, 10);
2039
+ break;
2040
+ case graphql.Kind.FLOAT:
2041
+ args[arg.name.value] = parseFloat(value.value);
2042
+ break;
2043
+ case graphql.Kind.STRING:
2044
+ args[arg.name.value] = value.value;
2045
+ break;
2046
+ case graphql.Kind.BOOLEAN:
2047
+ args[arg.name.value] = value.value;
2048
+ break;
2049
+ case graphql.Kind.NULL:
2050
+ args[arg.name.value] = null;
2051
+ break;
2052
+ case graphql.Kind.ENUM:
2053
+ args[arg.name.value] = value.value;
2054
+ break;
2055
+ case graphql.Kind.LIST:
2056
+ args[arg.name.value] = [];
2057
+ break;
2058
+ case graphql.Kind.OBJECT:
2059
+ args[arg.name.value] = {};
2060
+ break;
2061
+ }
2062
+ }
2063
+ return args;
2064
+ }
2065
+ var validateComplexity = (query2, operationName, variables, schema, fieldComplexities, config) => effect.Effect.gen(function* () {
2066
+ const document = yield* effect.Effect.try({
2067
+ try: () => graphql.parse(query2),
2068
+ catch: (error) => new ComplexityAnalysisError({
2069
+ message: `Failed to parse query: ${error}`,
2070
+ cause: error
2071
+ })
2072
+ });
2073
+ const operation = yield* effect.Effect.try({
2074
+ try: () => {
2075
+ const operations = document.definitions.filter(
2076
+ (d) => d.kind === graphql.Kind.OPERATION_DEFINITION
2077
+ );
2078
+ if (operations.length === 0) {
2079
+ throw new Error("No operation found in query");
2080
+ }
2081
+ if (operationName) {
2082
+ const op = operations.find((o) => o.name?.value === operationName);
2083
+ if (!op) {
2084
+ throw new Error(`Operation "${operationName}" not found`);
2085
+ }
2086
+ return op;
2087
+ }
2088
+ if (operations.length > 1) {
2089
+ throw new Error("Multiple operations found - operationName required");
2090
+ }
2091
+ return operations[0];
2092
+ },
2093
+ catch: (error) => new ComplexityAnalysisError({
2094
+ message: String(error),
2095
+ cause: error
2096
+ })
2097
+ });
2098
+ const calculator = config.calculator ?? defaultComplexityCalculator(config.defaultFieldComplexity ?? 1);
2099
+ const result = yield* calculator({
2100
+ document,
2101
+ operation,
2102
+ variables,
2103
+ schema,
2104
+ fieldComplexities
2105
+ });
2106
+ const checkLimit = (limitType, limit, actual) => effect.Effect.gen(function* () {
2107
+ if (limit !== void 0 && actual > limit) {
2108
+ const exceededInfo = {
2109
+ result,
2110
+ exceededLimit: limitType,
2111
+ limit,
2112
+ actual,
2113
+ query: query2,
2114
+ operationName
2115
+ };
2116
+ if (config.onExceeded) {
2117
+ yield* config.onExceeded(exceededInfo);
2118
+ }
2119
+ yield* effect.Effect.fail(
2120
+ new ComplexityLimitExceededError({
2121
+ message: `Query ${limitType} of ${actual} exceeds maximum allowed ${limitType} of ${limit}`,
2122
+ limit,
2123
+ actual,
2124
+ limitType
2125
+ })
2126
+ );
2127
+ }
2128
+ });
2129
+ yield* checkLimit("depth", config.maxDepth, result.depth);
2130
+ yield* checkLimit("complexity", config.maxComplexity, result.complexity);
2131
+ yield* checkLimit("aliases", config.maxAliases, result.aliasCount);
2132
+ yield* checkLimit("fields", config.maxFields, result.fieldCount);
2133
+ return result;
2134
+ });
2135
+ var ComplexityConfigFromEnv = effect.Config.all({
2136
+ maxDepth: effect.Config.number("GRAPHQL_MAX_DEPTH").pipe(effect.Config.option),
2137
+ maxComplexity: effect.Config.number("GRAPHQL_MAX_COMPLEXITY").pipe(effect.Config.option),
2138
+ maxAliases: effect.Config.number("GRAPHQL_MAX_ALIASES").pipe(effect.Config.option),
2139
+ maxFields: effect.Config.number("GRAPHQL_MAX_FIELDS").pipe(effect.Config.option),
2140
+ defaultFieldComplexity: effect.Config.number("GRAPHQL_DEFAULT_FIELD_COMPLEXITY").pipe(
2141
+ effect.Config.withDefault(1)
2142
+ )
2143
+ }).pipe(
2144
+ effect.Config.map(({ maxDepth, maxComplexity, maxAliases, maxFields, defaultFieldComplexity }) => ({
2145
+ maxDepth: effect.Option.getOrUndefined(maxDepth),
2146
+ maxComplexity: effect.Option.getOrUndefined(maxComplexity),
2147
+ maxAliases: effect.Option.getOrUndefined(maxAliases),
2148
+ maxFields: effect.Option.getOrUndefined(maxFields),
2149
+ defaultFieldComplexity
2150
+ }))
2151
+ );
2152
+ var depthOnlyCalculator = (info) => effect.Effect.try({
2153
+ try: () => {
2154
+ const fragments = /* @__PURE__ */ new Map();
2155
+ for (const definition of info.document.definitions) {
2156
+ if (definition.kind === graphql.Kind.FRAGMENT_DEFINITION) {
2157
+ fragments.set(definition.name.value, definition);
2158
+ }
2159
+ }
2160
+ const depth = calculateMaxDepth(info.operation.selectionSet, fragments, 1, /* @__PURE__ */ new Set());
2161
+ return {
2162
+ depth,
2163
+ complexity: 0,
2164
+ fieldCount: 0,
2165
+ aliasCount: 0
2166
+ };
2167
+ },
2168
+ catch: (error) => new ComplexityAnalysisError({
2169
+ message: `Failed to analyze query depth: ${error}`,
2170
+ cause: error
2171
+ })
2172
+ });
2173
+ function calculateMaxDepth(selectionSet, fragments, currentDepth, visitedFragments) {
2174
+ let maxDepth = currentDepth;
2175
+ for (const selection of selectionSet.selections) {
2176
+ switch (selection.kind) {
2177
+ case graphql.Kind.FIELD:
2178
+ if (selection.selectionSet) {
2179
+ const nestedDepth = calculateMaxDepth(
2180
+ selection.selectionSet,
2181
+ fragments,
2182
+ currentDepth + 1,
2183
+ visitedFragments
2184
+ );
2185
+ maxDepth = Math.max(maxDepth, nestedDepth);
2186
+ }
2187
+ break;
2188
+ case graphql.Kind.FRAGMENT_SPREAD: {
2189
+ const fragmentName = selection.name.value;
2190
+ if (!visitedFragments.has(fragmentName)) {
2191
+ const fragment = fragments.get(fragmentName);
2192
+ if (fragment) {
2193
+ const newVisited = new Set(visitedFragments);
2194
+ newVisited.add(fragmentName);
2195
+ const fragmentDepth = calculateMaxDepth(
2196
+ fragment.selectionSet,
2197
+ fragments,
2198
+ currentDepth,
2199
+ newVisited
2200
+ );
2201
+ maxDepth = Math.max(maxDepth, fragmentDepth);
2202
+ }
2203
+ }
2204
+ break;
2205
+ }
2206
+ case graphql.Kind.INLINE_FRAGMENT: {
2207
+ const inlineDepth = calculateMaxDepth(
2208
+ selection.selectionSet,
2209
+ fragments,
2210
+ currentDepth,
2211
+ visitedFragments
2212
+ );
2213
+ maxDepth = Math.max(maxDepth, inlineDepth);
2214
+ break;
2215
+ }
2216
+ }
2217
+ }
2218
+ return maxDepth;
2219
+ }
2220
+ var combineCalculators = (...calculators) => {
2221
+ return (info) => effect.Effect.gen(function* () {
2222
+ let maxDepth = 0;
2223
+ let maxComplexity = 0;
2224
+ let maxFieldCount = 0;
2225
+ let maxAliasCount = 0;
2226
+ for (const calculator of calculators) {
2227
+ const result = yield* calculator(info);
2228
+ maxDepth = Math.max(maxDepth, result.depth);
2229
+ maxComplexity = Math.max(maxComplexity, result.complexity);
2230
+ maxFieldCount = Math.max(maxFieldCount, result.fieldCount);
2231
+ maxAliasCount = Math.max(maxAliasCount, result.aliasCount);
2232
+ }
2233
+ return {
2234
+ depth: maxDepth,
2235
+ complexity: maxComplexity,
2236
+ fieldCount: maxFieldCount,
2237
+ aliasCount: maxAliasCount
2238
+ };
2239
+ });
2240
+ };
2241
+ var computeCachePolicy = (info) => effect.Effect.sync(() => {
2242
+ const fragments = /* @__PURE__ */ new Map();
2243
+ for (const definition of info.document.definitions) {
2244
+ if (definition.kind === graphql.Kind.FRAGMENT_DEFINITION) {
2245
+ fragments.set(definition.name.value, definition);
2246
+ }
2247
+ }
2248
+ const rootType = getRootType2(info.schema, info.operation.operation);
2249
+ if (!rootType) {
2250
+ return { maxAge: 0, scope: "PUBLIC" };
2251
+ }
2252
+ const defaultMaxAge = info.config.defaultMaxAge ?? 0;
2253
+ const defaultScope = info.config.defaultScope ?? "PUBLIC";
2254
+ const result = analyzeSelectionSet2(
2255
+ info.operation.selectionSet,
2256
+ rootType,
2257
+ info.schema,
2258
+ fragments,
2259
+ info.cacheHints,
2260
+ defaultMaxAge,
2261
+ defaultScope,
2262
+ void 0,
2263
+ // No parent maxAge for root
2264
+ /* @__PURE__ */ new Set()
2265
+ );
2266
+ return result;
2267
+ });
2268
+ var computeCachePolicyFromQuery = (query2, operationName, schema, cacheHints, config = {}) => effect.Effect.gen(function* () {
2269
+ const document = yield* effect.Effect.try({
2270
+ try: () => graphql.parse(query2),
2271
+ catch: (error) => new Error(`Failed to parse query: ${error}`)
2272
+ });
2273
+ const operation = yield* effect.Effect.try({
2274
+ try: () => {
2275
+ const operations = document.definitions.filter(
2276
+ (d) => d.kind === graphql.Kind.OPERATION_DEFINITION
2277
+ );
2278
+ if (operations.length === 0) {
2279
+ throw new Error("No operation found in query");
2280
+ }
2281
+ if (operationName) {
2282
+ const op = operations.find((o) => o.name?.value === operationName);
2283
+ if (!op) {
2284
+ throw new Error(`Operation "${operationName}" not found`);
2285
+ }
2286
+ return op;
2287
+ }
2288
+ if (operations.length > 1) {
2289
+ throw new Error("Multiple operations found - operationName required");
2290
+ }
2291
+ return operations[0];
2292
+ },
2293
+ catch: (error) => error
2294
+ });
2295
+ return yield* computeCachePolicy({
2296
+ document,
2297
+ operation,
2298
+ schema,
2299
+ cacheHints,
2300
+ config
2301
+ });
2302
+ });
2303
+ var toCacheControlHeader = (policy) => {
2304
+ if (policy.maxAge === 0) {
2305
+ return "no-store";
2306
+ }
2307
+ const directives = [];
2308
+ directives.push(policy.scope === "PRIVATE" ? "private" : "public");
2309
+ directives.push(`max-age=${policy.maxAge}`);
2310
+ return directives.join(", ");
2311
+ };
2312
+ function getRootType2(schema, operation) {
2313
+ switch (operation) {
2314
+ case "query":
2315
+ return schema.getQueryType() ?? null;
2316
+ case "mutation":
2317
+ return schema.getMutationType() ?? null;
2318
+ case "subscription":
2319
+ return schema.getSubscriptionType() ?? null;
2320
+ }
2321
+ }
2322
+ function getNamedType2(type) {
2323
+ if (type instanceof graphql.GraphQLNonNull || type instanceof graphql.GraphQLList) {
2324
+ return getNamedType2(type.ofType);
2325
+ }
2326
+ if (type instanceof graphql.GraphQLObjectType || type instanceof graphql.GraphQLScalarType || type instanceof graphql.GraphQLEnumType) {
2327
+ return type;
2328
+ }
2329
+ return null;
2330
+ }
2331
+ function isLeafType(type) {
2332
+ const namedType = getNamedType2(type);
2333
+ return namedType instanceof graphql.GraphQLScalarType || namedType instanceof graphql.GraphQLEnumType;
2334
+ }
2335
+ function aggregatePolicy(acc, policy) {
2336
+ if (acc.minMaxAge === void 0) {
2337
+ acc.minMaxAge = policy.maxAge;
2338
+ } else {
2339
+ acc.minMaxAge = Math.min(acc.minMaxAge, policy.maxAge);
2340
+ }
2341
+ if (policy.scope === "PRIVATE") {
2342
+ acc.hasPrivate = true;
2343
+ }
2344
+ }
2345
+ function analyzeFragmentSpread2(fragmentName, ctx, parentMaxAge, visitedFragments) {
2346
+ if (visitedFragments.has(fragmentName)) {
2347
+ return void 0;
2348
+ }
2349
+ const fragment = ctx.fragments.get(fragmentName);
2350
+ if (!fragment) {
2351
+ return void 0;
2352
+ }
2353
+ const fragmentType = ctx.schema.getType(fragment.typeCondition.name.value);
2354
+ if (!(fragmentType instanceof graphql.GraphQLObjectType)) {
2355
+ return void 0;
2356
+ }
2357
+ const newVisited = new Set(visitedFragments);
2358
+ newVisited.add(fragmentName);
2359
+ return analyzeSelectionSet2(fragment.selectionSet, fragmentType, ctx, parentMaxAge, newVisited);
2360
+ }
2361
+ function analyzeInlineFragment2(selection, parentType, ctx, parentMaxAge, visitedFragments) {
2362
+ let targetType = parentType;
2363
+ if (selection.typeCondition) {
2364
+ const conditionType = ctx.schema.getType(selection.typeCondition.name.value);
2365
+ if (conditionType instanceof graphql.GraphQLObjectType) {
2366
+ targetType = conditionType;
2367
+ }
2368
+ }
2369
+ return analyzeSelectionSet2(
2370
+ selection.selectionSet,
2371
+ targetType,
2372
+ ctx,
2373
+ parentMaxAge,
2374
+ visitedFragments
2375
+ );
2376
+ }
2377
+ function lookupEffectiveCacheHint(parentTypeName, fieldName, returnType, cacheHints) {
2378
+ const fieldKey = `${parentTypeName}.${fieldName}`;
2379
+ const fieldHint = cacheHints.get(fieldKey);
2380
+ if (fieldHint) return fieldHint;
2381
+ const namedType = getNamedType2(returnType);
2382
+ return namedType ? cacheHints.get(namedType.name) : void 0;
2383
+ }
2384
+ function computeFieldMaxAge(hint, fieldType, parentMaxAge, defaultMaxAge) {
2385
+ if (hint) {
2386
+ if (hint.inheritMaxAge && parentMaxAge !== void 0) {
2387
+ return parentMaxAge;
2388
+ }
2389
+ if (hint.maxAge !== void 0) {
2390
+ return hint.maxAge;
2391
+ }
2392
+ }
2393
+ if (isLeafType(fieldType) && parentMaxAge !== void 0) {
2394
+ return parentMaxAge;
2395
+ }
2396
+ return defaultMaxAge;
2397
+ }
2398
+ function analyzeSelectionSet2(selectionSet, parentType, schemaOrCtx, fragmentsOrParentMaxAge, cacheHintsOrVisited, defaultMaxAge, defaultScope, parentMaxAge, visitedFragments) {
2399
+ let ctx;
2400
+ let actualParentMaxAge;
2401
+ let actualVisitedFragments;
2402
+ if (schemaOrCtx instanceof graphql.GraphQLSchema) {
2403
+ ctx = {
2404
+ schema: schemaOrCtx,
2405
+ fragments: fragmentsOrParentMaxAge,
2406
+ cacheHints: cacheHintsOrVisited,
2407
+ defaultMaxAge,
2408
+ defaultScope
2409
+ };
2410
+ actualParentMaxAge = parentMaxAge;
2411
+ actualVisitedFragments = visitedFragments;
2412
+ } else {
2413
+ ctx = schemaOrCtx;
2414
+ actualParentMaxAge = fragmentsOrParentMaxAge;
2415
+ actualVisitedFragments = cacheHintsOrVisited;
2416
+ }
2417
+ const acc = { minMaxAge: void 0, hasPrivate: false };
2418
+ for (const selection of selectionSet.selections) {
2419
+ let fieldPolicy;
2420
+ switch (selection.kind) {
2421
+ case graphql.Kind.FIELD:
2422
+ fieldPolicy = analyzeField2(
2423
+ selection,
2424
+ parentType,
2425
+ ctx,
2426
+ actualParentMaxAge,
2427
+ actualVisitedFragments
2428
+ );
2429
+ break;
2430
+ case graphql.Kind.FRAGMENT_SPREAD:
2431
+ fieldPolicy = analyzeFragmentSpread2(
2432
+ selection.name.value,
2433
+ ctx,
2434
+ actualParentMaxAge,
2435
+ actualVisitedFragments
2436
+ );
2437
+ break;
2438
+ case graphql.Kind.INLINE_FRAGMENT:
2439
+ fieldPolicy = analyzeInlineFragment2(
2440
+ selection,
2441
+ parentType,
2442
+ ctx,
2443
+ actualParentMaxAge,
2444
+ actualVisitedFragments
2445
+ );
2446
+ break;
2447
+ }
2448
+ if (fieldPolicy) {
2449
+ aggregatePolicy(acc, fieldPolicy);
2450
+ }
2451
+ }
2452
+ return {
2453
+ maxAge: acc.minMaxAge ?? ctx.defaultMaxAge,
2454
+ scope: acc.hasPrivate ? "PRIVATE" : ctx.defaultScope
2455
+ };
2456
+ }
2457
+ function analyzeField2(field2, parentType, ctx, parentMaxAge, visitedFragments) {
2458
+ const fieldName = field2.name.value;
2459
+ if (fieldName.startsWith("__")) {
2460
+ return { maxAge: Infinity, scope: "PUBLIC" };
2461
+ }
2462
+ const schemaField = parentType.getFields()[fieldName];
2463
+ if (!schemaField) {
2464
+ return { maxAge: ctx.defaultMaxAge, scope: ctx.defaultScope };
2465
+ }
2466
+ const effectiveHint = lookupEffectiveCacheHint(
2467
+ parentType.name,
2468
+ fieldName,
2469
+ schemaField.type,
2470
+ ctx.cacheHints
2471
+ );
2472
+ const fieldMaxAge = computeFieldMaxAge(
2473
+ effectiveHint,
2474
+ schemaField.type,
2475
+ parentMaxAge,
2476
+ ctx.defaultMaxAge
2477
+ );
2478
+ const fieldScope = effectiveHint?.scope ?? ctx.defaultScope;
2479
+ const namedType = getNamedType2(schemaField.type);
2480
+ if (field2.selectionSet && namedType instanceof graphql.GraphQLObjectType) {
2481
+ const nestedPolicy = analyzeSelectionSet2(
2482
+ field2.selectionSet,
2483
+ namedType,
2484
+ ctx,
2485
+ fieldMaxAge,
2486
+ visitedFragments
2487
+ );
2488
+ return {
2489
+ maxAge: Math.min(fieldMaxAge, nestedPolicy.maxAge),
2490
+ scope: fieldScope === "PRIVATE" || nestedPolicy.scope === "PRIVATE" ? "PRIVATE" : "PUBLIC"
2491
+ };
2492
+ }
2493
+ return { maxAge: fieldMaxAge, scope: fieldScope };
2494
+ }
2495
+ var CacheControlConfigFromEnv = effect.Config.all({
2496
+ enabled: effect.Config.boolean("GRAPHQL_CACHE_CONTROL_ENABLED").pipe(effect.Config.withDefault(true)),
2497
+ defaultMaxAge: effect.Config.number("GRAPHQL_CACHE_CONTROL_DEFAULT_MAX_AGE").pipe(effect.Config.withDefault(0)),
2498
+ defaultScope: effect.Config.string("GRAPHQL_CACHE_CONTROL_DEFAULT_SCOPE").pipe(
2499
+ effect.Config.withDefault("PUBLIC"),
2500
+ effect.Config.map((s) => s === "PRIVATE" ? "PRIVATE" : "PUBLIC")
2501
+ ),
2502
+ calculateHttpHeaders: effect.Config.boolean("GRAPHQL_CACHE_CONTROL_HTTP_HEADERS").pipe(
2503
+ effect.Config.withDefault(true)
2504
+ )
2505
+ });
2506
+
2507
+ // src/server/router.ts
2508
+ var defaultErrorHandler = (cause) => (process.env.NODE_ENV !== "production" ? effect.Effect.logError("GraphQL error", cause) : effect.Effect.void).pipe(
2509
+ effect.Effect.andThen(
2510
+ platform.HttpServerResponse.json(
2511
+ {
2512
+ errors: [
2513
+ {
2514
+ message: "An error occurred processing your request"
2515
+ }
2516
+ ]
2517
+ },
2518
+ { status: 500 }
2519
+ ).pipe(effect.Effect.orDie)
2520
+ )
2521
+ );
2522
+ var GraphQLRequestBodySchema = effect.Schema.Struct({
2523
+ query: effect.Schema.String,
2524
+ variables: effect.Schema.optionalWith(effect.Schema.Record({ key: effect.Schema.String, value: effect.Schema.Unknown }), {
2525
+ as: "Option"
2526
+ }),
2527
+ operationName: effect.Schema.optionalWith(effect.Schema.String, { as: "Option" })
2528
+ });
2529
+ var decodeRequestBody = platform.HttpIncomingMessage.schemaBodyJson(GraphQLRequestBodySchema);
2530
+ var parseGraphQLQuery = (query2, extensionsService) => {
2531
+ try {
2532
+ const document = graphql.parse(query2);
2533
+ return effect.Effect.succeed({ ok: true, document });
2534
+ } catch (parseError) {
2535
+ return extensionsService.get().pipe(
2536
+ effect.Effect.flatMap(
2537
+ (extensionData) => platform.HttpServerResponse.json({
2538
+ errors: [{ message: String(parseError) }],
2539
+ extensions: Object.keys(extensionData).length > 0 ? extensionData : void 0
2540
+ }).pipe(
2541
+ effect.Effect.orDie,
2542
+ effect.Effect.map((response) => ({ ok: false, response }))
2543
+ )
2544
+ )
2545
+ );
2546
+ }
2547
+ };
2548
+ var runComplexityValidation = (body, schema, fieldComplexities, complexityConfig) => {
2549
+ if (!complexityConfig) {
2550
+ return effect.Effect.void;
2551
+ }
2552
+ return validateComplexity(
2553
+ body.query,
2554
+ body.operationName,
2555
+ body.variables,
2556
+ schema,
2557
+ fieldComplexities,
2558
+ complexityConfig
2559
+ ).pipe(
2560
+ effect.Effect.catchTag("ComplexityLimitExceededError", (error) => effect.Effect.fail(error)),
2561
+ effect.Effect.catchTag(
2562
+ "ComplexityAnalysisError",
2563
+ (error) => effect.Effect.logWarning("Complexity analysis failed", error)
2564
+ )
2565
+ );
2566
+ };
2567
+ var isPromiseLike = (value) => value !== null && typeof value === "object" && "then" in value && typeof value.then === "function";
2568
+ var executeGraphQLQuery = (schema, document, variables, operationName, runtime) => {
2569
+ const tryExecute = effect.Effect.try({
2570
+ try: () => graphql.execute({
2571
+ schema,
2572
+ document,
2573
+ variableValues: variables,
2574
+ operationName,
2575
+ contextValue: { runtime }
2576
+ }),
2577
+ catch: (error) => new Error(String(error))
2578
+ });
2579
+ return tryExecute.pipe(
2580
+ effect.Effect.flatMap((executeResult) => {
2581
+ if (isPromiseLike(executeResult)) {
2582
+ return effect.Effect.promise(() => executeResult);
2583
+ }
2584
+ return effect.Effect.succeed(executeResult);
2585
+ })
2586
+ );
2587
+ };
2588
+ var computeCacheControlHeader = (document, operationName, schema, cacheHints, cacheControlConfig) => {
2589
+ if (cacheControlConfig?.enabled === false || cacheControlConfig?.calculateHttpHeaders === false) {
2590
+ return effect.Effect.succeed(void 0);
2591
+ }
2592
+ const operations = document.definitions.filter(
2593
+ (d) => d.kind === graphql.Kind.OPERATION_DEFINITION
2594
+ );
2595
+ const operation = operationName ? operations.find((o) => o.name?.value === operationName) : operations[0];
2596
+ if (!operation || operation.operation === "mutation") {
2597
+ return effect.Effect.succeed(void 0);
2598
+ }
2599
+ return computeCachePolicy({
2600
+ document,
2601
+ operation,
2602
+ schema,
2603
+ cacheHints,
2604
+ config: cacheControlConfig ?? {}
2605
+ }).pipe(effect.Effect.map(toCacheControlHeader));
2606
+ };
2607
+ var buildGraphQLResponse = (result, extensionData, cacheControlHeader) => {
2608
+ const finalResult = Object.keys(extensionData).length > 0 ? {
2609
+ ...result,
2610
+ extensions: {
2611
+ ...result.extensions,
2612
+ ...extensionData
2613
+ }
2614
+ } : result;
2615
+ const responseHeaders = cacheControlHeader ? { "cache-control": cacheControlHeader } : void 0;
2616
+ return platform.HttpServerResponse.json(finalResult, { headers: responseHeaders }).pipe(effect.Effect.orDie);
2617
+ };
2618
+ var handleComplexityError = (error) => platform.HttpServerResponse.json(
2619
+ {
2620
+ errors: [
2621
+ {
2622
+ message: error.message,
2623
+ extensions: {
2624
+ code: "COMPLEXITY_LIMIT_EXCEEDED",
2625
+ limitType: error.limitType,
2626
+ limit: error.limit,
2627
+ actual: error.actual
2628
+ }
2629
+ }
2630
+ ]
2631
+ },
2632
+ { status: 400 }
2633
+ ).pipe(effect.Effect.orDie);
2634
+ var makeGraphQLRouter = (schema, layer, options = {}) => {
2635
+ const resolvedConfig = normalizeConfig(options);
2636
+ const fieldComplexities = options.fieldComplexities ?? /* @__PURE__ */ new Map();
2637
+ const cacheHints = options.cacheHints ?? /* @__PURE__ */ new Map();
2638
+ const extensions = options.extensions ?? [];
2639
+ const errorHandler = options.errorHandler ?? defaultErrorHandler;
2640
+ const graphqlHandler = effect.Effect.gen(function* () {
2641
+ const extensionsService = yield* makeExtensionsService();
2642
+ const runtime = yield* effect.Effect.runtime();
2643
+ const request = yield* platform.HttpServerRequest.HttpServerRequest;
2644
+ const parsedBody = yield* decodeRequestBody(request);
2645
+ const body = {
2646
+ query: parsedBody.query,
2647
+ variables: parsedBody.variables._tag === "Some" ? parsedBody.variables.value : void 0,
2648
+ operationName: parsedBody.operationName._tag === "Some" ? parsedBody.operationName.value : void 0
2649
+ };
2650
+ const parseResult = yield* parseGraphQLQuery(body.query, extensionsService);
2651
+ if (!parseResult.ok) {
2652
+ return parseResult.response;
2653
+ }
2654
+ const document = parseResult.document;
2655
+ yield* runParseHooks(extensions, body.query, document).pipe(
2656
+ effect.Effect.provideService(ExtensionsService, extensionsService)
2657
+ );
2658
+ const validationRules = resolvedConfig.introspection ? void 0 : graphql.specifiedRules.concat(graphql.NoSchemaIntrospectionCustomRule);
2659
+ const validationErrors = graphql.validate(schema, document, validationRules);
2660
+ yield* runValidateHooks(extensions, document, validationErrors).pipe(
2661
+ effect.Effect.provideService(ExtensionsService, extensionsService)
2662
+ );
2663
+ if (validationErrors.length > 0) {
2664
+ const extensionData2 = yield* extensionsService.get();
2665
+ return yield* platform.HttpServerResponse.json(
2666
+ {
2667
+ errors: validationErrors.map((e) => ({
2668
+ message: e.message,
2669
+ locations: e.locations,
2670
+ path: e.path
2671
+ })),
2672
+ extensions: Object.keys(extensionData2).length > 0 ? extensionData2 : void 0
2673
+ },
2674
+ { status: 400 }
2675
+ );
2676
+ }
2677
+ yield* runComplexityValidation(body, schema, fieldComplexities, resolvedConfig.complexity);
2678
+ yield* runExecuteStartHooks(extensions, {
2679
+ source: body.query,
2680
+ document,
2681
+ variableValues: body.variables,
2682
+ operationName: body.operationName,
2683
+ schema,
2684
+ fieldComplexities
2685
+ }).pipe(effect.Effect.provideService(ExtensionsService, extensionsService));
2686
+ const result = yield* executeGraphQLQuery(
2687
+ schema,
2688
+ document,
2689
+ body.variables,
2690
+ body.operationName,
2691
+ runtime
2692
+ );
2693
+ yield* runExecuteEndHooks(extensions, result).pipe(
2694
+ effect.Effect.provideService(ExtensionsService, extensionsService)
2695
+ );
2696
+ const extensionData = yield* extensionsService.get();
2697
+ const cacheControlHeader = yield* computeCacheControlHeader(
2698
+ document,
2699
+ body.operationName,
2700
+ schema,
2701
+ cacheHints,
2702
+ resolvedConfig.cacheControl
2703
+ );
2704
+ return yield* buildGraphQLResponse(result, extensionData, cacheControlHeader);
2705
+ }).pipe(
2706
+ effect.Effect.provide(layer),
2707
+ effect.Effect.catchAll((error) => {
2708
+ if (error instanceof ComplexityLimitExceededError) {
2709
+ return handleComplexityError(error);
2710
+ }
2711
+ return effect.Effect.fail(error);
2712
+ }),
2713
+ effect.Effect.catchAllCause(errorHandler)
2714
+ );
2715
+ let router = platform.HttpRouter.empty.pipe(
2716
+ platform.HttpRouter.post(resolvedConfig.path, graphqlHandler)
2717
+ );
2718
+ if (resolvedConfig.graphiql) {
2719
+ const { path, endpoint, subscriptionEndpoint } = resolvedConfig.graphiql;
2720
+ router = router.pipe(
2721
+ platform.HttpRouter.get(
2722
+ path,
2723
+ platform.HttpServerResponse.html(graphiqlHtml(endpoint, subscriptionEndpoint))
2724
+ )
2725
+ );
2726
+ }
2727
+ return router;
2728
+ };
2729
+
2730
+ // src/server/schema-builder-extensions.ts
2731
+ var toRouter = (builder, layer, options) => {
2732
+ const schema = builder.buildSchema();
2733
+ const fieldComplexities = builder.getFieldComplexities();
2734
+ const cacheHints = builder.getCacheHints();
2735
+ return makeGraphQLRouter(schema, layer, { ...options, fieldComplexities, cacheHints });
2736
+ };
2737
+ var WebSocketError = class extends effect.Data.TaggedError("WebSocketError") {
2738
+ };
2739
+ var createConnectionContext = (extra) => ({
2740
+ runtime: extra.runtime,
2741
+ connectionParams: extra.connectionParams,
2742
+ socket: extra.socket
2743
+ });
2744
+ var makeOnConnectHandler = (options) => {
2745
+ if (!options?.onConnect) return void 0;
2746
+ return async (ctx) => {
2747
+ const extra = ctx.extra;
2748
+ try {
2749
+ const result = await effect.Runtime.runPromise(extra.runtime)(
2750
+ options.onConnect(ctx.connectionParams ?? {})
2751
+ );
2752
+ if (typeof result === "object" && result !== null) {
2753
+ Object.assign(extra.connectionParams, result);
2754
+ }
2755
+ return result !== false;
2756
+ } catch {
2757
+ return false;
2758
+ }
2759
+ };
2760
+ };
2761
+ var makeOnDisconnectHandler = (options) => {
2762
+ if (!options?.onDisconnect) return void 0;
2763
+ return async (ctx) => {
2764
+ const extra = ctx.extra;
2765
+ await effect.Runtime.runPromise(extra.runtime)(
2766
+ options.onDisconnect(createConnectionContext(extra))
2767
+ ).catch(() => {
2768
+ });
2769
+ };
2770
+ };
2771
+ var makeOnSubscribeHandler = (options, schema, complexityConfig, fieldComplexities) => {
2772
+ return async (ctx, id, payload) => {
2773
+ const extra = ctx.extra;
2774
+ const connectionCtx = createConnectionContext(extra);
2775
+ if (complexityConfig) {
2776
+ const validationEffect = validateComplexity(
2777
+ payload.query,
2778
+ payload.operationName ?? void 0,
2779
+ payload.variables ?? void 0,
2780
+ schema,
2781
+ fieldComplexities,
2782
+ complexityConfig
2783
+ ).pipe(
2784
+ effect.Effect.catchAll((error) => {
2785
+ if (error._tag === "ComplexityLimitExceededError") {
2786
+ throw new graphql.GraphQLError(error.message, {
2787
+ extensions: {
2788
+ code: "COMPLEXITY_LIMIT_EXCEEDED",
2789
+ limitType: error.limitType,
2790
+ limit: error.limit,
2791
+ actual: error.actual
2792
+ }
2793
+ });
2794
+ }
2795
+ return effect.Effect.logWarning("Complexity analysis failed for subscription", error);
2796
+ })
2797
+ );
2798
+ await effect.Effect.runPromise(validationEffect);
2799
+ }
2800
+ if (options?.onSubscribe) {
2801
+ await effect.Runtime.runPromise(extra.runtime)(
2802
+ options.onSubscribe(connectionCtx, {
2803
+ id,
2804
+ payload: {
2805
+ query: payload.query,
2806
+ variables: payload.variables ?? void 0,
2807
+ operationName: payload.operationName ?? void 0,
2808
+ extensions: payload.extensions ?? void 0
2809
+ }
2810
+ })
2811
+ );
2812
+ }
2813
+ };
2814
+ };
2815
+ var makeOnCompleteHandler = (options) => {
2816
+ if (!options?.onComplete) return void 0;
2817
+ return async (ctx, id, _payload) => {
2818
+ const extra = ctx.extra;
2819
+ await effect.Runtime.runPromise(extra.runtime)(
2820
+ options.onComplete(createConnectionContext(extra), { id })
2821
+ ).catch(() => {
2822
+ });
2823
+ };
2824
+ };
2825
+ var makeOnErrorHandler = (options) => {
2826
+ if (!options?.onError) return void 0;
2827
+ return async (ctx, _id, _payload, errors) => {
2828
+ const extra = ctx.extra;
2829
+ await effect.Runtime.runPromise(extra.runtime)(
2830
+ options.onError(createConnectionContext(extra), errors)
2831
+ ).catch(() => {
2832
+ });
2833
+ };
2834
+ };
2835
+ var createGraphqlWsSocketAdapter = (socket, runtime) => {
2836
+ let messageCallback = null;
2837
+ return {
2838
+ adapter: {
2839
+ protocol: socket.protocol,
2840
+ send: (data) => effect.Runtime.runPromise(runtime)(
2841
+ socket.send(data).pipe(effect.Effect.catchAll((error) => effect.Effect.logError("WebSocket send error", error)))
2842
+ ),
2843
+ close: (code, reason) => {
2844
+ effect.Runtime.runPromise(runtime)(socket.close(code, reason)).catch(() => {
2845
+ });
2846
+ },
2847
+ onMessage: (cb) => {
2848
+ messageCallback = cb;
2849
+ },
2850
+ onPong: (_payload) => {
2851
+ }
2852
+ },
2853
+ dispatchMessage: async (message) => {
2854
+ if (messageCallback) {
2855
+ await messageCallback(message);
2856
+ }
2857
+ }
2858
+ };
2859
+ };
2860
+ var runConnectionLifecycle = (socket, wsServer, extra) => effect.Effect.gen(function* () {
2861
+ const messageQueue = yield* effect.Queue.unbounded();
2862
+ const closedDeferred = yield* effect.Deferred.make();
2863
+ const messageFiber = yield* effect.Effect.fork(
2864
+ effect.Stream.runForEach(socket.messages, (msg) => effect.Queue.offer(messageQueue, msg)).pipe(
2865
+ effect.Effect.catchAll((error) => effect.Deferred.fail(closedDeferred, error))
2866
+ )
2867
+ );
2868
+ const closeFiber = yield* effect.Effect.fork(
2869
+ socket.closed.pipe(
2870
+ effect.Effect.tap((event) => effect.Deferred.succeed(closedDeferred, event)),
2871
+ effect.Effect.catchAll((error) => effect.Deferred.fail(closedDeferred, error))
2872
+ )
2873
+ );
2874
+ const { adapter, dispatchMessage } = createGraphqlWsSocketAdapter(socket, extra.runtime);
2875
+ const closedHandler = wsServer.opened(adapter, extra);
2876
+ const processMessagesFiber = yield* effect.Effect.fork(
2877
+ effect.Effect.gen(function* () {
2878
+ while (true) {
2879
+ const message = yield* effect.Queue.take(messageQueue);
2880
+ yield* effect.Effect.tryPromise({
2881
+ try: () => dispatchMessage(message),
2882
+ catch: (error) => error
2883
+ }).pipe(effect.Effect.catchAll(() => effect.Effect.void));
2884
+ }
2885
+ })
2886
+ );
2887
+ yield* effect.Deferred.await(closedDeferred).pipe(
2888
+ effect.Effect.catchAll(() => effect.Effect.succeed({ code: 1e3, reason: "Error" }))
2889
+ );
2890
+ closedHandler(1e3, "Connection closed");
2891
+ yield* effect.Fiber.interrupt(messageFiber);
2892
+ yield* effect.Fiber.interrupt(closeFiber);
2893
+ yield* effect.Fiber.interrupt(processMessagesFiber);
2894
+ yield* effect.Queue.shutdown(messageQueue);
2895
+ }).pipe(
2896
+ effect.Effect.catchAllCause(() => effect.Effect.void),
2897
+ effect.Effect.scoped
2898
+ );
2899
+ var makeGraphQLWSHandler = (schema, layer, options) => {
2900
+ const complexityConfig = options?.complexity;
2901
+ const fieldComplexities = options?.fieldComplexities ?? /* @__PURE__ */ new Map();
2902
+ const serverOptions = {
2903
+ schema,
2904
+ context: async (ctx) => {
2905
+ const extra = ctx.extra;
2906
+ return {
2907
+ runtime: extra.runtime,
2908
+ ...extra.connectionParams
2909
+ };
2910
+ },
2911
+ subscribe: async (args) => graphql.subscribe(args),
2912
+ onConnect: makeOnConnectHandler(options),
2913
+ onDisconnect: makeOnDisconnectHandler(options),
2914
+ onSubscribe: makeOnSubscribeHandler(options, schema, complexityConfig, fieldComplexities),
2915
+ onComplete: makeOnCompleteHandler(options),
2916
+ onError: makeOnErrorHandler(options)
2917
+ };
2918
+ const wsServer = graphqlWs.makeServer(serverOptions);
2919
+ return (socket) => effect.Effect.gen(function* () {
2920
+ const runtime = yield* effect.Effect.provide(effect.Effect.runtime(), layer);
2921
+ const extra = {
2922
+ socket,
2923
+ runtime,
2924
+ connectionParams: {}
2925
+ };
2926
+ yield* runConnectionLifecycle(socket, wsServer, extra);
2927
+ }).pipe(
2928
+ effect.Effect.catchAllCause(() => effect.Effect.void),
2929
+ effect.Effect.scoped
2930
+ );
2931
+ };
2932
+ var WS_CLOSED = 3;
2933
+ var toEffectWebSocketFromWs = (ws) => {
2934
+ const messagesEffect = effect.Effect.gen(function* () {
2935
+ const queue = yield* effect.Queue.unbounded();
2936
+ const closed = yield* effect.Deferred.make();
2937
+ ws.on("message", (data) => {
2938
+ const message = data.toString();
2939
+ effect.Effect.runPromise(effect.Queue.offer(queue, message)).catch(() => {
2940
+ });
2941
+ });
2942
+ ws.on("error", (error) => {
2943
+ effect.Effect.runPromise(effect.Deferred.fail(closed, new WebSocketError({ cause: error }))).catch(() => {
2944
+ });
2945
+ });
2946
+ ws.on("close", (code, reason) => {
2947
+ effect.Effect.runPromise(
2948
+ effect.Queue.shutdown(queue).pipe(
2949
+ effect.Effect.andThen(effect.Deferred.succeed(closed, { code, reason: reason.toString() }))
2950
+ )
2951
+ ).catch(() => {
2952
+ });
2953
+ });
2954
+ return { queue, closed };
2955
+ });
2956
+ const messages = effect.Stream.unwrap(
2957
+ messagesEffect.pipe(
2958
+ effect.Effect.map(({ queue }) => effect.Stream.fromQueue(queue).pipe(effect.Stream.catchAll(() => effect.Stream.empty)))
2959
+ )
2960
+ );
2961
+ return {
2962
+ protocol: ws.protocol || "graphql-transport-ws",
2963
+ send: (data) => effect.Effect.async((resume) => {
2964
+ ws.send(data, (error) => {
2965
+ if (error) {
2966
+ resume(effect.Effect.fail(new WebSocketError({ cause: error })));
2967
+ } else {
2968
+ resume(effect.Effect.succeed(void 0));
2969
+ }
2970
+ });
2971
+ }),
2972
+ close: (code, reason) => effect.Effect.sync(() => {
2973
+ ws.close(code ?? 1e3, reason ?? "");
2974
+ }),
2975
+ messages,
2976
+ closed: effect.Effect.async((resume) => {
2977
+ if (ws.readyState === WS_CLOSED) {
2978
+ resume(effect.Effect.succeed({ code: 1e3, reason: "" }));
2979
+ return;
2980
+ }
2981
+ const onClose = (code, reason) => {
2982
+ cleanup();
2983
+ resume(effect.Effect.succeed({ code, reason: reason.toString() }));
2984
+ };
2985
+ const onError = (error) => {
2986
+ cleanup();
2987
+ resume(effect.Effect.fail(new WebSocketError({ cause: error })));
2988
+ };
2989
+ const cleanup = () => {
2990
+ ws.removeListener("close", onClose);
2991
+ ws.removeListener("error", onError);
2992
+ };
2993
+ ws.on("close", onClose);
2994
+ ws.on("error", onError);
2995
+ return effect.Effect.sync(cleanup);
2996
+ })
2997
+ };
2998
+ };
2999
+ var SSE_HEADERS = {
3000
+ "Content-Type": "text/event-stream",
3001
+ "Cache-Control": "no-cache",
3002
+ Connection: "keep-alive",
3003
+ "X-Accel-Buffering": "no"
3004
+ // Disable nginx buffering
3005
+ };
3006
+ var SSEError = class extends effect.Data.TaggedError("SSEError") {
3007
+ };
3008
+ var formatNextEvent = (result) => ({
3009
+ event: "next",
3010
+ data: JSON.stringify(result)
3011
+ });
3012
+ var formatErrorEvent = (errors) => ({
3013
+ event: "error",
3014
+ data: JSON.stringify({ errors })
3015
+ });
3016
+ var formatCompleteEvent = () => ({
3017
+ event: "complete",
3018
+ data: ""
3019
+ });
3020
+ var formatSSEMessage = (event) => {
3021
+ const lines = [`event: ${event.event}`];
3022
+ if (event.data) {
3023
+ lines.push(`data: ${event.data}`);
3024
+ }
3025
+ lines.push("", "");
3026
+ return lines.join("\n");
3027
+ };
3028
+ var makeSSESubscriptionStream = (schema, layer, request, headers, options) => {
3029
+ const complexityConfig = options?.complexity;
3030
+ const fieldComplexities = options?.fieldComplexities ?? /* @__PURE__ */ new Map();
3031
+ return effect.Stream.unwrap(
3032
+ effect.Effect.gen(function* () {
3033
+ const runtime = yield* effect.Effect.provide(effect.Effect.runtime(), layer);
3034
+ let connectionContext = {};
3035
+ if (options?.onConnect) {
3036
+ try {
3037
+ connectionContext = yield* effect.Effect.provide(options.onConnect(request, headers), layer);
3038
+ } catch {
3039
+ return effect.Stream.make(
3040
+ formatErrorEvent([
3041
+ new graphql.GraphQLError("Subscription connection rejected", {
3042
+ extensions: { code: "CONNECTION_REJECTED" }
3043
+ })
3044
+ ]),
3045
+ formatCompleteEvent()
3046
+ );
3047
+ }
3048
+ }
3049
+ let document;
3050
+ try {
3051
+ document = graphql.parse(request.query);
3052
+ } catch (syntaxError) {
3053
+ return effect.Stream.make(formatErrorEvent([syntaxError]), formatCompleteEvent());
3054
+ }
3055
+ const validationErrors = graphql.validate(schema, document);
3056
+ if (validationErrors.length > 0) {
3057
+ return effect.Stream.make(formatErrorEvent(validationErrors), formatCompleteEvent());
3058
+ }
3059
+ const operations = document.definitions.filter(
3060
+ (d) => d.kind === graphql.Kind.OPERATION_DEFINITION
3061
+ );
3062
+ const operation = request.operationName ? operations.find((o) => o.name?.value === request.operationName) : operations[0];
3063
+ if (!operation) {
3064
+ return effect.Stream.make(
3065
+ formatErrorEvent([new graphql.GraphQLError("No operation found in query")]),
3066
+ formatCompleteEvent()
3067
+ );
3068
+ }
3069
+ if (operation.operation !== "subscription") {
3070
+ return effect.Stream.make(
3071
+ formatErrorEvent([
3072
+ new graphql.GraphQLError(
3073
+ `SSE endpoint only supports subscriptions, received: ${operation.operation}`,
3074
+ { extensions: { code: "OPERATION_NOT_SUPPORTED" } }
3075
+ )
3076
+ ]),
3077
+ formatCompleteEvent()
3078
+ );
3079
+ }
3080
+ if (complexityConfig) {
3081
+ const complexityResult = yield* validateComplexity(
3082
+ request.query,
3083
+ request.operationName,
3084
+ request.variables,
3085
+ schema,
3086
+ fieldComplexities,
3087
+ complexityConfig
3088
+ ).pipe(
3089
+ effect.Effect.map(() => null),
3090
+ effect.Effect.catchAll((error) => {
3091
+ if (error._tag === "ComplexityLimitExceededError") {
3092
+ return effect.Effect.succeed(
3093
+ new graphql.GraphQLError(error.message, {
3094
+ extensions: {
3095
+ code: "COMPLEXITY_LIMIT_EXCEEDED",
3096
+ limitType: error.limitType,
3097
+ limit: error.limit,
3098
+ actual: error.actual
3099
+ }
3100
+ })
3101
+ );
3102
+ }
3103
+ return effect.Effect.logWarning("Complexity analysis failed for SSE subscription", error).pipe(
3104
+ effect.Effect.map(() => null)
3105
+ );
3106
+ })
3107
+ );
3108
+ if (complexityResult) {
3109
+ return effect.Stream.make(formatErrorEvent([complexityResult]), formatCompleteEvent());
3110
+ }
3111
+ }
3112
+ const ctx = {
3113
+ runtime,
3114
+ request,
3115
+ connectionContext
3116
+ };
3117
+ if (options?.onSubscribe) {
3118
+ yield* effect.Effect.provide(options.onSubscribe(ctx), layer).pipe(
3119
+ effect.Effect.catchAll(() => effect.Effect.void)
3120
+ );
3121
+ }
3122
+ const graphqlContext = {
3123
+ runtime,
3124
+ ...connectionContext
3125
+ };
3126
+ const subscriptionResult = yield* effect.Effect.tryPromise({
3127
+ try: () => graphql.subscribe({
3128
+ schema,
3129
+ document,
3130
+ variableValues: request.variables,
3131
+ operationName: request.operationName ?? void 0,
3132
+ contextValue: graphqlContext
3133
+ }),
3134
+ catch: (error) => new SSEError({ cause: error })
3135
+ });
3136
+ if (!isAsyncIterable(subscriptionResult)) {
3137
+ const result = subscriptionResult;
3138
+ if (result.errors) {
3139
+ return effect.Stream.make(formatErrorEvent(result.errors), formatCompleteEvent());
3140
+ }
3141
+ return effect.Stream.make(formatNextEvent(result), formatCompleteEvent());
3142
+ }
3143
+ const asyncIterator = subscriptionResult[Symbol.asyncIterator]();
3144
+ const eventStream = effect.Stream.async((emit) => {
3145
+ let done = false;
3146
+ const iterate = async () => {
3147
+ try {
3148
+ while (!done) {
3149
+ const result = await asyncIterator.next();
3150
+ if (result.done) {
3151
+ emit.end();
3152
+ break;
3153
+ }
3154
+ emit.single(formatNextEvent(result.value));
3155
+ }
3156
+ } catch (error) {
3157
+ if (!done) {
3158
+ emit.single(
3159
+ formatErrorEvent([
3160
+ error instanceof graphql.GraphQLError ? error : new graphql.GraphQLError(
3161
+ error instanceof Error ? error.message : "Subscription error",
3162
+ { extensions: { code: "SUBSCRIPTION_ERROR" } }
3163
+ )
3164
+ ])
3165
+ );
3166
+ emit.end();
3167
+ }
3168
+ }
3169
+ };
3170
+ iterate();
3171
+ return effect.Effect.sync(() => {
3172
+ done = true;
3173
+ asyncIterator.return?.();
3174
+ });
3175
+ });
3176
+ return eventStream.pipe(
3177
+ effect.Stream.onDone(
3178
+ () => effect.Effect.gen(function* () {
3179
+ yield* effect.Effect.sync(() => {
3180
+ });
3181
+ }).pipe(effect.Effect.asVoid)
3182
+ ),
3183
+ effect.Stream.concat(effect.Stream.make(formatCompleteEvent())),
3184
+ effect.Stream.onDone(() => {
3185
+ if (options?.onComplete) {
3186
+ return effect.Effect.provide(options.onComplete(ctx), layer).pipe(
3187
+ effect.Effect.catchAll(() => effect.Effect.void)
3188
+ );
3189
+ }
3190
+ return effect.Effect.void;
3191
+ })
3192
+ );
3193
+ }).pipe(
3194
+ effect.Effect.catchAll(
3195
+ (error) => effect.Effect.succeed(
3196
+ effect.Stream.make(
3197
+ formatErrorEvent([
3198
+ new graphql.GraphQLError(error instanceof Error ? error.message : "Internal error", {
3199
+ extensions: { code: "INTERNAL_ERROR" }
3200
+ })
3201
+ ]),
3202
+ formatCompleteEvent()
3203
+ )
3204
+ )
3205
+ )
3206
+ )
3207
+ );
3208
+ };
3209
+ var makeGraphQLSSEHandler = (schema, layer, options) => {
3210
+ return (request, headers) => makeSSESubscriptionStream(schema, layer, request, headers, options);
3211
+ };
3212
+ function isAsyncIterable(value) {
3213
+ return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
3214
+ }
3215
+ var createAnalyzerExtension = (config = {}) => {
3216
+ const {
3217
+ includeComplexity = true,
3218
+ includeDepth = true,
3219
+ includeFieldCount = false,
3220
+ includeAliasCount = false,
3221
+ key = "analyzer",
3222
+ thresholds,
3223
+ defaultFieldComplexity = 1,
3224
+ fieldComplexities: configFieldComplexities
3225
+ } = config;
3226
+ return {
3227
+ name: "analyzer",
3228
+ description: "Reports query complexity metrics in response extensions",
3229
+ onExecuteStart: (args) => effect.Effect.gen(function* () {
3230
+ const ext = yield* ExtensionsService;
3231
+ const operation = findOperation(args);
3232
+ if (!operation) {
3233
+ return;
3234
+ }
3235
+ const fieldComplexities = configFieldComplexities ?? args.fieldComplexities;
3236
+ const calculator = defaultComplexityCalculator(defaultFieldComplexity);
3237
+ const result = yield* calculator({
3238
+ document: args.document,
3239
+ operation,
3240
+ variables: args.variableValues,
3241
+ schema: args.schema,
3242
+ fieldComplexities
3243
+ }).pipe(
3244
+ effect.Effect.catchAll(
3245
+ (error) => effect.Effect.logWarning("Analyzer extension: complexity calculation failed", error).pipe(
3246
+ effect.Effect.as(null)
3247
+ )
3248
+ )
3249
+ );
3250
+ if (!result) {
3251
+ return;
3252
+ }
3253
+ yield* checkThresholds(result, thresholds);
3254
+ const output = {};
3255
+ if (includeComplexity) {
3256
+ output.complexity = result.complexity;
3257
+ }
3258
+ if (includeDepth) {
3259
+ output.depth = result.depth;
3260
+ }
3261
+ if (includeFieldCount) {
3262
+ output.fieldCount = result.fieldCount;
3263
+ }
3264
+ if (includeAliasCount) {
3265
+ output.aliasCount = result.aliasCount;
3266
+ }
3267
+ yield* ext.set(key, output);
3268
+ })
3269
+ };
3270
+ };
3271
+ function findOperation(args) {
3272
+ const operations = args.document.definitions.filter(
3273
+ (d) => d.kind === graphql.Kind.OPERATION_DEFINITION
3274
+ );
3275
+ if (operations.length === 0) {
3276
+ return null;
3277
+ }
3278
+ if (args.operationName) {
3279
+ return operations.find((o) => o.name?.value === args.operationName) ?? null;
3280
+ }
3281
+ return operations[0];
3282
+ }
3283
+ function checkThresholds(result, thresholds) {
3284
+ if (!thresholds) {
3285
+ return effect.Effect.void;
3286
+ }
3287
+ const warnings = [];
3288
+ if (thresholds.depth !== void 0 && result.depth > thresholds.depth) {
3289
+ warnings.push(`Query depth ${result.depth} exceeds threshold ${thresholds.depth}`);
3290
+ }
3291
+ if (thresholds.complexity !== void 0 && result.complexity > thresholds.complexity) {
3292
+ warnings.push(
3293
+ `Query complexity ${result.complexity} exceeds threshold ${thresholds.complexity}`
3294
+ );
3295
+ }
3296
+ if (thresholds.fieldCount !== void 0 && result.fieldCount > thresholds.fieldCount) {
3297
+ warnings.push(
3298
+ `Query field count ${result.fieldCount} exceeds threshold ${thresholds.fieldCount}`
3299
+ );
3300
+ }
3301
+ if (thresholds.aliasCount !== void 0 && result.aliasCount > thresholds.aliasCount) {
3302
+ warnings.push(
3303
+ `Query alias count ${result.aliasCount} exceeds threshold ${thresholds.aliasCount}`
3304
+ );
3305
+ }
3306
+ if (warnings.length > 0) {
3307
+ return effect.Effect.logWarning("Analyzer extension: thresholds exceeded", {
3308
+ warnings,
3309
+ result
3310
+ });
3311
+ }
3312
+ return effect.Effect.void;
3313
+ }
3314
+
3315
+ Object.defineProperty(exports, "DirectiveLocation", {
3316
+ enumerable: true,
3317
+ get: function () { return graphql.DirectiveLocation; }
3318
+ });
3319
+ Object.defineProperty(exports, "GraphQLBoolean", {
3320
+ enumerable: true,
3321
+ get: function () { return graphql.GraphQLBoolean; }
3322
+ });
3323
+ Object.defineProperty(exports, "GraphQLEnumType", {
3324
+ enumerable: true,
3325
+ get: function () { return graphql.GraphQLEnumType; }
3326
+ });
3327
+ Object.defineProperty(exports, "GraphQLFloat", {
3328
+ enumerable: true,
3329
+ get: function () { return graphql.GraphQLFloat; }
3330
+ });
3331
+ Object.defineProperty(exports, "GraphQLID", {
3332
+ enumerable: true,
3333
+ get: function () { return graphql.GraphQLID; }
3334
+ });
3335
+ Object.defineProperty(exports, "GraphQLInputObjectType", {
3336
+ enumerable: true,
3337
+ get: function () { return graphql.GraphQLInputObjectType; }
3338
+ });
3339
+ Object.defineProperty(exports, "GraphQLInt", {
3340
+ enumerable: true,
3341
+ get: function () { return graphql.GraphQLInt; }
3342
+ });
3343
+ Object.defineProperty(exports, "GraphQLInterfaceType", {
3344
+ enumerable: true,
3345
+ get: function () { return graphql.GraphQLInterfaceType; }
3346
+ });
3347
+ Object.defineProperty(exports, "GraphQLList", {
3348
+ enumerable: true,
3349
+ get: function () { return graphql.GraphQLList; }
3350
+ });
3351
+ Object.defineProperty(exports, "GraphQLNonNull", {
3352
+ enumerable: true,
3353
+ get: function () { return graphql.GraphQLNonNull; }
3354
+ });
3355
+ Object.defineProperty(exports, "GraphQLObjectType", {
3356
+ enumerable: true,
3357
+ get: function () { return graphql.GraphQLObjectType; }
3358
+ });
3359
+ Object.defineProperty(exports, "GraphQLScalarType", {
3360
+ enumerable: true,
3361
+ get: function () { return graphql.GraphQLScalarType; }
3362
+ });
3363
+ Object.defineProperty(exports, "GraphQLSchema", {
3364
+ enumerable: true,
3365
+ get: function () { return graphql.GraphQLSchema; }
3366
+ });
3367
+ Object.defineProperty(exports, "GraphQLString", {
3368
+ enumerable: true,
3369
+ get: function () { return graphql.GraphQLString; }
3370
+ });
3371
+ Object.defineProperty(exports, "GraphQLUnionType", {
3372
+ enumerable: true,
3373
+ get: function () { return graphql.GraphQLUnionType; }
3374
+ });
3375
+ Object.defineProperty(exports, "Kind", {
3376
+ enumerable: true,
3377
+ get: function () { return graphql.Kind; }
3378
+ });
3379
+ Object.defineProperty(exports, "graphql", {
3380
+ enumerable: true,
3381
+ get: function () { return graphql.graphql; }
3382
+ });
3383
+ Object.defineProperty(exports, "lexicographicSortSchema", {
3384
+ enumerable: true,
3385
+ get: function () { return graphql.lexicographicSortSchema; }
3386
+ });
3387
+ Object.defineProperty(exports, "printSchema", {
3388
+ enumerable: true,
3389
+ get: function () { return graphql.printSchema; }
3390
+ });
3391
+ exports.AuthorizationError = AuthorizationError;
3392
+ exports.CacheControlConfigFromEnv = CacheControlConfigFromEnv;
3393
+ exports.ComplexityAnalysisError = ComplexityAnalysisError;
3394
+ exports.ComplexityConfigFromEnv = ComplexityConfigFromEnv;
3395
+ exports.ComplexityLimitExceededError = ComplexityLimitExceededError;
3396
+ exports.ExtensionsService = ExtensionsService;
3397
+ exports.GraphQLError = GraphQLError2;
3398
+ exports.GraphQLRequestContext = GraphQLRequestContext;
3399
+ exports.GraphQLRouterConfigFromEnv = GraphQLRouterConfigFromEnv;
3400
+ exports.GraphQLSchemaBuilder = GraphQLSchemaBuilder;
3401
+ exports.Loader = Loader;
3402
+ exports.MissingResolverContextError = MissingResolverContextError;
3403
+ exports.NotFoundError = NotFoundError;
3404
+ exports.ResolverContext = ResolverContext;
3405
+ exports.ResolverContextStore = ResolverContextStore;
3406
+ exports.SSEError = SSEError;
3407
+ exports.SSE_HEADERS = SSE_HEADERS;
3408
+ exports.ValidationError = ValidationError;
3409
+ exports.WS_CLOSED = WS_CLOSED;
3410
+ exports.WebSocketError = WebSocketError;
3411
+ exports.combineCalculators = combineCalculators;
3412
+ exports.compose = compose;
3413
+ exports.computeCachePolicy = computeCachePolicy;
3414
+ exports.computeCachePolicyFromQuery = computeCachePolicyFromQuery;
3415
+ exports.createAnalyzerExtension = createAnalyzerExtension;
3416
+ exports.defaultComplexityCalculator = defaultComplexityCalculator;
3417
+ exports.defaultConfig = defaultConfig;
3418
+ exports.defaultErrorHandler = defaultErrorHandler;
3419
+ exports.depthOnlyCalculator = depthOnlyCalculator;
3420
+ exports.directive = directive;
3421
+ exports.enumType = enumType;
3422
+ exports.execute = execute;
3423
+ exports.extension = extension;
3424
+ exports.field = field;
3425
+ exports.formatCompleteEvent = formatCompleteEvent;
3426
+ exports.formatErrorEvent = formatErrorEvent;
3427
+ exports.formatNextEvent = formatNextEvent;
3428
+ exports.formatSSEMessage = formatSSEMessage;
3429
+ exports.get = get;
3430
+ exports.getOption = getOption;
3431
+ exports.getOrElse = getOrElse;
3432
+ exports.getSchemaName = getSchemaName;
3433
+ exports.graphiqlHtml = graphiqlHtml;
3434
+ exports.has = has;
3435
+ exports.inputType = inputType;
3436
+ exports.interfaceType = interfaceType;
3437
+ exports.make = make3;
3438
+ exports.makeExtensionsService = makeExtensionsService;
3439
+ exports.makeGraphQLRouter = makeGraphQLRouter;
3440
+ exports.makeGraphQLSSEHandler = makeGraphQLSSEHandler;
3441
+ exports.makeGraphQLWSHandler = makeGraphQLWSHandler;
3442
+ exports.makeRequestContextLayer = makeRequestContextLayer;
3443
+ exports.makeSSESubscriptionStream = makeSSESubscriptionStream;
3444
+ exports.makeStoreLayer = makeStoreLayer;
3445
+ exports.middleware = middleware;
3446
+ exports.mutation = mutation;
3447
+ exports.normalizeConfig = normalizeConfig;
3448
+ exports.objectType = objectType;
3449
+ exports.query = query;
3450
+ exports.runExecuteEndHooks = runExecuteEndHooks;
3451
+ exports.runExecuteStartHooks = runExecuteStartHooks;
3452
+ exports.runParseHooks = runParseHooks;
3453
+ exports.runValidateHooks = runValidateHooks;
3454
+ exports.scoped = scoped;
3455
+ exports.set = set;
3456
+ exports.setMany = setMany;
3457
+ exports.storeLayer = storeLayer;
3458
+ exports.subscription = subscription;
3459
+ exports.toCacheControlHeader = toCacheControlHeader;
3460
+ exports.toEffectWebSocketFromWs = toEffectWebSocketFromWs;
3461
+ exports.toGraphQLArgs = toGraphQLArgs;
3462
+ exports.toGraphQLInputType = toGraphQLInputType;
3463
+ exports.toGraphQLObjectType = toGraphQLObjectType;
3464
+ exports.toGraphQLType = toGraphQLType;
3465
+ exports.toRouter = toRouter;
3466
+ exports.unionType = unionType;
3467
+ exports.validateComplexity = validateComplexity;
3468
+ //# sourceMappingURL=index.cjs.map
3469
+ //# sourceMappingURL=index.cjs.map