@zengenti/contensis-react-base 3.0.0-beta.8 → 3.0.0-beta.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/README.md +1 -1
  2. package/cjs/{App-e3200f18.js → App-5a34ea98.js} +228 -181
  3. package/cjs/App-5a34ea98.js.map +1 -0
  4. package/cjs/{RouteLoader-df3de0cb.js → RouteLoader-2675e1c9.js} +31 -23
  5. package/cjs/RouteLoader-2675e1c9.js.map +1 -0
  6. package/cjs/{ToJs-697ace9f.js → ToJs-a9a8522b.js} +39 -34
  7. package/cjs/ToJs-a9a8522b.js.map +1 -0
  8. package/cjs/{actions-a24bf46e.js → actions-8dc9e8de.js} +5 -4
  9. package/cjs/actions-8dc9e8de.js.map +1 -0
  10. package/cjs/client.js +22 -44
  11. package/cjs/client.js.map +1 -1
  12. package/cjs/contensis-react-base.js +3955 -135
  13. package/cjs/contensis-react-base.js.map +1 -1
  14. package/cjs/forms.js +547 -580
  15. package/cjs/forms.js.map +1 -1
  16. package/cjs/{fromJSLeaveImmer-c00d597f.js → fromJSLeaveImmer-e74c673c.js} +2 -16
  17. package/cjs/fromJSLeaveImmer-e74c673c.js.map +1 -0
  18. package/cjs/{login-bc55ee33.js → login-6b9de6a1.js} +92 -55
  19. package/cjs/login-6b9de6a1.js.map +1 -0
  20. package/cjs/{reducers-fde41d6b.js → reducers-3a4f8971.js} +26 -25
  21. package/cjs/reducers-3a4f8971.js.map +1 -0
  22. package/cjs/redux.js +6 -5
  23. package/cjs/redux.js.map +1 -1
  24. package/cjs/routing.js +5 -4
  25. package/cjs/routing.js.map +1 -1
  26. package/cjs/sagas-594b5ecd.js +2090 -0
  27. package/cjs/sagas-594b5ecd.js.map +1 -0
  28. package/cjs/search.js +296 -1915
  29. package/cjs/search.js.map +1 -1
  30. package/cjs/{selectors-0ec95076.js → selectors-656da4b7.js} +8 -3
  31. package/cjs/selectors-656da4b7.js.map +1 -0
  32. package/cjs/setCachingHeaders-ee619bdf.js +12 -0
  33. package/cjs/setCachingHeaders-ee619bdf.js.map +1 -0
  34. package/cjs/user.js +21 -12
  35. package/cjs/user.js.map +1 -1
  36. package/cjs/util.js +17 -17
  37. package/cjs/util.js.map +1 -1
  38. package/cjs/{version-4f0f5fa6.js → version-330551f5.js} +34 -22
  39. package/cjs/version-330551f5.js.map +1 -0
  40. package/cjs/{version-be0c7b7a.js → version-eba6d09b.js} +2 -2
  41. package/{esm/version-ad2ec52c.js.map → cjs/version-eba6d09b.js.map} +1 -1
  42. package/esm/{App-f9e7d03b.js → App-a973f962.js} +228 -182
  43. package/esm/App-a973f962.js.map +1 -0
  44. package/esm/{RouteLoader-027215f2.js → RouteLoader-f607a134.js} +31 -23
  45. package/esm/RouteLoader-f607a134.js.map +1 -0
  46. package/esm/{ToJs-46761960.js → ToJs-4e02a04d.js} +38 -32
  47. package/esm/ToJs-4e02a04d.js.map +1 -0
  48. package/esm/{actions-b949ef5c.js → actions-180948dd.js} +5 -4
  49. package/esm/actions-180948dd.js.map +1 -0
  50. package/esm/client.js +24 -27
  51. package/esm/client.js.map +1 -1
  52. package/esm/contensis-react-base.js +3953 -134
  53. package/esm/contensis-react-base.js.map +1 -1
  54. package/esm/forms.js +547 -583
  55. package/esm/forms.js.map +1 -1
  56. package/esm/{fromJSLeaveImmer-392af4e3.js → fromJSLeaveImmer-0114ffcf.js} +2 -16
  57. package/esm/fromJSLeaveImmer-0114ffcf.js.map +1 -0
  58. package/esm/{login-6eab4c94.js → login-508cac0f.js} +92 -55
  59. package/esm/login-508cac0f.js.map +1 -0
  60. package/esm/{reducers-d6c0edb1.js → reducers-8e5d6232.js} +26 -25
  61. package/esm/reducers-8e5d6232.js.map +1 -0
  62. package/esm/redux.js +8 -7
  63. package/esm/redux.js.map +1 -1
  64. package/esm/routing.js +5 -4
  65. package/esm/routing.js.map +1 -1
  66. package/esm/sagas-1f2b2aa0.js +2000 -0
  67. package/esm/sagas-1f2b2aa0.js.map +1 -0
  68. package/esm/search.js +252 -1856
  69. package/esm/search.js.map +1 -1
  70. package/esm/{selectors-8fca7fb2.js → selectors-a5e5835b.js} +9 -6
  71. package/esm/selectors-a5e5835b.js.map +1 -0
  72. package/esm/setCachingHeaders-d49060e1.js +10 -0
  73. package/esm/setCachingHeaders-d49060e1.js.map +1 -0
  74. package/esm/user.js +23 -14
  75. package/esm/user.js.map +1 -1
  76. package/esm/util.js +17 -17
  77. package/esm/util.js.map +1 -1
  78. package/esm/{version-ad2ec52c.js → version-2485e2fb.js} +2 -2
  79. package/{cjs/version-be0c7b7a.js.map → esm/version-2485e2fb.js.map} +1 -1
  80. package/esm/{version-612d9ef0.js → version-c776a92b.js} +33 -22
  81. package/esm/version-c776a92b.js.map +1 -0
  82. package/models/app/pages/VersionInfo/components/VersionInfo.d.ts +1 -1
  83. package/models/forms/index.d.ts +3 -1
  84. package/models/index.d.ts +1 -0
  85. package/models/redux/appstate.d.ts +5 -10
  86. package/models/redux/sagas/navigation.d.ts +1 -1
  87. package/models/redux/selectors/navigation.d.ts +2 -1
  88. package/models/routing/components/RouteLoader.d.ts +2 -19
  89. package/models/routing/redux/actions.d.ts +1 -1
  90. package/models/routing/redux/selectors.d.ts +1 -1
  91. package/models/routing/routes.d.ts +9 -3
  92. package/models/routing/util/expressions.d.ts +3 -2
  93. package/models/routing/util/queries.d.ts +1 -1
  94. package/models/search/containers/withListing.d.ts +1 -1
  95. package/models/search/containers/withSearch.d.ts +1 -1
  96. package/models/search/hooks/useFacets.hook.d.ts +3 -0
  97. package/models/search/hooks/useListing.hook.d.ts +3 -0
  98. package/models/search/hooks/useMinilist.hook.d.ts +2 -9
  99. package/models/search/index.d.ts +6 -2
  100. package/models/search/models/Queries.d.ts +8 -5
  101. package/models/search/models/Search.d.ts +60 -28
  102. package/models/search/models/SearchActions.d.ts +9 -5
  103. package/models/search/models/SearchProps.d.ts +52 -7
  104. package/models/search/models/SearchState.d.ts +5 -1
  105. package/models/search/models/index.d.ts +3 -1
  106. package/models/search/redux/actions.d.ts +5 -2
  107. package/models/search/redux/reducers.d.ts +230 -314
  108. package/models/search/redux/sagas.d.ts +11 -7
  109. package/models/search/redux/selectors.d.ts +21 -24
  110. package/models/search/redux/util.d.ts +1 -0
  111. package/models/search/search/ContensisDeliveryApi.d.ts +1 -0
  112. package/models/search/search/expressions.d.ts +5 -8
  113. package/models/search/{redux → search}/queries.d.ts +0 -0
  114. package/models/search/search/util.d.ts +14 -0
  115. package/models/search/transformations/entry-to-filteritem.mapper.d.ts +2 -1
  116. package/models/search/transformations/filter-to-filterexpression.mapper.d.ts +6 -0
  117. package/models/search/transformations/filters-to-filterexpressions.mapper.d.ts +3 -0
  118. package/models/search/transformations/index.d.ts +3 -0
  119. package/models/search/transformations/queryParams-to-customapi.mapper.d.ts +3 -0
  120. package/models/search/transformations/state-to-searchuri.d.ts +2 -13
  121. package/models/server/features/linkdepth-api/LinkDepthSearchService.d.ts +24 -0
  122. package/models/server/features/linkdepth-api/QueryLevelResults.d.ts +50 -0
  123. package/models/server/features/linkdepth-api/api.d.ts +12 -0
  124. package/models/server/features/linkdepth-api/events-api.config.d.ts +37 -0
  125. package/models/server/features/linkdepth-api/search.d.ts +31 -0
  126. package/models/server/features/linkdepth-api/util.d.ts +11 -0
  127. package/models/server/middleware/bundleManipulation.d.ts +2 -1
  128. package/models/server/util/bundles.d.ts +17 -21
  129. package/models/server/util/getVersionInfo.d.ts +1 -0
  130. package/models/server/util/headers.d.ts +3 -2
  131. package/models/user/components/Login.d.ts +1 -2
  132. package/models/user/components/LoginForm.d.ts +1 -2
  133. package/models/user/hocs/withLogin.d.ts +4 -2
  134. package/models/user/hocs/withRegistration.d.ts +2 -0
  135. package/models/user/hooks/useLogin.d.ts +5 -3
  136. package/models/user/redux/reducers.d.ts +4 -5
  137. package/models/user/redux/sagas/login.d.ts +11 -8
  138. package/models/user/redux/selectors.d.ts +12 -6
  139. package/models/user/util/LoginHelper.class.d.ts +4 -3
  140. package/models/util/ContensisDeliveryApi.d.ts +4 -4
  141. package/models/util/json-mapper.d.ts +9 -3
  142. package/models/util/merge.d.ts +1 -0
  143. package/package.json +60 -55
  144. package/CHANGELOG.md +0 -293
  145. package/cjs/App-e3200f18.js.map +0 -1
  146. package/cjs/RouteLoader-df3de0cb.js.map +0 -1
  147. package/cjs/ToJs-697ace9f.js.map +0 -1
  148. package/cjs/actions-a24bf46e.js.map +0 -1
  149. package/cjs/fromJSLeaveImmer-c00d597f.js.map +0 -1
  150. package/cjs/login-bc55ee33.js.map +0 -1
  151. package/cjs/reducers-fde41d6b.js.map +0 -1
  152. package/cjs/selectors-0ec95076.js.map +0 -1
  153. package/cjs/version-4f0f5fa6.js.map +0 -1
  154. package/esm/App-f9e7d03b.js.map +0 -1
  155. package/esm/RouteLoader-027215f2.js.map +0 -1
  156. package/esm/ToJs-46761960.js.map +0 -1
  157. package/esm/actions-b949ef5c.js.map +0 -1
  158. package/esm/fromJSLeaveImmer-392af4e3.js.map +0 -1
  159. package/esm/login-6eab4c94.js.map +0 -1
  160. package/esm/reducers-d6c0edb1.js.map +0 -1
  161. package/esm/selectors-8fca7fb2.js.map +0 -1
  162. package/esm/version-612d9ef0.js.map +0 -1
  163. package/models/search/transformations/filters-to-filterexpression.d.ts +0 -1
  164. package/models/search/transformations/filters-to-filterexpression.mapper.d.ts +0 -2
  165. package/models/server/features/caching/cacheHashing.d.ts +0 -1
  166. package/package-lock.json +0 -14093
