@makerx/graphql-core 2.1.0 → 2.2.1

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 (77) hide show
  1. package/User.d.ts +1 -2
  2. package/User.js +7 -6
  3. package/User.js.map +1 -1
  4. package/User.mjs +48 -0
  5. package/User.mjs.map +1 -0
  6. package/context.d.ts +1 -2
  7. package/context.js +13 -15
  8. package/context.js.map +1 -1
  9. package/context.mjs +75 -0
  10. package/context.mjs.map +1 -0
  11. package/index.d.ts +0 -2
  12. package/index.js +24 -25
  13. package/index.js.map +1 -1
  14. package/index.mjs +7 -0
  15. package/index.mjs.map +1 -0
  16. package/logging.d.ts +4 -4
  17. package/logging.js +19 -21
  18. package/logging.js.map +1 -1
  19. package/logging.mjs +44 -0
  20. package/logging.mjs.map +1 -0
  21. package/models.d.ts +0 -1
  22. package/package.json +29 -11
  23. package/schema-util.d.ts +1 -2
  24. package/schema-util.js +7 -6
  25. package/schema-util.js.map +1 -1
  26. package/schema-util.mjs +29 -0
  27. package/schema-util.mjs.map +1 -0
  28. package/shield.d.ts +5 -5
  29. package/shield.js +11 -10
  30. package/shield.js.map +1 -1
  31. package/shield.mjs +49 -0
  32. package/shield.mjs.map +1 -0
  33. package/subscriptions/context.d.ts +1 -2
  34. package/subscriptions/context.js +15 -14
  35. package/subscriptions/context.js.map +1 -1
  36. package/subscriptions/context.mjs +62 -0
  37. package/subscriptions/context.mjs.map +1 -0
  38. package/subscriptions/index.d.ts +0 -1
  39. package/subscriptions/index.js +12 -22
  40. package/subscriptions/index.js.map +1 -1
  41. package/subscriptions/index.mjs +4 -0
  42. package/subscriptions/index.mjs.map +1 -0
  43. package/subscriptions/server.d.ts +4 -5
  44. package/subscriptions/server.js +24 -26
  45. package/subscriptions/server.js.map +1 -1
  46. package/subscriptions/server.mjs +87 -0
  47. package/subscriptions/server.mjs.map +1 -0
  48. package/subscriptions/utils.d.ts +0 -1
  49. package/subscriptions/utils.js +5 -5
  50. package/subscriptions/utils.js.map +1 -1
  51. package/subscriptions/utils.mjs +21 -0
  52. package/subscriptions/utils.mjs.map +1 -0
  53. package/testing.d.ts +6 -6
  54. package/testing.js +26 -35
  55. package/testing.js.map +1 -1
  56. package/testing.mjs +60 -0
  57. package/testing.mjs.map +1 -0
  58. package/utils.d.ts +0 -1
  59. package/utils.js +6 -6
  60. package/utils.js.map +1 -1
  61. package/utils.mjs +6 -0
  62. package/utils.mjs.map +1 -0
  63. package/User.d.ts.map +0 -1
  64. package/context.d.ts.map +0 -1
  65. package/index.d.ts.map +0 -1
  66. package/logging.d.ts.map +0 -1
  67. package/models.d.ts.map +0 -1
  68. package/models.js +0 -3
  69. package/models.js.map +0 -1
  70. package/schema-util.d.ts.map +0 -1
  71. package/shield.d.ts.map +0 -1
  72. package/subscriptions/context.d.ts.map +0 -1
  73. package/subscriptions/index.d.ts.map +0 -1
  74. package/subscriptions/server.d.ts.map +0 -1
  75. package/subscriptions/utils.d.ts.map +0 -1
  76. package/testing.d.ts.map +0 -1
  77. package/utils.d.ts.map +0 -1
package/package.json CHANGED
@@ -1,14 +1,16 @@
1
1
  {
2
- "main": "index.js",
3
- "types": "index.d.ts",
2
+ "scripts": {},
3
+ "files": [
4
+ "**"
5
+ ],
4
6
  "name": "@makerx/graphql-core",
5
- "version": "2.1.0",
7
+ "version": "2.2.1",
6
8
  "private": false,
7
9
  "description": "A set of core GraphQL utilities that MakerX uses to build GraphQL APIs",
8
10
  "author": "MakerX",
9
11
  "license": "MIT",
10
12
  "engines": {
11
- "node": ">=16.0"
13
+ "node": ">=20.0"
12
14
  },
13
15
  "bugs": {
14
16
  "url": "https://github.com/MakerXStudio/graphql-core/issues"
@@ -19,16 +21,15 @@
19
21
  "url": "git+https://github.com/MakerXStudio/graphql-core.git"
20
22
  },
21
23
  "dependencies": {
22
- "@makerx/node-common": "^1.2.0",
23
- "lodash.omitby": "^4.6.0",
24
- "lodash.pick": "^4.4.0"
24
+ "@makerx/node-common": "^1.4.0"
25
25
  },
26
26
  "peerDependencies": {
27
27
  "@apollo/client": "*",
28
28
  "express": "*",
29
+ "graphql": "*",
29
30
  "graphql-shield": "*",
30
31
  "graphql-ws": "*",
31
- "graphql": "*",
32
+ "lodash": "*",
32
33
  "ws": "*"
33
34
  },
34
35
  "peerDependenciesMeta": {
@@ -42,8 +43,25 @@
42
43
  "optional": true
43
44
  }
44
45
  },
