@envelop/core 2.6.0 → 2.6.1-alpha-20220901205925-b1fd44a9

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 (45) hide show
  1. package/cjs/create.js +7 -5
  2. package/cjs/index.js +3 -3
  3. package/cjs/orchestrator.js +20 -12
  4. package/cjs/plugins/use-error-handler.js +1 -2
  5. package/cjs/traced-schema.js +29 -7
  6. package/cjs/utils.js +8 -40
  7. package/esm/create.js +7 -5
  8. package/esm/index.js +1 -3
  9. package/esm/orchestrator.js +12 -4
  10. package/esm/plugins/use-error-handler.js +1 -2
  11. package/esm/traced-schema.js +25 -3
  12. package/esm/utils.js +7 -36
  13. package/package.json +2 -5
  14. package/typings/create.d.cts +5 -1
  15. package/typings/create.d.ts +5 -1
  16. package/typings/index.d.cts +1 -3
  17. package/typings/index.d.ts +1 -3
  18. package/typings/orchestrator.d.cts +11 -4
  19. package/typings/orchestrator.d.ts +11 -4
  20. package/typings/plugins/use-error-handler.d.cts +1 -2
  21. package/typings/plugins/use-error-handler.d.ts +1 -2
  22. package/typings/plugins/use-payload-formatter.d.cts +1 -2
  23. package/typings/plugins/use-payload-formatter.d.ts +1 -2
  24. package/typings/plugins/use-schema.d.cts +3 -4
  25. package/typings/plugins/use-schema.d.ts +3 -4
  26. package/typings/traced-schema.d.cts +1 -3
  27. package/typings/traced-schema.d.ts +1 -3
  28. package/typings/utils.d.cts +4 -8
  29. package/typings/utils.d.ts +4 -8
  30. package/cjs/plugins/use-immediate-introspection.js +0 -50
  31. package/cjs/plugins/use-masked-errors.js +0 -93
  32. package/cjs/plugins/use-timing.js +0 -138
  33. package/cjs/traced-orchestrator.js +0 -136
  34. package/esm/plugins/use-immediate-introspection.js +0 -46
  35. package/esm/plugins/use-masked-errors.js +0 -87
  36. package/esm/plugins/use-timing.js +0 -134
  37. package/esm/traced-orchestrator.js +0 -132
  38. package/typings/plugins/use-immediate-introspection.d.cts +0 -6
  39. package/typings/plugins/use-immediate-introspection.d.ts +0 -6
  40. package/typings/plugins/use-masked-errors.d.cts +0 -39
  41. package/typings/plugins/use-masked-errors.d.ts +0 -39
  42. package/typings/plugins/use-timing.d.cts +0 -21
  43. package/typings/plugins/use-timing.d.ts +0 -21
  44. package/typings/traced-orchestrator.d.cts +0 -7
  45. package/typings/traced-orchestrator.d.ts +0 -7
@@ -1,5 +1,4 @@
1
- import { ArbitraryObject, EnvelopContextFnWrapper, GetEnvelopedFn, Plugin, DefaultContext, Maybe } from '@envelop/types';
2
- import { GraphQLSchema } from 'graphql';
1
+ import { ArbitraryObject, EnvelopContextFnWrapper, GetEnvelopedFn, Plugin, SubscribeFunction, ExecuteFunction, DefaultContext, Maybe, ParseFunction, ValidateFunction } from '@envelop/types';
3
2
  export declare type EnvelopOrchestrator<InitialContext extends ArbitraryObject = ArbitraryObject, PluginsContext extends ArbitraryObject = ArbitraryObject> = {
4
3
  init: (initialContext?: Maybe<InitialContext>) => void;
5
4
  parse: EnvelopContextFnWrapper<ReturnType<GetEnvelopedFn<PluginsContext>>['parse'], InitialContext>;
@@ -7,6 +6,14 @@ export declare type EnvelopOrchestrator<InitialContext extends ArbitraryObject =
7
6
  execute: ReturnType<GetEnvelopedFn<PluginsContext>>['execute'];
8
7
  subscribe: ReturnType<GetEnvelopedFn<PluginsContext>>['subscribe'];
9
8
  contextFactory: EnvelopContextFnWrapper<ReturnType<GetEnvelopedFn<PluginsContext>>['contextFactory'], PluginsContext>;
10
- getCurrentSchema: () => Maybe<GraphQLSchema>;
9
+ getCurrentSchema: () => Maybe<any>;
11
10
  };
