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