45
- "overrides": {
46
- "@typescript-eslint/eslint-plugin": "^6.0.0",
47
- "@typescript-eslint/parser": "^6.0.0"
46
+ "main": "./index.js",
47
+ "module": "./index.mjs",
48
+ "types": "./index.d.ts",
49
+ "type": "module",
50
+ "exports": {
51
+ ".": {
52
+ "types": "./index.d.ts",
53
+ "import": "./index.mjs",
54
+ "require": "./index.js"
55
+ },
56
+ "./testing": {
57
+ "types": "./testing.d.ts",
58
+ "import": "./testing.mjs",
59
+ "require": "./testing.js"
60
+ },
61
+ "./subscriptions": {
62
+ "types": "./subscriptions/index.d.ts",
63
+ "import": "./subscriptions/index.mjs",
64
+ "require": "./subscriptions/index.js"
65
+ }
48
66
  }
49
67
  }
package/schema-util.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { GraphQLSchema } from 'graphql';
1
+ import type { GraphQLSchema } from 'graphql';
2
2
  /**
3
3
  * It is possible to register a custom scalar with apollo server without defining an explicit resolver (a default resolver is used in
4
4
  * this case), but it is rarely desirable. This function, when provided with your built schema, will ensure any registered scalar types
@@ -7,4 +7,3 @@ import { GraphQLSchema } from 'graphql';
7
7
  * @param schema A schema object, the result of calling `makeExecutableSchema` from `@graphql-tools/schema`
8
8
  */
9
9
  export declare function requireExplicitResolversForScalars(schema: GraphQLSchema, ...scalarsToIgnore: string[]): void;
10
- //# sourceMappingURL=schema-util.d.ts.map
package/schema-util.js CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.requireExplicitResolversForScalars = void 0;
4
- const graphql_1 = require("graphql");
1
+ 'use strict';
2
+
3
+ var graphql = require('graphql');
4
+
5
5
  /**
6
6
  * It is possible to register a custom scalar with apollo server without defining an explicit resolver (a default resolver is used in
7
7
  * this case), but it is rarely desirable. This function, when provided with your built schema, will ensure any registered scalar types
@@ -11,7 +11,7 @@ const graphql_1 = require("graphql");
11
11
  */
12
12
  function requireExplicitResolversForScalars(schema, ...scalarsToIgnore) {
13
13
  const testSymbol = Symbol('testSymbol');
14
- const scalars = Object.values(schema.getTypeMap()).filter((t) => t instanceof graphql_1.GraphQLScalarType);
14
+ const scalars = Object.values(schema.getTypeMap()).filter((t) => t instanceof graphql.GraphQLScalarType);
15
15
  for (const scalar of scalars) {
16
16
  if (scalar.name === 'Void' || scalar.name === 'JSON' || scalarsToIgnore.includes(scalar.name))
17
17
  continue;
@@ -26,5 +26,6 @@ function requireExplicitResolversForScalars(schema, ...scalarsToIgnore) {
26
26
  "If you're satisfied with this scalar you can ignore it in the call to `requireExplicitResolversForScalars`.");
27
27
  }
28
28
  }
29
+
29
30
  exports.requireExplicitResolversForScalars = requireExplicitResolversForScalars;