12
- export declare function createEnvelopOrchestrator<PluginsContext extends DefaultContext>(plugins: Plugin[]): EnvelopOrchestrator<any, PluginsContext>;
11
+ declare type EnvelopOrchestratorOptions = {
12
+ plugins: Plugin[];
13
+ parse: ParseFunction;
14
+ execute: ExecuteFunction;
15
+ subscribe: SubscribeFunction;
16
+ validate: ValidateFunction;
17
+ };
18
+ export declare function createEnvelopOrchestrator<PluginsContext extends DefaultContext>({ plugins, parse, execute, subscribe, validate, }: EnvelopOrchestratorOptions): EnvelopOrchestrator<any, PluginsContext>;
19
+ export {};
@@ -1,4 +1,3 @@
1
1
  import { Plugin, DefaultContext } from '@envelop/types';
2
- import { GraphQLError } from 'graphql';
3
- export declare type ErrorHandler = (errors: readonly GraphQLError[], context: Readonly<DefaultContext>) => void;
2
+ export declare type ErrorHandler = (errors: readonly Error[] | any[], context: Readonly<DefaultContext>) => void;
4
3
  export declare const useErrorHandler: <ContextType extends Record<string, any>>(errorHandler: ErrorHandler) => Plugin<ContextType>;
@@ -1,4 +1,3 @@
1
1
  import { Plugin, DefaultContext } from '@envelop/types';
2
- import { GraphQLError } from 'graphql';
3
- export declare type ErrorHandler = (errors: readonly GraphQLError[], context: Readonly<DefaultContext>) => void;
2
+ export declare type ErrorHandler = (errors: readonly Error[] | any[], context: Readonly<DefaultContext>) => void;
4
3
  export declare const useErrorHandler: <ContextType extends Record<string, any>>(errorHandler: ErrorHandler) => Plugin<ContextType>;
@@ -1,4 +1,3 @@
1
- import { Plugin, TypedExecutionArgs } from '@envelop/types';
2
- import { ExecutionResult } from 'graphql';
1
+ import { Plugin, TypedExecutionArgs, ExecutionResult } from '@envelop/types';
3
2
  export declare type FormatterFunction = (result: ExecutionResult<any, any>, args: TypedExecutionArgs<any>) => false | ExecutionResult<any, any>;
4
3
  export declare const usePayloadFormatter: (formatter: FormatterFunction) => Plugin;
@@ -1,4 +1,3 @@
1
- import { Plugin, TypedExecutionArgs } from '@envelop/types';
2
- import { ExecutionResult } from 'graphql';
1
+ import { Plugin, TypedExecutionArgs, ExecutionResult } from '@envelop/types';
3
2
  export declare type FormatterFunction = (result: ExecutionResult<any, any>, args: TypedExecutionArgs<any>) => false | ExecutionResult<any, any>;
4
3
  export declare const usePayloadFormatter: (formatter: FormatterFunction) => Plugin;
@@ -1,5 +1,4 @@
1
- import { GraphQLSchema } from 'graphql';
2
1
  import { DefaultContext, Maybe, Plugin } from '@envelop/types';
3
- export declare const useSchema: (schema: GraphQLSchema) => Plugin;
4
- export declare const useLazyLoadedSchema: (schemaLoader: (context: Maybe<DefaultContext>) => GraphQLSchema) => Plugin;
5
- export declare const useAsyncSchema: (schemaPromise: Promise<GraphQLSchema>) => Plugin;
2
+ export declare const useSchema: (schema: any) => Plugin;
3
+ export declare const useLazyLoadedSchema: (schemaLoader: (context: Maybe<DefaultContext>) => any) => Plugin;
4
+ export declare const useAsyncSchema: (schemaPromise: Promise<any>) => Plugin;
@@ -1,5 +1,4 @@
1
- import { GraphQLSchema } from 'graphql';
2
1
  import { DefaultContext, Maybe, Plugin } from '@envelop/types';
