@alxia/graphql 0.16.5 → 0.18.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 (74) hide show
  1. package/README.md +60 -62
  2. package/dist/endpoint.d.ts +14 -2
  3. package/dist/endpoint.d.ts.map +1 -1
  4. package/dist/executor.d.ts +20 -37
  5. package/dist/executor.d.ts.map +1 -1
  6. package/dist/explorer.d.ts +24 -0
  7. package/dist/explorer.d.ts.map +1 -0
  8. package/dist/graphql.d.ts +32 -95
  9. package/dist/graphql.d.ts.map +1 -1
  10. package/dist/handler.d.ts +7 -34
  11. package/dist/handler.d.ts.map +1 -1
  12. package/dist/index.d.ts +3 -4
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +301 -1011
  15. package/dist/index.js.map +14 -23
  16. package/dist/once-per-request.d.ts +5 -0
  17. package/dist/once-per-request.d.ts.map +1 -1
  18. package/dist/operation.d.ts +2 -7
  19. package/dist/operation.d.ts.map +1 -1
  20. package/dist/options.d.ts +38 -0
  21. package/dist/options.d.ts.map +1 -0
  22. package/dist/removed.d.ts +14 -0
  23. package/dist/removed.d.ts.map +1 -0
  24. package/dist/sandbox.d.ts +3 -17
  25. package/dist/sandbox.d.ts.map +1 -1
  26. package/dist/testing/client.d.ts +9 -7
  27. package/dist/testing/client.d.ts.map +1 -1
  28. package/dist/testing/index.js +5 -1
  29. package/dist/testing/index.js.map +3 -3
  30. package/dist/ws.d.ts +18 -30
  31. package/dist/ws.d.ts.map +1 -1
  32. package/docs/README.md +3 -2
  33. package/docs/guide/context.md +40 -32
  34. package/docs/guide/endpoint.md +42 -27
  35. package/docs/guide/executor.md +23 -8
  36. package/docs/guide/ide.md +27 -64
  37. package/docs/guide/{yoga.md → plugins.md} +87 -72
  38. package/docs/guide/production.md +115 -196
  39. package/docs/guide/testing.md +24 -24
  40. package/docs/guide/websockets.md +21 -14
  41. package/docs/migrating-to-graxia.md +283 -0
  42. package/docs/roadmap.md +7 -11
  43. package/docs/troubleshooting.md +231 -248
  44. package/package.json +15 -22
  45. package/dist/body-refusal.d.ts +0 -25
  46. package/dist/body-refusal.d.ts.map +0 -1
  47. package/dist/document-cache.d.ts +0 -39
  48. package/dist/document-cache.d.ts.map +0 -1
  49. package/dist/field-rate-limit/count.d.ts +0 -28
  50. package/dist/field-rate-limit/count.d.ts.map +0 -1
  51. package/dist/field-rate-limit/from-store.d.ts +0 -21
  52. package/dist/field-rate-limit/from-store.d.ts.map +0 -1
  53. package/dist/field-rate-limit/index.d.ts +0 -5
  54. package/dist/field-rate-limit/index.d.ts.map +0 -1
  55. package/dist/field-rate-limit/ipv6-network.d.ts +0 -8
  56. package/dist/field-rate-limit/ipv6-network.d.ts.map +0 -1
  57. package/dist/field-rate-limit/plugin.d.ts +0 -28
  58. package/dist/field-rate-limit/plugin.d.ts.map +0 -1
  59. package/dist/field-rate-limit/types.d.ts +0 -60
  60. package/dist/field-rate-limit/types.d.ts.map +0 -1
  61. package/dist/nesting.d.ts +0 -18
  62. package/dist/nesting.d.ts.map +0 -1
  63. package/dist/parse-limits.d.ts +0 -50
  64. package/dist/parse-limits.d.ts.map +0 -1
  65. package/dist/same-origin/index.d.ts +0 -2
  66. package/dist/same-origin/index.d.ts.map +0 -1
  67. package/dist/same-origin/same-origin.d.ts +0 -30
  68. package/dist/same-origin/same-origin.d.ts.map +0 -1
  69. package/dist/ws-operations.d.ts +0 -31
  70. package/dist/ws-operations.d.ts.map +0 -1
  71. package/dist/ws-server.d.ts +0 -32
  72. package/dist/ws-server.d.ts.map +0 -1
  73. package/dist/yoga.d.ts +0 -12
  74. package/dist/yoga.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,3 +1,9 @@
1
+ // src/index.ts
2
+ import {
3
+ fieldRateLimit,
4
+ limitFromStore
5
+ } from "@graxia/core";
6
+
1
7
  // src/bounded-stream.ts
2
8
  var DONE = { done: true, value: undefined };
3
9
  function boundedStream(source, options) {
@@ -105,160 +111,262 @@ function boundedStream(source, options) {
105
111
  };
106
112
  return stream;
107
113
  }
108
- // src/yoga.ts
109
- import { isDev } from "@alxia/core";
114
+ // src/executor.ts
115
+ import { createGraxia } from "@graxia/core";
110
116
 
111
- // src/handler.ts
117
+ // src/explorer.ts
112
118
  import {
113
- shutdownSignal,
114
- vary
115
- } from "@alxia/core";
116
- import {
117
- createYoga
118
- } from "graphql-yoga";
119
+ apolloSandbox,
120
+ graphiql
121
+ } from "@graxia/graphiql";
122
+ function defined(values) {
123
+ return Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined));
124
+ }
125
+ function sandboxPlugin(sandbox) {
126
+ const options = {
127
+ enabled: true,
128
+ ...defined({ title: sandbox?.title }),
129
+ initialState: defined({
130
+ document: sandbox?.initialDocument,
131
+ headers: sandbox?.initialHeaders,
132
+ includeCookies: sandbox?.includeCookies
133
+ })
134
+ };
135
+ return apolloSandbox(options);
136
+ }
137
+ function explorerPlugins(options, devs) {
138
+ const { ide, graphiql: graphiqlOptions, sandbox } = options;
139
+ if (ide === "apollo-sandbox")
140
+ return [sandboxPlugin(sandbox)];
141
+ if (ide === false || graphiqlOptions === false)
142
+ return [];
143
+ return [
144
+ graphiql({
145
+ enabled: ide === "graphiql" ? true : (request) => devs.get(request) === true,
146
+ ...graphiqlOptions
147
+ })
148
+ ];
149
+ }
119
150
 
