@graphql-yoga/plugin-apollo-usage-report 0.2.0-alpha-20241004073709-b5c42658 → 0.2.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.
package/cjs/index.js CHANGED
@@ -12,19 +12,34 @@ function getEnvVar(name, defaultValue) {
12
12
  const DEFAULT_REPORTING_ENDPOINT = 'https://usage-reporting.api.apollographql.com/api/ingress/traces';
13
13
  function useApolloUsageReport(options = {}) {
14
14
  const [instrumentation, ctxForReq] = (0, plugin_apollo_inline_trace_1.useApolloInstrumentation)(options);
15
- let logger;
16
- let fetchAPI;
17
15
  let schemaId;
16
+ let yoga;
17
+ const logger = Object.fromEntries(['error', 'warn', 'info', 'debug'].map(level => [
18
+ level,
19
+ (...messages) => yoga.logger[level]('[ApolloUsageReport]', ...messages),
20
+ ]));
21
+ let clientNameFactory = req => req.headers.get('apollographql-client-name') || 'graphql-yoga';
22
+ if (typeof options.clientName === 'string') {
23
+ const clientName = options.clientName;
24
+ clientNameFactory = () => clientName;
25
+ }
26
+ else if (typeof options.clientName === 'function') {
27
+ clientNameFactory = options.clientName;
28
+ }
29
+ let clientVersionFactory = req => req.headers.get('apollographql-client-version') || yoga.version;
30
+ if (typeof options.clientVersion === 'string') {
31
+ const clientVersion = options.clientVersion;
32
+ clientVersionFactory = () => clientVersion;
33
+ }
34
+ else if (typeof options.clientVersion === 'function') {
35
+ clientVersionFactory = options.clientVersion;
36
+ }
18
37
  return {
19
38
  onPluginInit({ addPlugin }) {
20
39
  addPlugin(instrumentation);
21
40
  addPlugin({
22
41
  onYogaInit(args) {
23
- fetchAPI = args.yoga.fetchAPI;
24
- logger = Object.fromEntries(['error', 'warn', 'info', 'debug'].map(level => [
25
- level,
26
- (...messages) => args.yoga.logger[level]('[ApolloUsageReport]', ...messages),
27
- ]));
42
+ yoga = args.yoga;
28
43
  if (!getEnvVar('APOLLO_KEY', options.apiKey)) {
29
44
  throw new Error(`[ApolloUsageReport] Missing API key. Please provide one in plugin options or with 'APOLLO_KEY' environment variable.`);
30
45
  }
@@ -72,13 +87,22 @@ function useApolloUsageReport(options = {}) {
72
87
  if (!trace.schemaId || !trace.operationKey) {
73
88
  throw new TypeError('Misformed trace, missing operation key or schema id');
74
89
  }
90
+ const clientName = clientNameFactory(request);
91
+ if (clientName) {
92
+ trace.trace.clientName = clientName;
93
+ }
94
+ const clientVersion = clientVersionFactory(request);
95
+ if (clientVersion) {
96
+ trace.trace.clientVersion = clientVersion;
97
+ }
75
98
  tracesPerSchema[trace.schemaId] ||= {};
76
99
  tracesPerSchema[trace.schemaId][trace.operationKey] ||= { trace: [] };
77
100
  tracesPerSchema[trace.schemaId][trace.operationKey].trace?.push(trace.trace);
78
101
  }
79
102
  for (const schemaId in tracesPerSchema) {
80
103
  const tracesPerQuery = tracesPerSchema[schemaId];
81
- serverContext.waitUntil(sendTrace(options, logger, fetchAPI, schemaId, tracesPerQuery));
104
+ const agentVersion = options.agentVersion || `graphql-yoga@${yoga.version}`;
105
+ serverContext.waitUntil(sendTrace(options, logger, yoga.fetchAPI.fetch, schemaId, tracesPerQuery, agentVersion));
82
106
  }
83
107
  },
84
108
  });
@@ -96,11 +120,12 @@ async function hashSHA256(str, api = globalThis) {
96
120
  }
97
121
  return hashHex;
98
122
  }
99
- async function sendTrace(options, logger, { fetch }, schemaId, tracesPerQuery) {
123
+ async function sendTrace(options, logger, fetch, schemaId, tracesPerQuery, agentVersion) {
100
124
  const { graphRef = getEnvVar('APOLLO_GRAPH_REF'), apiKey = getEnvVar('APOLLO_KEY'), endpoint = DEFAULT_REPORTING_ENDPOINT, } = options;
101
125
  try {
102
126
  const body = usage_reporting_protobuf_1.Report.encode({
103
127
  header: {
128
+ agentVersion,
104
129
  graphRef,
105
130
  executableSchemaId: schemaId,
106
131
  },
@@ -118,11 +143,12 @@ async function sendTrace(options, logger, { fetch }, schemaId, tracesPerQuery) {
118
143
  },
119
144
  body,
120
145
  });
146
+ const responseText = await response.text();
121
147
  if (response.ok) {
122
- logger.debug('Traces sent:', await response.text());
148
+ logger.debug('Traces sent:', responseText);
123
149
  }
124
150
  else {
125
- logger.error('Failed to send trace:', await response.text());
151
+ logger.error('Failed to send trace:', responseText);
126
152
  }
127
153
  }
128
154
  catch (err) {
package/esm/index.js CHANGED
@@ -8,19 +8,34 @@ function getEnvVar(name, defaultValue) {
8
8
  const DEFAULT_REPORTING_ENDPOINT = 'https://usage-reporting.api.apollographql.com/api/ingress/traces';
9
9
  export function useApolloUsageReport(options = {}) {
10
10
  const [instrumentation, ctxForReq] = useApolloInstrumentation(options);
11
- let logger;
12
- let fetchAPI;
13
11
  let schemaId;
12
+ let yoga;
13
+ const logger = Object.fromEntries(['error', 'warn', 'info', 'debug'].map(level => [
14
+ level,
15
+ (...messages) => yoga.logger[level]('[ApolloUsageReport]', ...messages),
16
+ ]));
17
+ let clientNameFactory = req => req.headers.get('apollographql-client-name') || 'graphql-yoga';
18
+ if (typeof options.clientName === 'string') {
19
+ const clientName = options.clientName;
20
+ clientNameFactory = () => clientName;
21
+ }
22
+ else if (typeof options.clientName === 'function') {
23
+ clientNameFactory = options.clientName;
24
+ }
25
+ let clientVersionFactory = req => req.headers.get('apollographql-client-version') || yoga.version;
26
+ if (typeof options.clientVersion === 'string') {
27
+ const clientVersion = options.clientVersion;
28
+ clientVersionFactory = () => clientVersion;
29
+ }
30
+ else if (typeof options.clientVersion === 'function') {
31
+ clientVersionFactory = options.clientVersion;
32
+ }
14
33
  return {
15
34
  onPluginInit({ addPlugin }) {
16
35
  addPlugin(instrumentation);
17
36
  addPlugin({
18
37
  onYogaInit(args) {
19
- fetchAPI = args.yoga.fetchAPI;
20
- logger = Object.fromEntries(['error', 'warn', 'info', 'debug'].map(level => [
21
- level,
22
- (...messages) => args.yoga.logger[level]('[ApolloUsageReport]', ...messages),
23
- ]));
38
+ yoga = args.yoga;
24
39
  if (!getEnvVar('APOLLO_KEY', options.apiKey)) {
25
40
  throw new Error(`[ApolloUsageReport] Missing API key. Please provide one in plugin options or with 'APOLLO_KEY' environment variable.`);
26
41
  }
@@ -68,13 +83,22 @@ export function useApolloUsageReport(options = {}) {
68
83
  if (!trace.schemaId || !trace.operationKey) {
69
84
  throw new TypeError('Misformed trace, missing operation key or schema id');
70
85
  }
86
+ const clientName = clientNameFactory(request);
87
+ if (clientName) {
88
+ trace.trace.clientName = clientName;
89
+ }
90
+ const clientVersion = clientVersionFactory(request);
91
+ if (clientVersion) {
92
+ trace.trace.clientVersion = clientVersion;
93
+ }
71
94
  tracesPerSchema[trace.schemaId] ||= {};
72
95
  tracesPerSchema[trace.schemaId][trace.operationKey] ||= { trace: [] };
73
96
  tracesPerSchema[trace.schemaId][trace.operationKey].trace?.push(trace.trace);
74
97
  }
75
98
  for (const schemaId in tracesPerSchema) {
76
99
  const tracesPerQuery = tracesPerSchema[schemaId];
77
- serverContext.waitUntil(sendTrace(options, logger, fetchAPI, schemaId, tracesPerQuery));
100
+ const agentVersion = options.agentVersion || `graphql-yoga@${yoga.version}`;
101
+ serverContext.waitUntil(sendTrace(options, logger, yoga.fetchAPI.fetch, schemaId, tracesPerQuery, agentVersion));
78
102
  }
79
103
  },
80
104
  });
@@ -92,11 +116,12 @@ export async function hashSHA256(str, api = globalThis) {
92
116
  }
93
117
  return hashHex;
94
118
  }
95
- async function sendTrace(options, logger, { fetch }, schemaId, tracesPerQuery) {
119
+ async function sendTrace(options, logger, fetch, schemaId, tracesPerQuery, agentVersion) {
96
120
  const { graphRef = getEnvVar('APOLLO_GRAPH_REF'), apiKey = getEnvVar('APOLLO_KEY'), endpoint = DEFAULT_REPORTING_ENDPOINT, } = options;
97
121
  try {
98
122
  const body = Report.encode({
99
123
  header: {
124
+ agentVersion,
100
125
  graphRef,
101
126
  executableSchemaId: schemaId,
102
127
  },
@@ -114,11 +139,12 @@ async function sendTrace(options, logger, { fetch }, schemaId, tracesPerQuery) {
114
139
  },
115
140
  body,
116
141
  });
142
+ const responseText = await response.text();
117
143
  if (response.ok) {
118
- logger.debug('Traces sent:', await response.text());
144
+ logger.debug('Traces sent:', responseText);
119
145
  }
120
146
  else {
121
- logger.error('Failed to send trace:', await response.text());
147
+ logger.error('Failed to send trace:', responseText);
122
148
  }
123
149
  }
124
150
  catch (err) {
package/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@graphql-yoga/plugin-apollo-usage-report",
3
- "version": "0.2.0-alpha-20241004073709-b5c42658",
3
+ "version": "0.2.0",
4
4
  "description": "Apollo's GraphOS usage report plugin for GraphQL Yoga.",
5
5
  "peerDependencies": {
6
6
  "@graphql-tools/utils": "^10.0.0",
7
- "@whatwg-node/fetch": "^0.9.17",
7
+ "@whatwg-node/fetch": "^0.9.22",
8
8
  "graphql": "^15.2.0 || ^16.0.0",
9
- "graphql-yoga": "^5.8.0-alpha-20241004073709-b5c42658"
9
+ "graphql-yoga": "^5.8.0"
10
10
  },
11
11
  "dependencies": {
12
12
  "@apollo/usage-reporting-protobuf": "^4.1.1",
13
13
  "tslib": "^2.5.2",
14
- "@graphql-yoga/plugin-apollo-inline-trace": "^3.8.0-alpha-20241004073709-b5c42658"
14
+ "@graphql-yoga/plugin-apollo-inline-trace": "^3.8.0"
15
15
  },
16
16
  "repository": {
17
17
  "type": "git",
@@ -1,4 +1,4 @@
1
- import { Plugin, YogaInitialContext } from 'graphql-yoga';
1
+ import { Maybe, Plugin, YogaInitialContext } from 'graphql-yoga';
2
2
  import { ApolloInlineGraphqlTraceContext, ApolloInlineRequestTraceContext, ApolloInlineTracePluginOptions } from '@graphql-yoga/plugin-apollo-inline-trace';
3
3
  type ApolloUsageReportOptions = ApolloInlineTracePluginOptions & {
4
4
  /**
@@ -25,6 +25,18 @@ type ApolloUsageReportOptions = ApolloInlineTracePluginOptions & {
25
25
  * Defaults to GraphOS endpoint (https://usage-reporting.api.apollographql.com/api/ingress/traces)
26
26
  */
27
27
  endpoint?: string;
28
+ /**
29
+ * Agent Version to report to the usage reporting API
30
+ */
31
+ agentVersion?: string;
32
+ /**
33
+ * Client name to report to the usage reporting API
34
+ */
35
+ clientName?: StringFromRequestFn | string;
36
+ /**
37
+ * Client version to report to the usage reporting API
38
+ */
39
+ clientVersion?: StringFromRequestFn | string;
28
40
  };
29
41
  export interface ApolloUsageReportRequestContext extends ApolloInlineRequestTraceContext {
30
42
  traces: Map<YogaInitialContext, ApolloUsageReportGraphqlContext>;
@@ -33,6 +45,7 @@ export interface ApolloUsageReportGraphqlContext extends ApolloInlineGraphqlTrac
33
45
  operationKey?: string;
34
46
  schemaId?: string;
35
47
  }
48
+ type StringFromRequestFn = (req: Request) => Maybe<string>;
36
49
  export declare function useApolloUsageReport(options?: ApolloUsageReportOptions): Plugin;
37
50
  export declare function hashSHA256(str: string, api?: {
38
51
  crypto: Crypto;
@@ -1,4 +1,4 @@
1
- import { Plugin, YogaInitialContext } from 'graphql-yoga';
1
+ import { Maybe, Plugin, YogaInitialContext } from 'graphql-yoga';
2
2
  import { ApolloInlineGraphqlTraceContext, ApolloInlineRequestTraceContext, ApolloInlineTracePluginOptions } from '@graphql-yoga/plugin-apollo-inline-trace';
3
3
  type ApolloUsageReportOptions = ApolloInlineTracePluginOptions & {
4
4
  /**
@@ -25,6 +25,18 @@ type ApolloUsageReportOptions = ApolloInlineTracePluginOptions & {
25
25
  * Defaults to GraphOS endpoint (https://usage-reporting.api.apollographql.com/api/ingress/traces)
26
26
  */
27
27
  endpoint?: string;
28
+ /**
29
+ * Agent Version to report to the usage reporting API
30
+ */
31
+ agentVersion?: string;
32
+ /**
33
+ * Client name to report to the usage reporting API
34
+ */
35
+ clientName?: StringFromRequestFn | string;
36
+ /**
37
+ * Client version to report to the usage reporting API
38
+ */
39
+ clientVersion?: StringFromRequestFn | string;
28
40
  };
29
41
  export interface ApolloUsageReportRequestContext extends ApolloInlineRequestTraceContext {
30
42
  traces: Map<YogaInitialContext, ApolloUsageReportGraphqlContext>;
@@ -33,6 +45,7 @@ export interface ApolloUsageReportGraphqlContext extends ApolloInlineGraphqlTrac
33
45
  operationKey?: string;
34
46
  schemaId?: string;
35
47
  }
48
+ type StringFromRequestFn = (req: Request) => Maybe<string>;
36
49
  export declare function useApolloUsageReport(options?: ApolloUsageReportOptions): Plugin;
37
50
  export declare function hashSHA256(str: string, api?: {
38
51
  crypto: Crypto;