@commercetools-frontend/application-shell-connectors 0.0.0-CRAFT-1791-20251006162610
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/LICENSE +21 -0
- package/README.md +16 -0
- package/dist/commercetools-frontend-application-shell-connectors.cjs.d.ts +2 -0
- package/dist/commercetools-frontend-application-shell-connectors.cjs.dev.js +1105 -0
- package/dist/commercetools-frontend-application-shell-connectors.cjs.js +7 -0
- package/dist/commercetools-frontend-application-shell-connectors.cjs.prod.js +1098 -0
- package/dist/commercetools-frontend-application-shell-connectors.esm.js +1038 -0
- package/dist/declarations/src/components/application-context/application-context.d.ts +109 -0
- package/dist/declarations/src/components/application-context/index.d.ts +10 -0
- package/dist/declarations/src/components/application-context/normalizers.d.ts +48 -0
- package/dist/declarations/src/components/custom-view-context/custom-view-context.d.ts +19 -0
- package/dist/declarations/src/components/custom-view-context/index.d.ts +4 -0
- package/dist/declarations/src/components/project-extension-image-regex/index.d.ts +3 -0
- package/dist/declarations/src/components/project-extension-image-regex/project-extension-image-regex.d.ts +37 -0
- package/dist/declarations/src/configure-apollo.d.ts +7 -0
- package/dist/declarations/src/export-types.d.ts +21 -0
- package/dist/declarations/src/hooks/apollo-hooks/apollo-hooks.d.ts +12 -0
- package/dist/declarations/src/hooks/apollo-hooks/index.d.ts +1 -0
- package/dist/declarations/src/hooks/custom-views/use-custom-view-parent-data-refresher.d.ts +5 -0
- package/dist/declarations/src/index.d.ts +12 -0
- package/dist/declarations/src/test-utils/index.d.ts +1 -0
- package/dist/declarations/src/test-utils/test-utils.d.ts +56 -0
- package/dist/declarations/src/types/generated/mc.d.ts +742 -0
- package/dist/declarations/src/types/generated/settings.d.ts +2116 -0
- package/dist/declarations/src/utils/apollo-client-runtime-cache.d.ts +4 -0
- package/dist/declarations/src/utils/apollo-context.d.ts +16 -0
- package/dist/declarations/src/utils/get-correlation-id/get-correlation-id.d.ts +3 -0
- package/dist/declarations/src/utils/get-correlation-id/index.d.ts +1 -0
- package/dist/declarations/src/utils/get-mc-api-url/get-mc-api-url.d.ts +3 -0
- package/dist/declarations/src/utils/get-mc-api-url/index.d.ts +1 -0
- package/dist/declarations/src/utils/http-client.d.ts +107 -0
- package/dist/declarations/src/utils/index.d.ts +7 -0
- package/dist/declarations/src/utils/logger.d.ts +10 -0
- package/dist/declarations/src/utils/oidc-storage.d.ts +12 -0
- package/dist/declarations/src/utils/select-project-key-from-url/index.d.ts +1 -0
- package/dist/declarations/src/utils/select-project-key-from-url/select-project-key-from-url.d.ts +1 -0
- package/dist/declarations/src/utils/select-team-id-from-storage/index.d.ts +1 -0
- package/dist/declarations/src/utils/select-team-id-from-storage/select-team-id-from-storage.d.ts +1 -0
- package/dist/declarations/src/utils/select-user-id/index.d.ts +1 -0
- package/dist/declarations/src/utils/select-user-id/select-user-id.d.ts +1 -0
- package/dist/declarations/src/version.d.ts +2 -0
- package/package.json +76 -0
- package/test-utils/dist/commercetools-frontend-application-shell-connectors-test-utils.cjs.d.ts +2 -0
- package/test-utils/dist/commercetools-frontend-application-shell-connectors-test-utils.cjs.dev.js +70 -0
- package/test-utils/dist/commercetools-frontend-application-shell-connectors-test-utils.cjs.js +7 -0
- package/test-utils/dist/commercetools-frontend-application-shell-connectors-test-utils.cjs.prod.js +70 -0
- package/test-utils/dist/commercetools-frontend-application-shell-connectors-test-utils.esm.js +54 -0
- package/test-utils/package.json +4 -0
|
@@ -0,0 +1,1105 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
var _Object$keys = require('@babel/runtime-corejs3/core-js-stable/object/keys');
|
|
6
|
+
var _Object$getOwnPropertySymbols = require('@babel/runtime-corejs3/core-js-stable/object/get-own-property-symbols');
|
|
7
|
+
var _filterInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/filter');
|
|
8
|
+
var _Object$getOwnPropertyDescriptor = require('@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor');
|
|
9
|
+
var _forEachInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/for-each');
|
|
10
|
+
var _Object$getOwnPropertyDescriptors = require('@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptors');
|
|
11
|
+
var _Object$defineProperties = require('@babel/runtime-corejs3/core-js-stable/object/define-properties');
|
|
12
|
+
var _Object$defineProperty = require('@babel/runtime-corejs3/core-js-stable/object/define-property');
|
|
13
|
+
var _defineProperty = require('@babel/runtime-corejs3/helpers/defineProperty');
|
|
14
|
+
var react = require('react');
|
|
15
|
+
var moment = require('moment-timezone');
|
|
16
|
+
var sentry = require('@commercetools-frontend/sentry');
|
|
17
|
+
var _URL = require('@babel/runtime-corejs3/core-js-stable/url');
|
|
18
|
+
var _slicedToArray = require('@babel/runtime-corejs3/helpers/slicedToArray');
|
|
19
|
+
var _reduceInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/reduce');
|
|
20
|
+
var _Object$entries = require('@babel/runtime-corejs3/core-js-stable/object/entries');
|
|
21
|
+
var _valuesInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/values');
|
|
22
|
+
var jsxRuntime = require('@emotion/react/jsx-runtime');
|
|
23
|
+
var _includesInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/includes');
|
|
24
|
+
var constants = require('@commercetools-frontend/constants');
|
|
25
|
+
var react$1 = require('@apollo/client/react');
|
|
26
|
+
var warning = require('tiny-warning');
|
|
27
|
+
var _findInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/find');
|
|
28
|
+
var client = require('@apollo/client');
|
|
29
|
+
var loggerLink = require('apollo-link-logger');
|
|
30
|
+
var error = require('@apollo/client/link/error');
|
|
31
|
+
var history = require('@commercetools-frontend/browser-history');
|
|
32
|
+
var _Array$isArray = require('@babel/runtime-corejs3/core-js-stable/array/is-array');
|
|
33
|
+
var _someInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/some');
|
|
34
|
+
var _Object$values = require('@babel/runtime-corejs3/core-js-stable/object/values');
|
|
35
|
+
var _mapInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/map');
|
|
36
|
+
var createHttpUserAgent = require('@commercetools/http-user-agent');
|
|
37
|
+
var omitEmpty = require('omit-empty-es');
|
|
38
|
+
var uuid = require('uuid');
|
|
39
|
+
var _Reflect$construct = require('@babel/runtime-corejs3/core-js-stable/reflect/construct');
|
|
40
|
+
var _createClass = require('@babel/runtime-corejs3/helpers/createClass');
|
|
41
|
+
var _classCallCheck = require('@babel/runtime-corejs3/helpers/classCallCheck');
|
|
42
|
+
var _possibleConstructorReturn = require('@babel/runtime-corejs3/helpers/possibleConstructorReturn');
|
|
43
|
+
var _getPrototypeOf = require('@babel/runtime-corejs3/helpers/getPrototypeOf');
|
|
44
|
+
var _inherits = require('@babel/runtime-corejs3/helpers/inherits');
|
|
45
|
+
var _wrapNativeSuper = require('@babel/runtime-corejs3/helpers/wrapNativeSuper');
|
|
46
|
+
var _JSON$stringify = require('@babel/runtime-corejs3/core-js-stable/json/stringify');
|
|
47
|
+
var retry = require('@apollo/client/link/retry');
|
|
48
|
+
|
|
49
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
|
|
50
|
+
|
|
51
|
+
var _Object$keys__default = /*#__PURE__*/_interopDefault(_Object$keys);
|
|
52
|
+
var _Object$getOwnPropertySymbols__default = /*#__PURE__*/_interopDefault(_Object$getOwnPropertySymbols);
|
|
53
|
+
var _filterInstanceProperty__default = /*#__PURE__*/_interopDefault(_filterInstanceProperty);
|
|
54
|
+
var _Object$getOwnPropertyDescriptor__default = /*#__PURE__*/_interopDefault(_Object$getOwnPropertyDescriptor);
|
|
55
|
+
var _forEachInstanceProperty__default = /*#__PURE__*/_interopDefault(_forEachInstanceProperty);
|
|
56
|
+
var _Object$getOwnPropertyDescriptors__default = /*#__PURE__*/_interopDefault(_Object$getOwnPropertyDescriptors);
|
|
57
|
+
var _Object$defineProperties__default = /*#__PURE__*/_interopDefault(_Object$defineProperties);
|
|
58
|
+
var _Object$defineProperty__default = /*#__PURE__*/_interopDefault(_Object$defineProperty);
|
|
59
|
+
var moment__default = /*#__PURE__*/_interopDefault(moment);
|
|
60
|
+
var _URL__default = /*#__PURE__*/_interopDefault(_URL);
|
|
61
|
+
var _reduceInstanceProperty__default = /*#__PURE__*/_interopDefault(_reduceInstanceProperty);
|
|
62
|
+
var _Object$entries__default = /*#__PURE__*/_interopDefault(_Object$entries);
|
|
63
|
+
var _valuesInstanceProperty__default = /*#__PURE__*/_interopDefault(_valuesInstanceProperty);
|
|
64
|
+
var _includesInstanceProperty__default = /*#__PURE__*/_interopDefault(_includesInstanceProperty);
|
|
65
|
+
var warning__default = /*#__PURE__*/_interopDefault(warning);
|
|
66
|
+
var _findInstanceProperty__default = /*#__PURE__*/_interopDefault(_findInstanceProperty);
|
|
67
|
+
var loggerLink__default = /*#__PURE__*/_interopDefault(loggerLink);
|
|
68
|
+
var history__default = /*#__PURE__*/_interopDefault(history);
|
|
69
|
+
var _Array$isArray__default = /*#__PURE__*/_interopDefault(_Array$isArray);
|
|
70
|
+
var _someInstanceProperty__default = /*#__PURE__*/_interopDefault(_someInstanceProperty);
|
|
71
|
+
var _Object$values__default = /*#__PURE__*/_interopDefault(_Object$values);
|
|
72
|
+
var _mapInstanceProperty__default = /*#__PURE__*/_interopDefault(_mapInstanceProperty);
|
|
73
|
+
var createHttpUserAgent__default = /*#__PURE__*/_interopDefault(createHttpUserAgent);
|
|
74
|
+
var omitEmpty__default = /*#__PURE__*/_interopDefault(omitEmpty);
|
|
75
|
+
var _Reflect$construct__default = /*#__PURE__*/_interopDefault(_Reflect$construct);
|
|
76
|
+
var _JSON$stringify__default = /*#__PURE__*/_interopDefault(_JSON$stringify);
|
|
77
|
+
|
|
78
|
+
// NOTE: This string will be replaced on build time with the package version.
|
|
79
|
+
var version = "24.7.2";
|
|
80
|
+
|
|
81
|
+
// From https://github.com/acdlite/recompose/blob/master/src/packages/recompose/getDisplayName.js
|
|
82
|
+
const getDisplayName = Component => {
|
|
83
|
+
if (typeof Component === 'string') {
|
|
84
|
+
return Component;
|
|
85
|
+
}
|
|
86
|
+
if (!Component) {
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
return Component.displayName || Component.name || 'Component';
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const mcHostnameRegex = /^mc(-(\d){4,})?\.(.*)$/;
|
|
93
|
+
const mcPreviewHostnameRegex = /^.*\.mc-preview\.(.*)$/;
|
|
94
|
+
const getMcOriginTld = host => {
|
|
95
|
+
if (host.match(mcPreviewHostnameRegex)) {
|
|
96
|
+
return host.replace(mcPreviewHostnameRegex, '$1');
|
|
97
|
+
}
|
|
98
|
+
return host.replace(mcHostnameRegex, '$3');
|
|
99
|
+
};
|
|
100
|
+
const getMcApiUrlFromOrigin = origin => {
|
|
101
|
+
const url = new _URL__default["default"](origin);
|
|
102
|
+
const originTld = getMcOriginTld(url.host);
|
|
103
|
+
return `${url.protocol}//mc-api.${originTld}`;
|
|
104
|
+
};
|
|
105
|
+
const parseAsBoolean = value => value === true || value === 'true';
|
|
106
|
+
function getMcApiUrl() {
|
|
107
|
+
let environment = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window.app;
|
|
108
|
+
let origin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.origin;
|
|
109
|
+
const isServedByProxy = parseAsBoolean(environment.servedByProxy);
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Prefer using the origin URL for the MC API based on the origin value
|
|
113
|
+
* of the browser's `window.location`.
|
|
114
|
+
* This ensures that the application always uses the correct URL associated
|
|
115
|
+
* with that environment, instead of relying on the config value.
|
|
116
|
+
*/
|
|
117
|
+
if (isServedByProxy) {
|
|
118
|
+
return getMcApiUrlFromOrigin(origin);
|
|
119
|
+
}
|
|
120
|
+
return environment.mcApiUrl;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function ownKeys$7(e, r) { var t = _Object$keys__default["default"](e); if (_Object$getOwnPropertySymbols__default["default"]) { var o = _Object$getOwnPropertySymbols__default["default"](e); r && (o = _filterInstanceProperty__default["default"](o).call(o, function (r) { return _Object$getOwnPropertyDescriptor__default["default"](e, r).enumerable; })), t.push.apply(t, o); } return t; }
|
|
124
|
+
function _objectSpread$7(e) { for (var r = 1; r < arguments.length; r++) { var _context2, _context3; var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? _forEachInstanceProperty__default["default"](_context2 = ownKeys$7(Object(t), !0)).call(_context2, function (r) { _defineProperty(e, r, t[r]); }) : _Object$getOwnPropertyDescriptors__default["default"] ? _Object$defineProperties__default["default"](e, _Object$getOwnPropertyDescriptors__default["default"](t)) : _forEachInstanceProperty__default["default"](_context3 = ownKeys$7(Object(t))).call(_context3, function (r) { _Object$defineProperty__default["default"](e, r, _Object$getOwnPropertyDescriptor__default["default"](t, r)); }); } return e; }
|
|
125
|
+
// Menu visibilities
|
|
126
|
+
|
|
127
|
+
// Permissions
|
|
128
|
+
|
|
129
|
+
// Action rights
|
|
130
|
+
|
|
131
|
+
// Data fences
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* NOTE:
|
|
135
|
+
*
|
|
136
|
+
* Permissions and menu visibilities are being fetched though the `allAppliedPermissions`
|
|
137
|
+
* and the `allAppliedMenuVisibilities` which both return an array of `{ name: string, value: boolean }`.
|
|
138
|
+
* This gives more flexibility to introduce new values to apps without having to release
|
|
139
|
+
* the merchant-center-app-kit by adding/exposing them from the mc-be (our proxy service).
|
|
140
|
+
*
|
|
141
|
+
* The application below however expects both permissions an menu visibilities to be of the shape
|
|
142
|
+
* `[name: string]: boolean` which is what the shape above is mapped into here. This object shape is easier
|
|
143
|
+
* to work with in application level code (while be a non breaking change to other packages) as you can just
|
|
144
|
+
* do `canViewProducts`.
|
|
145
|
+
*
|
|
146
|
+
* This function considering its concern belongs into the `permissions` package. However,
|
|
147
|
+
* for now it doesn't have to be shared and as a result can be co-located with
|
|
148
|
+
* the fetching logic. Given this mapping needs to be used elsewere feel free
|
|
149
|
+
* to move this over to `permissions` and export it there.
|
|
150
|
+
*/
|
|
151
|
+
const normalizeAllAppliedPermissions = allAppliedPermissions => {
|
|
152
|
+
if (!allAppliedPermissions || allAppliedPermissions.length === 0) {
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
return _reduceInstanceProperty__default["default"](allAppliedPermissions).call(allAppliedPermissions, (transformedAllApplied, allApplied) => {
|
|
156
|
+
if (!allApplied) return transformedAllApplied;
|
|
157
|
+
return _objectSpread$7(_objectSpread$7({}, transformedAllApplied), {}, {
|
|
158
|
+
[allApplied.name]: allApplied.value
|
|
159
|
+
});
|
|
160
|
+
}, {});
|
|
161
|
+
};
|
|
162
|
+
const normalizeAllAppliedMenuVisibilities = allAppliedMenuVisibilities => {
|
|
163
|
+
if (!allAppliedMenuVisibilities || allAppliedMenuVisibilities.length === 0) {
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
return _reduceInstanceProperty__default["default"](allAppliedMenuVisibilities).call(allAppliedMenuVisibilities, (transformedAllApplied, allApplied) => {
|
|
167
|
+
if (!allApplied) return transformedAllApplied;
|
|
168
|
+
return _objectSpread$7(_objectSpread$7({}, transformedAllApplied), {}, {
|
|
169
|
+
[allApplied.name]: allApplied.value
|
|
170
|
+
});
|
|
171
|
+
}, {});
|
|
172
|
+
};
|
|
173
|
+
const normalizeAllAppliedActionRights = allAppliedActionRights => {
|
|
174
|
+
if (!allAppliedActionRights || allAppliedActionRights.length === 0) {
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
return _reduceInstanceProperty__default["default"](allAppliedActionRights).call(allAppliedActionRights, (transformedAllApplied, allApplied) => {
|
|
178
|
+
if (!allApplied) return transformedAllApplied;
|
|
179
|
+
const previousAllAppliedGroup = transformedAllApplied[allApplied.group];
|
|
180
|
+
return _objectSpread$7(_objectSpread$7({}, transformedAllApplied), {}, {
|
|
181
|
+
[allApplied.group]: _objectSpread$7(_objectSpread$7({}, previousAllAppliedGroup), {}, {
|
|
182
|
+
[allApplied.name]: allApplied.value
|
|
183
|
+
})
|
|
184
|
+
});
|
|
185
|
+
}, {});
|
|
186
|
+
};
|
|
187
|
+
const normalizeAppliedDataFencesForStoresByResourceType = dataFences => {
|
|
188
|
+
var _context;
|
|
189
|
+
const groupedByResourceType = _reduceInstanceProperty__default["default"](dataFences).call(dataFences, (previousGroupsOfSameType, appliedDataFence) => {
|
|
190
|
+
if (!appliedDataFence) return previousGroupsOfSameType;
|
|
191
|
+
const previousGroup = previousGroupsOfSameType[appliedDataFence.group];
|
|
192
|
+
return _objectSpread$7(_objectSpread$7({}, previousGroupsOfSameType), {}, {
|
|
193
|
+
[appliedDataFence.group]: [...(previousGroup || []), appliedDataFence]
|
|
194
|
+
});
|
|
195
|
+
}, {});
|
|
196
|
+
return _reduceInstanceProperty__default["default"](_context = _Object$entries__default["default"](groupedByResourceType)).call(_context, (previousGroupedByResourceType, _ref) => {
|
|
197
|
+
let _ref2 = _slicedToArray(_ref, 2),
|
|
198
|
+
resourceType = _ref2[0],
|
|
199
|
+
dataFences = _ref2[1];
|
|
200
|
+
const groupByDataFenceName = _reduceInstanceProperty__default["default"](dataFences).call(dataFences, (nextDataFenceValues, dataFence) => {
|
|
201
|
+
const dataFenceByName = nextDataFenceValues[dataFence.name] || {
|
|
202
|
+
values: []
|
|
203
|
+
};
|
|
204
|
+
return _objectSpread$7(_objectSpread$7({}, nextDataFenceValues), {}, {
|
|
205
|
+
[dataFence.name]: _objectSpread$7(_objectSpread$7({}, dataFenceByName), {}, {
|
|
206
|
+
values: [..._valuesInstanceProperty__default["default"](dataFenceByName), dataFence.value]
|
|
207
|
+
})
|
|
208
|
+
});
|
|
209
|
+
}, {});
|
|
210
|
+
return _objectSpread$7(_objectSpread$7({}, previousGroupedByResourceType), {}, {
|
|
211
|
+
[resourceType]: groupByDataFenceName
|
|
212
|
+
});
|
|
213
|
+
}, {});
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
// input:
|
|
217
|
+
// [
|
|
218
|
+
// {
|
|
219
|
+
// type: 'store',
|
|
220
|
+
// name: 'canManageOrders',
|
|
221
|
+
// value: 'usa',
|
|
222
|
+
// group: 'orders',
|
|
223
|
+
// },
|
|
224
|
+
// {
|
|
225
|
+
// type: 'store',
|
|
226
|
+
// name: 'canManageOrders',
|
|
227
|
+
// value: 'germany',
|
|
228
|
+
// group: 'orders',
|
|
229
|
+
// },
|
|
230
|
+
// {
|
|
231
|
+
// type: 'store',
|
|
232
|
+
// name: 'canViewOrders',
|
|
233
|
+
// value: 'canada',
|
|
234
|
+
// group: 'orders',
|
|
235
|
+
// },
|
|
236
|
+
// ]
|
|
237
|
+
// output:
|
|
238
|
+
// {
|
|
239
|
+
// store: {
|
|
240
|
+
// orders: {
|
|
241
|
+
// canManageOrders: { values: ['usa', 'germany'] },
|
|
242
|
+
// canViewOrders: { values: ['canada'] },
|
|
243
|
+
// }
|
|
244
|
+
// }
|
|
245
|
+
// }
|
|
246
|
+
|
|
247
|
+
const normalizeAllAppliedDataFences = allAppliedDataFences => {
|
|
248
|
+
if (!allAppliedDataFences || allAppliedDataFences.length === 0) {
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
const groupedByType = _reduceInstanceProperty__default["default"](allAppliedDataFences).call(allAppliedDataFences, (previousGroupsOfSameType, appliedDataFence) => {
|
|
252
|
+
if (!appliedDataFence) return previousGroupsOfSameType;
|
|
253
|
+
const previousGroup = previousGroupsOfSameType[appliedDataFence.type];
|
|
254
|
+
return _objectSpread$7(_objectSpread$7({}, previousGroupsOfSameType), {}, {
|
|
255
|
+
[appliedDataFence.type]: [...(previousGroup || []), appliedDataFence]
|
|
256
|
+
});
|
|
257
|
+
}, {});
|
|
258
|
+
const normalizedDataFences = _objectSpread$7({}, 'store' in groupedByType ? {
|
|
259
|
+
store: normalizeAppliedDataFencesForStoresByResourceType(groupedByType.store)
|
|
260
|
+
} : {});
|
|
261
|
+
if (_Object$keys__default["default"](normalizedDataFences).length > 0) return normalizedDataFences;
|
|
262
|
+
return null;
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
function ownKeys$6(e, r) { var t = _Object$keys__default["default"](e); if (_Object$getOwnPropertySymbols__default["default"]) { var o = _Object$getOwnPropertySymbols__default["default"](e); r && (o = _filterInstanceProperty__default["default"](o).call(o, function (r) { return _Object$getOwnPropertyDescriptor__default["default"](e, r).enumerable; })), t.push.apply(t, o); } return t; }
|
|
266
|
+
function _objectSpread$6(e) { for (var r = 1; r < arguments.length; r++) { var _context, _context2; var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? _forEachInstanceProperty__default["default"](_context = ownKeys$6(Object(t), !0)).call(_context, function (r) { _defineProperty(e, r, t[r]); }) : _Object$getOwnPropertyDescriptors__default["default"] ? _Object$defineProperties__default["default"](e, _Object$getOwnPropertyDescriptors__default["default"](t)) : _forEachInstanceProperty__default["default"](_context2 = ownKeys$6(Object(t))).call(_context2, function (r) { _Object$defineProperty__default["default"](e, r, _Object$getOwnPropertyDescriptor__default["default"](t, r)); }); } return e; }
|
|
267
|
+
const Context$2 = /*#__PURE__*/react.createContext({});
|
|
268
|
+
const defaultTimeZone = moment__default["default"].tz.guess() || 'Etc/UTC';
|
|
269
|
+
|
|
270
|
+
// Expose only certain fields as some of them are only meant to
|
|
271
|
+
// be used internally in the AppShell
|
|
272
|
+
const mapUserToApplicationContextUser = user => {
|
|
273
|
+
if (!user) return null;
|
|
274
|
+
let applicationContextUser = {
|
|
275
|
+
id: user.id,
|
|
276
|
+
email: user.email,
|
|
277
|
+
createdAt: user.createdAt,
|
|
278
|
+
firstName: user.firstName,
|
|
279
|
+
lastName: user.lastName,
|
|
280
|
+
businessRole: user.businessRole,
|
|
281
|
+
// NOTE: this is an alias for the original field `user.language` but it's actually
|
|
282
|
+
// a locale (language + country).
|
|
283
|
+
locale: user.language,
|
|
284
|
+
timeZone: user.timeZone || defaultTimeZone,
|
|
285
|
+
projects: user.projects
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
// This property will only be populated when user has logged in using SSO
|
|
289
|
+
if (user.idTokenUserInfo) {
|
|
290
|
+
let additionalClaims = {};
|
|
291
|
+
try {
|
|
292
|
+
additionalClaims = JSON.parse(user.idTokenUserInfo.additionalClaims || '{}');
|
|
293
|
+
} catch (error) {
|
|
294
|
+
sentry.reportErrorToSentry(new Error('@commercetools-frontend/application-shell-connectors: Could not parse received user sso token additional claims from server.'), {
|
|
295
|
+
extra: {
|
|
296
|
+
receivedAdditionalClaims: user.idTokenUserInfo.additionalClaims
|
|
297
|
+
}
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
applicationContextUser.idTokenUserInfo = _objectSpread$6(_objectSpread$6({}, user.idTokenUserInfo), {}, {
|
|
301
|
+
additionalClaims
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
return applicationContextUser;
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
// Adjust certain fields which depend e.g. on the origin
|
|
308
|
+
const mapEnvironmentToApplicationContextEnvironment = (environment, origin) => _objectSpread$6(_objectSpread$6({}, environment), {}, {
|
|
309
|
+
// NOTE: The `mcApiUrl` depends on `servedByProxy`
|
|
310
|
+
mcApiUrl: getMcApiUrl(environment, origin)
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
// Expose only certain fields as some of them are only meant to
|
|
314
|
+
// be used internally in the AppShell
|
|
315
|
+
const mapProjectToApplicationContextProject = project => {
|
|
316
|
+
if (!project) return null;
|
|
317
|
+
return {
|
|
318
|
+
key: project.key,
|
|
319
|
+
version: project.version,
|
|
320
|
+
name: project.name,
|
|
321
|
+
countries: project.countries,
|
|
322
|
+
currencies: project.currencies,
|
|
323
|
+
languages: project.languages,
|
|
324
|
+
ownerId: project.owner.id,
|
|
325
|
+
ownerName: project.owner.name,
|
|
326
|
+
sampleDataImportDataset: project.sampleDataImportDataset,
|
|
327
|
+
isUserAdminOfCurrentProject: project.isUserAdminOfCurrentProject,
|
|
328
|
+
isProductionProject: project.isProductionProject
|
|
329
|
+
};
|
|
330
|
+
};
|
|
331
|
+
const createApplicationContext = (environment, user, project, projectDataLocale) => ({
|
|
332
|
+
environment: mapEnvironmentToApplicationContextEnvironment(environment),
|
|
333
|
+
user: mapUserToApplicationContextUser(user),
|
|
334
|
+
project: mapProjectToApplicationContextProject(project),
|
|
335
|
+
permissions: normalizeAllAppliedPermissions(project?.allAppliedPermissions),
|
|
336
|
+
actionRights: normalizeAllAppliedActionRights(project?.allAppliedActionRights),
|
|
337
|
+
dataFences: normalizeAllAppliedDataFences(project?.allAppliedDataFences),
|
|
338
|
+
dataLocale: projectDataLocale || null
|
|
339
|
+
});
|
|
340
|
+
const ApplicationContextProvider = props => jsxRuntime.jsx(Context$2.Provider, {
|
|
341
|
+
value: createApplicationContext(props.environment, props.user, props.project, props.projectDataLocale),
|
|
342
|
+
children: props.children
|
|
343
|
+
});
|
|
344
|
+
ApplicationContextProvider.displayName = 'ApplicationContextProvider';
|
|
345
|
+
const ApplicationContext = props => jsxRuntime.jsx(Context$2.Consumer, {
|
|
346
|
+
children: context => {
|
|
347
|
+
// Because of the way the ApplicationShell configures the Context.Provider,
|
|
348
|
+
// we ensure that, when we read from the context, we always get actual
|
|
349
|
+
// context object and not the initial value.
|
|
350
|
+
// Therefore, we can safely cast the value to be out `TApplicationContext` type.
|
|
351
|
+
const applicationContext = context;
|
|
352
|
+
return props.render(applicationContext);
|
|
353
|
+
}
|
|
354
|
+
});
|
|
355
|
+
ApplicationContext.displayName = 'ApplicationContext';
|
|
356
|
+
function withApplicationContext(mapApplicationContextToProps) {
|
|
357
|
+
return Component => {
|
|
358
|
+
const WrappedComponent = props => jsxRuntime.jsx(ApplicationContext, {
|
|
359
|
+
render: applicationContext => {
|
|
360
|
+
const mappedProps = mapApplicationContextToProps ? mapApplicationContextToProps(applicationContext) : {
|
|
361
|
+
applicationContext
|
|
362
|
+
};
|
|
363
|
+
// @ts-ignore: relates to https://github.com/emotion-js/emotion/issues/3245
|
|
364
|
+
return jsxRuntime.jsx(Component, _objectSpread$6(_objectSpread$6({}, props), mappedProps));
|
|
365
|
+
}
|
|
366
|
+
});
|
|
367
|
+
WrappedComponent.displayName = `withApplicationContext(${getDisplayName(Component)})`;
|
|
368
|
+
return WrappedComponent;
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// Use function overloading to declare two possible signatures with two
|
|
373
|
+
// distict return types, based on the selector function argument.
|
|
374
|
+
|
|
375
|
+
// Then implement the function. Typescript will pick the appropriate signature
|
|
376
|
+
// based on the function arguments.
|
|
377
|
+
function useApplicationContextHook(selector) {
|
|
378
|
+
const context = react.useContext(Context$2);
|
|
379
|
+
// Because of the way the ApplicationShell configures the Context.Provider,
|
|
380
|
+
// we ensure that, when we read from the context, we always get actual
|
|
381
|
+
// context object and not the initial value.
|
|
382
|
+
// Therefore, we can safely cast the value to be out `TApplicationContext` type.
|
|
383
|
+
const applicationContext = context;
|
|
384
|
+
return selector ? selector(applicationContext) : applicationContext;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// This is a workaround to trick babel/rollup to correctly export the function.
|
|
388
|
+
// Most likely the problem arises with the use of overloading.
|
|
389
|
+
// See related issue: https://github.com/babel/babel/issues/8361
|
|
390
|
+
const useApplicationContext = useApplicationContextHook;
|
|
391
|
+
|
|
392
|
+
const useCustomViewParentDataRefresher = params => {
|
|
393
|
+
const onCustomViewEventHandler = react.useCallback(event => {
|
|
394
|
+
var _context;
|
|
395
|
+
const originLocatorCode = event.detail.originLocatorCode;
|
|
396
|
+
if (_includesInstanceProperty__default["default"](_context = params.locators).call(_context, originLocatorCode)) {
|
|
397
|
+
params.onRefreshDataRequested(event.detail);
|
|
398
|
+
}
|
|
399
|
+
}, []);
|
|
400
|
+
react.useEffect(() => {
|
|
401
|
+
window.addEventListener(constants.CUSTOM_VIEWS_EVENTS_NAMES.CUSTOM_VIEW_ON_CLOSE_AFTER, onCustomViewEventHandler);
|
|
402
|
+
return () => {
|
|
403
|
+
window.removeEventListener(constants.CUSTOM_VIEWS_EVENTS_NAMES.CUSTOM_VIEW_ON_CLOSE_AFTER, onCustomViewEventHandler);
|
|
404
|
+
};
|
|
405
|
+
}, [onCustomViewEventHandler]);
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
function ownKeys$5(e, r) { var t = _Object$keys__default["default"](e); if (_Object$getOwnPropertySymbols__default["default"]) { var o = _Object$getOwnPropertySymbols__default["default"](e); r && (o = _filterInstanceProperty__default["default"](o).call(o, function (r) { return _Object$getOwnPropertyDescriptor__default["default"](e, r).enumerable; })), t.push.apply(t, o); } return t; }
|
|
409
|
+
function _objectSpread$5(e) { for (var r = 1; r < arguments.length; r++) { var _context, _context2; var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? _forEachInstanceProperty__default["default"](_context = ownKeys$5(Object(t), !0)).call(_context, function (r) { _defineProperty(e, r, t[r]); }) : _Object$getOwnPropertyDescriptors__default["default"] ? _Object$defineProperties__default["default"](e, _Object$getOwnPropertyDescriptors__default["default"](t)) : _forEachInstanceProperty__default["default"](_context2 = ownKeys$5(Object(t))).call(_context2, function (r) { _Object$defineProperty__default["default"](e, r, _Object$getOwnPropertyDescriptor__default["default"](t, r)); }); } return e; }
|
|
410
|
+
const Context$1 = /*#__PURE__*/react.createContext({});
|
|
411
|
+
const CustomViewContextProvider = props => {
|
|
412
|
+
const contextValue = react.useMemo(() => ({
|
|
413
|
+
hostUrl: props.hostUrl,
|
|
414
|
+
customViewConfig: props.customViewConfig
|
|
415
|
+
}), [props.hostUrl, props.customViewConfig]);
|
|
416
|
+
return jsxRuntime.jsx(Context$1.Provider, {
|
|
417
|
+
value: contextValue,
|
|
418
|
+
children: props.children
|
|
419
|
+
});
|
|
420
|
+
};
|
|
421
|
+
|
|
422
|
+
// Use function overloading to declare two possible signatures with two
|
|
423
|
+
// distict return types, based on the selector function argument.
|
|
424
|
+
|
|
425
|
+
// Then implement the function. Typescript will pick the appropriate signature
|
|
426
|
+
// based on the function arguments.
|
|
427
|
+
function useCustomViewContextHook(selector) {
|
|
428
|
+
// Because of the way the CustomViewShell configures the Context.Provider,
|
|
429
|
+
// we ensure that, when we read from the context, we always get actual
|
|
430
|
+
// context object and not the initial value.
|
|
431
|
+
// Therefore, we can safely cast the value to be out `TCustomViewContext` type.
|
|
432
|
+
const customViewContext = react.useContext(Context$1);
|
|
433
|
+
const applicationContext = useApplicationContext();
|
|
434
|
+
const mergedContext = _objectSpread$5(_objectSpread$5({}, applicationContext), customViewContext);
|
|
435
|
+
return selector ? selector(mergedContext) : mergedContext;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// This is a workaround to trick babel/rollup to correctly export the function.
|
|
439
|
+
// Most likely the problem arises with the use of overloading.
|
|
440
|
+
// See related issue: https://github.com/babel/babel/issues/8361
|
|
441
|
+
const useCustomViewContext = useCustomViewContextHook;
|
|
442
|
+
|
|
443
|
+
function ownKeys$4(e, r) { var t = _Object$keys__default["default"](e); if (_Object$getOwnPropertySymbols__default["default"]) { var o = _Object$getOwnPropertySymbols__default["default"](e); r && (o = _filterInstanceProperty__default["default"](o).call(o, function (r) { return _Object$getOwnPropertyDescriptor__default["default"](e, r).enumerable; })), t.push.apply(t, o); } return t; }
|
|
444
|
+
function _objectSpread$4(e) { for (var r = 1; r < arguments.length; r++) { var _context, _context2; var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? _forEachInstanceProperty__default["default"](_context = ownKeys$4(Object(t), !0)).call(_context, function (r) { _defineProperty(e, r, t[r]); }) : _Object$getOwnPropertyDescriptors__default["default"] ? _Object$defineProperties__default["default"](e, _Object$getOwnPropertyDescriptors__default["default"](t)) : _forEachInstanceProperty__default["default"](_context2 = ownKeys$4(Object(t))).call(_context2, function (r) { _Object$defineProperty__default["default"](e, r, _Object$getOwnPropertyDescriptor__default["default"](t, r)); }); } return e; }
|
|
445
|
+
var FetchProjectExtensionImageRegex = { kind: "Document", definitions: [{ kind: "OperationDefinition", operation: "query", name: { kind: "Name", value: "FetchProjectExtensionImageRegex" }, variableDefinitions: [], directives: [], selectionSet: { kind: "SelectionSet", selections: [{ kind: "Field", name: { kind: "Name", value: "projectExtension" }, arguments: [], directives: [], selectionSet: { kind: "SelectionSet", selections: [{ kind: "Field", name: { kind: "Name", value: "id" }, arguments: [], directives: [] }, { kind: "Field", name: { kind: "Name", value: "imageRegex" }, arguments: [], directives: [], selectionSet: { kind: "SelectionSet", selections: [{ kind: "Field", name: { kind: "Name", value: "thumb" }, arguments: [], directives: [], selectionSet: { kind: "SelectionSet", selections: [{ kind: "FragmentSpread", name: { kind: "Name", value: "ImageRegex" }, directives: [] }] } }, { kind: "Field", name: { kind: "Name", value: "small" }, arguments: [], directives: [], selectionSet: { kind: "SelectionSet", selections: [{ kind: "FragmentSpread", name: { kind: "Name", value: "ImageRegex" }, directives: [] }] } }] } }] } }] } }, { kind: "FragmentDefinition", name: { kind: "Name", value: "ImageRegex" }, typeCondition: { kind: "NamedType", name: { kind: "Name", value: "ImageRegexOptions" } }, directives: [], selectionSet: { kind: "SelectionSet", selections: [{ kind: "Field", name: { kind: "Name", value: "flag" }, arguments: [], directives: [] }, { kind: "Field", name: { kind: "Name", value: "search" }, arguments: [], directives: [] }, { kind: "Field", name: { kind: "Name", value: "replace" }, arguments: [], directives: [] }] } }], loc: { start: 0, end: 256, source: { body: "query FetchProjectExtensionImageRegex {\n projectExtension {\n id\n imageRegex {\n thumb {\n ...ImageRegex\n }\n small {\n ...ImageRegex\n }\n }\n }\n}\nfragment ImageRegex on ImageRegexOptions {\n flag\n search\n replace\n}\n", name: "GraphQL request", locationOffset: { line: 1, column: 1 } } } };
|
|
446
|
+
const useWarning = (condition, message) => {
|
|
447
|
+
react.useEffect(() => {
|
|
448
|
+
process.env.NODE_ENV !== "production" ? warning__default["default"](condition, message) : void 0;
|
|
449
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
450
|
+
}, []);
|
|
451
|
+
};
|
|
452
|
+
const Context = /*#__PURE__*/react.createContext({
|
|
453
|
+
isLoading: false
|
|
454
|
+
});
|
|
455
|
+
const useProjectExtensionImageRegex = () => {
|
|
456
|
+
const _useContext = react.useContext(Context),
|
|
457
|
+
isLoading = _useContext.isLoading,
|
|
458
|
+
imageRegex = _useContext.imageRegex;
|
|
459
|
+
return {
|
|
460
|
+
isLoading,
|
|
461
|
+
imageRegex
|
|
462
|
+
};
|
|
463
|
+
};
|
|
464
|
+
const ProjectExtensionProviderForImageRegex = props => {
|
|
465
|
+
const _useQuery = react$1.useQuery(FetchProjectExtensionImageRegex, {
|
|
466
|
+
skip: props.skip,
|
|
467
|
+
context: {
|
|
468
|
+
target: constants.GRAPHQL_TARGETS.SETTINGS_SERVICE
|
|
469
|
+
}
|
|
470
|
+
}),
|
|
471
|
+
loading = _useQuery.loading,
|
|
472
|
+
data = _useQuery.data;
|
|
473
|
+
return jsxRuntime.jsx(Context.Provider, {
|
|
474
|
+
value: {
|
|
475
|
+
isLoading: loading,
|
|
476
|
+
imageRegex: data && data.projectExtension && data.projectExtension.imageRegex
|
|
477
|
+
},
|
|
478
|
+
children: props.children
|
|
479
|
+
});
|
|
480
|
+
};
|
|
481
|
+
ProjectExtensionProviderForImageRegex.displayName = 'ProjectExtensionProviderForImageRegex';
|
|
482
|
+
const GetProjectExtensionImageRegex = props => {
|
|
483
|
+
useWarning(false, `@commercetools-frontend/application-shell-connectors: It is not recommended to use the 'GetProjectExtensionImageRegex' anymore. Please use the 'useProjectExtensionImageRegex' hook instead.`);
|
|
484
|
+
return jsxRuntime.jsx(Context.Consumer, {
|
|
485
|
+
children: imageRegexContext => props.render(imageRegexContext)
|
|
486
|
+
});
|
|
487
|
+
};
|
|
488
|
+
GetProjectExtensionImageRegex.displayName = 'GetProjectExtensionImageRegex';
|
|
489
|
+
function withProjectExtensionImageRegex() {
|
|
490
|
+
let propKey = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'imageRegexData';
|
|
491
|
+
return Component => {
|
|
492
|
+
const WrappedComponent = props => {
|
|
493
|
+
useWarning(false, `@commercetools-frontend/application-shell-connectors: It is not recommended to use the 'withProjectExtensionImageRegex' high order component anymore. Please use the 'useProjectExtensionImageRegex' hook instead.`);
|
|
494
|
+
const imageregexContext = useProjectExtensionImageRegex();
|
|
495
|
+
return jsxRuntime.jsx(GetProjectExtensionImageRegex, {
|
|
496
|
+
render: () =>
|
|
497
|
+
// @ts-ignore: relates to https://github.com/emotion-js/emotion/issues/3245
|
|
498
|
+
jsxRuntime.jsx(Component, _objectSpread$4(_objectSpread$4({}, props), {}, {
|
|
499
|
+
[propKey]: imageregexContext
|
|
500
|
+
}))
|
|
501
|
+
});
|
|
502
|
+
};
|
|
503
|
+
WrappedComponent.displayName = `withProjectExtensionImageRegex(${getDisplayName(Component)})`;
|
|
504
|
+
return WrappedComponent;
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
function ownKeys$3(e, r) { var t = _Object$keys__default["default"](e); if (_Object$getOwnPropertySymbols__default["default"]) { var o = _Object$getOwnPropertySymbols__default["default"](e); r && (o = _filterInstanceProperty__default["default"](o).call(o, function (r) { return _Object$getOwnPropertyDescriptor__default["default"](e, r).enumerable; })), t.push.apply(t, o); } return t; }
|
|
509
|
+
function _objectSpread$3(e) { for (var r = 1; r < arguments.length; r++) { var _context2, _context3; var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? _forEachInstanceProperty__default["default"](_context2 = ownKeys$3(Object(t), !0)).call(_context2, function (r) { _defineProperty(e, r, t[r]); }) : _Object$getOwnPropertyDescriptors__default["default"] ? _Object$defineProperties__default["default"](e, _Object$getOwnPropertyDescriptors__default["default"](t)) : _forEachInstanceProperty__default["default"](_context3 = ownKeys$3(Object(t))).call(_context3, function (r) { _Object$defineProperty__default["default"](e, r, _Object$getOwnPropertyDescriptor__default["default"](t, r)); }); } return e; }
|
|
510
|
+
const getSkipTokenRetry = context => {
|
|
511
|
+
const skipTokenRetry = Boolean(context.skipTokenRetry);
|
|
512
|
+
return skipTokenRetry;
|
|
513
|
+
};
|
|
514
|
+
const forwardTokenRetryHeader = headers => _objectSpread$3(_objectSpread$3({}, headers), {}, {
|
|
515
|
+
[constants.SUPPORTED_HEADERS.X_TOKEN_RETRY]: 'true'
|
|
516
|
+
});
|
|
517
|
+
|
|
518
|
+
// This link retries requests to the CTP API that have been rejected
|
|
519
|
+
// because of an invalid/expired oauth token.
|
|
520
|
+
// To do so, we resend the request with the header "X-Force-Token: true"
|
|
521
|
+
// so that the MC BE can issue a new token.
|
|
522
|
+
// NOTE: the retry is not meant to work for the MC access token.
|
|
523
|
+
const getDoesGraphQLTargetSupportTokenRetry = context => {
|
|
524
|
+
var _context;
|
|
525
|
+
const graphQLTarget = context.headers?.[constants.SUPPORTED_HEADERS.X_GRAPHQL_TARGET] || context.headers?.[constants.SUPPORTED_HEADERS.X_GRAPHQL_TARGET.toLowerCase()];
|
|
526
|
+
return Boolean(graphQLTarget && _includesInstanceProperty__default["default"](_context = [constants.GRAPHQL_TARGETS.COMMERCETOOLS_PLATFORM, constants.GRAPHQL_TARGETS.ADMINISTRATION_SERVICE, constants.GRAPHQL_TARGETS.SETTINGS_SERVICE, constants.GRAPHQL_TARGETS.MERCHANT_CENTER_BACKEND]).call(_context, graphQLTarget));
|
|
527
|
+
};
|
|
528
|
+
const isHttpError = error => error.statusCode !== undefined || error.statusCode !== undefined;
|
|
529
|
+
const isGraphQLError = error => _Array$isArray__default["default"](error) && _someInstanceProperty__default["default"](error).call(error, err => err.message !== undefined || err.extensions !== undefined);
|
|
530
|
+
|
|
531
|
+
// Checks response from GraphQL in order to scan 401 errors and redirect the
|
|
532
|
+
// user to the login page resetting the store and showing the proper message
|
|
533
|
+
const errorLink = error.onError(_ref => {
|
|
534
|
+
let graphQLErrors = _ref.graphQLErrors,
|
|
535
|
+
networkError = _ref.networkError,
|
|
536
|
+
operation = _ref.operation,
|
|
537
|
+
forward = _ref.forward;
|
|
538
|
+
if (networkError && isHttpError(networkError) && networkError.statusCode === constants.STATUS_CODES.UNAUTHORIZED) {
|
|
539
|
+
history__default["default"].push(`/logout?reason=${constants.LOGOUT_REASONS.UNAUTHORIZED}`);
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// In case of graphql errors, we want to retry unauthenticated requests by
|
|
544
|
+
// forcing our API to fetch a new token, using the `X-Force-Token` header.
|
|
545
|
+
// https://www.apollographql.com/docs/link/links/error/#retrying-failed-requests
|
|
546
|
+
// We need to do this as the `token-retry-link` only works for network errors.
|
|
547
|
+
// https://www.apollographql.com/docs/link/links/retry/
|
|
548
|
+
const context = operation.getContext();
|
|
549
|
+
if (graphQLErrors && isGraphQLError(graphQLErrors)) {
|
|
550
|
+
for (const err of graphQLErrors) {
|
|
551
|
+
const isNonAuthenticatedViaExtensionCode = err?.extensions?.code === 'UNAUTHENTICATED';
|
|
552
|
+
/**
|
|
553
|
+
* NOTE:
|
|
554
|
+
* Not not all GraphQL APIs expose an `extensions` field in
|
|
555
|
+
* each error. For those we have to use the `message`
|
|
556
|
+
* property until they introduced support for the `extensions`
|
|
557
|
+
* field.
|
|
558
|
+
*/
|
|
559
|
+
const isNonAuthenticatedViaCode = err?.message === 'invalid_token';
|
|
560
|
+
if ((isNonAuthenticatedViaExtensionCode || isNonAuthenticatedViaCode) && getDoesGraphQLTargetSupportTokenRetry(context) && !getSkipTokenRetry(context)) {
|
|
561
|
+
operation.setContext(_ref2 => {
|
|
562
|
+
let headers = _ref2.headers;
|
|
563
|
+
return {
|
|
564
|
+
headers: forwardTokenRetryHeader(headers)
|
|
565
|
+
};
|
|
566
|
+
});
|
|
567
|
+
// retry the request, returning the new observable
|
|
568
|
+
return forward(operation);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// Report unhandled errors to Sentry
|
|
574
|
+
if (context.enableSentryErrorReporting && networkError) {
|
|
575
|
+
sentry.reportErrorToSentry(networkError, {
|
|
576
|
+
extra: {
|
|
577
|
+
operationName: operation.operationName
|
|
578
|
+
}
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
if (context.enableSentryErrorReporting && graphQLErrors) {
|
|
582
|
+
for (const err of graphQLErrors) {
|
|
583
|
+
sentry.reportErrorToSentry(err, {
|
|
584
|
+
extra: {
|
|
585
|
+
operationName: operation.operationName
|
|
586
|
+
}
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
return;
|
|
591
|
+
});
|
|
592
|
+
|
|
593
|
+
// Attempt to load the `teamId` from sessionStorage
|
|
594
|
+
function selectTeamIdFromStorage() {
|
|
595
|
+
return window.sessionStorage.getItem(constants.STORAGE_KEYS.ACTIVE_TEAM_ID) || window.app.__DEVELOPMENT__?.oidc?.teamId;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
const staticUrlPathsInPositionOfProjectKey = ['login', 'logout', 'account'];
|
|
599
|
+
|
|
600
|
+
// Attempt to extract the `:projectKey` from the URL.
|
|
601
|
+
// If the value matches one of the values in the list above,
|
|
602
|
+
// return `undefined` as we're not within a project context.
|
|
603
|
+
function selectProjectKeyFromUrl() {
|
|
604
|
+
let locationPath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window.location.pathname;
|
|
605
|
+
let possibleProjectKey = '';
|
|
606
|
+
const pathParts = locationPath.split('/');
|
|
607
|
+
if (pathParts[1] === 'custom-views') {
|
|
608
|
+
// Custom Views paths: /custom-views/:customViewId/projects/:projectKey
|
|
609
|
+
possibleProjectKey = pathParts[4];
|
|
610
|
+
} else {
|
|
611
|
+
// Application paths: /:projectKey/:applicationId
|
|
612
|
+
possibleProjectKey = pathParts[1];
|
|
613
|
+
}
|
|
614
|
+
return _includesInstanceProperty__default["default"](staticUrlPathsInPositionOfProjectKey).call(staticUrlPathsInPositionOfProjectKey, possibleProjectKey) ? undefined : possibleProjectKey;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// Keep an in-memory reference to the apollo client that would be initialized
|
|
618
|
+
// by the application. This is useful to retrieve on runtime the reference
|
|
619
|
+
// to the apollo client in other static modules.
|
|
620
|
+
let cachedApolloClient;
|
|
621
|
+
const setCachedApolloClient = apolloClient => {
|
|
622
|
+
cachedApolloClient = apolloClient;
|
|
623
|
+
};
|
|
624
|
+
const getCachedApolloClient = () => cachedApolloClient;
|
|
625
|
+
|
|
626
|
+
var FetchUserId = { kind: "Document", definitions: [{ kind: "OperationDefinition", operation: "query", name: { kind: "Name", value: "FetchUserId" }, variableDefinitions: [], directives: [], selectionSet: { kind: "SelectionSet", selections: [{ kind: "Field", alias: { kind: "Name", value: "user" }, name: { kind: "Name", value: "me" }, arguments: [], directives: [], selectionSet: { kind: "SelectionSet", selections: [{ kind: "Field", name: { kind: "Name", value: "id" }, arguments: [], directives: [] }] } }] } }], loc: { start: 0, end: 46, source: { body: "query FetchUserId {\n user: me {\n id\n }\n}\n", name: "GraphQL request", locationOffset: { line: 1, column: 1 } } } };
|
|
627
|
+
function selectUserId() {
|
|
628
|
+
const apolloClient = getCachedApolloClient();
|
|
629
|
+
if (!apolloClient) {
|
|
630
|
+
return null;
|
|
631
|
+
}
|
|
632
|
+
try {
|
|
633
|
+
const queryResult = apolloClient.readQuery({
|
|
634
|
+
query: FetchUserId
|
|
635
|
+
});
|
|
636
|
+
if (queryResult && queryResult.user) {
|
|
637
|
+
return queryResult.user.id;
|
|
638
|
+
}
|
|
639
|
+
} catch (e) {
|
|
640
|
+
return null;
|
|
641
|
+
}
|
|
642
|
+
return null;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
const VALID_ID_PART_FORMAT = /^[\w-/]+$/;
|
|
646
|
+
const skipMalformedPart = part => part && VALID_ID_PART_FORMAT.test(part);
|
|
647
|
+
function getCorrelationId() {
|
|
648
|
+
var _context;
|
|
649
|
+
let _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
|
|
650
|
+
userId = _ref.userId;
|
|
651
|
+
return _filterInstanceProperty__default["default"](_context = ['mc', selectProjectKeyFromUrl(), userId, uuid.v4()]).call(_context, skipMalformedPart).join('/');
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
const createApolloContextForProxyForwardTo = proxyForwardTocontext => ({
|
|
655
|
+
// Send the request to the forward-to endpoint.
|
|
656
|
+
uri: `${getMcApiUrl()}/proxy/forward-to`,
|
|
657
|
+
// Custom properties to be used by the "header-link".
|
|
658
|
+
forwardToConfig: proxyForwardTocontext,
|
|
659
|
+
skipGraphQlTargetCheck: true
|
|
660
|
+
});
|
|
661
|
+
|
|
662
|
+
/* eslint-disable no-console */
|
|
663
|
+
|
|
664
|
+
const isLoggerEnabled = () => {
|
|
665
|
+
if (process.env.DEBUG === 'true') return true;
|
|
666
|
+
if (process.env.NODE_ENV === 'development') return true;
|
|
667
|
+
const queryParams = new _URL__default["default"](window.location.href);
|
|
668
|
+
if (process.env.NODE_ENV === 'production' && queryParams.searchParams.get('debug') === 'true') return true;
|
|
669
|
+
return false;
|
|
670
|
+
};
|
|
671
|
+
const logger = {
|
|
672
|
+
groupCollapsed: function () {
|
|
673
|
+
return isLoggerEnabled() && console.groupCollapsed(...arguments);
|
|
674
|
+
},
|
|
675
|
+
groupEnd: () => isLoggerEnabled() && console.groupEnd(),
|
|
676
|
+
info: function () {
|
|
677
|
+
return isLoggerEnabled() && console.info(...arguments);
|
|
678
|
+
},
|
|
679
|
+
log: function () {
|
|
680
|
+
return isLoggerEnabled() && console.log(...arguments);
|
|
681
|
+
},
|
|
682
|
+
error: function () {
|
|
683
|
+
return isLoggerEnabled() && console.error(...arguments);
|
|
684
|
+
},
|
|
685
|
+
warn: function () {
|
|
686
|
+
return isLoggerEnabled() && console.warn(...arguments);
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
|
|
690
|
+
const getSessionToken = () => window.sessionStorage.getItem(constants.STORAGE_KEYS.SESSION_TOKEN);
|
|
691
|
+
const setActiveSession = sessionToken => {
|
|
692
|
+
if (!sessionToken) return;
|
|
693
|
+
window.sessionStorage.setItem(constants.STORAGE_KEYS.SESSION_TOKEN, sessionToken ?? '');
|
|
694
|
+
window.localStorage.setItem(constants.STORAGE_KEYS.LOGIN_STRATEGY, constants.LOGIN_STRATEGY_OIDC);
|
|
695
|
+
// Remove flag for original workflow
|
|
696
|
+
window.localStorage.removeItem(constants.STORAGE_KEYS.IS_AUTHENTICATED);
|
|
697
|
+
};
|
|
698
|
+
const clearSession = () => {
|
|
699
|
+
window.sessionStorage.removeItem(constants.STORAGE_KEYS.SESSION_TOKEN);
|
|
700
|
+
window.sessionStorage.removeItem(constants.STORAGE_KEYS.SESSION_SCOPE);
|
|
701
|
+
window.sessionStorage.removeItem(constants.STORAGE_KEYS.IS_AUTHENTICATED);
|
|
702
|
+
};
|
|
703
|
+
const getActiveProjectKey = () => window.localStorage.getItem(constants.STORAGE_KEYS.ACTIVE_PROJECT_KEY);
|
|
704
|
+
const removeActiveProjectKey = () => {
|
|
705
|
+
window.localStorage.removeItem(constants.STORAGE_KEYS.ACTIVE_PROJECT_KEY);
|
|
706
|
+
};
|
|
707
|
+
const setActiveProjectKey = projectKey => {
|
|
708
|
+
window.localStorage.setItem(constants.STORAGE_KEYS.ACTIVE_PROJECT_KEY, projectKey);
|
|
709
|
+
};
|
|
710
|
+
const getSessionScope = () => window.sessionStorage.getItem(constants.STORAGE_KEYS.SESSION_SCOPE);
|
|
711
|
+
const setSessionScope = scope => {
|
|
712
|
+
window.sessionStorage.setItem(constants.STORAGE_KEYS.SESSION_SCOPE, scope);
|
|
713
|
+
};
|
|
714
|
+
const getSessionState = stateId => {
|
|
715
|
+
const sessionStateKey = `${constants.STORAGE_KEYS.NONCE}_${stateId}`;
|
|
716
|
+
const unparsedSessionState = window.sessionStorage.getItem(sessionStateKey);
|
|
717
|
+
if (unparsedSessionState) {
|
|
718
|
+
try {
|
|
719
|
+
const parsedSessionState = JSON.parse(unparsedSessionState);
|
|
720
|
+
return parsedSessionState;
|
|
721
|
+
} catch (error) {
|
|
722
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
723
|
+
// eslint-disable-next-line no-console
|
|
724
|
+
console.warn(`Cannot parse session state for "${sessionStateKey}".\n${unparsedSessionState}`);
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
return null;
|
|
729
|
+
};
|
|
730
|
+
const setSessionState = (stateId, state) => {
|
|
731
|
+
const sessionStateKey = `${constants.STORAGE_KEYS.NONCE}_${stateId}`;
|
|
732
|
+
window.sessionStorage.setItem(sessionStateKey, _JSON$stringify__default["default"](state));
|
|
733
|
+
};
|
|
734
|
+
const removeSessionState = stateId => {
|
|
735
|
+
const sessionStateKey = `${constants.STORAGE_KEYS.NONCE}_${stateId}`;
|
|
736
|
+
window.sessionStorage.removeItem(sessionStateKey);
|
|
737
|
+
};
|
|
738
|
+
|
|
739
|
+
var oidcStorage = /*#__PURE__*/Object.freeze({
|
|
740
|
+
__proto__: null,
|
|
741
|
+
getSessionToken: getSessionToken,
|
|
742
|
+
setActiveSession: setActiveSession,
|
|
743
|
+
clearSession: clearSession,
|
|
744
|
+
getSessionState: getSessionState,
|
|
745
|
+
setSessionState: setSessionState,
|
|
746
|
+
removeSessionState: removeSessionState,
|
|
747
|
+
getActiveProjectKey: getActiveProjectKey,
|
|
748
|
+
setActiveProjectKey: setActiveProjectKey,
|
|
749
|
+
removeActiveProjectKey: removeActiveProjectKey,
|
|
750
|
+
getSessionScope: getSessionScope,
|
|
751
|
+
setSessionScope: setSessionScope
|
|
752
|
+
});
|
|
753
|
+
|
|
754
|
+
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? _Reflect$construct__default["default"](o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
|
|
755
|
+
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(_Reflect$construct__default["default"](Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function () { return !!t; })(); }
|
|
756
|
+
function ownKeys$2(e, r) { var t = _Object$keys__default["default"](e); if (_Object$getOwnPropertySymbols__default["default"]) { var o = _Object$getOwnPropertySymbols__default["default"](e); r && (o = _filterInstanceProperty__default["default"](o).call(o, function (r) { return _Object$getOwnPropertyDescriptor__default["default"](e, r).enumerable; })), t.push.apply(t, o); } return t; }
|
|
757
|
+
function _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var _context2, _context3; var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? _forEachInstanceProperty__default["default"](_context2 = ownKeys$2(Object(t), !0)).call(_context2, function (r) { _defineProperty(e, r, t[r]); }) : _Object$getOwnPropertyDescriptors__default["default"] ? _Object$defineProperties__default["default"](e, _Object$getOwnPropertyDescriptors__default["default"](t)) : _forEachInstanceProperty__default["default"](_context3 = ownKeys$2(Object(t))).call(_context3, function (r) { _Object$defineProperty__default["default"](e, r, _Object$getOwnPropertyDescriptor__default["default"](t, r)); }); } return e; }
|
|
758
|
+
let _userAgent$1;
|
|
759
|
+
const getUserAgent$1 = () => {
|
|
760
|
+
if (!_userAgent$1) {
|
|
761
|
+
_userAgent$1 = createHttpUserAgent__default["default"]({
|
|
762
|
+
name: 'unknown-http-client',
|
|
763
|
+
libraryName: typeof window !== 'undefined' ? window.app?.applicationName ?? 'unknown-application-name' : undefined
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
return _userAgent$1;
|
|
767
|
+
};
|
|
768
|
+
const defaultForwardToVersion = 'v2';
|
|
769
|
+
const defaultForwardToAudiencePolicy = 'forward-url-full-path';
|
|
770
|
+
function buildApiUrl(endpoint) {
|
|
771
|
+
const apiUrl = getMcApiUrl().replace(/\/$/, '');
|
|
772
|
+
return `${apiUrl}${endpoint}`;
|
|
773
|
+
}
|
|
774
|
+
const getAppliedForwardToHeaders = forwardToConfig => {
|
|
775
|
+
var _context;
|
|
776
|
+
if (!forwardToConfig) {
|
|
777
|
+
return {};
|
|
778
|
+
}
|
|
779
|
+
if (!forwardToConfig.uri) {
|
|
780
|
+
throw new Error(`Missing required "uri" option.`);
|
|
781
|
+
}
|
|
782
|
+
const exchangeTokenClaims = [];
|
|
783
|
+
if (forwardToConfig.includeUserPermissions) {
|
|
784
|
+
exchangeTokenClaims.push('permissions');
|
|
785
|
+
}
|
|
786
|
+
return _objectSpread$2(_objectSpread$2({}, _reduceInstanceProperty__default["default"](_context = _Object$entries__default["default"](forwardToConfig.headers ?? {})).call(_context, (customForwardHeaders, _ref) => {
|
|
787
|
+
let _ref2 = _slicedToArray(_ref, 2),
|
|
788
|
+
headerName = _ref2[0],
|
|
789
|
+
headerValue = _ref2[1];
|
|
790
|
+
return _objectSpread$2(_objectSpread$2({}, customForwardHeaders), {}, {
|
|
791
|
+
// Prefix headers so that the MC API can allow and forward them.
|
|
792
|
+
[`x-forward-header-${headerName}`]: headerValue
|
|
793
|
+
});
|
|
794
|
+
}, {})), {}, {
|
|
795
|
+
[constants.SUPPORTED_HEADERS.ACCEPT_VERSION]: forwardToConfig.version ?? defaultForwardToVersion,
|
|
796
|
+
[constants.SUPPORTED_HEADERS.X_FORWARD_TO]: forwardToConfig.uri,
|
|
797
|
+
[constants.SUPPORTED_HEADERS.X_FORWARD_TO_AUDIENCE_POLICY]: forwardToConfig.audiencePolicy ?? defaultForwardToAudiencePolicy,
|
|
798
|
+
[constants.SUPPORTED_HEADERS.X_FORWARD_TO_CLAIMS]: exchangeTokenClaims.join(' ')
|
|
799
|
+
});
|
|
800
|
+
};
|
|
801
|
+
function createHttpClientOptions() {
|
|
802
|
+
let config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
|
803
|
+
const sessionToken = getSessionToken();
|
|
804
|
+
const projectKey = config.projectKey ?? selectProjectKeyFromUrl();
|
|
805
|
+
const userId = selectUserId();
|
|
806
|
+
const userAgent = config?.userAgent || getUserAgent$1();
|
|
807
|
+
return {
|
|
808
|
+
credentials: 'include',
|
|
809
|
+
headers: omitEmpty__default["default"](_objectSpread$2(_objectSpread$2({}, config.headers), {}, {
|
|
810
|
+
// Required headers
|
|
811
|
+
[constants.SUPPORTED_HEADERS.ACCEPT]: 'application/json',
|
|
812
|
+
[constants.SUPPORTED_HEADERS.AUTHORIZATION]: sessionToken ? `Bearer ${sessionToken}` : undefined,
|
|
813
|
+
[constants.SUPPORTED_HEADERS.X_APPLICATION_ID]: window.app.applicationIdentifier,
|
|
814
|
+
[constants.SUPPORTED_HEADERS.X_CUSTOM_VIEW_ID]: window.app.customViewId,
|
|
815
|
+
[constants.SUPPORTED_HEADERS.X_CORRELATION_ID]: getCorrelationId({
|
|
816
|
+
userId
|
|
817
|
+
}),
|
|
818
|
+
[constants.SUPPORTED_HEADERS.X_PROJECT_KEY]: projectKey,
|
|
819
|
+
[constants.SUPPORTED_HEADERS.X_USER_AGENT]: userAgent
|
|
820
|
+
}, getAppliedForwardToHeaders(config.forwardToConfig)))
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
let RenewTokenError = /*#__PURE__*/function (_Error) {
|
|
824
|
+
function RenewTokenError(message) {
|
|
825
|
+
var _this;
|
|
826
|
+
_classCallCheck(this, RenewTokenError);
|
|
827
|
+
_this = _callSuper(this, RenewTokenError, [message]);
|
|
828
|
+
_Object$defineProperty__default["default"](_this, 'name', {
|
|
829
|
+
value: 'RenewTokenError'
|
|
830
|
+
});
|
|
831
|
+
return _this;
|
|
832
|
+
}
|
|
833
|
+
_inherits(RenewTokenError, _Error);
|
|
834
|
+
return _createClass(RenewTokenError);
|
|
835
|
+
}(/*#__PURE__*/_wrapNativeSuper(Error));
|
|
836
|
+
async function executeHttpClientRequest(fetcher) {
|
|
837
|
+
let config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
838
|
+
// Wrapper function to be called again (once) on retry.
|
|
839
|
+
async function sendRequest() {
|
|
840
|
+
let _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
|
|
841
|
+
shouldRenewToken = _ref3.shouldRenewToken;
|
|
842
|
+
const requestOptions = createHttpClientOptions(config);
|
|
843
|
+
const response = await fetcher(_objectSpread$2(_objectSpread$2({}, requestOptions), {}, {
|
|
844
|
+
headers: omitEmpty__default["default"](_objectSpread$2(_objectSpread$2({}, requestOptions.headers), {}, {
|
|
845
|
+
// Passing this header forces a token renewal.
|
|
846
|
+
[constants.SUPPORTED_HEADERS.X_TOKEN_RETRY]: shouldRenewToken
|
|
847
|
+
}))
|
|
848
|
+
}));
|
|
849
|
+
if (response.statusCode === constants.STATUS_CODES.UNAUTHORIZED) {
|
|
850
|
+
throw new RenewTokenError(`Unauthorized response, attempting retry.`);
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
// In case a new session token is returned from the server, save it.
|
|
854
|
+
const refreshedSessionToken = response.getHeader('x-refreshed-session-token');
|
|
855
|
+
if (refreshedSessionToken) {
|
|
856
|
+
setActiveSession(refreshedSessionToken);
|
|
857
|
+
}
|
|
858
|
+
return response.data;
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
// Attempt to send the request.
|
|
862
|
+
return sendRequest().catch(error => {
|
|
863
|
+
if (error instanceof RenewTokenError) {
|
|
864
|
+
// Retry the request and ask to renew the token.
|
|
865
|
+
return sendRequest({
|
|
866
|
+
shouldRenewToken: true
|
|
867
|
+
});
|
|
868
|
+
}
|
|
869
|
+
throw error;
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
function ownKeys$1(e, r) { var t = _Object$keys__default["default"](e); if (_Object$getOwnPropertySymbols__default["default"]) { var o = _Object$getOwnPropertySymbols__default["default"](e); r && (o = _filterInstanceProperty__default["default"](o).call(o, function (r) { return _Object$getOwnPropertyDescriptor__default["default"](e, r).enumerable; })), t.push.apply(t, o); } return t; }
|
|
874
|
+
function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var _context4, _context5; var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? _forEachInstanceProperty__default["default"](_context4 = ownKeys$1(Object(t), !0)).call(_context4, function (r) { _defineProperty(e, r, t[r]); }) : _Object$getOwnPropertyDescriptors__default["default"] ? _Object$defineProperties__default["default"](e, _Object$getOwnPropertyDescriptors__default["default"](t)) : _forEachInstanceProperty__default["default"](_context5 = ownKeys$1(Object(t))).call(_context5, function (r) { _Object$defineProperty__default["default"](e, r, _Object$getOwnPropertyDescriptor__default["default"](t, r)); }); } return e; }
|
|
875
|
+
let _userAgent;
|
|
876
|
+
const getUserAgent = () => {
|
|
877
|
+
if (!_userAgent) {
|
|
878
|
+
var _context;
|
|
879
|
+
_userAgent = createHttpUserAgent__default["default"]({
|
|
880
|
+
name: 'apollo-client',
|
|
881
|
+
// version: apolloVersion,
|
|
882
|
+
libraryName: _filterInstanceProperty__default["default"](_context = [typeof window !== 'undefined' ? window.app?.applicationName ?? 'unknown-application-name' : undefined, 'application-shell']).call(_context, Boolean).join('/'),
|
|
883
|
+
libraryVersion: version,
|
|
884
|
+
contactUrl: 'https://git.io/fjuyC',
|
|
885
|
+
// points to the appkit repo issues
|
|
886
|
+
contactEmail: 'support@commercetools.com'
|
|
887
|
+
});
|
|
888
|
+
}
|
|
889
|
+
return _userAgent;
|
|
890
|
+
};
|
|
891
|
+
const isKnownGraphQlTarget = target => {
|
|
892
|
+
var _context2;
|
|
893
|
+
return target ? _includesInstanceProperty__default["default"](_context2 = _Object$values__default["default"](constants.GRAPHQL_TARGETS)).call(_context2, target) : false;
|
|
894
|
+
};
|
|
895
|
+
const extractSessionTokenFromResponse = context => {
|
|
896
|
+
const refreshedSessionToken = context.response?.headers?.get('x-refreshed-session-token');
|
|
897
|
+
if (refreshedSessionToken) {
|
|
898
|
+
return refreshedSessionToken ?? null;
|
|
899
|
+
}
|
|
900
|
+
const restResponseWithRefreshTokenHeader = context.restResponses?.find(response => response.headers?.has('x-refreshed-session-token'));
|
|
901
|
+
if (restResponseWithRefreshTokenHeader) {
|
|
902
|
+
return restResponseWithRefreshTokenHeader.headers.get('x-refreshed-session-token') ?? null;
|
|
903
|
+
}
|
|
904
|
+
return null;
|
|
905
|
+
};
|
|
906
|
+
|
|
907
|
+
/* eslint-disable import/prefer-default-export */
|
|
908
|
+
// Use a middleware to update the request headers with the correct params.
|
|
909
|
+
const headerLink = new client.ApolloLink((operation, forward) => {
|
|
910
|
+
var _context3;
|
|
911
|
+
const apolloContext = operation.getContext();
|
|
912
|
+
const variables = operation.variables;
|
|
913
|
+
const graphQlTarget = apolloContext.target || variables.target;
|
|
914
|
+
if (!apolloContext.skipGraphQlTargetCheck && !isKnownGraphQlTarget(graphQlTarget)) throw new Error(`GraphQL target "${graphQlTarget}" is missing (or is not supported) in operation "${operation.operationName}"`);
|
|
915
|
+
|
|
916
|
+
/**
|
|
917
|
+
* NOTE:
|
|
918
|
+
* The project key is read from the url in a project related application context.
|
|
919
|
+
* This holds for most applications like `application-categories`, `application-discounts` etc.
|
|
920
|
+
* However, the `application-account` does not run with the project key being part of the url.
|
|
921
|
+
* As a result we allow passing the project key as a variable on the operation allowing
|
|
922
|
+
* it to be the fallback.
|
|
923
|
+
*/
|
|
924
|
+
const projectKey = apolloContext.projectKey || variables.projectKey || selectProjectKeyFromUrl();
|
|
925
|
+
const teamId = apolloContext.teamId || variables.teamId || selectTeamIdFromStorage();
|
|
926
|
+
const featureFlag = apolloContext.featureFlag || variables.featureFlag;
|
|
927
|
+
operation.setContext(createHttpClientOptions({
|
|
928
|
+
userAgent: getUserAgent(),
|
|
929
|
+
headers: omitEmpty__default["default"](_objectSpread$1(_objectSpread$1({}, apolloContext.headers), {}, {
|
|
930
|
+
// Required headers for GraphQL API.
|
|
931
|
+
[constants.SUPPORTED_HEADERS.X_GRAPHQL_TARGET]: graphQlTarget,
|
|
932
|
+
// For logging/debugging purposes.
|
|
933
|
+
[constants.SUPPORTED_HEADERS.X_GRAPHQL_OPERATION_NAME]: operation.operationName,
|
|
934
|
+
// Experimental features, use with caution.
|
|
935
|
+
[constants.SUPPORTED_HEADERS.X_TEAM_ID]: teamId,
|
|
936
|
+
[constants.SUPPORTED_HEADERS.X_FEATURE_FLAG]: featureFlag
|
|
937
|
+
})),
|
|
938
|
+
forwardToConfig: apolloContext.forwardToConfig,
|
|
939
|
+
projectKey
|
|
940
|
+
}));
|
|
941
|
+
return _mapInstanceProperty__default["default"](_context3 = forward(operation)).call(_context3, response => {
|
|
942
|
+
const context = operation.getContext();
|
|
943
|
+
const refreshedSessionToken = extractSessionTokenFromResponse(context);
|
|
944
|
+
if (refreshedSessionToken) {
|
|
945
|
+
setActiveSession(refreshedSessionToken);
|
|
946
|
+
}
|
|
947
|
+
return response;
|
|
948
|
+
});
|
|
949
|
+
});
|
|
950
|
+
|
|
951
|
+
const tokenRetryLink = new retry.RetryLink({
|
|
952
|
+
attempts: (count, operation, error) => {
|
|
953
|
+
const context = operation.getContext();
|
|
954
|
+
if (error?.statusCode === constants.STATUS_CODES.UNAUTHORIZED && count === 1 && getDoesGraphQLTargetSupportTokenRetry(context) && !getSkipTokenRetry(context)) {
|
|
955
|
+
operation.setContext(_ref => {
|
|
956
|
+
let headers = _ref.headers;
|
|
957
|
+
return {
|
|
958
|
+
headers: forwardTokenRetryHeader(headers)
|
|
959
|
+
};
|
|
960
|
+
});
|
|
961
|
+
return true;
|
|
962
|
+
}
|
|
963
|
+
return false;
|
|
964
|
+
}
|
|
965
|
+
});
|
|
966
|
+
|
|
967
|
+
function ownKeys(e, r) { var t = _Object$keys__default["default"](e); if (_Object$getOwnPropertySymbols__default["default"]) { var o = _Object$getOwnPropertySymbols__default["default"](e); r && (o = _filterInstanceProperty__default["default"](o).call(o, function (r) { return _Object$getOwnPropertyDescriptor__default["default"](e, r).enumerable; })), t.push.apply(t, o); } return t; }
|
|
968
|
+
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var _context, _context2; var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? _forEachInstanceProperty__default["default"](_context = ownKeys(Object(t), !0)).call(_context, function (r) { _defineProperty(e, r, t[r]); }) : _Object$getOwnPropertyDescriptors__default["default"] ? _Object$defineProperties__default["default"](e, _Object$getOwnPropertyDescriptors__default["default"](t)) : _forEachInstanceProperty__default["default"](_context2 = ownKeys(Object(t))).call(_context2, function (r) { _Object$defineProperty__default["default"](e, r, _Object$getOwnPropertyDescriptor__default["default"](t, r)); }); } return e; }
|
|
969
|
+
const createApolloLink = function () {
|
|
970
|
+
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
|
971
|
+
const httpLink = client.createHttpLink({
|
|
972
|
+
uri: `${getMcApiUrl()}/graphql`,
|
|
973
|
+
fetch
|
|
974
|
+
});
|
|
975
|
+
|
|
976
|
+
// The order of links is IMPORTANT!
|
|
977
|
+
// In the request-phase they are executed top to bottom.
|
|
978
|
+
// In the response/phase they are executed bottom to top.
|
|
979
|
+
// The `httpLink` is terminating so it must be last, while `tokenRetryLink` and `errorLink`
|
|
980
|
+
// wrap the links the their right.
|
|
981
|
+
return client.from([headerLink,
|
|
982
|
+
// See https://www.apollographql.com/docs/react/api/link/apollo-link-rest/#link-order
|
|
983
|
+
// State & context links should happen before (to the left of) `restLink`.
|
|
984
|
+
...(options.restLink ? [options.restLink] : []),
|
|
985
|
+
// Must be before `tokenRetryLink`.
|
|
986
|
+
errorLink,
|
|
987
|
+
// Avoid logging queries in test environment
|
|
988
|
+
...(isLoggerEnabled() ? [loggerLink__default["default"]] : []),
|
|
989
|
+
// Must be after `errorLink`.
|
|
990
|
+
tokenRetryLink,
|
|
991
|
+
// Must be last.
|
|
992
|
+
httpLink]);
|
|
993
|
+
};
|
|
994
|
+
|
|
995
|
+
// This custom merge function allows to merge two arrays of objects.
|
|
996
|
+
// The incoming list is what we need to update to, but we still need
|
|
997
|
+
// to ensure that existing cache elements are not removed but updated.
|
|
998
|
+
// This is usually the case when elements get removed.
|
|
999
|
+
const mergeArraysObjects = function () {
|
|
1000
|
+
let existing = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
|
|
1001
|
+
let incoming = arguments.length > 1 ? arguments[1] : undefined;
|
|
1002
|
+
let _ref = arguments.length > 2 ? arguments[2] : undefined,
|
|
1003
|
+
mergeObjects = _ref.mergeObjects;
|
|
1004
|
+
return _reduceInstanceProperty__default["default"](incoming).call(incoming, (mergedElements, elem) => {
|
|
1005
|
+
const existingElem = _findInstanceProperty__default["default"](existing).call(existing, el => el.__ref === elem.__ref);
|
|
1006
|
+
if (existingElem) {
|
|
1007
|
+
const updatedElem = mergeObjects(existingElem, elem);
|
|
1008
|
+
if (updatedElem) {
|
|
1009
|
+
return [...mergedElements, updatedElem];
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
return [...mergedElements, elem];
|
|
1013
|
+
}, []);
|
|
1014
|
+
};
|
|
1015
|
+
const createApolloClient = function () {
|
|
1016
|
+
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
|
1017
|
+
const customCacheConfig = options?.cache ?? {};
|
|
1018
|
+
return new client.ApolloClient({
|
|
1019
|
+
link: createApolloLink(options),
|
|
1020
|
+
// https://www.apollographql.com/docs/react/caching/cache-configuration/
|
|
1021
|
+
cache: new client.InMemoryCache(_objectSpread(_objectSpread({}, customCacheConfig), {}, {
|
|
1022
|
+
// https://www.apollographql.com/docs/react/caching/cache-configuration/#generating-unique-identifiers
|
|
1023
|
+
typePolicies: _objectSpread({
|
|
1024
|
+
// CTP types with `key` as identifier
|
|
1025
|
+
Project: {
|
|
1026
|
+
keyFields: ['key'],
|
|
1027
|
+
fields: {
|
|
1028
|
+
expiry: {
|
|
1029
|
+
merge: (existing, incoming, _ref2) => {
|
|
1030
|
+
let mergeObjects = _ref2.mergeObjects;
|
|
1031
|
+
return mergeObjects(existing, incoming);
|
|
1032
|
+
}
|
|
1033
|
+
},
|
|
1034
|
+
suspension: {
|
|
1035
|
+
merge: (existing, incoming, _ref3) => {
|
|
1036
|
+
let mergeObjects = _ref3.mergeObjects;
|
|
1037
|
+
return mergeObjects(existing, incoming);
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
},
|
|
1042
|
+
Store: {
|
|
1043
|
+
keyFields: ['key']
|
|
1044
|
+
},
|
|
1045
|
+
// Internal apps menu links representations
|
|
1046
|
+
ApplicationsMenu: {
|
|
1047
|
+
fields: {
|
|
1048
|
+
appBar: {
|
|
1049
|
+
merge: mergeArraysObjects
|
|
1050
|
+
},
|
|
1051
|
+
navBarGroups: {
|
|
1052
|
+
merge: mergeArraysObjects
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
}, customCacheConfig.typePolicies ?? {})
|
|
1057
|
+
}))
|
|
1058
|
+
});
|
|
1059
|
+
};
|
|
1060
|
+
|
|
1061
|
+
function useMcQuery(query, options) {
|
|
1062
|
+
return react$1.useQuery(query, options);
|
|
1063
|
+
}
|
|
1064
|
+
function useMcLazyQuery(query, options) {
|
|
1065
|
+
return react$1.useLazyQuery(query, options);
|
|
1066
|
+
}
|
|
1067
|
+
function useMcMutation(mutation, options) {
|
|
1068
|
+
return react$1.useMutation(mutation, options);
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
exports.ApplicationContext = ApplicationContext;
|
|
1072
|
+
exports.ApplicationContextProvider = ApplicationContextProvider;
|
|
1073
|
+
exports.Context = Context$2;
|
|
1074
|
+
exports.CustomViewContextProvider = CustomViewContextProvider;
|
|
1075
|
+
exports.GetProjectExtensionImageRegex = GetProjectExtensionImageRegex;
|
|
1076
|
+
exports.ProjectExtensionProviderForImageRegex = ProjectExtensionProviderForImageRegex;
|
|
1077
|
+
exports.buildApiUrl = buildApiUrl;
|
|
1078
|
+
exports.createApolloClient = createApolloClient;
|
|
1079
|
+
exports.createApolloContextForProxyForwardTo = createApolloContextForProxyForwardTo;
|
|
1080
|
+
exports.createHttpClientOptions = createHttpClientOptions;
|
|
1081
|
+
exports.executeHttpClientRequest = executeHttpClientRequest;
|
|
1082
|
+
exports.getCachedApolloClient = getCachedApolloClient;
|
|
1083
|
+
exports.getCorrelationId = getCorrelationId;
|
|
1084
|
+
exports.getMcApiUrl = getMcApiUrl;
|
|
1085
|
+
exports.isLoggerEnabled = isLoggerEnabled;
|
|
1086
|
+
exports.logger = logger;
|
|
1087
|
+
exports.normalizeAllAppliedActionRights = normalizeAllAppliedActionRights;
|
|
1088
|
+
exports.normalizeAllAppliedDataFences = normalizeAllAppliedDataFences;
|
|
1089
|
+
exports.normalizeAllAppliedMenuVisibilities = normalizeAllAppliedMenuVisibilities;
|
|
1090
|
+
exports.normalizeAllAppliedPermissions = normalizeAllAppliedPermissions;
|
|
1091
|
+
exports.oidcStorage = oidcStorage;
|
|
1092
|
+
exports.selectProjectKeyFromUrl = selectProjectKeyFromUrl;
|
|
1093
|
+
exports.selectTeamIdFromStorage = selectTeamIdFromStorage;
|
|
1094
|
+
exports.selectUserId = selectUserId;
|
|
1095
|
+
exports.setCachedApolloClient = setCachedApolloClient;
|
|
1096
|
+
exports.useApplicationContext = useApplicationContext;
|
|
1097
|
+
exports.useCustomViewContext = useCustomViewContext;
|
|
1098
|
+
exports.useCustomViewParentDataRefresher = useCustomViewParentDataRefresher;
|
|
1099
|
+
exports.useMcLazyQuery = useMcLazyQuery;
|
|
1100
|
+
exports.useMcMutation = useMcMutation;
|
|
1101
|
+
exports.useMcQuery = useMcQuery;
|
|
1102
|
+
exports.useProjectExtensionImageRegex = useProjectExtensionImageRegex;
|
|
1103
|
+
exports.version = version;
|
|
1104
|
+
exports.withApplicationContext = withApplicationContext;
|
|
1105
|
+
exports.withProjectExtensionImageRegex = withProjectExtensionImageRegex;
|