3
- export declare const useSchema: (schema: GraphQLSchema) => Plugin;
4
- export declare const useLazyLoadedSchema: (schemaLoader: (context: Maybe<DefaultContext>) => GraphQLSchema) => Plugin;
5
- export declare const useAsyncSchema: (schemaPromise: Promise<GraphQLSchema>) => Plugin;
2
+ export declare const useSchema: (schema: any) => Plugin;
3
+ export declare const useLazyLoadedSchema: (schemaLoader: (context: Maybe<DefaultContext>) => any) => Plugin;
4
+ export declare const useAsyncSchema: (schemaPromise: Promise<any>) => Plugin;
@@ -1,4 +1,2 @@
1
- import { GraphQLSchema } from 'graphql';
2
- export declare const trackedSchemaSymbol: unique symbol;
3
1
  export declare const resolversHooksSymbol: unique symbol;
4
- export declare function prepareTracedSchema(schema: GraphQLSchema | null | undefined): void;
2
+ export declare function prepareTracedSchema(schema: any | null | undefined): void;
@@ -1,4 +1,2 @@
1
- import { GraphQLSchema } from 'graphql';
2
- export declare const trackedSchemaSymbol: unique symbol;
3
1
  export declare const resolversHooksSymbol: unique symbol;
4
- export declare function prepareTracedSchema(schema: GraphQLSchema | null | undefined): void;
2
+ export declare function prepareTracedSchema(schema: any | null | undefined): void;
@@ -1,19 +1,15 @@
1
- import { ASTNode, DocumentNode, OperationDefinitionNode, Source, ExecutionResult, SubscriptionArgs, ExecutionArgs } from 'graphql';
2
- import { AsyncIterableIteratorOrValue, ExecuteFunction, SubscribeFunction, PromiseOrValue, DefaultContext, OnExecuteDoneEventPayload, OnExecuteDoneHookResult, OnExecuteDoneHookResultOnNextHook } from '@envelop/types';
1
+ import { AsyncIterableIteratorOrValue, ExecuteFunction, SubscribeFunction, PromiseOrValue, DefaultContext, OnExecuteDoneEventPayload, OnExecuteDoneHookResult, OnExecuteDoneHookResultOnNextHook, ExecutionArgs } from '@envelop/types';
3
2
  export declare const envelopIsIntrospectionSymbol: unique symbol;
4
- export declare function isOperationDefinition(def: ASTNode): def is OperationDefinitionNode;
5
- export declare function isIntrospectionOperation(operation: OperationDefinitionNode): boolean;
6
- export declare function isIntrospectionDocument(document: DocumentNode): boolean;
7
- export declare function isIntrospectionOperationString(operation: string | Source): boolean;
3
+ export declare function isIntrospectionOperationString(operation: string | any): boolean;
8
4
  /**
9
5
  * Utility function for making a subscribe function that handles polymorphic arguments.
10
6
  */
11
- export declare const makeSubscribe: (subscribeFn: (args: SubscriptionArgs) => PromiseOrValue<AsyncIterableIterator<ExecutionResult>>) => SubscribeFunction;
7
+ export declare const makeSubscribe: (subscribeFn: (args: ExecutionArgs) => any) => SubscribeFunction;
12
8
  export declare function mapAsyncIterator<T, O>(source: AsyncIterable<T>, mapper: (input: T) => Promise<O> | O): AsyncGenerator<O>;
13
9
  /**
14
10
  * Utility function for making a execute function that handles polymorphic arguments.
15
11
  */
