@ocap/gql 1.30.24 → 1.30.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/http.cjs ADDED
@@ -0,0 +1,748 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let _ocap_schema = require("@ocap/schema");
3
+ _ocap_schema = require_rolldown_runtime.__toESM(_ocap_schema);
4
+ let graphql = require("graphql");
5
+ let lodash_get = require("lodash/get");
6
+ lodash_get = require_rolldown_runtime.__toESM(lodash_get);
7
+
8
+ //#region src/http.ts
9
+ const wrapResolver = async (_name, keys, callback) => {
10
+ const result = await callback();
11
+ const resultsMap = {};
12
+ if (Array.isArray(keys)) keys.forEach((key) => {
13
+ resultsMap[key] = result[key];
14
+ });
15
+ else resultsMap[keys] = result;
16
+ return {
17
+ code: "OK",
18
+ page: result ? result.paging || {} : null,
19
+ ...resultsMap
20
+ };
21
+ };
22
+ const formatContext = (ctx = {}) => {
23
+ return {
24
+ featureSwitch: {},
25
+ gasStakeHeaders: {
26
+ token: (0, lodash_get.default)(ctx, "headers[x-gas-payer-sig]", ""),
27
+ pk: (0, lodash_get.default)(ctx, "headers[x-gas-payer-pk]", "")
28
+ },
29
+ request: {
30
+ userAgent: (0, lodash_get.default)(ctx, "headers.user-agent"),
31
+ ip: (0, lodash_get.default)(ctx, "headers.x-real-ip") || ctx.ip || ctx._remoteAddress || ctx.connection?.remoteAddress || "-",
32
+ id: (0, lodash_get.default)(ctx, "headers[x-request-id]") || (0, lodash_get.default)(ctx, "headers[X-Request-ID]") || "-"
33
+ }
34
+ };
35
+ };
36
+ const resolvers = [
37
+ {
38
+ fn: "sendTx",
39
+ dataKey: "hash"
40
+ },
41
+ {
42
+ fn: "subscribe",
43
+ dataKey: "value"
44
+ },
45
+ {
46
+ fn: "unsubscribe",
47
+ dataKey: "result"
48
+ },
49
+ {
50
+ fn: "getAccountState",
51
+ dataKey: "state"
52
+ },
53
+ {
54
+ fn: "getAssetState",
55
+ dataKey: "state"
56
+ },
57
+ {
58
+ fn: "getFactoryState",
59
+ dataKey: "state"
60
+ },
61
+ {
62
+ fn: "getDelegateState",
63
+ dataKey: "state"
64
+ },
65
+ {
66
+ fn: "getTokenState",
67
+ dataKey: "state"
68
+ },
69
+ {
70
+ fn: "getForgeState",
71
+ dataKey: "state"
72
+ },
73
+ {
74
+ fn: "getStakeState",
75
+ dataKey: "state"
76
+ },
77
+ {
78
+ fn: "getEvidenceState",
79
+ dataKey: "state"
80
+ },
81
+ {
82
+ fn: "getRollupState",
83
+ dataKey: "state"
84
+ },
85
+ {
86
+ fn: "getRollupBlock",
87
+ dataKey: "block"
88
+ },
89
+ {
90
+ fn: "getTokenFactoryState",
91
+ dataKey: "state"
92
+ },
93
+ {
94
+ fn: "getAccountTokens",
95
+ dataKey: "tokens"
96
+ },
97
+ {
98
+ fn: "getBlock",
99
+ dataKey: "block"
100
+ },
101
+ {
102
+ fn: "getBlocks",
103
+ dataKey: "blocks"
104
+ },
105
+ {
106
+ fn: "getChainInfo",
107
+ dataKey: "info"
108
+ },
109
+ {
110
+ fn: "getConfig",
111
+ dataKey: "config"
112
+ },
113
+ {
114
+ fn: "getForgeStats",
115
+ dataKey: "forgeStats"
116
+ },
117
+ {
118
+ fn: "getNetInfo",
119
+ dataKey: "netInfo"
120
+ },
121
+ {
122
+ fn: "getNodeInfo",
123
+ dataKey: "info"
124
+ },
125
+ {
126
+ fn: "getTx",
127
+ dataKey: "info"
128
+ },
129
+ {
130
+ fn: "getUnconfirmedTxs",
131
+ dataKey: "unconfirmedTxs"
132
+ },
133
+ {
134
+ fn: "getValidatorsInfo",
135
+ dataKey: "validatorsInfo"
136
+ },
137
+ {
138
+ fn: "getLatestCheckpoint",
139
+ dataKey: "checkpoint"
140
+ },
141
+ {
142
+ fn: "getLedgerEntry",
143
+ dataKey: "entry"
144
+ },
145
+ {
146
+ fn: "getMerkleProof",
147
+ dataKey: ["proof", "checkpoint"]
148
+ },
149
+ {
150
+ fn: "getTokenDistribution",
151
+ dataKey: "data"
152
+ },
153
+ {
154
+ fn: "listTransactions",
155
+ dataKey: ["transactions"]
156
+ },
157
+ {
158
+ fn: "listAssets",
159
+ dataKey: ["assets", "account"]
160
+ },
161
+ {
162
+ fn: "listAssetTransactions",
163
+ dataKey: ["transactions"]
164
+ },
165
+ {
166
+ fn: "listFactories",
167
+ dataKey: ["factories"]
168
+ },
169
+ {
170
+ fn: "listTokens",
171
+ dataKey: ["tokens"]
172
+ },
173
+ {
174
+ fn: "listTokenFactories",
175
+ dataKey: ["tokenFactories"]
176
+ },
177
+ {
178
+ fn: "listTopAccounts",
179
+ dataKey: ["accounts"]
180
+ },
181
+ {
182
+ fn: "listBlocks",
183
+ dataKey: ["blocks"]
184
+ },
185
+ {
186
+ fn: "listStakes",
187
+ dataKey: ["stakes"]
188
+ },
189
+ {
190
+ fn: "listRollups",
191
+ dataKey: ["rollups"]
192
+ },
193
+ {
194
+ fn: "listRollupBlocks",
195
+ dataKey: ["blocks"]
196
+ },
197
+ {
198
+ fn: "listRollupValidators",
199
+ dataKey: ["validators"]
200
+ },
201
+ {
202
+ fn: "listDelegations",
203
+ dataKey: ["delegations"]
204
+ },
205
+ {
206
+ fn: "listTokenFlows",
207
+ dataKey: "data"
208
+ },
209
+ {
210
+ fn: "verifyAccountRisk",
211
+ dataKey: "data"
212
+ },
213
+ {
214
+ fn: "search",
215
+ dataKey: ["results"]
216
+ },
217
+ {
218
+ fn: "estimateGas",
219
+ dataKey: ["estimate"]
220
+ }
221
+ ];
222
+ const createResolvers = (resolver) => resolvers.reduce((acc, { fn, dataKey }) => {
223
+ acc[fn] = (args, ctx) => wrapResolver(fn, dataKey, () => {
224
+ const method = resolver[fn];
225
+ if (typeof method === "function") return method.call(resolver, args, formatContext(ctx));
226
+ return null;
227
+ });
228
+ return acc;
229
+ }, {});
230
+ const defaultErrorHandler = (err) => {
231
+ if (process.env.NODE_ENV !== "test") console.error("GraphQLError", err.originalError || err);
232
+ };
233
+ const MAX_BATCH_SIZE = 40;
234
+ const MAX_QUERY_DEPTH = 15;
235
+ const MAX_TOTAL_SELECTIONS = 1e3;
236
+ const MAX_ALIASES = 100;
237
+ const BODY_SIZE_LIMIT = 100 * 1024;
238
+ /**
239
+ * Read the raw express request body as a utf-8 string, enforcing the size limit.
240
+ * Mirrors express-graphql's parseBody behavior for the subset of content
241
+ * types we support (JSON and application/graphql).
242
+ */
243
+ async function readRawBody(req, limit) {
244
+ return new Promise((resolve, reject) => {
245
+ const chunks = [];
246
+ let size = 0;
247
+ req.on("data", (chunk) => {
248
+ size += chunk.length;
249
+ if (size > limit) {
250
+ const err = /* @__PURE__ */ new Error(`Request body too large (limit ${limit} bytes).`);
251
+ err.status = 413;
252
+ reject(err);
253
+ req.destroy();
254
+ return;
255
+ }
256
+ chunks.push(chunk);
257
+ });
258
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
259
+ req.on("error", reject);
260
+ });
261
+ }
262
+ const isBuffer = (v) => typeof Buffer !== "undefined" && Buffer.isBuffer(v);
263
+ /**
264
+ * Extract GraphQL params from the request. URL query string takes precedence
265
+ * over the body so that callers can override fields via `?query=...` on a
266
+ * POST. Supports four body modes (matches upstream express-graphql):
267
+ * 1. Already parsed by upstream middleware (req.body is an object)
268
+ * 2. Content-Type: application/json — JSON.parse the raw body
269
+ * 3. Content-Type: application/graphql — raw body IS the query
270
+ * 4. Content-Type: application/x-www-form-urlencoded — parse as query string
271
+ */
272
+ async function parseGraphQLParams(req) {
273
+ const urlData = new URLSearchParams((req.url || "").split("?")[1] || "");
274
+ let query = urlData.get("query");
275
+ let variablesRaw = urlData.get("variables");
276
+ let operationName = urlData.get("operationName");
277
+ const raw = urlData.get("raw") != null;
278
+ if (req.method === "POST") {
279
+ const contentType = String(req.headers["content-type"] || "").split(";")[0].trim().toLowerCase();
280
+ const preparsed = req.body;
281
+ let bodyData = {};
282
+ if (preparsed != null && typeof preparsed === "object" && !isBuffer(preparsed)) bodyData = preparsed;
283
+ else if (typeof preparsed === "string" && contentType === "application/graphql") bodyData = { query: preparsed };
284
+ else if (preparsed == null && contentType) {
285
+ const rawBody = await req.readBody(BODY_SIZE_LIMIT);
286
+ if (contentType === "application/graphql") bodyData = { query: rawBody };
287
+ else if (contentType === "application/json") try {
288
+ bodyData = JSON.parse(rawBody);
289
+ } catch {
290
+ const err = /* @__PURE__ */ new Error("POST body sent invalid JSON.");
291
+ err.status = 400;
292
+ throw err;
293
+ }
294
+ else if (contentType === "application/x-www-form-urlencoded") {
295
+ const form = new URLSearchParams(rawBody);
296
+ const parsed = {};
297
+ for (const [k, v] of form) parsed[k] = v;
298
+ bodyData = parsed;
299
+ }
300
+ }
301
+ if (query == null && typeof bodyData.query === "string") query = bodyData.query;
302
+ if (variablesRaw == null && bodyData.variables != null) variablesRaw = bodyData.variables;
303
+ if (operationName == null && typeof bodyData.operationName === "string") operationName = bodyData.operationName;
304
+ }
305
+ let variables = null;
306
+ if (typeof variablesRaw === "string") try {
307
+ variables = JSON.parse(variablesRaw);
308
+ } catch {
309
+ const err = /* @__PURE__ */ new Error("Variables are invalid JSON.");
310
+ err.status = 400;
311
+ throw err;
312
+ }
313
+ else if (variablesRaw && typeof variablesRaw === "object") variables = variablesRaw;
314
+ return {
315
+ query,
316
+ variables,
317
+ operationName,
318
+ raw
319
+ };
320
+ }
321
+ /**
322
+ * Minimal GraphiQL HTML served on GET + Accept: text/html when graphiql=true.
323
+ * Loads GraphiQL 3.x from unpkg; consumers who need offline GraphiQL should
324
+ * configure their own static route.
325
+ */
326
+ const GRAPHIQL_HTML = `<!doctype html>
327
+ <html lang="en">
328
+ <head>
329
+ <meta charset="utf-8" />
330
+ <title>GraphiQL</title>
331
+ <link href="https://unpkg.com/graphiql@3/graphiql.min.css" rel="stylesheet" />
332
+ </head>
333
+ <body style="margin:0;height:100vh">
334
+ <div id="graphiql" style="height:100%">Loading...</div>
335
+ <script src="https://unpkg.com/react@18/umd/react.production.min.js" crossorigin><\/script>
336
+ <script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js" crossorigin><\/script>
337
+ <script src="https://unpkg.com/graphiql@3/graphiql.min.js" crossorigin><\/script>
338
+ <script>
339
+ const fetcher = GraphiQL.createFetcher({ url: window.location.pathname });
340
+ const root = ReactDOM.createRoot(document.getElementById('graphiql'));
341
+ root.render(React.createElement(GraphiQL, { fetcher }));
342
+ <\/script>
343
+ </body>
344
+ </html>`;
345
+ function shouldShowGraphiQL(req, params, graphiqlEnabled) {
346
+ if (!graphiqlEnabled || params.raw) return false;
347
+ if (req.method !== "GET") return false;
348
+ return String(req.headers.accept || "").includes("text/html");
349
+ }
350
+ /**
351
+ * Count the top-level field selections across all operation definitions
352
+ * in the document, recursively expanding inline and named fragments.
353
+ */
354
+ function countTopLevelSelections(documentAST, limit = MAX_BATCH_SIZE + 1) {
355
+ const fragments = /* @__PURE__ */ new Map();
356
+ const operations = [];
357
+ for (const def of documentAST.definitions) if (def.kind === "FragmentDefinition" && def.name?.value) fragments.set(def.name.value, def.selectionSet?.selections || []);
358
+ else if (def.kind === "OperationDefinition") operations.push(def);
359
+ const fragMemo = /* @__PURE__ */ new Map();
360
+ const countSelections = (selections, visited = /* @__PURE__ */ new Set()) => {
361
+ let total = 0;
362
+ const hitCycle = false;
363
+ for (const sel of selections) {
364
+ if (total >= limit) return {
365
+ count: limit,
366
+ hitCycle
367
+ };
368
+ if (sel.kind === "Field") total += 1;
369
+ else if (sel.kind === "InlineFragment") {
370
+ const sub = countSelections(sel.selectionSet?.selections || [], visited);
371
+ if (sub.hitCycle) return {
372
+ count: limit,
373
+ hitCycle: true
374
+ };
375
+ total += sub.count;
376
+ } else if (sel.kind === "FragmentSpread" && sel.name?.value) {
377
+ const fragName = sel.name.value;
378
+ if (visited.has(fragName)) return {
379
+ count: limit,
380
+ hitCycle: true
381
+ };
382
+ const cached = fragMemo.get(fragName);
383
+ if (cached !== void 0) {
384
+ total += cached;
385
+ continue;
386
+ }
387
+ const nextVisited = new Set(visited);
388
+ nextVisited.add(fragName);
389
+ const sub = countSelections(fragments.get(fragName) || [], nextVisited);
390
+ if (sub.hitCycle) return {
391
+ count: limit,
392
+ hitCycle: true
393
+ };
394
+ fragMemo.set(fragName, Math.min(sub.count, limit));
395
+ total += sub.count;
396
+ }
397
+ }
398
+ return {
399
+ count: Math.min(total, limit),
400
+ hitCycle
401
+ };
402
+ };
403
+ let sum = 0;
404
+ for (const op of operations) {
405
+ sum += countSelections(op.selectionSet?.selections || []).count;
406
+ if (sum >= limit) return limit;
407
+ }
408
+ return sum;
409
+ }
410
+ function getMaxSelectionDepth(documentAST, limit = MAX_QUERY_DEPTH + 1) {
411
+ const fragments = /* @__PURE__ */ new Map();
412
+ const operations = [];
413
+ for (const def of documentAST.definitions) if (def.kind === "FragmentDefinition" && def.name?.value) fragments.set(def.name.value, def.selectionSet?.selections || []);
414
+ else if (def.kind === "OperationDefinition") operations.push(def);
415
+ const fragDepthMemo = /* @__PURE__ */ new Map();
416
+ const measureDepth = (selections, visited = /* @__PURE__ */ new Set()) => {
417
+ let maxDepth = 0;
418
+ const hitCycle = false;
419
+ for (const sel of selections) {
420
+ if (maxDepth >= limit) return {
421
+ depth: limit,
422
+ hitCycle
423
+ };
424
+ if (sel.kind === "Field") {
425
+ const childSelections = sel.selectionSet?.selections || [];
426
+ let childDepth = 0;
427
+ if (childSelections.length > 0) {
428
+ const sub = measureDepth(childSelections, visited);
429
+ if (sub.hitCycle) return {
430
+ depth: limit,
431
+ hitCycle: true
432
+ };
433
+ childDepth = sub.depth;
434
+ }
435
+ const depth = 1 + childDepth;
436
+ if (depth > maxDepth) maxDepth = depth;
437
+ } else if (sel.kind === "InlineFragment") {
438
+ const sub = measureDepth(sel.selectionSet?.selections || [], visited);
439
+ if (sub.hitCycle) return {
440
+ depth: limit,
441
+ hitCycle: true
442
+ };
443
+ if (sub.depth > maxDepth) maxDepth = sub.depth;
444
+ } else if (sel.kind === "FragmentSpread" && sel.name?.value) {
445
+ const fragName = sel.name.value;
446
+ if (visited.has(fragName)) return {
447
+ depth: limit,
448
+ hitCycle: true
449
+ };
450
+ const cached = fragDepthMemo.get(fragName);
451
+ if (cached !== void 0) {
452
+ if (cached > maxDepth) maxDepth = cached;
453
+ continue;
454
+ }
455
+ const nextVisited = new Set(visited);
456
+ nextVisited.add(fragName);
457
+ const sub = measureDepth(fragments.get(fragName) || [], nextVisited);
458
+ if (sub.hitCycle) return {
459
+ depth: limit,
460
+ hitCycle: true
461
+ };
462
+ fragDepthMemo.set(fragName, Math.min(sub.depth, limit));
463
+ if (sub.depth > maxDepth) maxDepth = sub.depth;
464
+ }
465
+ }
466
+ return {
467
+ depth: Math.min(maxDepth, limit),
468
+ hitCycle
469
+ };
470
+ };
471
+ let max = 0;
472
+ for (const op of operations) {
473
+ const { depth } = measureDepth(op.selectionSet?.selections || []);
474
+ if (depth > max) max = depth;
475
+ if (max >= limit) return limit;
476
+ }
477
+ return max;
478
+ }
479
+ /**
480
+ * Count total expanded field selections and field aliases across all operations
481
+ * in the document, recursively expanding inline and named fragments with memoization.
482
+ * Bounds fragment + alias width amplification (e.g. K^D nested fragment spreads) in O(|AST|) time.
483
+ */
484
+ function countTotalSelectionsAndAliases(documentAST, selectionLimit = MAX_TOTAL_SELECTIONS + 1, aliasLimit = MAX_ALIASES + 1) {
485
+ const fragments = /* @__PURE__ */ new Map();
486
+ const operations = [];
487
+ for (const def of documentAST.definitions) if (def.kind === "FragmentDefinition" && def.name?.value) fragments.set(def.name.value, def.selectionSet?.selections || []);
488
+ else if (def.kind === "OperationDefinition") operations.push(def);
489
+ const fragMemo = /* @__PURE__ */ new Map();
490
+ const measure = (selections, visited = /* @__PURE__ */ new Set()) => {
491
+ let fields = 0;
492
+ let aliases = 0;
493
+ for (const sel of selections) {
494
+ if (fields >= selectionLimit && aliases >= aliasLimit) return {
495
+ fields: selectionLimit,
496
+ aliases: aliasLimit,
497
+ hitCycle: false
498
+ };
499
+ if (sel.kind === "Field") {
500
+ fields = Math.min(selectionLimit, fields + 1);
501
+ if (sel.alias?.value) aliases = Math.min(aliasLimit, aliases + 1);
502
+ const childSelections = sel.selectionSet?.selections || [];
503
+ if (childSelections.length > 0) {
504
+ const sub = measure(childSelections, visited);
505
+ if (sub.hitCycle) return {
506
+ fields: selectionLimit,
507
+ aliases: aliasLimit,
508
+ hitCycle: true
509
+ };
510
+ fields = Math.min(selectionLimit, fields + sub.fields);
511
+ aliases = Math.min(aliasLimit, aliases + sub.aliases);
512
+ }
513
+ } else if (sel.kind === "InlineFragment") {
514
+ const sub = measure(sel.selectionSet?.selections || [], visited);
515
+ if (sub.hitCycle) return {
516
+ fields: selectionLimit,
517
+ aliases: aliasLimit,
518
+ hitCycle: true
519
+ };
520
+ fields = Math.min(selectionLimit, fields + sub.fields);
521
+ aliases = Math.min(aliasLimit, aliases + sub.aliases);
522
+ } else if (sel.kind === "FragmentSpread" && sel.name?.value) {
523
+ const fragName = sel.name.value;
524
+ if (visited.has(fragName)) return {
525
+ fields: selectionLimit,
526
+ aliases: aliasLimit,
527
+ hitCycle: true
528
+ };
529
+ const cached = fragMemo.get(fragName);
530
+ if (cached !== void 0) {
531
+ fields = Math.min(selectionLimit, fields + cached.fields);
532
+ aliases = Math.min(aliasLimit, aliases + cached.aliases);
533
+ continue;
534
+ }
535
+ const nextVisited = new Set(visited);
536
+ nextVisited.add(fragName);
537
+ const sub = measure(fragments.get(fragName) || [], nextVisited);
538
+ if (sub.hitCycle) return {
539
+ fields: selectionLimit,
540
+ aliases: aliasLimit,
541
+ hitCycle: true
542
+ };
543
+ const clamped = {
544
+ fields: Math.min(selectionLimit, sub.fields),
545
+ aliases: Math.min(aliasLimit, sub.aliases)
546
+ };
547
+ fragMemo.set(fragName, clamped);
548
+ fields = Math.min(selectionLimit, fields + clamped.fields);
549
+ aliases = Math.min(aliasLimit, aliases + clamped.aliases);
550
+ }
551
+ }
552
+ return {
553
+ fields,
554
+ aliases,
555
+ hitCycle: false
556
+ };
557
+ };
558
+ let totalFields = 0;
559
+ let totalAliases = 0;
560
+ for (const op of operations) {
561
+ const sub = measure(op.selectionSet?.selections || []);
562
+ totalFields = Math.min(selectionLimit, totalFields + sub.fields);
563
+ totalAliases = Math.min(aliasLimit, totalAliases + sub.aliases);
564
+ if (totalFields >= selectionLimit && totalAliases >= aliasLimit) break;
565
+ }
566
+ return {
567
+ fields: totalFields,
568
+ aliases: totalAliases
569
+ };
570
+ }
571
+ const parseEnvPositiveInt = (raw) => {
572
+ if (raw === void 0 || raw.trim() === "") return void 0;
573
+ const parsed = Number.parseInt(raw.trim(), 10);
574
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
575
+ };
576
+ const parseEnvBoolean = (raw) => {
577
+ if (raw === void 0 || raw.trim() === "") return void 0;
578
+ const normalized = raw.trim().toLowerCase();
579
+ if (normalized === "1" || normalized === "true") return true;
580
+ if (normalized === "0" || normalized === "false") return false;
581
+ };
582
+ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, graphiql = parseEnvBoolean(process.env.GQL_GRAPHIQL ?? process.env.GRAPHQL_GRAPHIQL) ?? process.env.NODE_ENV !== "production", introspection = parseEnvBoolean(process.env.GQL_INTROSPECTION ?? process.env.GRAPHQL_INTROSPECTION) ?? process.env.NODE_ENV !== "production", showStack = process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test", maxQueryDepth = MAX_QUERY_DEPTH, maxTotalSelections = parseEnvPositiveInt(process.env.GQL_MAX_TOTAL_SELECTIONS) ?? MAX_TOTAL_SELECTIONS, maxAliases = parseEnvPositiveInt(process.env.GQL_MAX_ALIASES) ?? MAX_ALIASES }) => {
583
+ const schema = (0, graphql.buildSchema)(_ocap_schema.default);
584
+ const rootValue = createResolvers(resolver);
585
+ const formatGraphQLError = (err) => {
586
+ onError(err);
587
+ const includeStack = showStack && process.env.NODE_ENV !== "production";
588
+ return {
589
+ code: (0, lodash_get.default)(err, "originalError.code", "INTERNAL"),
590
+ message: err.message,
591
+ locations: err.locations || [],
592
+ stack: includeStack ? (0, lodash_get.default)(err, "originalError.stack", "").split("\n") : [],
593
+ path: err.path
594
+ };
595
+ };
596
+ const formatAnyError = (input) => {
597
+ const message = typeof input === "string" ? input : input.message;
598
+ return formatGraphQLError(new graphql.GraphQLError(message, { originalError: typeof input === "string" ? new Error(message) : input }));
599
+ };
600
+ const sendJSON = (status, body, extra = {}) => ({
601
+ status,
602
+ headers: {
603
+ "content-type": "application/json; charset=utf-8",
604
+ ...extra
605
+ },
606
+ body: JSON.stringify(body)
607
+ });
608
+ const sendHTML = (html) => ({
609
+ status: 200,
610
+ headers: { "content-type": "text/html; charset=utf-8" },
611
+ body: html
612
+ });
613
+ return async (req, contextValue) => {
614
+ if (req.method !== "GET" && req.method !== "POST") return sendJSON(405, { errors: [formatAnyError("GraphQL only supports GET and POST requests.")] }, { Allow: "GET, POST" });
615
+ let params;
616
+ try {
617
+ params = await parseGraphQLParams(req);
618
+ } catch (err) {
619
+ return sendJSON(err.status ?? 500, { errors: [formatAnyError(err)] });
620
+ }
621
+ const showGraphiQL = shouldShowGraphiQL(req, params, graphiql);
622
+ if (params.query == null) {
623
+ if (showGraphiQL) return sendHTML(GRAPHIQL_HTML);
624
+ return sendJSON(400, { errors: [formatAnyError("Must provide query string.")] });
625
+ }
626
+ let documentAST;
627
+ try {
628
+ documentAST = (0, graphql.parse)(params.query);
629
+ } catch (syntaxError) {
630
+ return sendJSON(400, { errors: [formatGraphQLError(syntaxError)] });
631
+ }
632
+ if (!introspection) {
633
+ const validationErrors = (0, graphql.validate)(schema, documentAST, [graphql.NoSchemaIntrospectionCustomRule]);
634
+ if (validationErrors.length > 0) return sendJSON(400, { errors: validationErrors.map(formatGraphQLError) });
635
+ }
636
+ try {
637
+ if (countTopLevelSelections(documentAST) > MAX_BATCH_SIZE) throw new Error(`Batch query size exceeded allowed maximum batch size of ${MAX_BATCH_SIZE}`);
638
+ if (maxQueryDepth > 0) {
639
+ if (getMaxSelectionDepth(documentAST, maxQueryDepth + 1) > maxQueryDepth) throw new Error(`Query depth exceeded allowed maximum depth of ${maxQueryDepth}`);
640
+ }
641
+ if (maxTotalSelections > 0 || maxAliases > 0) {
642
+ const selLimit = maxTotalSelections > 0 ? maxTotalSelections + 1 : Number.MAX_SAFE_INTEGER;
643
+ const aliasLimit = maxAliases > 0 ? maxAliases + 1 : Number.MAX_SAFE_INTEGER;
644
+ const { fields, aliases } = countTotalSelectionsAndAliases(documentAST, selLimit, aliasLimit);
645
+ if (maxTotalSelections > 0 && fields > maxTotalSelections) throw new Error(`Query complexity exceeded allowed maximum of ${maxTotalSelections} total field selections`);
646
+ if (maxAliases > 0 && aliases > maxAliases) throw new Error(`Query aliases exceeded allowed maximum of ${maxAliases} aliases`);
647
+ }
648
+ } catch (batchError) {
649
+ return sendJSON(500, { errors: [formatAnyError(batchError)] });
650
+ }
651
+ if (req.method === "GET") {
652
+ const operationAST = (0, graphql.getOperationAST)(documentAST, params.operationName || void 0);
653
+ if (operationAST && operationAST.operation !== "query") return sendJSON(405, { errors: [formatAnyError(`Can only perform a ${operationAST.operation} operation from a POST request.`)] }, { Allow: "POST" });
654
+ }
655
+ let result;
656
+ try {
657
+ result = await (0, graphql.execute)({
658
+ schema,
659
+ document: documentAST,
660
+ rootValue,
661
+ contextValue,
662
+ variableValues: params.variables,
663
+ operationName: params.operationName
664
+ });
665
+ } catch (contextError) {
666
+ return sendJSON(400, { errors: [formatAnyError(contextError)] });
667
+ }
668
+ const formattedResult = { data: result.data };
669
+ if (result.errors && result.errors.length > 0) formattedResult.errors = result.errors.map(formatGraphQLError);
670
+ return sendJSON(result.data == null ? 500 : 200, formattedResult);
671
+ };
672
+ };
673
+ /** Express / connect adapter. Behavior is unchanged from the pre-split `createHttpHandler`. */
674
+ const createHttpHandler = (options) => {
675
+ const engine = createGraphQLEngine(options);
676
+ return async (req, res) => {
677
+ const result = await engine({
678
+ method: req.method,
679
+ url: req.url,
680
+ headers: req.headers,
681
+ body: req.body,
682
+ readBody: (limit) => readRawBody(req, limit)
683
+ }, req);
684
+ res.statusCode = result.status;
685
+ for (const [name, value] of Object.entries(result.headers)) res.setHeader(name, value);
686
+ res.end(result.body);
687
+ };
688
+ };
689
+ const readFetchBody = async (request, limit) => {
690
+ const tooLarge = () => {
691
+ const err = /* @__PURE__ */ new Error(`Request body too large (limit ${limit} bytes).`);
692
+ err.status = 413;
693
+ return err;
694
+ };
695
+ const declared = Number(request.headers.get("content-length"));
696
+ if (Number.isFinite(declared) && declared > limit) throw tooLarge();
697
+ if (!request.body) return "";
698
+ const reader = request.body.getReader();
699
+ const decoder = new TextDecoder();
700
+ let size = 0;
701
+ let text = "";
702
+ for (;;) {
703
+ const { done, value } = await reader.read();
704
+ if (done) break;
705
+ size += value.byteLength;
706
+ if (size > limit) {
707
+ await reader.cancel().catch(() => {});
708
+ throw tooLarge();
709
+ }
710
+ text += decoder.decode(value, { stream: true });
711
+ }
712
+ return text + decoder.decode();
713
+ };
714
+ /**
715
+ * Fetch-native adapter (Cloudflare Workers / Durable Objects, Deno, Bun): `(Request) => Promise<Response>`.
716
+ * Same engine, same guards (depth limit, batch guard, introspection off in production, 100kb body cap) as
717
+ * `createHttpHandler`; no `node:http`, no express and no WebSocket server are imported.
718
+ */
719
+ const createFetchHandler = (options) => {
720
+ const engine = createGraphQLEngine(options);
721
+ return async (request) => {
722
+ const headers = {};
723
+ request.headers.forEach((value, key) => {
724
+ headers[key.toLowerCase()] = value;
725
+ });
726
+ const url = new URL(request.url);
727
+ const result = await engine({
728
+ method: request.method,
729
+ url: `${url.pathname}${url.search}`,
730
+ headers,
731
+ readBody: (limit) => readFetchBody(request, limit)
732
+ }, {
733
+ headers,
734
+ ip: headers["cf-connecting-ip"] || headers["x-real-ip"]
735
+ });
736
+ return new Response(result.body, {
737
+ status: result.status,
738
+ headers: result.headers
739
+ });
740
+ };
741
+ };
742
+
743
+ //#endregion
744
+ exports.createFetchHandler = createFetchHandler;
745
+ exports.createHttpHandler = createHttpHandler;
746
+ exports.createResolvers = createResolvers;
747
+ exports.formatContext = formatContext;
748
+ exports.wrapResolver = wrapResolver;