30
- //# sourceMappingURL=schema-util.js.map
31
+ //# sourceMappingURL=schema-util.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"schema-util.js","sourceRoot":"","sources":["../src/schema-util.ts"],"names":[],"mappings":";;;AAAA,qCAA0D;AAE1D;;;;;;GAMG;AACH,SAAgB,kCAAkC,CAAC,MAAqB,EAAE,GAAG,eAAyB;IACpG,MAAM,UAAU,GAAG,MAAM,CAAC,YAAY,CAAC,CAAA;IACvC,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAA0B,EAAE,CAAC,CAAC,YAAY,2BAAiB,CAAC,CAAA;IACxH,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;QAC5B,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM,IAAI,eAAe,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC;YAAE,SAAQ;QACvG,IAAI;YACF,MAAM,CAAC,UAAU,CAAC,UAAU,CAAC,CAAA;SAC9B;QAAC,MAAM;YACN,yEAAyE;YACzE,SAAQ;SACT;QACD,MAAM,IAAI,KAAK,CACb,UAAU,MAAM,CAAC,IAAI,gHAAgH;YACnI,6GAA6G,CAChH,CAAA;KACF;AACH,CAAC;AAhBD,gFAgBC"}
1
+ {"version":3,"file":"schema-util.js","sources":["../src/schema-util.ts"],"sourcesContent":["import type { GraphQLSchema } from 'graphql'\nimport { GraphQLScalarType } from 'graphql'\n\n/**\n * It is possible to register a custom scalar with apollo server without defining an explicit resolver (a default resolver is used in\n * this case), but it is rarely desirable. This function, when provided with your built schema, will ensure any registered scalar types\n * provide at least a base level of validation by failing to parse a Symbol instance. The default resolver does not pass this test\n * meaning any scalars that are falling back to the default resolver will fail.\n * @param schema A schema object, the result of calling `makeExecutableSchema` from `@graphql-tools/schema`\n */\nexport function requireExplicitResolversForScalars(schema: GraphQLSchema, ...scalarsToIgnore: string[]) {\n const testSymbol = Symbol('testSymbol')\n const scalars = Object.values(schema.getTypeMap()).filter((t): t is GraphQLScalarType => t instanceof GraphQLScalarType)\n for (const scalar of scalars) {\n if (scalar.name === 'Void' || scalar.name === 'JSON' || scalarsToIgnore.includes(scalar.name)) continue\n try {\n scalar.parseValue(testSymbol)\n } catch {\n // We expect that a good parser should throw when parsing a random symbol\n continue\n }\n throw new Error(\n `Scalar ${scalar.name} does not appear to have an explicit resolver, or is not performing sufficient validation when parsing input. ` +\n \"If you're satisfied with this scalar you can ignore it in the call to `requireExplicitResolversForScalars`.\",\n )\n }\n}\n"],"names":["GraphQLScalarType"],"mappings":";;;;AAGA;;;;;;AAMG;SACa,kCAAkC,CAAC,MAAqB,EAAE,GAAG,eAAyB,EAAA;AACpG,IAAA,MAAM,UAAU,GAAG,MAAM,CAAC,YAAY,CAAC,CAAA;IACvC,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAA6B,CAAC,YAAYA,yBAAiB,CAAC,CAAA;AACxH,IAAA,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;AAC5B,QAAA,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM,IAAI,eAAe,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC;YAAE,SAAQ;AACvG,QAAA,IAAI;AACF,YAAA,MAAM,CAAC,UAAU,CAAC,UAAU,CAAC,CAAA;SAC9B;AAAC,QAAA,MAAM;;YAEN,SAAQ;SACT;AACD,QAAA,MAAM,IAAI,KAAK,CACb,UAAU,MAAM,CAAC,IAAI,CAAgH,8GAAA,CAAA;AACnI,YAAA,6GAA6G,CAChH,CAAA;KACF;AACH;;;;"}
@@ -0,0 +1,29 @@
1
+ import { GraphQLScalarType } from 'graphql';
2
+
3
+ /**
4
+ * It is possible to register a custom scalar with apollo server without defining an explicit resolver (a default resolver is used in
5
+ * this case), but it is rarely desirable. This function, when provided with your built schema, will ensure any registered scalar types
6
+ * provide at least a base level of validation by failing to parse a Symbol instance. The default resolver does not pass this test
7
+ * meaning any scalars that are falling back to the default resolver will fail.
8
+ * @param schema A schema object, the result of calling `makeExecutableSchema` from `@graphql-tools/schema`
9
+ */
10
+ function requireExplicitResolversForScalars(schema, ...scalarsToIgnore) {
11
+ const testSymbol = Symbol('testSymbol');
12
+ const scalars = Object.values(schema.getTypeMap()).filter((t) => t instanceof GraphQLScalarType);
13
+ for (const scalar of scalars) {
14
+ if (scalar.name === 'Void' || scalar.name === 'JSON' || scalarsToIgnore.includes(scalar.name))
15
+ continue;
16
+ try {
17
+ scalar.parseValue(testSymbol);
18
+ }
19
+ catch {
20
+ // We expect that a good parser should throw when parsing a random symbol
21
+ continue;
22
+ }
23
+ throw new Error(`Scalar ${scalar.name} does not appear to have an explicit resolver, or is not performing sufficient validation when parsing input. ` +
24
+ "If you're satisfied with this scalar you can ignore it in the call to `requireExplicitResolversForScalars`.");
25
+ }
26
+ }
27
+
28
+ export { requireExplicitResolversForScalars };
29
+ //# sourceMappingURL=schema-util.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-util.mjs","sources":["../src/schema-util.ts"],"sourcesContent":["import type { GraphQLSchema } from 'graphql'\nimport { GraphQLScalarType } from 'graphql'\n\n/**\n * It is possible to register a custom scalar with apollo server without defining an explicit resolver (a default resolver is used in\n * this case), but it is rarely desirable. This function, when provided with your built schema, will ensure any registered scalar types\n * provide at least a base level of validation by failing to parse a Symbol instance. The default resolver does not pass this test\n * meaning any scalars that are falling back to the default resolver will fail.\n * @param schema A schema object, the result of calling `makeExecutableSchema` from `@graphql-tools/schema`\n */\nexport function requireExplicitResolversForScalars(schema: GraphQLSchema, ...scalarsToIgnore: string[]) {\n const testSymbol = Symbol('testSymbol')\n const scalars = Object.values(schema.getTypeMap()).filter((t): t is GraphQLScalarType => t instanceof GraphQLScalarType)\n for (const scalar of scalars) {\n if (scalar.name === 'Void' || scalar.name === 'JSON' || scalarsToIgnore.includes(scalar.name)) continue\n try {\n scalar.parseValue(testSymbol)\n } catch {\n // We expect that a good parser should throw when parsing a random symbol\n continue\n }\n throw new Error(\n `Scalar ${scalar.name} does not appear to have an explicit resolver, or is not performing sufficient validation when parsing input. ` +\n \"If you're satisfied with this scalar you can ignore it in the call to `requireExplicitResolversForScalars`.\",\n )\n }\n}\n"],"names":[],"mappings":";;AAGA;;;;;;AAMG;SACa,kCAAkC,CAAC,MAAqB,EAAE,GAAG,eAAyB,EAAA;AACpG,IAAA,MAAM,UAAU,GAAG,MAAM,CAAC,YAAY,CAAC,CAAA;IACvC,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAA6B,CAAC,YAAY,iBAAiB,CAAC,CAAA;AACxH,IAAA,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;AAC5B,QAAA,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM,IAAI,eAAe,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC;YAAE,SAAQ;AACvG,QAAA,IAAI;AACF,YAAA,MAAM,CAAC,UAAU,CAAC,UAAU,CAAC,CAAA;SAC9B;AAAC,QAAA,MAAM;;YAEN,SAAQ;SACT;AACD,QAAA,MAAM,IAAI,KAAK,CACb,UAAU,MAAM,CAAC,IAAI,CAAgH,8GAAA,CAAA;AACnI,YAAA,6GAA6G,CAChH,CAAA;KACF;AACH;;;;"}
package/shield.d.ts CHANGED
@@ -1,8 +1,9 @@
1
- import { ShieldRule } from 'graphql-shield/typings/types';
2
- import { Primitive } from './models';
3
- import { and, chain, or, race } from 'graphql-shield';
1
+ import type { and, chain, or, race } from 'graphql-shield';
2
+ import { allow } from 'graphql-shield';
3
+ import type { Primitive } from './models';
4
4
  type RuleCombinator = typeof chain | typeof race | typeof or | typeof and;