120
- // src/body-refusal.ts
121
- import { GraphQLError } from "graphql";
122
- function isTooLarge(error) {
123
- return error instanceof Error && error.name === "ContentTooLargeError" && typeof error.limit === "number";
151
+ // src/operation.ts
152
+ import {
153
+ reportOperation,
154
+ startOperation
155
+ } from "@alxia/core";
156
+ import { createStateKey, definePlugin } from "@graxia/core";
157
+ import { getOperationAST } from "graphql";
158
+ var nameKey = createStateKey("alxia-operation-name");
159
+ var openKey = createStateKey("alxia-operation-open");
160
+ function describe(document, name) {
161
+ const operation = getOperationAST(document, name);
162
+ if (operation === undefined || operation === null)
163
+ return;
164
+ return { type: operation.operation, name: operation.name?.value };
124
165
  }
125
- function watchBody(request) {
126
- const source = request.body;
127
- if (source === null || request.bodyUsed || source.locked) {
128
- return { request, refusal: () => {
129
- return;
130
- } };
131
- }
132
- let refused;
133
- const reader = source.getReader();
134
- const body = new ReadableStream({
135
- async pull(controller) {
136
- try {
137
- const { value, done } = await reader.read();
138
- if (done)
139
- controller.close();
140
- else
141
- controller.enqueue(value);
142
- } catch (error) {
143
- if (!isTooLarge(error))
144
- throw error;
145
- refused = error;
146
- throw new GraphQLError("Request body too large", {
147
- extensions: {
148
- code: "REQUEST_ENTITY_TOO_LARGE",
149
- http: { status: 413 }
150
- }
151
- });
152
- }
166
+ var isStream = (result) => typeof result === "object" && result !== null && (Symbol.asyncIterator in result);
167
+ var failed = (result) => typeof result === "object" && result !== null && ("errors" in result) ? "errors" : "ok";
168
+ function reportsOperations() {
169
+ return definePlugin({
170
+ name: "alxia-report-operations",
171
+ onParse: ({ params, state }) => {
172
+ state.set(nameKey, params.operationName ?? null);
173
+ },
174
+ onValidate: ({ document, serverContext, state }) => {
175
+ return ({ errors }) => {
176
+ if (errors === undefined || errors.length === 0)
177
+ return;
178
+ const report = describe(document, state.get(nameKey));
179
+ if (report !== undefined)
180
+ startOperation(serverContext, report)("errors");
181
+ };
182
+ },
183
+ onExecute: ({ args }) => {
184
+ const { document, operationName, contextValue } = args;
185
+ const report = describe(document, operationName);
186
+ if (report === undefined)
187
+ return;
188
+ reportOperation(contextValue, report);
189
+ const end = startOperation(contextValue, report);
190
+ return ({ result }) => end(failed(result));
153
191
  },
154
- cancel: (reason) => reader.cancel(reason)
192
+ onSubscribe: ({ args, state }) => {
193
+ const { document, operationName, contextValue } = args;
194
+ const report = describe(document, operationName);
195
+ if (report === undefined)
196
+ return;
197
+ const context = contextValue;
198
+ reportOperation(context, report);
199
+ const end = startOperation(context, report);
200
+ const open = { outcome: "ok" };
201
+ state.set(openKey, open);
202
+ context.signal?.addEventListener("abort", () => end(open.outcome), {
203
+ once: true
204
+ });
205
+ return ({ result }) => {
206
+ if (isStream(result))
207
+ return;
208
+ open.outcome = failed(result);
209
+ end(open.outcome);
210
+ };
211
+ },
212
+ onResultChunk: ({ chunk, state }) => {
213
+ const open = state.get(openKey);
214
+ if (open !== undefined && failed(chunk) === "errors") {
215
+ open.outcome = "errors";
216
+ }
217
+ }
155
218
  });
156
- return {
157
- request: new Request(request, { body, duplex: "half" }),
158
- refusal: () => refused
159
- };
160
219
  }
161
- async function withoutOriginalError(response) {
162
- const type = response.headers.get("content-type") ?? "";
163
- if (response.status !== 400 || !/^application\/(?:[\w.-]+\+)?json/.test(type)) {
164
- return response;
165
- }
166
- const text = await response.text();
167
- let failure;
168
- try {
169
- failure = JSON.parse(text);
170
- } catch {
171
- return new Response(text, response);
172
- }
173
- for (const error of failure.errors ?? []) {
174
- delete error.extensions?.["originalError"];
220
+
221
+ // src/removed.ts
222
+ var FIXES = {
223
+ logging: "`logging` was Yoga's. Unexpected failures go to graxia's `onUnexpected` (console.error by default, off in production); log requests with `@alxia/logger`",
224
+ requestId: "`requestId` was Yoga's. Graxia generates its own `x-request-id` and never echoes the client's; the app's own id is `@alxia/core`'s",
225
+ cors: "`cors` is gone. Mount `@alxia/cors` on the app before `graphql()`",
226
+ sameOrigin: "`sameOrigin` is gone. Use `csrf: { sameOrigin: true }` (off by default; the CSRF header check is on)"
227
+ };
228
+ function rejectRemoved(options, caller = "graphql(app") {
229
+ for (const name of Object.keys(FIXES)) {
230
+ if (name in options && options[name] !== undefined) {
231
+ const call = caller === "graphql(app" ? `graphql(app, { ${name} })` : `graphqlExecutor({ ${name} })`;
232
+ throw new TypeError(`${call}: ${FIXES[name]}`);
233
+ }
175
234
  }
176
- const headers = new Headers(response.headers);
177
- headers.delete("content-length");
178
- return new Response(JSON.stringify(failure), { status: 400, headers });
179
235
  }
180
236
 
181
- // src/sandbox.ts
182
- var SANDBOX_POLICY = [
183
- "default-src 'self'",
184
- "script-src 'self' 'unsafe-inline' https://embeddable-sandbox.cdn.apollographql.com",
185
- "style-src 'self' 'unsafe-inline'",
186
- "frame-src https://sandbox.embed.apollographql.com",
187
- "img-src 'self' data: https:",
188
- "connect-src 'self'"
189
- ].join("; ");
190
- function renderSandbox(endpoint, options = {}) {
191
- const config = {
192
- target: "#sandbox",
193
- initialEndpoint: endpoint,
194
- initialState: {
195
- includeCookies: options.includeCookies ?? true,
196
- pollForSchemaUpdates: options.pollForSchemaUpdates ?? true,
197
- ...options.initialDocument === undefined ? {} : { document: options.initialDocument },
198
- ...options.initialHeaders === undefined ? {} : { headers: options.initialHeaders }
199
- },
200
- hideCookieToggle: false,
201
- endpointIsEditable: false
237
+ // src/options.ts
238
+ function limitsOf(legacy, bodyLimit, limits) {
239
+ return {
240
+ ...legacy.maxTokens === undefined ? {} : { tokens: legacy.maxTokens },
241
+ ...legacy.maxNesting === undefined ? {} : { nesting: legacy.maxNesting },
242
+ ...bodyLimit === undefined ? {} : { bodyBytes: bodyLimit },
243
+ ...limits
202
244
  };
203
- return `<!doctype html>
204
- <html lang="en">
205
- <head>
206
- <meta charset="utf-8" />
207
- <meta name="viewport" content="width=device-width, initial-scale=1" />
208
- <title>${html(options.title ?? "Sandbox Explorer")}</title>
209
- <style>html, body { margin: 0; height: 100%; } #sandbox { position: absolute; inset: 0; }</style>
210
- </head>
211
- <body>
212
- <div id="sandbox"></div>
213
- <script src="https://embeddable-sandbox.cdn.apollographql.com/_latest/embeddable-sandbox.umd.production.min.js"></script>
214
- <script>
215
- {
216
- const config = ${script(config)};
217
- config.initialEndpoint = new URL(config.initialEndpoint, location.href).href;
218
- new window.EmbeddedSandbox(config);
219
245
  }
220
- </script>
221
- </body>
222
- </html>`;
246
+ function cachesOf(parseCache, caches) {
247
+ if (caches !== undefined)
248
+ return caches;
249
+ if (parseCache === undefined || parseCache === false) {
250
+ return parseCache === false ? false : undefined;
251
+ }
252
+ return {
253
+ parse: {
254
+ ...parseCache.maxBytes === undefined ? {} : { maxBytes: parseCache.maxBytes },
255
+ ...parseCache.max === undefined ? {} : { max: parseCache.max },
256
+ ...parseCache.ttl === undefined ? {} : { ttlMs: parseCache.ttl }
257
+ }
258
+ };
223
259
  }
224
- function html(text) {
225
- return text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
260
+ function subscriptionsOf(ws) {
261
+ if (ws === false)
262
+ return { sse: true, ws: false };
263
+ const { keepAlive } = ws;
264
+ if (keepAlive === undefined)
265
+ return { sse: true, ws: true };
266
+ return {
267
+ sse: true,
268
+ ws: { keepAliveMs: keepAlive === false ? 0 : Math.ceil(keepAlive) }
269
+ };
270
+ }
271
+ function telemetryOf(telemetry) {
272
+ if (telemetry === false)
273
+ return false;
274
+ return { operationSpans: false, ...telemetry };
226
275
  }
227
- function script(value) {
228
- return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
276
+ function graxiaOptions(options, wiring) {
277
+ rejectRemoved(options, wiring.caller);
278
+ const {
279
+ maxTokens,
280
+ maxNesting,
281
+ parseCache,
282
+ maskedErrors,
283
+ ide,
284
+ graphiql,
285
+ sandbox,
286
+ path: _path,
287
+ ws: _ws,
288
+ bodyLimit: _bodyLimit,
289
+ plugins = [],
290
+ limits,
291
+ caches,
292
+ telemetry,
293
+ ...rest
294
+ } = options;
295
+ return {
296
+ ...rest,
297
+ telemetry: telemetryOf(telemetry),
298
+ path: false,
299
+ plugins: [
300
+ ...plugins,
301
+ ...explorerPlugins({ ide, graphiql, sandbox }, wiring.devs ?? new WeakMap),
302
+ reportsOperations()
303
+ ],
304
+ limits: limitsOf({ maxTokens, maxNesting }, wiring.bodyLimit, limits),
305
+ caches: cachesOf(parseCache, caches),
306
+ ...maskedErrors === false ? { maskErrors: false } : {},
307
+ subscriptions: subscriptionsOf(wiring.ws)
308
+ };
229
309
  }
230
310
 
231
- // src/handler.ts
232
- var GRAPHIQL_FILES = /https:\/\/unpkg\.com\/@graphql-yoga\/graphiql@[\w.-]+\//;
233
- function graphiqlPolicy(html) {
234
- const files = html.match(GRAPHIQL_FILES)?.[0] ?? "";
235
- const from = files === "" ? "" : ` ${files}`;
236
- return [
237
- "default-src 'self'",
238
- `script-src 'self' 'unsafe-inline'${from}`,
239
- `style-src 'self' 'unsafe-inline'${from}`,
240
- "img-src 'self' data: https:",
241
- `font-src 'self' data:${from}`,
242
- "worker-src 'self' blob:",
243
- `connect-src 'self'${from}`,
244
- "frame-ancestors 'none'"
245
- ].join("; ");
311
+ // src/executor.ts
312
+ function plain(error) {
313
+ return typeof error.toJSON === "function" ? error.toJSON() : error;
246
314
  }
247
- function yogaServers(options, caches) {
248
- const servers = new Map;
249
- return (endpoint) => {
250
- let yoga = servers.get(endpoint);
251
- if (yoga === undefined) {
252
- yoga = createYoga({
253
- ...options,
254
- ...caches === undefined ? {} : { parserAndValidationCache: caches() },
255
- graphqlEndpoint: endpoint
256
- });
257
- servers.set(endpoint, yoga);
258
- }
259
- return yoga;
315
+ function graphqlExecutor(options) {
316
+ const graxia = createGraxia({
317
+ ...graxiaOptions({ ...options, ide: false }, { ws: false, caller: "graphqlExecutor(" }),
318
+ csrf: false,
319
+ subscriptions: { sse: false, ws: false }
320
+ });
321
+ const run = async (request, context, call) => {
322
+ const body = await graxia.execute({
323
+ document: request.query,
324
+ ...request.operationName !== undefined && {
325
+ operationName: request.operationName
326
+ },
327
+ ...request.variables !== undefined && {
328
+ variables: request.variables
329
+ },
330
+ ...call?.signal !== undefined && { signal: call.signal },
331
+ serverContext: context
332
+ });
333
+ return {
334
+ ...body.data !== undefined && { data: body.data },
335
+ ...body.errors !== undefined && {
336
+ errors: body.errors.map(plain)
337
+ }
338
+ };
260
339
  };
340
+ return Object.assign(run, { dispose: () => graxia.dispose() });
261
341
  }
342
+ // src/graphql.ts
343
+ import {
344
+ createGraxia as createGraxia2
345
+ } from "@graxia/core";
346
+
347
+ // src/endpoint.ts
348
+ import { GraxiaConfigError } from "@graxia/core";
349
+ var DEFAULT_BODY_LIMIT = 1048576;
350
+ var HOST_LIMIT_OFF = Number.MAX_SAFE_INTEGER;
351
+ function declareEndpoint(app, path, bodyLimit, mount) {
352
+ const bodyBytes = bodyLimit ?? app.bodyLimitInForce ?? DEFAULT_BODY_LIMIT;
353
+ if (!(Number.isInteger(bodyBytes) && bodyBytes > 0)) {
354
+ throw new GraxiaConfigError("limits.bodyBytes must be a positive integer");
355
+ }
356
+ const route = app;
357
+ const mounted = mount(bodyBytes);
358
+ route.get(path, mounted.handler);
359
+ route.post(path, { bodyLimit: HOST_LIMIT_OFF }, mounted.handler);
360
+ if (mounted.socket !== undefined) {
361
+ route.ws(mounted.socket.path, mounted.socket.middleware, mounted.socket.handlers);
362
+ }
363
+ }
364
+
365
+ // src/handler.ts
366
+ import {
367
+ isDev,
368
+ shutdownSignal
369
+ } from "@alxia/core";
262
370
  function serverContext(ctx) {
263
371
  const {
264
372
  params: _params,
@@ -272,52 +380,14 @@ function serverContext(ctx) {
272
380
  } = ctx;
273
381
  return server;
274
382
  }
275
- var REFUSAL_OWN_HEADERS = new Set([
276
- "content-type",
277
- "content-length",
278
- "content-encoding",
279
- "transfer-encoding"
280
- ]);
281
- function graphqlHandler(yogaAt, sandbox) {
383
+ function graphqlHandler(graxia, devs) {
282
384
  return async function graphql(ctx) {
283
385
  const { reply } = ctx;
284
- const server = serverContext(ctx);
285
- if (sandbox !== false && ctx.request.method === "GET" && ctx.request.headers.get("accept")?.includes("text/html") && !ctx.url.searchParams.has("query")) {
286
- return reply(200, renderSandbox(ctx.route, sandbox), {
287
- headers: {
288
- "content-type": "text/html;charset=utf-8",
289
- "content-security-policy": SANDBOX_POLICY
290
- }
291
- });
292
- }
293
- const watched = watchBody(ctx.request);
294
- const answered = await yogaAt(ctx.route).fetch(watched.request, server);
295
- const refusal = watched.refusal();
296
- if (refusal !== undefined) {
297
- answered.body?.cancel();
298
- for (const [name, value] of answered.headers) {
299
- if (REFUSAL_OWN_HEADERS.has(name))
300
- continue;
301
- if (name === "set-cookie")
302
- ctx.set.headers.append(name, value);
303
- else if (name === "vary") {
304
- for (const part of value.split(","))
305
- vary(ctx.set.headers, part);
306
- } else
307
- ctx.set.headers.set(name, value);
308
- }
309
- throw refusal;
310
- }
311
- const response = await withoutOriginalError(answered);
312
- const headers = new Headers(response.headers);
313
- if (headers.get("content-type")?.startsWith("text/html") && !headers.has("content-security-policy")) {
314
- const html = await response.text();
315
- headers.set("content-security-policy", graphiqlPolicy(html));
316
- return reply(response.status, html, { headers });
317
- }
386
+ devs.set(ctx.request, isDev(ctx));
387
+ const response = await graxia.fetch(ctx.request, serverContext(ctx));
318
388
  const body = endedOnShutdown(response, shutdownSignal(ctx));
319
389
  return reply(response.status, body ?? undefined, {
320
- headers
390
+ headers: new Headers(response.headers)
321
391
  });
322
392
  };
323
393
  }
@@ -365,801 +435,71 @@ function endedOnShutdown(response, signal) {
365
435
  });
366
436
  }
367
437
 
368
- // src/operation.ts
369
- import { reportOperation } from "@alxia/core";
370
- import { getOperationAST } from "graphql";
371
- function report(args) {
372
- const operation = getOperationAST(args.document, args.operationName);
373
- if (operation === undefined || operation === null)
374
- return;
375
- reportOperation(args.contextValue, {
376
- type: operation.operation,
377
- name: operation.name?.value
378
- });
379
- }
380
- function reportsOperations() {
381
- return {
382
- onExecute: ({ args }) => report(args),
383
- onSubscribe: ({ args }) => report(args)
384
- };
385
- }
386
-
387
- // src/parse-limits.ts
388
- import { Source, syntaxError } from "graphql";
389
-
390
- // src/document-cache.ts
391
- import { TokenKind } from "graphql";
392
- function boundedCache(options) {
393
- const { max, ttl, maxBytes, weigh, now = Date.now } = options;
394
- const entries = new Map;
395
- let total = 0;
396
- const drop = (key, entry) => {
397
- entries.delete(key);
398
- total -= entry.weight;
399
- };
400
- return {
401
- get(key) {
402
- const entry = entries.get(key);
403
- if (entry === undefined)
404
- return;
405
- if (entry.expires <= now()) {
406
- drop(key, entry);
407
- return;
408
- }
409
- entries.delete(key);
410
- entries.set(key, entry);
411
- return entry.value;
412
- },
413
- set(key, value) {
414
- const previous = entries.get(key);
415
- if (previous !== undefined)
416
- drop(key, previous);
417
- const weight = weigh(key, value);
418
- if (weight > maxBytes / 8)
419
- return;
420
- entries.set(key, { value, weight, expires: now() + ttl });
421
- total += weight;
422
- for (const [oldest, entry] of entries) {
423
- if (entries.size <= max && total <= maxBytes)
424
- break;
425
- drop(oldest, entry);
426
- }
427
- }
428
- };
429
- }
430
- var BYTES_PER_TOKEN = 512;
431
- var BYTES_PER_CHAR = 4;
432
- var BYTES_PER_ESCAPED_CHAR = 32;
433
- var BYTES_PER_CHAR_NO_LOC = BYTES_PER_CHAR + BYTES_PER_ESCAPED_CHAR;
434
- var flattened = 0;
435
- function chainWalk(document) {
436
- const first = document.loc?.startToken;
437
- if (first === undefined)
438
+ // src/ws.ts
439
+ var KEY = "graxiaSocket";
440
+ function checkKeepAlive(options) {
441
+ const { keepAlive } = options;
442
+ if (keepAlive === undefined || keepAlive === false)
438
443
  return;
439
- let tokens = 0;
440
- let extra = 0;
441
- for (let token = first;token !== null; token = token.next) {
442
- tokens++;
443
- if (token.kind === TokenKind.STRING && token.value.length < token.end - token.start - 2) {
444
- extra += BYTES_PER_ESCAPED_CHAR * (token.end - token.start);
445
- if (token.value.length > 0)
446
- flattened = token.value.charCodeAt(0);
447
- }
448
- }
449
- return { tokens, extra: extra + (flattened & 0) };
450
- }
451
- function documentWeight(source, document) {
452
- const walk = chainWalk(document);
453
- if (walk !== undefined) {
454
- return BYTES_PER_TOKEN * walk.tokens + BYTES_PER_CHAR * source.length + walk.extra;
455
- }
456
- const tokenCount = document.tokenCount;
457
- if (typeof tokenCount !== "number") {
458
- return Math.max(256, BYTES_PER_CHAR_NO_LOC) * source.length;
459
- }
460
- return BYTES_PER_TOKEN * tokenCount + BYTES_PER_CHAR_NO_LOC * source.length;
461
- }
462
- function errorWeight(source) {
463
- return BYTES_PER_CHAR * source.length + 1024;
464
- }
465
-
466
- // src/nesting.ts
467
- var DEFAULT_MAX_NESTING = 1000;
468
- function nestingLimit(maxNesting) {
469
- if (maxNesting === undefined)
470
- return DEFAULT_MAX_NESTING;
471
- if (maxNesting === false)
472
- return false;
473
- if (typeof maxNesting === "number" && Number.isSafeInteger(maxNesting)) {
474
- if (maxNesting > 0)
475
- return maxNesting;
476
- }
477
- throw new TypeError(`graphql(app, { maxNesting }): maxNesting is the most levels of { ( [ a document may nest, a positive whole number, or false for none; got ${String(maxNesting)}`);
478
- }
479
- var QUOTE = 34;
480
- var BACKSLASH = 92;
481
- var HASH = 35;
482
- var LF = 10;
483
- var CR = 13;
484
- function tooDeepAt(body, max) {
485
- let depth = 0;
486
- const end = body.length;
487
- for (let i = 0;i < end; i++) {
488
- const code = body.charCodeAt(i);
489
- if (code === 123 || code === 40 || code === 91) {
490
- if (++depth > max)
491
- return i;
492
- } else if (code === 125 || code === 41 || code === 93) {
493
- if (depth > 0)
494
- depth--;
495
- } else if (code === HASH) {
496
- while (i + 1 < end) {
497
- const next = body.charCodeAt(i + 1);
498
- if (next === LF || next === CR)
499
- break;
500
- i++;
501
- }
502
- } else if (code === QUOTE) {
503
- if (body.startsWith('"""', i)) {
504
- i += 3;
505
- while (i < end) {
506
- if (body.startsWith('\\"""', i))
507
- i += 4;
508
- else if (body.startsWith('"""', i))
509
- break;
510
- else
511
- i++;
512
- }
513
- i += 2;
514
- } else {
515
- i++;
516
- while (i < end) {
517
- const inString = body.charCodeAt(i);
518
- if (inString === BACKSLASH)
519
- i += 2;
520
- else if (inString === QUOTE || inString === LF || inString === CR) {
521
- break;
522
- } else
523
- i++;
524
- }
525
- }
526
- }
527
- }
528
- return -1;
529
- }
530
-
531
- // src/parse-limits.ts
532
- var DEFAULT_MAX_TOKENS = 15000;
533
- var DEFAULT_BYTES = 64 * 1024 * 1024;
534
- function positive(name, value, what, alternative = "") {
535
- if (typeof value === "number" && Number.isSafeInteger(value) && value > 0) {
536
- return value;
537
- }
538
- throw new TypeError(`graphql(app, { ${name} }): ${what}, a positive whole number${alternative}; got ${String(value)}`);
539
- }
540
- function tokenLimit(maxTokens) {
541
- if (maxTokens === undefined)
542
- return DEFAULT_MAX_TOKENS;
543
- if (maxTokens === false)
544
- return false;
545
- return positive("maxTokens", maxTokens, "maxTokens is the most tokens a document may hold", ", or false for none");
546
- }
547
- var overflowed = (error) => error instanceof RangeError && /call stack/i.test(error.message);
548
- function limitsParsing(maxTokens, maxNesting) {
549
- return {
550
- onParse({ parseFn, setParseFn }) {
551
- setParseFn((source, options) => {
552
- const body = typeof source === "string" ? source : source.body;
553
- const refuse = (position, why) => syntaxError(typeof source === "string" ? new Source(source) : source, position, why);
554
- if (maxNesting !== false) {
555
- const at = tooDeepAt(body, maxNesting);
556
- if (at >= 0) {
557
- throw refuse(at, `Document is nested more than ${maxNesting} levels deep. Parsing aborted.`);
558
- }
559
- }
560
- try {
561
- return parseFn(source, maxTokens === false ? options : { ...options, maxTokens });
562
- } catch (error) {
563
- if (!overflowed(error))
564
- throw error;
565
- throw refuse(0, "Document is nested too deeply to parse.");
566
- }
567
- });
568
- }
569
- };
570
- }
571
- function cacheSizes(parseCache) {
572
- if (parseCache === false)
573
- return false;
574
- if (parseCache !== undefined && (typeof parseCache !== "object" || parseCache === null)) {
575
- throw new TypeError(`graphql(app, { parseCache }): parseCache is an object of cache sizes, or false for none; got ${String(parseCache)}`);
576
- }
577
- const given = parseCache ?? {};
578
- return {
579
- maxBytes: positive("parseCache.maxBytes", given.maxBytes ?? DEFAULT_BYTES, "maxBytes is the most estimated bytes of documents kept"),
580
- max: positive("parseCache.max", given.max ?? 1024, "max is the most documents kept"),
581
- ttl: positive("parseCache.ttl", given.ttl ?? 3600000, "ttl is the milliseconds a document is kept")
582
- };
583
- }
584
- function resolveLimits(maxTokens, maxNesting, parseCache, yogaOptions) {
585
- const tokens = tokenLimit(maxTokens);
586
- const depth = nestingLimit(maxNesting);
587
- if (parseCache !== undefined && yogaOptions.parserAndValidationCache !== undefined) {
588
- throw new TypeError("graphql(app, { parseCache, parserAndValidationCache }): give one: parseCache sizes alxia's bounded cache, parserAndValidationCache replaces it");
444
+ const valid = typeof keepAlive === "number" && Number.isFinite(keepAlive) && keepAlive > 0 && keepAlive <= 2 ** 31 - 1;
445
+ if (!valid) {
446
+ throw new TypeError(`graphql(app, { ws: { keepAlive: ${keepAlive} } }): keepAlive is the milliseconds between pings, a positive number up to ${2 ** 31 - 1}, or false for none`);
589
447
  }
590
- cacheSizes(parseCache);
591
- return { tokens, depth };
592
448
  }
593
- function parseCaches(parseCache) {
594
- const sizes = cacheSizes(parseCache);
595
- if (sizes === false)
596
- return false;
597
- const { maxBytes, max, ttl } = sizes;
598
- const documentCache = boundedCache({
599
- max,
600
- ttl,
601
- maxBytes,
602
- weigh: (source, document) => documentWeight(source, document)
603
- });
604
- const errorCache = boundedCache({
605
- max,
606
- ttl,
607
- maxBytes: Math.floor(maxBytes / 8),
608
- weigh: (source) => errorWeight(source)
609
- });
610
- return { documentCache, errorCache };
611
- }
612
-
613
- // src/yoga.ts
614
- function yogaFor(yogaOptions, page) {
615
- const { maxTokens, maxNesting, parseCache, ...rest } = yogaOptions;
616
- const { cors, ide, graphiql } = page;
617
- const limits = resolveLimits(maxTokens, maxNesting, parseCache, rest);
618
- const shown = graphiql ?? true;
619
- return yogaServers({
620
- ...rest,
621
- ...rest["logging"] === undefined ? { logging: "warn" } : {},
622
- ...untrustedRequestId(rest),
623
- plugins: [
624
- limitsParsing(limits.tokens, limits.depth),
625
- ...rest["plugins"] ?? [],
626
- reportsOperations()
627
- ],
628
- cors,
629
- graphiql: ide === undefined ? (_request, context) => isDev(context) && shown : ide === "graphiql" ? shown : false
630
- }, rest["parserAndValidationCache"] === undefined ? () => parseCaches(parseCache) : undefined);
631
- }
632
- function untrustedRequestId(options) {
633
- const { requestId } = options;
634
- if (requestId === undefined)
635
- return { requestId: false };
636
- if (requestId === true)
637
- return { requestId: { trustHeader: false } };
638
- if (typeof requestId === "object" && requestId !== null) {
639
- return { requestId: { trustHeader: false, ...requestId } };
640
- }
641
- return {};
642
- }
643
-
644
- // src/executor.ts
645
- var SUBSCRIPTION_REFUSED = {
646
- errors: [
647
- {
648
- message: "graphqlExecutor runs queries and mutations, not a subscription.",
649
- extensions: { code: "SUBSCRIPTION_NOT_SUPPORTED" }
650
- }
651
- ]
652
- };
653
- function graphqlExecutor(options) {
654
- const yoga = yogaFor(options, { cors: false, ide: false })("/graphql");
655
- return async (request, context, call) => {
656
- const response = await yoga.fetch(new Request("http://in-process/graphql", {
657
- method: "POST",
658
- headers: {
659
- "content-type": "application/json",
660
- accept: "application/json, text/event-stream"
661
- },
662
- body: JSON.stringify({
663
- query: request.query,
664
- ...request.operationName !== undefined && {
665
- operationName: request.operationName
666
- },
667
- ...request.variables !== undefined && {
668
- variables: request.variables
669
- }
670
- }),
671
- ...call?.signal !== undefined && { signal: call.signal }
672
- }), context);
673
- if (/text\/event-stream|multipart\/mixed/.test(response.headers.get("content-type") ?? "")) {
674
- response.body?.cancel();
675
- return SUBSCRIPTION_REFUSED;
676
- }
677
- const body = await response.json();
678
- return {
679
- ...body.data !== undefined && { data: body.data },
680
- ...body.errors !== undefined && { errors: body.errors }
681
- };
682
- };
683
- }
684
- // src/field-rate-limit/count.ts
685
- import {
686
- print
687
- } from "graphql";
688
- function countSelections(document, selections, names, singles = new Set) {
689
- const fragments = new Map;
690
- for (const definition of document.definitions) {
691
- if (definition.kind === "FragmentDefinition") {
692
- fragments.set(definition.name.value, definition);
693
- }
694
- }
695
- const done = new Map;
696
- const active = new Set;
697
- const walk = (set) => {
698
- const counts = new Map;
699
- const add = (from, under = "") => {
700
- for (const [name, selected] of from) {
701
- const own = counts.get(name) ?? { count: 0, distinct: new Set };
702
- own.count += selected.count;
703
- for (const one of selected.distinct) {
704
- if (own.distinct.size >= 2)
705
- break;
706
- own.distinct.add(under + one);
707
- }
708
- counts.set(name, own);
449
+ function graphqlSocket(graxia, endpoint, options) {
450
+ async function graphqlWs(ctx, next) {
451
+ let captured;
452
+ const standIn = {
453
+ upgrade(_request, given) {
454
+ captured = given;
455
+ return true;
709
456
  }
710
457
  };
711
- for (const selection of set.selections) {
712
- if (selection.kind === "Field") {
713
- const name = selection.name.value;
714
- const written = `${selection.alias?.value ?? name}(${(selection.arguments ?? []).map((argument) => print(argument)).sort().join(",")})`;
715
- if (names.has(name)) {
716
- const own = counts.get(name) ?? { count: 0, distinct: new Set };
717
- own.count += 1;
718
- if (singles.has(name) && own.distinct.size < 2)
719
- own.distinct.add(written);
720
- counts.set(name, own);
721
- }
722
- if (selection.selectionSet) {
723
- add(walk(selection.selectionSet), `${written}/`);
724
- }
725
- } else if (selection.kind === "InlineFragment") {
726
- add(walk(selection.selectionSet));
727
- } else {
728
- const name = selection.name.value;
729
- const fragment = fragments.get(name);
730
- if (fragment === undefined || active.has(name))
731
- continue;
732
- let own = done.get(name);
733
- if (own === undefined) {
734
- active.add(name);
735
- own = walk(fragment.selectionSet);
736
- active.delete(name);
737
- done.set(name, own);
738
- }
739
- add(own);
740
- }
741
- }
742
- return counts;
743
- };
744
- return walk(selections);
745
- }
746
- // src/field-rate-limit/from-store.ts
747
- function limitFromStore(store, policy) {
748
- const own = store.policy;
749
- const resolved = {
750
- limit: policy?.limit ?? own?.limit ?? Number.NaN,
751
- windowMs: policy?.windowMs ?? own?.windowMs ?? Number.NaN
752
- };
753
- for (const name of ["limit", "windowMs"]) {
754
- const value = resolved[name];
755
- if (!Number.isSafeInteger(value) || value < 1) {
756
- throw new TypeError(`limitFromStore: ${name} must be a whole number of 1 or more, not ${String(policy?.[name] ?? own?.[name])}`);
757
- }
758
- if (own !== undefined && value !== own[name]) {
759
- throw new TypeError(`limitFromStore: ${name} ${value} differs from the store's policy of ${own.limit} per ${own.windowMs}ms. Leave the policy out to use the store's, or give the same numbers.`);
760
- }
761
- }
762
- return {
763
- async consume(key, cost) {
764
- for (let i = 0;i < cost; i++) {
765
- const decision = await store.consume(key, resolved);
766
- if (!decision.allowed) {
767
- return { allowed: false, retryAfter: decision.retryAfter };
768
- }
769
- }
770
- return { allowed: true, retryAfter: 0 };
771
- }
772
- };
773
- }
774
- // src/field-rate-limit/plugin.ts
775
- import { GraphQLError as GraphQLError2, getOperationAST as getOperationAST2 } from "graphql";
776
-
777
- // src/field-rate-limit/ipv6-network.ts
778
- function groupsOf(text) {
779
- const zone = text.indexOf("%");
780
- const address = zone === -1 ? text : text.slice(0, zone);
781
- const halves = address.split("::");
782
- if (halves.length > 2 || !address.includes(":"))
783
- return;
784
- const read = (half) => half === undefined || half === "" ? [] : half.split(":");
785
- const head = read(halves[0]) ?? [];
786
- const tail = read(halves[1]) ?? [];
787
- const written = [...head, ...tail];
788
- const last = written[written.length - 1];
789
- if (last?.includes(".")) {
790
- if (!address.endsWith(last))
791
- return;
792
- const octets = last.split(".");
793
- const bytes = octets.map((octet) => /^\d{1,3}$/.test(octet) ? Number(octet) : Number.NaN);
794
- if (bytes.length !== 4 || bytes.some((byte) => !(byte <= 255)))
795
- return;
796
- const [a = 0, b = 0, c = 0, d = 0] = bytes;
797
- written.splice(-1, 1, (a << 8 | b).toString(16), (c << 8 | d).toString(16));
798
- if (tail.length > 0)
799
- tail.splice(-1, 1, "x", "x");
800
- else
801
- head.splice(-1, 1, "x", "x");
802
- }
803
- const compressed = halves.length === 2;
804
- const missing = 8 - written.length;
805
- if (compressed ? missing < 1 : missing !== 0)
806
- return;
807
- const all = compressed ? [
808
- ...written.slice(0, head.length),
809
- ...new Array(missing).fill("0"),
810
- ...written.slice(head.length)
811
- ] : written;
812
- const groups = all.map((group) => /^[0-9a-f]{1,4}$/i.test(group) ? Number.parseInt(group, 16) : Number.NaN);
813
- return groups.some(Number.isNaN) ? undefined : groups;
814
- }
815
- function written(groups) {
816
- let start = -1;
817
- let length = 0;
818
- for (let i = 0;i < 8; ) {
819
- if (groups[i] !== 0) {
820
- i++;
821
- continue;
822
- }
823
- let end = i;
824
- while (end < 8 && groups[end] === 0)
825
- end++;
826
- if (end - i > length) {
827
- start = i;
828
- length = end - i;
829
- }
830
- i = end;
831
- }
832
- const hex = (list) => list.map((group) => group.toString(16)).join(":");
833
- if (length < 2)
834
- return hex(groups);
835
- return `${hex(groups.slice(0, start))}::${hex(groups.slice(start + length))}`;
836
- }
837
- function ipv6Network(address, prefix) {
838
- const groups = groupsOf(address);
839
- if (groups === undefined)
840
- return address;
841
- if (groups.slice(0, 5).every((group) => group === 0) && groups[5] === 65535) {
842
- const [a = 0, b = 0] = groups.slice(6);
843
- return `${a >> 8}.${a & 255}.${b >> 8}.${b & 255}`;
844
- }
845
- const masked = groups.map((group, index) => {
846
- const kept = Math.min(16, Math.max(0, prefix - index * 16));
847
- return group >> 16 - kept << 16 - kept;
848
- });
849
- return `${written(masked.map((group) => group & 65535))}/${prefix}`;
850
- }
851
-
852
- // src/field-rate-limit/plugin.ts
853
- var DEFAULT_LIMIT_CODE = "RATE_LIMITED";
854
- function rulesOf(fields) {
855
- if (typeof fields !== "object" || fields === null || Object.keys(fields).length === 0) {
856
- throw new TypeError("fieldRateLimit({ fields }): fields maps each field name to count to its limit, and holds at least one");
857
- }
858
- const rules = new Map;
859
- for (const [name, rule] of Object.entries(fields)) {
860
- const wrapped = typeof rule === "object" && rule !== null && "limit" in rule && typeof rule.limit === "object";
861
- const limit = wrapped ? rule.limit : rule;
862
- if (typeof limit?.consume !== "function") {
863
- throw new TypeError(`fieldRateLimit({ fields: { ${name} } }): a limit has a consume(key, cost) method, or is { limit, single? }`);
864
- }
865
- rules.set(name, {
866
- limit,
867
- single: wrapped && rule.single === true
868
- });
869
- }
870
- return rules;
871
- }
872
- function checked(options) {
873
- const { ipv6Prefix } = options;
874
- if (ipv6Prefix !== undefined) {
875
- if (!Number.isInteger(ipv6Prefix) || ipv6Prefix < 0 || ipv6Prefix > 128) {
876
- throw new TypeError(`fieldRateLimit: ipv6Prefix must be a whole number from 0 to 128, not ${String(ipv6Prefix)}`);
877
- }
878
- if (options.key !== undefined) {
879
- throw new TypeError("fieldRateLimit: ipv6Prefix applies to the default key, and a key of your own was given. Drop one, or group the address in your key.");
880
- }
881
- }
882
- const { code } = options;
883
- if (code !== undefined && (typeof code !== "string" || code === "")) {
884
- throw new TypeError("fieldRateLimit: code is a non-empty string");
885
- }
886
- }
887
- function refusal(message, code, status, extensions = {}, headers) {
888
- return {
889
- errors: [
890
- new GraphQLError2(message, {
891
- extensions: {
892
- code,
893
- ...extensions,
894
- http: headers === undefined ? { status } : { status, headers }
895
- }
896
- })
897
- ]
898
- };
899
- }
900
- function fieldRateLimit(options) {
901
- const rules = rulesOf(options.fields);
902
- checked(options);
903
- const names = new Set(rules.keys());
904
- const singles = new Set([...rules].filter(([, r]) => r.single).map(([n]) => n));
905
- const code = options.code ?? DEFAULT_LIMIT_CODE;
906
- const prefix = options.ipv6Prefix;
907
- const keyOf = options.key ?? ((ctx) => {
908
- const { ip } = ctx;
909
- return prefix === undefined || ip === undefined ? ip : ipv6Network(ip, prefix);
910
- });
911
- return {
912
- async onExecute({ args, setResultAndStopExecution }) {
913
- const operation = getOperationAST2(args.document, args.operationName);
914
- if (!operation)
915
- return;
916
- const counts = countSelections(args.document, operation.selectionSet, names, singles);
917
- if (counts.size === 0)
918
- return;
919
- for (const [name, selected] of counts) {
920
- if (rules.get(name)?.single && selected.distinct.size > 1) {
921
- return setResultAndStopExecution(refusal(`${name} may be selected once per operation`, "FIELD_SELECTED_ONCE", 400));
922
- }
923
- }
924
- const who = await keyOf(args.contextValue);
925
- if (who === undefined)
926
- return;
927
- for (const [name, selected] of counts) {
928
- const decision = await rules.get(name).limit.consume(`${name}:${who}`, selected.count);
929
- if (!decision.allowed) {
930
- const wait = Math.ceil(decision.retryAfter / 1000);
931
- const retryAfter = Number.isFinite(wait) ? Math.max(1, wait) : 1;
932
- return setResultAndStopExecution(refusal("Too many attempts, try again later", code, 429, { retryAfter }, { "retry-after": String(retryAfter) }));
933
- }
934
- }
935
- }
936
- };
937
- }
938
- // src/endpoint.ts
939
- var DEFAULT_BODY_LIMIT = 1048576;
940
- function declareEndpoint(app, path, handler, bodyLimit, socket) {
941
- const route = app;
942
- route.get(path, handler);
943
- const inherited = app.routes.at(-1)?.bodyLimit;
944
- const own = bodyLimit ?? (inherited === undefined ? DEFAULT_BODY_LIMIT : undefined);
945
- if (own === undefined)
946
- route.post(path, handler);
947
- else
948
- route.post(path, { bodyLimit: own }, handler);
949
- if (socket !== undefined) {
950
- route.ws(socket.path, socket.middleware, socket.handlers);
951
- }
952
- }
953
-
954
- // src/ws-operations.ts
955
- import { startOperation } from "@alxia/core";
956
- import { getOperationAST as getOperationAST3 } from "graphql";
957
-
958
- class SocketOperations {
959
- #ctx;
960
- #open = new Map;
961
- constructor(ctx) {
962
- this.#ctx = ctx;
963
- }
964
- begin(id, document, operationName) {
965
- this.end(id);
966
- const operation = getOperationAST3(document, operationName);
967
- if (operation === undefined || operation === null)
968
- return;
969
- const end = startOperation(this.#ctx, {
970
- type: operation.operation,
971
- name: operation.name?.value
972
- });
973
- this.#open.set(id, { end, outcome: "ok" });
974
- }
975
- failed(id) {
976
- const open = this.#open.get(id);
977
- if (open !== undefined)
978
- open.outcome = "errors";
979
- }
980
- end(id) {
981
- const open = this.#open.get(id);
982
- if (open === undefined)
983
- return;
984
- this.#open.delete(id);
985
- open.end(open.outcome);
986
- }
987
- closed() {
988
- for (const id of [...this.#open.keys()]) {
989
- this.failed(id);
990
- this.end(id);
991
- }
992
- }
993
- }
994
- function following() {
995
- return {
996
- onNext({ extra }, id, _payload, _args, result) {
997
- if (result.errors !== undefined && result.errors.length > 0) {
998
- extra.operations.failed(id);
999
- }
1000
- },
1001
- onError({ extra }, id) {
1002
- extra.operations.failed(id);
1003
- extra.operations.end(id);
1004
- },
1005
- onComplete({ extra }, id) {
1006
- extra.operations.end(id);
458
+ const host = serverContext(ctx);
459
+ const refused = await graxia.upgrade(ctx.request, standIn, host);
460
+ if (refused !== undefined || captured === undefined)
461
+ return refused;
462
+ for (const [name, value] of new Headers(captured.headers)) {
463
+ ctx.set.headers.set(name, value);
1007
464
  }
1008
- };
1009
- }
1010
-
1011
- // src/ws-server.ts
1012
- function endpointOf(route, paths) {
1013
- const own = paths.socket === "/" ? "" : paths.socket;
1014
- const at = paths.endpoint === "/" ? "" : paths.endpoint;
1015
- return route.slice(0, route.length - own.length) + at || "/";
1016
- }
1017
- function serverOptions(yogaAt, paths) {
1018
- const enveloped = new WeakMap;
1019
- const of = (args) => enveloped.get(args.contextValue);
1020
- return {
1021
- execute: (args) => of(args).execute(args),
1022
- subscribe: (args) => of(args).subscribe(args),
1023
- ...following(),
1024
- async onSubscribe(context, id, params) {
1025
- const { ctx, request } = context.extra;
1026
- const initial = {
1027
- ...serverContext(ctx),
1028
- request,
1029
- params,
1030
- connectionParams: context.connectionParams
1031
- };
1032
- const { schema, execute, subscribe, contextFactory, parse, validate } = yogaAt(endpointOf(ctx.route, paths)).getEnveloped(initial);
1033
- let document;
1034
- try {
1035
- document = parse(params.query);
1036
- } catch (error) {
1037
- return [error];
1038
- }
1039
- context.extra.operations.begin(id, document, params.operationName);
1040
- const errors = validate(schema, document);
1041
- if (errors.length > 0)
1042
- return errors;
1043
- const contextValue = await contextFactory();
1044
- enveloped.set(contextValue, { execute, subscribe });
1045
- return {
1046
- schema,
1047
- document,
1048
- operationName: params.operationName,
1049
- variableValues: params.variables,
1050
- contextValue
1051
- };
1052
- }
1053
- };
1054
- }
1055
-
1056
- // src/ws.ts
1057
- var MISSING_PEER = "@alxia/graphql: graphql(app, { ws }) serves GraphQL over WebSocket with the optional peer graphql-ws, which is not installed: bun add graphql-ws";
1058
- function loader() {
1059
- let loading;
1060
- return () => {
1061
- loading ??= import("graphql-ws").catch((cause) => {
1062
- throw new Error(MISSING_PEER, { cause });
1063
- });
1064
- return loading;
1065
- };
1066
- }
1067
- function chosen(module, request) {
1068
- const offered = request.headers.get("sec-websocket-protocol") ?? "";
1069
- return module.handleProtocols(offered) || "";
1070
- }
1071
- function operationRequest(upgrade, signal) {
1072
- return new Request(upgrade.url, {
1073
- method: "POST",
1074
- headers: upgrade.headers,
1075
- signal
1076
- });
1077
- }
1078
- function pingEvery(keepAlive) {
1079
- if (keepAlive === undefined)
1080
- return 12000;
1081
- if (keepAlive === false)
1082
- return false;
1083
- if (Number.isFinite(keepAlive) && keepAlive > 0)
1084
- return keepAlive;
1085
- throw new TypeError(`graphql(app, { ws: { keepAlive: ${keepAlive} } }): keepAlive is the milliseconds between pings, a positive number, or false for none`);
1086
- }
1087
- function graphqlSocket(yogaAt, endpoint, options) {
1088
- const paths = { endpoint, socket: options.path ?? endpoint };
1089
- const keepAlive = pingEvery(options.keepAlive);
1090
- const load = loader();
1091
- let module;
1092
- let server;
1093
- const clients = new WeakMap;
1094
- async function graphqlWs(ctx, next) {
1095
- module ??= await load();
1096
- server ??= module.makeServer(serverOptions(yogaAt, paths));
1097
- const protocol = chosen(module, ctx.request);
1098
- if (protocol !== "")
1099
- ctx.set.headers.set("sec-websocket-protocol", protocol);
1100
- return next();
465
+ return next({ [KEY]: captured.data });
1101
466
  }
1102
467
  const handlers = {
1103
468
  open(socket) {
1104
- const raw = socket.raw;
1105
- const client = {
1106
- gone: new AbortController,
1107
- operations: new SocketOperations(socket.data)
1108
- };
1109
- clients.set(raw, client);
1110
- const graphqlWsServer = server;
1111
- client.closed = graphqlWsServer.opened({
1112
- protocol: chosen(module, socket.data.request),
1113
- send: (data) => {
1114
- if (raw.readyState === 1)
1115
- raw.sendText(data);
1116
- },
1117
- close: (code, reason) => raw.close(code, reason),
1118
- onMessage: (handle) => {
1119
- client.onMessage = handle;
1120
- }
1121
- }, {
1122
- ctx: socket.data,
1123
- request: operationRequest(socket.data.request, client.gone.signal),
1124
- operations: client.operations
1125
- });
1126
- if (keepAlive !== false) {
1127
- client.pings = setInterval(() => raw.ping(), keepAlive);
1128
- }
469
+ Object.assign(socket.raw.data, socket.data[KEY]);
470
+ graxia.websocket.open?.(socket.raw);
1129
471
  },
1130
472
  async message(socket, message) {
1131
- const data = typeof message === "string" ? message : new TextDecoder().decode(message);
1132
- await clients.get(socket.raw)?.onMessage?.(data);
473
+ await graxia.websocket.message?.(socket.raw, message);
1133
474
  },
1134
475
  async close(socket, code, reason) {
1135
- const client = clients.get(socket.raw);
1136
- if (client === undefined)
1137
- return;
1138
- clearInterval(client.pings);
1139
- clients.delete(socket.raw);
1140
- client.gone.abort();
1141
- await client.closed?.(code, reason);
1142
- client.operations.closed();
476
+ await graxia.websocket.close?.(socket.raw, code, reason);
477
+ },
478
+ drain(socket) {
479
+ graxia.websocket.drain?.(socket.raw);
1143
480
  }
1144
481
  };
1145
- return { path: paths.socket, middleware: graphqlWs, handlers };
482
+ return { path: options.path ?? endpoint, middleware: graphqlWs, handlers };
1146
483
  }
1147
484
 
1148
485
  // src/graphql.ts
1149
486
  function graphql(app, options) {
1150
- const {
1151
- path = "/graphql",
1152
- cors = false,
1153
- ide,
1154
- graphiql,
1155
- sandbox,
1156
- ws = false,
1157
- bodyLimit,
1158
- ...yogaOptions
1159
- } = options;
1160
- const yogaAt = yogaFor(yogaOptions, { cors, ide, graphiql });
1161
- const handler = graphqlHandler(yogaAt, ide === "apollo-sandbox" ? sandbox ?? {} : false);
1162
- declareEndpoint(app, path, handler, bodyLimit, ws === false ? undefined : graphqlSocket(yogaAt, path, ws === true ? {} : ws));
487
+ const { path = "/graphql", ws = false, bodyLimit } = options;
488
+ if (typeof ws === "object")
489
+ checkKeepAlive(ws);
490
+ const devs = new WeakMap;
491
+ declareEndpoint(app, path, bodyLimit, (bodyBytes) => {
492
+ const graxia = createGraxia2(graxiaOptions(options, {
493
+ devs,
494
+ ws: ws === false ? false : ws === true ? {} : ws,
495
+ bodyLimit: bodyBytes
496
+ }));
497
+ app.onStop(() => graxia.dispose());
498
+ return {
499
+ handler: graphqlHandler(graxia, devs),
500
+ socket: ws === false ? undefined : graphqlSocket(graxia, path, ws === true ? {} : ws)
501
+ };
502
+ });
1163
503
  return app;
1164
504
  }
1165
505
  // src/once-per-request.ts
@@ -1187,6 +527,12 @@ function clearRequestCache(request) {
1187
527
  caches.delete(request);
1188
528
  }
1189
529
  function freshPerMutation(resolvers) {
530
+ if (Array.isArray(resolvers)) {
531
+ return resolvers.map((map) => freshPerMutation(map));
532
+ }
533
+ return wrapMutation(resolvers);
534
+ }
535
+ function wrapMutation(resolvers) {
1190
536
  const mutation = resolvers.Mutation;
1191
537
  if (!mutation)
1192
538
  return resolvers;
@@ -1205,61 +551,7 @@ function freshPerMutation(resolvers) {
1205
551
  }
1206
552
  return { ...resolvers, Mutation: wrapped };
1207
553
  }
1208
- // src/same-origin/same-origin.ts
1209
- function hostOf(value) {
1210
- try {
1211
- return new URL(value).host;
1212
- } catch {
1213
- return null;
1214
- }
1215
- }
1216
- function hostsOf(allow) {
1217
- const hosts = new Set;
1218
- for (const entry of allow) {
1219
- const host = entry.includes("://") ? hostOf(entry) : entry.toLowerCase();
1220
- if (host === null || host === "") {
1221
- throw new TypeError(`sameOrigin({ allow }): "${entry}" is neither an origin nor a host`);
1222
- }
1223
- hosts.add(host);
1224
- }
1225
- return hosts;
1226
- }
1227
- var forbidden = () => new Response(JSON.stringify({
1228
- errors: [
1229
- {
1230
- message: "Cross-origin requests are not allowed",
1231
- extensions: { code: "FORBIDDEN" }
1232
- }
1233
- ]
1234
- }), {
1235
- status: 403,
1236
- headers: {
1237
- "content-type": "application/json",
1238
- "cache-control": "no-store"
1239
- }
1240
- });
1241
- function sameOrigin(options = {}) {
1242
- const allowed = hostsOf(options.allow ?? []);
1243
- const json = options.json !== false;
1244
- const refuse = options.refuse ?? forbidden;
1245
- return {
1246
- async onRequest({ request, endResponse }) {
1247
- const origin = request.headers.get("origin");
1248
- if (origin !== null) {
1249
- const host = hostOf(origin);
1250
- if (host === null || host !== hostOf(request.url) && !allowed.has(host)) {
1251
- endResponse(await refuse(request));
1252
- return;
1253
- }
1254
- }
1255
- if (json && request.method === "POST" && !(request.headers.get("content-type") ?? "").startsWith("application/json")) {
1256
- endResponse(await refuse(request));
1257
- }
1258
- }
1259
- };
1260
- }
1261
554
  export {
1262
- SANDBOX_POLICY,
1263
555
  boundedStream,
1264
556
  clearRequestCache,
1265
557
  fieldRateLimit,
@@ -1267,10 +559,8 @@ export {
1267
559
  graphql,
1268
560
  graphqlExecutor,
1269
561
  limitFromStore,
1270
- oncePerRequest,
1271
- renderSandbox,
1272
- sameOrigin
562
+ oncePerRequest
1273
563
  };
1274
564
 
1275
- //# debugId=F6774FF2900578EC64756E2164756E21
565
+ //# debugId=32A986800C6A89D964756E2164756E21
1276
566
  //# sourceMappingURL=index.js.map