16
- export declare const makeExecute: (executeFn: (args: ExecutionArgs) => PromiseOrValue<AsyncIterableIteratorOrValue<ExecutionResult>>) => ExecuteFunction;
12
+ export declare const makeExecute: (executeFn: (args: ExecutionArgs) => PromiseOrValue<AsyncIterableIteratorOrValue<any>>) => ExecuteFunction;
17
13
  /**
18
14
  * Returns true if the provided object implements the AsyncIterator protocol via
19
15
  * implementing a `Symbol.asyncIterator` method.
@@ -1,19 +1,15 @@
1
- import { ASTNode, DocumentNode, OperationDefinitionNode, Source, ExecutionResult, SubscriptionArgs, ExecutionArgs } from 'graphql';
2
- import { AsyncIterableIteratorOrValue, ExecuteFunction, SubscribeFunction, PromiseOrValue, DefaultContext, OnExecuteDoneEventPayload, OnExecuteDoneHookResult, OnExecuteDoneHookResultOnNextHook } from '@envelop/types';
1
+ import { AsyncIterableIteratorOrValue, ExecuteFunction, SubscribeFunction, PromiseOrValue, DefaultContext, OnExecuteDoneEventPayload, OnExecuteDoneHookResult, OnExecuteDoneHookResultOnNextHook, ExecutionArgs } from '@envelop/types';
3
2
  export declare const envelopIsIntrospectionSymbol: unique symbol;
4
- export declare function isOperationDefinition(def: ASTNode): def is OperationDefinitionNode;
5
- export declare function isIntrospectionOperation(operation: OperationDefinitionNode): boolean;
6
- export declare function isIntrospectionDocument(document: DocumentNode): boolean;
7
- export declare function isIntrospectionOperationString(operation: string | Source): boolean;
3
+ export declare function isIntrospectionOperationString(operation: string | any): boolean;
8
4
  /**
9
5
  * Utility function for making a subscribe function that handles polymorphic arguments.
10
6
  */
11
- export declare const makeSubscribe: (subscribeFn: (args: SubscriptionArgs) => PromiseOrValue<AsyncIterableIterator<ExecutionResult>>) => SubscribeFunction;
7
+ export declare const makeSubscribe: (subscribeFn: (args: ExecutionArgs) => any) => SubscribeFunction;
12
8
  export declare function mapAsyncIterator<T, O>(source: AsyncIterable<T>, mapper: (input: T) => Promise<O> | O): AsyncGenerator<O>;
13
9
  /**
14
10
  * Utility function for making a execute function that handles polymorphic arguments.
15
11
  */
