@makerx/graphql-core 2.2.2 → 3.0.0-beta.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 (53) hide show
  1. package/README.md +76 -100
  2. package/User.js.map +1 -1
  3. package/User.mjs.map +1 -1
  4. package/context.d.ts +17 -20
  5. package/context.js +19 -28
  6. package/context.js.map +1 -1
  7. package/context.mjs +13 -22
  8. package/context.mjs.map +1 -1
  9. package/index.d.ts +4 -4
  10. package/index.js +10 -9
  11. package/index.js.map +1 -1
  12. package/index.mjs +3 -3
  13. package/logging.d.ts +6 -4
  14. package/logging.js +8 -6
  15. package/logging.js.map +1 -1
  16. package/logging.mjs +6 -4
  17. package/logging.mjs.map +1 -1
  18. package/package.json +7 -11
  19. package/request-info.d.ts +22 -0
  20. package/request-info.js +85 -0
  21. package/request-info.js.map +1 -0
  22. package/request-info.mjs +80 -0
  23. package/request-info.mjs.map +1 -0
  24. package/schema-util.js.map +1 -1
  25. package/schema-util.mjs.map +1 -1
  26. package/shield.d.ts +2 -2
  27. package/shield.js.map +1 -1
  28. package/shield.mjs +1 -1
  29. package/shield.mjs.map +1 -1
  30. package/subscriptions/context.d.ts +12 -10
  31. package/subscriptions/context.js +16 -25
  32. package/subscriptions/context.js.map +1 -1
  33. package/subscriptions/context.mjs +12 -21
  34. package/subscriptions/context.mjs.map +1 -1
  35. package/subscriptions/server.d.ts +3 -3
  36. package/subscriptions/server.js +7 -7
  37. package/subscriptions/server.js.map +1 -1
  38. package/subscriptions/server.mjs +4 -4
  39. package/subscriptions/server.mjs.map +1 -1
  40. package/subscriptions/utils.d.ts +0 -1
  41. package/subscriptions/utils.js +1 -1
  42. package/subscriptions/utils.js.map +1 -1
  43. package/subscriptions/utils.mjs +1 -1
  44. package/subscriptions/utils.mjs.map +1 -1
  45. package/utils.d.ts +1 -1
  46. package/utils.js.map +1 -1
  47. package/utils.mjs.map +1 -1
  48. package/testing.d.ts +0 -7
  49. package/testing.js +0 -68
  50. package/testing.js.map +0 -1
  51. package/testing.mjs +0 -60
  52. package/testing.mjs.map +0 -1
  53. /package/{models.d.ts → type-utils.d.ts} +0 -0
@@ -1,30 +1,23 @@
1
1
  'use strict';
2
2
 
3
- var crypto = require('crypto');
4
- var lodash = require('lodash');
3
+ var compat = require('es-toolkit/compat');
5
4
  var User = require('../User.js');
5
+ var requestInfo = require('../request-info.js');
6
6
  var utils = require('./utils.js');
7
7
 
