@faststore/api 1.12.41 → 1.12.43

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/dist/api.esm.js CHANGED
@@ -4,12 +4,21 @@ import DataLoader from 'dataloader';
4
4
  import pLimit from 'p-limit';
5
5
  import deepEquals from 'fast-deep-equal';
6
6
  import crypto from 'crypto';
7
- import { GraphQLScalarType, print } from 'graphql';
7
+ import { GraphQLScalarType, print, Kind as Kind$1 } from 'graphql';
8
8
  import { Kind } from 'graphql/language';
9
9
  import { mapSchema, MapperKind, getDirective } from '@graphql-tools/utils';
10
+ import { BasicTracerProvider, SimpleSpanProcessor, ConsoleSpanExporter } from '@opentelemetry/sdk-trace-base';
11
+ import { Resource } from '@opentelemetry/resources';
12
+ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';
13
+ import { LoggerProvider, SimpleLogRecordProcessor, ConsoleLogRecordExporter } from '@opentelemetry/sdk-logs';
14
+ import { OTLPLogsExporter } from '@opentelemetry/exporter-logs-otlp-grpc';
15
+ import { isAsyncIterable } from '@envelop/core';
16
+ import { useOnResolve } from '@envelop/on-resolve';
17
+ import { trace, context, SpanKind } from '@opentelemetry/api';
18
+ import { SeverityNumber } from '@opentelemetry/api-logs';
10
19
 
11
20
  var name = "@faststore/api";
12
- var version = "1.12.40";
21
+ var version = "1.12.42";
13
22
  var license = "MIT";
14
23
  var main = "dist/index.js";
15
24
  var typings = "dist/index.d.ts";
@@ -31,7 +40,12 @@ var scripts = {
31
40
  generate: "graphql-codegen --config codegen.yml"
32
41
  };