5
- export declare const createRule: <TContext, TParent = unknown, TArgs = unknown>(logic: (parent: TParent, args: TArgs, ctx: TContext) => boolean | Promise<boolean> | Error, cache?: 'contextual' | 'strict') => import("graphql-shield/typings/rules").Rule;
5
+ export type ShieldRule = ReturnType<(typeof allow)['getRules']>[number];
6
+ export declare const createRule: <TContext, TParent = unknown, TArgs = unknown>(logic: (parent: TParent, args: TArgs, ctx: TContext) => boolean | Promise<boolean> | Error, cache?: 'contextual' | 'strict') => ShieldRule;
6
7
  /**
7
8
  * Combines a given rule with all existing defined rules using the provided combinator
8
9
  * @param schema The existing shield schema with rules
@@ -40,4 +41,3 @@ export type ShieldSchema<TResolver> = TResolver extends Primitive ? ShieldRule :
40
41
  '*'?: ShieldRule;
41
42
  };
42
43
  export {};
43
- //# sourceMappingURL=shield.d.ts.map
package/shield.js CHANGED
@@ -1,9 +1,8 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createShieldSchema = exports.combineRuleWithAll = exports.createRule = void 0;
4
- const graphql_shield_1 = require("graphql-shield");
5
- const createRule = (logic, cache = 'strict') => (0, graphql_shield_1.rule)({ cache })(async (parent, args, ctx) => logic(parent, args, ctx));
6
- exports.createRule = createRule;
1
+ 'use strict';
2
+
3
+ var graphqlShield = require('graphql-shield');
4
+
5
+ const createRule = (logic, cache = 'strict') => graphqlShield.rule({ cache })(async (parent, args, ctx) => logic(parent, args, ctx));
7
6
  /**
8
7
  * Combines a given rule with all existing defined rules using the provided combinator
9
8
  * @param schema The existing shield schema with rules
@@ -22,7 +21,6 @@ function combineRuleWithAll(schema, rule, combinator) {
22
21
  return [key, combineRuleWithAll(value, rule, combinator)];
23
22
  }));
24
23
  }
25
- exports.combineRuleWithAll = combineRuleWithAll;
26
24
  /**
27
25
  * Creates graphql shield middleware making use of generics to type the definition of the rules.
28
26
  * @param schema A mapping of schema objects to the shield rules that define the access to that object
@@ -42,11 +40,14 @@ exports.combineRuleWithAll = combineRuleWithAll;
42
40
  *
43
41
  * schema = applyMiddleware(schema, shieldSchema)
44
42
  */