8
- const createSubscriptionContextFactory = ({ requestLogger, augmentRequestInfo, claimsToLog, createUser = defaultCreateUser, requestInfoToLog, augmentContext, }) => {
9
- // the function that creates the GraphQL context
8
+ const createSubscriptionContextFactory = (config) => {
9
+ const { requestLogger, augmentRequestInfo, claimsToLog, requestInfoToLog, augmentContext } = config;
10
+ // The conditional type on CreateSubscriptionContextConfig guarantees `createUser` is provided
11
+ // when TUser is narrower than `User | undefined`, so defaulting is sound here.
12
+ const createUser = (config.createUser ?? defaultCreateUser);
10
13
  return async (input) => {
11
14
  const { connectRequest: req, claims } = input;
12
- const xForwardedFor = req.headers['x-forwarded-for'];
13
- const host = Array.isArray(xForwardedFor) ? xForwardedFor[0] : xForwardedFor ?? req.headers.host;
14
15
  // build request info from the connect request and socket
15
- const requestInfo = {
16
- requestId: req.headers['x-request-id']?.toString() ?? crypto.randomUUID(),
17
- protocol: 'ws',
18
- host: host ?? '',
19
- method: req.method ?? '',
20
- url: req.url ?? '',
21
- origin: req.headers['origin'] ?? '',
22
- referer: req.headers.referer?.toString() ?? '',
23
- arrLogId: req.headers['x-arr-log-id']?.toString() ?? undefined,
24
- clientIp: req.headers['x-forwarded-for']?.toString() ?? req.socket.remoteAddress,
25
- correlationId: req.headers['x-correlation-id']?.toString() ?? undefined,
16
+ const requestInfo$1 = {
17
+ ...requestInfo.buildConnectRequestInfo(req),
26
18
  ...augmentRequestInfo?.(input),
27
19
  };
20
+ const user = await createUser(input);
28
21
  // create request logger
29
22
  let logger;
30
23
  if (typeof requestLogger === 'function') {
@@ -32,24 +25,22 @@ const createSubscriptionContextFactory = ({ requestLogger, augmentRequestInfo, c
32
25
  const requestLoggerMetadata = {};
33
26
  // add request info to log
34
27
  if (requestInfoToLog?.length)
35
- requestLoggerMetadata.request = lodash.pick(requestInfo, requestInfoToLog);
28
+ requestLoggerMetadata.request = compat.pick(requestInfo$1, requestInfoToLog);
36
29
  // add user claims to log
37
30
  if (claims && claimsToLog?.length)
38
- requestLoggerMetadata.user = lodash.pick(claims, claimsToLog);
31
+ requestLoggerMetadata.user = compat.pick(claims, claimsToLog);
39
32
  // build the request logger
40
- logger = requestLogger(requestLoggerMetadata);
33
+ logger = requestLogger(requestLoggerMetadata, user);
41
34
  }
42
35
  else
43
36
  logger = requestLogger;
44
37
  const graphqlContext = {
45
- requestInfo,
38
+ requestInfo: requestInfo$1,
46
39
  logger,
47
- user: await createUser(input),
40
+ user,
48
41
  started: Date.now(),
49
42
  };
50
- const augmentedGraphQLContext = augmentContext
51
- ? { ...graphqlContext, ...(await augmentContext(graphqlContext)) }
52
- : graphqlContext;
43
+ const augmentedGraphQLContext = augmentContext ? { ...graphqlContext, ...(await augmentContext(graphqlContext)) } : graphqlContext;
53
44
  return augmentedGraphQLContext;
54
45
  };
55
46
  };
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","sources":["../../src/subscriptions/context.ts"],"sourcesContent":["import type { Logger } from '@makerx/node-common'\nimport { randomUUID } from 'crypto'\nimport type { IncomingMessage } from 'http'\nimport { pick } from 'lodash'\nimport { User } from '../User'\nimport type { CreateRequestLogger, GraphQLContext, JwtPayload, RequestInfo } from '../context'\nimport { extractTokenFromConnectionParams } from './utils'\n\nexport interface SubscriptionContextInput {\n connectRequest: IncomingMessage\n connectionParams?: Readonly<Record<string, unknown>>\n claims?: JwtPayload\n}\n\nexport type CreateSubscriptionUser<T = User | undefined> = (input: SubscriptionContextInput) => Promise<T>\nexport type CreateSubscriptionContext<TContext = GraphQLContext> = (input: SubscriptionContextInput) => Promise<TContext>\nexport type AugmentSubscriptionRequestInfo = (input: SubscriptionContextInput) => Record<string, unknown>\n\nexport interface CreateSubscriptionContextConfig<TContext = GraphQLContext> {\n requestLogger: CreateRequestLogger | Logger\n augmentRequestInfo?: AugmentSubscriptionRequestInfo\n claimsToLog?: string[]\n createUser?: CreateSubscriptionUser\n requestInfoToLog?: Array<keyof RequestInfo>\n augmentContext?: (context: TContext) => Record<string, unknown> | Promise<Record<string, unknown>>\n}\n\nexport const createSubscriptionContextFactory = <TContext extends GraphQLContext = GraphQLContext>({\n requestLogger,\n augmentRequestInfo,\n claimsToLog,\n createUser = defaultCreateUser,\n requestInfoToLog,\n augmentContext,\n}: CreateSubscriptionContextConfig<TContext>): CreateSubscriptionContext<TContext> => {\n // the function that creates the GraphQL context\n return async (input: SubscriptionContextInput) => {\n const { connectRequest: req, claims } = input\n\n const xForwardedFor = req.headers['x-forwarded-for']\n const host = Array.isArray(xForwardedFor) ? xForwardedFor[0] : xForwardedFor ?? req.headers.host\n\n // build request info from the connect request and socket\n const requestInfo: RequestInfo = {\n requestId: req.headers['x-request-id']?.toString() ?? randomUUID(),\n protocol: 'ws',\n host: host ?? '',\n method: req.method ?? '',\n url: req.url ?? '',\n origin: req.headers['origin'] ?? '',\n referer: req.headers.referer?.toString() ?? '',\n arrLogId: req.headers['x-arr-log-id']?.toString() ?? undefined,\n clientIp: req.headers['x-forwarded-for']?.toString() ?? req.socket.remoteAddress,\n correlationId: req.headers['x-correlation-id']?.toString() ?? undefined,\n ...augmentRequestInfo?.(input),\n }\n\n // create request logger\n let logger: Logger\n if (typeof requestLogger === 'function') {\n // build request logger metadata\n const requestLoggerMetadata: Record<string, unknown> = {}\n // add request info to log\n if (requestInfoToLog?.length) requestLoggerMetadata.request = pick(requestInfo, requestInfoToLog)\n // add user claims to log\n if (claims && claimsToLog?.length) requestLoggerMetadata.user = pick(claims, claimsToLog)\n // build the request logger\n logger = requestLogger(requestLoggerMetadata)\n } else logger = requestLogger\n\n const graphqlContext: GraphQLContext = {\n requestInfo,\n logger,\n user: await createUser(input),\n started: Date.now(),\n }\n\n const augmentedGraphQLContext = augmentContext\n ? { ...graphqlContext, ...(await augmentContext(graphqlContext as TContext)) }\n : graphqlContext\n\n return augmentedGraphQLContext as TContext\n }\n}\n\nconst defaultCreateUser: CreateSubscriptionUser<User | undefined> = ({ claims, connectionParams }) => {\n if (!claims) return Promise.resolve(undefined)\n const accessToken = extractTokenFromConnectionParams(connectionParams)\n return Promise.resolve(new User(claims, accessToken ?? ''))\n}\n"],"names":["randomUUID","pick","extractTokenFromConnectionParams","User"],"mappings":";;;;;;;MA2Ba,gCAAgC,GAAG,CAAmD,EACjG,aAAa,EACb,kBAAkB,EAClB,WAAW,EACX,UAAU,GAAG,iBAAiB,EAC9B,gBAAgB,EAChB,cAAc,GAC4B,KAAyC;;AAEnF,IAAA,OAAO,OAAO,KAA+B,KAAI;QAC/C,MAAM,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,KAAK,CAAA;QAE7C,MAAM,aAAa,GAAG,GAAG,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAA;QACpD,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,GAAG,aAAa,IAAI,GAAG,CAAC,OAAO,CAAC,IAAI,CAAA;;AAGhG,QAAA,MAAM,WAAW,GAAgB;AAC/B,YAAA,SAAS,EAAE,GAAG,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,QAAQ,EAAE,IAAIA,iBAAU,EAAE;AAClE,YAAA,QAAQ,EAAE,IAAI;YACd,IAAI,EAAE,IAAI,IAAI,EAAE;AAChB,YAAA,MAAM,EAAE,GAAG,CAAC,MAAM,IAAI,EAAE;AACxB,YAAA,GAAG,EAAE,GAAG,CAAC,GAAG,IAAI,EAAE;YAClB,MAAM,EAAE,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,EAAE;YACnC,OAAO,EAAE,GAAG,CAAC,OA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AM,iBAAiB,GAA6C,CAAC,EAAE,MAAM,EAAE,gBAAgB,EAAE,KAAI;AACnG,IAAA,IAAI,CAAC,MAAM;AAAE,QAAA,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAA;AAC9C,IAAA,MAAM,WAAW,GAAGC,sCAAgC,CAAC,gBAAgB,CAAC,CAAA;AACtE,IAAA,OAAO,OAAO,CAAC,OAAO,CAAC,IAAIC,SAAI,CAAC,MAAM,EAAE,WAAW,IAAI,EAAE,CAAC,CAAC,CAAA;AAC7D,CAAC;;;;"}
1
+ {"version":3,"file":"context.js","sources":["../../src/subscriptions/context.ts"],"sourcesContent":["import type { Logger } from '@makerx/node-common'\nimport { pick } from 'es-toolkit/compat'\nimport type { IncomingMessage } from 'http'\nimport { User } from '../User'\nimport type { CreateRequestLogger, GraphQLContext, JwtPayload, RequestInfo, RequestInfoLogKey } from '../context'\nimport { buildConnectRequestInfo } from '../request-info'\nimport { extractTokenFromConnectionParams } from './utils'\n\nexport interface SubscriptionContextInput {\n connectRequest: IncomingMessage\n connectionParams?: Readonly<Record<string, unknown>>\n claims?: JwtPayload\n}\n\nexport type CreateSubscriptionUser<T = User | undefined> = (input: SubscriptionContextInput) => Promise<T> | T\nexport type CreateSubscriptionContext<TContext = GraphQLContext> = (input: SubscriptionContextInput) => Promise<TContext>\nexport type AugmentSubscriptionRequestInfo = (input: SubscriptionContextInput) => Record<string, unknown>\n\n// `createUser` is optional when TUser is compatible with the default `User | undefined`\n// (i.e. defaultCreateUser can satisfy it), and required when TUser is narrower.\nexport type CreateSubscriptionContextConfig<\n TUser = User | undefined,\n TAugment extends Record<string, unknown> = Record<string, never>,\n TLogger extends Logger = Logger,\n> = {\n requestLogger: CreateRequestLogger<TUser, TLogger> | TLogger\n augmentRequestInfo?: AugmentSubscriptionRequestInfo\n claimsToLog?: string[]\n requestInfoToLog?: Array<RequestInfoLogKey>\n augmentContext?: (context: GraphQLContext<TLogger, RequestInfo, TUser>) => TAugment | Promise<TAugment>\n} & ([User | undefined] extends [TUser] ? { createUser?: CreateSubscriptionUser<TUser> } : { createUser: CreateSubscriptionUser<TUser> })\n\nexport const createSubscriptionContextFactory = <\n TUser = User | undefined,\n TAugment extends Record<string, unknown> = Record<string, never>,\n TLogger extends Logger = Logger,\n>(\n config: CreateSubscriptionContextConfig<TUser, TAugment, TLogger>,\n): CreateSubscriptionContext<GraphQLContext<TLogger, RequestInfo, TUser> & TAugment> => {\n const { requestLogger, augmentRequestInfo, claimsToLog, requestInfoToLog, augmentContext } = config\n // The conditional type on CreateSubscriptionContextConfig guarantees `createUser` is provided\n // when TUser is narrower than `User | undefined`, so defaulting is sound here.\n const createUser = (config.createUser ?? defaultCreateUser) as CreateSubscriptionUser<TUser>\n\n return async (input: SubscriptionContextInput) => {\n const { connectRequest: req, claims } = input\n\n // build request info from the connect request and socket\n const requestInfo: RequestInfo = {\n ...buildConnectRequestInfo(req),\n ...augmentRequestInfo?.(input),\n }\n\n const user = await createUser(input)\n\n // create request logger\n let logger: TLogger\n if (typeof requestLogger === 'function') {\n // build request logger metadata\n const requestLoggerMetadata: Record<string, unknown> = {}\n // add request info to log\n if (requestInfoToLog?.length) requestLoggerMetadata.request = pick(requestInfo, requestInfoToLog)\n // add user claims to log\n if (claims && claimsToLog?.length) requestLoggerMetadata.user = pick(claims, claimsToLog)\n // build the request logger\n logger = requestLogger(requestLoggerMetadata, user)\n } else logger = requestLogger\n\n const graphqlContext: GraphQLContext<TLogger, RequestInfo, TUser> = {\n requestInfo,\n logger,\n user,\n started: Date.now(),\n }\n\n const augmentedGraphQLContext = augmentContext ? { ...graphqlContext, ...(await augmentContext(graphqlContext)) } : graphqlContext\n\n return augmentedGraphQLContext as GraphQLContext<TLogger, RequestInfo, TUser> & TAugment\n }\n}\n\nconst defaultCreateUser: CreateSubscriptionUser<User | undefined> = ({ claims, connectionParams }) => {\n if (!claims) return Promise.resolve(undefined)\n const accessToken = extractTokenFromConnectionParams(connectionParams)\n return Promise.resolve(new User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,cAAc,CAAC,cAAc,CAAC,CAAC,EAAE,GAAG,cAAc;AAElI,QAAA,OAAO,uBAAiF;AAC1F,IAAA,CAAC;AACH;AAEA,MAAM,iBAAiB,GAA6C,CAAC,EAAE,MAAM,EAAE,gBAAgB,EAAE,KAAI;AACnG,IAAA,IAAI,CAAC,MAAM;AAAE,QAAA,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC;AAC9C,IAAA,MAAM,WAAW,GAAGG,sCAAgC,CAAC,gBAAgB,CAAC;AACtE,IAAA,OAAO,OAAO,CAAC,OAAO,CAAC,IAAIC,SAAI,CAAC,MAAM,EAAE,WAAW,IAAI,EAAE,CAAC,CAAC;AAC7D,CAAC;;;;"}
@@ -1,28 +1,21 @@
1
- import { randomUUID } from 'crypto';
2
- import { pick } from 'lodash';
1
+ import { pick } from 'es-toolkit/compat';
3
2
  import { User } from '../User.mjs';
3
+ import { buildConnectRequestInfo } from '../request-info.mjs';
4
4
  import { extractTokenFromConnectionParams } from './utils.mjs';
5
5
 
6
- const createSubscriptionContextFactory = ({ requestLogger, augmentRequestInfo, claimsToLog, createUser = defaultCreateUser, requestInfoToLog, augmentContext, }) => {
7
- // the function that creates the GraphQL context
6
+ const createSubscriptionContextFactory = (config) => {
7
+ const { requestLogger, augmentRequestInfo, claimsToLog, requestInfoToLog, augmentContext } = config;
8
+ // The conditional type on CreateSubscriptionContextConfig guarantees `createUser` is provided
9
+ // when TUser is narrower than `User | undefined`, so defaulting is sound here.
10
+ const createUser = (config.createUser ?? defaultCreateUser);
8
11
  return async (input) => {
9
12
  const { connectRequest: req, claims } = input;
10
- const xForwardedFor = req.headers['x-forwarded-for'];
11
- const host = Array.isArray(xForwardedFor) ? xForwardedFor[0] : xForwardedFor ?? req.headers.host;
12
13
  // build request info from the connect request and socket
13
14
  const requestInfo = {
14
- requestId: req.headers['x-request-id']?.toString() ?? randomUUID(),
15
- protocol: 'ws',
16
- host: host ?? '',
17
- method: req.method ?? '',
18
- url: req.url ?? '',
19
- origin: req.headers['origin'] ?? '',
20
- referer: req.headers.referer?.toString() ?? '',
21
- arrLogId: req.headers['x-arr-log-id']?.toString() ?? undefined,
22
- clientIp: req.headers['x-forwarded-for']?.toString() ?? req.socket.remoteAddress,
23
- correlationId: req.headers['x-correlation-id']?.toString() ?? undefined,
15
+ ...buildConnectRequestInfo(req),
24
16
  ...augmentRequestInfo?.(input),
25
17
  };
18
+ const user = await createUser(input);
26
19
  // create request logger
27
20
  let logger;
28
21
  if (typeof requestLogger === 'function') {
@@ -35,19 +28,17 @@ const createSubscriptionContextFactory = ({ requestLogger, augmentRequestInfo, c
35
28
  if (claims && claimsToLog?.length)
36
29
  requestLoggerMetadata.user = pick(claims, claimsToLog);
37
30
  // build the request logger
38
- logger = requestLogger(requestLoggerMetadata);
31
+ logger = requestLogger(requestLoggerMetadata, user);
39
32
  }
40
33
  else
41
34
  logger = requestLogger;
42
35
  const graphqlContext = {
43
36
  requestInfo,
44
37
  logger,
45
- user: await createUser(input),
38
+ user,
46
39
  started: Date.now(),
47
40
  };
48
- const augmentedGraphQLContext = augmentContext
49
- ? { ...graphqlContext, ...(await augmentContext(graphqlContext)) }
50
- : graphqlContext;
41
+ const augmentedGraphQLContext = augmentContext ? { ...graphqlContext, ...(await augmentContext(graphqlContext)) } : graphqlContext;
51
42
  return augmentedGraphQLContext;
52
43
  };
53
44
  };
@@ -1 +1 @@
1
- {"version":3,"file":"context.mjs","sources":["../../src/subscriptions/context.ts"],"sourcesContent":["import type { Logger } from '@makerx/node-common'\nimport { randomUUID } from 'crypto'\nimport type { IncomingMessage } from 'http'\nimport { pick } from 'lodash'\nimport { User } from '../User'\nimport type { CreateRequestLogger, GraphQLContext, JwtPayload, RequestInfo } from '../context'\nimport { extractTokenFromConnectionParams } from './utils'\n\nexport interface SubscriptionContextInput {\n connectRequest: IncomingMessage\n connectionParams?: Readonly<Record<string, unknown>>\n claims?: JwtPayload\n}\n\nexport type CreateSubscriptionUser<T = User | undefined> = (input: SubscriptionContextInput) => Promise<T>\nexport type CreateSubscriptionContext<TContext = GraphQLContext> = (input: SubscriptionContextInput) => Promise<TContext>\nexport type AugmentSubscriptionRequestInfo = (input: SubscriptionContextInput) => Record<string, unknown>\n\nexport interface CreateSubscriptionContextConfig<TContext = GraphQLContext> {\n requestLogger: CreateRequestLogger | Logger\n augmentRequestInfo?: AugmentSubscriptionRequestInfo\n claimsToLog?: string[]\n createUser?: CreateSubscriptionUser\n requestInfoToLog?: Array<keyof RequestInfo>\n augmentContext?: (context: TContext) => Record<string, unknown> | Promise<Record<string, unknown>>\n}\n\nexport const createSubscriptionContextFactory = <TContext extends GraphQLContext = GraphQLContext>({\n requestLogger,\n augmentRequestInfo,\n claimsToLog,\n createUser = defaultCreateUser,\n requestInfoToLog,\n augmentContext,\n}: CreateSubscriptionContextConfig<TContext>): CreateSubscriptionContext<TContext> => {\n // the function that creates the GraphQL context\n return async (input: SubscriptionContextInput) => {\n const { connectRequest: req, claims } = input\n\n const xForwardedFor = req.headers['x-forwarded-for']\n const host = Array.isArray(xForwardedFor) ? xForwardedFor[0] : xForwardedFor ?? req.headers.host\n\n // build request info from the connect request and socket\n const requestInfo: RequestInfo = {\n requestId: req.headers['x-request-id']?.toString() ?? randomUUID(),\n protocol: 'ws',\n host: host ?? '',\n method: req.method ?? '',\n url: req.url ?? '',\n origin: req.headers['origin'] ?? '',\n referer: req.headers.referer?.toString() ?? '',\n arrLogId: req.headers['x-arr-log-id']?.toString() ?? undefined,\n clientIp: req.headers['x-forwarded-for']?.toString() ?? req.socket.remoteAddress,\n correlationId: req.headers['x-correlation-id']?.toString() ?? undefined,\n ...augmentRequestInfo?.(input),\n }\n\n // create request logger\n let logger: Logger\n if (typeof requestLogger === 'function') {\n // build request logger metadata\n const requestLoggerMetadata: Record<string, unknown> = {}\n // add request info to log\n if (requestInfoToLog?.length) requestLoggerMetadata.request = pick(requestInfo, requestInfoToLog)\n // add user claims to log\n if (claims && claimsToLog?.length) requestLoggerMetadata.user = pick(claims, claimsToLog)\n // build the request logger\n logger = requestLogger(requestLoggerMetadata)\n } else logger = requestLogger\n\n const graphqlContext: GraphQLContext = {\n requestInfo,\n logger,\n user: await createUser(input),\n started: Date.now(),\n }\n\n const augmentedGraphQLContext = augmentContext\n ? { ...graphqlContext, ...(await augmentContext(graphqlContext as TContext)) }\n : graphqlContext\n\n return augmentedGraphQLContext as TContext\n }\n}\n\nconst defaultCreateUser: CreateSubscriptionUser<User | undefined> = ({ claims, connectionParams }) => {\n if (!claims) return Promise.resolve(undefined)\n const accessToken = extractTokenFromConnectionParams(connectionParams)\n return Promise.resolve(new User(claims, accessToken ?? ''))\n}\n"],"names":[],"mappings":";;;;;MA2Ba,gCAAgC,GAAG,CAAmD,EACjG,aAAa,EACb,kBAAkB,EAClB,WAAW,EACX,UAAU,GAAG,iBAAiB,EAC9B,gBAAgB,EAChB,cAAc,GAC4B,KAAyC;;AAEnF,IAAA,OAAO,OAAO,KAA+B,KAAI;QAC/C,MAAM,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,KAAK,CAAA;QAE7C,MAAM,aAAa,GAAG,GAAG,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAA;QACpD,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,GAAG,aAAa,IAAI,GAAG,CAAC,OAAO,CAAC,IAAI,CAAA;;AAGhG,QAAA,MAAM,WAAW,GAAgB;AAC/B,YAAA,SAAS,EAAE,GAAG,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,QAAQ,EAAE,IAAI,UAAU,EAAE;AAClE,YAAA,QAAQ,EAAE,IAAI;YACd,IAAI,EAAE,IAAI,IAAI,EAAE;AAChB,YAAA,MAAM,EAAE,GAAG,CAAC,MAAM,IAAI,EAAE;AACxB,YAAA,GAAG,EAAE,GAAG,CAAC,GAAG,IAAI,EAAE;YAClB,MAAM,EAAE,GAAG,CAAC,OAAO,CAAC,QAA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uBAAmC,CAAA;AAC5C,KAAC,CAAA;AACH,EAAC;AAED,MAAM,iBAAiB,GAA6C,CAAC,EAAE,MAAM,EAAE,gBAAgB,EAAE,KAAI;AACnG,IAAA,IAAI,CAAC,MAAM;AAAE,QAAA,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAA;AAC9C,IAAA,MAAM,WAAW,GAAG,gCAAgC,CAAC,gBAAgB,CAAC,CAAA;AACtE,IAAA,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC,MAAM,EAAE,WAAW,IAAI,EAAE,CAAC,CAAC,CAAA;AAC7D,CAAC;;;;"}
1
+ {"version":3,"file":"context.mjs","sources":["../../src/subscriptions/context.ts"],"sourcesContent":["import type { Logger } from '@makerx/node-common'\nimport { pick } from 'es-toolkit/compat'\nimport type { IncomingMessage } from 'http'\nimport { User } from '../User'\nimport type { CreateRequestLogger, GraphQLContext, JwtPayload, RequestInfo, RequestInfoLogKey } from '../context'\nimport { buildConnectRequestInfo } from '../request-info'\nimport { extractTokenFromConnectionParams } from './utils'\n\nexport interface SubscriptionContextInput {\n connectRequest: IncomingMessage\n connectionParams?: Readonly<Record<string, unknown>>\n claims?: JwtPayload\n}\n\nexport type CreateSubscriptionUser<T = User | undefined> = (input: SubscriptionContextInput) => Promise<T> | T\nexport type CreateSubscriptionContext<TContext = GraphQLContext> = (input: SubscriptionContextInput) => Promise<TContext>\nexport type AugmentSubscriptionRequestInfo = (input: SubscriptionContextInput) => Record<string, unknown>\n\n// `createUser` is optional when TUser is compatible with the default `User | undefined`\n// (i.e. defaultCreateUser can satisfy it), and required when TUser is narrower.\nexport type CreateSubscriptionContextConfig<\n TUser = User | undefined,\n TAugment extends Record<string, unknown> = Record<string, never>,\n TLogger extends Logger = Logger,\n> = {\n requestLogger: CreateRequestLogger<TUser, TLogger> | TLogger\n augmentRequestInfo?: AugmentSubscriptionRequestInfo\n claimsToLog?: string[]\n requestInfoToLog?: Array<RequestInfoLogKey>\n augmentContext?: (context: GraphQLContext<TLogger, RequestInfo, TUser>) => TAugment | Promise<TAugment>\n} & ([User | undefined] extends [TUser] ? { createUser?: CreateSubscriptionUser<TUser> } : { createUser: CreateSubscriptionUser<TUser> })\n\nexport const createSubscriptionContextFactory = <\n TUser = User | undefined,\n TAugment extends Record<string, unknown> = Record<string, never>,\n TLogger extends Logger = Logger,\n>(\n config: CreateSubscriptionContextConfig<TUser, TAugment, TLogger>,\n): CreateSubscriptionContext<GraphQLContext<TLogger, RequestInfo, TUser> & TAugment> => {\n const { requestLogger, augmentRequestInfo, claimsToLog, requestInfoToLog, augmentContext } = config\n // The conditional type on CreateSubscriptionContextConfig guarantees `createUser` is provided\n // when TUser is narrower than `User | undefined`, so defaulting is sound here.\n const createUser = (config.createUser ?? defaultCreateUser) as CreateSubscriptionUser<TUser>\n\n return async (input: SubscriptionContextInput) => {\n const { connectRequest: req, claims } = input\n\n // build request info from the connect request and socket\n const requestInfo: RequestInfo = {\n ...buildConnectRequestInfo(req),\n ...augmentRequestInfo?.(input),\n }\n\n const user = await createUser(input)\n\n // create request logger\n let logger: TLogger\n if (typeof requestLogger === 'function') {\n // build request logger metadata\n const requestLoggerMetadata: Record<string, unknown> = {}\n // add request info to log\n if (requestInfoToLog?.length) requestLoggerMetadata.request = pick(requestInfo, requestInfoToLog)\n // add user claims to log\n if (claims && claimsToLog?.length) requestLoggerMetadata.user = pick(claims, claimsToLog)\n // build the request logger\n logger = requestLogger(requestLoggerMetadata, user)\n } else logger = requestLogger\n\n const graphqlContext: GraphQLContext<TLogger, RequestInfo, TUser> = {\n requestInfo,\n logger,\n user,\n started: Date.now(),\n }\n\n const augmentedGraphQLContext = augmentContext ? { ...graphqlContext, ...(await augmentContext(graphqlContext)) } : graphqlContext\n\n return augmentedGraphQLContext as GraphQLContext<TLogger, RequestInfo, TUser> & TAugment\n }\n}\n\nconst defaultCreateUser: CreateSubscriptionUser<User | undefined> = ({ claims, connectionParams }) => {\n if (!claims) return Promise.resolve(undefined)\n const accessToken = extractTokenFromConnectionParams(connectionParams)\n return Promise.resolve(new User(claims, accessToken ?? ''))\n}\n"],"names":[],"mappings":";;;;;AAgCO,MAAM,gCAAgC,GAAG,CAK9C,MAAiE,KACoB;AACrF,IAAA,MAAM,EAAE,aAAa,EAAE,kBAAkB,EAAE,WAAW,EAAE,gBAAgB,EAAE,cAAc,EAAE,GAAG,MAAM;;;IAGnG,MAAM,UAAU,IAAI,MAAM,CAAC,UAAU,IAAI,iBAAiB,CAAkC;AAE5F,IAAA,OAAO,OAAO,KAA+B,KAAI;QAC/C,MAAM,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,KAAK;;AAG7C,QAAA,MAAM,WAAW,GAAgB;YAC/B,GAAG,uBAAuB,CAAC,GAAG,CAAC;AAC/B,YAAA,GAAG,kBAAkB,GAAG,KAAK,CAAC;SAC/B;AAED,QAAA,MAAM,IAAI,GAAG,MAAM,UAAU,CAAC,KAAK,CAAC;;AAGpC,QAAA,IAAI,MAAe;AACnB,QAAA,IAAI,OAAO,aAAa,KAAK,UAAU,EAAE;;YAEvC,MAAM,qBAAqB,GAA4B,EAAE;;YAEzD,IAAI,gBAAgB,EAAE,MAAM;gBAAE,qBAAqB,CAAC,OAAO,GAAG,IAAI,CAAC,WAAW,EAAE,gBAAgB,CAAC;;AAEjG,YAAA,IAAI,MAAM,IAAI,WAAW,EAAE,MAAM;gBAAE,qBAAqB,CAAC,IAAI,GAAG,IAAI,CAAC,MAAM,EAAE,WAAW,CAAC;;AAEzF,YAAA,MAAM,GAAG,aAAa,CAAC,qBAAqB,EAAE,IAAI,CAAC;QACrD;;YAAO,MAAM,GAAG,aAAa;AAE7B,QAAA,MAAM,cAAc,GAAgD;YAClE,WAAW;YACX,MAAM;YACN,IAAI;AACJ,YAAA,OAAO,EAAE,IAAI,CAAC,GAAG,EAAE;SACpB;QAED,MAAM,uBAAuB,GAAG,cAAc,GAAG,EAAE,GAAG,cAAc,EAAE,IAAI,MAAM,cAAc,CAAC,cAAc,CAAC,CAAC,EAAE,GAAG,cAAc;AAElI,QAAA,OAAO,uBAAiF;AAC1F,IAAA,CAAC;AACH;AAEA,MAAM,iBAAiB,GAA6C,CAAC,EAAE,MAAM,EAAE,gBAAgB,EAAE,KAAI;AACnG,IAAA,IAAI,CAAC,MAAM;AAAE,QAAA,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC;AAC9C,IAAA,MAAM,WAAW,GAAG,gCAAgC,CAAC,gBAAgB,CAAC;AACtE,IAAA,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC,MAAM,EAAE,WAAW,IAAI,EAAE,CAAC,CAAC;AAC7D,CAAC;;;;"}
@@ -1,10 +1,9 @@
1
- /// <reference types="node" />
2
1
  import type { Logger } from '@makerx/node-common';
3
2
  import type { GraphQLSchema } from 'graphql';
4
3
  import type { Server } from 'http';
5
- import type { JwtPayload } from '../context';
4
+ import type { GraphQLContext, JwtPayload } from '../context';
6
5
  import type { CreateSubscriptionContext } from './context';
7
- export declare function useSubscriptionsServer<TLogger extends Logger = Logger>({ schema, httpServer, createSubscriptionContext, logger, operationLogLevel, path, verifyToken, requireAuth, jwtClaimsToLog, }: {
6
+ export declare function useSubscriptionsServer<TLogger extends Logger = Logger>({ schema, httpServer, createSubscriptionContext, logger, operationLogLevel, path, verifyToken, requireAuth, jwtClaimsToLog, resolveSubscriptionOperationLogger, }: {
8
7
  schema: GraphQLSchema;
9
8
  httpServer: Server;
10
9
  createSubscriptionContext: CreateSubscriptionContext;
@@ -14,4 +13,5 @@ export declare function useSubscriptionsServer<TLogger extends Logger = Logger>(
14
13
  verifyToken?: (host: string, token: string) => Promise<JwtPayload>;
15
14
  requireAuth?: boolean;
16
15
  jwtClaimsToLog?: string[];
16
+ resolveSubscriptionOperationLogger?: (context: GraphQLContext) => TLogger;
17
17
  }): import("graphql-ws").Disposable;
@@ -2,12 +2,12 @@
2
2
 
3
3
  var graphqlWs = require('graphql-ws');
4
4
  var ws$1 = require('graphql-ws/lib/use/ws');
5
- var lodash = require('lodash');
5
+ var compat = require('es-toolkit/compat');
6
6
  var ws = require('ws');
7
7
  var logging = require('../logging.js');
8
8
  var utils = require('./utils.js');
9
9
 
10
- function useSubscriptionsServer({ schema, httpServer, createSubscriptionContext, logger, operationLogLevel = 'info', path = '/graphql', verifyToken, requireAuth, jwtClaimsToLog = ['oid', 'iss'], }) {
10
+ function useSubscriptionsServer({ schema, httpServer, createSubscriptionContext, logger, operationLogLevel = 'info', path = '/graphql', verifyToken, requireAuth, jwtClaimsToLog = ['oid', 'iss'], resolveSubscriptionOperationLogger, }) {
11
11
  if (requireAuth && !verifyToken)
12
12
  throw new Error('verifyToken must be supplied when requireAuth is true');
13
13
  const wsServer = new ws.WebSocketServer({
@@ -38,7 +38,7 @@ function useSubscriptionsServer({ schema, httpServer, createSubscriptionContext,
38
38
  const claims = await verifyToken(utils.getHost(ctx.extra.request), token);
39
39
  ctx.extra.claims = claims;
40
40
  logger.info(connectionEstablished, {
41
- claims: lodash.pick(claims, jwtClaimsToLog),
41
+ claims: compat.pick(claims, jwtClaimsToLog),
42
42
  });
43
43
  return true;
44
44
  }
@@ -62,12 +62,12 @@ function useSubscriptionsServer({ schema, httpServer, createSubscriptionContext,
62
62
  await verifyToken(utils.getHost(ctx.extra.request), token);
63
63
  }
64
64
  catch (error) {
65
- logger.warn('Subscription connection auth token is no longer valid', { claims: lodash.pick(ctx.extra.claims, jwtClaimsToLog), error });
65
+ logger.warn('Subscription connection auth token is no longer valid', { claims: compat.pick(ctx.extra.claims, jwtClaimsToLog), error });
66
66
  ctx.extra.socket.close(graphqlWs.CloseCode.Forbidden, 'Forbidden');
67
67
  }
68
68
  },
69
69
  onDisconnect({ extra: { claims } }) {
70
- logger.info('Subscription connection disconnected', { claims: lodash.pick(claims, jwtClaimsToLog) });
70
+ logger.info('Subscription connection disconnected', { claims: compat.pick(claims, jwtClaimsToLog) });
71
71
  },
72
72
  context: async (ctx) => {
73
73
  return createSubscriptionContext({
@@ -77,10 +77,10 @@ function useSubscriptionsServer({ schema, httpServer, createSubscriptionContext,
77
77
  });
78
78
  },
79
79
  onOperation(_ctx, _message, args) {
80
- logging.logSubscriptionOperation({ args, logLevel: operationLogLevel });
80
+ logging.logSubscriptionOperation({ args, logLevel: operationLogLevel, resolveLogger: resolveSubscriptionOperationLogger });
81
81
  },
82
82
  onNext(_ctx, _message, args, { data, ...result }) {
83
- logging.logSubscriptionOperation({ args, logLevel: operationLogLevel, result });
83
+ logging.logSubscriptionOperation({ args, logLevel: operationLogLevel, result, resolveLogger: resolveSubscriptionOperationLogger });
84
84
  },
85
85
  }, wsServer);
86
86
  }
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sources":["../../src/subscriptions/server.ts"],"sourcesContent":["import type { Logger } from '@makerx/node-common'\nimport type { GraphQLSchema } from 'graphql'\nimport { CloseCode } from 'graphql-ws'\nimport { useServer } from 'graphql-ws/lib/use/ws'\nimport type { Server } from 'http'\nimport { pick } from 'lodash'\nimport { WebSocketServer } from 'ws'\nimport type { JwtPayload } from '../context'\nimport { logSubscriptionOperation } from '../logging'\nimport type { CreateSubscriptionContext } from './context'\nimport { extractTokenFromConnectionParams, getHost } from './utils'\n\nexport function useSubscriptionsServer<TLogger extends Logger = Logger>({\n schema,\n httpServer,\n createSubscriptionContext,\n logger,\n operationLogLevel = 'info',\n path = '/graphql',\n verifyToken,\n requireAuth,\n jwtClaimsToLog = ['oid', 'iss'],\n}: {\n schema: GraphQLSchema\n httpServer: Server\n createSubscriptionContext: CreateSubscriptionContext\n logger: TLogger\n operationLogLevel?: keyof TLogger\n path?: string\n verifyToken?: (host: string, token: string) => Promise<JwtPayload>\n requireAuth?: boolean\n jwtClaimsToLog?: string[]\n}) {\n if (requireAuth && !verifyToken) throw new Error('verifyToken must be supplied when requireAuth is true')\n\n const wsServer = new WebSocketServer({\n server: httpServer,\n path,\n })\n\n return useServer(\n {\n schema,\n onError(_ctx, message, errors) {\n logger.error('GraphQL subscriptions server error', { message, errors })\n },\n onConnect: async (ctx) => {\n const connectionEstablished = 'Subscription connection established'\n if (!verifyToken) {\n logger.info(connectionEstablished)\n return true\n }\n\n const token = extractTokenFromConnectionParams(ctx.connectionParams)\n if (!token) {\n if (requireAuth) {\n logger.error('No authorization parameter was supplied via websocket connection params')\n return false\n }\n logger.info(connectionEstablished)\n return true\n }\n\n try {\n const claims = await verifyToken(getHost(ctx.extra.request), token)\n ctx.extra.claims = claims as unknown as undefined\n logger.info(connectionEstablished, {\n claims: pick(claims, jwtClaimsToLog),\n })\n return true\n } catch (error) {\n logger.error('Failed to verify subscription connection auth token', { error })\n return false\n }\n },\n onSubscribe: async (ctx) => {\n if (!verifyToken) return\n const token = extractTokenFromConnectionParams(ctx.connectionParams)\n if (!token) {\n if (requireAuth) {\n logger.error('No authorization parameter was supplied via websocket connection params')\n ctx.extra.socket.close(CloseCode.Forbidden, 'Forbidden')\n }\n return\n }\n try {\n await verifyToken(getHost(ctx.extra.request), token)\n } catch (error) {\n logger.warn('Subscription connection auth token is no longer valid', { claims: pick(ctx.extra.claims, jwtClaimsToLog), error })\n ctx.extra.socket.close(CloseCode.Forbidden, 'Forbidden')\n }\n },\n onDisconnect({ extra: { claims } }) {\n logger.info('Subscription connection disconnected', { claims: pick(claims, jwtClaimsToLog) })\n },\n context: async (ctx) => {\n return createSubscriptionContext({\n connectRequest: ctx.extra.request,\n connectionParams: ctx.connectionParams,\n claims: ctx.extra.claims as JwtPayload | undefined,\n })\n },\n onOperation(_ctx, _message, args) {\n logSubscriptionOperation({ args, logLevel: operationLogLevel })\n },\n onNext(_ctx, _message, args, { data, ...result }) {\n logSubscriptionOperation({ args, logLevel: operationLogLevel, result })\n },\n },\n wsServer,\n )\n}\n"],"names":["WebSocketServer","useServer","extractTokenFromConnectionParams","getHost","pick","CloseCode","logSubscriptionOperation"],"mappings":";;;;;;;;;AAYgB,SAAA,sBAAsB,CAAkC,EACtE,MAAM,EACN,UAAU,EACV,yBAAyB,EACz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AA;AAChC,YAAA,MAAM,CAAC,IAAI,CAAC,sCAAsC,EAAE,EAAE,MAAM,EAAED,WAAI,CAAC,MAAM,EAAE,cAAc,CAAC,EAAE,CAAC,CAAA;SAC9F;AACD,QAAA,OAAO,EAAE,OAAO,GAAG,KAAI;AACrB,YAAA,OAAO,yBAAyB,CAAC;AAC/B,gBAAA,cAAc,EAAE,GAAG,CAAC,KAAK,CAAC,OAAO;gBACjC,gBAAgB,EAAE,GAAG,CAAC,gBAAgB;AACtC,gBAAA,MAAM,EAAE,GAAG,CAAC,KAAK,CAAC,MAAgC;AACnD,aAAA,CAAC,CAAA;SACH;AACD,QAAA,WAAW,CAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAA;YAC9BE,gCAAwB,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,iBAAiB,EAAE,CAAC,CAAA;SAChE;AACD,QAAA,MAAM,CAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,GAAG,MAAM,EAAE,EAAA;YAC9CA,gCAAwB,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,EAAE,CAAC,CAAA;SACxE;KACF,EACD,QAAQ,CACT,CAAA;AACH;;;;"}
1
+ {"version":3,"file":"server.js","sources":["../../src/subscriptions/server.ts"],"sourcesContent":["import type { Logger } from '@makerx/node-common'\nimport type { GraphQLSchema } from 'graphql'\nimport { CloseCode } from 'graphql-ws'\nimport { useServer } from 'graphql-ws/lib/use/ws'\nimport type { Server } from 'http'\nimport { pick } from 'es-toolkit/compat'\nimport { WebSocketServer } from 'ws'\nimport type { GraphQLContext, JwtPayload } from '../context'\nimport { logSubscriptionOperation } from '../logging'\nimport type { CreateSubscriptionContext } from './context'\nimport { extractTokenFromConnectionParams, getHost } from './utils'\n\nexport function useSubscriptionsServer<TLogger extends Logger = Logger>({\n schema,\n httpServer,\n createSubscriptionContext,\n logger,\n operationLogLevel = 'info',\n path = '/graphql',\n verifyToken,\n requireAuth,\n jwtClaimsToLog = ['oid', 'iss'],\n resolveSubscriptionOperationLogger,\n}: {\n schema: GraphQLSchema\n httpServer: Server\n createSubscriptionContext: CreateSubscriptionContext\n logger: TLogger\n operationLogLevel?: keyof TLogger\n path?: string\n verifyToken?: (host: string, token: string) => Promise<JwtPayload>\n requireAuth?: boolean\n jwtClaimsToLog?: string[]\n resolveSubscriptionOperationLogger?: (context: GraphQLContext) => TLogger\n}) {\n if (requireAuth && !verifyToken) throw new Error('verifyToken must be supplied when requireAuth is true')\n\n const wsServer = new WebSocketServer({\n server: httpServer,\n path,\n })\n\n return useServer(\n {\n schema,\n onError(_ctx, message, errors) {\n logger.error('GraphQL subscriptions server error', { message, errors })\n },\n onConnect: async (ctx) => {\n const connectionEstablished = 'Subscription connection established'\n if (!verifyToken) {\n logger.info(connectionEstablished)\n return true\n }\n\n const token = extractTokenFromConnectionParams(ctx.connectionParams)\n if (!token) {\n if (requireAuth) {\n logger.error('No authorization parameter was supplied via websocket connection params')\n return false\n }\n logger.info(connectionEstablished)\n return true\n }\n\n try {\n const claims = await verifyToken(getHost(ctx.extra.request), token)\n ctx.extra.claims = claims as unknown as undefined\n logger.info(connectionEstablished, {\n claims: pick(claims, jwtClaimsToLog),\n })\n return true\n } catch (error) {\n logger.error('Failed to verify subscription connection auth token', { error })\n return false\n }\n },\n onSubscribe: async (ctx) => {\n if (!verifyToken) return\n const token = extractTokenFromConnectionParams(ctx.connectionParams)\n if (!token) {\n if (requireAuth) {\n logger.error('No authorization parameter was supplied via websocket connection params')\n ctx.extra.socket.close(CloseCode.Forbidden, 'Forbidden')\n }\n return\n }\n try {\n await verifyToken(getHost(ctx.extra.request), token)\n } catch (error) {\n logger.warn('Subscription connection auth token is no longer valid', { claims: pick(ctx.extra.claims, jwtClaimsToLog), error })\n ctx.extra.socket.close(CloseCode.Forbidden, 'Forbidden')\n }\n },\n onDisconnect({ extra: { claims } }) {\n logger.info('Subscription connection disconnected', { claims: pick(claims, jwtClaimsToLog) })\n },\n context: async (ctx) => {\n return createSubscriptionContext({\n connectRequest: ctx.extra.request,\n connectionParams: ctx.connectionParams,\n claims: ctx.extra.claims as JwtPayload | undefined,\n })\n },\n onOperation(_ctx, _message, args) {\n logSubscriptionOperation({ args, logLevel: operationLogLevel, resolveLogger: resolveSubscriptionOperationLogger })\n },\n onNext(_ctx, _message, args, { data, ...result }) {\n logSubscriptionOperation({ args, logLevel: operationLogLevel, result, resolveLogger: resolveSubscriptionOperationLogger })\n },\n },\n wsServer,\n )\n}\n"],"names":["WebSocketServer","useServer","extractTokenFromConnectionParams","getHost","pick","CloseCode","logSubscriptionOperation"],"mappings":";;;;;;;;;AAYM,SAAU,sBAAsB,CAAkC,EACtE,MAAM,EACN,UAAU,EACV,yBAAyB,EACzB,MAAM,EACN,iBAAiB,GAAG,MAAM,EAC1B,IAAI,GAAG,UAAU,EACjB,WAAW,EACX,WAAW,EACX,cAAc,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,EAC/B,kCAAkC,GAYnC,EAAA;IACC,IAAI,WAAW,IAAI,CAAC,WAAW;AAAE,QAAA,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC;AAEzG,IAAA,MAAM,QAAQ,GAAG,IAAIA,kBAAe,CAAC;AACnC,QAAA,MAAM,EAAE,UAAU;QAClB,IAAI;AACL,KAAA,CAAC;AAEF,IAAA,OAAOC,cAAS,CACd;QACE,MAAM;AACN,QAAA,OAAO,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,EAAA;YAC3B,MAAM,CAAC,KAAK,CAAC,oCAAoC,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;QACzE,CAAC;AACD,QAAA,SAAS,EAAE,OAAO,GAAG,KAAI;YACvB,MAAM,qBAAqB,GAAG,qCAAqC;YACnE,IAAI,CAAC,WAAW,EAAE;AAChB,gBAAA,MAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC;AAClC,gBAAA,OAAO,IAAI;YACb;YAEA,MAAM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
  import { CloseCode } from 'graphql-ws';
2
2
  import { useServer } from 'graphql-ws/lib/use/ws';
3
- import { pick } from 'lodash';
3
+ import { pick } from 'es-toolkit/compat';
4
4
  import { WebSocketServer } from 'ws';
5
5
  import { logSubscriptionOperation } from '../logging.mjs';
6
6
  import { extractTokenFromConnectionParams, getHost } from './utils.mjs';
7
7
 
8
- function useSubscriptionsServer({ schema, httpServer, createSubscriptionContext, logger, operationLogLevel = 'info', path = '/graphql', verifyToken, requireAuth, jwtClaimsToLog = ['oid', 'iss'], }) {
8
+ function useSubscriptionsServer({ schema, httpServer, createSubscriptionContext, logger, operationLogLevel = 'info', path = '/graphql', verifyToken, requireAuth, jwtClaimsToLog = ['oid', 'iss'], resolveSubscriptionOperationLogger, }) {
9
9
  if (requireAuth && !verifyToken)
10
10
  throw new Error('verifyToken must be supplied when requireAuth is true');
11
11
  const wsServer = new WebSocketServer({
@@ -75,10 +75,10 @@ function useSubscriptionsServer({ schema, httpServer, createSubscriptionContext,
75
75
  });
76
76
  },
77
77
  onOperation(_ctx, _message, args) {
78
- logSubscriptionOperation({ args, logLevel: operationLogLevel });
78
+ logSubscriptionOperation({ args, logLevel: operationLogLevel, resolveLogger: resolveSubscriptionOperationLogger });
79
79
  },
80
80
  onNext(_ctx, _message, args, { data, ...result }) {
81
- logSubscriptionOperation({ args, logLevel: operationLogLevel, result });
81
+ logSubscriptionOperation({ args, logLevel: operationLogLevel, result, resolveLogger: resolveSubscriptionOperationLogger });
82
82
  },
83
83
  }, wsServer);
84
84
  }
@@ -1 +1 @@
1
- {"version":3,"file":"server.mjs","sources":["../../src/subscriptions/server.ts"],"sourcesContent":["import type { Logger } from '@makerx/node-common'\nimport type { GraphQLSchema } from 'graphql'\nimport { CloseCode } from 'graphql-ws'\nimport { useServer } from 'graphql-ws/lib/use/ws'\nimport type { Server } from 'http'\nimport { pick } from 'lodash'\nimport { WebSocketServer } from 'ws'\nimport type { JwtPayload } from '../context'\nimport { logSubscriptionOperation } from '../logging'\nimport type { CreateSubscriptionContext } from './context'\nimport { extractTokenFromConnectionParams, getHost } from './utils'\n\nexport function useSubscriptionsServer<TLogger extends Logger = Logger>({\n schema,\n httpServer,\n createSubscriptionContext,\n logger,\n operationLogLevel = 'info',\n path = '/graphql',\n verifyToken,\n requireAuth,\n jwtClaimsToLog = ['oid', 'iss'],\n}: {\n schema: GraphQLSchema\n httpServer: Server\n createSubscriptionContext: CreateSubscriptionContext\n logger: TLogger\n operationLogLevel?: keyof TLogger\n path?: string\n verifyToken?: (host: string, token: string) => Promise<JwtPayload>\n requireAuth?: boolean\n jwtClaimsToLog?: string[]\n}) {\n if (requireAuth && !verifyToken) throw new Error('verifyToken must be supplied when requireAuth is true')\n\n const wsServer = new WebSocketServer({\n server: httpServer,\n path,\n })\n\n return useServer(\n {\n schema,\n onError(_ctx, message, errors) {\n logger.error('GraphQL subscriptions server error', { message, errors })\n },\n onConnect: async (ctx) => {\n const connectionEstablished = 'Subscription connection established'\n if (!verifyToken) {\n logger.info(connectionEstablished)\n return true\n }\n\n const token = extractTokenFromConnectionParams(ctx.connectionParams)\n if (!token) {\n if (requireAuth) {\n logger.error('No authorization parameter was supplied via websocket connection params')\n return false\n }\n logger.info(connectionEstablished)\n return true\n }\n\n try {\n const claims = await verifyToken(getHost(ctx.extra.request), token)\n ctx.extra.claims = claims as unknown as undefined\n logger.info(connectionEstablished, {\n claims: pick(claims, jwtClaimsToLog),\n })\n return true\n } catch (error) {\n logger.error('Failed to verify subscription connection auth token', { error })\n return false\n }\n },\n onSubscribe: async (ctx) => {\n if (!verifyToken) return\n const token = extractTokenFromConnectionParams(ctx.connectionParams)\n if (!token) {\n if (requireAuth) {\n logger.error('No authorization parameter was supplied via websocket connection params')\n ctx.extra.socket.close(CloseCode.Forbidden, 'Forbidden')\n }\n return\n }\n try {\n await verifyToken(getHost(ctx.extra.request), token)\n } catch (error) {\n logger.warn('Subscription connection auth token is no longer valid', { claims: pick(ctx.extra.claims, jwtClaimsToLog), error })\n ctx.extra.socket.close(CloseCode.Forbidden, 'Forbidden')\n }\n },\n onDisconnect({ extra: { claims } }) {\n logger.info('Subscription connection disconnected', { claims: pick(claims, jwtClaimsToLog) })\n },\n context: async (ctx) => {\n return createSubscriptionContext({\n connectRequest: ctx.extra.request,\n connectionParams: ctx.connectionParams,\n claims: ctx.extra.claims as JwtPayload | undefined,\n })\n },\n onOperation(_ctx, _message, args) {\n logSubscriptionOperation({ args, logLevel: operationLogLevel })\n },\n onNext(_ctx, _message, args, { data, ...result }) {\n logSubscriptionOperation({ args, logLevel: operationLogLevel, result })\n },\n },\n wsServer,\n )\n}\n"],"names":[],"mappings":";;;;;;;AAYgB,SAAA,sBAAsB,CAAkC,EACtE,MAAM,EACN,UAAU,EACV,yBAAyB,EACzB,MAAM,EACN,iBAAiB,GAAG,MAAM,EAC1B,IAAI,GAAG,UAAU,EACjB,WAAW,EACX,WAAW,EACX,cAAc,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,GAWhC,EAAA;IACC,IAAI,WAAW,IAAI,CAAC,WAAW;AAAE,QAAA,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAA;AAEzG,IAAA,MAAM,QAAQ,GAAG,IAAI,eAAe,CAAC;AACnC,QAAA,MAAM,EAAE,UAAU;QAClB,IAAI;AACL,KAAA,CAAC,CAAA;AAEF,IAAA,OAAO,SAAS,CACd;QACE,MAAM;AACN,QAAA,OAAO,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,EAAA;YAC3B,MAAM,CAAC,KAAK,CAAC,oCAAoC,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAA;SACxE;AACD,QAAA,SAAS,EAAE,OAAO,GAAG,KAAI;YACvB,MAAM,qBAAqB,GAAG,qCAAqC,CAAA;YACnE,IAAI,CAAC,WAAW,EAAE;AAChB,gBAAA,MAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAA;AAClC,gBAAA,OAAO,IAAI,CAAA;aACZ;YAED,MAAM,KAA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}
1
+ {"version":3,"file":"server.mjs","sources":["../../src/subscriptions/server.ts"],"sourcesContent":["import type { Logger } from '@makerx/node-common'\nimport type { GraphQLSchema } from 'graphql'\nimport { CloseCode } from 'graphql-ws'\nimport { useServer } from 'graphql-ws/lib/use/ws'\nimport type { Server } from 'http'\nimport { pick } from 'es-toolkit/compat'\nimport { WebSocketServer } from 'ws'\nimport type { GraphQLContext, JwtPayload } from '../context'\nimport { logSubscriptionOperation } from '../logging'\nimport type { CreateSubscriptionContext } from './context'\nimport { extractTokenFromConnectionParams, getHost } from './utils'\n\nexport function useSubscriptionsServer<TLogger extends Logger = Logger>({\n schema,\n httpServer,\n createSubscriptionContext,\n logger,\n operationLogLevel = 'info',\n path = '/graphql',\n verifyToken,\n requireAuth,\n jwtClaimsToLog = ['oid', 'iss'],\n resolveSubscriptionOperationLogger,\n}: {\n schema: GraphQLSchema\n httpServer: Server\n createSubscriptionContext: CreateSubscriptionContext\n logger: TLogger\n operationLogLevel?: keyof TLogger\n path?: string\n verifyToken?: (host: string, token: string) => Promise<JwtPayload>\n requireAuth?: boolean\n jwtClaimsToLog?: string[]\n resolveSubscriptionOperationLogger?: (context: GraphQLContext) => TLogger\n}) {\n if (requireAuth && !verifyToken) throw new Error('verifyToken must be supplied when requireAuth is true')\n\n const wsServer = new WebSocketServer({\n server: httpServer,\n path,\n })\n\n return useServer(\n {\n schema,\n onError(_ctx, message, errors) {\n logger.error('GraphQL subscriptions server error', { message, errors })\n },\n onConnect: async (ctx) => {\n const connectionEstablished = 'Subscription connection established'\n if (!verifyToken) {\n logger.info(connectionEstablished)\n return true\n }\n\n const token = extractTokenFromConnectionParams(ctx.connectionParams)\n if (!token) {\n if (requireAuth) {\n logger.error('No authorization parameter was supplied via websocket connection params')\n return false\n }\n logger.info(connectionEstablished)\n return true\n }\n\n try {\n const claims = await verifyToken(getHost(ctx.extra.request), token)\n ctx.extra.claims = claims as unknown as undefined\n logger.info(connectionEstablished, {\n claims: pick(claims, jwtClaimsToLog),\n })\n return true\n } catch (error) {\n logger.error('Failed to verify subscription connection auth token', { error })\n return false\n }\n },\n onSubscribe: async (ctx) => {\n if (!verifyToken) return\n const token = extractTokenFromConnectionParams(ctx.connectionParams)\n if (!token) {\n if (requireAuth) {\n logger.error('No authorization parameter was supplied via websocket connection params')\n ctx.extra.socket.close(CloseCode.Forbidden, 'Forbidden')\n }\n return\n }\n try {\n await verifyToken(getHost(ctx.extra.request), token)\n } catch (error) {\n logger.warn('Subscription connection auth token is no longer valid', { claims: pick(ctx.extra.claims, jwtClaimsToLog), error })\n ctx.extra.socket.close(CloseCode.Forbidden, 'Forbidden')\n }\n },\n onDisconnect({ extra: { claims } }) {\n logger.info('Subscription connection disconnected', { claims: pick(claims, jwtClaimsToLog) })\n },\n context: async (ctx) => {\n return createSubscriptionContext({\n connectRequest: ctx.extra.request,\n connectionParams: ctx.connectionParams,\n claims: ctx.extra.claims as JwtPayload | undefined,\n })\n },\n onOperation(_ctx, _message, args) {\n logSubscriptionOperation({ args, logLevel: operationLogLevel, resolveLogger: resolveSubscriptionOperationLogger })\n },\n onNext(_ctx, _message, args, { data, ...result }) {\n logSubscriptionOperation({ args, logLevel: operationLogLevel, result, resolveLogger: resolveSubscriptionOperationLogger })\n },\n },\n wsServer,\n )\n}\n"],"names":[],"mappings":";;;;;;;AAYM,SAAU,sBAAsB,CAAkC,EACtE,MAAM,EACN,UAAU,EACV,yBAAyB,EACzB,MAAM,EACN,iBAAiB,GAAG,MAAM,EAC1B,IAAI,GAAG,UAAU,EACjB,WAAW,EACX,WAAW,EACX,cAAc,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,EAC/B,kCAAkC,GAYnC,EAAA;IACC,IAAI,WAAW,IAAI,CAAC,WAAW;AAAE,QAAA,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC;AAEzG,IAAA,MAAM,QAAQ,GAAG,IAAI,eAAe,CAAC;AACnC,QAAA,MAAM,EAAE,UAAU;QAClB,IAAI;AACL,KAAA,CAAC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C,EAAE,IAAI,EAAE,QAAQ,EAAE,iBAAiB,EAAE,aAAa,EAAE,kCAAkC,EAAE,CAAC;QACpH,CAAC;AACD,QAAA,MAAM,CAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,GAAG,MAAM,EAAE,EAAA;AAC9C,YAAA,wBAAwB,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,EAAE,aAAa,EAAE,kCAAkC,EAAE,CAAC;QAC5H,CAAC;KACF,EACD,QAAQ,CACT;AACH;;;;"}
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import type { IncomingMessage } from 'http';
3
2
  /**
4
3
  * Extracts a token from a connection parameter named `authorization` or `Authorization`.
@@ -15,7 +15,7 @@ function extractTokenFromConnectionParams(connectionParams) {
15
15
  }
16
16
  function getHost(request) {
17
17
  const proxyHostHeader = request.headers['x-forwarded-host'];
18
- const host = Array.isArray(proxyHostHeader) ? proxyHostHeader[0] ?? undefined : proxyHostHeader ?? request.headers.host ?? undefined;
18
+ const host = Array.isArray(proxyHostHeader) ? (proxyHostHeader[0] ?? undefined) : (proxyHostHeader ?? request.headers.host ?? undefined);
19
19
  return host ?? 'subscriptions';
20
20
  }
21
21
 
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sources":["../../src/subscriptions/utils.ts"],"sourcesContent":["import type { IncomingMessage } from 'http'\n\n/**\n * Extracts a token from a connection parameter named `authorization` or `Authorization`.\n * The expected format of the parameter value is: Bearer <token>, consistent with an HTTP Authorization header.\n * Apollo Sandbox sets an `Authorization` connection parameter when you specify an HTTP Authorization header via the UI.\n * @param connectionParams\n * @returns\n */\nexport function extractTokenFromConnectionParams(connectionParams?: Readonly<Record<string, unknown>>) {\n const bearerTokenValue = (connectionParams?.authorization ?? connectionParams?.Authorization) as string | undefined\n if (!bearerTokenValue?.startsWith('Bearer ')) return undefined\n return bearerTokenValue.substring(7)\n}\n\nexport function getHost(request: IncomingMessage) {\n const proxyHostHeader = request.headers['x-forwarded-host']\n const host = Array.isArray(proxyHostHeader) ? proxyHostHeader[0] ?? undefined : proxyHostHeader ?? request.headers.host ?? undefined\n return host ?? 'subscriptions'\n}\n"],"names":[],"mappings":";;AAEA;;;;;;AAMG;AACG,SAAU,gCAAgC,CAAC,gBAAoD,EAAA;IACnG,MAAM,gBAAgB,IAAI,gBAAgB,EAAE,aAAa,IAAI,gBAAgB,EAAE,aAAa,CAAuB,CAAA;AACnH,IAAA,IAAI,CAAC,gBAAgB,EAAE,UAAU,CAAC,SAAS,CAAC;AAAE,QAAA,OAAO,SAAS,CAAA;AAC9D,IAAA,OAAO,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,CAAA;AACtC,CAAC;AAEK,SAAU,OAAO,CAAC,OAAwB,EAAA;IAC9C,MAAM,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAA;AAC3D,IAAA,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,eAAe,CAAC,CAAC,CAAC,IAAI,SAAS,GAAG,eAAe,IAAI,OAAO,CAAC,OAAO,CAAC,IAAI,IAAI,SAAS,CAAA;IACpI,OAAO,IAAI,IAAI,eAAe,CAAA;AAChC;;;;;"}
1
+ {"version":3,"file":"utils.js","sources":["../../src/subscriptions/utils.ts"],"sourcesContent":["import type { IncomingMessage } from 'http'\n\n/**\n * Extracts a token from a connection parameter named `authorization` or `Authorization`.\n * The expected format of the parameter value is: Bearer <token>, consistent with an HTTP Authorization header.\n * Apollo Sandbox sets an `Authorization` connection parameter when you specify an HTTP Authorization header via the UI.\n * @param connectionParams\n * @returns\n */\nexport function extractTokenFromConnectionParams(connectionParams?: Readonly<Record<string, unknown>>) {\n const bearerTokenValue = (connectionParams?.authorization ?? connectionParams?.Authorization) as string | undefined\n if (!bearerTokenValue?.startsWith('Bearer ')) return undefined\n return bearerTokenValue.substring(7)\n}\n\nexport function getHost(request: IncomingMessage) {\n const proxyHostHeader = request.headers['x-forwarded-host']\n const host = Array.isArray(proxyHostHeader) ? (proxyHostHeader[0] ?? undefined) : (proxyHostHeader ?? request.headers.host ?? undefined)\n return host ?? 'subscriptions'\n}\n"],"names":[],"mappings":";;AAEA;;;;;;AAMG;AACG,SAAU,gCAAgC,CAAC,gBAAoD,EAAA;IACnG,MAAM,gBAAgB,IAAI,gBAAgB,EAAE,aAAa,IAAI,gBAAgB,EAAE,aAAa,CAAuB;AACnH,IAAA,IAAI,CAAC,gBAAgB,EAAE,UAAU,CAAC,SAAS,CAAC;AAAE,QAAA,OAAO,SAAS;AAC9D,IAAA,OAAO,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC;AACtC;AAEM,SAAU,OAAO,CAAC,OAAwB,EAAA;IAC9C,MAAM,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,kBAAkB,CAAC;AAC3D,IAAA,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,eAAe,CAAC,IAAI,eAAe,CAAC,CAAC,CAAC,IAAI,SAAS,KAAK,eAAe,IAAI,OAAO,CAAC,OAAO,CAAC,IAAI,IAAI,SAAS,CAAC;IACxI,OAAO,IAAI,IAAI,eAAe;AAChC;;;;;"}
@@ -13,7 +13,7 @@ function extractTokenFromConnectionParams(connectionParams) {
13
13
  }
14
14
  function getHost(request) {
15
15
  const proxyHostHeader = request.headers['x-forwarded-host'];
16
- const host = Array.isArray(proxyHostHeader) ? proxyHostHeader[0] ?? undefined : proxyHostHeader ?? request.headers.host ?? undefined;
16
+ const host = Array.isArray(proxyHostHeader) ? (proxyHostHeader[0] ?? undefined) : (proxyHostHeader ?? request.headers.host ?? undefined);
17
17
  return host ?? 'subscriptions';
18
18
  }
19
19
 
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","sources":["../../src/subscriptions/utils.ts"],"sourcesContent":["import type { IncomingMessage } from 'http'\n\n/**\n * Extracts a token from a connection parameter named `authorization` or `Authorization`.\n * The expected format of the parameter value is: Bearer <token>, consistent with an HTTP Authorization header.\n * Apollo Sandbox sets an `Authorization` connection parameter when you specify an HTTP Authorization header via the UI.\n * @param connectionParams\n * @returns\n */\nexport function extractTokenFromConnectionParams(connectionParams?: Readonly<Record<string, unknown>>) {\n const bearerTokenValue = (connectionParams?.authorization ?? connectionParams?.Authorization) as string | undefined\n if (!bearerTokenValue?.startsWith('Bearer ')) return undefined\n return bearerTokenValue.substring(7)\n}\n\nexport function getHost(request: IncomingMessage) {\n const proxyHostHeader = request.headers['x-forwarded-host']\n const host = Array.isArray(proxyHostHeader) ? proxyHostHeader[0] ?? undefined : proxyHostHeader ?? request.headers.host ?? undefined\n return host ?? 'subscriptions'\n}\n"],"names":[],"mappings":"AAEA;;;;;;AAMG;AACG,SAAU,gCAAgC,CAAC,gBAAoD,EAAA;IACnG,MAAM,gBAAgB,IAAI,gBAAgB,EAAE,aAAa,IAAI,gBAAgB,EAAE,aAAa,CAAuB,CAAA;AACnH,IAAA,IAAI,CAAC,gBAAgB,EAAE,UAAU,CAAC,SAAS,CAAC;AAAE,QAAA,OAAO,SAAS,CAAA;AAC9D,IAAA,OAAO,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,CAAA;AACtC,CAAC;AAEK,SAAU,OAAO,CAAC,OAAwB,EAAA;IAC9C,MAAM,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAA;AAC3D,IAAA,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,eAAe,CAAC,CAAC,CAAC,IAAI,SAAS,GAAG,eAAe,IAAI,OAAO,CAAC,OAAO,CAAC,IAAI,IAAI,SAAS,CAAA;IACpI,OAAO,IAAI,IAAI,eAAe,CAAA;AAChC;;;;"}
1
+ {"version":3,"file":"utils.mjs","sources":["../../src/subscriptions/utils.ts"],"sourcesContent":["import type { IncomingMessage } from 'http'\n\n/**\n * Extracts a token from a connection parameter named `authorization` or `Authorization`.\n * The expected format of the parameter value is: Bearer <token>, consistent with an HTTP Authorization header.\n * Apollo Sandbox sets an `Authorization` connection parameter when you specify an HTTP Authorization header via the UI.\n * @param connectionParams\n * @returns\n */\nexport function extractTokenFromConnectionParams(connectionParams?: Readonly<Record<string, unknown>>) {\n const bearerTokenValue = (connectionParams?.authorization ?? connectionParams?.Authorization) as string | undefined\n if (!bearerTokenValue?.startsWith('Bearer ')) return undefined\n return bearerTokenValue.substring(7)\n}\n\nexport function getHost(request: IncomingMessage) {\n const proxyHostHeader = request.headers['x-forwarded-host']\n const host = Array.isArray(proxyHostHeader) ? (proxyHostHeader[0] ?? undefined) : (proxyHostHeader ?? request.headers.host ?? undefined)\n return host ?? 'subscriptions'\n}\n"],"names":[],"mappings":"AAEA;;;;;;AAMG;AACG,SAAU,gCAAgC,CAAC,gBAAoD,EAAA;IACnG,MAAM,gBAAgB,IAAI,gBAAgB,EAAE,aAAa,IAAI,gBAAgB,EAAE,aAAa,CAAuB;AACnH,IAAA,IAAI,CAAC,gBAAgB,EAAE,UAAU,CAAC,SAAS,CAAC;AAAE,QAAA,OAAO,SAAS;AAC9D,IAAA,OAAO,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC;AACtC;AAEM,SAAU,OAAO,CAAC,OAAwB,EAAA;IAC9C,MAAM,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,kBAAkB,CAAC;AAC3D,IAAA,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,eAAe,CAAC,IAAI,eAAe,CAAC,CAAC,CAAC,IAAI,SAAS,KAAK,eAAe,IAAI,OAAO,CAAC,OAAO,CAAC,IAAI,IAAI,SAAS,CAAC;IACxI,OAAO,IAAI,IAAI,eAAe;AAChC;;;;"}
package/utils.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export declare const isIntrospectionQuery: (query?: string) => boolean | undefined;
2
2
  export declare const isNil: (value: unknown) => value is null | undefined;
3
- export declare const isNotNil: <T>(value: T) => value is Exclude<T, null | undefined>;
3
+ export declare const isNotNil: <T>(value: T) => value is Exclude<T, undefined | null>;
package/utils.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sources":["../src/utils.ts"],"sourcesContent":["export const isIntrospectionQuery = (query?: string) => query?.includes('__schema')\nexport const isNil = (value: unknown): value is null | undefined => value === null || value === undefined\nexport const isNotNil = <T>(value: T): value is Exclude<T, undefined | null> => !isNil(value)\n"],"names":[],"mappings":";;AAAO,MAAM,oBAAoB,GAAG,CAAC,KAAc,KAAK,KAAK,EAAE,QAAQ,CAAC,UAAU,EAAC;AACtE,MAAA,KAAK,GAAG,CAAC,KAAc,KAAgC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,UAAS;AAClG,MAAM,QAAQ,GAAG,CAAI,KAAQ,KAA4C,CAAC,KAAK,CAAC,KAAK;;;;;;"}
1
+ {"version":3,"file":"utils.js","sources":["../src/utils.ts"],"sourcesContent":["export const isIntrospectionQuery = (query?: string) => query?.includes('__schema')\nexport const isNil = (value: unknown): value is null | undefined => value === null || value === undefined\nexport const isNotNil = <T>(value: T): value is Exclude<T, undefined | null> => !isNil(value)\n"],"names":[],"mappings":";;AAAO,MAAM,oBAAoB,GAAG,CAAC,KAAc,KAAK,KAAK,EAAE,QAAQ,CAAC,UAAU;AAC3E,MAAM,KAAK,GAAG,CAAC,KAAc,KAAgC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK;AACzF,MAAM,QAAQ,GAAG,CAAI,KAAQ,KAA4C,CAAC,KAAK,CAAC,KAAK;;;;;;"}
package/utils.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","sources":["../src/utils.ts"],"sourcesContent":["export const isIntrospectionQuery = (query?: string) => query?.includes('__schema')\nexport const isNil = (value: unknown): value is null | undefined => value === null || value === undefined\nexport const isNotNil = <T>(value: T): value is Exclude<T, undefined | null> => !isNil(value)\n"],"names":[],"mappings":"AAAO,MAAM,oBAAoB,GAAG,CAAC,KAAc,KAAK,KAAK,EAAE,QAAQ,CAAC,UAAU,EAAC;AACtE,MAAA,KAAK,GAAG,CAAC,KAAc,KAAgC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,UAAS;AAClG,MAAM,QAAQ,GAAG,CAAI,KAAQ,KAA4C,CAAC,KAAK,CAAC,KAAK;;;;"}
1
+ {"version":3,"file":"utils.mjs","sources":["../src/utils.ts"],"sourcesContent":["export const isIntrospectionQuery = (query?: string) => query?.includes('__schema')\nexport const isNil = (value: unknown): value is null | undefined => value === null || value === undefined\nexport const isNotNil = <T>(value: T): value is Exclude<T, undefined | null> => !isNil(value)\n"],"names":[],"mappings":"AAAO,MAAM,oBAAoB,GAAG,CAAC,KAAc,KAAK,KAAK,EAAE,QAAQ,CAAC,UAAU;AAC3E,MAAM,KAAK,GAAG,CAAC,KAAc,KAAgC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK;AACzF,MAAM,QAAQ,GAAG,CAAI,KAAQ,KAA4C,CAAC,KAAK,CAAC,KAAK;;;;"}
package/testing.d.ts DELETED
@@ -1,7 +0,0 @@
1
- import type { NormalizedCacheObject } from '@apollo/client/core';
2
- import { ApolloClient } from '@apollo/client/core';
3
- import type { ApolloClientOptions } from '@apollo/client/core/ApolloClient';
4
- import type { ClientCredentialsConfig } from '@makerx/node-common';
5
- export * from '@apollo/client/core';
6
- export declare const createTestClient: (url: string, accessToken?: string, options?: Partial<ApolloClientOptions<NormalizedCacheObject>>) => ApolloClient<NormalizedCacheObject>;
7
- export declare const createTestClientWithClientCredentials: (url: string, clientCredentialsConfig: ClientCredentialsConfig, options?: Partial<ApolloClientOptions<NormalizedCacheObject>>) => ApolloClient<NormalizedCacheObject>;
package/testing.js DELETED
@@ -1,68 +0,0 @@
1
- 'use strict';
2
-
3
- var core = require('@apollo/client/core');
4
- var context = require('@apollo/client/link/context');
5
- var nodeCommon = require('@makerx/node-common');
6
-
7
- const bearerTokenLink = (accessToken) => context.setContext((_, { headers }) => {
8
- if (accessToken)
9
- return {
10
- headers: {
11
- ...headers,
12
- authorization: `Bearer ${accessToken}`,
13
- },
14
- };
15
- return {
16
- headers,
17
- };
18
- });
19
- const clientCredentialsLink = (clientCredentialsConfig) => {
20
- let promise;
21
- return context.setContext(async () => {
22
- if (!promise)
23
- promise = nodeCommon.getClientCredentialsToken(clientCredentialsConfig);
24
- let tokenResponse = await promise;
25
- if (tokenResponse.isExpired) {
26
- promise = nodeCommon.getClientCredentialsToken(clientCredentialsConfig);
27
- tokenResponse = await promise;
28
- }
29
- return {
30
- headers: {
31
- authorization: `Bearer ${tokenResponse.access_token}`,
32
- },
33
- };
34
- });
35
- };
36
- const httpLink = (url) => core.createHttpLink({
37
- uri: url,
38
- });
39
- const createTestClient = (url, accessToken, options) => new core.ApolloClient({
40
- link: core.from([bearerTokenLink(accessToken), httpLink(url)]),
41
- cache: new core.InMemoryCache(),
42
- defaultOptions: {
43
- query: {
44
- errorPolicy: 'all',
45
- },
46
- },
47
- ...options,
48
- });
49
- const createTestClientWithClientCredentials = (url, clientCredentialsConfig, options) => new core.ApolloClient({
50
- link: core.from([clientCredentialsLink(clientCredentialsConfig), httpLink(url)]),
51
- cache: new core.InMemoryCache(),
52
- defaultOptions: {
53
- query: {
54
- errorPolicy: 'all',
55
- },
56
- },
57
- ...options,
58
- });
59
-
60
- exports.createTestClient = createTestClient;
61
- exports.createTestClientWithClientCredentials = createTestClientWithClientCredentials;
62
- Object.keys(core).forEach(function (k) {
63
- if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
64
- enumerable: true,
65
- get: function () { return core[k]; }
66
- });
67
- });
68
- //# sourceMappingURL=testing.js.map
package/testing.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"testing.js","sources":["../src/testing.ts"],"sourcesContent":["import type { NormalizedCacheObject } from '@apollo/client/core'\nimport { ApolloClient, createHttpLink, from, InMemoryCache } from '@apollo/client/core'\nimport type { ApolloClientOptions } from '@apollo/client/core/ApolloClient'\nimport { setContext } from '@apollo/client/link/context'\nimport type { AccessTokenResponse, ClientCredentialsConfig } from '@makerx/node-common'\nimport { getClientCredentialsToken } from '@makerx/node-common'\n\nexport * from '@apollo/client/core'\n\nconst bearerTokenLink = (accessToken?: string) =>\n setContext((_, { headers }) => {\n if (accessToken)\n return {\n headers: {\n ...headers,\n authorization: `Bearer ${accessToken}`,\n },\n }\n return {\n headers,\n }\n })\n\nconst clientCredentialsLink = (clientCredentialsConfig: ClientCredentialsConfig) => {\n let promise: Promise<AccessTokenResponse> | undefined\n return setContext(async () => {\n if (!promise) promise = getClientCredentialsToken(clientCredentialsConfig)\n let tokenResponse = await promise\n if (tokenResponse.isExpired) {\n promise = getClientCredentialsToken(clientCredentialsConfig)\n tokenResponse = await promise\n }\n return {\n headers: {\n authorization: `Bearer ${tokenResponse.access_token}`,\n },\n }\n })\n}\n\nconst httpLink = (url: string) =>\n createHttpLink({\n uri: url,\n })\n\nexport const createTestClient = (\n url: string,\n accessToken?: string,\n options?: Partial<ApolloClientOptions<NormalizedCacheObject>>,\n): ApolloClient<NormalizedCacheObject> =>\n new ApolloClient({\n link: from([bearerTokenLink(accessToken), httpLink(url)]),\n cache: new InMemoryCache(),\n defaultOptions: {\n query: {\n errorPolicy: 'all',\n },\n },\n ...options,\n })\n\nexport const createTestClientWithClientCredentials = (\n url: string,\n clientCredentialsConfig: ClientCredentialsConfig,\n options?: Partial<ApolloClientOptions<NormalizedCacheObject>>,\n): ApolloClient<NormalizedCacheObject> =>\n new ApolloClient({\n link: from([clientCredentialsLink(clientCredentialsConfig), httpLink(url)]),\n cache: new InMemoryCache(),\n defaultOptions: {\n query: {\n errorPolicy: 'all',\n },\n },\n ...options,\n })\n"],"names":["setContext","getClientCredentialsToken","createHttpLink","ApolloClient","from","InMemoryCache"],"mappings":";;;;;;AASA,MAAM,eAAe,GAAG,CAAC,WAAoB,KAC3CA,kBAAU,CAAC,CAAC,CAAC,EAAE,EAAE,OAAO,EAAE,KAAI;AAC5B,IAAA,IAAI,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,GAAG,OAAO;AACX,CAAA,EAAC;AAEG,MAAM,qCAAqC,GAAG,CACnD,GAAW,EACX,uBAAgD,EAChD,OAA6D,KAE7D,IAAIF,iBAAY,CAAC;AACf,IAAA,IAAI,EAAEC,SAAI,CAAC,CAAC,qBAAqB,CAAC,uBAAuB,CAAC,EAAE,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3E,KAAK,EAAE,IAAIC,kBAAa,EAAE;AAC1B,IAAA,cAAc,EAAE;AACd,QAAA,KAAK,EAAE;AACL,YAAA,WAAW,EAAE,KAAK;AACnB,SAAA;AACF,KAAA;AACD,IAAA,GAAG,OAAO;AACX,CAAA;;;;;;;;;;;"}
package/testing.mjs DELETED
@@ -1,60 +0,0 @@
1
- import { ApolloClient, from, InMemoryCache, createHttpLink } from '@apollo/client/core';
2
- export * from '@apollo/client/core';
3
- import { setContext } from '@apollo/client/link/context';
4
- import { getClientCredentialsToken } from '@makerx/node-common';
5
-
6
- const bearerTokenLink = (accessToken) => setContext((_, { headers }) => {
7
- if (accessToken)
8
- return {
9
- headers: {
10
- ...headers,
11
- authorization: `Bearer ${accessToken}`,
12
- },
13
- };
14
- return {
15
- headers,
16
- };
17
- });
18
- const clientCredentialsLink = (clientCredentialsConfig) => {
19
- let promise;
20
- return setContext(async () => {
21
- if (!promise)
22
- promise = getClientCredentialsToken(clientCredentialsConfig);
23
- let tokenResponse = await promise;
24
- if (tokenResponse.isExpired) {
25
- promise = getClientCredentialsToken(clientCredentialsConfig);
26
- tokenResponse = await promise;
27
- }
28
- return {
29
- headers: {
30
- authorization: `Bearer ${tokenResponse.access_token}`,
31
- },
32
- };
33
- });
34
- };
35
- const httpLink = (url) => createHttpLink({
36
- uri: url,
37
- });
38
- const createTestClient = (url, accessToken, options) => new ApolloClient({
39
- link: from([bearerTokenLink(accessToken), httpLink(url)]),
40
- cache: new InMemoryCache(),
41
- defaultOptions: {
42
- query: {
43
- errorPolicy: 'all',
44
- },
45
- },
46
- ...options,
47
- });
48
- const createTestClientWithClientCredentials = (url, clientCredentialsConfig, options) => new ApolloClient({
49
- link: from([clientCredentialsLink(clientCredentialsConfig), httpLink(url)]),
50
- cache: new InMemoryCache(),
51
- defaultOptions: {
52
- query: {
53
- errorPolicy: 'all',
54
- },
55
- },
56
- ...options,
57
- });
58
-
59
- export { createTestClient, createTestClientWithClientCredentials };
60
- //# sourceMappingURL=testing.mjs.map