33
42
  var dependencies = {
43
+ "@envelop/on-resolve": "^2.0.6",
34
44
  "@graphql-tools/schema": "^8.2.0",
45
+ "@opentelemetry/exporter-logs-otlp-grpc": "^0.39.1",
46
+ "@opentelemetry/exporter-trace-otlp-grpc": "^0.39.1",
47
+ "@opentelemetry/sdk-logs": "^0.39.1",
48
+ "@opentelemetry/sdk-trace-base": "^1.13.0",
35
49
  "@rollup/plugin-graphql": "^1.0.0",
36
50
  dataloader: "^2.1.0",
37
51
  "fast-deep-equal": "^3.1.3",
@@ -39,6 +53,7 @@ var dependencies = {
39
53
  "p-limit": "^3.1.0"
40
54
  };
41
55
  var devDependencies = {
56
+ "@envelop/core": "^2.6.0",
42
57
  "@faststore/shared": "^1.12.37",
43
58
  "@graphql-codegen/cli": "2.2.0",
44
59
  "@graphql-codegen/typescript": "2.2.2",
@@ -53,6 +68,7 @@ var devDependencies = {
53
68
  typescript: "^4.4.2"
54
69
  };
55
70
  var peerDependencies = {
71
+ "@envelop/core": "^1 || ^2",
56
72
  graphql: "^15.6.0"
57
73
  };
58
74
  var packageJson = {
@@ -153,6 +169,14 @@ const VtexCommerce = ({
153
169
  id,
154
170
  body
155
171
  }) => {
172
+ if (body.selectedAddresses) {
173
+ body.selectedAddresses.forEach(address => {
174
+ if (address.geoCoordinates === null) {
175
+ address.geoCoordinates = [];
176
+ }
177
+ });
178
+ }
179
+
156
180
  return fetchAPI(`${base}/api/checkout/pub/orderForm/${id}/attachments/shippingData`, { ...BASE_INIT,
157
181
  body: JSON.stringify(body)
158
182
  });
@@ -2628,6 +2652,268 @@ const directive = {
2628
2652
  })
2629
2653
  };
2630
2654
 
2655
+ var AttributeName;
2656
+
2657
+ (function (AttributeName) {
2658
+ AttributeName["EXECUTION_ERROR"] = "graphql.error";
2659
+ AttributeName["EXECUTION_RESULT"] = "graphql.result";
2660
+ AttributeName["RESOLVER_EXECUTION_ERROR"] = "graphql.resolver.error";
2661
+ AttributeName["RESOLVER_EXCEPTION"] = "graphql.resolver.exception";
2662
+ AttributeName["RESOLVER_FIELD_NAME"] = "graphql.resolver.fieldName";
2663
+ AttributeName["RESOLVER_TYPE_NAME"] = "graphql.resolver.typeName";
2664
+ AttributeName["RESOLVER_RESULT_TYPE"] = "graphql.resolver.resultType";
2665
+ AttributeName["RESOLVER_ARGS"] = "graphql.resolver.args";
2666
+ AttributeName["EXECUTION_OPERATION_NAME"] = "graphql.operation.name";
2667
+ AttributeName["EXECUTION_OPERATION_TYPE"] = "graphql.operation.type";
2668
+ AttributeName["EXECUTION_OPERATION_DOCUMENT"] = "graphql.document";
2669
+ AttributeName["EXECUTION_VARIABLES"] = "graphql.variables";
2670
+ })(AttributeName || (AttributeName = {}));
2671
+
2672
+ const tracingSpanSymbol = /*#__PURE__*/Symbol('OPEN_TELEMETRY_GRAPHQL');
2673
+
2674
+ function getResolverSpanKey(path) {
2675
+ const nodes = []; // If the first node (after reversed, it will be the last one) is an integer, that is, identifies a list,
2676
+ // we don't want to include it in the key. Note that this will only happen when analysing .prev paths in
2677
+ // a list of elements. We just want to remove the initial node that is a integer, not all of them.
2678
+ //
2679
+ // Nodes with keys 6bc73341b2a183fc::product::image::0::url would not be able to find
2680
+ // parents with key 6bc73341b2a183fc::product::image because of the "0" list index -
2681
+ // it would search for 6bc73341b2a183fc::product::image::0
2682
+
2683
+ let currentPath = nodes.length === 0 && Number.isInteger(path.key) ? path.prev : path;
2684
+
2685
+ while (currentPath) {
2686
+ nodes.push(currentPath.key);
2687
+ currentPath = currentPath.prev;
2688
+ }
2689
+
2690
+ return [...nodes].reverse().join('.');
2691
+ }
2692
+
2693
+ const getFaststoreTelemetryPlugin = (tracingProvider, loggerProvider, serviceName, experimentalSendLogs) => {
2694
+ return function useFaststoreTelemetry() {
2695
+ const tracer = tracingProvider.getTracer(serviceName);
2696
+ const logger = loggerProvider.getLogger(serviceName);
2697
+ const resolverContextsByRootSpans = {};
2698
+ return {
2699
+ onPluginInit({
2700
+ addPlugin
2701
+ }) {
2702
+ addPlugin( // eslint-disable-next-line
2703
+ useOnResolve(({
2704
+ info,
2705
+ context: context$1
2706
+ }) => {
2707
+ if (context$1 && typeof context$1 === 'object' && context$1[tracingSpanSymbol]) {
2708
+ var _path$prev, _path$prev2;
2709
+
2710
+ tracer.getActiveSpanProcessor();
2711
+ const rootContextSpanId = context$1[tracingSpanSymbol].spanContext().spanId;
2712
+ const {
2713
+ fieldName,
2714
+ returnType,
2715
+ parentType,
2716
+ path
2717
+ } = info;
2718
+ const previousResolverSpanKey = path.prev && getResolverSpanKey(path.prev);
2719
+ let ctx = null;
2720
+
2721
+ if (previousResolverSpanKey && resolverContextsByRootSpans[rootContextSpanId][previousResolverSpanKey]) {
2722
+ ctx = resolverContextsByRootSpans[rootContextSpanId][previousResolverSpanKey];
2723
+ } else {
2724
+ var _resolverContextsByRo;
2725
+
2726
+ ctx = trace.setSpan(context.active(), context$1[tracingSpanSymbol]);
2727
+ resolverContextsByRootSpans[rootContextSpanId] = (_resolverContextsByRo = resolverContextsByRootSpans[rootContextSpanId]) != null ? _resolverContextsByRo : {};
2728
+ }
2729
+
2730
+ const resolverIndexInList = Number.isInteger((_path$prev = path.prev) == null ? void 0 : _path$prev.key) ? `[${(_path$prev2 = path.prev) == null ? void 0 : _path$prev2.key}]` : '';
2731
+ const resolverSpan = tracer.startSpan(`${parentType.toString()}.${fieldName}${resolverIndexInList}`, {
2732
+ attributes: {
2733
+ [AttributeName.RESOLVER_FIELD_NAME]: fieldName,
2734
+ [AttributeName.RESOLVER_TYPE_NAME]: parentType.toString(),
2735
+ [AttributeName.RESOLVER_RESULT_TYPE]: returnType.toString(),
2736
+ 'meta.span.path': getResolverSpanKey(path)
2737
+ }
2738
+ }, ctx);
2739
+ const resolverCtx = trace.setSpan(ctx, resolverSpan);
2740
+ resolverContextsByRootSpans[rootContextSpanId][getResolverSpanKey(path)] = resolverCtx;
2741
+ return ({
2742
+ result
2743
+ }) => {
2744
+ if (result instanceof Error) {
2745
+ resolverSpan.setAttributes({
2746
+ error: true,
2747
+ 'exception.category': AttributeName.RESOLVER_EXECUTION_ERROR,
2748
+ 'exception.message': result.message,
2749
+ 'exception.type': result.name
2750
+ });
2751
+ resolverSpan.recordException(result);
2752
+ }
2753
+
2754
+ resolverSpan.end();
2755
+ };
2756
+ } // eslint-disable-next-line @typescript-eslint/no-empty-function
2757
+
2758
+
2759
+ return () => {};
2760
+ }));
2761
+ },
2762
+
2763
+ onExecute({
2764
+ args,
2765
+ extendContext
2766
+ }) {
2767
+ var _args$document$defini, _args$operationName;
2768
+
2769
+ const operationType = (_args$document$defini = args.document.definitions.filter(def => def.kind === Kind$1.OPERATION_DEFINITION).map(def => def.operation)) == null ? void 0 : _args$document$defini[0]; // Span name according to Semantic Conventions
2770
+ // https://github.com/open-telemetry/semantic-conventions
2771
+
2772
+ let spanName = 'GraphQL Operation';
2773
+
2774
+ if (operationType && args.operationName) {
2775
+ spanName = `${operationType} ${args.operationName}`;
2776
+ } else if (operationType && !args.operationName) {
2777
+ spanName = operationType;
2778
+ }
2779
+
2780
+ const executionSpan = tracer.startSpan(spanName, {
2781
+ kind: SpanKind.SERVER,
2782
+ attributes: {
2783
+ [AttributeName.EXECUTION_OPERATION_NAME]: (_args$operationName = args.operationName) != null ? _args$operationName : undefined,
2784
+ [AttributeName.EXECUTION_OPERATION_TYPE]: operationType != null ? operationType : undefined,
2785
+ [AttributeName.EXECUTION_OPERATION_DOCUMENT]: print(args.document)
2786
+ }
2787
+ });
2788
+ const executeContext = context.active();
2789
+ const resultCbs = {
2790
+ onExecuteDone({
2791
+ result
2792
+ }) {
2793
+ var _args$operationName2, _args$variableValues;
2794
+
2795
+ if (isAsyncIterable(result)) {
2796
+ executionSpan.end(); // eslint-disable-next-line no-console
2797
+
2798
+ console.warn(`Plugin "newrelic" encountered a AsyncIterator which is not supported yet, so tracing data is not available for the operation.`);
2799
+ return;
2800
+ }
2801
+
2802
+ const logRecord = {
2803
+ context: executeContext,
2804
+ attributes: {
2805
+ 'service.name': 'faststore-api',
2806
+ 'service.version': '1.12.38',
2807
+ 'service.name_and_version': 'faststore-api@1.12.38',
2808
+ 'vtex.search_index': 'faststore_beta_api',
2809
+ [AttributeName.EXECUTION_OPERATION_NAME]: (_args$operationName2 = args.operationName) != null ? _args$operationName2 : undefined,
2810
+ [AttributeName.EXECUTION_OPERATION_DOCUMENT]: print(args.document),
2811
+ [AttributeName.EXECUTION_VARIABLES]: JSON.stringify((_args$variableValues = args.variableValues) != null ? _args$variableValues : {})
2812
+ }
2813
+ };
2814
+
2815
+ if (typeof result.data !== 'undefined' && !(result.errors && result.errors.length > 0)) {
2816
+ logRecord.severityNumber = SeverityNumber.INFO;
2817
+ logRecord.severityText = 'Info';
2818
+ logRecord.attributes[AttributeName.EXECUTION_RESULT] = JSON.stringify(result);
2819
+ }
2820
+
2821
+ if (result.errors && result.errors.length > 0) {
2822
+ logRecord.severityNumber = SeverityNumber.ERROR;
2823
+ logRecord.severityText = 'Error';
2824
+ logRecord.attributes[AttributeName.EXECUTION_ERROR] = JSON.stringify(result.errors);
2825
+ executionSpan.setAttributes({
2826
+ error: true,
2827
+ 'exception.category': AttributeName.EXECUTION_ERROR,
2828
+ 'exception.message': JSON.stringify(result.errors)
2829
+ });
2830
+ }
2831
+
2832
+ if (experimentalSendLogs) {
2833
+ logger.emit(logRecord);
2834
+ }
2835
+
2836
+ executionSpan.end();
2837
+ }
2838
+
2839
+ };
2840
+ extendContext({
2841
+ [tracingSpanSymbol]: executionSpan
2842
+ });
2843
+ return resultCbs;
2844
+ }
2845
+
2846
+ };
2847
+ };
2848
+ };
2849
+
2850
+ const FASTSTORE_API_VERSION = packageJson.version; // TODO: These urls are hardcoded for now, but they should be configurable via ENV variables
2851
+ // They are only acessible from within the VTEX network, so they are not a security risk
2852
+
2853
+ const TRACE_COLLECTOR_URL = 'opentelemetry-collector.vtex.systems';
2854
+ const TRACE_COLLECTOR_URL_DEV = 'opentelemetry-collector-beta.vtex.systems';
2855
+ const LOG_COLLECTOR_URL = 'opentelemetry-collector.vtex.systems';
2856
+ function getTelemetry(APIOptions, telemetryOptions) {
2857
+ var _telemetryOptions$exp;
2858
+
2859
+ const honeycombCollectorOptions = {
2860
+ url: (telemetryOptions == null ? void 0 : telemetryOptions.mode) === 'dev' ? TRACE_COLLECTOR_URL_DEV : TRACE_COLLECTOR_URL
2861
+ };
2862
+ const openSearchCollectorOptions = {
2863
+ url: LOG_COLLECTOR_URL
2864
+ }; // Create a new tracer provider
2865
+
2866
+ const tracerProvider = new BasicTracerProvider({
2867
+ resource: new Resource({
2868
+ 'service.name': 'faststore-api',
2869
+ 'service.version': FASTSTORE_API_VERSION,
2870
+ 'service.name_and_version': `faststore-api@${FASTSTORE_API_VERSION}`,
2871
+ platform: APIOptions.platform,
2872
+ [`${APIOptions.platform}.account`]: APIOptions.account,
2873
+ [`${APIOptions.platform}.environment`]: APIOptions.environment,
2874
+ // TODO: include the following properties in the logs
2875
+ // [`${APIOptions.platform}.options.hideUnavailableItems`]:
2876
+ // APIOptions.hideUnavailableItems,
2877
+ // [`${APIOptions.platform}.flags.enableOrderFormSync`]:
2878
+ // APIOptions.flags?.enableOrderFormSync,
2879
+ // channel: APIOptions.channel,
2880
+ locale: APIOptions.locale
2881
+ })
2882
+ });
2883
+ const loggerProvider = new LoggerProvider(); // Create trace exporter
2884
+
2885
+ const honeycombExporter = new OTLPTraceExporter(honeycombCollectorOptions); // Create log exporter
2886
+
2887
+ const openSearchExporter = new OTLPLogsExporter(openSearchCollectorOptions); // Set up a span processor to export spans to Honeycomb
2888
+
2889
+ const honeyCombSpanProcessor = new SimpleSpanProcessor(honeycombExporter); // Set up a log record processor to export spans to OpenSearch
2890
+
2891
+ const openSearchLogProcessor = new SimpleLogRecordProcessor(openSearchExporter); // Register the span processor with the tracer provider
2892
+
2893
+ tracerProvider.addSpanProcessor(honeyCombSpanProcessor); // Register the log record processor with the log provider
2894
+
2895
+ loggerProvider.addLogRecordProcessor(openSearchLogProcessor);
2896
+
2897
+ if ((telemetryOptions == null ? void 0 : telemetryOptions.mode) === 'verbose' || (telemetryOptions == null ? void 0 : telemetryOptions.mode) === 'dev') {
2898
+ // Set up a console exporter for verbose mode
2899
+ const consoleExporter = new ConsoleSpanExporter();
2900
+ const verboseTraceProcessor = new SimpleSpanProcessor(consoleExporter); // Set up processors for verbose mode
2901
+
2902
+ const consoleLogExporter = new ConsoleLogRecordExporter();
2903
+ const veboseLogRecordExporter = new SimpleLogRecordProcessor(consoleLogExporter);
2904
+ tracerProvider.addSpanProcessor(verboseTraceProcessor);
2905
+ loggerProvider.addLogRecordProcessor(veboseLogRecordExporter);
2906
+ }
2907
+
2908
+ const useFaststoreTelemetry = getFaststoreTelemetryPlugin( // The @opentelemetry/sdk-trace-base was renamed from @opentelemetry/tracing but the
2909
+ // envelop plugin doesn't support this change yet. This causes the class type to be incompatible,
2910
+ // even if they are the same. https://github.com/n1ru4l/envelop/issues/1610
2911
+ tracerProvider, loggerProvider, 'faststore-api', (_telemetryOptions$exp = telemetryOptions == null ? void 0 : telemetryOptions.experimentalSendLogs) != null ? _telemetryOptions$exp : false);
2912
+ return {
2913
+ useFaststoreTelemetry
2914
+ };
2915
+ }
2916
+
2631
2917
  const platforms = {
2632
2918
  vtex: {
2633
2919
  getResolvers: getResolvers,
@@ -2646,5 +2932,5 @@ const getSchema = async options => {
2646
2932
  return directives.reduce((s, d) => d.transformer(s), schema);
2647
2933
  };
2648
2934
 
2649
- export { BadRequestError, NotFoundError, getContextFactory$1 as getContextFactory, getResolvers$1 as getResolvers, getSchema, getTypeDefs, isBadRequestError, isFastStoreError, isNotFoundError, stringify$1 as stringifyCacheControl };
2935
+ export { BadRequestError, NotFoundError, getContextFactory$1 as getContextFactory, getResolvers$1 as getResolvers, getSchema, getTelemetry, getTypeDefs, isBadRequestError, isFastStoreError, isNotFoundError, stringify$1 as stringifyCacheControl };
2650
2936
  //# sourceMappingURL=api.esm.js.map