@ocap/gql 1.30.23 → 1.30.25

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,642 @@
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 BODY_SIZE_LIMIT = 100 * 1024;
236
+ /**
237
+ * Read the raw express request body as a utf-8 string, enforcing the size limit.
238
+ * Mirrors express-graphql's parseBody behavior for the subset of content
239
+ * types we support (JSON and application/graphql).
240
+ */
241
+ async function readRawBody(req, limit) {
242
+ return new Promise((resolve, reject) => {
243
+ const chunks = [];
244
+ let size = 0;
245
+ req.on("data", (chunk) => {
246
+ size += chunk.length;
247
+ if (size > limit) {
248
+ const err = /* @__PURE__ */ new Error(`Request body too large (limit ${limit} bytes).`);
249
+ err.status = 413;
250
+ reject(err);
251
+ req.destroy();
252
+ return;
253
+ }
254
+ chunks.push(chunk);
255
+ });
256
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
257
+ req.on("error", reject);
258
+ });
259
+ }
260
+ const isBuffer = (v) => typeof Buffer !== "undefined" && Buffer.isBuffer(v);
261
+ /**
262
+ * Extract GraphQL params from the request. URL query string takes precedence
263
+ * over the body so that callers can override fields via `?query=...` on a
264
+ * POST. Supports four body modes (matches upstream express-graphql):
265
+ * 1. Already parsed by upstream middleware (req.body is an object)
266
+ * 2. Content-Type: application/json — JSON.parse the raw body
267
+ * 3. Content-Type: application/graphql — raw body IS the query
268
+ * 4. Content-Type: application/x-www-form-urlencoded — parse as query string
269
+ */
270
+ async function parseGraphQLParams(req) {
271
+ const urlData = new URLSearchParams((req.url || "").split("?")[1] || "");
272
+ let query = urlData.get("query");
273
+ let variablesRaw = urlData.get("variables");
274
+ let operationName = urlData.get("operationName");
275
+ const raw = urlData.get("raw") != null;
276
+ if (req.method === "POST") {
277
+ const contentType = String(req.headers["content-type"] || "").split(";")[0].trim().toLowerCase();
278
+ const preparsed = req.body;
279
+ let bodyData = {};
280
+ if (preparsed != null && typeof preparsed === "object" && !isBuffer(preparsed)) bodyData = preparsed;
281
+ else if (typeof preparsed === "string" && contentType === "application/graphql") bodyData = { query: preparsed };
282
+ else if (preparsed == null && contentType) {
283
+ const rawBody = await req.readBody(BODY_SIZE_LIMIT);
284
+ if (contentType === "application/graphql") bodyData = { query: rawBody };
285
+ else if (contentType === "application/json") try {
286
+ bodyData = JSON.parse(rawBody);
287
+ } catch {
288
+ const err = /* @__PURE__ */ new Error("POST body sent invalid JSON.");
289
+ err.status = 400;
290
+ throw err;
291
+ }
292
+ else if (contentType === "application/x-www-form-urlencoded") {
293
+ const form = new URLSearchParams(rawBody);
294
+ const parsed = {};
295
+ for (const [k, v] of form) parsed[k] = v;
296
+ bodyData = parsed;
297
+ }
298
+ }
299
+ if (query == null && typeof bodyData.query === "string") query = bodyData.query;
300
+ if (variablesRaw == null && bodyData.variables != null) variablesRaw = bodyData.variables;
301
+ if (operationName == null && typeof bodyData.operationName === "string") operationName = bodyData.operationName;
302
+ }
303
+ let variables = null;
304
+ if (typeof variablesRaw === "string") try {
305
+ variables = JSON.parse(variablesRaw);
306
+ } catch {
307
+ const err = /* @__PURE__ */ new Error("Variables are invalid JSON.");
308
+ err.status = 400;
309
+ throw err;
310
+ }
311
+ else if (variablesRaw && typeof variablesRaw === "object") variables = variablesRaw;
312
+ return {
313
+ query,
314
+ variables,
315
+ operationName,
316
+ raw
317
+ };
318
+ }
319
+ /**
320
+ * Minimal GraphiQL HTML served on GET + Accept: text/html when graphiql=true.
321
+ * Loads GraphiQL 3.x from unpkg; consumers who need offline GraphiQL should
322
+ * configure their own static route.
323
+ */
324
+ const GRAPHIQL_HTML = `<!doctype html>
325
+ <html lang="en">
326
+ <head>
327
+ <meta charset="utf-8" />
328
+ <title>GraphiQL</title>
329
+ <link href="https://unpkg.com/graphiql@3/graphiql.min.css" rel="stylesheet" />
330
+ </head>
331
+ <body style="margin:0;height:100vh">
332
+ <div id="graphiql" style="height:100%">Loading...</div>
333
+ <script src="https://unpkg.com/react@18/umd/react.production.min.js" crossorigin><\/script>
334
+ <script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js" crossorigin><\/script>
335
+ <script src="https://unpkg.com/graphiql@3/graphiql.min.js" crossorigin><\/script>
336
+ <script>
337
+ const fetcher = GraphiQL.createFetcher({ url: window.location.pathname });
338
+ const root = ReactDOM.createRoot(document.getElementById('graphiql'));
339
+ root.render(React.createElement(GraphiQL, { fetcher }));
340
+ <\/script>
341
+ </body>
342
+ </html>`;
343
+ function shouldShowGraphiQL(req, params, graphiqlEnabled) {
344
+ if (!graphiqlEnabled || params.raw) return false;
345
+ if (req.method !== "GET") return false;
346
+ return String(req.headers.accept || "").includes("text/html");
347
+ }
348
+ /**
349
+ * Count the top-level field selections across all operation definitions
350
+ * in the document, recursively expanding inline and named fragments.
351
+ */
352
+ function countTopLevelSelections(documentAST, limit = MAX_BATCH_SIZE + 1) {
353
+ const fragments = /* @__PURE__ */ new Map();
354
+ const operations = [];
355
+ for (const def of documentAST.definitions) if (def.kind === "FragmentDefinition" && def.name?.value) fragments.set(def.name.value, def.selectionSet?.selections || []);
356
+ else if (def.kind === "OperationDefinition") operations.push(def);
357
+ const fragMemo = /* @__PURE__ */ new Map();
358
+ const countSelections = (selections, visited = /* @__PURE__ */ new Set()) => {
359
+ let total = 0;
360
+ const hitCycle = false;
361
+ for (const sel of selections) {
362
+ if (total >= limit) return {
363
+ count: limit,
364
+ hitCycle
365
+ };
366
+ if (sel.kind === "Field") total += 1;
367
+ else if (sel.kind === "InlineFragment") {
368
+ const sub = countSelections(sel.selectionSet?.selections || [], visited);
369
+ if (sub.hitCycle) return {
370
+ count: limit,
371
+ hitCycle: true
372
+ };
373
+ total += sub.count;
374
+ } else if (sel.kind === "FragmentSpread" && sel.name?.value) {
375
+ const fragName = sel.name.value;
376
+ if (visited.has(fragName)) return {
377
+ count: limit,
378
+ hitCycle: true
379
+ };
380
+ const cached = fragMemo.get(fragName);
381
+ if (cached !== void 0) {
382
+ total += cached;
383
+ continue;
384
+ }
385
+ const nextVisited = new Set(visited);
386
+ nextVisited.add(fragName);
387
+ const sub = countSelections(fragments.get(fragName) || [], nextVisited);
388
+ if (sub.hitCycle) return {
389
+ count: limit,
390
+ hitCycle: true
391
+ };
392
+ fragMemo.set(fragName, Math.min(sub.count, limit));
393
+ total += sub.count;
394
+ }
395
+ }
396
+ return {
397
+ count: Math.min(total, limit),
398
+ hitCycle
399
+ };
400
+ };
401
+ let sum = 0;
402
+ for (const op of operations) {
403
+ sum += countSelections(op.selectionSet?.selections || []).count;
404
+ if (sum >= limit) return limit;
405
+ }
406
+ return sum;
407
+ }
408
+ function getMaxSelectionDepth(documentAST, limit = MAX_QUERY_DEPTH + 1) {
409
+ const fragments = /* @__PURE__ */ new Map();
410
+ const operations = [];
411
+ for (const def of documentAST.definitions) if (def.kind === "FragmentDefinition" && def.name?.value) fragments.set(def.name.value, def.selectionSet?.selections || []);
412
+ else if (def.kind === "OperationDefinition") operations.push(def);
413
+ const fragDepthMemo = /* @__PURE__ */ new Map();
414
+ const measureDepth = (selections, visited = /* @__PURE__ */ new Set()) => {
415
+ let maxDepth = 0;
416
+ const hitCycle = false;
417
+ for (const sel of selections) {
418
+ if (maxDepth >= limit) return {
419
+ depth: limit,
420
+ hitCycle
421
+ };
422
+ if (sel.kind === "Field") {
423
+ const childSelections = sel.selectionSet?.selections || [];
424
+ let childDepth = 0;
425
+ if (childSelections.length > 0) {
426
+ const sub = measureDepth(childSelections, visited);
427
+ if (sub.hitCycle) return {
428
+ depth: limit,
429
+ hitCycle: true
430
+ };
431
+ childDepth = sub.depth;
432
+ }
433
+ const depth = 1 + childDepth;
434
+ if (depth > maxDepth) maxDepth = depth;
435
+ } else if (sel.kind === "InlineFragment") {
436
+ const sub = measureDepth(sel.selectionSet?.selections || [], visited);
437
+ if (sub.hitCycle) return {
438
+ depth: limit,
439
+ hitCycle: true
440
+ };
441
+ if (sub.depth > maxDepth) maxDepth = sub.depth;
442
+ } else if (sel.kind === "FragmentSpread" && sel.name?.value) {
443
+ const fragName = sel.name.value;
444
+ if (visited.has(fragName)) return {
445
+ depth: limit,
446
+ hitCycle: true
447
+ };
448
+ const cached = fragDepthMemo.get(fragName);
449
+ if (cached !== void 0) {
450
+ if (cached > maxDepth) maxDepth = cached;
451
+ continue;
452
+ }
453
+ const nextVisited = new Set(visited);
454
+ nextVisited.add(fragName);
455
+ const sub = measureDepth(fragments.get(fragName) || [], nextVisited);
456
+ if (sub.hitCycle) return {
457
+ depth: limit,
458
+ hitCycle: true
459
+ };
460
+ fragDepthMemo.set(fragName, Math.min(sub.depth, limit));
461
+ if (sub.depth > maxDepth) maxDepth = sub.depth;
462
+ }
463
+ }
464
+ return {
465
+ depth: Math.min(maxDepth, limit),
466
+ hitCycle
467
+ };
468
+ };
469
+ let max = 0;
470
+ for (const op of operations) {
471
+ const { depth } = measureDepth(op.selectionSet?.selections || []);
472
+ if (depth > max) max = depth;
473
+ if (max >= limit) return limit;
474
+ }
475
+ return max;
476
+ }
477
+ const parseEnvBoolean = (raw) => {
478
+ if (raw === void 0 || raw.trim() === "") return void 0;
479
+ const normalized = raw.trim().toLowerCase();
480
+ if (normalized === "1" || normalized === "true") return true;
481
+ if (normalized === "0" || normalized === "false") return false;
482
+ };
483
+ 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 }) => {
484
+ const schema = (0, graphql.buildSchema)(_ocap_schema.default);
485
+ const rootValue = createResolvers(resolver);
486
+ const formatGraphQLError = (err) => {
487
+ onError(err);
488
+ const includeStack = showStack && process.env.NODE_ENV !== "production";
489
+ return {
490
+ code: (0, lodash_get.default)(err, "originalError.code", "INTERNAL"),
491
+ message: err.message,
492
+ locations: err.locations || [],
493
+ stack: includeStack ? (0, lodash_get.default)(err, "originalError.stack", "").split("\n") : [],
494
+ path: err.path
495
+ };
496
+ };
497
+ const formatAnyError = (input) => {
498
+ const message = typeof input === "string" ? input : input.message;
499
+ return formatGraphQLError(new graphql.GraphQLError(message, { originalError: typeof input === "string" ? new Error(message) : input }));
500
+ };
501
+ const sendJSON = (status, body, extra = {}) => ({
502
+ status,
503
+ headers: {
504
+ "content-type": "application/json; charset=utf-8",
505
+ ...extra
506
+ },
507
+ body: JSON.stringify(body)
508
+ });
509
+ const sendHTML = (html) => ({
510
+ status: 200,
511
+ headers: { "content-type": "text/html; charset=utf-8" },
512
+ body: html
513
+ });
514
+ return async (req, contextValue) => {
515
+ if (req.method !== "GET" && req.method !== "POST") return sendJSON(405, { errors: [formatAnyError("GraphQL only supports GET and POST requests.")] }, { Allow: "GET, POST" });
516
+ let params;
517
+ try {
518
+ params = await parseGraphQLParams(req);
519
+ } catch (err) {
520
+ return sendJSON(err.status ?? 500, { errors: [formatAnyError(err)] });
521
+ }
522
+ const showGraphiQL = shouldShowGraphiQL(req, params, graphiql);
523
+ if (params.query == null) {
524
+ if (showGraphiQL) return sendHTML(GRAPHIQL_HTML);
525
+ return sendJSON(400, { errors: [formatAnyError("Must provide query string.")] });
526
+ }
527
+ let documentAST;
528
+ try {
529
+ documentAST = (0, graphql.parse)(params.query);
530
+ } catch (syntaxError) {
531
+ return sendJSON(400, { errors: [formatGraphQLError(syntaxError)] });
532
+ }
533
+ if (!introspection) {
534
+ const validationErrors = (0, graphql.validate)(schema, documentAST, [graphql.NoSchemaIntrospectionCustomRule]);
535
+ if (validationErrors.length > 0) return sendJSON(400, { errors: validationErrors.map(formatGraphQLError) });
536
+ }
537
+ try {
538
+ if (countTopLevelSelections(documentAST) > MAX_BATCH_SIZE) throw new Error(`Batch query size exceeded allowed maximum batch size of ${MAX_BATCH_SIZE}`);
539
+ if (maxQueryDepth > 0) {
540
+ if (getMaxSelectionDepth(documentAST, maxQueryDepth + 1) > maxQueryDepth) throw new Error(`Query depth exceeded allowed maximum depth of ${maxQueryDepth}`);
541
+ }
542
+ } catch (batchError) {
543
+ return sendJSON(500, { errors: [formatAnyError(batchError)] });
544
+ }
545
+ if (req.method === "GET") {
546
+ const operationAST = (0, graphql.getOperationAST)(documentAST, params.operationName || void 0);
547
+ if (operationAST && operationAST.operation !== "query") return sendJSON(405, { errors: [formatAnyError(`Can only perform a ${operationAST.operation} operation from a POST request.`)] }, { Allow: "POST" });
548
+ }
549
+ let result;
550
+ try {
551
+ result = await (0, graphql.execute)({
552
+ schema,
553
+ document: documentAST,
554
+ rootValue,
555
+ contextValue,
556
+ variableValues: params.variables,
557
+ operationName: params.operationName
558
+ });
559
+ } catch (contextError) {
560
+ return sendJSON(400, { errors: [formatAnyError(contextError)] });
561
+ }
562
+ const formattedResult = { data: result.data };
563
+ if (result.errors && result.errors.length > 0) formattedResult.errors = result.errors.map(formatGraphQLError);
564
+ return sendJSON(result.data == null ? 500 : 200, formattedResult);
565
+ };
566
+ };
567
+ /** Express / connect adapter. Behavior is unchanged from the pre-split `createHttpHandler`. */
568
+ const createHttpHandler = (options) => {
569
+ const engine = createGraphQLEngine(options);
570
+ return async (req, res) => {
571
+ const result = await engine({
572
+ method: req.method,
573
+ url: req.url,
574
+ headers: req.headers,
575
+ body: req.body,
576
+ readBody: (limit) => readRawBody(req, limit)
577
+ }, req);
578
+ res.statusCode = result.status;
579
+ for (const [name, value] of Object.entries(result.headers)) res.setHeader(name, value);
580
+ res.end(result.body);
581
+ };
582
+ };
583
+ const readFetchBody = async (request, limit) => {
584
+ const tooLarge = () => {
585
+ const err = /* @__PURE__ */ new Error(`Request body too large (limit ${limit} bytes).`);
586
+ err.status = 413;
587
+ return err;
588
+ };
589
+ const declared = Number(request.headers.get("content-length"));
590
+ if (Number.isFinite(declared) && declared > limit) throw tooLarge();
591
+ if (!request.body) return "";
592
+ const reader = request.body.getReader();
593
+ const decoder = new TextDecoder();
594
+ let size = 0;
595
+ let text = "";
596
+ for (;;) {
597
+ const { done, value } = await reader.read();
598
+ if (done) break;
599
+ size += value.byteLength;
600
+ if (size > limit) {
601
+ await reader.cancel().catch(() => {});
602
+ throw tooLarge();
603
+ }
604
+ text += decoder.decode(value, { stream: true });
605
+ }
606
+ return text + decoder.decode();
607
+ };
608
+ /**
609
+ * Fetch-native adapter (Cloudflare Workers / Durable Objects, Deno, Bun): `(Request) => Promise<Response>`.
610
+ * Same engine, same guards (depth limit, batch guard, introspection off in production, 100kb body cap) as
611
+ * `createHttpHandler`; no `node:http`, no express and no WebSocket server are imported.
612
+ */
613
+ const createFetchHandler = (options) => {
614
+ const engine = createGraphQLEngine(options);
615
+ return async (request) => {
616
+ const headers = {};
617
+ request.headers.forEach((value, key) => {
618
+ headers[key.toLowerCase()] = value;
619
+ });
620
+ const url = new URL(request.url);
621
+ const result = await engine({
622
+ method: request.method,
623
+ url: `${url.pathname}${url.search}`,
624
+ headers,
625
+ readBody: (limit) => readFetchBody(request, limit)
626
+ }, {
627
+ headers,
628
+ ip: headers["cf-connecting-ip"] || headers["x-real-ip"]
629
+ });
630
+ return new Response(result.body, {
631
+ status: result.status,
632
+ headers: result.headers
633
+ });
634
+ };
635
+ };
636
+
637
+ //#endregion
638
+ exports.createFetchHandler = createFetchHandler;
639
+ exports.createHttpHandler = createHttpHandler;
640
+ exports.createResolvers = createResolvers;
641
+ exports.formatContext = formatContext;
642
+ exports.wrapResolver = wrapResolver;
package/lib/http.d.cts ADDED
@@ -0,0 +1,66 @@
1
+ import { IResolver, IResolverContext, TPageInfo } from "@ocap/types";
2
+ import { RequestHandler } from "express";
3
+ import { GraphQLError } from "graphql";
4
+
5
+ //#region src/http.d.ts
6
+ interface ResolverResult {
7
+ paging?: TPageInfo;
8
+ [key: string]: any;
9
+ }
10
+ interface WrapResolverResult {
11
+ code: string;
12
+ page: TPageInfo | Record<string, never> | null;
13
+ [key: string]: any;
14
+ }
15
+ declare const wrapResolver: (_name: string, keys: string | string[], callback: () => Promise<ResolverResult | null> | ResolverResult | null | string) => Promise<WrapResolverResult>;
16
+ interface RequestContext {
17
+ headers?: Record<string, string>;
18
+ ip?: string;
19
+ _remoteAddress?: string;
20
+ connection?: {
21
+ remoteAddress?: string;
22
+ };
23
+ }
24
+ declare const formatContext: (ctx?: RequestContext) => IResolverContext;
25
+ type Resolver = IResolver;
26
+ type ResolverFn = (args: unknown, ctx: unknown) => Promise<WrapResolverResult>;
27
+ declare const createResolvers: (resolver: Resolver) => Record<string, ResolverFn>;
28
+ interface HttpHandlerOptions {
29
+ resolver?: IResolver;
30
+ onError?: (err: GraphQLError) => void;
31
+ graphiql?: boolean;
32
+ introspection?: boolean;
33
+ showStack?: boolean;
34
+ maxQueryDepth?: number;
35
+ }
36
+ /**
37
+ * Transport-agnostic view of an incoming GraphQL request, so the same engine serves express (`createHttpHandler`)
38
+ * and fetch-native runtimes such as Cloudflare Workers (`createFetchHandler`).
39
+ */
40
+ interface GqlRequestLike {
41
+ method: string;
42
+ /** Request target, path plus optional `?query` string. */
43
+ url: string;
44
+ /** Lower-cased header names. */
45
+ headers: Record<string, string | string[] | undefined>;
46
+ /** Body already parsed by upstream middleware (express.json()), if any. */
47
+ body?: unknown;
48
+ /** Read the raw body as utf-8, rejecting with `status: 413` above `limit` bytes. */
49
+ readBody: (limit: number) => Promise<string>;
50
+ }
51
+ /** Transport-agnostic response produced by the engine. */
52
+ interface GqlResponseLike {
53
+ status: number;
54
+ headers: Record<string, string>;
55
+ body: string;
56
+ }
57
+ /** Express / connect adapter. Behavior is unchanged from the pre-split `createHttpHandler`. */
58
+ declare const createHttpHandler: (options: HttpHandlerOptions) => RequestHandler;
59
+ /**
60
+ * Fetch-native adapter (Cloudflare Workers / Durable Objects, Deno, Bun): `(Request) => Promise<Response>`.
61
+ * Same engine, same guards (depth limit, batch guard, introspection off in production, 100kb body cap) as
62
+ * `createHttpHandler`; no `node:http`, no express and no WebSocket server are imported.
63
+ */
64
+ declare const createFetchHandler: (options: HttpHandlerOptions) => (request: globalThis.Request) => Promise<globalThis.Response>;
65
+ //#endregion
66
+ export { GqlRequestLike, GqlResponseLike, HttpHandlerOptions, type Resolver, createFetchHandler, createHttpHandler, createResolvers, formatContext, wrapResolver };