16
- export declare const makeExecute: (executeFn: (args: ExecutionArgs) => PromiseOrValue<AsyncIterableIteratorOrValue<ExecutionResult>>) => ExecuteFunction;
12
+ export declare const makeExecute: (executeFn: (args: ExecutionArgs) => PromiseOrValue<AsyncIterableIteratorOrValue<any>>) => ExecuteFunction;
17
13
  /**
18
14
  * Returns true if the provided object implements the AsyncIterator protocol via
19
15
  * implementing a `Symbol.asyncIterator` method.
@@ -1,50 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.useImmediateIntrospection = void 0;
4
- const graphql_1 = require("graphql");
5
- const OnNonIntrospectionFieldReachedValidationRule = (onNonIntrospectionField) => ctx => {
6
- const rootQueryType = ctx.getSchema().getQueryType();
7
- const rootMutationType = ctx.getSchema().getMutationType();
8
- const rootSubscriptionType = ctx.getSchema().getSubscriptionType();
9
- return {
10
- Field(field) {
11
- const parentType = ctx.getParentType();
12
- const isQuery = parentType === rootQueryType;
13
- const isMutation = parentType === rootMutationType;
14
- const isSubscription = parentType === rootSubscriptionType;
15
- if ((isQuery && !field.name.value.startsWith('__')) || isMutation || isSubscription) {
16
- onNonIntrospectionField();
17
- return graphql_1.BREAK;
18
- }
19
- return undefined;
20
- },
21
- };
22
- };
23
- const fastIntroSpectionSymbol = Symbol('fastIntrospection');
24
- /**
25
- * In case a GraphQL operation only contains introspection fields the context building can be skipped completely.
26
- * With this plugin any further context extensions will be skipped.
27
- */
28
- const useImmediateIntrospection = () => {
29
- return {
30
- onValidate({ addValidationRule }) {
31
- let isIntrospectionOnly = true;
32
- addValidationRule(OnNonIntrospectionFieldReachedValidationRule(() => {
33
- isIntrospectionOnly = false;
34
- }));
35
- return function afterValidate({ extendContext }) {
36
- if (isIntrospectionOnly) {
37
- extendContext({ [fastIntroSpectionSymbol]: true });
38
- }
39
- };
40
- },
41
- onContextBuilding({ context, breakContextBuilding }) {
42
- if (context[fastIntroSpectionSymbol]) {
43
- // hijack and skip all other context related stuff.
44
- // We dont need a context!
45
- breakContextBuilding();
46
- }
47
- },
48
- };
49
- };
50
- exports.useImmediateIntrospection = useImmediateIntrospection;
@@ -1,93 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.useMaskedErrors = exports.formatError = exports.EnvelopError = exports.DEFAULT_ERROR_MESSAGE = void 0;
4
- const graphql_1 = require("graphql");
5
- const utils_js_1 = require("../utils.js");
6
- exports.DEFAULT_ERROR_MESSAGE = 'Unexpected error.';
7
- class EnvelopError extends graphql_1.GraphQLError {
8
- constructor(message, extensions) {
9
- super(message, undefined, undefined, undefined, undefined, undefined, extensions);
10
- }
11
- }
12
- exports.EnvelopError = EnvelopError;
13
- const formatError = (err, message, isDev) => {
14
- var _a, _b, _c, _d;
15
- if (err instanceof graphql_1.GraphQLError) {
16
- if (
17
- /** execution error */
18
- (err.originalError && err.originalError instanceof EnvelopError === false) ||
19
- /** validate and parse errors */
20
- (err.originalError === undefined && err instanceof EnvelopError === false)) {
21
- return new graphql_1.GraphQLError(message, err.nodes, err.source, err.positions, err.path, undefined, isDev
22
- ? {
23
- originalError: {
24
- message: (_b = (_a = err.originalError) === null || _a === void 0 ? void 0 : _a.message) !== null && _b !== void 0 ? _b : err.message,
25
- stack: (_d = (_c = err.originalError) === null || _c === void 0 ? void 0 : _c.stack) !== null && _d !== void 0 ? _d : err.stack,
26
- },
27
- }
28
- : undefined);
29
- }
30
- return err;
31
- }
32
- return new graphql_1.GraphQLError(message);
33
- };
34
- exports.formatError = formatError;
35
- const makeHandleResult = (format, message, isDev) => ({ result, setResult }) => {
36
- if (result.errors != null) {
37
- setResult({ ...result, errors: result.errors.map(error => format(error, message, isDev)) });
38
- }
39
- };
40
- const useMaskedErrors = (opts) => {
41
- var _a, _b;
42
- const format = (_a = opts === null || opts === void 0 ? void 0 : opts.formatError) !== null && _a !== void 0 ? _a : exports.formatError;
43
- const message = (opts === null || opts === void 0 ? void 0 : opts.errorMessage) || exports.DEFAULT_ERROR_MESSAGE;
44
- // eslint-disable-next-line dot-notation
45
- const isDev = (_b = opts === null || opts === void 0 ? void 0 : opts.isDev) !== null && _b !== void 0 ? _b : (typeof process !== 'undefined' ? process.env['NODE_ENV'] === 'development' : false);
46
- const handleResult = makeHandleResult(format, message, isDev);
47
- return {
48
- onParse: (opts === null || opts === void 0 ? void 0 : opts.handleParseErrors) === true
49
- ? function onParse() {
50
- return function onParseEnd({ result, replaceParseResult }) {
51
- if (result instanceof Error) {
52
- replaceParseResult(format(result, message, isDev));
53
- }
54
- };
55
- }
56
- : undefined,
57
- onValidate: (opts === null || opts === void 0 ? void 0 : opts.handleValidationErrors) === true
58
- ? function onValidate() {
59
- return function onValidateEnd({ valid, result, setResult }) {
60
- if (valid === false) {
61
- setResult(result.map(error => format(error, message, isDev)));
62
- }
63
- };
64
- }
65
- : undefined,
66
- onPluginInit(context) {
67
- context.registerContextErrorHandler(({ error, setError }) => {
68
- if (error instanceof graphql_1.GraphQLError === false && error instanceof Error) {
69
- error = new graphql_1.GraphQLError(error.message, undefined, undefined, undefined, undefined, error);
70
- }
71
- setError(format(error, message, isDev));
72
- });
73
- },
74
- onExecute() {
75
- return {
76
- onExecuteDone(payload) {
77
- return (0, utils_js_1.handleStreamOrSingleExecutionResult)(payload, handleResult);
78
- },
79
- };
80
- },
81
- onSubscribe() {
82
- return {
83
- onSubscribeResult(payload) {
84
- return (0, utils_js_1.handleStreamOrSingleExecutionResult)(payload, handleResult);
85
- },
86
- onSubscribeError({ error, setError }) {
87
- setError(format(error, message, isDev));
88
- },
89
- };
90
- },
91
- };
92
- };
93
- exports.useMaskedErrors = useMaskedErrors;
@@ -1,138 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.useTiming = void 0;
4
- const graphql_1 = require("graphql");
5
- const utils_js_1 = require("../utils.js");
6
- const HR_TO_NS = 1e9;
7
- const NS_TO_MS = 1e6;
8
- const DEFAULT_OPTIONS = {
9
- onExecutionMeasurement: (args, timing) => console.log(`Operation execution "${args.operationName}" done in ${timing.ms}ms`),
10
- onSubscriptionMeasurement: (args, timing) => console.log(`Operation subscription "${args.operationName}" done in ${timing.ms}ms`),
11
- onParsingMeasurement: (source, timing) => console.log(`Parsing "${source}" done in ${timing.ms}ms`),
12
- onValidationMeasurement: (document, timing) => { var _a, _b; return console.log(`Validation "${((_b = (_a = (0, graphql_1.getOperationAST)(document)) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.value) || '-'}" done in ${timing.ms}ms`); },
13
- onResolverMeasurement: (info, timing) => console.log(`\tResolver of "${info.parentType.toString()}.${info.fieldName}" done in ${timing.ms}ms`),
14
- onContextBuildingMeasurement: (timing) => console.log(`Context building done in ${timing.ms}ms`),
15
- };
16
- const deltaFrom = (hrtime) => {
17
- const delta = process.hrtime(hrtime);
18
- const ns = delta[0] * HR_TO_NS + delta[1];
19
- return {
20
- ns,
21
- get ms() {
22
- return ns / NS_TO_MS;
23
- },
24
- };
25
- };
26
- const useTiming = (rawOptions) => {
27
- const options = {
28
- ...DEFAULT_OPTIONS,
29
- ...rawOptions,
30
- };
31
- const result = {};
32
- if (options.onContextBuildingMeasurement) {
33
- result.onContextBuilding = ({ context }) => {
34
- if (context[utils_js_1.envelopIsIntrospectionSymbol]) {
35
- return;
36
- }
37
- const contextStartTime = process.hrtime();
38
- return () => {
39
- options.onContextBuildingMeasurement(deltaFrom(contextStartTime));
40
- };
41
- };
42
- }
43
- if (options.onParsingMeasurement) {
44
- result.onParse = ({ params, extendContext }) => {
45
- if (options.skipIntrospection && (0, utils_js_1.isIntrospectionOperationString)(params.source)) {
46
- extendContext({
47
- [utils_js_1.envelopIsIntrospectionSymbol]: true,
48
- });
49
- return;
50
- }
51
- const parseStartTime = process.hrtime();
52
- return () => {
53
- options.onParsingMeasurement(params.source, deltaFrom(parseStartTime));
54
- };
55
- };
56
- }
57
- if (options.onValidationMeasurement) {
58
- result.onValidate = ({ params, context }) => {
59
- if (context[utils_js_1.envelopIsIntrospectionSymbol]) {
60
- return;
61
- }
62
- const validateStartTime = process.hrtime();
63
- return () => {
64
- options.onValidationMeasurement(params.documentAST, deltaFrom(validateStartTime));
65
- };
66
- };
67
- }
68
- if (options.onExecutionMeasurement) {
69
- if (options.onResolverMeasurement) {
70
- result.onExecute = ({ args }) => {
71
- if (args.contextValue[utils_js_1.envelopIsIntrospectionSymbol]) {
72
- return;
73
- }
74
- const executeStartTime = process.hrtime();
75
- return {
76
- onExecuteDone: () => {
77
- options.onExecutionMeasurement(args, deltaFrom(executeStartTime));
78
- },
79
- };
80
- };
81
- result.onResolverCalled = ({ info }) => {
82
- const resolverStartTime = process.hrtime();
83
- return () => {
84
- options.onResolverMeasurement(info, deltaFrom(resolverStartTime));
85
- };
86
- };
87
- }
88
- else {
89
- result.onExecute = ({ args }) => {
90
- if (args.contextValue[utils_js_1.envelopIsIntrospectionSymbol]) {
91
- return;
92
- }
93
- const executeStartTime = process.hrtime();
94
- return {
95
- onExecuteDone: () => {
96
- options.onExecutionMeasurement(args, deltaFrom(executeStartTime));
97
- },
98
- };
99
- };
100
- }
101
- }
102
- if (options.onSubscriptionMeasurement) {
103
- if (options.onResolverMeasurement) {
104
- result.onSubscribe = ({ args }) => {
105
- if (args.contextValue[utils_js_1.envelopIsIntrospectionSymbol]) {
106
- return;
107
- }
108
- const subscribeStartTime = process.hrtime();
109
- return {
110
- onSubscribeResult: () => {
111
- options.onSubscriptionMeasurement && options.onSubscriptionMeasurement(args, deltaFrom(subscribeStartTime));
112
- },
113
- };
114
- };
115
- result.onResolverCalled = ({ info }) => {
116
- const resolverStartTime = process.hrtime();
117
- return () => {
118
- options.onResolverMeasurement && options.onResolverMeasurement(info, deltaFrom(resolverStartTime));
119
- };
120
- };
121
- }
122
- else {
123
- result.onSubscribe = ({ args }) => {
124
- if (args.contextValue[utils_js_1.envelopIsIntrospectionSymbol]) {
125
- return;
126
- }
127
- const subscribeStartTime = process.hrtime();
128
- return {
129
- onSubscribeResult: () => {
130
- options.onSubscriptionMeasurement && options.onSubscriptionMeasurement(args, deltaFrom(subscribeStartTime));
131
- },
132
- };
133
- };
134
- }
135
- }
136
- return result;
137
- };
138
- exports.useTiming = useTiming;
@@ -1,136 +0,0 @@
1
- "use strict";
2
- var _a;
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.traceOrchestrator = void 0;
5
- const graphql_1 = require("graphql");
6
- const utils_js_1 = require("./utils.js");
7
- const getTimestamp = typeof globalThis !== 'undefined' && ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.performance) === null || _a === void 0 ? void 0 : _a.now)
8
- ? () => globalThis.performance.now()
9
- : () => Date.now();
10
- const measure = () => {
11
- const start = getTimestamp();
12
- return () => {
13
- const end = getTimestamp();
14
- return end - start;
15
- };
16
- };
17
- const tracingSymbol = Symbol('envelopTracing');
18
- function traceOrchestrator(orchestrator) {
19
- const createTracer = (name, ctx) => {
20
- const end = measure();
21
- return () => {
22
- ctx[tracingSymbol][name] = end();
23
- };
24
- };
25
- return {
26
- ...orchestrator,
27
- init: (ctx = {}) => {
28
- ctx[tracingSymbol] = ctx[tracingSymbol] || {};
29
- const done = createTracer('init', ctx || {});
30
- try {
31
- return orchestrator.init(ctx);
32
- }
33
- finally {
34
- done();
35
- }
36
- },
37
- parse: (ctx = {}) => {
38
- ctx[tracingSymbol] = ctx[tracingSymbol] || {};
39
- const actualFn = orchestrator.parse(ctx);
40
- return (...args) => {
41
- const done = createTracer('parse', ctx);
42
- try {
43
- return actualFn(...args);
44
- }
45
- finally {
46
- done();
47
- }
48
- };
49
- },
50
- validate: (ctx = {}) => {
51
- ctx[tracingSymbol] = ctx[tracingSymbol] || {};
52
- const actualFn = orchestrator.validate(ctx);
53
- return (...args) => {
54
- const done = createTracer('validate', ctx);
55
- try {
56
- return actualFn(...args);
57
- }
58
- finally {
59
- done();
60
- }
61
- };
62
- },
63
- execute: async (argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) => {
64
- const args = argsOrSchema instanceof graphql_1.GraphQLSchema
65
- ? {
66
- schema: argsOrSchema,
67
- document: document,
68
- rootValue,
69
- contextValue,
70
- variableValues,
71
- operationName,
72
- fieldResolver,
73
- typeResolver,
74
- }
75
- : argsOrSchema;
76
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
77
- // @ts-ignore GraphQL.js types contextValue as unknown
78
- const done = createTracer('execute', args.contextValue || {});
79
- try {
80
- const result = await orchestrator.execute(args);
81
- done();
82
- if (!(0, utils_js_1.isAsyncIterable)(result)) {
83
- result.extensions = result.extensions || {};
84
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
85
- // @ts-ignore GraphQL.js types contextValue as unknown
86
- result.extensions.envelopTracing = args.contextValue[tracingSymbol];
87
- }
88
- else {
89
- // eslint-disable-next-line no-console
90
- console.warn(`"traceOrchestrator" encountered a AsyncIterator which is not supported yet, so tracing data is not available for the operation.`);
91
- }
92
- return result;
93
- }
94
- catch (e) {
95
- done();
96
- throw e;
97
- }
98
- },
99
- subscribe: async (argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) => {
100
- const args = argsOrSchema instanceof graphql_1.GraphQLSchema
101
- ? {
102
- schema: argsOrSchema,
103
- document: document,
104
- rootValue,
105
- contextValue,
106
- variableValues,
107
- operationName,
108
- fieldResolver,
109
- subscribeFieldResolver,
110
- }
111
- : argsOrSchema;
112
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
113
- // @ts-ignore GraphQL.js types contextValue as unknown
114
- const done = createTracer('subscribe', args.contextValue || {});
115
- try {
116
- return await orchestrator.subscribe(args);
117
- }
118
- finally {
119
- done();
120
- }
121
- },
122
- contextFactory: (ctx = {}) => {
123
- const actualFn = orchestrator.contextFactory(ctx);
124
- return async (childCtx) => {
125
- const done = createTracer('contextFactory', ctx);
126
- try {
127
- return await actualFn(childCtx);
128
- }
129
- finally {
130
- done();
131
- }
132
- };
133
- },
134
- };
135
- }
136
- exports.traceOrchestrator = traceOrchestrator;
@@ -1,46 +0,0 @@
1
- import { BREAK } from 'graphql';
2
- const OnNonIntrospectionFieldReachedValidationRule = (onNonIntrospectionField) => ctx => {
3
- const rootQueryType = ctx.getSchema().getQueryType();
4
- const rootMutationType = ctx.getSchema().getMutationType();
5
- const rootSubscriptionType = ctx.getSchema().getSubscriptionType();
6
- return {
7
- Field(field) {
8
- const parentType = ctx.getParentType();
9
- const isQuery = parentType === rootQueryType;
10
- const isMutation = parentType === rootMutationType;
11
- const isSubscription = parentType === rootSubscriptionType;
12
- if ((isQuery && !field.name.value.startsWith('__')) || isMutation || isSubscription) {
13
- onNonIntrospectionField();
14
- return BREAK;
15
- }
16
- return undefined;
17
- },
18
- };
19
- };
20
- const fastIntroSpectionSymbol = Symbol('fastIntrospection');
21
- /**
22
- * In case a GraphQL operation only contains introspection fields the context building can be skipped completely.
23
- * With this plugin any further context extensions will be skipped.
24
- */
25
- export const useImmediateIntrospection = () => {
26
- return {
27
- onValidate({ addValidationRule }) {
28
- let isIntrospectionOnly = true;
29
- addValidationRule(OnNonIntrospectionFieldReachedValidationRule(() => {
30
- isIntrospectionOnly = false;
31
- }));
32
- return function afterValidate({ extendContext }) {
33
- if (isIntrospectionOnly) {
34
- extendContext({ [fastIntroSpectionSymbol]: true });
35
- }
36
- };
37
- },
38
- onContextBuilding({ context, breakContextBuilding }) {
39
- if (context[fastIntroSpectionSymbol]) {
40
- // hijack and skip all other context related stuff.
41
- // We dont need a context!
42
- breakContextBuilding();
43
- }
44
- },
45
- };
46
- };