@@ -0,0 +1,2090 @@
1
+ 'use strict';
2
+
3
+ var log = require('loglevel');
4
+ var effects = require('@redux-saga/core/effects');
5
+ var contensisDeliveryApi = require('contensis-delivery-api');
6
+ var queryString = require('query-string');
7
+ var mapJson = require('jsonpath-mapper');
8
+ var contensisCoreApi = require('contensis-core-api');
9
+ var merge = require('deepmerge');
10
+
11
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
12
+
13
+ function _interopNamespace(e) {
14
+ if (e && e.__esModule) return e;
15
+ var n = Object.create(null);
16
+ if (e) {
17
+ Object.keys(e).forEach(function (k) {
18
+ if (k !== 'default') {
19
+ var d = Object.getOwnPropertyDescriptor(e, k);
20
+ Object.defineProperty(n, k, d.get ? d : {
21
+ enumerable: true,
22
+ get: function () { return e[k]; }
23
+ });
24
+ }
25
+ });
26
+ }
27
+ n["default"] = e;
28
+ return Object.freeze(n);
29
+ }
30
+
31
+ var log__namespace = /*#__PURE__*/_interopNamespace(log);
32
+ var mapJson__default = /*#__PURE__*/_interopDefaultLegacy(mapJson);
33
+ var merge__default = /*#__PURE__*/_interopDefaultLegacy(merge);
34
+
35
+ const ACTION_PREFIX = '@SEARCH/';
36
+ const APPLY_CONFIG = `${ACTION_PREFIX}APPLY_CONFIG`;
37
+ const CLEAR_FILTERS = `${ACTION_PREFIX}CLEAR_FILTERS`;
38
+ const DO_SEARCH = `${ACTION_PREFIX}DO_SEARCH`;
39
+ const EXECUTE_SEARCH = `${ACTION_PREFIX}EXECUTE_SEARCH`;
40
+ const EXECUTE_SEARCH_ERROR = `${ACTION_PREFIX}EXECUTE_SEARCH_ERROR`;
41
+ const EXECUTE_SEARCH_PRELOAD = `${ACTION_PREFIX}EXECUTE_SEARCH_PRELOAD`;
42
+ const LOAD_FILTERS = `${ACTION_PREFIX}LOAD_FILTERS`;
43
+ const LOAD_FILTERS_COMPLETE = `${ACTION_PREFIX}LOAD_FILTERS_COMPLETE`;
44
+ const LOAD_FILTERS_ERROR = `${ACTION_PREFIX}LOAD_FILTERS_ERROR`;
45
+ const SET_FEATURED_ENTRIES = `${ACTION_PREFIX}SET_FEATURED_ENTRIES`;
46
+ const SET_ROUTE_FILTERS = `${ACTION_PREFIX}SET_ROUTE_FILTERS`;
47
+ const SET_SEARCH_FILTERS = `${ACTION_PREFIX}SET_SEARCH_FILTERS`;
48
+ const SET_SEARCH_ENTRIES = `${ACTION_PREFIX}SET_SEARCH_ENTRIES`;
49
+ const SET_SELECTED_FILTER = `${ACTION_PREFIX}SET_SELECTED_FILTER`;
50
+ const UPDATE_CURRENT_FACET = `${ACTION_PREFIX}UPDATE_CURRENT_FACET`;
51
+ const UPDATE_CURRENT_TAB = `${ACTION_PREFIX}UPDATE_CURRENT_TAB`;
52
+ const UPDATE_SORT_ORDER = `${ACTION_PREFIX}UPDATE_SORT_ORDER`;
53
+ const UPDATE_PAGE_INDEX = `${ACTION_PREFIX}UPDATE_PAGE_INDEX`;
54
+ const UPDATE_SEARCH_TERM = `${ACTION_PREFIX}UPDATE_SEARCH_TERM`;
55
+ const UPDATE_SELECTED_FILTERS = `${ACTION_PREFIX}UPDATE_SELECTED_FILTERS`;
56
+
57
+ var types = /*#__PURE__*/Object.freeze({
58
+ __proto__: null,
59
+ APPLY_CONFIG: APPLY_CONFIG,
60
+ CLEAR_FILTERS: CLEAR_FILTERS,
61
+ DO_SEARCH: DO_SEARCH,
62
+ EXECUTE_SEARCH: EXECUTE_SEARCH,
63
+ EXECUTE_SEARCH_ERROR: EXECUTE_SEARCH_ERROR,
64
+ EXECUTE_SEARCH_PRELOAD: EXECUTE_SEARCH_PRELOAD,
65
+ LOAD_FILTERS: LOAD_FILTERS,
66
+ LOAD_FILTERS_COMPLETE: LOAD_FILTERS_COMPLETE,
67
+ LOAD_FILTERS_ERROR: LOAD_FILTERS_ERROR,
68
+ SET_FEATURED_ENTRIES: SET_FEATURED_ENTRIES,
69
+ SET_ROUTE_FILTERS: SET_ROUTE_FILTERS,
70
+ SET_SEARCH_FILTERS: SET_SEARCH_FILTERS,
71
+ SET_SEARCH_ENTRIES: SET_SEARCH_ENTRIES,
72
+ SET_SELECTED_FILTER: SET_SELECTED_FILTER,
73
+ UPDATE_CURRENT_FACET: UPDATE_CURRENT_FACET,
74
+ UPDATE_CURRENT_TAB: UPDATE_CURRENT_TAB,
75
+ UPDATE_SORT_ORDER: UPDATE_SORT_ORDER,
76
+ UPDATE_PAGE_INDEX: UPDATE_PAGE_INDEX,
77
+ UPDATE_SEARCH_TERM: UPDATE_SEARCH_TERM,
78
+ UPDATE_SELECTED_FILTERS: UPDATE_SELECTED_FILTERS
79
+ });
80
+
81
+ const withMappers = (action, mappers) => {
82
+ return { ...action,
83
+ mappers
84
+ };
85
+ };
86
+ const triggerSearch = ({
87
+ config,
88
+ context,
89
+ debug,
90
+ defaultLang,
91
+ excludeIds,
92
+ facet,
93
+ mapper,
94
+ mappers,
95
+ params
96
+ }) => {
97
+ return {
98
+ type: DO_SEARCH,
99
+ config,
100
+ context,
101
+ debug,
102
+ defaultLang,
103
+ excludeIds,
104
+ facet,
105
+ mapper,
106
+ mappers,
107
+ params
108
+ };
109
+ };
110
+ const initListing = ({
111
+ context,
112
+ facet,
113
+ mapper,
114
+ params
115
+ }) => {
116
+ return {
117
+ type: SET_ROUTE_FILTERS,
118
+ context,
119
+ facet,
120
+ mapper,
121
+ params
122
+ };
123
+ };
124
+ const navigate = (path, state) => {
125
+ return {
126
+ type: '@ROUTING/_SET_ROUTE',
127
+ path,
128
+ state
129
+ };
130
+ };
131
+ const clearFilters$1 = filterKey => {
132
+ return {
133
+ type: CLEAR_FILTERS,
134
+ filterKey
135
+ };
136
+ };
137
+ const updatePageIndex$1 = (pageIndex, scrollYPos) => {
138
+ return {
139
+ type: UPDATE_PAGE_INDEX,
140
+ pageIndex,
141
+ scrollYPos
142
+ };
143
+ };
144
+ const updateCurrentFacet$1 = facet => {
145
+ return {
146
+ type: UPDATE_CURRENT_FACET,
147
+ facet
148
+ };
149
+ };
150
+ const updateCurrentTab$1 = id => {
151
+ return {
152
+ type: UPDATE_CURRENT_TAB,
153
+ id
154
+ };
155
+ };
156
+ const updateSearchTerm$1 = term => {
157
+ return {
158
+ type: UPDATE_SEARCH_TERM,
159
+ term
160
+ };
161
+ };
162
+ const updateSelectedFilters = (filter, key, isUnknownItem = false, scrollYPos) => {
163
+ return {
164
+ type: UPDATE_SELECTED_FILTERS,
165
+ filter,
166
+ key,
167
+ isUnknownItem,
168
+ scrollYPos
169
+ };
170
+ };
171
+ const updateSortOrder$1 = (orderBy, facet) => {
172
+ return {
173
+ type: UPDATE_SORT_ORDER,
174
+ orderBy,
175
+ facet
176
+ };
177
+ };
178
+
179
+ var actions = /*#__PURE__*/Object.freeze({
180
+ __proto__: null,
181
+ withMappers: withMappers,
182
+ triggerSearch: triggerSearch,
183
+ initListing: initListing,
184
+ navigate: navigate,
185
+ clearFilters: clearFilters$1,
186
+ updatePageIndex: updatePageIndex$1,
187
+ updateCurrentFacet: updateCurrentFacet$1,
188
+ updateCurrentTab: updateCurrentTab$1,
189
+ updateSearchTerm: updateSearchTerm$1,
190
+ updateSelectedFilters: updateSelectedFilters,
191
+ updateSortOrder: updateSortOrder$1
192
+ });
193
+
194
+ exports.Context = void 0; // export type Context = 'facets' | 'listings' | 'minilist';
195
+
196
+ (function (Context) {
197
+ Context["facets"] = "facets";
198
+ Context["listings"] = "listings";
199
+ Context["minilist"] = "minilist";
200
+ })(exports.Context || (exports.Context = {}));
201
+
202
+ // or replace with a stub function for non-immutable gets
203
+
204
+ const makeFromJS = (returnType = globalThis.STATE_TYPE || 'immutable') => {
205
+ var _immutable, _immutable2;
206
+
207
+ return returnType === 'immutable' ? ((_immutable = globalThis.immutable) === null || _immutable === void 0 ? void 0 : _immutable.fromJSOrdered) || ((_immutable2 = globalThis.immutable) === null || _immutable2 === void 0 ? void 0 : _immutable2.fromJS) || (v => v) : v => v;
208
+ };
209
+
210
+ const getImmutableOrJS = (state, stateKey, fallbackValue, returnType = globalThis.STATE_TYPE || 'immutable') => {
211
+ // Find a fromJS function from global that is dynamically loaded in createStore
212
+ // or replace with a stub function for non-immutable gets
213
+ const fromJS = makeFromJS(returnType);
214
+
215
+ if (state && 'get' in state && typeof state.get === 'function' && 'getIn' in state && typeof state.getIn === 'function' && 'toJS' in state && typeof state.toJS === 'function') {
216
+ if (Array.isArray(stateKey)) return fromJS(state.getIn(stateKey, fallbackValue));
217
+ return fromJS(state.get(stateKey, fallbackValue));
218
+ }
219
+
220
+ if (Array.isArray(stateKey) && state && typeof state === 'object') {
221
+ const result = mapJson.jpath(stateKey.join('.'), state);
222
+ if (typeof result === 'undefined') return fallbackValue;
223
+ return result;
224
+ }
225
+
226
+ const result = state && typeof state === 'object' ? state[stateKey] : undefined;
227
+ if (typeof result === 'undefined') return fallbackValue;
228
+ return result;
229
+ };
230
+
231
+ const getSearchContext = state => getImmutableOrJS(state, ['search', 'context'], exports.Context.facets);
232
+ const getCurrent = (state, context = exports.Context.facets) => context === exports.Context.facets ? getCurrentFacet(state) : getCurrentListing(state);
233
+ const getCurrentFacet = state => getImmutableOrJS(state, ['search', 'currentFacet']);
234
+ const getCurrentListing = state => getImmutableOrJS(state, ['search', 'currentListing']);
235
+ const getCurrentTab = state => getImmutableOrJS(state, ['search', exports.Context.facets, getCurrentFacet(state), 'tabId'], 0);
236
+ const getFacets = (state, returnType) => getImmutableOrJS(state, ['search', exports.Context.facets], {}, returnType);
237
+ const getTabFacets = state => Object.fromEntries(Object.entries(getFacets(state, 'js')).filter(([key]) => getImmutableOrJS(getFacets(state), [key, 'tabId'], 0) === getCurrentTab(state)));
238
+ const getFacetTitles = state => Object.entries(getFacets(state, 'js')).map(([key, facet = {}]) => {
239
+ var _facet$pagingInfo;
240
+
241
+ return {
242
+ isSelected: getCurrentFacet(state) === key,
243
+ key,
244
+ title: facet.title,
245
+ totalCount: (_facet$pagingInfo = facet.pagingInfo) === null || _facet$pagingInfo === void 0 ? void 0 : _facet$pagingInfo.totalCount
246
+ };
247
+ });
248
+ const getFacet = (state, facetName = '', context = exports.Context.facets, returnType) => {
249
+ const currentFacet = facetName || getCurrentFacet(state);
250
+ return getImmutableOrJS(state, ['search', context, currentFacet], {}, returnType);
251
+ };
252
+ const getListing = (state, listing = '') => {
253
+ const currentListing = listing || getCurrentListing(state);
254
+ return getImmutableOrJS(state, ['search', exports.Context.listings, currentListing], {});
255
+ };
256
+ const getFilters = (state, facet, context = exports.Context.facets, returnType) => {
257
+ return getImmutableOrJS(state, ['search', context, facet || getCurrent(state, context), 'filters'], {}, returnType);
258
+ };
259
+ const getRenderableFilters = (state, facet = '', context = exports.Context.facets) => Object.fromEntries(Object.entries(getFilters(state, facet, context, 'js')).filter(([, f = {}]) => typeof f.renderable !== 'boolean' ? true : f.renderable));
260
+ const getFiltersToLoad = (state, facet, context = exports.Context.facets, returnType) => {
261
+ const filters = getFilters(state, facet, context, returnType);
262
+ const loadedFilters = Object.entries(filters).map(([key, f = {}]) => [key, (f.items || []).filter(i => {
263
+ const title = i === null || i === void 0 ? void 0 : i.title;
264
+ return typeof title !== 'undefined' && !!title;
265
+ }).length > 0 && (f.isError || false) === false]);
266
+ return loadedFilters.map(([filterKey, isLoaded]) => !isLoaded ? filterKey : null).filter(f => !!f);
267
+ }; // We lowercase the filter key unless it's an ISO date string where the T must be uppercase
268
+
269
+ const getSelectedFilters = (state, facet = '', context = exports.Context.facets, returnType) => {
270
+ const filters = getFilters(state, facet, context, 'js');
271
+ const isoDateRegex = RegExp(/\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d/);
272
+ const selectedFilters = Object.fromEntries(Object.entries(filters).map(([key, filter = {}]) => [key, (filter.items || []).filter(item => !!(item.isSelected || false)).map(item => {
273
+ const key = (item === null || item === void 0 ? void 0 : item.key) || '';
274
+ const isIsoDate = isoDateRegex.test(key);
275
+ return isIsoDate ? key : typeof key.toLowerCase !== 'undefined' ? key.toLowerCase() : key;
276
+ })]));
277
+ const fromJS = makeFromJS(returnType);
278
+ return fromJS(selectedFilters);
279
+ };
280
+ const getResults = (state, current = '', context = exports.Context.facets, returnType) => {
281
+ return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'results'], [], returnType);
282
+ };
283
+ const getIsInternalPaging = (state, current, context = exports.Context.facets) => {
284
+ return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'queryParams', 'internalPaging'], false);
285
+ };
286
+ const getIsLoaded = (state, context = exports.Context.facets, facet) => {
287
+ return !!getImmutableOrJS(state, ['search', context, facet || getCurrent(state, context), 'queryDuration'], 0);
288
+ };
289
+ const getIsLoading = (state, context = exports.Context.facets, facet) => {
290
+ return getImmutableOrJS(state, ['search', context, facet || getCurrent(state, context), 'entries', 'isLoading']);
291
+ };
292
+ const getIsSsr = state => getImmutableOrJS(state, ['search', 'config', 'ssr'], false);
293
+ const getFeaturedResults = (state, current = '', context = exports.Context.facets, returnType) => {
294
+ return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'featuredResults'], [], returnType);
295
+ };
296
+ const getPaging = (state, current = '', context = exports.Context.facets, returnType) => {
297
+ return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'pagingInfo'], {}, returnType);
298
+ };
299
+ const getPageIndex = (state, current = '', context = exports.Context.facets) => {
300
+ return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'pagingInfo', 'pageIndex']);
301
+ };
302
+ const getPrevPageIndex = (state, current = '', context = exports.Context.facets) => {
303
+ return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'pagingInfo', 'prevPageIndex']);
304
+ };
305
+ const getPageIsLoading = (state, current = '', context = exports.Context.facets) => {
306
+ return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'pagingInfo', 'isLoading']);
307
+ };
308
+ const getPagesLoaded = (state, current = '', context = exports.Context.facets) => {
309
+ return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'pagingInfo', 'pagesLoaded'], [], 'js');
310
+ };
311
+ const getTotalCount = (state, current = '', context = exports.Context.facets) => {
312
+ return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'pagingInfo', 'totalCount']);
313
+ };
314
+ const getSearchTerm = state => getImmutableOrJS(state, ['search', 'term']);
315
+ const getSearchTabs = (state, returnType) => getImmutableOrJS(state, ['search', 'tabs'], [], returnType);
316
+ const getQueryParams = (state, current = '', context = exports.Context.facets) => {
317
+ return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'queryParams'], {}, 'js');
318
+ };
319
+ const getQueryParameter = ({
320
+ state,
321
+ facet,
322
+ context = exports.Context.facets
323
+ }, key, ifnull = null) => {
324
+ return getImmutableOrJS(getQueryParams(state, facet, context), key, ifnull, 'js');
325
+ };
326
+ const getCustomApi = (state, current, context = exports.Context.facets, returnType) => {
327
+ return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'customApi'], null, returnType);
328
+ };
329
+ const getCustomEnv = (state, current, context = exports.Context.facets) => {
330
+ return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'env']);
331
+ };
332
+ const getTabsAndFacets = (state, returnType) => {
333
+ const tabs = getSearchTabs(state, 'js');
334
+ const facets = getFacets(state, 'js');
335
+ const tabsAndFacets = (tabs || []).map((tab = {}) => {
336
+ const fieldsToCount = tab.totalCount;
337
+ let countFields;
338
+ if (typeof fieldsToCount === 'string') countFields = [[fieldsToCount]];
339
+ const thisTabFacets = Object.entries(facets).filter(([key]) => getImmutableOrJS(facets, [key, 'tabId'], 0) === tab.id);
340
+ const thisTabTotal = thisTabFacets.map(([facetName, facet = {}]) => {
341
+ if (!countFields || countFields.find((f = []) => (f === null || f === void 0 ? void 0 : f[0]) === facetName)) return getImmutableOrJS(facet, ['pagingInfo', 'totalCount']);
342
+ return 0;
343
+ }).reduce((a, b) => a + b, 0);
344
+ return { ...tab,
345
+ [exports.Context.facets]: Object.fromEntries(thisTabFacets),
346
+ totalCount: thisTabTotal
347
+ };
348
+ });
349
+ const fromJS = makeFromJS(returnType);
350
+ return fromJS(tabsAndFacets);
351
+ };
352
+ const getSearchTotalCount = state => {
353
+ const tabsAndFacets = getTabsAndFacets(state, 'js');
354
+ const wholeSearchTotal = tabsAndFacets.map((t = {}) => t.totalCount).reduce((a, b) => a + b, 0);
355
+ return wholeSearchTotal;
356
+ };
357
+ const getFacetsTotalCount = state => {
358
+ const facets = getFacets(state);
359
+ const wholeSearchTotal = Object.entries(facets).map(([, t = {}]) => {
360
+ var _t$pagingInfo;
361
+
362
+ return ((_t$pagingInfo = t.pagingInfo) === null || _t$pagingInfo === void 0 ? void 0 : _t$pagingInfo.totalCount) || 0;
363
+ }).reduce((a, b) => a + b, 0);
364
+ return wholeSearchTotal;
365
+ }; // An exported copy of the relevant selectors scoped by default to a facets context
366
+
367
+ const selectFacets = {
368
+ getCurrent: getCurrentFacet,
369
+ getCurrentTab,
370
+ getCustomApi,
371
+ getCustomEnv,
372
+ getFacet,
373
+ getFacetTitles,
374
+ getFacets,
375
+ getFacetsTotalCount,
376
+ getFeaturedResults,
377
+ getFilters,
378
+ getFiltersToLoad,
379
+ getIsLoaded,
380
+ getIsLoading,
381
+ getPageIndex,
382
+ getPageIsLoading,
383
+ getPagesLoaded,
384
+ getPaging,
385
+ getQueryParams: (state, facet) => getQueryParams(state, facet, exports.Context.facets),
386
+ getQueryParameter: ({
387
+ state,
388
+ facet
389
+ }, key, ifnull) => getQueryParameter({
390
+ state,
391
+ facet,
392
+ context: exports.Context.facets
393
+ }, key, ifnull),
394
+ getRenderableFilters,
395
+ getResults,
396
+ getTabFacets,
397
+ getTabsAndFacets,
398
+ getTotalCount,
399
+ getSearchTabs,
400
+ getSearchTerm,
401
+ getSearchTotalCount,
402
+ getSelectedFilters
403
+ }; // An exported copy of the relevant selectors pre-scoped to a listing context
404
+
405
+ const selectListing = {
406
+ getCurrent: getCurrentListing,
407
+ getFeaturedResults: (state, listing = '') => getFeaturedResults(state, listing, exports.Context.listings, 'js'),
408
+ getFilters: (state, listing = '') => getFilters(state, listing, exports.Context.listings, 'js'),
409
+ getFiltersToLoad: (state, listing = '') => getFiltersToLoad(state, listing, exports.Context.listings),
410
+ getListing,
411
+ getIsLoaded: state => getIsLoaded(state, exports.Context.listings),
412
+ getIsLoading: state => getIsLoading(state, exports.Context.listings),
413
+ getPageIndex: (state, listing = '') => getPageIndex(state, listing, exports.Context.listings),
414
+ getPaging: (state, listing = '') => getPaging(state, listing, exports.Context.listings, 'js'),
415
+ getPageIsLoading: (state, listing = '') => getPageIsLoading(state, listing, exports.Context.listings),
416
+ getPagesLoaded: (state, listing = '') => getPagesLoaded(state, listing, exports.Context.listings),
417
+ getQueryParams: (state, listing = '') => getQueryParams(state, listing, exports.Context.listings),
418
+ getQueryParameter: ({
419
+ state,
420
+ facet
421
+ }, key, ifnull) => getQueryParameter({
422
+ state,
423
+ facet,
424
+ context: exports.Context.listings
425
+ }, key, ifnull),
426
+ getRenderableFilters: (state, listing = '') => getRenderableFilters(state, listing, exports.Context.listings),
427
+ getResults: (state, listing = '') => getResults(state, listing, exports.Context.listings, 'js'),
428
+ getSearchTerm,
429
+ getTotalCount: (state, listing = '') => getTotalCount(state, listing, exports.Context.listings),
430
+ getSelectedFilters: (state, listing = '') => getSelectedFilters(state, listing, exports.Context.listings, 'js')
431
+ };
432
+ const selectCurrentPath = state => getImmutableOrJS(state, ['routing', 'currentPath']);
433
+ const selectCurrentProject = state => getImmutableOrJS(state, ['routing', 'currentProject']);
434
+ const selectVersionStatus = state => getImmutableOrJS(state, ['version', 'contensisVersionStatus']);
435
+
436
+ var selectors = /*#__PURE__*/Object.freeze({
437
+ __proto__: null,
438
+ getSearchContext: getSearchContext,
439
+ getCurrent: getCurrent,
440
+ getCurrentFacet: getCurrentFacet,
441
+ getCurrentListing: getCurrentListing,
442
+ getCurrentTab: getCurrentTab,
443
+ getFacets: getFacets,
444
+ getTabFacets: getTabFacets,
445
+ getFacetTitles: getFacetTitles,
446
+ getFacet: getFacet,
447
+ getListing: getListing,
448
+ getFilters: getFilters,
449
+ getRenderableFilters: getRenderableFilters,
450
+ getFiltersToLoad: getFiltersToLoad,
451
+ getSelectedFilters: getSelectedFilters,
452
+ getResults: getResults,
453
+ getIsInternalPaging: getIsInternalPaging,
454
+ getIsLoaded: getIsLoaded,
455
+ getIsLoading: getIsLoading,
456
+ getIsSsr: getIsSsr,
457
+ getFeaturedResults: getFeaturedResults,
458
+ getPaging: getPaging,
459
+ getPageIndex: getPageIndex,
460
+ getPrevPageIndex: getPrevPageIndex,
461
+ getPageIsLoading: getPageIsLoading,
462
+ getPagesLoaded: getPagesLoaded,
463
+ getTotalCount: getTotalCount,
464
+ getSearchTerm: getSearchTerm,
465
+ getSearchTabs: getSearchTabs,
466
+ getQueryParams: getQueryParams,
467
+ getQueryParameter: getQueryParameter,
468
+ getCustomApi: getCustomApi,
469
+ getCustomEnv: getCustomEnv,
470
+ getTabsAndFacets: getTabsAndFacets,
471
+ getSearchTotalCount: getSearchTotalCount,
472
+ getFacetsTotalCount: getFacetsTotalCount,
473
+ selectFacets: selectFacets,
474
+ selectListing: selectListing,
475
+ selectCurrentPath: selectCurrentPath,
476
+ selectCurrentProject: selectCurrentProject,
477
+ selectVersionStatus: selectVersionStatus
478
+ });
479
+
480
+ const now = () => {
481
+ if (typeof window == 'undefined') {
482
+ return Date.now();
483
+ }
484
+
485
+ return window.performance.now();
486
+ };
487
+
488
+ const getClientConfig = (project, env) => {
489
+ let config = DELIVERY_API_CONFIG;
490
+ /* global DELIVERY_API_CONFIG */
491
+
492
+ if (project) {
493
+ config.projectId = project;
494
+ }
495
+
496
+ if (typeof window != 'undefined' && PROXY_DELIVERY_API
497
+ /* global PROXY_DELIVERY_API */
498
+ ) {
499
+ // ensure a relative url is used to bypass the need for CORS (separate OPTIONS calls)
500
+ config.rootUrl = env || '';
501
+ config.responseHandler = {
502
+ 404: () => null
503
+ };
504
+ }
505
+
506
+ return config;
507
+ };
508
+
509
+ class CacheNode {
510
+ constructor(key, value) {
511
+ this.key = key;
512
+ this.value = value;
513
+ this.next = null;
514
+ this.prev = null;
515
+ }
516
+
517
+ }
518
+
519
+ class LruCache {
520
+ constructor(limit = 100) {
521
+ this.map = {};
522
+ this.head = null;
523
+ this.tail = null;
524
+ this.limit = limit || 100;
525
+ this.size = 0;
526
+ }
527
+
528
+ get(key) {
529
+ if (this.map[key]) {
530
+ let value = this.map[key].value;
531
+ let node = new CacheNode(key, value);
532
+ this.remove(key);
533
+ this.setHead(node);
534
+ return value;
535
+ }
536
+ }
537
+
538
+ set(key, value) {
539
+ let node = new CacheNode(key, value);
540
+
541
+ if (this.map[key]) {
542
+ this.remove(key);
543
+ } else {
544
+ if (this.size >= this.limit) {
545
+ delete this.map[this.tail.key];
546
+ this.size--;
547
+ this.tail = this.tail.prev;
548
+ this.tail.next = null;
549
+ }
550
+ }
551
+
552
+ this.setHead(node);
553
+ }
554
+
555
+ setHead(node) {
556
+ node.next = this.head;
557
+ node.prev = null;
558
+
559
+ if (this.head) {
560
+ this.head.prev = node;
561
+ }
562
+
563
+ this.head = node;
564
+
565
+ if (!this.tail) {
566
+ this.tail = node;
567
+ }
568
+
569
+ this.size++;
570
+ this.map[node.key] = node;
571
+ }
572
+
573
+ remove(key) {
574
+ let node = this.map[key];
575
+
576
+ if (node.prev) {
577
+ node.prev.next = node.next;
578
+ } else {
579
+ this.head = node.next;
580
+ }
581
+
582
+ if (node.next) {
583
+ node.next.prev = node.prev;
584
+ } else {
585
+ this.tail = node.prev;
586
+ }
587
+
588
+ delete this.map[key];
589
+ this.size--;
590
+ }
591
+
592
+ }
593
+
594
+ class CachedSearch {
595
+ constructor() {
596
+ this.cache = new LruCache();
597
+ this.taxonomyLookup = {};
598
+ }
599
+
600
+ search(query, linkDepth, project, env) {
601
+ const client = contensisDeliveryApi.Client.create(getClientConfig(project, env));
602
+ return this.request(project + JSON.stringify(query) + linkDepth.toString(), () => client.entries.search(query, linkDepth));
603
+ }
604
+
605
+ getTaxonomyNodeByPath(path, project, env) {
606
+ const client = contensisDeliveryApi.Client.create(getClientConfig(project, env));
607
+ return this.request(`[TAXONOMY NODE] ${path}`, () => client.taxonomy.getNodeByPath({
608
+ path: path,
609
+ order: 'defined',
610
+ childDepth: 2
611
+ }).then(node => this.extendTaxonomyNode(node)));
612
+ }
613
+
614
+ request(key, execute) {
615
+ if (!this.cache.get(key) || typeof window == 'undefined') {
616
+ let promise = execute();
617
+ this.cache.set(key, promise);
618
+ promise.catch(() => {
619
+ this.cache.remove(key);
620
+ });
621
+ }
622
+
623
+ return this.cache.get(key);
624
+ }
625
+
626
+ extendTaxonomyNode(node) {
627
+ let id = this.getTaxonomyId(node);
628
+ this.taxonomyLookup[id] = node.key;
629
+ return { ...node,
630
+ id,
631
+ children: node.children ? node.children.map(n => this.extendTaxonomyNode(n)) : null
632
+ };
633
+ }
634
+
635
+ getTaxonomyId(node) {
636
+ if (node.key) {
637
+ let parts = node.key.split('/');
638
+ return parts[parts.length - 1];
639
+ }
640
+
641
+ return '';
642
+ }
643
+
644
+ fetch(uri, opts = {}) {
645
+ return this.request(`[FETCH] ${uri} ${JSON.stringify(opts)}`, () => fetch(uri, opts));
646
+ }
647
+
648
+ }
649
+
650
+ const cachedSearch = new CachedSearch();
651
+
652
+ // eslint-disable-next-line import/default
653
+ function fixFreeTextForElastic(s) {
654
+ const illegalChars = ['>', '<', '=', '|', '!', '{', '}', '[', ']', '^', '~', '*', '?', ':', '\\', '/'];
655
+ const illegalRegEx = new RegExp(illegalChars.map(c => '\\' + c).join('|'), 'g');
656
+ s = s.replace(illegalRegEx, ''); // s = s.replace(encodedRegEx, ''); // (m) => '\\\\' + m);
657
+
658
+ return s;
659
+ }
660
+ const timedSearch = async (query, linkDepth = 0, projectId, env) => {
661
+ if (!query) return null;
662
+ let duration = 0;
663
+ const start = now();
664
+ const payload = await cachedSearch.search(query, linkDepth, projectId, env);
665
+ const end = now();
666
+ duration = end - start;
667
+ return {
668
+ duration,
669
+ payload
670
+ };
671
+ };
672
+ const getItemsFromResult = result => {
673
+ const {
674
+ payload
675
+ } = result || {};
676
+
677
+ if (payload) {
678
+ if (Array.isArray(payload)) return payload;
679
+ if (Array.isArray(payload.items)) return payload.items;
680
+ return payload;
681
+ }
682
+
683
+ return [];
684
+ };
685
+ const extractQuotedPhrases = searchTerm => {
686
+ const pattern = new RegExp(/(?=["'])(?:"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]*(?:\\[\s\S][^'\\]*)*')/gm);
687
+ return (searchTerm.match(pattern) || []).map(match => match.replace(/"/g, ''));
688
+ };
689
+ const buildUrl = (route, params) => {
690
+ const qs = queryString.stringify(params);
691
+ const path = qs ? `${route}${route.includes('?') ? '&' : '?'}${qs}` : route;
692
+ return path;
693
+ };
694
+ /**
695
+ * Returns all params from the current route query string or static route
696
+ * Supply static route argument if reading parameters from the route path
697
+ * Supply location argument for the params to be read in SSR
698
+ * @param staticRoute Matched static route from react-router 5 or 6
699
+ * @param location location object containing at least pathname and search
700
+ * @returns Keyed params object
701
+ */
702
+
703
+ const routeParams = (staticRoute, location) => {
704
+ var _staticRoute$match;
705
+
706
+ // match.params is react-router-config/react-router@5 style
707
+ // params is supplied with RouteObject in react-router@6
708
+ const pathParams = (staticRoute === null || staticRoute === void 0 ? void 0 : (_staticRoute$match = staticRoute.match) === null || _staticRoute$match === void 0 ? void 0 : _staticRoute$match.params) || (staticRoute === null || staticRoute === void 0 ? void 0 : staticRoute.params) || {};
709
+ const queryParams = queryString.parse(typeof window !== 'undefined' ? window.location.search : (location === null || location === void 0 ? void 0 : location.search) || '');
710
+ return { ...pathParams,
711
+ ...queryParams
712
+ };
713
+ };
714
+ const callCustomApi = async (customApi, filters) => {
715
+ const apiUri = customApi.uri || '';
716
+ let uri = buildUrl(apiUri, filters);
717
+ if (!uri) throw new Error('uri is required to use customApi');
718
+ if (typeof window == 'undefined' && uri.startsWith('/')) uri = `http://localhost:3001${uri}`;
719
+ const response = await cachedSearch.fetch(uri);
720
+ return await response.clone().json();
721
+ };
722
+ const removeEmptyAttributes = obj => {
723
+ Object.entries(obj).forEach(([key, val]) => val && typeof val === 'object' && removeEmptyAttributes(val) || (typeof val === 'undefined' || val === null || val === '') && delete obj[key]);
724
+ return obj;
725
+ };
726
+ const toArray = (obj, seperator = ',') => typeof obj === 'undefined' || obj === null ? obj : Array.isArray(obj) ? obj : obj.split(seperator); // assumes array elements are primitive types
727
+
728
+ const areArraysEqualSets = (a1, a2) => {
729
+ const superSet = {};
730
+
731
+ for (const ai of a1) {
732
+ const e = ai + typeof ai;
733
+ superSet[e] = 1;
734
+ }
735
+
736
+ for (const ai of a2) {
737
+ const e = ai + typeof ai;
738
+
739
+ if (!superSet[e]) {
740
+ return false;
741
+ }
742
+
743
+ superSet[e] = 2;
744
+ }
745
+
746
+ for (const e in superSet) {
747
+ if (superSet[e] === 1) {
748
+ return false;
749
+ }
750
+ }
751
+
752
+ return true;
753
+ };
754
+
755
+ const searchUriTemplate = {
756
+ path: ({
757
+ state,
758
+ facet,
759
+ pageIndex
760
+ }) => {
761
+ const currentFacet = getSearchContext(state) !== exports.Context.listings && (facet || getCurrentFacet(state));
762
+ const currentPath = selectCurrentPath(state) || '/search';
763
+ const newPath = currentFacet ? `${currentPath}/${currentFacet}` : currentPath;
764
+ if (pageIndex) return `${newPath}/${pageIndex + 1}`;
765
+ return newPath;
766
+ },
767
+ search: ({
768
+ state,
769
+ facet,
770
+ orderBy,
771
+ term
772
+ }) => {
773
+ const searchContext = getSearchContext(state); // Lose stateFilters and currentSearch if a new
774
+ // term is passed via an argument
775
+
776
+ const stateFilters = term ? {} : Object.fromEntries(Object.entries(getSelectedFilters(state, facet, searchContext, 'js')).map(([key, f]) => [key, f === null || f === void 0 ? void 0 : f.join(',')]));
777
+ const currentSearch = !term && getImmutableOrJS(state, ['routing', 'location', 'search']);
778
+ const currentQs = removeEmptyAttributes(queryString.parse(currentSearch));
779
+ if (orderBy) currentQs.orderBy = orderBy;
780
+ const searchTerm = getSearchTerm(state); // Merge the stateFilters with any current qs to build the new qs
781
+
782
+ const mergedSearch = removeEmptyAttributes({ ...merge__default["default"](currentQs, stateFilters),
783
+ term: searchTerm
784
+ });
785
+ return queryString.stringify(mergedSearch);
786
+ },
787
+ hash: state => getImmutableOrJS(state, ['routing', 'location', 'hash'], '').replace('#', '')
788
+ };
789
+
790
+ const mapStateToSearchUri = params => mapJson__default["default"](params, searchUriTemplate);
791
+
792
+ const DataFormats = {
793
+ asset: 'asset',
794
+ entry: 'entry',
795
+ webpage: 'webpage'
796
+ };
797
+ const FilterExpressionTypes = {
798
+ contentType: 'contentType',
799
+ field: 'field'
800
+ };
801
+ const sys = {
802
+ allUris: 'sys.allUris',
803
+ contentTypeId: 'sys.contentTypeId',
804
+ dataFormat: 'sys.dataFormat',
805
+ filename: 'sys.properties.filename',
806
+ id: 'sys.id',
807
+ includeInSearch: 'sys.metadata.includeInSearch',
808
+ language: 'sys.language',
809
+ uri: 'sys.uri',
810
+ versionStatus: 'sys.versionStatus'
811
+ };
812
+ const Fields = {
813
+ entryDescription: 'entryDescription',
814
+ entryTitle: 'entryTitle',
815
+ keywords: 'keywords',
816
+ searchContent: 'searchContent',
817
+ sys,
818
+ contentTypeId: 'sys.contentTypeId',
819
+ wildcard: '*'
820
+ };
821
+
822
+ const fieldExpression = (field, value, operator = 'equalTo', weight) => {
823
+ if (!field || !value || Array.isArray(value) && value.length === 0) return [];
824
+ if (Array.isArray(field)) // If an array of fieldIds have been provided, call self for each fieldId
825
+ // to generate expressions that are combined with an 'or' operator
826
+ return [contensisCoreApi.Op.or(...field.map(fieldId => fieldExpression(fieldId, value, operator, weight)).flat())];
827
+ if (operator === 'between') return between(field, value);
828
+ if (Array.isArray(value)) return equalToOrIn(field, value, operator);else return !weight ? equalToOrIn(field, value, operator) : [equalToOrIn(field, value, operator)[0].weight(weight)];
829
+ };
830
+ const contentTypeIdExpression = (contentTypeIds, webpageTemplates, assetTypes) => {
831
+ const expressions = [];
832
+ if (!contentTypeIds && !webpageTemplates && !assetTypes) return expressions;
833
+
834
+ if (contentTypeIds && contentTypeIds.length > 0) {
835
+ expressions.push(...dataFormatExpression(contentTypeIds, DataFormats.entry));
836
+ }
837
+
838
+ if (webpageTemplates && webpageTemplates.length > 0) {
839
+ expressions.push(...dataFormatExpression(webpageTemplates, DataFormats.webpage));
840
+ }
841
+
842
+ if (assetTypes && assetTypes.length > 0) {
843
+ expressions.push(...dataFormatExpression(assetTypes, DataFormats.asset));
844
+ }
845
+
846
+ if (expressions.length > 1) return [contensisCoreApi.Op.or(...expressions)];
847
+ return expressions;
848
+ };
849
+ const filterExpressions = (filters, isOptional = false) => {
850
+ if (!filters) return [];
851
+ const expressions = [];
852
+ filters.map(selectedFilter => {
853
+ if (selectedFilter.logicOperator === 'and') // using 'and' logic operator we loop through each filter
854
+ // and loop through all values to add an expression for each filter value
855
+ selectedFilter.values.forEach(value => expressions.push(...fieldExpression(selectedFilter.key, value, selectedFilter.fieldOperator || 'equalTo')));else if (selectedFilter.logicOperator === 'not') {
856
+ const fieldExpressions = fieldExpression(selectedFilter.key, selectedFilter.values, selectedFilter.fieldOperator || 'in');
857
+ fieldExpressions.forEach(expr => {
858
+ expressions.push(contensisCoreApi.Op.not(expr));
859
+ });
860
+ } // using 'or' logic operator we loop over each filter
861
+ // and simply add the array of values to an expression with an 'in' operator
862
+ else expressions.push(...fieldExpression(selectedFilter.key, selectedFilter.values, selectedFilter.fieldOperator || 'in'));
863
+ if (isOptional) expressions.push(contensisCoreApi.Op.not(fieldExpression(selectedFilter.key, true, 'exists')[0]));
864
+ });
865
+ return expressions;
866
+ };
867
+ const dataFormatExpression = (contentTypeIds, dataFormat = DataFormats.entry) => {
868
+ if (contentTypeIds && contentTypeIds.length > 0) {
869
+ /**
870
+ * We have an array of contentTypeIds some may be prefixed with a "!"
871
+ * to indicate this is a "not" expression
872
+ */
873
+ const withContentTypeIds = contentTypeIds.filter(c => !c.startsWith('!'));
874
+ const notContentTypeIds = contentTypeIds.filter(c => c.startsWith('!')).map(id => id.substring(1));
875
+ const andExpr = contensisCoreApi.Op.and();
876
+ const dataFormatExpr = fieldExpression(Fields.sys.dataFormat, dataFormat)[0];
877
+ const withExpr = fieldExpression(Fields.sys.contentTypeId, withContentTypeIds)[0];
878
+ const notExpr = contensisCoreApi.Op.not(fieldExpression(Fields.sys.contentTypeId, notContentTypeIds)[0]);
879
+ andExpr.add(dataFormatExpr);
880
+ if (withContentTypeIds.length > 0 && withExpr) andExpr.add(withExpr);
881
+ if (notContentTypeIds.length > 0 && notExpr) andExpr.add(notExpr);
882
+ return [andExpr];
883
+ }
884
+
885
+ return [];
886
+ };
887
+ const featuredResultsExpression = ({
888
+ contentTypeId,
889
+ fieldId,
890
+ fieldValue = true
891
+ } = {}) => {
892
+ const expressions = [];
893
+
894
+ if (contentTypeId) {
895
+ expressions.push(...contentTypeIdExpression(Array.isArray(contentTypeId) ? contentTypeId : [contentTypeId]));
896
+ }
897
+
898
+ if (fieldId && fieldValue) {
899
+ expressions.push(...fieldExpression(fieldId, fieldValue));
900
+ }
901
+
902
+ return expressions;
903
+ };
904
+ const languagesExpression = languages => fieldExpression(Fields.sys.language, languages);
905
+ const includeInSearchExpressions = (webpageTemplates, includeInSearchFields) => {
906
+ const expressions = []; // Or include this expression if we have explicity specified non-default includeInSearch fields
907
+
908
+ if (Array.isArray(includeInSearchFields)) expressions.push(...includeInSearchFields.map(includeInSearchField => contensisCoreApi.Op.or(contensisCoreApi.Op.and(contensisCoreApi.Op.exists(includeInSearchField, true), contensisCoreApi.Op.equalTo(includeInSearchField, true)), contensisCoreApi.Op.exists(includeInSearchField, false)))); // If webpageTemplates have been specified, include this expression
909
+ // with the default includeInSearch field from classic Contensis.
910
+
911
+ if (Array.isArray(webpageTemplates) && webpageTemplates.length > 0) expressions.push(contensisCoreApi.Op.or(contensisCoreApi.Op.and(contensisCoreApi.Op.exists(Fields.sys.includeInSearch, true), contensisCoreApi.Op.equalTo(Fields.sys.includeInSearch, true)), contensisCoreApi.Op.exists(Fields.sys.includeInSearch, false)));
912
+ return expressions;
913
+ };
914
+ const defaultExpressions = versionStatus => {
915
+ return [contensisCoreApi.Op.equalTo(Fields.sys.versionStatus, versionStatus)];
916
+ };
917
+ const includeIdsExpression = includeIds => {
918
+ if (Array.isArray(includeIds) && includeIds.length > 0) {
919
+ return fieldExpression(Fields.sys.id, includeIds);
920
+ } else return [];
921
+ };
922
+ const excludeIdsExpression = excludeIds => {
923
+ if (Array.isArray(excludeIds) && excludeIds.length > 0) {
924
+ const [expr] = fieldExpression(Fields.sys.id, excludeIds);
925
+ return [contensisCoreApi.Op.not(expr)];
926
+ } else return [];
927
+ };
928
+ const orderByExpression = orderBy => {
929
+ let expression;
930
+
931
+ if (orderBy && orderBy.length > 0) {
932
+ expression = contensisCoreApi.OrderBy;
933
+
934
+ for (const ob of orderBy) {
935
+ var _expression, _expression2;
936
+
937
+ expression = ob.startsWith('-') ? (_expression = expression) === null || _expression === void 0 ? void 0 : _expression.desc(ob.substring(1)) : (_expression2 = expression) === null || _expression2 === void 0 ? void 0 : _expression2.asc(ob);
938
+ }
939
+ }
940
+
941
+ return expression;
942
+ };
943
+
944
+ const equalToOrIn = (field, value, operator = 'equalTo') => {
945
+ if (value.length === 0) return [];
946
+
947
+ if (Array.isArray(value)) {
948
+ if (operator === 'equalTo' || operator === 'in') return [contensisCoreApi.Op.in(field, ...value)];
949
+ const expressions = value.map(innerValue => {
950
+ var _between, _distanceWithin;
951
+
952
+ switch (operator) {
953
+ case 'between':
954
+ return (_between = between(field, innerValue)) === null || _between === void 0 ? void 0 : _between[0];
955
+
956
+ case 'distanceWithin':
957
+ return (_distanceWithin = distanceWithin(field, innerValue)) === null || _distanceWithin === void 0 ? void 0 : _distanceWithin[0];
958
+
959
+ case 'exists':
960
+ return contensisCoreApi.Op.exists(field, innerValue);
961
+
962
+ case 'freeText':
963
+ // TODO: Potentially needs further implementation of new options
964
+ return contensisCoreApi.Op[operator](field, innerValue, false, undefined);
965
+
966
+ default:
967
+ return contensisCoreApi.Op[operator](field, innerValue);
968
+ }
969
+ });
970
+ return (expressions === null || expressions === void 0 ? void 0 : expressions.length) > 1 ? [contensisCoreApi.Op.or(...expressions)] : expressions || [];
971
+ }
972
+
973
+ switch (operator) {
974
+ case 'between':
975
+ return between(field, value);
976
+
977
+ case 'distanceWithin':
978
+ return distanceWithin(field, value);
979
+
980
+ case 'freeText':
981
+ // TODO: Potentially needs further implementation of new options
982
+ return [contensisCoreApi.Op.freeText(field, value, false, undefined)];
983
+
984
+ default:
985
+ return [contensisCoreApi.Op[operator](field, value)];
986
+ }
987
+ };
988
+
989
+ const between = (field, value) => {
990
+ const handle = betweenValue => {
991
+ const valArr = betweenValue.split('--');
992
+
993
+ if (valArr.length > 1) {
994
+ const [minimum, maximum] = valArr;
995
+ return contensisCoreApi.Op.between(field, minimum, maximum);
996
+ } else {
997
+ // eslint-disable-next-line no-console
998
+ console.log(`[search] You have supplied only one value to a "between" operator which must have two values. Your supplied value "${valArr.length && valArr[0]}" has been discarded.`);
999
+ return false;
1000
+ }
1001
+ };
1002
+
1003
+ if (value.length === 0) return [];
1004
+ if (Array.isArray(value)) return [contensisCoreApi.Op.or(...value.map(handle).filter(bc => bc !== false))];
1005
+ const op = handle(value);
1006
+ return op ? [op] : [];
1007
+ };
1008
+
1009
+ const distanceWithin = (field, value) => {
1010
+ const handle = distanceValue => {
1011
+ const valArr = distanceValue.split(' ');
1012
+
1013
+ if (valArr.length > 1) {
1014
+ const [lat, lon] = valArr;
1015
+ return contensisCoreApi.Op.distanceWithin(field, Number(lat), Number(lon), (valArr === null || valArr === void 0 ? void 0 : valArr[2]) || '10mi');
1016
+ } else {
1017
+ // eslint-disable-next-line no-console
1018
+ console.log(`[search] You have supplied only one value to a "distanceWithin" operator which must be made up of "lat,lon,distance". Your supplied value "${valArr.length && valArr[0]}" has been discarded.`);
1019
+ return false;
1020
+ }
1021
+ };
1022
+
1023
+ if (value.length === 0) return [];
1024
+ if (Array.isArray(value)) return [contensisCoreApi.Op.or(...value.map(handle).filter(bc => bc !== false))];
1025
+ const op = handle(value);
1026
+ return op ? [op] : [];
1027
+ };
1028
+ /**
1029
+ * Accept HTTP style objects and map them to
1030
+ * their equivalent JS client "Op" expressions
1031
+ * @param {array} where the where array as you'd provide it to the HTTP API
1032
+ * @returns {array} array of constructed Delivery API Operators
1033
+ */
1034
+
1035
+
1036
+ const customWhereExpressions = where => {
1037
+ if (!where || !Array.isArray(where)) return []; // Map each clause inside the where array
1038
+
1039
+ return where.map(clause => {
1040
+ let expression; // Map through each property in the clause so we can
1041
+ // capture the values required and reconstruct them as
1042
+ // a Delivery API expression
1043
+
1044
+ let operator;
1045
+ Object.keys(clause).map((key, idx) => {
1046
+ // The clause may contain only one key
1047
+ if (idx === 0) operator = key;
1048
+ const field = clause.field;
1049
+ const value = clause[Object.keys(clause).find(k => !['field', 'weight'].includes(k)) || ''];
1050
+ const weight = clause.weight;
1051
+
1052
+ if (idx === 0) {
1053
+ if (operator === 'and' || operator === 'or') {
1054
+ // These are array expressions so we can call ourself recursively
1055
+ // to map these inner values to expressions
1056
+ const recurseExpr = customWhereExpressions(clause[operator]);
1057
+ expression = contensisCoreApi.Op[operator](...recurseExpr);
1058
+ }
1059
+
1060
+ if (['not'].includes(operator)) {
1061
+ // A 'not' expression is an object with only one inner field and inner operator
1062
+ Object.keys(value).map((notKey, notIdx) => {
1063
+ const innerOperator = notKey;
1064
+ const innerValue = value[notKey];
1065
+ const innerField = value.field; // Map the expression when we've looped and scoped to
1066
+ // the second property inside the clause
1067
+
1068
+ if (notIdx === 1) expression = contensisCoreApi.Op.not(makeJsExpression(innerOperator, innerField, innerValue));
1069
+ });
1070
+ }
1071
+ } // Map the expression when we've looped and scoped to
1072
+ // the second property inside the clause
1073
+
1074
+
1075
+ operator = Object.keys(clause).find(clauseKey => !['field', 'weight'].includes(clauseKey));
1076
+
1077
+ if (idx === 1) {
1078
+ expression = makeJsExpression(operator, field, value);
1079
+ if (typeof weight === 'number') expression = expression.weight(weight);
1080
+ }
1081
+ });
1082
+ return expression;
1083
+ });
1084
+ };
1085
+
1086
+ const makeJsExpression = (operator, field, value) => operator === 'freeText' || operator === 'contains' ? contensisCoreApi.Op[operator](field, value) : operator === 'in' ? contensisCoreApi.Op[operator](field, ...value) : operator === 'exists' ? contensisCoreApi.Op[operator](field, value) : operator === 'between' ? contensisCoreApi.Op[operator](field, value[0], value[1]) : operator === 'distanceWithin' ? contensisCoreApi.Op[operator](field, value === null || value === void 0 ? void 0 : value.lat, value === null || value === void 0 ? void 0 : value.lon, value === null || value === void 0 ? void 0 : value.distance) : contensisCoreApi.Op[operator](field, value);
1087
+
1088
+ const termExpressions = (searchTerm, weightedSearchFields) => {
1089
+ if (searchTerm && weightedSearchFields && weightedSearchFields.length > 0) {
1090
+ // Extract any phrases in quotes to array
1091
+ const quotedPhrases = extractQuotedPhrases(searchTerm); // Modify the search term to remove any quoted phrases to leave any remaining terms
1092
+
1093
+ let modifiedSearchTerm = searchTerm;
1094
+ quotedPhrases.forEach(qp => modifiedSearchTerm = modifiedSearchTerm.replace(qp, '').replace('""', '').trim()); // Push to the operators array to include in the query
1095
+
1096
+ const operators = []; // Helper functions to generate Op expressions
1097
+
1098
+ const containsOp = (f, term) => fieldExpression(f.fieldId, fixFreeTextForElastic(term), 'contains', f.weight);
1099
+
1100
+ const freeTextOp = (f, term) => fieldExpression(f.fieldId, fixFreeTextForElastic(term), 'freeText', f.weight); // For each weighted search field
1101
+
1102
+
1103
+ weightedSearchFields.forEach(wsf => {
1104
+ // Push to field operators
1105
+ const fieldOperators = []; // Add operator expressions for modified search term
1106
+
1107
+ if (modifiedSearchTerm) {
1108
+ if ([Fields.keywords, Fields.sys.filename, Fields.sys.uri].includes(wsf.fieldId)) {
1109
+ fieldOperators.push(...containsOp(wsf, modifiedSearchTerm));
1110
+ } else {
1111
+ if ([Fields.entryTitle].includes(wsf.fieldId)) {
1112
+ fieldOperators.push(contensisCoreApi.Op.or(...containsOp(wsf, modifiedSearchTerm), ...freeTextOp(wsf, modifiedSearchTerm)));
1113
+ } else {
1114
+ fieldOperators.push(...freeTextOp(wsf, modifiedSearchTerm));
1115
+ }
1116
+ }
1117
+ } // Add operator expressions for any quoted phrases
1118
+
1119
+
1120
+ quotedPhrases.forEach(qp => fieldOperators.push(...containsOp(wsf, qp))); // If we are using multiple operators for a field we will
1121
+ // wrap each field inside an And operator so we will match
1122
+ // all terms/phrases rather than any terms/phrases
1123
+
1124
+ if (fieldOperators.length > 1) {
1125
+ operators.push(contensisCoreApi.Op.and(...fieldOperators));
1126
+ } else {
1127
+ operators.push(...fieldOperators);
1128
+ }
1129
+ }); // Wrap operators in an Or operator
1130
+
1131
+ return [contensisCoreApi.Op.or().addRange(operators).add(contensisCoreApi.Op.freeText(Fields.searchContent, searchTerm))];
1132
+ } else if (searchTerm) {
1133
+ // Searching without weightedSearchFields defined will fall back
1134
+ // to a default set of search fields with arbritary weights set.
1135
+ return [contensisCoreApi.Op.or(contensisCoreApi.Op.equalTo(Fields.entryTitle, searchTerm).weight(10), contensisCoreApi.Op.freeText(Fields.entryTitle, searchTerm).weight(2), contensisCoreApi.Op.freeText(Fields.entryDescription, searchTerm).weight(2), contensisCoreApi.Op.contains(Fields.keywords, searchTerm).weight(2), contensisCoreApi.Op.contains(Fields.sys.uri, searchTerm).weight(2), contensisCoreApi.Op.contains(Fields.sys.allUris, searchTerm), contensisCoreApi.Op.freeText(Fields.searchContent, searchTerm))];
1136
+ } else {
1137
+ return [];
1138
+ }
1139
+ };
1140
+
1141
+ var expressions = /*#__PURE__*/Object.freeze({
1142
+ __proto__: null,
1143
+ fieldExpression: fieldExpression,
1144
+ contentTypeIdExpression: contentTypeIdExpression,
1145
+ filterExpressions: filterExpressions,
1146
+ dataFormatExpression: dataFormatExpression,
1147
+ featuredResultsExpression: featuredResultsExpression,
1148
+ languagesExpression: languagesExpression,
1149
+ includeInSearchExpressions: includeInSearchExpressions,
1150
+ defaultExpressions: defaultExpressions,
1151
+ includeIdsExpression: includeIdsExpression,
1152
+ excludeIdsExpression: excludeIdsExpression,
1153
+ orderByExpression: orderByExpression,
1154
+ customWhereExpressions: customWhereExpressions,
1155
+ termExpressions: termExpressions
1156
+ });
1157
+
1158
+ const filterQuery = (contentTypeIds, versionStatus, customWhere) => {
1159
+ const query = new contensisCoreApi.Query(...[...contentTypeIdExpression(contentTypeIds), ...defaultExpressions(versionStatus), ...customWhereExpressions(customWhere)]);
1160
+ query.orderBy = contensisCoreApi.OrderBy.asc(Fields.entryTitle);
1161
+ query.pageSize = 100;
1162
+ return query;
1163
+ };
1164
+ const searchQuery = ({
1165
+ assetTypes,
1166
+ contentTypeIds,
1167
+ customWhere,
1168
+ dynamicOrderBy,
1169
+ excludeIds,
1170
+ featuredResults,
1171
+ fields,
1172
+ filters,
1173
+ includeInSearchFields,
1174
+ languages,
1175
+ pageSize,
1176
+ pageIndex,
1177
+ orderBy,
1178
+ searchTerm,
1179
+ versionStatus,
1180
+ webpageTemplates,
1181
+ weightedSearchFields
1182
+ }, isFeatured = false) => {
1183
+ let expressions = [...termExpressions(searchTerm, weightedSearchFields), ...defaultExpressions(versionStatus), ...includeInSearchExpressions(webpageTemplates, includeInSearchFields), ...languagesExpression(languages), ...customWhereExpressions(customWhere), ...excludeIdsExpression(excludeIds)];
1184
+ if (isFeatured) expressions = [...expressions, ...featuredResultsExpression(featuredResults)];
1185
+ if (!isFeatured || featuredResults && !featuredResults.contentTypeId) expressions = [...expressions, ...filterExpressions(filters), ...contentTypeIdExpression(contentTypeIds, webpageTemplates, assetTypes)];
1186
+ const query = new contensisCoreApi.Query(...expressions);
1187
+ if (!searchTerm) query.orderBy = orderByExpression(orderBy);
1188
+ if (dynamicOrderBy && dynamicOrderBy.length) query.orderBy = orderByExpression(dynamicOrderBy);
1189
+
1190
+ if (fields && fields.length > 0 && !isFeatured) {
1191
+ query.fields = fields;
1192
+ }
1193
+
1194
+ query.pageIndex = isFeatured ? 0 : pageIndex;
1195
+ query.pageSize = isFeatured && typeof featuredResults.count === 'number' ? featuredResults.count : pageSize;
1196
+ return query;
1197
+ };
1198
+
1199
+ var queries = /*#__PURE__*/Object.freeze({
1200
+ __proto__: null,
1201
+ filterQuery: filterQuery,
1202
+ searchQuery: searchQuery
1203
+ });
1204
+
1205
+ const mapEntriesToSearchResults = ({
1206
+ mappers,
1207
+ mapper,
1208
+ context,
1209
+ facet
1210
+ }, items, state) => {
1211
+ const mapperFunc = mapper || mappers && mappers.results;
1212
+ return items && typeof mapperFunc === 'function' ? mapperFunc(items, facet, context, state) : [];
1213
+ };
1214
+
1215
+ const facetTemplate = {
1216
+ type: () => SET_SEARCH_ENTRIES,
1217
+ context: 'action.context',
1218
+ facet: 'action.facet',
1219
+ mappers: 'action.mappers',
1220
+ nextFacet: {
1221
+ entries: {
1222
+ isLoading: () => false,
1223
+ isError: () => false
1224
+ },
1225
+ featuredEntries: {
1226
+ isLoading: () => false,
1227
+ isError: () => false
1228
+ },
1229
+ featuredResults: ({
1230
+ action,
1231
+ featuredResult,
1232
+ state
1233
+ }) => mapEntriesToSearchResults(action, getItemsFromResult(featuredResult), state),
1234
+ queryDuration: 'result.duration',
1235
+ pagingInfo: {
1236
+ isLoading: () => false,
1237
+ pageCount: {
1238
+ $path: 'result.payload.pageCount',
1239
+ $default: 0
1240
+ },
1241
+ totalCount: {
1242
+ $path: 'result.payload.totalCount',
1243
+ $default: 0
1244
+ },
1245
+ pageSize: {
1246
+ $path: 'result.payload.pageSize',
1247
+ $default: 0
1248
+ },
1249
+ pageIndex: 'pageIndex',
1250
+ pagesLoaded: {
1251
+ $path: 'action.queryParams',
1252
+ $formatting: ({
1253
+ pageIndex,
1254
+ pagesLoaded
1255
+ }) => {
1256
+ const loaded = [...(pagesLoaded || [])];
1257
+
1258
+ if (isNaN(loaded.find(l => l === pageIndex))) {
1259
+ loaded.push(pageIndex);
1260
+ }
1261
+
1262
+ return loaded.sort((a, b) => a - b);
1263
+ }
1264
+ },
1265
+ prevPageIndex: 'action.queryParams.prevPageIndex'
1266
+ },
1267
+ preloaded: {
1268
+ $path: 'preload',
1269
+ $default: false
1270
+ },
1271
+ results: ({
1272
+ action,
1273
+ pageIndex,
1274
+ result,
1275
+ prevResults,
1276
+ state
1277
+ }) => {
1278
+ const {
1279
+ loadMorePaging,
1280
+ pagesLoaded,
1281
+ prevPageIndex
1282
+ } = action.queryParams;
1283
+ const results = mapEntriesToSearchResults(action, getItemsFromResult(result), state);
1284
+ if (!loadMorePaging) return results; // add a _pageIndex property to the returned results to help us later
1285
+
1286
+ const nextResults = results.map((r, idx) => ({
1287
+ _pageIndex: pageIndex,
1288
+ _pagePosition: idx,
1289
+ ...r
1290
+ }));
1291
+ const loadedPages = pagesLoaded || []; // if pageIndex is found in loadedPages, we have already loaded this page
1292
+
1293
+ if (!isNaN(loadedPages.find(l => l === pageIndex))) return prevResults; // Determine where we put the results depending on if we
1294
+ // are paging forwards, backwards, or doing a new search
1295
+
1296
+ const firstResultSet = pageIndex > prevPageIndex ? prevResults || [] : nextResults;
1297
+ const secondResultSet = pageIndex > prevPageIndex ? nextResults : prevResults || [];
1298
+ const onlyResultSet = loadedPages.length === 0 ? nextResults : false;
1299
+ return onlyResultSet || [...firstResultSet, ...secondResultSet];
1300
+ }
1301
+ },
1302
+ preload: 'action.preload',
1303
+ ogState: 'action.ogState',
1304
+ debug: 'action.debug'
1305
+ };
1306
+ const filterTemplate = {
1307
+ type: ({
1308
+ type
1309
+ }) => type || LOAD_FILTERS_COMPLETE,
1310
+ context: 'context',
1311
+ facetKey: 'facetKey',
1312
+ filterKey: 'filterKey',
1313
+ nextFilter: {
1314
+ isLoading: () => false,
1315
+ isError: ({
1316
+ type
1317
+ }) => type === LOAD_FILTERS_ERROR,
1318
+ items: ({
1319
+ payload,
1320
+ selectedKeys,
1321
+ mapper
1322
+ }) => {
1323
+ if (payload && (payload.items || payload.children)) {
1324
+ const items = (payload.items || payload.children).map(item => {
1325
+ var _item$sys;
1326
+
1327
+ item.isSelected = selectedKeys === null || selectedKeys === void 0 ? void 0 : selectedKeys.includes((item === null || item === void 0 ? void 0 : (_item$sys = item.sys) === null || _item$sys === void 0 ? void 0 : _item$sys.id) || item.key);
1328
+ return item;
1329
+ });
1330
+ return mapper(items);
1331
+ }
1332
+
1333
+ return [];
1334
+ }
1335
+ },
1336
+ error: {
1337
+ $path: 'error',
1338
+ $disable: e => !e
1339
+ }
1340
+ };
1341
+
1342
+ const filterExpressionMapper = {
1343
+ // Expression type: so we can identify how to build the query
1344
+ expressionType: ({
1345
+ contentTypeId
1346
+ }) => contentTypeId ? FilterExpressionTypes.contentType : FilterExpressionTypes.field,
1347
+ // Key: so we can target the query to a specific field
1348
+ key: 'fieldId',
1349
+ // Value: so we can filter a specific field by an array of values
1350
+ // e.g. taxonomy key or contentTypeId array
1351
+ values: 'selectedValues',
1352
+ fieldOperator: 'fieldOperator',
1353
+ logicOperator: 'logicOperator'
1354
+ };
1355
+
1356
+ const mapFilterToFilterExpression = filter => mapJson__default["default"](filter, filterExpressionMapper);
1357
+
1358
+ const mapFiltersToFilterExpression = (filters, selectedFilters) => {
1359
+ if (!selectedFilters || Object.keys(selectedFilters).length === 0) return [];
1360
+ const filterExpressions = []; // Iterate through the keys in selectedFilters and locate
1361
+ // the items that are selected and queryable
1362
+
1363
+ Object.entries(selectedFilters).map(([fkey, selectedValues]) => {
1364
+ const filter = filters[fkey];
1365
+
1366
+ if (selectedValues && filter) {
1367
+ // Where we have a value for a selectedFilter
1368
+ // and a filter is found for the current key
1369
+ // map the filter to a filterExpression object
1370
+ const expr = mapFilterToFilterExpression({ ...filter,
1371
+ selectedValues
1372
+ });
1373
+ filterExpressions.push(expr);
1374
+ }
1375
+ });
1376
+ return filterExpressions;
1377
+ };
1378
+
1379
+ const queryParamsTemplate = {
1380
+ assetTypes: root => getQueryParameter(root, 'assetTypes', []),
1381
+ contentTypeIds: root => getQueryParameter(root, 'contentTypeIds', []),
1382
+ customWhere: root => getQueryParameter(root, 'customWhere', []),
1383
+ dynamicOrderBy: root => getQueryParameter(root, 'dynamicOrderBy', []),
1384
+ env: ({
1385
+ state,
1386
+ facet,
1387
+ context
1388
+ }) => getCustomEnv(state, facet, context),
1389
+ excludeIds: ({
1390
+ action: {
1391
+ excludeIds
1392
+ }
1393
+ }) => {
1394
+ // Exclude current route entry id from minilist searches or any supplied ids
1395
+ if (excludeIds) return Array.isArray(excludeIds) ? excludeIds : excludeIds.split(',').map(id => id.trim());
1396
+ return null;
1397
+ },
1398
+ featuredResults: root => getQueryParameter(root, 'featuredResults', null),
1399
+ fields: root => getQueryParameter(root, 'fields', []),
1400
+ filters: ({
1401
+ state,
1402
+ facet,
1403
+ context
1404
+ }) => {
1405
+ const stateFilters = getFilters(state, facet, context, 'js');
1406
+ const selectedFilters = getSelectedFilters(state, facet, context, 'js'); // Use another mapping function to map the filter parameters for the query
1407
+
1408
+ const filterParams = mapFiltersToFilterExpression(stateFilters, selectedFilters);
1409
+ return filterParams;
1410
+ },
1411
+ includeInSearchFields: root => getQueryParameter(root, 'includeInSearch', []),
1412
+ internalPageIndex: ({
1413
+ action,
1414
+ state
1415
+ }) => getPageIndex(state, '', action.context),
1416
+ internalPaging: root => getQueryParameter(root, 'internalPaging', false),
1417
+ languages: ({
1418
+ action
1419
+ }) => action.defaultLang ? [action.defaultLang] : [],
1420
+ linkDepth: root => getQueryParameter(root, 'linkDepth', 0),
1421
+ loadMorePaging: root => getQueryParameter(root, 'loadMorePaging', false),
1422
+ orderBy: root => getQueryParameter(root, 'orderBy', []),
1423
+ pageIndex: root => {
1424
+ const {
1425
+ action,
1426
+ state
1427
+ } = root;
1428
+ if (getQueryParameter(root, 'internalPaging', false)) return 0;
1429
+ if (action.type === UPDATE_PAGE_INDEX) return action.params.pageIndex;
1430
+ return !action.preload ? getPageIndex(state, action.facet, action.context) : 0;
1431
+ },
1432
+ pageSize: root => getQueryParameter(root, 'pageSize'),
1433
+ pagesLoaded: ({
1434
+ state,
1435
+ facet,
1436
+ context
1437
+ }) => getPagesLoaded(state, facet, context),
1438
+ prevPageIndex: ({
1439
+ state,
1440
+ facet,
1441
+ context
1442
+ }) => getPrevPageIndex(state, facet, context),
1443
+ projectId: ({
1444
+ state,
1445
+ facet,
1446
+ context
1447
+ }) => {
1448
+ var _getFacet;
1449
+
1450
+ return ((_getFacet = getFacet(state, facet, context)) === null || _getFacet === void 0 ? void 0 : _getFacet.projectId) || selectCurrentProject(state);
1451
+ },
1452
+ searchTerm: root => root.context !== exports.Context.minilist || getQueryParameter(root, 'useSearchTerm', false) ? getSearchTerm(root.state) : '',
1453
+ selectedFilters: ({
1454
+ state,
1455
+ facet,
1456
+ context
1457
+ }) => Object.fromEntries(Object.entries(getSelectedFilters(state, facet, context, 'js')).map(([key, f]) => [key, f === null || f === void 0 ? void 0 : f.join(',')])),
1458
+ versionStatus: ({
1459
+ state
1460
+ }) => selectVersionStatus(state),
1461
+ weightedSearchFields: root => {
1462
+ const wsf = getQueryParameter(root, 'weightedSearchFields', []);
1463
+ const deduped = wsf.filter((v, i, a) => a.findIndex(t => t.fieldId === v.fieldId) === i);
1464
+ return deduped; // return wsf;
1465
+ },
1466
+ webpageTemplates: root => getQueryParameter(root, 'webpageTemplates', [])
1467
+ };
1468
+
1469
+ const mapStateToQueryParams = sourceJson => mapJson__default["default"](sourceJson, queryParamsTemplate);
1470
+
1471
+ /**
1472
+ * 1, Generates all the parameters required to run the search query.
1473
+ * 2, Tells us if we should run the search.
1474
+ * @param {object} action
1475
+ * @param {AppState} state
1476
+ * @returns [queryParams, runSearch]
1477
+ */
1478
+ const generateQueryParams = (action, state) => {
1479
+ const {
1480
+ context,
1481
+ facet
1482
+ } = action; // Map parameters using state and some additional
1483
+ // inputs from the action
1484
+
1485
+ const queryParams = mapStateToQueryParams({
1486
+ context,
1487
+ facet,
1488
+ action,
1489
+ state
1490
+ });
1491
+ return [queryParams, runSearch(action, state, queryParams)];
1492
+ };
1493
+ /**
1494
+ * Checks if we have already loaded everything we're asking for and tells us to run the search or not
1495
+ * @param action
1496
+ * @param state
1497
+ */
1498
+
1499
+ const runSearch = (action, state, queryParams) => {
1500
+ const {
1501
+ context,
1502
+ defaultLang,
1503
+ facet,
1504
+ ogState = state,
1505
+ preload,
1506
+ ssr
1507
+ } = action;
1508
+ let willRun = false;
1509
+ const facetIsLoaded = defaultLang ? false : getIsLoaded(state, context, facet);
1510
+ const stateParams = { ...getQueryParams(ogState, facet, context)
1511
+ };
1512
+ stateParams.pageIndex = getPageIndex(ogState, facet, context);
1513
+ stateParams.searchTerm = getSearchTerm(ogState);
1514
+
1515
+ if (context === exports.Context.facets && ssr || // context === Context.minilist ||
1516
+ preload || !facetIsLoaded || filterParamsChanged(action) || defaultLang) {
1517
+ willRun = true;
1518
+ } else {
1519
+ // Don't execute the search if the inbound query params
1520
+ // are the same as what we already have in state
1521
+ Object.entries(stateParams).forEach(([param, value]) => {
1522
+ const queryParam = queryParams[param];
1523
+
1524
+ if (JSON.stringify(value) !== JSON.stringify(queryParam)) {
1525
+ willRun = true;
1526
+ }
1527
+ });
1528
+ }
1529
+
1530
+ const internalPaging = getIsInternalPaging(ogState, facet, context);
1531
+
1532
+ if (internalPaging && facetIsLoaded) {
1533
+ willRun = false;
1534
+ }
1535
+
1536
+ return willRun;
1537
+ };
1538
+ /**
1539
+ * This will tell us if filter parameters have been
1540
+ * changed by some external event such as a route change
1541
+ * @param action
1542
+ * @returns true or false
1543
+ */
1544
+
1545
+ const filterParamsChanged = (action, state) => {
1546
+ const {
1547
+ context,
1548
+ facet,
1549
+ params,
1550
+ ogState = state
1551
+ } = action;
1552
+ const selectedFilters = getSelectedFilters(ogState, facet, context, 'js');
1553
+ const paramsChanged = Object.entries(selectedFilters).map(([filterKey, selectedValues]) => {
1554
+ const inboundValues = params && params[filterKey] && params[filterKey].split(',') || [];
1555
+ if (!areArraysEqualSets(selectedValues, inboundValues)) return true;
1556
+ });
1557
+ return paramsChanged.filter(f => f === true).length > 0;
1558
+ };
1559
+ /* eslint-disable no-console */
1560
+
1561
+ const debugExecuteSearch = (action, state) => {
1562
+ const [queryParams, runSearch] = generateQueryParams(action, state);
1563
+ console.log('runSearch', runSearch, 'action', action, 'filterParamsChanged', filterParamsChanged(action, state), 'getIsLoaded(state, context, facet)', getIsLoaded(state, action.context, action.facet));
1564
+ const stateParams = { ...getQueryParams(action.ogState || state, action.facet, action.context),
1565
+ pageIndex: getPageIndex(action.ogState || state, action.facet, action.context),
1566
+ searchTerm: getSearchTerm(action.ogState || state)
1567
+ };
1568
+ console.log(stateParams, queryParams);
1569
+ console.log('getSelectedFilters', getSelectedFilters(action.ogState || state, action.facet, action.context, 'js'), 'params', action.params);
1570
+ };
1571
+ const scrollTop = scrollYPos => {
1572
+ if (typeof window !== 'undefined') window.scrollTo(0, scrollYPos);
1573
+ };
1574
+
1575
+ // Base mapping, fields that are the same across all mappings
1576
+ // to save repeating these elements in every mapper, spread this
1577
+ // into your discrete mappings
1578
+
1579
+ const base = {
1580
+ contentTypeId: Fields.sys.contentTypeId,
1581
+ title: 'entryTitle',
1582
+ key: 'sys.id',
1583
+ path: 'sys.slug',
1584
+ isSelected: 'isSelected'
1585
+ };
1586
+
1587
+ const mapEntriesToFilterItems = entries => {
1588
+ if (!entries) return [];
1589
+ return entries.map(entry => {
1590
+ const template = base;
1591
+
1592
+ if (template) {
1593
+ return mapJson__default["default"](entry, template);
1594
+ }
1595
+
1596
+ return entry;
1597
+ });
1598
+ };
1599
+
1600
+ const mapQueryParamsToCustomApi = queryParams => {
1601
+ const customApiMapping = {
1602
+ fields: ({
1603
+ fields
1604
+ }) => JSON.stringify(fields),
1605
+ orderBy: 'orderBy',
1606
+ linkDepth: 'linkDepth',
1607
+ pageSize: 'pageSize',
1608
+ pageIndex: 'pageIndex',
1609
+ term: {
1610
+ $path: 'searchTerm',
1611
+ $disable: t => !t
1612
+ },
1613
+ versionStatus: 'versionStatus'
1614
+ };
1615
+ Object.keys(queryParams.selectedFilters).forEach(k => {
1616
+ customApiMapping[k] = {
1617
+ $path: `selectedFilters.${k}`,
1618
+ $disable: f => !f
1619
+ };
1620
+ });
1621
+ return mapJson__default["default"](queryParams, customApiMapping);
1622
+ };
1623
+
1624
+ const searchSagas = [effects.takeEvery(CLEAR_FILTERS, clearFilters), effects.takeEvery(DO_SEARCH, doSearch), effects.takeEvery(SET_ROUTE_FILTERS, loadFilters), effects.takeEvery(SET_SEARCH_ENTRIES, preloadOtherFacets), effects.takeEvery(UPDATE_CURRENT_FACET, updateCurrentFacet), effects.takeEvery(UPDATE_CURRENT_TAB, updateCurrentTab), effects.takeEvery(UPDATE_PAGE_INDEX, updatePageIndex), effects.takeEvery(UPDATE_SEARCH_TERM, updateSearchTerm), effects.takeEvery(UPDATE_SORT_ORDER, updateSortOrder), effects.takeEvery(UPDATE_SELECTED_FILTERS, applySearchFilter)];
1625
+
1626
+ const toJS = obj => obj && 'toJS' in obj && typeof obj.toJS === 'function' ? obj.toJS() : obj;
1627
+
1628
+ function* setRouteFilters(action) {
1629
+ const {
1630
+ mappers,
1631
+ params,
1632
+ listingType,
1633
+ defaultLang,
1634
+ debug
1635
+ } = action;
1636
+ const context = listingType ? exports.Context.listings : exports.Context.facets;
1637
+ const state = toJS(yield effects.select());
1638
+ const ssr = getIsSsr(state); // Get current facet from params or state
1639
+
1640
+ let currentFacet = params && params.facet || listingType; // Pick the default facet from initialState
1641
+
1642
+ if (!currentFacet) {
1643
+ var _Object$keys;
1644
+
1645
+ const tabs = getSearchTabs(state, 'js');
1646
+ currentFacet = (tabs === null || tabs === void 0 ? void 0 : tabs[0].defaultFacet) || ((_Object$keys = Object.keys(getFacets(state, 'js'))) === null || _Object$keys === void 0 ? void 0 : _Object$keys[0]) || '';
1647
+ }
1648
+
1649
+ const nextAction = {
1650
+ type: SET_ROUTE_FILTERS,
1651
+ context,
1652
+ facet: currentFacet,
1653
+ mappers,
1654
+ params,
1655
+ defaultLang,
1656
+ ssr,
1657
+ debug
1658
+ };
1659
+ yield effects.put(nextAction); // keep track of this state ref for comparing changes to params later
1660
+
1661
+ const ogState = {
1662
+ search: state.search
1663
+ }; // Using call instead of triggering from the put
1664
+ // to allow this exported saga to continue during SSR
1665
+
1666
+ yield effects.call(ensureSearch, { ...nextAction,
1667
+ ogState
1668
+ });
1669
+ }
1670
+ function* doSearch(action) {
1671
+ var _action$params;
1672
+
1673
+ const state = toJS(yield effects.select());
1674
+
1675
+ if (action.config) {
1676
+ // If the action contains a config object, we can add this to the
1677
+ // state at runtime
1678
+ yield effects.put({ ...action,
1679
+ type: APPLY_CONFIG
1680
+ });
1681
+ }
1682
+
1683
+ const nextAction = { ...action,
1684
+ type: SET_SEARCH_FILTERS,
1685
+ ssr: getIsSsr(state),
1686
+ facet: action.facet || ((_action$params = action.params) === null || _action$params === void 0 ? void 0 : _action$params.facet)
1687
+ };
1688
+
1689
+ if (nextAction.facet && (action.config || Object.keys(getFacet(state, nextAction.facet, action.context, 'js')).length > 0)) {
1690
+ yield effects.put(nextAction); // keep track of this state ref for comparing changes to params later
1691
+
1692
+ const ogState = {
1693
+ search: state.search
1694
+ };
1695
+ yield effects.call(ensureSearch, { ...nextAction,
1696
+ ogState
1697
+ });
1698
+ }
1699
+ }
1700
+
1701
+ function* loadFilters(action) {
1702
+ const {
1703
+ facet: facetKey,
1704
+ context,
1705
+ mappers = {}
1706
+ } = action;
1707
+ const filtersToLoad = yield effects.select(getFiltersToLoad, facetKey, context, 'js');
1708
+
1709
+ if (filtersToLoad.length > 0) {
1710
+ yield effects.put({
1711
+ type: LOAD_FILTERS,
1712
+ filtersToLoad,
1713
+ facetKey,
1714
+ context
1715
+ });
1716
+ const selectedKeys = yield effects.select(getSelectedFilters, facetKey, context, 'js');
1717
+ const facet = yield effects.select(getFacet, facetKey, context, 'js');
1718
+ const filters = facet.filters || {};
1719
+ const projectId = facet.projectId;
1720
+ const filtersToLoadSagas = filters && filtersToLoad.map((filterKey = '') => {
1721
+ return effects.call(loadFilter, {
1722
+ facetKey,
1723
+ filterKey,
1724
+ filter: filters[filterKey],
1725
+ projectId,
1726
+ selectedKeys: selectedKeys[filterKey],
1727
+ context,
1728
+ mapper: 'filterItems' in mappers && mappers.filterItems || mapEntriesToFilterItems
1729
+ });
1730
+ });
1731
+ if (filtersToLoadSagas) yield effects.all(filtersToLoadSagas);
1732
+ }
1733
+ }
1734
+
1735
+ function* loadFilter(action) {
1736
+ const {
1737
+ facetKey,
1738
+ filterKey,
1739
+ filter,
1740
+ projectId,
1741
+ selectedKeys,
1742
+ context,
1743
+ mapper
1744
+ } = action;
1745
+ const {
1746
+ contentTypeId,
1747
+ customWhere,
1748
+ path
1749
+ } = filter;
1750
+ const createStateFrom = {
1751
+ type: LOAD_FILTERS_COMPLETE,
1752
+ context,
1753
+ error: undefined,
1754
+ facetKey,
1755
+ filterKey,
1756
+ payload: {},
1757
+ selectedKeys,
1758
+ mapper
1759
+ };
1760
+
1761
+ try {
1762
+ if (contentTypeId) {
1763
+ const versionStatus = yield effects.select(selectVersionStatus);
1764
+ const query = filterQuery(Array.isArray(contentTypeId) ? contentTypeId : [contentTypeId], versionStatus, customWhere);
1765
+ const payload = yield cachedSearch.search(query, 0, projectId);
1766
+ if (!payload) throw new Error('No payload returned by search');
1767
+ if (payload.type === 'error') throw payload;
1768
+ createStateFrom.payload = payload;
1769
+ }
1770
+
1771
+ if (path) {
1772
+ const payload = yield cachedSearch.getTaxonomyNodeByPath(path, projectId);
1773
+ if (!payload) throw new Error(`No payload returned for taxonomy path: '${path}'`);
1774
+ if (payload.type === 'error') throw payload;
1775
+ createStateFrom.payload = payload;
1776
+ }
1777
+ } catch (error) {
1778
+ createStateFrom.type = LOAD_FILTERS_ERROR;
1779
+ createStateFrom.error = error;
1780
+ }
1781
+
1782
+ const nextAction = mapJson__default["default"](createStateFrom, filterTemplate);
1783
+ yield effects.put(nextAction);
1784
+ }
1785
+
1786
+ function* ensureSearch(action) {
1787
+ const {
1788
+ context,
1789
+ facet,
1790
+ debug
1791
+ } = action;
1792
+
1793
+ try {
1794
+ const state = yield effects.select();
1795
+ const nextAction = { ...action,
1796
+ ogState: action.ogState || {
1797
+ search: state.search
1798
+ }
1799
+ };
1800
+ const [queryParams, runSearch] = generateQueryParams(nextAction, state);
1801
+ if (debug && (debug === true || debug.executeSearch)) debugExecuteSearch(nextAction, state);
1802
+
1803
+ if (runSearch) {
1804
+ yield effects.put({
1805
+ type: EXECUTE_SEARCH,
1806
+ facet,
1807
+ context
1808
+ });
1809
+ yield effects.call(executeSearch, { ...nextAction,
1810
+ context,
1811
+ facet,
1812
+ queryParams,
1813
+ debug
1814
+ });
1815
+ }
1816
+ } catch (error) {
1817
+ // eslint-disable-next-line import/namespace
1818
+ log__namespace.error(...['Error running search saga:', error, error.stack]);
1819
+ }
1820
+ }
1821
+
1822
+ function* executeSearch(action) {
1823
+ const {
1824
+ context,
1825
+ facet,
1826
+ queryParams,
1827
+ mappers
1828
+ } = action;
1829
+
1830
+ try {
1831
+ const state = yield effects.select();
1832
+ let result = {};
1833
+ let featuredResult;
1834
+ let featuredQuery;
1835
+ const customApi = getCustomApi(state, facet, context, 'js');
1836
+
1837
+ if (customApi) {
1838
+ const apiParams = typeof mappers === 'object' && typeof mappers.customApi === 'function' && mappers.customApi(queryParams) || mapQueryParamsToCustomApi(queryParams);
1839
+ result.payload = yield callCustomApi(customApi, apiParams);
1840
+ result.duration = 1;
1841
+ } else {
1842
+ if (queryParams.featuredResults) {
1843
+ featuredQuery = searchQuery(queryParams, true);
1844
+ featuredResult = yield timedSearch(featuredQuery, queryParams.linkDepth, queryParams.projectId, queryParams.env); // eslint-disable-next-line require-atomic-updates
1845
+
1846
+ queryParams.excludeIds = getItemsFromResult(featuredResult).map(fi => {
1847
+ var _fi$sys;
1848
+
1849
+ return fi === null || fi === void 0 ? void 0 : (_fi$sys = fi.sys) === null || _fi$sys === void 0 ? void 0 : _fi$sys.id;
1850
+ }).filter(fi => typeof fi === 'string');
1851
+ }
1852
+
1853
+ const query = searchQuery(queryParams);
1854
+ result = yield timedSearch(query, queryParams.linkDepth, queryParams.projectId, queryParams.env);
1855
+ }
1856
+
1857
+ const createStateFrom = {
1858
+ action,
1859
+ featuredResult,
1860
+ pageIndex: queryParams.internalPaging && queryParams.internalPageIndex || queryParams.pageIndex,
1861
+ prevResults: getResults(state, facet, action.context, 'js'),
1862
+ result,
1863
+ state
1864
+ };
1865
+ const nextAction = mapJson__default["default"](createStateFrom, facetTemplate);
1866
+ yield effects.put(nextAction);
1867
+ } catch (error) {
1868
+ // eslint-disable-next-line import/namespace
1869
+ log__namespace.error(...['Error running search saga:', error, error.stack]);
1870
+ }
1871
+ }
1872
+
1873
+ function* preloadOtherFacets(action) {
1874
+ const {
1875
+ preload,
1876
+ context,
1877
+ facet,
1878
+ debug
1879
+ } = action;
1880
+ const state = yield effects.select();
1881
+ const currentFacet = getCurrentFacet(state);
1882
+
1883
+ if (!preload && facet === currentFacet && context !== exports.Context.listings) {
1884
+ const allFacets = getFacets(state, 'js');
1885
+ const otherFacets = Object.keys(allFacets).filter(f => f !== currentFacet);
1886
+ yield effects.all(otherFacets.map((preloadFacet = '') => {
1887
+ const preloadAction = { ...action,
1888
+ facet: preloadFacet,
1889
+ preload: true
1890
+ };
1891
+ const [queryParams, runSearch] = generateQueryParams(preloadAction, state);
1892
+ if (debug && (debug === true || debug.preloadOtherFacets)) debugExecuteSearch(preloadAction, state);
1893
+ return runSearch && effects.call(executeSearch, { ...action,
1894
+ type: EXECUTE_SEARCH_PRELOAD,
1895
+ preload: true,
1896
+ facet: preloadFacet,
1897
+ queryParams
1898
+ });
1899
+ }));
1900
+ }
1901
+ }
1902
+
1903
+ function* updateCurrentTab(action) {
1904
+ const {
1905
+ id,
1906
+ mappers
1907
+ } = action;
1908
+ const state = yield effects.select();
1909
+ const facets = getFacets(state, 'js');
1910
+ const tabs = getSearchTabs(state, 'js');
1911
+ let nextFacet = tabs === null || tabs === void 0 ? void 0 : tabs[id].currentFacet;
1912
+
1913
+ if (!nextFacet) {
1914
+ Object.entries(facets).map(([facetName, facet]) => {
1915
+ if (facet.tabId === id && (tabs === null || tabs === void 0 ? void 0 : tabs[id].defaultFacet) === facetName) nextFacet = facetName;
1916
+ });
1917
+ } // If the next Tab does not have a defaultFacet,
1918
+ // take the first facet for that tab
1919
+
1920
+
1921
+ if (!nextFacet) nextFacet = Object.entries(facets).filter(([, f]) => f.tabId === id)[0][0];
1922
+ yield effects.put(withMappers(updateCurrentFacet$1(nextFacet), mappers));
1923
+ }
1924
+
1925
+ function* clearFilters(action) {
1926
+ const {
1927
+ mappers
1928
+ } = action;
1929
+ const uri = yield buildUri({}, mappers);
1930
+ yield effects.put(navigate(uri));
1931
+ }
1932
+
1933
+ function* updateCurrentFacet(action) {
1934
+ const {
1935
+ facet,
1936
+ mappers
1937
+ } = action;
1938
+ const pageIndex = yield effects.select(getPageIndex, facet);
1939
+ const uri = yield buildUri({
1940
+ facet,
1941
+ pageIndex
1942
+ }, mappers);
1943
+ yield effects.put(navigate(uri));
1944
+ }
1945
+
1946
+ function* updateSearchTerm(action) {
1947
+ const {
1948
+ term,
1949
+ mappers
1950
+ } = action;
1951
+ const uri = yield buildUri({
1952
+ term
1953
+ }, mappers);
1954
+ yield effects.put(navigate(uri));
1955
+ }
1956
+
1957
+ function* updateSortOrder(action) {
1958
+ const {
1959
+ orderBy,
1960
+ facet,
1961
+ mappers
1962
+ } = action;
1963
+ const uri = yield buildUri({
1964
+ orderBy,
1965
+ facet
1966
+ }, mappers);
1967
+ yield effects.put(navigate(uri));
1968
+ }
1969
+
1970
+ function* updatePageIndex(action) {
1971
+ const {
1972
+ pageIndex,
1973
+ mappers,
1974
+ scrollYPos
1975
+ } = action;
1976
+ const uri = yield buildUri({
1977
+ pageIndex
1978
+ }, mappers);
1979
+ yield effects.put(navigate(uri));
1980
+ if (typeof scrollYPos !== 'undefined') scrollTop(scrollYPos);
1981
+ }
1982
+
1983
+ function* applySearchFilter(action) {
1984
+ const {
1985
+ mappers,
1986
+ scrollYPos
1987
+ } = action;
1988
+ const uri = yield buildUri({}, mappers);
1989
+ yield effects.put(navigate(uri));
1990
+ if (typeof scrollYPos !== 'undefined') scrollTop(scrollYPos);
1991
+ }
1992
+
1993
+ function* buildUri({
1994
+ facet,
1995
+ orderBy,
1996
+ pageIndex = 0,
1997
+ term
1998
+ }, mappers) {
1999
+ const state = yield effects.select();
2000
+ const mapUri = (mappers === null || mappers === void 0 ? void 0 : mappers.navigate) || mapStateToSearchUri;
2001
+ const uri = mapUri({
2002
+ state,
2003
+ facet,
2004
+ orderBy,
2005
+ pageIndex,
2006
+ term
2007
+ }); // return uri;
2008
+
2009
+ return `${uri.path}${uri.search && `?${uri.search}` || ''}${uri.hash && `#${uri.hash}` || ''}`;
2010
+ }
2011
+
2012
+ function* triggerMinilistSsr(options) {
2013
+ yield effects.call(doSearch, {
2014
+ type: DO_SEARCH,
2015
+ ...options
2016
+ });
2017
+ }
2018
+ function* triggerListingSsr(options) {
2019
+ yield effects.call(setRouteFilters, options);
2020
+ }
2021
+ function* triggerSearchSsr(options) {
2022
+ yield effects.call(setRouteFilters, options);
2023
+ }
2024
+
2025
+ exports.APPLY_CONFIG = APPLY_CONFIG;
2026
+ exports.CLEAR_FILTERS = CLEAR_FILTERS;
2027
+ exports.EXECUTE_SEARCH = EXECUTE_SEARCH;
2028
+ exports.EXECUTE_SEARCH_ERROR = EXECUTE_SEARCH_ERROR;
2029
+ exports.LOAD_FILTERS = LOAD_FILTERS;
2030
+ exports.LOAD_FILTERS_COMPLETE = LOAD_FILTERS_COMPLETE;
2031
+ exports.LOAD_FILTERS_ERROR = LOAD_FILTERS_ERROR;
2032
+ exports.SET_ROUTE_FILTERS = SET_ROUTE_FILTERS;
2033
+ exports.SET_SEARCH_ENTRIES = SET_SEARCH_ENTRIES;
2034
+ exports.SET_SEARCH_FILTERS = SET_SEARCH_FILTERS;
2035
+ exports.UPDATE_PAGE_INDEX = UPDATE_PAGE_INDEX;
2036
+ exports.UPDATE_SEARCH_TERM = UPDATE_SEARCH_TERM;
2037
+ exports.UPDATE_SELECTED_FILTERS = UPDATE_SELECTED_FILTERS;
2038
+ exports.UPDATE_SORT_ORDER = UPDATE_SORT_ORDER;
2039
+ exports.actions = actions;
2040
+ exports.clearFilters = clearFilters$1;
2041
+ exports.contentTypeIdExpression = contentTypeIdExpression;
2042
+ exports.customWhereExpressions = customWhereExpressions;
2043
+ exports.defaultExpressions = defaultExpressions;
2044
+ exports.doSearch = doSearch;
2045
+ exports.expressions = expressions;
2046
+ exports.filterExpressions = filterExpressions;
2047
+ exports.getCurrentFacet = getCurrentFacet;
2048
+ exports.getCurrentTab = getCurrentTab;
2049
+ exports.getFacet = getFacet;
2050
+ exports.getFacetTitles = getFacetTitles;
2051
+ exports.getFacetsTotalCount = getFacetsTotalCount;
2052
+ exports.getFeaturedResults = getFeaturedResults;
2053
+ exports.getFilters = getFilters;
2054
+ exports.getIsLoading = getIsLoading;
2055
+ exports.getPageIndex = getPageIndex;
2056
+ exports.getPageIsLoading = getPageIsLoading;
2057
+ exports.getPaging = getPaging;
2058
+ exports.getQueryParameter = getQueryParameter;
2059
+ exports.getRenderableFilters = getRenderableFilters;
2060
+ exports.getResults = getResults;
2061
+ exports.getSearchTerm = getSearchTerm;
2062
+ exports.getSearchTotalCount = getSearchTotalCount;
2063
+ exports.getSelectedFilters = getSelectedFilters;
2064
+ exports.getTabFacets = getTabFacets;
2065
+ exports.getTabsAndFacets = getTabsAndFacets;
2066
+ exports.getTotalCount = getTotalCount;
2067
+ exports.mapStateToSearchUri = mapStateToSearchUri;
2068
+ exports.orderByExpression = orderByExpression;
2069
+ exports.queries = queries;
2070
+ exports.routeParams = routeParams;
2071
+ exports.searchSagas = searchSagas;
2072
+ exports.selectFacets = selectFacets;
2073
+ exports.selectListing = selectListing;
2074
+ exports.selectors = selectors;
2075
+ exports.setRouteFilters = setRouteFilters;
2076
+ exports.termExpressions = termExpressions;
2077
+ exports.toArray = toArray;
2078
+ exports.triggerListingSsr = triggerListingSsr;
2079
+ exports.triggerMinilistSsr = triggerMinilistSsr;
2080
+ exports.triggerSearch = triggerSearch;
2081
+ exports.triggerSearchSsr = triggerSearchSsr;
2082
+ exports.types = types;
2083
+ exports.updateCurrentFacet = updateCurrentFacet$1;
2084
+ exports.updateCurrentTab = updateCurrentTab$1;
2085
+ exports.updatePageIndex = updatePageIndex$1;
2086
+ exports.updateSearchTerm = updateSearchTerm$1;
2087
+ exports.updateSelectedFilters = updateSelectedFilters;
2088
+ exports.updateSortOrder = updateSortOrder$1;
2089
+ exports.withMappers = withMappers;
2090
+ //# sourceMappingURL=sagas-594b5ecd.js.map