45
- function createShieldSchema(schema, fallbackRule = graphql_shield_1.allow) {
46
- return (0, graphql_shield_1.shield)(schema, {
43
+ function createShieldSchema(schema, fallbackRule = graphqlShield.allow) {
44
+ return graphqlShield.shield(schema, {
47
45
  allowExternalErrors: true,
48
46
  fallbackRule: fallbackRule,
49
47
  });
50
48
  }
49
+
50
+ exports.combineRuleWithAll = combineRuleWithAll;
51
+ exports.createRule = createRule;
51
52
  exports.createShieldSchema = createShieldSchema;
52
- //# sourceMappingURL=shield.js.map
53
+ //# sourceMappingURL=shield.js.map
package/shield.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"shield.js","sourceRoot":"","sources":["../src/shield.ts"],"names":[],"mappings":";;;AAEA,mDAA0E;AAInE,MAAM,UAAU,GAAG,CACxB,KAA0F,EAC1F,QAAiC,QAAQ,EACzC,EAAE,CAAC,IAAA,qBAAI,EAAC,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC,CAAA;AAH9D,QAAA,UAAU,cAGoD;AAE3E;;;;;;;;;GASG;AACH,SAAgB,kBAAkB,CAAI,MAAuB,EAAE,IAAgB,EAAE,UAA0B;IACzG,OAAO,MAAM,CAAC,WAAW,CACvB,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;QAC1C,IAAI,KAAK,CAAC,WAAW,CAAC,IAAI,KAAK,QAAQ,EAAE;YACvC,OAAO,CAAC,GAAG,EAAE,UAAU,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAA;SACtC;QACD,OAAO,CAAC,GAAG,EAAE,kBAAkB,CAAC,KAAK,EAAE,IAAI,EAAE,UAAU,CAAC,CAAC,CAAA;IAC3D,CAAC,CAAC,CACgB,CAAA;AACtB,CAAC;AATD,gDASC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAgB,kBAAkB,CAAiB,MAAoC,EAAE,eAA2B,sBAAK;IACvH,OAAO,IAAA,uBAAM,EAAC,MAAgB,EAAE;QAC9B,mBAAmB,EAAE,IAAI;QACzB,YAAY,EAAE,YAAY;KAC3B,CAAC,CAAA;AACJ,CAAC;AALD,gDAKC"}
1
+ {"version":3,"file":"shield.js","sources":["../src/shield.ts"],"sourcesContent":["import type { and, chain, or, race } from 'graphql-shield'\nimport { allow, rule, shield } from 'graphql-shield'\nimport type { IRules } from 'graphql-shield'\nimport type { Primitive } from './models'\n\ntype RuleCombinator = typeof chain | typeof race | typeof or | typeof and\n// For whatever reason, graphql-shield doesn't export this type, but we can extract if from\n// what it does export.\nexport type ShieldRule = ReturnType<(typeof allow)['getRules']>[number]\nexport const createRule = <TContext, TParent = unknown, TArgs = unknown>(\n logic: (parent: TParent, args: TArgs, ctx: TContext) => boolean | Promise<boolean> | Error,\n cache: 'contextual' | 'strict' = 'strict',\n): ShieldRule => rule({ cache })(async (parent, args, ctx) => logic(parent, args, ctx))\n\n/**\n * Combines a given rule with all existing defined rules using the provided combinator\n * @param schema The existing shield schema with rules\n * @param rule The rule to be combined with existing rules\n * @param combinator The combinator to use. Eg. and | or | chain | race\n *\n * Usage:\n *\n * const updatedSchema = combineRuleWithAll(shieldSchema, rules.accountNotBlocked, chain)\n */\nexport function combineRuleWithAll<T>(schema: ShieldSchema<T>, rule: ShieldRule, combinator: RuleCombinator): ShieldSchema<T> {\n return Object.fromEntries(\n Object.entries(schema).map(([key, value]) => {\n if (value.constructor.name !== 'Object') {\n return [key, combinator(rule, value)]\n }\n return [key, combineRuleWithAll(value, rule, combinator)]\n }),\n ) as ShieldSchema<T>\n}\n\n/**\n * Creates graphql shield middleware making use of generics to type the definition of the rules.\n * @param schema A mapping of schema objects to the shield rules that define the access to that object\n * @param fallbackRule A fallback rule to apply to any object or property which doesn't have a defined rule.\n *\n * Usage:\n * import { Resolvers } from '../generated/types'\n *\n * const shieldSchema = createShieldSchema<Resolvers>({\n * Query: {\n * getThings: allow,\n * dontGetThings: deny,\n * }\n * })\n *\n * let schema = makeExecutableSchema({...})\n *\n * schema = applyMiddleware(schema, shieldSchema)\n */\nexport function createShieldSchema<TRootResolvers>(schema: ShieldSchema<TRootResolvers>, fallbackRule: ShieldRule = allow) {\n return shield(schema as IRules, {\n allowExternalErrors: true,\n fallbackRule: fallbackRule,\n })\n}\n\nexport type ShieldSchema<TResolver> = TResolver extends Primitive\n ? ShieldRule\n : {\n [key in keyof TResolver]?: ShieldSchema<TResolver[key]> | ShieldRule\n } & {\n '*'?: ShieldRule\n }\n"],"names":["rule","allow","shield"],"mappings":";;;;AASa,MAAA,UAAU,GAAG,CACxB,KAA0F,EAC1F,KAAA,GAAiC,QAAQ,KAC1BA,kBAAI,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,OAAO,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,KAAK,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,CAAC,EAAC;AAEvF;;;;;;;;;AASG;SACa,kBAAkB,CAAI,MAAuB,EAAE,IAAgB,EAAE,UAA0B,EAAA;IACzG,OAAO,MAAM,CAAC,WAAW,CACvB,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,KAAI;QAC1C,IAAI,KAAK,CAAC,WAAW,CAAC,IAAI,KAAK,QAAQ,EAAE;YACvC,OAAO,CAAC,GAAG,EAAE,UAAU,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAA;SACtC;AACD,QAAA,OAAO,CAAC,GAAG,EAAE,kBAAkB,CAAC,KAAK,EAAE,IAAI,EAAE,UAAU,CAAC,CAAC,CAAA;KAC1D,CAAC,CACgB,CAAA;AACtB,CAAC;AAED;;;;;;;;;;;;;;;;;;AAkBG;SACa,kBAAkB,CAAiB,MAAoC,EAAE,eAA2BC,mBAAK,EAAA;IACvH,OAAOC,oBAAM,CAAC,MAAgB,EAAE;AAC9B,QAAA,mBAAmB,EAAE,IAAI;AACzB,QAAA,YAAY,EAAE,YAAY;AAC3B,KAAA,CAAC,CAAA;AACJ;;;;;;"}
package/shield.mjs ADDED
@@ -0,0 +1,49 @@
1
+ import { rule, shield, allow } from 'graphql-shield';
2
+
3
+ const createRule = (logic, cache = 'strict') => rule({ cache })(async (parent, args, ctx) => logic(parent, args, ctx));
4
+ /**
5
+ * Combines a given rule with all existing defined rules using the provided combinator
6
+ * @param schema The existing shield schema with rules
7
+ * @param rule The rule to be combined with existing rules
8
+ * @param combinator The combinator to use. Eg. and | or | chain | race
9
+ *
10
+ * Usage:
11
+ *
12
+ * const updatedSchema = combineRuleWithAll(shieldSchema, rules.accountNotBlocked, chain)
13
+ */
14
+ function combineRuleWithAll(schema, rule, combinator) {
15
+ return Object.fromEntries(Object.entries(schema).map(([key, value]) => {
16
+ if (value.constructor.name !== 'Object') {
17
+ return [key, combinator(rule, value)];
18
+ }
19
+ return [key, combineRuleWithAll(value, rule, combinator)];
20
+ }));
21
+ }
22
+ /**
23
+ * Creates graphql shield middleware making use of generics to type the definition of the rules.
24
+ * @param schema A mapping of schema objects to the shield rules that define the access to that object
25
+ * @param fallbackRule A fallback rule to apply to any object or property which doesn't have a defined rule.
26
+ *
27
+ * Usage:
28
+ * import { Resolvers } from '../generated/types'
29
+ *
30
+ * const shieldSchema = createShieldSchema<Resolvers>({
31
+ * Query: {
32
+ * getThings: allow,
33
+ * dontGetThings: deny,
34
+ * }
35
+ * })
36
+ *
37
+ * let schema = makeExecutableSchema({...})
38
+ *
39
+ * schema = applyMiddleware(schema, shieldSchema)
40
+ */
41
+ function createShieldSchema(schema, fallbackRule = allow) {
42
+ return shield(schema, {
43
+ allowExternalErrors: true,
44
+ fallbackRule: fallbackRule,
45
+ });
46
+ }
47
+
48
+ export { combineRuleWithAll, createRule, createShieldSchema };
49
+ //# sourceMappingURL=shield.mjs.map
package/shield.mjs.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shield.mjs","sources":["../src/shield.ts"],"sourcesContent":["import type { and, chain, or, race } from 'graphql-shield'\nimport { allow, rule, shield } from 'graphql-shield'\nimport type { IRules } from 'graphql-shield'\nimport type { Primitive } from './models'\n\ntype RuleCombinator = typeof chain | typeof race | typeof or | typeof and\n// For whatever reason, graphql-shield doesn't export this type, but we can extract if from\n// what it does export.\nexport type ShieldRule = ReturnType<(typeof allow)['getRules']>[number]\nexport const createRule = <TContext, TParent = unknown, TArgs = unknown>(\n logic: (parent: TParent, args: TArgs, ctx: TContext) => boolean | Promise<boolean> | Error,\n cache: 'contextual' | 'strict' = 'strict',\n): ShieldRule => rule({ cache })(async (parent, args, ctx) => logic(parent, args, ctx))\n\n/**\n * Combines a given rule with all existing defined rules using the provided combinator\n * @param schema The existing shield schema with rules\n * @param rule The rule to be combined with existing rules\n * @param combinator The combinator to use. Eg. and | or | chain | race\n *\n * Usage:\n *\n * const updatedSchema = combineRuleWithAll(shieldSchema, rules.accountNotBlocked, chain)\n */\nexport function combineRuleWithAll<T>(schema: ShieldSchema<T>, rule: ShieldRule, combinator: RuleCombinator): ShieldSchema<T> {\n return Object.fromEntries(\n Object.entries(schema).map(([key, value]) => {\n if (value.constructor.name !== 'Object') {\n return [key, combinator(rule, value)]\n }\n return [key, combineRuleWithAll(value, rule, combinator)]\n }),\n ) as ShieldSchema<T>\n}\n\n/**\n * Creates graphql shield middleware making use of generics to type the definition of the rules.\n * @param schema A mapping of schema objects to the shield rules that define the access to that object\n * @param fallbackRule A fallback rule to apply to any object or property which doesn't have a defined rule.\n *\n * Usage:\n * import { Resolvers } from '../generated/types'\n *\n * const shieldSchema = createShieldSchema<Resolvers>({\n * Query: {\n * getThings: allow,\n * dontGetThings: deny,\n * }\n * })\n *\n * let schema = makeExecutableSchema({...})\n *\n * schema = applyMiddleware(schema, shieldSchema)\n */\nexport function createShieldSchema<TRootResolvers>(schema: ShieldSchema<TRootResolvers>, fallbackRule: ShieldRule = allow) {\n return shield(schema as IRules, {\n allowExternalErrors: true,\n fallbackRule: fallbackRule,\n })\n}\n\nexport type ShieldSchema<TResolver> = TResolver extends Primitive\n ? ShieldRule\n : {\n [key in keyof TResolver]?: ShieldSchema<TResolver[key]> | ShieldRule\n } & {\n '*'?: ShieldRule\n }\n"],"names":[],"mappings":";;AASa,MAAA,UAAU,GAAG,CACxB,KAA0F,EAC1F,KAAA,GAAiC,QAAQ,KAC1B,IAAI,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,OAAO,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,KAAK,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,CAAC,EAAC;AAEvF;;;;;;;;;AASG;SACa,kBAAkB,CAAI,MAAuB,EAAE,IAAgB,EAAE,UAA0B,EAAA;IACzG,OAAO,MAAM,CAAC,WAAW,CACvB,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,KAAI;QAC1C,IAAI,KAAK,CAAC,WAAW,CAAC,IAAI,KAAK,QAAQ,EAAE;YACvC,OAAO,CAAC,GAAG,EAAE,UAAU,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAA;SACtC;AACD,QAAA,OAAO,CAAC,GAAG,EAAE,kBAAkB,CAAC,KAAK,EAAE,IAAI,EAAE,UAAU,CAAC,CAAC,CAAA;KAC1D,CAAC,CACgB,CAAA;AACtB,CAAC;AAED;;;;;;;;;;;;;;;;;;AAkBG;SACa,kBAAkB,CAAiB,MAAoC,EAAE,eAA2B,KAAK,EAAA;IACvH,OAAO,MAAM,CAAC,MAAgB,EAAE;AAC9B,QAAA,mBAAmB,EAAE,IAAI;AACzB,QAAA,YAAY,EAAE,YAAY;AAC3B,KAAA,CAAC,CAAA;AACJ;;;;"}
@@ -2,7 +2,7 @@
2
2
  import type { Logger } from '@makerx/node-common';
3
3
  import type { IncomingMessage } from 'http';
4
4
  import { User } from '../User';
5
- import { CreateRequestLogger, GraphQLContext, JwtPayload, RequestInfo } from '../context';
5
+ import type { CreateRequestLogger, GraphQLContext, JwtPayload, RequestInfo } from '../context';
6
6
  export interface SubscriptionContextInput {
7
7
  connectRequest: IncomingMessage;
8
8
  connectionParams?: Readonly<Record<string, unknown>>;
@@ -20,4 +20,3 @@ export interface CreateSubscriptionContextConfig<TContext = GraphQLContext> {
20
20
  augmentContext?: (context: TContext) => Record<string, unknown> | Promise<Record<string, unknown>>;
21
21
  }
22
22
  export declare const createSubscriptionContextFactory: <TContext extends GraphQLContext<Logger, RequestInfo, User | undefined> = GraphQLContext<Logger, RequestInfo, User | undefined>>({ requestLogger, augmentRequestInfo, claimsToLog, createUser, requestInfoToLog, augmentContext, }: CreateSubscriptionContextConfig<TContext>) => CreateSubscriptionContext<TContext>;
23
- //# sourceMappingURL=context.d.ts.map
@@ -1,10 +1,10 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createSubscriptionContextFactory = void 0;
4
- const crypto_1 = require("crypto");
5
- const lodash_1 = require("lodash");
6
- const User_1 = require("../User");
7
- const utils_1 = require("./utils");
1
+ 'use strict';
2
+
3
+ var crypto = require('crypto');
4
+ var lodash = require('lodash');
5
+ var User = require('../User.js');
6
+ var utils = require('./utils.js');
7
+
8
8
  const createSubscriptionContextFactory = ({ requestLogger, augmentRequestInfo, claimsToLog, createUser = defaultCreateUser, requestInfoToLog, augmentContext, }) => {
9
9
  // the function that creates the GraphQL context
10
10
  return async (input) => {
@@ -13,7 +13,7 @@ const createSubscriptionContextFactory = ({ requestLogger, augmentRequestInfo, c
13
13
  const host = Array.isArray(xForwardedFor) ? xForwardedFor[0] : xForwardedFor ?? req.headers.host;
14
14
  // build request info from the connect request and socket
15
15
  const requestInfo = {
16
- requestId: req.headers['x-request-id']?.toString() ?? (0, crypto_1.randomUUID)(),
16
+ requestId: req.headers['x-request-id']?.toString() ?? crypto.randomUUID(),
17
17
  protocol: 'ws',
18
18
  host: host ?? '',
19
19
  method: req.method ?? '',
@@ -32,10 +32,10 @@ const createSubscriptionContextFactory = ({ requestLogger, augmentRequestInfo, c
32
32
  const requestLoggerMetadata = {};
33
33
  // add request info to log
34
34
  if (requestInfoToLog?.length)
35
- requestLoggerMetadata.request = (0, lodash_1.pick)(requestInfo, requestInfoToLog);
35
+ requestLoggerMetadata.request = lodash.pick(requestInfo, requestInfoToLog);
36
36
  // add user claims to log
37
37
  if (claims && claimsToLog?.length)
38
- requestLoggerMetadata.user = (0, lodash_1.pick)(claims, claimsToLog);
38
+ requestLoggerMetadata.user = lodash.pick(claims, claimsToLog);
39
39
  // build the request logger
40
40
  logger = requestLogger(requestLoggerMetadata);
41
41
  }
@@ -53,11 +53,12 @@ const createSubscriptionContextFactory = ({ requestLogger, augmentRequestInfo, c
53
53
  return augmentedGraphQLContext;
54
54
  };
55
55
  };
56
- exports.createSubscriptionContextFactory = createSubscriptionContextFactory;
57
56
  const defaultCreateUser = ({ claims, connectionParams }) => {
58
57
  if (!claims)
59
58
  return Promise.resolve(undefined);
60
- const accessToken = (0, utils_1.extractTokenFromConnectionParams)(connectionParams);
61
- return Promise.resolve(new User_1.User(claims, accessToken ?? ''));
59
+ const accessToken = utils.extractTokenFromConnectionParams(connectionParams);
60
+ return Promise.resolve(new User.User(claims, accessToken ?? ''));
62
61
  };
63
- //# sourceMappingURL=context.js.map
62
+
63
+ exports.createSubscriptionContextFactory = createSubscriptionContextFactory;
64
+ //# sourceMappingURL=context.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/subscriptions/context.ts"],"names":[],"mappings":";;;AACA,mCAAmC;AAEnC,mCAA6B;AAC7B,kCAA8B;AAE9B,mCAA0D;AAqBnD,MAAM,gCAAgC,GAAG,CAAmD,EACjG,aAAa,EACb,kBAAkB,EAClB,WAAW,EACX,UAAU,GAAG,iBAAiB,EAC9B,gBAAgB,EAChB,cAAc,GAC4B,EAAuC,EAAE;IACnF,gDAAgD;IAChD,OAAO,KAAK,EAAE,KAA+B,EAAE,EAAE;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,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,IAAI,GAAG,CAAC,OAAO,CAAC,IAAI,CAAA;QAEhG,yDAAyD;QACzD,MAAM,WAAW,GAAgB;YAC/B,SAAS,EAAE,GAAG,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,QAAQ,EAAE,IA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YACN,IAAI,EAAE,MAAM,UAAU,CAAC,KAAK,CAAC;YAC7B,OAAO,EAAE,IAAI,CAAC,GAAG,EAAE;SACpB,CAAA;QAED,MAAM,uBAAuB,GAAG,cAAc;YAC5C,CAAC,CAAC,EAAE,GAAG,cAAc,EAAE,GAAG,CAAC,MAAM,cAAc,CAAC,cAA0B,CAAC,CAAC,EAAE;YAC9E,CAAC,CAAC,cAAc,CAAA;QAElB,OAAO,uBAAmC,CAAA;IAC5C,CAAC,CAAA;AACH,CAAC,CAAA;AAxDY,QAAA,gCAAgC,oCAwD5C;AAED,MAAM,iBAAiB,GAA6C,CAAC,EAAE,MAAM,EAAE,gBAAgB,EAAE,EAAE,EAAE;IACnG,IAAI,CAAC,MAAM;QAAE,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAA;IAC9C,MAAM,WAAW,GAAG,IAAA,wCAAgC,EAAC,gBAAgB,CAAC,CAAA;IACtE,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,WAAI,CAAC,MAAM,EAAE,WAAW,IAAI,EAAE,CAAC,CAAC,CAAA;AAC7D,CAAC,CAAA"}
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,OAAO,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE;YAC9C,QAAQ,EAAE,GAA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AAA,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;;;;"}
@@ -0,0 +1,62 @@
1
+ import { randomUUID } from 'crypto';
2
+ import { pick } from 'lodash';
3
+ import { User } from '../User.mjs';
4
+ import { extractTokenFromConnectionParams } from './utils.mjs';
5
+
6
+ const createSubscriptionContextFactory = ({ requestLogger, augmentRequestInfo, claimsToLog, createUser = defaultCreateUser, requestInfoToLog, augmentContext, }) => {
7
+ // the function that creates the GraphQL context
8
+ return async (input) => {
9
+ 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
+ // build request info from the connect request and socket
13
+ 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,
24
+ ...augmentRequestInfo?.(input),
25
+ };
26
+ // create request logger
27
+ let logger;
28
+ if (typeof requestLogger === 'function') {
29
+ // build request logger metadata
30
+ const requestLoggerMetadata = {};
31
+ // add request info to log
32
+ if (requestInfoToLog?.length)
33
+ requestLoggerMetadata.request = pick(requestInfo, requestInfoToLog);
34
+ // add user claims to log
35
+ if (claims && claimsToLog?.length)
36
+ requestLoggerMetadata.user = pick(claims, claimsToLog);
37
+ // build the request logger
38
+ logger = requestLogger(requestLoggerMetadata);
39
+ }
40
+ else
41
+ logger = requestLogger;
42
+ const graphqlContext = {
43
+ requestInfo,
44
+ logger,
45
+ user: await createUser(input),
46
+ started: Date.now(),
47
+ };
48
+ const augmentedGraphQLContext = augmentContext
49
+ ? { ...graphqlContext, ...(await augmentContext(graphqlContext)) }
50
+ : graphqlContext;
51
+ return augmentedGraphQLContext;
52
+ };
53
+ };
54
+ const defaultCreateUser = ({ claims, connectionParams }) => {
55
+ if (!claims)
56
+ return Promise.resolve(undefined);
57
+ const accessToken = extractTokenFromConnectionParams(connectionParams);
58
+ return Promise.resolve(new User(claims, accessToken ?? ''));
59
+ };
60
+
61
+ export { createSubscriptionContextFactory };
62
+ //# sourceMappingURL=context.mjs.map
@@ -0,0 +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,QAAQ,CAAC,IAAI,EAAE;YACnC,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE;YAC9C,QAAQ,EAAE,GAAG,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,QAAQ,EAAE,IAAI,SAAS;AAC9D,YAAA,QAAQ,EAAE,GAAG,CAAC,OAAO,CAAC,iBAAiB,CAAC,EAAE,QAAQ,EAAE,IAAI,GAAG,CAAC,MAAM,CAAC,aAAa;YAChF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IAAI,IAAI,CAAC,MAAM,EAAE,WAAW,IAAI,EAAE,CAAC,CAAC,CAAA;AAC7D,CAAC;;;;"}
@@ -1,4 +1,3 @@
1
1
  export * from './context';
2
2
  export * from './server';
3
3
  export { extractTokenFromConnectionParams } from './utils';
4
- //# sourceMappingURL=index.d.ts.map
@@ -1,22 +1,12 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.extractTokenFromConnectionParams = void 0;
18
- __exportStar(require("./context"), exports);
19
- __exportStar(require("./server"), exports);
20
- var utils_1 = require("./utils");
21
- Object.defineProperty(exports, "extractTokenFromConnectionParams", { enumerable: true, get: function () { return utils_1.extractTokenFromConnectionParams; } });
22
- //# sourceMappingURL=index.js.map
1
+ 'use strict';
2
+
3
+ var context = require('./context.js');
4
+ var server = require('./server.js');
5
+ var utils = require('./utils.js');
6
+
7
+
8
+
9
+ exports.createSubscriptionContextFactory = context.createSubscriptionContextFactory;
10
+ exports.useSubscriptionsServer = server.useSubscriptionsServer;
11
+ exports.extractTokenFromConnectionParams = utils.extractTokenFromConnectionParams;
12
+ //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/subscriptions/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,4CAAyB;AACzB,2CAAwB;AACxB,iCAA0D;AAAjD,yHAAA,gCAAgC,OAAA"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;"}
@@ -0,0 +1,4 @@
1
+ export { createSubscriptionContextFactory } from './context.mjs';
2
+ export { useSubscriptionsServer } from './server.mjs';
3
+ export { extractTokenFromConnectionParams } from './utils.mjs';
4
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;"}
@@ -1,9 +1,9 @@
1
1
  /// <reference types="node" />
2
- import { Logger } from '@makerx/node-common';
3
- import { GraphQLSchema } from 'graphql';
2
+ import type { Logger } from '@makerx/node-common';
3
+ import type { GraphQLSchema } from 'graphql';
4
4
  import type { Server } from 'http';
5
- import { JwtPayload } from '../context';
6
- import { CreateSubscriptionContext } from './context';
5
+ import type { JwtPayload } from '../context';
6
+ import type { CreateSubscriptionContext } from './context';
7
7
  export declare function useSubscriptionsServer<TLogger extends Logger = Logger>({ schema, httpServer, createSubscriptionContext, logger, operationLogLevel, path, verifyToken, requireAuth, jwtClaimsToLog, }: {
8
8
  schema: GraphQLSchema;
9
9
  httpServer: Server;
@@ -15,4 +15,3 @@ export declare function useSubscriptionsServer<TLogger extends Logger = Logger>(
15
15
  requireAuth?: boolean;
16
16
  jwtClaimsToLog?: string[];
17
17
  }): import("graphql-ws").Disposable;
18
- //# sourceMappingURL=server.d.ts.map