react-instantsearch-core 7.30.0 → 7.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- /*! React InstantSearch Core 7.30.0 | © Algolia, Inc. and contributors; MIT License | https://github.com/algolia/instantsearch */
1
+ /*! React InstantSearch Core 7.32.0 | © Algolia, Inc. and contributors; MIT License | https://github.com/algolia/instantsearch */
2
2
  (function (global, factory) {
3
3
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
4
4
  typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
@@ -24,7 +24,7 @@
24
24
 
25
25
  var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
26
26
 
27
- var version$2 = '7.30.0';
27
+ var version$2 = '7.32.0';
28
28
 
29
29
  function _define_property(obj, key, value) {
30
30
  if (key in obj) {
@@ -1507,6 +1507,12 @@
1507
1507
  * This doesn't contain any beta/hidden features.
1508
1508
  * @private
1509
1509
  */ SearchParameters.PARAMETERS = Object.keys(new SearchParameters());
1510
+ // Returns a finite number or null. Used to reject Infinity/-Infinity from parseFloat.
1511
+ function parseFiniteFloat(value) {
1512
+ var n = parseFloat(value);
1513
+ // global isFinite is safe here: n is always a number type (no string coercion risk)
1514
+ return isFinite(n) ? n : null;
1515
+ }
1510
1516
  /**
1511
1517
  * @private
1512
1518
  * @param {object} partialState full or part of a state
@@ -1532,8 +1538,18 @@
1532
1538
  var value = partialState[k];
1533
1539
  if (typeof value === 'string') {
1534
1540
  var parsedValue = parseFloat(value);
1535
- // global isNaN is ok to use here, value is only number or NaN
1536
- numbers[k] = isNaN(parsedValue) ? value : parsedValue;
1541
+ if (isNaN(parsedValue)) {
1542
+ // originally an unparseable string like "all", keep NaN
1543
+ numbers[k] = value;
1544
+ } else if (!isFinite(parsedValue)) {
1545
+ // Infinity/-Infinity — convert to null
1546
+ numbers[k] = null;
1547
+ } else {
1548
+ numbers[k] = parsedValue;
1549
+ }
1550
+ } else if (typeof value === 'number' && !isFinite(value)) {
1551
+ // Already-numeric Infinity — convert to null
1552
+ numbers[k] = null;
1537
1553
  }
1538
1554
  });
1539
1555
  // there's two formats of insideBoundingBox, we need to parse
@@ -1542,7 +1558,13 @@
1542
1558
  numbers.insideBoundingBox = partialState.insideBoundingBox.map(function(geoRect) {
1543
1559
  if (Array.isArray(geoRect)) {
1544
1560
  return geoRect.map(function(value) {
1545
- return parseFloat(value);
1561
+ if (typeof value === 'string') {
1562
+ return parseFiniteFloat(value);
1563
+ }
1564
+ if (typeof value === 'number' && !isFinite(value)) {
1565
+ return null;
1566
+ }
1567
+ return value;
1546
1568
  });
1547
1569
  }
1548
1570
  return geoRect;
@@ -1559,12 +1581,17 @@
1559
1581
  if (Array.isArray(v)) {
1560
1582
  return v.map(function(vPrime) {
1561
1583
  if (typeof vPrime === 'string') {
1562
- return parseFloat(vPrime);
1584
+ return parseFiniteFloat(vPrime);
1585
+ }
1586
+ if (typeof vPrime === 'number' && !isFinite(vPrime)) {
1587
+ return null;
1563
1588
  }
1564
1589
  return vPrime;
1565
1590
  });
1566
1591
  } else if (typeof v === 'string') {
1567
- return parseFloat(v);
1592
+ return parseFiniteFloat(v);
1593
+ } else if (typeof v === 'number' && !isFinite(v)) {
1594
+ return null;
1568
1595
  }
1569
1596
  return v;
1570
1597
  });
@@ -3892,7 +3919,7 @@
3892
3919
  function requireVersion() {
3893
3920
  if (hasRequiredVersion) return version$1;
3894
3921
  hasRequiredVersion = 1;
3895
- version$1 = '3.28.1';
3922
+ version$1 = '3.29.0';
3896
3923
  return version$1;
3897
3924
  }
3898
3925
 
@@ -5266,7 +5293,6 @@
5266
5293
  var derivedStateQueries = requestBuilder._getCompositionQueries(derivedState);
5267
5294
  states.push({
5268
5295
  state: derivedState,
5269
- queriesCount: derivedStateQueries.length,
5270
5296
  helper: derivedHelper
5271
5297
  });
5272
5298
  derivedHelper.emit('search', {
@@ -5396,7 +5422,7 @@
5396
5422
  var state = s.state;
5397
5423
  var queriesCount = s.queriesCount;
5398
5424
  var helper = s.helper;
5399
- var specificResults = results.splice(0, queriesCount);
5425
+ var specificResults = queriesCount !== undefined ? results.splice(0, queriesCount) : results;
5400
5426
  if (!state.index) {
5401
5427
  helper.emit('result', {
5402
5428
  results: null,
@@ -5404,8 +5430,24 @@
5404
5430
  });
5405
5431
  return;
5406
5432
  }
5407
- helper.lastResults = new SearchResults(state, specificResults, self._searchResultsOptions);
5408
- if (rawContent !== undefined) helper.lastResults._rawContent = rawContent;
5433
+ // Multifeed composition: build ordered SearchResults array on lastResults
5434
+ if (specificResults.length > 0 && specificResults[0].feedID) {
5435
+ var feeds = specificResults.map(function(r) {
5436
+ var sr = new SearchResults(state, [
5437
+ r
5438
+ ], self._searchResultsOptions);
5439
+ if (rawContent !== undefined) sr._rawContent = rawContent;
5440
+ return sr;
5441
+ });
5442
+ helper.lastResults = new SearchResults(state, [
5443
+ specificResults[0]
5444
+ ], self._searchResultsOptions);
5445
+ helper.lastResults.feeds = feeds;
5446
+ if (rawContent !== undefined) helper.lastResults._rawContent = rawContent;
5447
+ } else {
5448
+ helper.lastResults = new SearchResults(state, specificResults, self._searchResultsOptions);
5449
+ if (rawContent !== undefined) helper.lastResults._rawContent = rawContent;
5450
+ }
5409
5451
  helper.emit('result', {
5410
5452
  results: helper.lastResults,
5411
5453
  state: state
@@ -5938,7 +5980,7 @@
5938
5980
  }
5939
5981
  }
5940
5982
 
5941
- var withUsage$t = createDocumentationMessageGenerator({
5983
+ var withUsage$u = createDocumentationMessageGenerator({
5942
5984
  name: 'configure',
5943
5985
  connector: true
5944
5986
  });
@@ -5954,7 +5996,7 @@
5954
5996
  var renderFn = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : noop, unmountFn = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop;
5955
5997
  return function(widgetParams) {
5956
5998
  if (!widgetParams || !isPlainObject(widgetParams.searchParameters)) {
5957
- throw new Error(withUsage$t('The `searchParameters` option expects an object.'));
5999
+ throw new Error(withUsage$u('The `searchParameters` option expects an object.'));
5958
6000
  }
5959
6001
  var connectorState = {};
5960
6002
  function refine(helper) {
@@ -6238,216 +6280,1319 @@
6238
6280
  return stableValue;
6239
6281
  }
6240
6282
 
6241
- var useKey = 'use';
6242
- // @TODO: Remove this file and import directly from React when available.
6243
- var use = React__namespace[useKey];
6283
+ var id = 0;
6284
+ function addWidgetId(widget) {
6285
+ if (widget.dependsOn !== 'recommend') {
6286
+ return;
6287
+ }
6288
+ widget.$$id = id++;
6289
+ }
6290
+ function resetWidgetId() {
6291
+ id = 0;
6292
+ }
6244
6293
 
6245
- /**
6246
- * `useLayoutEffect` that doesn't show a warning when server-side rendering.
6247
- *
6248
- * It uses `useEffect` on the server (no-op), and `useLayoutEffect` on the browser.
6249
- */ var useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
6294
+ function _array_without_holes(arr) {
6295
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
6296
+ }
6250
6297
 
6251
- var InstantSearchRSCContext = React.createContext({
6252
- countRef: {
6253
- current: 0
6254
- },
6255
- waitForResultsRef: null,
6256
- ignoreMultipleHooksWarning: false
6257
- });
6298
+ function _non_iterable_spread() {
6299
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
6300
+ }
6258
6301
 
6259
- function useRSCContext() {
6260
- return React.useContext(InstantSearchRSCContext);
6302
+ function _to_consumable_array(arr) {
6303
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
6261
6304
  }
6262
6305
 
6263
- /* eslint-disable no-console, no-empty */ var warnCache = {
6264
- current: {}
6265
- };
6266
- /**
6267
- * Logs a warning if the condition is not met.
6268
- * This is used to log issues in development environment only.
6269
- */ function warn(condition, message) {
6270
- if (condition) {
6271
- return;
6272
- }
6273
- var sanitizedMessage = message.trim();
6274
- var hasAlreadyPrinted = warnCache.current[sanitizedMessage];
6275
- if (!hasAlreadyPrinted) {
6276
- warnCache.current[sanitizedMessage] = true;
6277
- var warning = "[InstantSearch] ".concat(sanitizedMessage);
6278
- console.warn(warning);
6279
- try {
6280
- // Welcome to debugging InstantSearch.
6281
- //
6282
- // This error was thrown as a convenience so that you can find the source
6283
- // of the warning that appears in the console by enabling "Pause on exceptions"
6284
- // in your debugger.
6285
- throw new Error(warning);
6286
- } catch (error) {}
6306
+ function getObjectType(object) {
6307
+ return Object.prototype.toString.call(object).slice(8, -1);
6308
+ }
6309
+
6310
+ function checkRendering(rendering, usage) {
6311
+ if (rendering === undefined || typeof rendering !== 'function') {
6312
+ throw new Error("The render function is not valid (received type ".concat(getObjectType(rendering), ").\n\n").concat(usage));
6287
6313
  }
6288
6314
  }
6289
6315
 
6290
- function useWidget(param) {
6291
- var widget = param.widget, parentIndex = param.parentIndex, props = param.props, shouldSsr = param.shouldSsr, skipSuspense = param.skipSuspense;
6292
- var _waitForResultsRef_current, _waitForResultsRef_current1;
6293
- var _useRSCContext = useRSCContext(), waitForResultsRef = _useRSCContext.waitForResultsRef, countRef = _useRSCContext.countRef, ignoreMultipleHooksWarning = _useRSCContext.ignoreMultipleHooksWarning;
6294
- var prevPropsRef = React.useRef(props);
6295
- React.useEffect(function() {
6296
- prevPropsRef.current = props;
6297
- }, [
6298
- props
6299
- ]);
6300
- var prevWidgetRef = React.useRef(widget);
6301
- React.useEffect(function() {
6302
- prevWidgetRef.current = widget;
6303
- }, [
6304
- widget
6305
- ]);
6306
- var cleanupTimerRef = React.useRef(null);
6307
- var shouldAddWidgetEarly = shouldSsr && !parentIndex.getWidgets().includes(widget);
6308
- var search = useInstantSearchContext();
6309
- // This effect is responsible for adding, removing, and updating the widget.
6310
- // We need to support scenarios where the widget is remounted quickly, like in
6311
- // Strict Mode, so that we don't lose its state, and therefore that we don't
6312
- // break routing.
6313
- useIsomorphicLayoutEffect(function() {
6314
- var previousWidget = prevWidgetRef.current;
6315
- // Scenario 1: the widget is added for the first time.
6316
- if (!cleanupTimerRef.current) {
6317
- if (!shouldSsr) {
6318
- parentIndex.addWidgets([
6319
- widget
6320
- ]);
6321
- }
6322
- } else {
6323
- // We cancel the original effect cleanup because it may not be necessary if
6324
- // props haven't changed. (We manually call it if it is below.)
6325
- clearTimeout(cleanupTimerRef.current);
6326
- // Warning: if an unstable function prop is provided, `dequal` is not able
6327
- // to keep its reference and therefore will consider that props did change.
6328
- // This could unsollicitely remove/add the widget, therefore forget its state,
6329
- // and could be a source of confusion.
6330
- // If users face this issue, we should advise them to provide stable function
6331
- // references.
6332
- var arePropsEqual = dequal(props, prevPropsRef.current);
6333
- // If props did change, then we execute the cleanup function instantly
6334
- // and then add the widget back. This lets us add the widget without
6335
- // waiting for the scheduled cleanup function to finish (that we canceled
6336
- // above).
6337
- if (!arePropsEqual) {
6338
- parentIndex.removeWidgets([
6339
- previousWidget
6340
- ]);
6341
- parentIndex.addWidgets([
6342
- widget
6343
- ]);
6344
- }
6316
+ /**
6317
+ * Clears the refinements of a SearchParameters object based on rules provided.
6318
+ * The included attributes list is applied before the excluded attributes list. If the list
6319
+ * is not provided, this list of all the currently refined attributes is used as included attributes.
6320
+ * @returns search parameters with refinements cleared
6321
+ */ function clearRefinements(param) {
6322
+ var helper = param.helper, _param_attributesToClear = param.attributesToClear, attributesToClear = _param_attributesToClear === void 0 ? [] : _param_attributesToClear;
6323
+ var finalState = helper.state.setPage(0);
6324
+ finalState = attributesToClear.reduce(function(state, attribute) {
6325
+ if (finalState.isNumericRefined(attribute)) {
6326
+ return state.removeNumericRefinement(attribute);
6345
6327
  }
6346
- return function() {
6347
- // We don't remove the widget right away, but rather schedule it so that
6348
- // we're able to cancel it in the next effect.
6349
- cleanupTimerRef.current = setTimeout(function() {
6350
- search._schedule(function() {
6351
- if (search._preventWidgetCleanup) return;
6352
- parentIndex.removeWidgets([
6353
- previousWidget
6354
- ]);
6355
- });
6356
- });
6357
- };
6358
- }, [
6359
- parentIndex,
6360
- widget,
6361
- shouldSsr,
6362
- search,
6363
- props
6364
- ]);
6365
- if (shouldAddWidgetEarly || (waitForResultsRef === null || waitForResultsRef === void 0 ? void 0 : (_waitForResultsRef_current = waitForResultsRef.current) === null || _waitForResultsRef_current === void 0 ? void 0 : _waitForResultsRef_current.status) === 'pending') {
6366
- parentIndex.addWidgets([
6367
- widget
6368
- ]);
6369
- }
6370
- if ((waitForResultsRef === null || waitForResultsRef === void 0 ? void 0 : waitForResultsRef.current) && !skipSuspense) {
6371
- var _search_helper;
6372
- use(waitForResultsRef.current);
6373
- // If we made a second request because of DynamicWidgets, we need to wait for the second result,
6374
- // except for DynamicWidgets itself which needs to render its children after the first result.
6375
- if (widget.$$type !== 'ais.dynamicWidgets' && ((_search_helper = search.helper) === null || _search_helper === void 0 ? void 0 : _search_helper.lastResults)) {
6376
- use(waitForResultsRef.current);
6328
+ if (finalState.isHierarchicalFacet(attribute)) {
6329
+ return state.removeHierarchicalFacetRefinement(attribute);
6377
6330
  }
6331
+ if (finalState.isDisjunctiveFacet(attribute)) {
6332
+ return state.removeDisjunctiveFacetRefinement(attribute);
6333
+ }
6334
+ if (finalState.isConjunctiveFacet(attribute)) {
6335
+ return state.removeFacetRefinement(attribute);
6336
+ }
6337
+ return state;
6338
+ }, finalState);
6339
+ if (attributesToClear.indexOf('query') !== -1) {
6340
+ finalState = finalState.setQuery('');
6378
6341
  }
6379
- if ((waitForResultsRef === null || waitForResultsRef === void 0 ? void 0 : (_waitForResultsRef_current1 = waitForResultsRef.current) === null || _waitForResultsRef_current1 === void 0 ? void 0 : _waitForResultsRef_current1.status) === 'fulfilled') {
6380
- countRef.current += 1;
6381
- { warn(ignoreMultipleHooksWarning || countRef.current <= parentIndex.getWidgets().length, "We detected you may have a component with multiple InstantSearch hooks.\n\nWith Next.js, you need to set `skipSuspense` to `true` for all but the last hook in the component, otherwise, only the first hook will be rendered on the server.\n\nThis warning can be a false positive if you are using dynamic widgets or multi-index, in which case you can ignore it by setting `ignoreMultipleHooksWarning` to `true` in `<InstantSearchNext`.\n\nFor more information, see https://www.algolia.com/doc/guides/building-search-ui/going-further/server-side-rendering/react/#composing-hooks"); }
6382
- }
6342
+ return finalState;
6383
6343
  }
6384
6344
 
6385
- function useConnector(connector) {
6386
- var _1 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : void 0, _2 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : void 0;
6387
- var _ref = [
6388
- _1,
6389
- _2
6390
- ], _ref1 = _to_array(_ref), tmp = _ref1[0], props = tmp === void 0 ? {} : tmp, _rest = _ref1.slice(1), _rest1 = _sliced_to_array(_rest, 1), tmp1 = _rest1[0], _ref2 = tmp1 === void 0 ? {} : tmp1, _ref_skipSuspense = _ref2.skipSuspense, skipSuspense = _ref_skipSuspense === void 0 ? false : _ref_skipSuspense, additionalWidgetProperties = _object_without_properties(_ref2, [
6391
- "skipSuspense"
6392
- ]);
6393
- var serverContext = useInstantSearchServerContext();
6394
- var ssrContext = useInstantSearchSSRContext();
6395
- var search = useInstantSearchContext();
6396
- var parentIndex = useIndexContext();
6397
- var stableProps = useStableValue(props);
6398
- var stableAdditionalWidgetProperties = useStableValue(additionalWidgetProperties);
6399
- var shouldSetStateRef = React.useRef(true);
6400
- var previousRenderStateRef = React.useRef(null);
6401
- var previousStatusRef = React.useRef(search.status);
6402
- var widget = React.useMemo(function() {
6403
- var createWidget = connector(function(connectorState, isFirstRender) {
6404
- // We skip the `init` widget render because:
6405
- // - We rely on `getWidgetRenderState` to compute the initial state before
6406
- // the InstantSearch.js lifecycle starts.
6407
- // - It prevents UI flashes when updating the widget props.
6408
- if (isFirstRender) {
6409
- shouldSetStateRef.current = true;
6410
- return;
6411
- }
6412
- // There are situations where InstantSearch.js may render widgets slightly
6413
- // after they're removed by React, and thus try to update the React state
6414
- // on unmounted components. React 16 and 17 consider them as memory leaks
6415
- // and display a warning.
6416
- // This happens in <DynamicWidgets> when `attributesToRender` contains a
6417
- // value without an attribute previously mounted. React will unmount the
6418
- // component controlled by that attribute, but InstantSearch.js will stay
6419
- // unaware of this change until the render pass finishes, and therefore
6420
- // notifies of a state change.
6421
- // This ref lets us track this situation and ignore these state updates.
6422
- if (shouldSetStateRef.current) {
6423
- var instantSearchInstance = connectorState.instantSearchInstance; connectorState.widgetParams; var renderState = _object_without_properties(connectorState, [
6424
- "instantSearchInstance",
6425
- "widgetParams"
6426
- ]);
6427
- // We only update the state when a widget render state param changes,
6428
- // except for functions. We ignore function reference changes to avoid
6429
- // infinite loops. It's safe to omit them because they get updated
6430
- // every time another render param changes.
6431
- if (!dequal(renderState, previousRenderStateRef.current, function(a, b) {
6432
- return (a === null || a === void 0 ? void 0 : a.constructor) === Function && (b === null || b === void 0 ? void 0 : b.constructor) === Function;
6433
- }) || instantSearchInstance.status !== previousStatusRef.current) {
6434
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
6435
- setState(renderState);
6436
- previousRenderStateRef.current = renderState;
6437
- previousStatusRef.current = instantSearchInstance.status;
6438
- }
6439
- }
6440
- }, function() {
6441
- // We'll ignore the next state update until we know for sure that
6442
- // InstantSearch.js re-inits the component.
6443
- shouldSetStateRef.current = false;
6444
- });
6445
- return _object_spread({}, createWidget(stableProps), stableAdditionalWidgetProperties);
6446
- }, [
6447
- connector,
6448
- stableProps,
6449
- stableAdditionalWidgetProperties
6450
- ]);
6345
+ function _extends() {
6346
+ _extends = Object.assign || function assign(target) {
6347
+ for (var i = 1; i < arguments.length; i++) {
6348
+ var source = arguments[i];
6349
+ for (var key in source) if (Object.prototype.hasOwnProperty.call(source, key)) target[key] = source[key];
6350
+ }
6351
+
6352
+ return target;
6353
+ };
6354
+
6355
+ return _extends.apply(this, arguments);
6356
+ }
6357
+
6358
+ function _object_destructuring_empty(o) {
6359
+ if (o === null || o === void 0) throw new TypeError("Cannot destructure " + o);
6360
+
6361
+ return o;
6362
+ }
6363
+
6364
+ /**
6365
+ * This implementation is taken from Lodash implementation.
6366
+ * See: https://github.com/lodash/lodash/blob/4.17.11-npm/escape.js
6367
+ */ // Used to map characters to HTML entities.
6368
+ var htmlEntities = {
6369
+ '&': '&amp;',
6370
+ '<': '&lt;',
6371
+ '>': '&gt;',
6372
+ '"': '&quot;',
6373
+ "'": '&#39;'
6374
+ };
6375
+ // Used to match HTML entities and HTML characters.
6376
+ var regexUnescapedHtml = /[&<>"']/g;
6377
+ var regexHasUnescapedHtml = RegExp(regexUnescapedHtml.source);
6378
+ /**
6379
+ * Converts the characters "&", "<", ">", '"', and "'" in `string` to their
6380
+ * corresponding HTML entities.
6381
+ */ function escape$1(value) {
6382
+ return value && regexHasUnescapedHtml.test(value) ? value.replace(regexUnescapedHtml, function(character) {
6383
+ return htmlEntities[character];
6384
+ }) : value;
6385
+ }
6386
+ /**
6387
+ * This implementation is taken from Lodash implementation.
6388
+ * See: https://github.com/lodash/lodash/blob/4.17.11-npm/unescape.js
6389
+ */ // Used to map HTML entities to characters.
6390
+ var htmlCharacters = {
6391
+ '&amp;': '&',
6392
+ '&lt;': '<',
6393
+ '&gt;': '>',
6394
+ '&quot;': '"',
6395
+ '&#39;': "'"
6396
+ };
6397
+ // Used to match HTML entities and HTML characters.
6398
+ var regexEscapedHtml = /&(amp|quot|lt|gt|#39);/g;
6399
+ var regexHasEscapedHtml = RegExp(regexEscapedHtml.source);
6400
+ /**
6401
+ * Converts the HTML entities "&", "<", ">", '"', and "'" in `string` to their
6402
+ * characters.
6403
+ */ function unescape$1(value) {
6404
+ return value && regexHasEscapedHtml.test(value) ? value.replace(regexEscapedHtml, function(character) {
6405
+ return htmlCharacters[character];
6406
+ }) : value;
6407
+ }
6408
+
6409
+ var TAG_PLACEHOLDER = {
6410
+ highlightPreTag: '__ais-highlight__',
6411
+ highlightPostTag: '__/ais-highlight__'
6412
+ };
6413
+ var TAG_REPLACEMENT = {
6414
+ highlightPreTag: '<mark>',
6415
+ highlightPostTag: '</mark>'
6416
+ };
6417
+ // @MAJOR: in the future, this should only escape, not replace
6418
+ function replaceTagsAndEscape(value) {
6419
+ return escape$1(value).replace(new RegExp(TAG_PLACEHOLDER.highlightPreTag, 'g'), TAG_REPLACEMENT.highlightPreTag).replace(new RegExp(TAG_PLACEHOLDER.highlightPostTag, 'g'), TAG_REPLACEMENT.highlightPostTag);
6420
+ }
6421
+ function recursiveEscape(input) {
6422
+ if (isPlainObject(input) && typeof input.value !== 'string') {
6423
+ return Object.keys(input).reduce(function(acc, key) {
6424
+ return _object_spread_props(_object_spread({}, acc), _define_property({}, key, recursiveEscape(input[key])));
6425
+ }, {});
6426
+ }
6427
+ if (Array.isArray(input)) {
6428
+ return input.map(recursiveEscape);
6429
+ }
6430
+ return _object_spread_props(_object_spread({}, input), {
6431
+ value: replaceTagsAndEscape(input.value)
6432
+ });
6433
+ }
6434
+ function escapeHits(hits) {
6435
+ if (hits.__escaped === undefined) {
6436
+ // We don't override the value on hit because it will mutate the raw results
6437
+ // instead we make a shallow copy and we assign the escaped values on it.
6438
+ hits = hits.map(function(_0) {
6439
+ _object_destructuring_empty(_0);
6440
+ var hit = _extends({}, _0);
6441
+ if (hit._highlightResult) {
6442
+ hit._highlightResult = recursiveEscape(hit._highlightResult);
6443
+ }
6444
+ if (hit._snippetResult) {
6445
+ hit._snippetResult = recursiveEscape(hit._snippetResult);
6446
+ }
6447
+ return hit;
6448
+ });
6449
+ hits.__escaped = true;
6450
+ }
6451
+ return hits;
6452
+ }
6453
+ function escapeFacets(facetHits) {
6454
+ return facetHits.map(function(h) {
6455
+ return _object_spread_props(_object_spread({}, h), {
6456
+ highlighted: replaceTagsAndEscape(h.highlighted)
6457
+ });
6458
+ });
6459
+ }
6460
+
6461
+ function concatHighlightedParts(parts) {
6462
+ var highlightPreTag = TAG_REPLACEMENT.highlightPreTag, highlightPostTag = TAG_REPLACEMENT.highlightPostTag;
6463
+ return parts.map(function(part) {
6464
+ return part.isHighlighted ? highlightPreTag + part.value + highlightPostTag : part.value;
6465
+ }).join('');
6466
+ }
6467
+
6468
+ function isFacetRefined(helper, facet, value) {
6469
+ if (helper.state.isHierarchicalFacet(facet)) {
6470
+ return helper.state.isHierarchicalFacetRefined(facet, value);
6471
+ } else if (helper.state.isConjunctiveFacet(facet)) {
6472
+ return helper.state.isFacetRefined(facet, value);
6473
+ } else {
6474
+ return helper.state.isDisjunctiveFacetRefined(facet, value);
6475
+ }
6476
+ }
6477
+
6478
+ function createSendEventForFacet(param) {
6479
+ var instantSearchInstance = param.instantSearchInstance, helper = param.helper, attr = param.attribute, widgetType = param.widgetType;
6480
+ var sendEventForFacet = function sendEventForFacet() {
6481
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
6482
+ args[_key] = arguments[_key];
6483
+ }
6484
+ var _args = _sliced_to_array(args, 4), facetValue = _args[1], tmp = _args[2], eventName = tmp === void 0 ? 'Filter Applied' : tmp, tmp1 = _args[3], additionalData = tmp1 === void 0 ? {} : tmp1;
6485
+ var _args__split = _sliced_to_array(args[0].split(':'), 2), eventType = _args__split[0], eventModifier = _args__split[1];
6486
+ var attribute = typeof attr === 'string' ? attr : attr(facetValue);
6487
+ if (args.length === 1 && _type_of(args[0]) === 'object') {
6488
+ instantSearchInstance.sendEventToInsights(args[0]);
6489
+ } else if (eventType === 'click' && args.length >= 2 && args.length <= 4) {
6490
+ if (!isFacetRefined(helper, attribute, facetValue)) {
6491
+ var _helper_lastResults;
6492
+ // send event only when the facet is being checked "ON"
6493
+ instantSearchInstance.sendEventToInsights({
6494
+ insightsMethod: 'clickedFilters',
6495
+ widgetType: widgetType,
6496
+ eventType: eventType,
6497
+ eventModifier: eventModifier,
6498
+ payload: _object_spread({
6499
+ eventName: eventName,
6500
+ index: ((_helper_lastResults = helper.lastResults) === null || _helper_lastResults === void 0 ? void 0 : _helper_lastResults.index) || helper.state.index,
6501
+ filters: [
6502
+ "".concat(attribute, ":").concat(facetValue)
6503
+ ]
6504
+ }, additionalData),
6505
+ attribute: attribute
6506
+ });
6507
+ }
6508
+ } else ;
6509
+ };
6510
+ return sendEventForFacet;
6511
+ }
6512
+
6513
+ function serializePayload(payload) {
6514
+ return btoa(encodeURIComponent(JSON.stringify(payload)));
6515
+ }
6516
+
6517
+ function chunk(arr) {
6518
+ var chunkSize = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 20;
6519
+ var chunks = [];
6520
+ for(var i = 0; i < Math.ceil(arr.length / chunkSize); i++){
6521
+ chunks.push(arr.slice(i * chunkSize, (i + 1) * chunkSize));
6522
+ }
6523
+ return chunks;
6524
+ }
6525
+ function _buildEventPayloadsForHits(param) {
6526
+ var helper = param.helper, widgetType = param.widgetType;
6527
+ param.methodName;
6528
+ var args = param.args, instantSearchInstance = param.instantSearchInstance;
6529
+ // when there's only one argument, that means it's custom
6530
+ if (args.length === 1 && _type_of(args[0]) === 'object') {
6531
+ return [
6532
+ args[0]
6533
+ ];
6534
+ }
6535
+ var _args__split = _sliced_to_array(args[0].split(':'), 2), eventType = _args__split[0], eventModifier = _args__split[1];
6536
+ var hits = args[1];
6537
+ var eventName = args[2];
6538
+ var additionalData = args[3] || {};
6539
+ if (!hits) {
6540
+ {
6541
+ return [];
6542
+ }
6543
+ }
6544
+ if ((eventType === 'click' || eventType === 'conversion') && !eventName) {
6545
+ {
6546
+ return [];
6547
+ }
6548
+ }
6549
+ var hitsArray = Array.isArray(hits) ? hits : [
6550
+ hits
6551
+ ];
6552
+ if (hitsArray.length === 0) {
6553
+ return [];
6554
+ }
6555
+ var queryID = hitsArray[0].__queryID;
6556
+ var hitsChunks = chunk(hitsArray);
6557
+ var objectIDsByChunk = hitsChunks.map(function(batch) {
6558
+ return batch.map(function(hit) {
6559
+ return hit.objectID;
6560
+ });
6561
+ });
6562
+ var positionsByChunk = hitsChunks.map(function(batch) {
6563
+ return batch.map(function(hit) {
6564
+ return hit.__position;
6565
+ });
6566
+ });
6567
+ if (eventType === 'view') {
6568
+ if (instantSearchInstance.status !== 'idle') {
6569
+ return [];
6570
+ }
6571
+ return hitsChunks.map(function(batch, i) {
6572
+ var _helper_lastResults;
6573
+ return {
6574
+ insightsMethod: 'viewedObjectIDs',
6575
+ widgetType: widgetType,
6576
+ eventType: eventType,
6577
+ payload: _object_spread({
6578
+ eventName: eventName || 'Hits Viewed',
6579
+ index: ((_helper_lastResults = helper.lastResults) === null || _helper_lastResults === void 0 ? void 0 : _helper_lastResults.index) || helper.state.index,
6580
+ objectIDs: objectIDsByChunk[i]
6581
+ }, additionalData),
6582
+ hits: batch,
6583
+ eventModifier: eventModifier
6584
+ };
6585
+ });
6586
+ } else if (eventType === 'click') {
6587
+ return hitsChunks.map(function(batch, i) {
6588
+ var _helper_lastResults;
6589
+ return {
6590
+ insightsMethod: 'clickedObjectIDsAfterSearch',
6591
+ widgetType: widgetType,
6592
+ eventType: eventType,
6593
+ payload: _object_spread({
6594
+ eventName: eventName || 'Hit Clicked',
6595
+ index: ((_helper_lastResults = helper.lastResults) === null || _helper_lastResults === void 0 ? void 0 : _helper_lastResults.index) || helper.state.index,
6596
+ queryID: queryID,
6597
+ objectIDs: objectIDsByChunk[i],
6598
+ positions: positionsByChunk[i]
6599
+ }, additionalData),
6600
+ hits: batch,
6601
+ eventModifier: eventModifier
6602
+ };
6603
+ });
6604
+ } else if (eventType === 'conversion') {
6605
+ return hitsChunks.map(function(batch, i) {
6606
+ var _helper_lastResults;
6607
+ return {
6608
+ insightsMethod: 'convertedObjectIDsAfterSearch',
6609
+ widgetType: widgetType,
6610
+ eventType: eventType,
6611
+ payload: _object_spread({
6612
+ eventName: eventName || 'Hit Converted',
6613
+ index: ((_helper_lastResults = helper.lastResults) === null || _helper_lastResults === void 0 ? void 0 : _helper_lastResults.index) || helper.state.index,
6614
+ queryID: queryID,
6615
+ objectIDs: objectIDsByChunk[i]
6616
+ }, additionalData),
6617
+ hits: batch,
6618
+ eventModifier: eventModifier
6619
+ };
6620
+ });
6621
+ } else {
6622
+ return [];
6623
+ }
6624
+ }
6625
+ function createSendEventForHits(param) {
6626
+ var instantSearchInstance = param.instantSearchInstance, helper = param.helper, widgetType = param.widgetType;
6627
+ var sentEvents = {};
6628
+ var timer = undefined;
6629
+ var sendEventForHits = function sendEventForHits() {
6630
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
6631
+ args[_key] = arguments[_key];
6632
+ }
6633
+ var payloads = _buildEventPayloadsForHits({
6634
+ widgetType: widgetType,
6635
+ helper: helper,
6636
+ methodName: 'sendEvent',
6637
+ args: args,
6638
+ instantSearchInstance: instantSearchInstance
6639
+ });
6640
+ payloads.forEach(function(payload) {
6641
+ if (payload.eventType === 'click' && payload.eventModifier === 'internal' && sentEvents[payload.eventType]) {
6642
+ return;
6643
+ }
6644
+ sentEvents[payload.eventType] = true;
6645
+ instantSearchInstance.sendEventToInsights(payload);
6646
+ });
6647
+ clearTimeout(timer);
6648
+ timer = setTimeout(function() {
6649
+ sentEvents = {};
6650
+ }, 0);
6651
+ };
6652
+ return sendEventForHits;
6653
+ }
6654
+ function createBindEventForHits(param) {
6655
+ var helper = param.helper, widgetType = param.widgetType, instantSearchInstance = param.instantSearchInstance;
6656
+ var bindEventForHits = function bindEventForHits() {
6657
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
6658
+ args[_key] = arguments[_key];
6659
+ }
6660
+ var payloads = _buildEventPayloadsForHits({
6661
+ widgetType: widgetType,
6662
+ helper: helper,
6663
+ methodName: 'bindEvent',
6664
+ args: args,
6665
+ instantSearchInstance: instantSearchInstance
6666
+ });
6667
+ return payloads.length ? "data-insights-event=".concat(serializePayload(payloads)) : '';
6668
+ };
6669
+ return bindEventForHits;
6670
+ }
6671
+
6672
+ var indexWidgetTypes = [
6673
+ 'ais.index',
6674
+ 'ais.feedContainer'
6675
+ ];
6676
+
6677
+ function isIndexWidget(widget) {
6678
+ return indexWidgetTypes.includes(widget.$$type);
6679
+ }
6680
+
6681
+ function setIndexHelperState(finalUiState, indexWidget) {
6682
+ var nextIndexUiState = finalUiState[indexWidget.getIndexId()] || {};
6683
+ indexWidget.getHelper().setState(indexWidget.getWidgetSearchParameters(indexWidget.getHelper().state, {
6684
+ uiState: nextIndexUiState
6685
+ }));
6686
+ indexWidget.getWidgets().filter(isIndexWidget).forEach(function(widget) {
6687
+ return setIndexHelperState(finalUiState, widget);
6688
+ });
6689
+ }
6690
+
6691
+ var nextMicroTask = Promise.resolve();
6692
+ function defer(callback) {
6693
+ var progress = null;
6694
+ var cancelled = false;
6695
+ var fn = function fn() {
6696
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
6697
+ args[_key] = arguments[_key];
6698
+ }
6699
+ if (progress !== null) {
6700
+ return;
6701
+ }
6702
+ progress = nextMicroTask.then(function() {
6703
+ progress = null;
6704
+ if (cancelled) {
6705
+ cancelled = false;
6706
+ return;
6707
+ }
6708
+ callback.apply(void 0, _to_consumable_array(args));
6709
+ });
6710
+ };
6711
+ fn.wait = function() {
6712
+ if (progress === null) {
6713
+ throw new Error('The deferred function should be called before calling `wait()`');
6714
+ }
6715
+ return progress;
6716
+ };
6717
+ fn.cancel = function() {
6718
+ if (progress === null) {
6719
+ return;
6720
+ }
6721
+ cancelled = true;
6722
+ };
6723
+ return fn;
6724
+ }
6725
+
6726
+ function sendChatMessageFeedback(param) {
6727
+ var agentId = param.agentId, vote = param.vote, messageId = param.messageId, appId = param.appId, apiKey = param.apiKey;
6728
+ return fetch("https://".concat(appId, ".algolia.net/agent-studio/1/feedback"), {
6729
+ method: 'POST',
6730
+ body: JSON.stringify({
6731
+ messageId: messageId,
6732
+ agentId: agentId,
6733
+ vote: vote
6734
+ }),
6735
+ headers: {
6736
+ 'x-algolia-application-id': appId,
6737
+ 'x-algolia-api-key': apiKey,
6738
+ 'content-type': 'application/json'
6739
+ }
6740
+ }).then(function(response) {
6741
+ if (response.status >= 300) {
6742
+ return response.json().then(function(data) {
6743
+ throw new Error("Feedback request failed with status ".concat(response.status, ": ").concat(data.message));
6744
+ });
6745
+ }
6746
+ return response.json();
6747
+ });
6748
+ }
6749
+
6750
+ function unescapeFacetValue(value) {
6751
+ if (typeof value === 'string') {
6752
+ return value.replace(/^\\-/, '-');
6753
+ }
6754
+ return value;
6755
+ }
6756
+ function escapeFacetValue(value) {
6757
+ if (typeof value === 'number' && value < 0 || typeof value === 'string') {
6758
+ return String(value).replace(/^-/, '\\-');
6759
+ }
6760
+ return value;
6761
+ }
6762
+
6763
+ // We aren't using the native `Array.prototype.find` because the refactor away from Lodash is not
6764
+ // published as a major version.
6765
+ // Relying on the `find` polyfill on user-land, which before was only required for niche use-cases,
6766
+ // was decided as too risky.
6767
+ // @MAJOR Replace with the native `Array.prototype.find` method
6768
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
6769
+ function find(items, predicate) {
6770
+ var value;
6771
+ for(var i = 0; i < items.length; i++){
6772
+ value = items[i];
6773
+ // inlined for performance: if (Call(predicate, thisArg, [value, i, list])) {
6774
+ if (predicate(value, i, items)) {
6775
+ return value;
6776
+ }
6777
+ }
6778
+ return undefined;
6779
+ }
6780
+
6781
+ var latLngRegExp = /^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)$/;
6782
+ function aroundLatLngToPosition(value) {
6783
+ var pattern = value.match(latLngRegExp);
6784
+ // Since the value provided is the one send with the request, the API should
6785
+ // throw an error due to the wrong format. So throw an error should be safe.
6786
+ if (!pattern) {
6787
+ throw new Error('Invalid value for "aroundLatLng" parameter: "'.concat(value, '"'));
6788
+ }
6789
+ return {
6790
+ lat: parseFloat(pattern[1]),
6791
+ lng: parseFloat(pattern[2])
6792
+ };
6793
+ }
6794
+ function insideBoundingBoxArrayToBoundingBox(value) {
6795
+ var _value = _sliced_to_array(value, 1), tmp = _value[0], _ref = _sliced_to_array(tmp === void 0 ? [
6796
+ undefined,
6797
+ undefined,
6798
+ undefined,
6799
+ undefined
6800
+ ] : tmp, 4), neLat = _ref[0], neLng = _ref[1], swLat = _ref[2], swLng = _ref[3];
6801
+ // Since the value provided is the one send with the request, the API should
6802
+ // throw an error due to the wrong format. So throw an error should be safe.
6803
+ if (!neLat || !neLng || !swLat || !swLng) {
6804
+ throw new Error('Invalid value for "insideBoundingBox" parameter: ['.concat(value, "]"));
6805
+ }
6806
+ return {
6807
+ northEast: {
6808
+ lat: neLat,
6809
+ lng: neLng
6810
+ },
6811
+ southWest: {
6812
+ lat: swLat,
6813
+ lng: swLng
6814
+ }
6815
+ };
6816
+ }
6817
+ function insideBoundingBoxStringToBoundingBox(value) {
6818
+ var _value_split_map = _sliced_to_array(value.split(',').map(parseFloat), 4), neLat = _value_split_map[0], neLng = _value_split_map[1], swLat = _value_split_map[2], swLng = _value_split_map[3];
6819
+ // Since the value provided is the one send with the request, the API should
6820
+ // throw an error due to the wrong format. So throw an error should be safe.
6821
+ if (!neLat || !neLng || !swLat || !swLng) {
6822
+ throw new Error('Invalid value for "insideBoundingBox" parameter: "'.concat(value, '"'));
6823
+ }
6824
+ return {
6825
+ northEast: {
6826
+ lat: neLat,
6827
+ lng: neLng
6828
+ },
6829
+ southWest: {
6830
+ lat: swLat,
6831
+ lng: swLng
6832
+ }
6833
+ };
6834
+ }
6835
+ function insideBoundingBoxToBoundingBox(value) {
6836
+ if (Array.isArray(value)) {
6837
+ return insideBoundingBoxArrayToBoundingBox(value);
6838
+ }
6839
+ return insideBoundingBoxStringToBoundingBox(value);
6840
+ }
6841
+
6842
+ function getAlgoliaAgent(client) {
6843
+ var clientTyped = client;
6844
+ return clientTyped.transporter && clientTyped.transporter.userAgent ? clientTyped.transporter.userAgent.value : clientTyped._ua;
6845
+ }
6846
+
6847
+ // typed as any, since it accepts the _real_ js clients, not the interface we otherwise expect
6848
+ function getAppIdAndApiKey(searchClient) {
6849
+ if (searchClient.appId && searchClient.apiKey) {
6850
+ // searchClient v5
6851
+ return [
6852
+ searchClient.appId,
6853
+ searchClient.apiKey
6854
+ ];
6855
+ } else if (searchClient.transporter) {
6856
+ // searchClient v4 or v5
6857
+ var transporter = searchClient.transporter;
6858
+ var headers = transporter.headers || transporter.baseHeaders;
6859
+ var queryParameters = transporter.queryParameters || transporter.baseQueryParameters;
6860
+ var APP_ID = 'x-algolia-application-id';
6861
+ var API_KEY = 'x-algolia-api-key';
6862
+ var appId = headers[APP_ID] || queryParameters[APP_ID];
6863
+ var apiKey = headers[API_KEY] || queryParameters[API_KEY];
6864
+ return [
6865
+ appId,
6866
+ apiKey
6867
+ ];
6868
+ } else {
6869
+ // searchClient v3
6870
+ return [
6871
+ searchClient.applicationID,
6872
+ searchClient.apiKey
6873
+ ];
6874
+ }
6875
+ }
6876
+
6877
+ function getHighlightedParts(highlightedValue) {
6878
+ // @MAJOR: this should use TAG_PLACEHOLDER
6879
+ var highlightPostTag = TAG_REPLACEMENT.highlightPostTag, highlightPreTag = TAG_REPLACEMENT.highlightPreTag;
6880
+ var splitByPreTag = highlightedValue.split(highlightPreTag);
6881
+ var firstValue = splitByPreTag.shift();
6882
+ var elements = !firstValue ? [] : [
6883
+ {
6884
+ value: firstValue,
6885
+ isHighlighted: false
6886
+ }
6887
+ ];
6888
+ splitByPreTag.forEach(function(split) {
6889
+ var splitByPostTag = split.split(highlightPostTag);
6890
+ elements.push({
6891
+ value: splitByPostTag[0],
6892
+ isHighlighted: true
6893
+ });
6894
+ if (splitByPostTag[1] !== '') {
6895
+ elements.push({
6896
+ value: splitByPostTag[1],
6897
+ isHighlighted: false
6898
+ });
6899
+ }
6900
+ });
6901
+ return elements;
6902
+ }
6903
+
6904
+ var hasAlphanumeric = new RegExp(/\w/i);
6905
+ function getHighlightFromSiblings(parts, i) {
6906
+ var _parts_, _parts_1;
6907
+ var current = parts[i];
6908
+ var isNextHighlighted = ((_parts_ = parts[i + 1]) === null || _parts_ === void 0 ? void 0 : _parts_.isHighlighted) || true;
6909
+ var isPreviousHighlighted = ((_parts_1 = parts[i - 1]) === null || _parts_1 === void 0 ? void 0 : _parts_1.isHighlighted) || true;
6910
+ if (!hasAlphanumeric.test(unescape$1(current.value)) && isPreviousHighlighted === isNextHighlighted) {
6911
+ return isPreviousHighlighted;
6912
+ }
6913
+ return current.isHighlighted;
6914
+ }
6915
+
6916
+ function getPropertyByPath(object, path) {
6917
+ var parts = Array.isArray(path) ? path : path.split('.');
6918
+ return parts.reduce(function(current, key) {
6919
+ return current && current[key];
6920
+ }, object);
6921
+ }
6922
+
6923
+ function getRefinement(state, type, attribute, name) {
6924
+ var resultsFacets = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : [];
6925
+ var res = {
6926
+ type: type,
6927
+ attribute: attribute,
6928
+ name: name,
6929
+ escapedValue: escapeFacetValue(name)
6930
+ };
6931
+ var facet = find(resultsFacets, function(resultsFacet) {
6932
+ return resultsFacet.name === attribute;
6933
+ });
6934
+ var count;
6935
+ if (type === 'hierarchical') {
6936
+ var _loop = function _loop(i) {
6937
+ facet = facet && facet.data && find(Object.keys(facet.data).map(getFacetRefinement(facet.data)), function(refinement) {
6938
+ return refinement.name === nameParts[i];
6939
+ });
6940
+ };
6941
+ var facetDeclaration = state.getHierarchicalFacetByName(attribute);
6942
+ var nameParts = name.split(facetDeclaration.separator);
6943
+ var getFacetRefinement = function getFacetRefinement(facetData) {
6944
+ return function(refinementKey) {
6945
+ return facetData[refinementKey];
6946
+ };
6947
+ };
6948
+ for(var i = 0; facet !== undefined && i < nameParts.length; ++i)_loop(i);
6949
+ count = facet && facet.count;
6950
+ } else {
6951
+ count = facet && facet.data && facet.data[res.name];
6952
+ }
6953
+ if (count !== undefined) {
6954
+ res.count = count;
6955
+ }
6956
+ if (facet && facet.exhaustive !== undefined) {
6957
+ res.exhaustive = facet.exhaustive;
6958
+ }
6959
+ return res;
6960
+ }
6961
+ function getRefinements(_results, state) {
6962
+ var includesQuery = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
6963
+ var results = _results || {};
6964
+ var refinements = [];
6965
+ var _state_facetsRefinements = state.facetsRefinements, facetsRefinements = _state_facetsRefinements === void 0 ? {} : _state_facetsRefinements, _state_facetsExcludes = state.facetsExcludes, facetsExcludes = _state_facetsExcludes === void 0 ? {} : _state_facetsExcludes, _state_disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements, disjunctiveFacetsRefinements = _state_disjunctiveFacetsRefinements === void 0 ? {} : _state_disjunctiveFacetsRefinements, _state_hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements, hierarchicalFacetsRefinements = _state_hierarchicalFacetsRefinements === void 0 ? {} : _state_hierarchicalFacetsRefinements, _state_numericRefinements = state.numericRefinements, numericRefinements = _state_numericRefinements === void 0 ? {} : _state_numericRefinements, _state_tagRefinements = state.tagRefinements, tagRefinements = _state_tagRefinements === void 0 ? [] : _state_tagRefinements;
6966
+ Object.keys(facetsRefinements).forEach(function(attribute) {
6967
+ var refinementNames = facetsRefinements[attribute];
6968
+ refinementNames.forEach(function(refinementName) {
6969
+ refinements.push(getRefinement(state, 'facet', attribute, refinementName, results.facets));
6970
+ });
6971
+ });
6972
+ Object.keys(facetsExcludes).forEach(function(attribute) {
6973
+ var refinementNames = facetsExcludes[attribute];
6974
+ refinementNames.forEach(function(refinementName) {
6975
+ refinements.push({
6976
+ type: 'exclude',
6977
+ attribute: attribute,
6978
+ name: refinementName,
6979
+ exclude: true
6980
+ });
6981
+ });
6982
+ });
6983
+ Object.keys(disjunctiveFacetsRefinements).forEach(function(attribute) {
6984
+ var refinementNames = disjunctiveFacetsRefinements[attribute];
6985
+ refinementNames.forEach(function(refinementName) {
6986
+ refinements.push(getRefinement(state, 'disjunctive', attribute, // they can be escaped on negative numeric values with `escapeFacetValue`.
6987
+ unescapeFacetValue(refinementName), results.disjunctiveFacets));
6988
+ });
6989
+ });
6990
+ Object.keys(hierarchicalFacetsRefinements).forEach(function(attribute) {
6991
+ var refinementNames = hierarchicalFacetsRefinements[attribute];
6992
+ refinementNames.forEach(function(refinement) {
6993
+ refinements.push(getRefinement(state, 'hierarchical', attribute, refinement, results.hierarchicalFacets));
6994
+ });
6995
+ });
6996
+ Object.keys(numericRefinements).forEach(function(attribute) {
6997
+ var operators = numericRefinements[attribute];
6998
+ Object.keys(operators).forEach(function(operatorOriginal) {
6999
+ var operator = operatorOriginal;
7000
+ var valueOrValues = operators[operator];
7001
+ var refinementNames = Array.isArray(valueOrValues) ? valueOrValues : [
7002
+ valueOrValues
7003
+ ];
7004
+ refinementNames.forEach(function(refinementName) {
7005
+ refinements.push({
7006
+ type: 'numeric',
7007
+ attribute: attribute,
7008
+ name: "".concat(refinementName),
7009
+ numericValue: refinementName,
7010
+ operator: operator
7011
+ });
7012
+ });
7013
+ });
7014
+ });
7015
+ tagRefinements.forEach(function(refinementName) {
7016
+ refinements.push({
7017
+ type: 'tag',
7018
+ attribute: '_tags',
7019
+ name: refinementName
7020
+ });
7021
+ });
7022
+ if (includesQuery && state.query && state.query.trim()) {
7023
+ refinements.push({
7024
+ attribute: 'query',
7025
+ type: 'query',
7026
+ name: state.query,
7027
+ query: state.query
7028
+ });
7029
+ }
7030
+ return refinements;
7031
+ }
7032
+
7033
+ function getWidgetAttribute$1(widget, initOptions) {
7034
+ var _widget_getWidgetRenderState;
7035
+ var renderState = (_widget_getWidgetRenderState = widget.getWidgetRenderState) === null || _widget_getWidgetRenderState === void 0 ? void 0 : _widget_getWidgetRenderState.call(widget, initOptions);
7036
+ var attribute = null;
7037
+ if (renderState && renderState.widgetParams) {
7038
+ // casting as widgetParams is checked just before
7039
+ var widgetParams = renderState.widgetParams;
7040
+ if (widgetParams.attribute) {
7041
+ attribute = widgetParams.attribute;
7042
+ } else if (Array.isArray(widgetParams.attributes)) {
7043
+ attribute = widgetParams.attributes[0];
7044
+ }
7045
+ }
7046
+ if (typeof attribute !== 'string') {
7047
+ throw new Error("Could not find the attribute of the widget:\n\n".concat(JSON.stringify(widget), "\n\nPlease check whether the widget's getWidgetRenderState returns widgetParams.attribute correctly."));
7048
+ }
7049
+ return attribute;
7050
+ }
7051
+
7052
+ function addAbsolutePosition(hits, page, hitsPerPage) {
7053
+ return hits.map(function(hit, idx) {
7054
+ return _object_spread_props(_object_spread({}, hit), {
7055
+ __position: hitsPerPage * page + idx + 1
7056
+ });
7057
+ });
7058
+ }
7059
+
7060
+ function addQueryID(hits, queryID) {
7061
+ if (!queryID) {
7062
+ return hits;
7063
+ }
7064
+ return hits.map(function(hit) {
7065
+ return _object_spread_props(_object_spread({}, hit), {
7066
+ __queryID: queryID
7067
+ });
7068
+ });
7069
+ }
7070
+
7071
+ function hydrateRecommendCache(helper, initialResults) {
7072
+ var recommendCache = Object.keys(initialResults).reduce(function(acc, indexName) {
7073
+ var initialResult = initialResults[indexName];
7074
+ if (initialResult.recommendResults) {
7075
+ // @MAJOR: Use `Object.assign` instead of spread operator
7076
+ return _object_spread({}, acc, initialResult.recommendResults.results);
7077
+ }
7078
+ return acc;
7079
+ }, {});
7080
+ helper._recommendCache = recommendCache;
7081
+ }
7082
+
7083
+ function getServerResults(entry) {
7084
+ var _entry_compositionFeedsResults;
7085
+ return ((_entry_compositionFeedsResults = entry.compositionFeedsResults) === null || _entry_compositionFeedsResults === void 0 ? void 0 : _entry_compositionFeedsResults.length) ? entry.compositionFeedsResults : entry.results || [];
7086
+ }
7087
+ function hydrateSearchClient(client, results) {
7088
+ if (!results) {
7089
+ return;
7090
+ }
7091
+ // Disable cache hydration on:
7092
+ // - Algoliasearch API Client < v4 with cache disabled
7093
+ // - Third party clients (detected by the `addAlgoliaAgent` function missing)
7094
+ if ((!('transporter' in client) || client._cacheHydrated) && (!client._useCache || typeof client.addAlgoliaAgent !== 'function')) {
7095
+ return;
7096
+ }
7097
+ var cachedRequest = [
7098
+ Object.keys(results).reduce(function(acc, key) {
7099
+ var entry = results[key];
7100
+ var state = entry.state, requestParams = entry.requestParams;
7101
+ var serverResults = getServerResults(entry);
7102
+ var mappedResults = serverResults && state ? serverResults.map(function(result, idx) {
7103
+ return _object_spread({
7104
+ indexName: state.index || result.index
7105
+ }, (requestParams === null || requestParams === void 0 ? void 0 : requestParams[idx]) || result.params ? {
7106
+ params: serializeQueryParameters((requestParams === null || requestParams === void 0 ? void 0 : requestParams[idx]) || deserializeQueryParameters(result.params))
7107
+ } : {});
7108
+ }) : [];
7109
+ return acc.concat(mappedResults);
7110
+ }, [])
7111
+ ];
7112
+ var cachedResults = Object.keys(results).reduce(function(acc, key) {
7113
+ var res = getServerResults(results[key]);
7114
+ if (!res) {
7115
+ return acc;
7116
+ }
7117
+ return acc.concat(res);
7118
+ }, []);
7119
+ // Algoliasearch API Client >= v4
7120
+ // To hydrate the client we need to populate the cache with the data from
7121
+ // the server (done in `hydrateSearchClientWithMultiIndexRequest` or
7122
+ // `hydrateSearchClientWithSingleIndexRequest`). But since there is no way
7123
+ // for us to compute the key the same way as `algoliasearch-client` we need
7124
+ // to populate it on a custom key and override the `search` method to
7125
+ // search on it first.
7126
+ if ('transporter' in client && !client._cacheHydrated) {
7127
+ client._cacheHydrated = true;
7128
+ var baseMethod = client.search.bind(client);
7129
+ client.search = function(requests) {
7130
+ for(var _len = arguments.length, methodArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
7131
+ methodArgs[_key - 1] = arguments[_key];
7132
+ }
7133
+ var requestsWithSerializedParams = Array.isArray(requests) ? requests.map(function(request) {
7134
+ return _object_spread_props(_object_spread({}, request), {
7135
+ params: serializeQueryParameters(request.params)
7136
+ });
7137
+ }) : serializeQueryParameters(requests.requestBody.params);
7138
+ return client.transporter.responsesCache.get({
7139
+ method: 'search',
7140
+ args: [
7141
+ requestsWithSerializedParams
7142
+ ].concat(_to_consumable_array(methodArgs))
7143
+ }, function() {
7144
+ return baseMethod.apply(void 0, [
7145
+ requests
7146
+ ].concat(_to_consumable_array(methodArgs)));
7147
+ });
7148
+ };
7149
+ client.transporter.responsesCache.set({
7150
+ method: 'search',
7151
+ args: cachedRequest
7152
+ }, {
7153
+ results: cachedResults
7154
+ });
7155
+ }
7156
+ // Algoliasearch API Client < v4
7157
+ // Prior to client v4 we didn't have a proper API to hydrate the client
7158
+ // cache from the outside. The following code populates the cache with
7159
+ // a single-index result. You can find more information about the
7160
+ // computation of the key inside the client (see link below).
7161
+ // https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240
7162
+ if (!('transporter' in client)) {
7163
+ var cacheKey = "/1/indexes/*/queries_body_".concat(JSON.stringify({
7164
+ requests: cachedRequest
7165
+ }));
7166
+ client.cache = _object_spread_props(_object_spread({}, client.cache), _define_property({}, cacheKey, JSON.stringify({
7167
+ results: Object.keys(results).map(function(key) {
7168
+ return getServerResults(results[key]);
7169
+ })
7170
+ })));
7171
+ }
7172
+ }
7173
+ function deserializeQueryParameters(parameters) {
7174
+ return parameters.split('&').reduce(function(acc, parameter) {
7175
+ var _parameter_split = _sliced_to_array(parameter.split('='), 2), key = _parameter_split[0], value = _parameter_split[1];
7176
+ acc[key] = value ? decodeURIComponent(value) : '';
7177
+ return acc;
7178
+ }, {});
7179
+ }
7180
+ // This function is copied from the algoliasearch v4 API Client. If modified,
7181
+ // consider updating it also in `serializeQueryParameters` from `@algolia/transporter`.
7182
+ function serializeQueryParameters(parameters) {
7183
+ var isObjectOrArray = function isObjectOrArray(value) {
7184
+ return Object.prototype.toString.call(value) === '[object Object]' || Object.prototype.toString.call(value) === '[object Array]';
7185
+ };
7186
+ var encode = function encode(format) {
7187
+ for(var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
7188
+ args[_key - 1] = arguments[_key];
7189
+ }
7190
+ var i = 0;
7191
+ return format.replace(/%s/g, function() {
7192
+ return encodeURIComponent(args[i++]);
7193
+ });
7194
+ };
7195
+ return Object.keys(parameters).map(function(key) {
7196
+ return encode('%s=%s', key, isObjectOrArray(parameters[key]) ? JSON.stringify(parameters[key]) : parameters[key]);
7197
+ }).join('&');
7198
+ }
7199
+
7200
+ function isPrimitive(obj) {
7201
+ return obj !== Object(obj);
7202
+ }
7203
+ function isEqual(first, second) {
7204
+ if (first === second) {
7205
+ return true;
7206
+ }
7207
+ if (isPrimitive(first) || isPrimitive(second) || typeof first === 'function' || typeof second === 'function') {
7208
+ return first === second;
7209
+ }
7210
+ if (Object.keys(first).length !== Object.keys(second).length) {
7211
+ return false;
7212
+ }
7213
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
7214
+ try {
7215
+ // @TODO avoid for..of because of the large polyfill
7216
+ // eslint-disable-next-line instantsearch/no-for-of
7217
+ for(var _iterator = Object.keys(first)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
7218
+ var key = _step.value;
7219
+ if (!(key in second)) {
7220
+ return false;
7221
+ }
7222
+ if (!isEqual(first[key], second[key])) {
7223
+ return false;
7224
+ }
7225
+ }
7226
+ } catch (err) {
7227
+ _didIteratorError = true;
7228
+ _iteratorError = err;
7229
+ } finally{
7230
+ try {
7231
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
7232
+ _iterator.return();
7233
+ }
7234
+ } finally{
7235
+ if (_didIteratorError) {
7236
+ throw _iteratorError;
7237
+ }
7238
+ }
7239
+ }
7240
+ return true;
7241
+ }
7242
+
7243
+ // This is the `Number.isFinite()` polyfill recommended by MDN.
7244
+ // We do not provide any tests for this function.
7245
+ // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill
7246
+ // @MAJOR Replace with the native `Number.isFinite` method
7247
+ function isFiniteNumber(value) {
7248
+ return typeof value === 'number' && isFinite(value);
7249
+ }
7250
+
7251
+ /**
7252
+ * Recurse over all child indices
7253
+ */ function walkIndex(indexWidget, callback) {
7254
+ callback(indexWidget);
7255
+ indexWidget.getWidgets().forEach(function(widget) {
7256
+ if (isIndexWidget(widget)) {
7257
+ walkIndex(widget, callback);
7258
+ }
7259
+ });
7260
+ }
7261
+
7262
+ /**
7263
+ * Returns true if the widget requires a second SSR pass to discover and
7264
+ * mount child widgets (e.g. DynamicWidgets, Feeds).
7265
+ */ function isTwoPassWidget(widget) {
7266
+ return widget.$$type === 'ais.dynamicWidgets' || widget.$$type === 'ais.feeds';
7267
+ }
7268
+
7269
+ function range(param) {
7270
+ var _param_start = param.start, start = _param_start === void 0 ? 0 : _param_start, end = param.end, _param_step = param.step, step = _param_step === void 0 ? 1 : _param_step;
7271
+ // We can't divide by 0 so we re-assign the step to 1 if it happens.
7272
+ var limitStep = step === 0 ? 1 : step;
7273
+ // In some cases the array to create has a decimal length.
7274
+ // We therefore need to round the value.
7275
+ // Example:
7276
+ // { start: 1, end: 5000, step: 500 }
7277
+ // => Array length = (5000 - 1) / 500 = 9.998
7278
+ var arrayLength = Math.round((end - start) / limitStep);
7279
+ return _to_consumable_array(Array(arrayLength)).map(function(_, current) {
7280
+ return start + current * limitStep;
7281
+ });
7282
+ }
7283
+
7284
+ function createInitArgs(instantSearchInstance, parent, uiState) {
7285
+ var helper = parent.getHelper();
7286
+ return {
7287
+ uiState: uiState,
7288
+ helper: helper,
7289
+ parent: parent,
7290
+ instantSearchInstance: instantSearchInstance,
7291
+ state: helper.state,
7292
+ renderState: instantSearchInstance.renderState,
7293
+ templatesConfig: instantSearchInstance.templatesConfig,
7294
+ createURL: parent.createURL,
7295
+ scopedResults: [],
7296
+ searchMetadata: {
7297
+ isSearchStalled: instantSearchInstance.status === 'stalled'
7298
+ },
7299
+ status: instantSearchInstance.status,
7300
+ error: instantSearchInstance.error
7301
+ };
7302
+ }
7303
+ function createRenderArgs(instantSearchInstance, parent, widget) {
7304
+ var results = parent.getResultsForWidget(widget);
7305
+ var helper = parent.getHelper();
7306
+ return {
7307
+ helper: helper,
7308
+ parent: parent,
7309
+ instantSearchInstance: instantSearchInstance,
7310
+ results: results,
7311
+ scopedResults: parent.getScopedResults(),
7312
+ state: results && '_state' in results ? results._state : helper.state,
7313
+ renderState: instantSearchInstance.renderState,
7314
+ templatesConfig: instantSearchInstance.templatesConfig,
7315
+ createURL: parent.createURL,
7316
+ searchMetadata: {
7317
+ isSearchStalled: instantSearchInstance.status === 'stalled'
7318
+ },
7319
+ status: instantSearchInstance.status,
7320
+ error: instantSearchInstance.error
7321
+ };
7322
+ }
7323
+ function storeRenderState(param) {
7324
+ var renderState = param.renderState, instantSearchInstance = param.instantSearchInstance, parent = param.parent;
7325
+ var parentIndexName = parent ? parent.getIndexId() : instantSearchInstance.mainIndex.getIndexId();
7326
+ instantSearchInstance.renderState = _object_spread_props(_object_spread({}, instantSearchInstance.renderState), _define_property({}, parentIndexName, _object_spread({}, instantSearchInstance.renderState[parentIndexName], renderState)));
7327
+ }
7328
+
7329
+ function resolveSearchParameters(current) {
7330
+ var parent = current.getParent();
7331
+ var states = [
7332
+ current.getHelper().state
7333
+ ];
7334
+ while(parent !== null){
7335
+ states = [
7336
+ parent.getHelper().state
7337
+ ].concat(states);
7338
+ parent = parent.getParent();
7339
+ }
7340
+ return states;
7341
+ }
7342
+
7343
+ function reverseHighlightedParts(parts) {
7344
+ if (!parts.some(function(part) {
7345
+ return part.isHighlighted;
7346
+ })) {
7347
+ return parts.map(function(part) {
7348
+ return _object_spread_props(_object_spread({}, part), {
7349
+ isHighlighted: false
7350
+ });
7351
+ });
7352
+ }
7353
+ return parts.map(function(part, i) {
7354
+ return _object_spread_props(_object_spread({}, part), {
7355
+ isHighlighted: !getHighlightFromSiblings(parts, i)
7356
+ });
7357
+ });
7358
+ }
7359
+
7360
+ // eslint-disable-next-line no-restricted-globals
7361
+ /**
7362
+ * Runs code on browser environments safely.
7363
+ */ function safelyRunOnBrowser(callback) {
7364
+ var fallback = (arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
7365
+ fallback: function fallback() {
7366
+ return undefined;
7367
+ }
7368
+ }).fallback;
7369
+ // eslint-disable-next-line no-restricted-globals
7370
+ if (typeof window === 'undefined') {
7371
+ return fallback();
7372
+ }
7373
+ // eslint-disable-next-line no-restricted-globals
7374
+ return callback({
7375
+ window: window
7376
+ });
7377
+ }
7378
+
7379
+ function toArray(value) {
7380
+ return Array.isArray(value) ? value : [
7381
+ value
7382
+ ];
7383
+ }
7384
+
7385
+ var useKey = 'use';
7386
+ // @TODO: Remove this file and import directly from React when available.
7387
+ var use = React__namespace[useKey];
7388
+
7389
+ /**
7390
+ * `useLayoutEffect` that doesn't show a warning when server-side rendering.
7391
+ *
7392
+ * It uses `useEffect` on the server (no-op), and `useLayoutEffect` on the browser.
7393
+ */ var useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
7394
+
7395
+ var InstantSearchRSCContext = React.createContext({
7396
+ countRef: {
7397
+ current: 0
7398
+ },
7399
+ waitForResultsRef: null,
7400
+ ignoreMultipleHooksWarning: false
7401
+ });
7402
+
7403
+ function useRSCContext() {
7404
+ return React.useContext(InstantSearchRSCContext);
7405
+ }
7406
+
7407
+ /* eslint-disable no-console, no-empty */ var warnCache = {
7408
+ current: {}
7409
+ };
7410
+ /**
7411
+ * Logs a warning if the condition is not met.
7412
+ * This is used to log issues in development environment only.
7413
+ */ function warn(condition, message) {
7414
+ if (condition) {
7415
+ return;
7416
+ }
7417
+ var sanitizedMessage = message.trim();
7418
+ var hasAlreadyPrinted = warnCache.current[sanitizedMessage];
7419
+ if (!hasAlreadyPrinted) {
7420
+ warnCache.current[sanitizedMessage] = true;
7421
+ var warning = "[InstantSearch] ".concat(sanitizedMessage);
7422
+ console.warn(warning);
7423
+ try {
7424
+ // Welcome to debugging InstantSearch.
7425
+ //
7426
+ // This error was thrown as a convenience so that you can find the source
7427
+ // of the warning that appears in the console by enabling "Pause on exceptions"
7428
+ // in your debugger.
7429
+ throw new Error(warning);
7430
+ } catch (error) {}
7431
+ }
7432
+ }
7433
+
7434
+ function useWidget(param) {
7435
+ var widget = param.widget, parentIndex = param.parentIndex, props = param.props, shouldSsr = param.shouldSsr, skipSuspense = param.skipSuspense;
7436
+ var _waitForResultsRef_current, _waitForResultsRef_current1;
7437
+ var _useRSCContext = useRSCContext(), waitForResultsRef = _useRSCContext.waitForResultsRef, countRef = _useRSCContext.countRef, ignoreMultipleHooksWarning = _useRSCContext.ignoreMultipleHooksWarning;
7438
+ var prevPropsRef = React.useRef(props);
7439
+ React.useEffect(function() {
7440
+ prevPropsRef.current = props;
7441
+ }, [
7442
+ props
7443
+ ]);
7444
+ var prevWidgetRef = React.useRef(widget);
7445
+ React.useEffect(function() {
7446
+ prevWidgetRef.current = widget;
7447
+ }, [
7448
+ widget
7449
+ ]);
7450
+ var cleanupTimerRef = React.useRef(null);
7451
+ var shouldAddWidgetEarly = shouldSsr && !parentIndex.getWidgets().includes(widget);
7452
+ var search = useInstantSearchContext();
7453
+ // This effect is responsible for adding, removing, and updating the widget.
7454
+ // We need to support scenarios where the widget is remounted quickly, like in
7455
+ // Strict Mode, so that we don't lose its state, and therefore that we don't
7456
+ // break routing.
7457
+ useIsomorphicLayoutEffect(function() {
7458
+ var previousWidget = prevWidgetRef.current;
7459
+ // Scenario 1: the widget is added for the first time.
7460
+ if (!cleanupTimerRef.current) {
7461
+ if (!shouldSsr) {
7462
+ parentIndex.addWidgets([
7463
+ widget
7464
+ ]);
7465
+ }
7466
+ } else {
7467
+ // We cancel the original effect cleanup because it may not be necessary if
7468
+ // props haven't changed. (We manually call it if it is below.)
7469
+ clearTimeout(cleanupTimerRef.current);
7470
+ // Warning: if an unstable function prop is provided, `dequal` is not able
7471
+ // to keep its reference and therefore will consider that props did change.
7472
+ // This could unsollicitely remove/add the widget, therefore forget its state,
7473
+ // and could be a source of confusion.
7474
+ // If users face this issue, we should advise them to provide stable function
7475
+ // references.
7476
+ var arePropsEqual = dequal(props, prevPropsRef.current);
7477
+ // If props did change, then we execute the cleanup function instantly
7478
+ // and then add the widget back. This lets us add the widget without
7479
+ // waiting for the scheduled cleanup function to finish (that we canceled
7480
+ // above).
7481
+ if (!arePropsEqual) {
7482
+ parentIndex.removeWidgets([
7483
+ previousWidget
7484
+ ]);
7485
+ parentIndex.addWidgets([
7486
+ widget
7487
+ ]);
7488
+ }
7489
+ }
7490
+ return function() {
7491
+ // We don't remove the widget right away, but rather schedule it so that
7492
+ // we're able to cancel it in the next effect.
7493
+ cleanupTimerRef.current = setTimeout(function() {
7494
+ search._schedule(function() {
7495
+ if (search._preventWidgetCleanup) return;
7496
+ parentIndex.removeWidgets([
7497
+ previousWidget
7498
+ ]);
7499
+ });
7500
+ });
7501
+ };
7502
+ }, [
7503
+ parentIndex,
7504
+ widget,
7505
+ shouldSsr,
7506
+ search,
7507
+ props
7508
+ ]);
7509
+ if (shouldAddWidgetEarly || (waitForResultsRef === null || waitForResultsRef === void 0 ? void 0 : (_waitForResultsRef_current = waitForResultsRef.current) === null || _waitForResultsRef_current === void 0 ? void 0 : _waitForResultsRef_current.status) === 'pending') {
7510
+ parentIndex.addWidgets([
7511
+ widget
7512
+ ]);
7513
+ }
7514
+ if ((waitForResultsRef === null || waitForResultsRef === void 0 ? void 0 : waitForResultsRef.current) && !skipSuspense) {
7515
+ var _search_helper;
7516
+ use(waitForResultsRef.current);
7517
+ // If we made a second request because of two-pass widgets, we need to
7518
+ // wait for the second result — except for the two-pass widgets themselves
7519
+ // which need to render their children after the first result.
7520
+ if (!isTwoPassWidget(widget) && ((_search_helper = search.helper) === null || _search_helper === void 0 ? void 0 : _search_helper.lastResults)) {
7521
+ use(waitForResultsRef.current);
7522
+ }
7523
+ }
7524
+ if ((waitForResultsRef === null || waitForResultsRef === void 0 ? void 0 : (_waitForResultsRef_current1 = waitForResultsRef.current) === null || _waitForResultsRef_current1 === void 0 ? void 0 : _waitForResultsRef_current1.status) === 'fulfilled') {
7525
+ countRef.current += 1;
7526
+ { warn(ignoreMultipleHooksWarning || countRef.current <= parentIndex.getWidgets().length, "We detected you may have a component with multiple InstantSearch hooks.\n\nWith Next.js, you need to set `skipSuspense` to `true` for all but the last hook in the component, otherwise, only the first hook will be rendered on the server.\n\nThis warning can be a false positive if you are using dynamic widgets or multi-index, in which case you can ignore it by setting `ignoreMultipleHooksWarning` to `true` in `<InstantSearchNext`.\n\nFor more information, see https://www.algolia.com/doc/guides/building-search-ui/going-further/server-side-rendering/react/#composing-hooks"); }
7527
+ }
7528
+ }
7529
+
7530
+ function useConnector(connector) {
7531
+ var _1 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : void 0, _2 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : void 0;
7532
+ var _ref = [
7533
+ _1,
7534
+ _2
7535
+ ], _ref1 = _to_array(_ref), tmp = _ref1[0], props = tmp === void 0 ? {} : tmp, _rest = _ref1.slice(1), _rest1 = _sliced_to_array(_rest, 1), tmp1 = _rest1[0], _ref2 = tmp1 === void 0 ? {} : tmp1, _ref_skipSuspense = _ref2.skipSuspense, skipSuspense = _ref_skipSuspense === void 0 ? false : _ref_skipSuspense, additionalWidgetProperties = _object_without_properties(_ref2, [
7536
+ "skipSuspense"
7537
+ ]);
7538
+ var serverContext = useInstantSearchServerContext();
7539
+ var ssrContext = useInstantSearchSSRContext();
7540
+ var search = useInstantSearchContext();
7541
+ var parentIndex = useIndexContext();
7542
+ var stableProps = useStableValue(props);
7543
+ var stableAdditionalWidgetProperties = useStableValue(additionalWidgetProperties);
7544
+ var shouldSetStateRef = React.useRef(true);
7545
+ var previousRenderStateRef = React.useRef(null);
7546
+ var previousStatusRef = React.useRef(search.status);
7547
+ var widget = React.useMemo(function() {
7548
+ var createWidget = connector(function(connectorState, isFirstRender) {
7549
+ // We skip the `init` widget render because:
7550
+ // - We rely on `getWidgetRenderState` to compute the initial state before
7551
+ // the InstantSearch.js lifecycle starts.
7552
+ // - It prevents UI flashes when updating the widget props.
7553
+ if (isFirstRender) {
7554
+ shouldSetStateRef.current = true;
7555
+ return;
7556
+ }
7557
+ // There are situations where InstantSearch.js may render widgets slightly
7558
+ // after they're removed by React, and thus try to update the React state
7559
+ // on unmounted components. React 16 and 17 consider them as memory leaks
7560
+ // and display a warning.
7561
+ // This happens in <DynamicWidgets> when `attributesToRender` contains a
7562
+ // value without an attribute previously mounted. React will unmount the
7563
+ // component controlled by that attribute, but InstantSearch.js will stay
7564
+ // unaware of this change until the render pass finishes, and therefore
7565
+ // notifies of a state change.
7566
+ // This ref lets us track this situation and ignore these state updates.
7567
+ if (shouldSetStateRef.current) {
7568
+ var instantSearchInstance = connectorState.instantSearchInstance; connectorState.widgetParams; var renderState = _object_without_properties(connectorState, [
7569
+ "instantSearchInstance",
7570
+ "widgetParams"
7571
+ ]);
7572
+ // We only update the state when a widget render state param changes,
7573
+ // except for functions. We ignore function reference changes to avoid
7574
+ // infinite loops. It's safe to omit them because they get updated
7575
+ // every time another render param changes.
7576
+ if (!dequal(renderState, previousRenderStateRef.current, function(a, b) {
7577
+ return (a === null || a === void 0 ? void 0 : a.constructor) === Function && (b === null || b === void 0 ? void 0 : b.constructor) === Function;
7578
+ }) || instantSearchInstance.status !== previousStatusRef.current) {
7579
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
7580
+ setState(renderState);
7581
+ previousRenderStateRef.current = renderState;
7582
+ previousStatusRef.current = instantSearchInstance.status;
7583
+ }
7584
+ }
7585
+ }, function() {
7586
+ // We'll ignore the next state update until we know for sure that
7587
+ // InstantSearch.js re-inits the component.
7588
+ shouldSetStateRef.current = false;
7589
+ });
7590
+ return _object_spread({}, createWidget(stableProps), stableAdditionalWidgetProperties);
7591
+ }, [
7592
+ connector,
7593
+ stableProps,
7594
+ stableAdditionalWidgetProperties
7595
+ ]);
6451
7596
  var _useState = _sliced_to_array(React.useState(function() {
6452
7597
  if (widget.getWidgetRenderState) {
6453
7598
  var _widget_getWidgetSearchParameters;
@@ -6506,42 +7651,13 @@
6506
7651
  return null;
6507
7652
  }
6508
7653
 
6509
- function getWidgetAttribute$1(widget, initOptions) {
6510
- var _widget_getWidgetRenderState;
6511
- var renderState = (_widget_getWidgetRenderState = widget.getWidgetRenderState) === null || _widget_getWidgetRenderState === void 0 ? void 0 : _widget_getWidgetRenderState.call(widget, initOptions);
6512
- var attribute = null;
6513
- if (renderState && renderState.widgetParams) {
6514
- // casting as widgetParams is checked just before
6515
- var widgetParams = renderState.widgetParams;
6516
- if (widgetParams.attribute) {
6517
- attribute = widgetParams.attribute;
6518
- } else if (Array.isArray(widgetParams.attributes)) {
6519
- attribute = widgetParams.attributes[0];
6520
- }
6521
- }
6522
- if (typeof attribute !== 'string') {
6523
- throw new Error("Could not find the attribute of the widget:\n\n".concat(JSON.stringify(widget), "\n\nPlease check whether the widget's getWidgetRenderState returns widgetParams.attribute correctly."));
6524
- }
6525
- return attribute;
6526
- }
6527
-
6528
- function getObjectType(object) {
6529
- return Object.prototype.toString.call(object).slice(8, -1);
6530
- }
6531
-
6532
- function checkRendering(rendering, usage) {
6533
- if (rendering === undefined || typeof rendering !== 'function') {
6534
- throw new Error("The render function is not valid (received type ".concat(getObjectType(rendering), ").\n\n").concat(usage));
6535
- }
6536
- }
6537
-
6538
- var withUsage$s = createDocumentationMessageGenerator({
7654
+ var withUsage$t = createDocumentationMessageGenerator({
6539
7655
  name: 'dynamic-widgets',
6540
7656
  connector: true
6541
7657
  });
6542
7658
  var connectDynamicWidgets = function connectDynamicWidgets(renderFn) {
6543
7659
  var unmountFn = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop;
6544
- checkRendering(renderFn, withUsage$s());
7660
+ checkRendering(renderFn, withUsage$t());
6545
7661
  return function(widgetParams) {
6546
7662
  var widgets = widgetParams.widgets, _widgetParams_maxValuesPerFacet = widgetParams.maxValuesPerFacet, maxValuesPerFacet = _widgetParams_maxValuesPerFacet === void 0 ? 20 : _widgetParams_maxValuesPerFacet, _widgetParams_facets = widgetParams.facets, facets = _widgetParams_facets === void 0 ? [
6547
7663
  '*'
@@ -6551,10 +7667,10 @@
6551
7667
  if (!(widgets && Array.isArray(widgets) && widgets.every(function(widget) {
6552
7668
  return (typeof widget === "undefined" ? "undefined" : _type_of(widget)) === 'object';
6553
7669
  }))) {
6554
- throw new Error(withUsage$s('The `widgets` option expects an array of widgets.'));
7670
+ throw new Error(withUsage$t('The `widgets` option expects an array of widgets.'));
6555
7671
  }
6556
7672
  if (!Array.isArray(facets)) {
6557
- throw new Error(withUsage$s("The `facets` option only accepts an array of facets, you passed ".concat(JSON.stringify(facets))));
7673
+ throw new Error(withUsage$t("The `facets` option only accepts an array of facets, you passed ".concat(JSON.stringify(facets))));
6558
7674
  }
6559
7675
  var localWidgets = new Map();
6560
7676
  return {
@@ -6656,7 +7772,7 @@
6656
7772
  results: results
6657
7773
  });
6658
7774
  if (!Array.isArray(attributesToRender)) {
6659
- throw new Error(withUsage$s('The `transformItems` option expects a function that returns an Array.'));
7775
+ throw new Error(withUsage$t('The `transformItems` option expects a function that returns an Array.'));
6660
7776
  }
6661
7777
  return {
6662
7778
  attributesToRender: attributesToRender,
@@ -6722,120 +7838,442 @@
6722
7838
  return undefined;
6723
7839
  }
6724
7840
 
6725
- function _array_without_holes(arr) {
6726
- if (Array.isArray(arr)) return _array_like_to_array(arr);
6727
- }
6728
-
6729
- function _non_iterable_spread() {
6730
- throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
6731
- }
6732
-
6733
- function _to_consumable_array(arr) {
6734
- return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
6735
- }
6736
-
6737
- var id = 0;
6738
- function addWidgetId(widget) {
6739
- if (widget.dependsOn !== 'recommend') {
6740
- return;
6741
- }
6742
- widget.$$id = id++;
6743
- }
6744
- function resetWidgetId() {
6745
- id = 0;
6746
- }
6747
-
6748
- function isIndexWidget(widget) {
6749
- return widget.$$type === 'ais.index';
6750
- }
6751
-
6752
- var nextMicroTask = Promise.resolve();
6753
- function defer(callback) {
6754
- var progress = null;
6755
- var cancelled = false;
6756
- var fn = function fn() {
6757
- for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
6758
- args[_key] = arguments[_key];
6759
- }
6760
- if (progress !== null) {
6761
- return;
6762
- }
6763
- progress = nextMicroTask.then(function() {
6764
- progress = null;
6765
- if (cancelled) {
6766
- cancelled = false;
6767
- return;
7841
+ function createFeedContainer(feedID, parentIndex, instantSearchInstance) {
7842
+ var localWidgets = [];
7843
+ var initialized = false;
7844
+ var container = {
7845
+ $$type: 'ais.feedContainer',
7846
+ $$widgetType: 'ais.feedContainer',
7847
+ _isolated: true,
7848
+ getIndexName: function getIndexName() {
7849
+ return parentIndex.getIndexName();
7850
+ },
7851
+ getIndexId: function getIndexId() {
7852
+ return feedID;
7853
+ },
7854
+ getHelper: function getHelper() {
7855
+ return parentIndex.getHelper();
7856
+ },
7857
+ getResults: function getResults() {
7858
+ var parentResults = parentIndex.getResults();
7859
+ if (!parentResults) return null;
7860
+ if (!parentResults.feeds) {
7861
+ // Single-feed backward compat: no feeds array means the parent result
7862
+ // itself is the only feed.
7863
+ if (feedID === '') {
7864
+ parentResults._state = parentIndex.getHelper().state;
7865
+ return parentResults;
7866
+ }
7867
+ return null;
6768
7868
  }
6769
- callback.apply(void 0, _to_consumable_array(args));
6770
- });
6771
- };
6772
- fn.wait = function() {
6773
- if (progress === null) {
6774
- throw new Error('The deferred function should be called before calling `wait()`');
6775
- }
6776
- return progress;
6777
- };
6778
- fn.cancel = function() {
6779
- if (progress === null) {
6780
- return;
7869
+ var feed = parentResults.feeds.find(function(f) {
7870
+ return f.feedID === feedID;
7871
+ });
7872
+ if (!feed) return null;
7873
+ // Optimistic state patching — same as index widget (index.ts:365-370)
7874
+ feed._state = parentIndex.getHelper().state;
7875
+ return feed;
7876
+ },
7877
+ getResultsForWidget: function getResultsForWidget() {
7878
+ return this.getResults();
7879
+ },
7880
+ getParent: function getParent() {
7881
+ return parentIndex;
7882
+ },
7883
+ getWidgets: function getWidgets() {
7884
+ return localWidgets;
7885
+ },
7886
+ getScopedResults: function getScopedResults() {
7887
+ return parentIndex.getScopedResults();
7888
+ },
7889
+ getPreviousState: function getPreviousState() {
7890
+ return null;
7891
+ },
7892
+ createURL: function createURL(nextState) {
7893
+ return parentIndex.createURL(nextState);
7894
+ },
7895
+ scheduleLocalSearch: function scheduleLocalSearch() {
7896
+ return parentIndex.scheduleLocalSearch();
7897
+ },
7898
+ addWidgets: function addWidgets(widgets) {
7899
+ var flatWidgets = widgets.reduce(function(acc, w) {
7900
+ return acc.concat(Array.isArray(w) ? w : [
7901
+ w
7902
+ ]);
7903
+ }, []);
7904
+ flatWidgets.forEach(function(widget) {
7905
+ widget.parent = container;
7906
+ });
7907
+ localWidgets = localWidgets.concat(flatWidgets);
7908
+ if (initialized) {
7909
+ flatWidgets.forEach(function(widget) {
7910
+ if (widget.getRenderState) {
7911
+ var renderState = widget.getRenderState(instantSearchInstance.renderState[container.getIndexId()] || {}, createInitArgs(instantSearchInstance, container, instantSearchInstance._initialUiState));
7912
+ storeRenderState({
7913
+ renderState: renderState,
7914
+ instantSearchInstance: instantSearchInstance,
7915
+ parent: container
7916
+ });
7917
+ }
7918
+ });
7919
+ flatWidgets.forEach(function(widget) {
7920
+ if (widget.init) {
7921
+ widget.init(createInitArgs(instantSearchInstance, container, instantSearchInstance._initialUiState));
7922
+ }
7923
+ });
7924
+ // Merge children's search params (e.g. disjunctiveFacets) into the
7925
+ // parent's helper state so they're included in the composition request.
7926
+ // uiState is {} because URL-derived refinements are already on the
7927
+ // parent state; children only need to declare structural params.
7928
+ var parentHelper = parentIndex.getHelper();
7929
+ var withChildParams = container.getWidgetSearchParameters(parentHelper.state, {
7930
+ uiState: {}
7931
+ });
7932
+ if (withChildParams !== parentHelper.state) {
7933
+ parentHelper.setState(withChildParams);
7934
+ }
7935
+ }
7936
+ return container;
7937
+ },
7938
+ removeWidgets: function removeWidgets(widgets) {
7939
+ var flatWidgets = widgets.reduce(function(acc, w) {
7940
+ return acc.concat(Array.isArray(w) ? w : [
7941
+ w
7942
+ ]);
7943
+ }, []);
7944
+ var helper = parentIndex.getHelper();
7945
+ if (!helper) {
7946
+ localWidgets = localWidgets.filter(function(w) {
7947
+ return !flatWidgets.includes(w);
7948
+ });
7949
+ return container;
7950
+ }
7951
+ // Chain through children's dispose so widgets clean up the
7952
+ // SearchParameters they declared (e.g. RefinementList removes its
7953
+ // disjunctiveFacet) instead of leaving them stale on the parent helper.
7954
+ var cleanedState = helper.state;
7955
+ flatWidgets.forEach(function(widget) {
7956
+ if (widget.dispose) {
7957
+ var next = widget.dispose({
7958
+ helper: helper,
7959
+ state: cleanedState,
7960
+ recommendState: helper.recommendState,
7961
+ parent: container
7962
+ });
7963
+ if (_instanceof(next, algoliasearchHelper.RecommendParameters)) ;
7964
+ else if (next) {
7965
+ cleanedState = next;
7966
+ }
7967
+ }
7968
+ });
7969
+ localWidgets = localWidgets.filter(function(w) {
7970
+ return !flatWidgets.includes(w);
7971
+ });
7972
+ if (cleanedState !== helper.state) {
7973
+ helper.setState(cleanedState);
7974
+ }
7975
+ return container;
7976
+ },
7977
+ init: function init() {
7978
+ initialized = true;
7979
+ localWidgets.forEach(function(widget) {
7980
+ if (widget.getRenderState) {
7981
+ var renderState = widget.getRenderState(instantSearchInstance.renderState[container.getIndexId()] || {}, createInitArgs(instantSearchInstance, container, instantSearchInstance._initialUiState));
7982
+ storeRenderState({
7983
+ renderState: renderState,
7984
+ instantSearchInstance: instantSearchInstance,
7985
+ parent: container
7986
+ });
7987
+ }
7988
+ });
7989
+ localWidgets.forEach(function(widget) {
7990
+ if (widget.init) {
7991
+ widget.init(createInitArgs(instantSearchInstance, container, instantSearchInstance._initialUiState));
7992
+ }
7993
+ });
7994
+ },
7995
+ render: function render() {
7996
+ localWidgets.forEach(function(widget) {
7997
+ if (widget.getRenderState) {
7998
+ var renderState = widget.getRenderState(instantSearchInstance.renderState[container.getIndexId()] || {}, createRenderArgs(instantSearchInstance, container, widget));
7999
+ storeRenderState({
8000
+ renderState: renderState,
8001
+ instantSearchInstance: instantSearchInstance,
8002
+ parent: container
8003
+ });
8004
+ }
8005
+ });
8006
+ localWidgets.forEach(function(widget) {
8007
+ if (widget.render) {
8008
+ widget.render(createRenderArgs(instantSearchInstance, container, widget));
8009
+ }
8010
+ });
8011
+ },
8012
+ dispose: function dispose(disposeOptions) {
8013
+ var _ref;
8014
+ var helper = parentIndex.getHelper();
8015
+ // Chain through children's dispose to return a cleaned state
8016
+ // (e.g. RefinementList.dispose removes its disjunctiveFacet declaration).
8017
+ // This mirrors how the index widget's removeWidgets chains dispose calls.
8018
+ var cleanedState = (_ref = disposeOptions === null || disposeOptions === void 0 ? void 0 : disposeOptions.state) !== null && _ref !== void 0 ? _ref : helper === null || helper === void 0 ? void 0 : helper.state;
8019
+ localWidgets.forEach(function(widget) {
8020
+ if (widget.dispose && helper) {
8021
+ var next = widget.dispose({
8022
+ helper: helper,
8023
+ state: cleanedState,
8024
+ recommendState: helper.recommendState,
8025
+ parent: container
8026
+ });
8027
+ if (_instanceof(next, algoliasearchHelper.RecommendParameters)) ;
8028
+ else if (next) {
8029
+ cleanedState = next;
8030
+ }
8031
+ }
8032
+ });
8033
+ localWidgets = [];
8034
+ initialized = false;
8035
+ return cleanedState;
8036
+ },
8037
+ getWidgetState: function getWidgetState(uiState) {
8038
+ return this.getWidgetUiState(uiState);
8039
+ },
8040
+ getWidgetUiState: function getWidgetUiState(uiState) {
8041
+ var helper = parentIndex.getHelper();
8042
+ var widgetUiStateOptions = {
8043
+ searchParameters: helper.state,
8044
+ helper: helper
8045
+ };
8046
+ return localWidgets.reduce(function(state, widget) {
8047
+ return widget.getWidgetUiState ? widget.getWidgetUiState(state, widgetUiStateOptions) : state;
8048
+ }, uiState);
8049
+ },
8050
+ getWidgetSearchParameters: function getWidgetSearchParameters(searchParameters, param) {
8051
+ var uiState = param.uiState;
8052
+ return localWidgets.reduce(function(params, widget) {
8053
+ return widget.getWidgetSearchParameters ? widget.getWidgetSearchParameters(params, {
8054
+ uiState: uiState
8055
+ }) : params;
8056
+ }, searchParameters);
8057
+ },
8058
+ refreshUiState: function refreshUiState() {
8059
+ // no-op: FeedContainer doesn't own UI state
8060
+ },
8061
+ setIndexUiState: function setIndexUiState() {
8062
+ // no-op: FeedContainer delegates to parent
6781
8063
  }
6782
- cancelled = true;
6783
8064
  };
6784
- return fn;
8065
+ return container;
6785
8066
  }
6786
8067
 
6787
- function resolveSearchParameters(current) {
6788
- var parent = current.getParent();
6789
- var states = [
6790
- current.getHelper().state
6791
- ];
6792
- while(parent !== null){
6793
- states = [
6794
- parent.getHelper().state
6795
- ].concat(states);
6796
- parent = parent.getParent();
8068
+ function toFeedSearchResults(state, raw) {
8069
+ return Object.assign(new algoliasearchHelper.SearchResults(state, [
8070
+ raw
8071
+ ]), {
8072
+ feedID: raw.feedID
8073
+ });
8074
+ }
8075
+ /**
8076
+ * Rebuild `lastResults.feeds` from `_initialResults.compositionFeedsResults`
8077
+ * because the index-widget hydration only restores `lastResults` (the merged
8078
+ * view), not the per-feed breakdown that the Feeds connector needs.
8079
+ */ function hydrateFeedsFromInitialResultsIfNeeded(instantSearchInstance, parent) {
8080
+ var _instantSearchInstance__initialResults, _parent_getHelper;
8081
+ var initial = (_instantSearchInstance__initialResults = instantSearchInstance._initialResults) === null || _instantSearchInstance__initialResults === void 0 ? void 0 : _instantSearchInstance__initialResults[parent.getIndexId()];
8082
+ var compositionFeedsResults = (initial === null || initial === void 0 ? void 0 : initial.compositionFeedsResults) || [];
8083
+ if (compositionFeedsResults.length === 0) {
8084
+ return;
6797
8085
  }
6798
- return states;
8086
+ var lastResults = (_parent_getHelper = parent.getHelper()) === null || _parent_getHelper === void 0 ? void 0 : _parent_getHelper.lastResults;
8087
+ if (!lastResults) {
8088
+ return;
8089
+ }
8090
+ if (lastResults.feeds && lastResults.feeds.length > 0) {
8091
+ return;
8092
+ }
8093
+ lastResults.feeds = compositionFeedsResults.map(function(raw) {
8094
+ return toFeedSearchResults(lastResults._state, raw);
8095
+ });
6799
8096
  }
6800
-
6801
- function createInitArgs(instantSearchInstance, parent, uiState) {
6802
- var helper = parent.getHelper();
6803
- return {
6804
- uiState: uiState,
6805
- helper: helper,
6806
- parent: parent,
6807
- instantSearchInstance: instantSearchInstance,
6808
- state: helper.state,
6809
- renderState: instantSearchInstance.renderState,
6810
- templatesConfig: instantSearchInstance.templatesConfig,
6811
- createURL: parent.createURL,
6812
- scopedResults: [],
6813
- searchMetadata: {
6814
- isSearchStalled: instantSearchInstance.status === 'stalled'
6815
- },
6816
- status: instantSearchInstance.status,
6817
- error: instantSearchInstance.error
8097
+ var withUsage$s = createDocumentationMessageGenerator({
8098
+ name: 'feeds',
8099
+ connector: true
8100
+ });
8101
+ var connectFeeds = function connectFeeds(renderFn) {
8102
+ var unmountFn = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop;
8103
+ checkRendering(renderFn, withUsage$s());
8104
+ return function(widgetParams) {
8105
+ var searchScope = widgetParams.searchScope, _widgetParams_transformFeeds = widgetParams.transformFeeds, transformFeeds = _widgetParams_transformFeeds === void 0 ? function(feeds) {
8106
+ return feeds;
8107
+ } : _widgetParams_transformFeeds;
8108
+ if (searchScope !== 'global') {
8109
+ throw new Error(withUsage$s('The `searchScope` option currently only supports "global".'));
8110
+ }
8111
+ return {
8112
+ $$type: 'ais.feeds',
8113
+ $$widgetType: 'ais.feeds',
8114
+ init: function init(initOptions) {
8115
+ var instantSearchInstance = initOptions.instantSearchInstance;
8116
+ if (!instantSearchInstance.compositionID) {
8117
+ throw new Error(withUsage$s('The `feeds` widget requires a composition-based InstantSearch instance (compositionID must be set).'));
8118
+ }
8119
+ hydrateFeedsFromInitialResultsIfNeeded(instantSearchInstance, initOptions.parent);
8120
+ renderFn(_object_spread_props(_object_spread({}, this.getWidgetRenderState(initOptions)), {
8121
+ instantSearchInstance: instantSearchInstance
8122
+ }), true);
8123
+ },
8124
+ render: function render(renderOptions) {
8125
+ var instantSearchInstance = renderOptions.instantSearchInstance;
8126
+ renderFn(_object_spread_props(_object_spread({}, this.getWidgetRenderState(renderOptions)), {
8127
+ instantSearchInstance: instantSearchInstance
8128
+ }), false);
8129
+ },
8130
+ dispose: function dispose() {
8131
+ unmountFn();
8132
+ },
8133
+ getWidgetSearchParameters: function getWidgetSearchParameters(state) {
8134
+ return state;
8135
+ },
8136
+ getRenderState: function getRenderState(renderState, renderOptions) {
8137
+ return _object_spread_props(_object_spread({}, renderState), {
8138
+ feeds: this.getWidgetRenderState(renderOptions)
8139
+ });
8140
+ },
8141
+ getWidgetRenderState: function getWidgetRenderState(param) {
8142
+ var results = param.results;
8143
+ if (!results) {
8144
+ return {
8145
+ feedIDs: [],
8146
+ widgetParams: widgetParams
8147
+ };
8148
+ }
8149
+ if (Array.isArray(results.feeds) && results.feeds.length > 0 && !results.feeds.every(function(feed) {
8150
+ return _instanceof(feed, algoliasearchHelper.SearchResults);
8151
+ })) {
8152
+ results.feeds = results.feeds.map(function(feed) {
8153
+ return _instanceof(feed, algoliasearchHelper.SearchResults) ? feed : toFeedSearchResults(results._state, feed);
8154
+ });
8155
+ }
8156
+ var feedIDs = results.feeds ? results.feeds.map(function(f) {
8157
+ return f.feedID;
8158
+ }) : [
8159
+ ''
8160
+ ];
8161
+ feedIDs = transformFeeds(feedIDs);
8162
+ if (!Array.isArray(feedIDs)) {
8163
+ throw new Error(withUsage$s('The `transformFeeds` option expects a function that returns an Array.'));
8164
+ }
8165
+ if (!feedIDs.every(function(feedID) {
8166
+ return typeof feedID === 'string';
8167
+ })) {
8168
+ throw new Error(withUsage$s('The `transformFeeds` option expects a function that returns an array of feed IDs (strings).'));
8169
+ }
8170
+ return {
8171
+ feedIDs: feedIDs,
8172
+ widgetParams: widgetParams
8173
+ };
8174
+ }
8175
+ };
6818
8176
  };
8177
+ };
8178
+
8179
+ function useFeeds(props, additionalWidgetProperties) {
8180
+ return useConnector(connectFeeds, props, additionalWidgetProperties);
6819
8181
  }
6820
- function createRenderArgs(instantSearchInstance, parent, widget) {
6821
- var results = parent.getResultsForWidget(widget);
6822
- var helper = parent.getHelper();
6823
- return {
6824
- helper: helper,
6825
- parent: parent,
6826
- instantSearchInstance: instantSearchInstance,
6827
- results: results,
6828
- scopedResults: parent.getScopedResults(),
6829
- state: results && '_state' in results ? results._state : helper.state,
6830
- renderState: instantSearchInstance.renderState,
6831
- templatesConfig: instantSearchInstance.templatesConfig,
6832
- createURL: parent.createURL,
6833
- searchMetadata: {
6834
- isSearchStalled: instantSearchInstance.status === 'stalled'
6835
- },
6836
- status: instantSearchInstance.status,
6837
- error: instantSearchInstance.error
6838
- };
8182
+
8183
+ function Feeds(_0) {
8184
+ var renderFeed = _0.renderFeed, props = _object_without_properties(_0, [
8185
+ "renderFeed"
8186
+ ]);
8187
+ var feedIDs = useFeeds(props, {
8188
+ $$widgetType: 'ais.feeds'
8189
+ }).feedIDs;
8190
+ var parentIndex = useIndexContext();
8191
+ var instantSearchInstance = useInstantSearchContext();
8192
+ var feedContainersRef = React.useRef(new Map());
8193
+ var removalTimerRef = React.useRef(null);
8194
+ var pendingRemovalsRef = React.useRef(new Map());
8195
+ // Create and register new FeedContainers synchronously so SSR and the first
8196
+ // client render can provide the matching feed index context to children.
8197
+ var toAdd = [];
8198
+ feedIDs.forEach(function(feedID) {
8199
+ if (!feedContainersRef.current.has(feedID)) {
8200
+ var pendingContainer = pendingRemovalsRef.current.get(feedID);
8201
+ if (pendingContainer) {
8202
+ pendingRemovalsRef.current.delete(feedID);
8203
+ feedContainersRef.current.set(feedID, pendingContainer);
8204
+ return;
8205
+ }
8206
+ var container = createFeedContainer(feedID, parentIndex, instantSearchInstance);
8207
+ feedContainersRef.current.set(feedID, container);
8208
+ toAdd.push(container);
8209
+ }
8210
+ });
8211
+ if (toAdd.length > 0) {
8212
+ parentIndex.addWidgets(toAdd);
8213
+ }
8214
+ // Remove containers that are no longer in feedIDs (deferred to match useWidget pattern).
8215
+ React.useEffect(function() {
8216
+ var containers = feedContainersRef.current;
8217
+ var activeSet = new Set(feedIDs);
8218
+ var toRemove = [];
8219
+ containers.forEach(function(container, id) {
8220
+ if (!activeSet.has(id)) {
8221
+ toRemove.push([
8222
+ id,
8223
+ container
8224
+ ]);
8225
+ containers.delete(id);
8226
+ }
8227
+ });
8228
+ if (toRemove.length > 0) {
8229
+ toRemove.forEach(function(param) {
8230
+ var _param = _sliced_to_array(param, 2), id = _param[0], container = _param[1];
8231
+ pendingRemovalsRef.current.set(id, container);
8232
+ });
8233
+ if (removalTimerRef.current !== null) {
8234
+ clearTimeout(removalTimerRef.current);
8235
+ }
8236
+ removalTimerRef.current = setTimeout(function() {
8237
+ var widgetsToRemove = Array.from(pendingRemovalsRef.current.values());
8238
+ pendingRemovalsRef.current.clear();
8239
+ removalTimerRef.current = null;
8240
+ if (widgetsToRemove.length > 0) {
8241
+ parentIndex.removeWidgets(widgetsToRemove);
8242
+ }
8243
+ }, 0);
8244
+ }
8245
+ }, [
8246
+ feedIDs,
8247
+ parentIndex
8248
+ ]);
8249
+ React.useEffect(function() {
8250
+ return function() {
8251
+ if (removalTimerRef.current !== null) {
8252
+ clearTimeout(removalTimerRef.current);
8253
+ removalTimerRef.current = null;
8254
+ }
8255
+ var containers = feedContainersRef.current;
8256
+ var toRemove = Array.from(new Set(_to_consumable_array(containers.values()).concat(_to_consumable_array(pendingRemovalsRef.current.values()))));
8257
+ pendingRemovalsRef.current.clear();
8258
+ containers.clear();
8259
+ if (toRemove.length > 0) {
8260
+ parentIndex.removeWidgets(toRemove);
8261
+ }
8262
+ };
8263
+ // eslint-disable-next-line react-hooks/exhaustive-deps
8264
+ }, []);
8265
+ return /*#__PURE__*/ React.createElement(React.Fragment, null, feedIDs.map(function(feedID) {
8266
+ var container = feedContainersRef.current.get(feedID);
8267
+ if (!container) {
8268
+ return null;
8269
+ }
8270
+ return /*#__PURE__*/ React.createElement(IndexContext.Provider, {
8271
+ key: feedID,
8272
+ value: container
8273
+ }, renderFeed({
8274
+ feedID: feedID
8275
+ }));
8276
+ }));
6839
8277
  }
6840
8278
 
6841
8279
  var withUsage$r = createDocumentationMessageGenerator({
@@ -7455,11 +8893,6 @@
7455
8893
  }
7456
8894
  };
7457
8895
  };
7458
- function storeRenderState(param) {
7459
- var renderState = param.renderState, instantSearchInstance = param.instantSearchInstance, parent = param.parent;
7460
- var parentIndexName = parent ? parent.getIndexId() : instantSearchInstance.mainIndex.getIndexId();
7461
- instantSearchInstance.renderState = _object_spread_props(_object_spread({}, instantSearchInstance.renderState), _define_property({}, parentIndexName, _object_spread({}, instantSearchInstance.renderState[parentIndexName], renderState)));
7462
- }
7463
8896
  /**
7464
8897
  * Walk up the parent chain to find the closest isolated index, or fall back to mainHelper
7465
8898
  */ function nearestIsolatedHelper(current, mainHelper) {
@@ -7598,124 +9031,57 @@
7598
9031
 
7599
9032
  return o;
7600
9033
  };
7601
-
7602
- return _set_prototype_of(o, p);
7603
- }
7604
-
7605
- function _inherits(subClass, superClass) {
7606
- if (typeof superClass !== "function" && superClass !== null) {
7607
- throw new TypeError("Super expression must either be null or a function");
7608
- }
7609
-
7610
- subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
7611
-
7612
- if (superClass) _set_prototype_of(subClass, superClass);
7613
- }
7614
-
7615
- var eventsExports = requireEvents();
7616
- var EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventsExports);
7617
-
7618
- /**
7619
- * Create UUID according to
7620
- * https://www.ietf.org/rfc/rfc4122.txt.
7621
- *
7622
- * @returns Generated UUID.
7623
- */ function createUUID() {
7624
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
7625
- /* eslint-disable no-bitwise */ var r = Math.random() * 16 | 0;
7626
- var v = c === 'x' ? r : r & 0x3 | 0x8;
7627
- /* eslint-enable */ return v.toString(16);
7628
- });
7629
- }
7630
-
7631
- var ANONYMOUS_TOKEN_COOKIE_KEY = '_ALGOLIA';
7632
- function getCookie(name) {
7633
- if ((typeof document === "undefined" ? "undefined" : _type_of(document)) !== 'object' || typeof document.cookie !== 'string') {
7634
- return undefined;
7635
- }
7636
- var prefix = "".concat(name, "=");
7637
- var cookies = document.cookie.split(';');
7638
- for(var i = 0; i < cookies.length; i++){
7639
- var cookie = cookies[i];
7640
- while(cookie.charAt(0) === ' '){
7641
- cookie = cookie.substring(1);
7642
- }
7643
- if (cookie.indexOf(prefix) === 0) {
7644
- return cookie.substring(prefix.length, cookie.length);
7645
- }
7646
- }
7647
- return undefined;
7648
- }
7649
- function getInsightsAnonymousUserTokenInternal() {
7650
- return getCookie(ANONYMOUS_TOKEN_COOKIE_KEY);
7651
- }
7652
-
7653
- // eslint-disable-next-line no-restricted-globals
7654
- /**
7655
- * Runs code on browser environments safely.
7656
- */ function safelyRunOnBrowser(callback) {
7657
- var fallback = (arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
7658
- fallback: function fallback() {
7659
- return undefined;
7660
- }
7661
- }).fallback;
7662
- // eslint-disable-next-line no-restricted-globals
7663
- if (typeof window === 'undefined') {
7664
- return fallback();
7665
- }
7666
- // eslint-disable-next-line no-restricted-globals
7667
- return callback({
7668
- window: window
7669
- });
7670
- }
7671
-
7672
- // typed as any, since it accepts the _real_ js clients, not the interface we otherwise expect
7673
- function getAppIdAndApiKey(searchClient) {
7674
- if (searchClient.appId && searchClient.apiKey) {
7675
- // searchClient v5
7676
- return [
7677
- searchClient.appId,
7678
- searchClient.apiKey
7679
- ];
7680
- } else if (searchClient.transporter) {
7681
- // searchClient v4 or v5
7682
- var transporter = searchClient.transporter;
7683
- var headers = transporter.headers || transporter.baseHeaders;
7684
- var queryParameters = transporter.queryParameters || transporter.baseQueryParameters;
7685
- var APP_ID = 'x-algolia-application-id';
7686
- var API_KEY = 'x-algolia-api-key';
7687
- var appId = headers[APP_ID] || queryParameters[APP_ID];
7688
- var apiKey = headers[API_KEY] || queryParameters[API_KEY];
7689
- return [
7690
- appId,
7691
- apiKey
7692
- ];
7693
- } else {
7694
- // searchClient v3
7695
- return [
7696
- searchClient.applicationID,
7697
- searchClient.apiKey
7698
- ];
9034
+
9035
+ return _set_prototype_of(o, p);
9036
+ }
9037
+
9038
+ function _inherits(subClass, superClass) {
9039
+ if (typeof superClass !== "function" && superClass !== null) {
9040
+ throw new TypeError("Super expression must either be null or a function");
7699
9041
  }
9042
+
9043
+ subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
9044
+
9045
+ if (superClass) _set_prototype_of(subClass, superClass);
7700
9046
  }
7701
9047
 
7702
- // We aren't using the native `Array.prototype.find` because the refactor away from Lodash is not
7703
- // published as a major version.
7704
- // Relying on the `find` polyfill on user-land, which before was only required for niche use-cases,
7705
- // was decided as too risky.
7706
- // @MAJOR Replace with the native `Array.prototype.find` method
7707
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
7708
- function find(items, predicate) {
7709
- var value;
7710
- for(var i = 0; i < items.length; i++){
7711
- value = items[i];
7712
- // inlined for performance: if (Call(predicate, thisArg, [value, i, list])) {
7713
- if (predicate(value, i, items)) {
7714
- return value;
9048
+ var eventsExports = requireEvents();
9049
+ var EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventsExports);
9050
+
9051
+ /**
9052
+ * Create UUID according to
9053
+ * https://www.ietf.org/rfc/rfc4122.txt.
9054
+ *
9055
+ * @returns Generated UUID.
9056
+ */ function createUUID() {
9057
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
9058
+ /* eslint-disable no-bitwise */ var r = Math.random() * 16 | 0;
9059
+ var v = c === 'x' ? r : r & 0x3 | 0x8;
9060
+ /* eslint-enable */ return v.toString(16);
9061
+ });
9062
+ }
9063
+
9064
+ var ANONYMOUS_TOKEN_COOKIE_KEY = '_ALGOLIA';
9065
+ function getCookie(name) {
9066
+ if ((typeof document === "undefined" ? "undefined" : _type_of(document)) !== 'object' || typeof document.cookie !== 'string') {
9067
+ return undefined;
9068
+ }
9069
+ var prefix = "".concat(name, "=");
9070
+ var cookies = document.cookie.split(';');
9071
+ for(var i = 0; i < cookies.length; i++){
9072
+ var cookie = cookies[i];
9073
+ while(cookie.charAt(0) === ' '){
9074
+ cookie = cookie.substring(1);
9075
+ }
9076
+ if (cookie.indexOf(prefix) === 0) {
9077
+ return cookie.substring(prefix.length, cookie.length);
7715
9078
  }
7716
9079
  }
7717
9080
  return undefined;
7718
9081
  }
9082
+ function getInsightsAnonymousUserTokenInternal() {
9083
+ return getCookie(ANONYMOUS_TOKEN_COOKIE_KEY);
9084
+ }
7719
9085
 
7720
9086
  var ALGOLIA_INSIGHTS_VERSION = '2.17.2';
7721
9087
  var ALGOLIA_INSIGHTS_SRC = "https://cdn.jsdelivr.net/npm/search-insights@".concat(ALGOLIA_INSIGHTS_VERSION, "/dist/search-insights.min.js");
@@ -8031,11 +9397,6 @@
8031
9397
  return typeof userToken === 'number' ? userToken.toString() : userToken;
8032
9398
  }
8033
9399
 
8034
- function getAlgoliaAgent(client) {
8035
- var clientTyped = client;
8036
- return clientTyped.transporter && clientTyped.transporter.userAgent ? clientTyped.transporter.userAgent.value : clientTyped._ua;
8037
- }
8038
-
8039
9400
  function extractWidgetPayload(widgets, instantSearchInstance, payload) {
8040
9401
  var initOptions = createInitArgs(instantSearchInstance, instantSearchInstance.mainIndex, instantSearchInstance._initialUiState);
8041
9402
  widgets.forEach(function(widget) {
@@ -8056,7 +9417,7 @@
8056
9417
  widgetType: widget.$$widgetType,
8057
9418
  params: params
8058
9419
  });
8059
- if (widget.$$type === 'ais.index') {
9420
+ if (isIndexWidget(widget)) {
8060
9421
  extractWidgetPayload(widget.getWidgets(), instantSearchInstance, payload);
8061
9422
  }
8062
9423
  });
@@ -9271,55 +10632,16 @@
9271
10632
  routeToState: function routeToState() {
9272
10633
  var routeState = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
9273
10634
  return Object.keys(routeState).reduce(function(state, indexId) {
9274
- return _object_spread_props(_object_spread({}, state), _define_property({}, indexId, getIndexStateWithoutConfigure(routeState[indexId])));
10635
+ var indexState = routeState[indexId];
10636
+ if ((typeof indexState === "undefined" ? "undefined" : _type_of(indexState)) !== 'object' || indexState === null) {
10637
+ return state;
10638
+ }
10639
+ return _object_spread_props(_object_spread({}, state), _define_property({}, indexId, getIndexStateWithoutConfigure(indexState)));
9275
10640
  }, {});
9276
10641
  }
9277
10642
  };
9278
10643
  }
9279
10644
 
9280
- function isPrimitive(obj) {
9281
- return obj !== Object(obj);
9282
- }
9283
- function isEqual(first, second) {
9284
- if (first === second) {
9285
- return true;
9286
- }
9287
- if (isPrimitive(first) || isPrimitive(second) || typeof first === 'function' || typeof second === 'function') {
9288
- return first === second;
9289
- }
9290
- if (Object.keys(first).length !== Object.keys(second).length) {
9291
- return false;
9292
- }
9293
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
9294
- try {
9295
- // @TODO avoid for..of because of the large polyfill
9296
- // eslint-disable-next-line instantsearch/no-for-of
9297
- for(var _iterator = Object.keys(first)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
9298
- var key = _step.value;
9299
- if (!(key in second)) {
9300
- return false;
9301
- }
9302
- if (!isEqual(first[key], second[key])) {
9303
- return false;
9304
- }
9305
- }
9306
- } catch (err) {
9307
- _didIteratorError = true;
9308
- _iteratorError = err;
9309
- } finally{
9310
- try {
9311
- if (!_iteratorNormalCompletion && _iterator.return != null) {
9312
- _iterator.return();
9313
- }
9314
- } finally{
9315
- if (_didIteratorError) {
9316
- throw _iteratorError;
9317
- }
9318
- }
9319
- }
9320
- return true;
9321
- }
9322
-
9323
10645
  var createRouterMiddleware = function createRouterMiddleware() {
9324
10646
  var props = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
9325
10647
  var _props_router = props.router, router = _props_router === void 0 ? historyRouter() : _props_router, _props_stateMapping = props.// this is needed because simpleStateMapping is StateMapping<TUiState, TUiState>.
@@ -9350,169 +10672,46 @@
9350
10672
  $$type: "ais.router({router:".concat(router.$$type || '__unknown__', ", stateMapping:").concat(stateMapping.$$type || '__unknown__', "})"),
9351
10673
  $$internal: $$internal,
9352
10674
  onStateChange: function onStateChange(param) {
9353
- var uiState = param.uiState;
9354
- var routeState = stateMapping.stateToRoute(uiState);
9355
- if (lastRouteState === undefined || !isEqual(lastRouteState, routeState)) {
9356
- router.write(routeState);
9357
- lastRouteState = routeState;
9358
- }
9359
- },
9360
- subscribe: function subscribe() {
9361
- instantSearchInstance._initialUiState = _object_spread({}, initialUiState, stateMapping.routeToState(router.read()));
9362
- router.onUpdate(function(route) {
9363
- if (instantSearchInstance.mainIndex.getWidgets().length > 0) {
9364
- instantSearchInstance.setUiState(stateMapping.routeToState(route));
9365
- }
9366
- });
9367
- },
9368
- started: function started() {
9369
- var _router_start;
9370
- (_router_start = router.start) === null || _router_start === void 0 ? void 0 : _router_start.call(router);
9371
- },
9372
- unsubscribe: function unsubscribe() {
9373
- router.dispose();
9374
- }
9375
- };
9376
- };
9377
- };
9378
-
9379
- function formatNumber(value, numberLocale) {
9380
- return value.toLocaleString(numberLocale);
9381
- }
9382
-
9383
- var NAMESPACE = 'ais';
9384
- var component = function component(componentName) {
9385
- return function() {
9386
- var _ref = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, descendantName = _ref.descendantName, modifierName = _ref.modifierName;
9387
- var descendent = descendantName ? "-".concat(descendantName) : '';
9388
- var modifier = modifierName ? "--".concat(modifierName) : '';
9389
- return "".concat(NAMESPACE, "-").concat(componentName).concat(descendent).concat(modifier);
9390
- };
9391
- };
9392
-
9393
- function getPropertyByPath(object, path) {
9394
- var parts = Array.isArray(path) ? path : path.split('.');
9395
- return parts.reduce(function(current, key) {
9396
- return current && current[key];
9397
- }, object);
9398
- }
9399
-
9400
- function _extends() {
9401
- _extends = Object.assign || function assign(target) {
9402
- for (var i = 1; i < arguments.length; i++) {
9403
- var source = arguments[i];
9404
- for (var key in source) if (Object.prototype.hasOwnProperty.call(source, key)) target[key] = source[key];
9405
- }
9406
-
9407
- return target;
9408
- };
9409
-
9410
- return _extends.apply(this, arguments);
9411
- }
9412
-
9413
- function _object_destructuring_empty(o) {
9414
- if (o === null || o === void 0) throw new TypeError("Cannot destructure " + o);
9415
-
9416
- return o;
9417
- }
9418
-
9419
- /**
9420
- * This implementation is taken from Lodash implementation.
9421
- * See: https://github.com/lodash/lodash/blob/4.17.11-npm/escape.js
9422
- */ // Used to map characters to HTML entities.
9423
- var htmlEntities = {
9424
- '&': '&amp;',
9425
- '<': '&lt;',
9426
- '>': '&gt;',
9427
- '"': '&quot;',
9428
- "'": '&#39;'
9429
- };
9430
- // Used to match HTML entities and HTML characters.
9431
- var regexUnescapedHtml = /[&<>"']/g;
9432
- var regexHasUnescapedHtml = RegExp(regexUnescapedHtml.source);
9433
- /**
9434
- * Converts the characters "&", "<", ">", '"', and "'" in `string` to their
9435
- * corresponding HTML entities.
9436
- */ function escape$1(value) {
9437
- return value && regexHasUnescapedHtml.test(value) ? value.replace(regexUnescapedHtml, function(character) {
9438
- return htmlEntities[character];
9439
- }) : value;
9440
- }
9441
- /**
9442
- * This implementation is taken from Lodash implementation.
9443
- * See: https://github.com/lodash/lodash/blob/4.17.11-npm/unescape.js
9444
- */ // Used to map HTML entities to characters.
9445
- var htmlCharacters = {
9446
- '&amp;': '&',
9447
- '&lt;': '<',
9448
- '&gt;': '>',
9449
- '&quot;': '"',
9450
- '&#39;': "'"
9451
- };
9452
- // Used to match HTML entities and HTML characters.
9453
- var regexEscapedHtml = /&(amp|quot|lt|gt|#39);/g;
9454
- var regexHasEscapedHtml = RegExp(regexEscapedHtml.source);
9455
- /**
9456
- * Converts the HTML entities "&", "<", ">", '"', and "'" in `string` to their
9457
- * characters.
9458
- */ function unescape$1(value) {
9459
- return value && regexHasEscapedHtml.test(value) ? value.replace(regexEscapedHtml, function(character) {
9460
- return htmlCharacters[character];
9461
- }) : value;
9462
- }
9463
-
9464
- var TAG_PLACEHOLDER = {
9465
- highlightPreTag: '__ais-highlight__',
9466
- highlightPostTag: '__/ais-highlight__'
9467
- };
9468
- var TAG_REPLACEMENT = {
9469
- highlightPreTag: '<mark>',
9470
- highlightPostTag: '</mark>'
9471
- };
9472
- // @MAJOR: in the future, this should only escape, not replace
9473
- function replaceTagsAndEscape(value) {
9474
- return escape$1(value).replace(new RegExp(TAG_PLACEHOLDER.highlightPreTag, 'g'), TAG_REPLACEMENT.highlightPreTag).replace(new RegExp(TAG_PLACEHOLDER.highlightPostTag, 'g'), TAG_REPLACEMENT.highlightPostTag);
9475
- }
9476
- function recursiveEscape(input) {
9477
- if (isPlainObject(input) && typeof input.value !== 'string') {
9478
- return Object.keys(input).reduce(function(acc, key) {
9479
- return _object_spread_props(_object_spread({}, acc), _define_property({}, key, recursiveEscape(input[key])));
9480
- }, {});
9481
- }
9482
- if (Array.isArray(input)) {
9483
- return input.map(recursiveEscape);
9484
- }
9485
- return _object_spread_props(_object_spread({}, input), {
9486
- value: replaceTagsAndEscape(input.value)
9487
- });
9488
- }
9489
- function escapeHits(hits) {
9490
- if (hits.__escaped === undefined) {
9491
- // We don't override the value on hit because it will mutate the raw results
9492
- // instead we make a shallow copy and we assign the escaped values on it.
9493
- hits = hits.map(function(_0) {
9494
- _object_destructuring_empty(_0);
9495
- var hit = _extends({}, _0);
9496
- if (hit._highlightResult) {
9497
- hit._highlightResult = recursiveEscape(hit._highlightResult);
9498
- }
9499
- if (hit._snippetResult) {
9500
- hit._snippetResult = recursiveEscape(hit._snippetResult);
10675
+ var uiState = param.uiState;
10676
+ var routeState = stateMapping.stateToRoute(uiState);
10677
+ if (lastRouteState === undefined || !isEqual(lastRouteState, routeState)) {
10678
+ router.write(routeState);
10679
+ lastRouteState = routeState;
10680
+ }
10681
+ },
10682
+ subscribe: function subscribe() {
10683
+ instantSearchInstance._initialUiState = _object_spread({}, initialUiState, stateMapping.routeToState(router.read()));
10684
+ router.onUpdate(function(route) {
10685
+ if (instantSearchInstance.mainIndex.getWidgets().length > 0) {
10686
+ instantSearchInstance.setUiState(stateMapping.routeToState(route));
10687
+ }
10688
+ });
10689
+ },
10690
+ started: function started() {
10691
+ var _router_start;
10692
+ (_router_start = router.start) === null || _router_start === void 0 ? void 0 : _router_start.call(router);
10693
+ },
10694
+ unsubscribe: function unsubscribe() {
10695
+ router.dispose();
9501
10696
  }
9502
- return hit;
9503
- });
9504
- hits.__escaped = true;
9505
- }
9506
- return hits;
9507
- }
9508
- function escapeFacets(facetHits) {
9509
- return facetHits.map(function(h) {
9510
- return _object_spread_props(_object_spread({}, h), {
9511
- highlighted: replaceTagsAndEscape(h.highlighted)
9512
- });
9513
- });
10697
+ };
10698
+ };
10699
+ };
10700
+
10701
+ function formatNumber(value, numberLocale) {
10702
+ return value.toLocaleString(numberLocale);
9514
10703
  }
9515
10704
 
10705
+ var NAMESPACE = 'ais';
10706
+ var component = function component(componentName) {
10707
+ return function() {
10708
+ var _ref = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, descendantName = _ref.descendantName, modifierName = _ref.modifierName;
10709
+ var descendent = descendantName ? "-".concat(descendantName) : '';
10710
+ var modifier = modifierName ? "--".concat(modifierName) : '';
10711
+ return "".concat(NAMESPACE, "-").concat(componentName).concat(descendent).concat(modifier);
10712
+ };
10713
+ };
10714
+
9516
10715
  var suit$3 = component('Highlight');
9517
10716
  /**
9518
10717
  * @deprecated use html tagged templates and the Highlight component instead
@@ -9527,69 +10726,6 @@
9527
10726
  return attributeValue.replace(new RegExp(TAG_REPLACEMENT.highlightPreTag, 'g'), "<".concat(highlightedTagName, ' class="').concat(className, '">')).replace(new RegExp(TAG_REPLACEMENT.highlightPostTag, 'g'), "</".concat(highlightedTagName, ">"));
9528
10727
  }
9529
10728
 
9530
- function concatHighlightedParts(parts) {
9531
- var highlightPreTag = TAG_REPLACEMENT.highlightPreTag, highlightPostTag = TAG_REPLACEMENT.highlightPostTag;
9532
- return parts.map(function(part) {
9533
- return part.isHighlighted ? highlightPreTag + part.value + highlightPostTag : part.value;
9534
- }).join('');
9535
- }
9536
-
9537
- var hasAlphanumeric = new RegExp(/\w/i);
9538
- function getHighlightFromSiblings(parts, i) {
9539
- var _parts_, _parts_1;
9540
- var current = parts[i];
9541
- var isNextHighlighted = ((_parts_ = parts[i + 1]) === null || _parts_ === void 0 ? void 0 : _parts_.isHighlighted) || true;
9542
- var isPreviousHighlighted = ((_parts_1 = parts[i - 1]) === null || _parts_1 === void 0 ? void 0 : _parts_1.isHighlighted) || true;
9543
- if (!hasAlphanumeric.test(unescape$1(current.value)) && isPreviousHighlighted === isNextHighlighted) {
9544
- return isPreviousHighlighted;
9545
- }
9546
- return current.isHighlighted;
9547
- }
9548
-
9549
- function reverseHighlightedParts(parts) {
9550
- if (!parts.some(function(part) {
9551
- return part.isHighlighted;
9552
- })) {
9553
- return parts.map(function(part) {
9554
- return _object_spread_props(_object_spread({}, part), {
9555
- isHighlighted: false
9556
- });
9557
- });
9558
- }
9559
- return parts.map(function(part, i) {
9560
- return _object_spread_props(_object_spread({}, part), {
9561
- isHighlighted: !getHighlightFromSiblings(parts, i)
9562
- });
9563
- });
9564
- }
9565
-
9566
- function getHighlightedParts(highlightedValue) {
9567
- // @MAJOR: this should use TAG_PLACEHOLDER
9568
- var highlightPostTag = TAG_REPLACEMENT.highlightPostTag, highlightPreTag = TAG_REPLACEMENT.highlightPreTag;
9569
- var splitByPreTag = highlightedValue.split(highlightPreTag);
9570
- var firstValue = splitByPreTag.shift();
9571
- var elements = !firstValue ? [] : [
9572
- {
9573
- value: firstValue,
9574
- isHighlighted: false
9575
- }
9576
- ];
9577
- splitByPreTag.forEach(function(split) {
9578
- var splitByPostTag = split.split(highlightPostTag);
9579
- elements.push({
9580
- value: splitByPostTag[0],
9581
- isHighlighted: true
9582
- });
9583
- if (splitByPostTag[1] !== '') {
9584
- elements.push({
9585
- value: splitByPostTag[1],
9586
- isHighlighted: false
9587
- });
9588
- }
9589
- });
9590
- return elements;
9591
- }
9592
-
9593
10729
  var suit$2 = component('ReverseHighlight');
9594
10730
  /**
9595
10731
  * @deprecated use html tagged templates and the ReverseHighlight component instead
@@ -9634,10 +10770,6 @@
9634
10770
  return reverseHighlightedValue.replace(new RegExp(TAG_REPLACEMENT.highlightPreTag, 'g'), "<".concat(highlightedTagName, ' class="').concat(className, '">')).replace(new RegExp(TAG_REPLACEMENT.highlightPostTag, 'g'), "</".concat(highlightedTagName, ">"));
9635
10771
  }
9636
10772
 
9637
- function serializePayload(payload) {
9638
- return btoa(encodeURIComponent(JSON.stringify(payload)));
9639
- }
9640
-
9641
10773
  /** @deprecated use bindEvent instead */ function writeDataAttributes(param) {
9642
10774
  var method = param.method, payload = param.payload;
9643
10775
  if ((typeof payload === "undefined" ? "undefined" : _type_of(payload)) !== 'object') {
@@ -9679,182 +10811,49 @@
9679
10811
  reverseHighlight: function reverseHighlight1(options, render) {
9680
10812
  try {
9681
10813
  var reverseHighlightOptions = JSON.parse(options);
9682
- return render(reverseHighlight(_object_spread_props(_object_spread({}, reverseHighlightOptions), {
9683
- hit: this
9684
- })));
9685
- } catch (error) {
9686
- throw new Error('\n The reverseHighlight helper expects a JSON object of the format:\n { "attribute": "name", "highlightedTagName": "mark" }');
9687
- }
9688
- },
9689
- snippet: function snippet1(options, render) {
9690
- try {
9691
- var snippetOptions = JSON.parse(options);
9692
- return render(snippet(_object_spread_props(_object_spread({}, snippetOptions), {
9693
- hit: this
9694
- })));
9695
- } catch (error) {
9696
- throw new Error('\nThe snippet helper expects a JSON object of the format:\n{ "attribute": "name", "highlightedTagName": "mark" }');
9697
- }
9698
- },
9699
- reverseSnippet: function reverseSnippet1(options, render) {
9700
- try {
9701
- var reverseSnippetOptions = JSON.parse(options);
9702
- return render(reverseSnippet(_object_spread_props(_object_spread({}, reverseSnippetOptions), {
9703
- hit: this
9704
- })));
9705
- } catch (error) {
9706
- throw new Error('\n The reverseSnippet helper expects a JSON object of the format:\n { "attribute": "name", "highlightedTagName": "mark" }');
9707
- }
9708
- },
9709
- insights: function insights1(options, render) {
9710
- try {
9711
- var _JSON_parse = JSON.parse(options), method = _JSON_parse.method, payload = _JSON_parse.payload;
9712
- return render(insights(method, _object_spread({
9713
- objectIDs: [
9714
- this.objectID
9715
- ]
9716
- }, payload)));
9717
- } catch (error) {
9718
- throw new Error('\nThe insights helper expects a JSON object of the format:\n{ "method": "method-name", "payload": { "eventName": "name of the event" } }');
9719
- }
9720
- }
9721
- };
9722
- }
9723
-
9724
- var version = '4.94.0';
9725
-
9726
- function hydrateSearchClient(client, results) {
9727
- if (!results) {
9728
- return;
9729
- }
9730
- // Disable cache hydration on:
9731
- // - Algoliasearch API Client < v4 with cache disabled
9732
- // - Third party clients (detected by the `addAlgoliaAgent` function missing)
9733
- if ((!('transporter' in client) || client._cacheHydrated) && (!client._useCache || typeof client.addAlgoliaAgent !== 'function')) {
9734
- return;
9735
- }
9736
- var cachedRequest = [
9737
- Object.keys(results).reduce(function(acc, key) {
9738
- var _results_key = results[key], state = _results_key.state, requestParams = _results_key.requestParams, serverResults = _results_key.results;
9739
- var mappedResults = serverResults && state ? serverResults.map(function(result, idx) {
9740
- return _object_spread({
9741
- indexName: state.index || result.index
9742
- }, (requestParams === null || requestParams === void 0 ? void 0 : requestParams[idx]) || result.params ? {
9743
- params: serializeQueryParameters((requestParams === null || requestParams === void 0 ? void 0 : requestParams[idx]) || deserializeQueryParameters(result.params))
9744
- } : {});
9745
- }) : [];
9746
- return acc.concat(mappedResults);
9747
- }, [])
9748
- ];
9749
- var cachedResults = Object.keys(results).reduce(function(acc, key) {
9750
- var res = results[key].results;
9751
- if (!res) {
9752
- return acc;
9753
- }
9754
- return acc.concat(res);
9755
- }, []);
9756
- // Algoliasearch API Client >= v4
9757
- // To hydrate the client we need to populate the cache with the data from
9758
- // the server (done in `hydrateSearchClientWithMultiIndexRequest` or
9759
- // `hydrateSearchClientWithSingleIndexRequest`). But since there is no way
9760
- // for us to compute the key the same way as `algoliasearch-client` we need
9761
- // to populate it on a custom key and override the `search` method to
9762
- // search on it first.
9763
- if ('transporter' in client && !client._cacheHydrated) {
9764
- client._cacheHydrated = true;
9765
- var baseMethod = client.search.bind(client);
9766
- client.search = function(requests) {
9767
- for(var _len = arguments.length, methodArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
9768
- methodArgs[_key - 1] = arguments[_key];
9769
- }
9770
- var requestsWithSerializedParams = Array.isArray(requests) ? requests.map(function(request) {
9771
- return _object_spread_props(_object_spread({}, request), {
9772
- params: serializeQueryParameters(request.params)
9773
- });
9774
- }) : serializeQueryParameters(requests.requestBody.params);
9775
- return client.transporter.responsesCache.get({
9776
- method: 'search',
9777
- args: [
9778
- requestsWithSerializedParams
9779
- ].concat(_to_consumable_array(methodArgs))
9780
- }, function() {
9781
- return baseMethod.apply(void 0, [
9782
- requests
9783
- ].concat(_to_consumable_array(methodArgs)));
9784
- });
9785
- };
9786
- client.transporter.responsesCache.set({
9787
- method: 'search',
9788
- args: cachedRequest
9789
- }, {
9790
- results: cachedResults
9791
- });
9792
- }
9793
- // Algoliasearch API Client < v4
9794
- // Prior to client v4 we didn't have a proper API to hydrate the client
9795
- // cache from the outside. The following code populates the cache with
9796
- // a single-index result. You can find more information about the
9797
- // computation of the key inside the client (see link below).
9798
- // https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240
9799
- if (!('transporter' in client)) {
9800
- var cacheKey = "/1/indexes/*/queries_body_".concat(JSON.stringify({
9801
- requests: cachedRequest
9802
- }));
9803
- client.cache = _object_spread_props(_object_spread({}, client.cache), _define_property({}, cacheKey, JSON.stringify({
9804
- results: Object.keys(results).map(function(key) {
9805
- return results[key].results;
9806
- })
9807
- })));
9808
- }
9809
- }
9810
- function deserializeQueryParameters(parameters) {
9811
- return parameters.split('&').reduce(function(acc, parameter) {
9812
- var _parameter_split = _sliced_to_array(parameter.split('='), 2), key = _parameter_split[0], value = _parameter_split[1];
9813
- acc[key] = value ? decodeURIComponent(value) : '';
9814
- return acc;
9815
- }, {});
9816
- }
9817
- // This function is copied from the algoliasearch v4 API Client. If modified,
9818
- // consider updating it also in `serializeQueryParameters` from `@algolia/transporter`.
9819
- function serializeQueryParameters(parameters) {
9820
- var isObjectOrArray = function isObjectOrArray(value) {
9821
- return Object.prototype.toString.call(value) === '[object Object]' || Object.prototype.toString.call(value) === '[object Array]';
9822
- };
9823
- var encode = function encode(format) {
9824
- for(var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
9825
- args[_key - 1] = arguments[_key];
10814
+ return render(reverseHighlight(_object_spread_props(_object_spread({}, reverseHighlightOptions), {
10815
+ hit: this
10816
+ })));
10817
+ } catch (error) {
10818
+ throw new Error('\n The reverseHighlight helper expects a JSON object of the format:\n { "attribute": "name", "highlightedTagName": "mark" }');
10819
+ }
10820
+ },
10821
+ snippet: function snippet1(options, render) {
10822
+ try {
10823
+ var snippetOptions = JSON.parse(options);
10824
+ return render(snippet(_object_spread_props(_object_spread({}, snippetOptions), {
10825
+ hit: this
10826
+ })));
10827
+ } catch (error) {
10828
+ throw new Error('\nThe snippet helper expects a JSON object of the format:\n{ "attribute": "name", "highlightedTagName": "mark" }');
10829
+ }
10830
+ },
10831
+ reverseSnippet: function reverseSnippet1(options, render) {
10832
+ try {
10833
+ var reverseSnippetOptions = JSON.parse(options);
10834
+ return render(reverseSnippet(_object_spread_props(_object_spread({}, reverseSnippetOptions), {
10835
+ hit: this
10836
+ })));
10837
+ } catch (error) {
10838
+ throw new Error('\n The reverseSnippet helper expects a JSON object of the format:\n { "attribute": "name", "highlightedTagName": "mark" }');
10839
+ }
10840
+ },
10841
+ insights: function insights1(options, render) {
10842
+ try {
10843
+ var _JSON_parse = JSON.parse(options), method = _JSON_parse.method, payload = _JSON_parse.payload;
10844
+ return render(insights(method, _object_spread({
10845
+ objectIDs: [
10846
+ this.objectID
10847
+ ]
10848
+ }, payload)));
10849
+ } catch (error) {
10850
+ throw new Error('\nThe insights helper expects a JSON object of the format:\n{ "method": "method-name", "payload": { "eventName": "name of the event" } }');
10851
+ }
9826
10852
  }
9827
- var i = 0;
9828
- return format.replace(/%s/g, function() {
9829
- return encodeURIComponent(args[i++]);
9830
- });
9831
10853
  };
9832
- return Object.keys(parameters).map(function(key) {
9833
- return encode('%s=%s', key, isObjectOrArray(parameters[key]) ? JSON.stringify(parameters[key]) : parameters[key]);
9834
- }).join('&');
9835
- }
9836
-
9837
- function hydrateRecommendCache(helper, initialResults) {
9838
- var recommendCache = Object.keys(initialResults).reduce(function(acc, indexName) {
9839
- var initialResult = initialResults[indexName];
9840
- if (initialResult.recommendResults) {
9841
- // @MAJOR: Use `Object.assign` instead of spread operator
9842
- return _object_spread({}, acc, initialResult.recommendResults.results);
9843
- }
9844
- return acc;
9845
- }, {});
9846
- helper._recommendCache = recommendCache;
9847
10854
  }
9848
10855
 
9849
- function setIndexHelperState(finalUiState, indexWidget) {
9850
- var nextIndexUiState = finalUiState[indexWidget.getIndexId()] || {};
9851
- indexWidget.getHelper().setState(indexWidget.getWidgetSearchParameters(indexWidget.getHelper().state, {
9852
- uiState: nextIndexUiState
9853
- }));
9854
- indexWidget.getWidgets().filter(isIndexWidget).forEach(function(widget) {
9855
- return setIndexHelperState(finalUiState, widget);
9856
- });
9857
- }
10856
+ var version = '4.96.0';
9858
10857
 
9859
10858
  var withUsage$q = createDocumentationMessageGenerator({
9860
10859
  name: 'instantsearch'
@@ -10891,161 +11890,6 @@
10891
11890
  }, children);
10892
11891
  }
10893
11892
 
10894
- function chunk(arr) {
10895
- var chunkSize = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 20;
10896
- var chunks = [];
10897
- for(var i = 0; i < Math.ceil(arr.length / chunkSize); i++){
10898
- chunks.push(arr.slice(i * chunkSize, (i + 1) * chunkSize));
10899
- }
10900
- return chunks;
10901
- }
10902
- function _buildEventPayloadsForHits(param) {
10903
- var helper = param.helper, widgetType = param.widgetType;
10904
- param.methodName;
10905
- var args = param.args, instantSearchInstance = param.instantSearchInstance;
10906
- // when there's only one argument, that means it's custom
10907
- if (args.length === 1 && _type_of(args[0]) === 'object') {
10908
- return [
10909
- args[0]
10910
- ];
10911
- }
10912
- var _args__split = _sliced_to_array(args[0].split(':'), 2), eventType = _args__split[0], eventModifier = _args__split[1];
10913
- var hits = args[1];
10914
- var eventName = args[2];
10915
- var additionalData = args[3] || {};
10916
- if (!hits) {
10917
- {
10918
- return [];
10919
- }
10920
- }
10921
- if ((eventType === 'click' || eventType === 'conversion') && !eventName) {
10922
- {
10923
- return [];
10924
- }
10925
- }
10926
- var hitsArray = Array.isArray(hits) ? hits : [
10927
- hits
10928
- ];
10929
- if (hitsArray.length === 0) {
10930
- return [];
10931
- }
10932
- var queryID = hitsArray[0].__queryID;
10933
- var hitsChunks = chunk(hitsArray);
10934
- var objectIDsByChunk = hitsChunks.map(function(batch) {
10935
- return batch.map(function(hit) {
10936
- return hit.objectID;
10937
- });
10938
- });
10939
- var positionsByChunk = hitsChunks.map(function(batch) {
10940
- return batch.map(function(hit) {
10941
- return hit.__position;
10942
- });
10943
- });
10944
- if (eventType === 'view') {
10945
- if (instantSearchInstance.status !== 'idle') {
10946
- return [];
10947
- }
10948
- return hitsChunks.map(function(batch, i) {
10949
- var _helper_lastResults;
10950
- return {
10951
- insightsMethod: 'viewedObjectIDs',
10952
- widgetType: widgetType,
10953
- eventType: eventType,
10954
- payload: _object_spread({
10955
- eventName: eventName || 'Hits Viewed',
10956
- index: ((_helper_lastResults = helper.lastResults) === null || _helper_lastResults === void 0 ? void 0 : _helper_lastResults.index) || helper.state.index,
10957
- objectIDs: objectIDsByChunk[i]
10958
- }, additionalData),
10959
- hits: batch,
10960
- eventModifier: eventModifier
10961
- };
10962
- });
10963
- } else if (eventType === 'click') {
10964
- return hitsChunks.map(function(batch, i) {
10965
- var _helper_lastResults;
10966
- return {
10967
- insightsMethod: 'clickedObjectIDsAfterSearch',
10968
- widgetType: widgetType,
10969
- eventType: eventType,
10970
- payload: _object_spread({
10971
- eventName: eventName || 'Hit Clicked',
10972
- index: ((_helper_lastResults = helper.lastResults) === null || _helper_lastResults === void 0 ? void 0 : _helper_lastResults.index) || helper.state.index,
10973
- queryID: queryID,
10974
- objectIDs: objectIDsByChunk[i],
10975
- positions: positionsByChunk[i]
10976
- }, additionalData),
10977
- hits: batch,
10978
- eventModifier: eventModifier
10979
- };
10980
- });
10981
- } else if (eventType === 'conversion') {
10982
- return hitsChunks.map(function(batch, i) {
10983
- var _helper_lastResults;
10984
- return {
10985
- insightsMethod: 'convertedObjectIDsAfterSearch',
10986
- widgetType: widgetType,
10987
- eventType: eventType,
10988
- payload: _object_spread({
10989
- eventName: eventName || 'Hit Converted',
10990
- index: ((_helper_lastResults = helper.lastResults) === null || _helper_lastResults === void 0 ? void 0 : _helper_lastResults.index) || helper.state.index,
10991
- queryID: queryID,
10992
- objectIDs: objectIDsByChunk[i]
10993
- }, additionalData),
10994
- hits: batch,
10995
- eventModifier: eventModifier
10996
- };
10997
- });
10998
- } else {
10999
- return [];
11000
- }
11001
- }
11002
- function createSendEventForHits(param) {
11003
- var instantSearchInstance = param.instantSearchInstance, helper = param.helper, widgetType = param.widgetType;
11004
- var sentEvents = {};
11005
- var timer = undefined;
11006
- var sendEventForHits = function sendEventForHits() {
11007
- for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
11008
- args[_key] = arguments[_key];
11009
- }
11010
- var payloads = _buildEventPayloadsForHits({
11011
- widgetType: widgetType,
11012
- helper: helper,
11013
- methodName: 'sendEvent',
11014
- args: args,
11015
- instantSearchInstance: instantSearchInstance
11016
- });
11017
- payloads.forEach(function(payload) {
11018
- if (payload.eventType === 'click' && payload.eventModifier === 'internal' && sentEvents[payload.eventType]) {
11019
- return;
11020
- }
11021
- sentEvents[payload.eventType] = true;
11022
- instantSearchInstance.sendEventToInsights(payload);
11023
- });
11024
- clearTimeout(timer);
11025
- timer = setTimeout(function() {
11026
- sentEvents = {};
11027
- }, 0);
11028
- };
11029
- return sendEventForHits;
11030
- }
11031
- function createBindEventForHits(param) {
11032
- var helper = param.helper, widgetType = param.widgetType, instantSearchInstance = param.instantSearchInstance;
11033
- var bindEventForHits = function bindEventForHits() {
11034
- for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
11035
- args[_key] = arguments[_key];
11036
- }
11037
- var payloads = _buildEventPayloadsForHits({
11038
- widgetType: widgetType,
11039
- helper: helper,
11040
- methodName: 'bindEvent',
11041
- args: args,
11042
- instantSearchInstance: instantSearchInstance
11043
- });
11044
- return payloads.length ? "data-insights-event=".concat(serializePayload(payloads)) : '';
11045
- };
11046
- return bindEventForHits;
11047
- }
11048
-
11049
11893
  var withUsage$p = createDocumentationMessageGenerator({
11050
11894
  name: 'autocomplete',
11051
11895
  connector: true
@@ -11092,7 +11936,7 @@
11092
11936
  }
11093
11937
  var sendEventMap = {};
11094
11938
  var indices = scopedResults.map(function(scopedResult) {
11095
- var _scopedResult_results, _scopedResult_results1;
11939
+ var _scopedResult_results;
11096
11940
  // We need to escape the hits because highlighting
11097
11941
  // exposes HTML tags to the end-user.
11098
11942
  if (scopedResult.results) {
@@ -11103,10 +11947,11 @@
11103
11947
  helper: scopedResult.helper,
11104
11948
  widgetType: _this.$$type
11105
11949
  });
11950
+ var hits = scopedResult.results ? addQueryID(addAbsolutePosition(scopedResult.results.hits, scopedResult.results.page, scopedResult.results.hitsPerPage), scopedResult.results.queryID) : [];
11106
11951
  return {
11107
11952
  indexId: scopedResult.indexId,
11108
11953
  indexName: ((_scopedResult_results = scopedResult.results) === null || _scopedResult_results === void 0 ? void 0 : _scopedResult_results.index) || '',
11109
- hits: ((_scopedResult_results1 = scopedResult.results) === null || _scopedResult_results1 === void 0 ? void 0 : _scopedResult_results1.hits) || [],
11954
+ hits: hits,
11110
11955
  results: scopedResult.results || {}
11111
11956
  };
11112
11957
  });
@@ -11509,12 +12354,81 @@
11509
12354
  return Promise.resolve(value);
11510
12355
  }
11511
12356
 
12357
+ var tryParseJson = function tryParseJson(value) {
12358
+ try {
12359
+ return JSON.parse(value);
12360
+ } catch (unused) {
12361
+ return undefined;
12362
+ }
12363
+ };
12364
+ var repairPartialJson = function repairPartialJson(value) {
12365
+ var repaired = value.trim();
12366
+ if (!repaired) {
12367
+ return repaired;
12368
+ }
12369
+ var inString = false;
12370
+ var isEscaped = false;
12371
+ var stack = [];
12372
+ for(var index = 0; index < repaired.length; index++){
12373
+ var char = repaired[index];
12374
+ if (inString) {
12375
+ if (isEscaped) {
12376
+ isEscaped = false;
12377
+ } else if (char === '\\') {
12378
+ isEscaped = true;
12379
+ } else if (char === '"') {
12380
+ inString = false;
12381
+ }
12382
+ continue;
12383
+ }
12384
+ if (char === '"') {
12385
+ inString = true;
12386
+ continue;
12387
+ }
12388
+ if (char === '{' || char === '[') {
12389
+ stack.push(char);
12390
+ continue;
12391
+ }
12392
+ if (char === '}' && stack[stack.length - 1] === '{') {
12393
+ stack.pop();
12394
+ continue;
12395
+ }
12396
+ if (char === ']' && stack[stack.length - 1] === '[') {
12397
+ stack.pop();
12398
+ }
12399
+ }
12400
+ if (inString && !isEscaped) {
12401
+ repaired += '"';
12402
+ }
12403
+ repaired = repaired.replace(RegExp(",\\s*$", "u"), '');
12404
+ if (stack.length > 0) {
12405
+ repaired += stack.reverse().map(function(opening) {
12406
+ return opening === '{' ? '}' : ']';
12407
+ }).join('');
12408
+ }
12409
+ return repaired.replace(RegExp(",\\s*([}\\]])", "gu"), '$1');
12410
+ };
12411
+ var parseToolInputDelta = function parseToolInputDelta(accumulatedRawInput, fallbackInput) {
12412
+ var normalized = accumulatedRawInput.trim();
12413
+ if (!normalized) {
12414
+ return fallbackInput;
12415
+ }
12416
+ var directParsed = tryParseJson(normalized);
12417
+ if (directParsed !== undefined) {
12418
+ return directParsed;
12419
+ }
12420
+ var repairedParsed = tryParseJson(repairPartialJson(normalized));
12421
+ if (repairedParsed !== undefined) {
12422
+ return repairedParsed;
12423
+ }
12424
+ return fallbackInput;
12425
+ };
11512
12426
  /**
11513
12427
  * Abstract base class for chat implementations.
11514
12428
  */ var AbstractChat = /*#__PURE__*/ function() {
11515
12429
  function AbstractChat(param) {
11516
12430
  var _this = this;
11517
- var _param_generateId = param.generateId, generateId$1 = _param_generateId === void 0 ? generateId : _param_generateId, _param_id = param.id, id = _param_id === void 0 ? generateId$1() : _param_id, transport = param.transport, state = param.state, onError = param.onError, onToolCall = param.onToolCall, onFinish = param.onFinish, onData = param.onData, sendAutomaticallyWhen = param.sendAutomaticallyWhen;
12431
+ var _param_generateId = param.generateId, generateId$1 = _param_generateId === void 0 ? generateId : _param_generateId, _param_id = param.id, id = _param_id === void 0 ? generateId$1() : _param_id, transport = param.transport, state = param.state, onError = param.onError, onToolCall = param.onToolCall, onFinish = param.onFinish, onData = param.onData, sendAutomaticallyWhen = param.sendAutomaticallyWhen, shouldRepairToolInput = param.shouldRepairToolInput;
11518
12432
  var _this1 = this;
11519
12433
  _class_call_check(this, AbstractChat);
11520
12434
  _define_property(this, "id", void 0);
@@ -11526,6 +12440,7 @@
11526
12440
  _define_property(this, "onFinish", void 0);
11527
12441
  _define_property(this, "onData", void 0);
11528
12442
  _define_property(this, "sendAutomaticallyWhen", void 0);
12443
+ _define_property(this, "shouldRepairToolInput", void 0);
11529
12444
  _define_property(this, "activeResponse", null);
11530
12445
  _define_property(this, "jobExecutor", new SerialJobExecutor());
11531
12446
  /**
@@ -11735,6 +12650,7 @@
11735
12650
  this.onFinish = onFinish;
11736
12651
  this.onData = onData;
11737
12652
  this.sendAutomaticallyWhen = sendAutomaticallyWhen;
12653
+ this.shouldRepairToolInput = shouldRepairToolInput;
11738
12654
  }
11739
12655
  _create_class(AbstractChat, [
11740
12656
  {
@@ -11837,6 +12753,8 @@
11837
12753
  // Track current text/reasoning part state
11838
12754
  var currentTextPartId;
11839
12755
  var currentReasoningPartId;
12756
+ var toolRawInputByCallId = {};
12757
+ var toolRawOutputByCallId = {};
11840
12758
  // Promise chain for handling tool calls that return promises
11841
12759
  var pendingToolCall = Promise.resolve();
11842
12760
  return new Promise(function(resolve) {
@@ -11975,11 +12893,14 @@
11975
12893
  case 'tool-input-start':
11976
12894
  {
11977
12895
  if (!currentMessage) break;
12896
+ var initialRawInput = typeof chunk.input === 'string' ? chunk.input : chunk.input !== undefined ? JSON.stringify(chunk.input) : '';
12897
+ toolRawInputByCallId[chunk.toolCallId] = initialRawInput;
11978
12898
  var toolPart = {
11979
12899
  type: "tool-".concat(chunk.toolName),
11980
12900
  toolCallId: chunk.toolCallId,
11981
12901
  state: 'input-streaming',
11982
12902
  input: chunk.input,
12903
+ rawInput: initialRawInput || undefined,
11983
12904
  providerExecuted: chunk.providerExecuted
11984
12905
  };
11985
12906
  currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
@@ -11992,11 +12913,47 @@
11992
12913
  }
11993
12914
  case 'tool-input-delta':
11994
12915
  {
12916
+ var _ref, _ref1, _chunk_toolName, _ref2;
12917
+ var _existingPart_type, _this_shouldRepairToolInput, _this1;
12918
+ if (!currentMessage) break;
12919
+ var toolIndex = currentMessage.parts.findIndex(function(p) {
12920
+ return 'toolCallId' in p && p.toolCallId === chunk.toolCallId;
12921
+ });
12922
+ var existingPart = toolIndex >= 0 ? currentMessage.parts[toolIndex] : null;
12923
+ var previousRawInput = (_ref = (_ref1 = existingPart === null || existingPart === void 0 ? void 0 : existingPart.rawInput) !== null && _ref1 !== void 0 ? _ref1 : toolRawInputByCallId[chunk.toolCallId]) !== null && _ref !== void 0 ? _ref : '';
12924
+ var nextRawInput = "".concat(previousRawInput).concat(chunk.inputTextDelta);
12925
+ toolRawInputByCallId[chunk.toolCallId] = nextRawInput;
12926
+ var toolName = (_chunk_toolName = chunk.toolName) !== null && _chunk_toolName !== void 0 ? _chunk_toolName : existingPart === null || existingPart === void 0 ? void 0 : (_existingPart_type = existingPart.type) === null || _existingPart_type === void 0 ? void 0 : _existingPart_type.replace('tool-', '');
12927
+ var shouldRepair = toolName ? (_ref2 = (_this_shouldRepairToolInput = (_this1 = _this).shouldRepairToolInput) === null || _this_shouldRepairToolInput === void 0 ? void 0 : _this_shouldRepairToolInput.call(_this1, toolName)) !== null && _ref2 !== void 0 ? _ref2 : true : true;
12928
+ var parsedInput = shouldRepair ? parseToolInputDelta(nextRawInput, existingPart === null || existingPart === void 0 ? void 0 : existingPart.input) : existingPart === null || existingPart === void 0 ? void 0 : existingPart.input;
12929
+ var nextToolPart = _object_spread_props(_object_spread({}, existingPart !== null && existingPart !== void 0 ? existingPart : {
12930
+ type: "tool-".concat(chunk.toolName),
12931
+ toolCallId: chunk.toolCallId
12932
+ }), {
12933
+ state: 'input-streaming',
12934
+ input: parsedInput,
12935
+ rawInput: nextRawInput
12936
+ });
12937
+ if (toolIndex >= 0) {
12938
+ var updatedParts4 = _to_consumable_array(currentMessage.parts);
12939
+ updatedParts4[toolIndex] = nextToolPart;
12940
+ currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
12941
+ parts: updatedParts4
12942
+ });
12943
+ } else {
12944
+ currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
12945
+ parts: _to_consumable_array(currentMessage.parts).concat([
12946
+ nextToolPart
12947
+ ])
12948
+ });
12949
+ }
12950
+ _this.state.replaceMessage(currentMessageIndex, currentMessage);
11995
12951
  break;
11996
12952
  }
11997
12953
  case 'tool-input-available':
11998
12954
  {
11999
12955
  if (!currentMessage) break;
12956
+ delete toolRawInputByCallId[chunk.toolCallId];
12000
12957
  // Find existing tool part or create new one
12001
12958
  var existingIndex = currentMessage.parts.findIndex(function(p) {
12002
12959
  return 'toolCallId' in p && p.toolCallId === chunk.toolCallId;
@@ -12010,10 +12967,10 @@
12010
12967
  providerExecuted: chunk.providerExecuted
12011
12968
  };
12012
12969
  if (existingIndex >= 0) {
12013
- var updatedParts4 = _to_consumable_array(currentMessage.parts);
12014
- updatedParts4[existingIndex] = toolPart1;
12970
+ var updatedParts5 = _to_consumable_array(currentMessage.parts);
12971
+ updatedParts5[existingIndex] = toolPart1;
12015
12972
  currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
12016
- parts: updatedParts4
12973
+ parts: updatedParts5
12017
12974
  });
12018
12975
  } else {
12019
12976
  currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
@@ -12030,7 +12987,8 @@
12030
12987
  toolCall: {
12031
12988
  toolName: chunk.toolName,
12032
12989
  toolCallId: chunk.toolCallId,
12033
- input: chunk.input
12990
+ input: chunk.input,
12991
+ dynamic: 'dynamic' in chunk ? chunk.dynamic : undefined
12034
12992
  }
12035
12993
  });
12036
12994
  if (result && typeof result.then === 'function') {
@@ -12041,23 +12999,69 @@
12041
12999
  }
12042
13000
  break;
12043
13001
  }
13002
+ case 'data-tool-output-delta':
13003
+ {
13004
+ var _ref3, _ref4;
13005
+ if (!currentMessage) break;
13006
+ var _chunk_data = chunk.data, toolCallId = _chunk_data.toolCallId, toolName1 = _chunk_data.toolName, delta = _chunk_data.delta;
13007
+ var toolIndex1 = currentMessage.parts.findIndex(function(p) {
13008
+ return 'toolCallId' in p && p.toolCallId === toolCallId;
13009
+ });
13010
+ var existingPart1 = toolIndex1 >= 0 ? currentMessage.parts[toolIndex1] : null;
13011
+ var previousRawOutput = (_ref3 = (_ref4 = existingPart1 === null || existingPart1 === void 0 ? void 0 : existingPart1.rawOutput) !== null && _ref4 !== void 0 ? _ref4 : toolRawOutputByCallId[toolCallId]) !== null && _ref3 !== void 0 ? _ref3 : '';
13012
+ var nextRawOutput = "".concat(previousRawOutput).concat(delta);
13013
+ toolRawOutputByCallId[toolCallId] = nextRawOutput;
13014
+ var parsedOutput = parseToolInputDelta(nextRawOutput, existingPart1 === null || existingPart1 === void 0 ? void 0 : existingPart1.output);
13015
+ var nextToolPart1 = _object_spread_props(_object_spread({}, existingPart1 !== null && existingPart1 !== void 0 ? existingPart1 : {
13016
+ type: "tool-".concat(toolName1),
13017
+ toolCallId: toolCallId,
13018
+ input: undefined
13019
+ }), {
13020
+ state: 'output-available',
13021
+ output: parsedOutput,
13022
+ rawOutput: nextRawOutput,
13023
+ preliminary: true
13024
+ });
13025
+ if (toolIndex1 >= 0) {
13026
+ var updatedParts6 = _to_consumable_array(currentMessage.parts);
13027
+ updatedParts6[toolIndex1] = nextToolPart1;
13028
+ currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13029
+ parts: updatedParts6
13030
+ });
13031
+ } else {
13032
+ currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13033
+ parts: _to_consumable_array(currentMessage.parts).concat([
13034
+ nextToolPart1
13035
+ ])
13036
+ });
13037
+ }
13038
+ _this.state.replaceMessage(currentMessageIndex, currentMessage);
13039
+ break;
13040
+ }
12044
13041
  case 'tool-output-available':
12045
13042
  {
12046
13043
  if (!currentMessage) break;
12047
- var toolIndex = currentMessage.parts.findIndex(function(p) {
13044
+ var toolIndex2 = currentMessage.parts.findIndex(function(p) {
12048
13045
  return 'toolCallId' in p && p.toolCallId === chunk.toolCallId;
12049
13046
  });
12050
- if (toolIndex >= 0) {
12051
- var updatedParts5 = _to_consumable_array(currentMessage.parts);
12052
- var existingPart = updatedParts5[toolIndex];
12053
- updatedParts5[toolIndex] = _object_spread_props(_object_spread({}, existingPart), {
13047
+ if (toolIndex2 >= 0) {
13048
+ delete toolRawInputByCallId[chunk.toolCallId];
13049
+ delete toolRawOutputByCallId[chunk.toolCallId];
13050
+ var updatedParts7 = _to_consumable_array(currentMessage.parts);
13051
+ var existingPart2 = updatedParts7[toolIndex2];
13052
+ // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
13053
+ existingPart2.rawOutput;
13054
+ var rest = _object_without_properties(existingPart2, [
13055
+ "rawOutput"
13056
+ ]);
13057
+ updatedParts7[toolIndex2] = _object_spread_props(_object_spread({}, rest), {
12054
13058
  state: 'output-available',
12055
13059
  output: chunk.output,
12056
13060
  callProviderMetadata: chunk.callProviderMetadata,
12057
13061
  preliminary: chunk.preliminary
12058
13062
  });
12059
13063
  currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
12060
- parts: updatedParts5
13064
+ parts: updatedParts7
12061
13065
  });
12062
13066
  _this.state.replaceMessage(currentMessageIndex, currentMessage);
12063
13067
  }
@@ -12066,21 +13070,30 @@
12066
13070
  case 'tool-error':
12067
13071
  {
12068
13072
  if (!currentMessage) break;
12069
- var toolIndex1 = currentMessage.parts.findIndex(function(p) {
13073
+ var toolIndex3 = currentMessage.parts.findIndex(function(p) {
12070
13074
  return 'toolCallId' in p && p.toolCallId === chunk.toolCallId;
12071
13075
  });
12072
- if (toolIndex1 >= 0) {
13076
+ if (toolIndex3 >= 0) {
12073
13077
  var _chunk_input;
12074
- var updatedParts6 = _to_consumable_array(currentMessage.parts);
12075
- var existingPart1 = updatedParts6[toolIndex1];
12076
- updatedParts6[toolIndex1] = _object_spread_props(_object_spread({}, existingPart1), {
13078
+ delete toolRawInputByCallId[chunk.toolCallId];
13079
+ delete toolRawOutputByCallId[chunk.toolCallId];
13080
+ var updatedParts8 = _to_consumable_array(currentMessage.parts);
13081
+ var existingPart3 = updatedParts8[toolIndex3];
13082
+ // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
13083
+ existingPart3.rawOutput; // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
13084
+ existingPart3.preliminary;
13085
+ var rest1 = _object_without_properties(existingPart3, [
13086
+ "rawOutput",
13087
+ "preliminary"
13088
+ ]);
13089
+ updatedParts8[toolIndex3] = _object_spread_props(_object_spread({}, rest1), {
12077
13090
  state: 'output-error',
12078
13091
  errorText: chunk.errorText,
12079
- input: (_chunk_input = chunk.input) !== null && _chunk_input !== void 0 ? _chunk_input : existingPart1.input,
13092
+ input: (_chunk_input = chunk.input) !== null && _chunk_input !== void 0 ? _chunk_input : existingPart3.input,
12080
13093
  callProviderMetadata: chunk.callProviderMetadata
12081
13094
  });
12082
13095
  currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
12083
- parts: updatedParts6
13096
+ parts: updatedParts8
12084
13097
  });
12085
13098
  _this.state.replaceMessage(currentMessageIndex, currentMessage);
12086
13099
  }
@@ -12561,250 +13574,74 @@
12561
13574
  resolveValue(this.body)
12562
13575
  ]).then(function(param) {
12563
13576
  var _param = _sliced_to_array(param, 3), resolvedCredentials = _param[0], resolvedHeaders = _param[1], resolvedBody = _param[2];
12564
- // Build default request options
12565
- var api = _this.api;
12566
- var headers = _object_spread({}, _instanceof(resolvedHeaders, Headers) ? Object.fromEntries(resolvedHeaders.entries()) : resolvedHeaders, _instanceof(requestHeaders, Headers) ? Object.fromEntries(requestHeaders.entries()) : requestHeaders);
12567
- var credentials = resolvedCredentials;
12568
- // Apply custom preparation if provided
12569
- var prepareRequestBody = _object_spread({}, resolvedBody, requestBody);
12570
- var preparePromise = _this.prepareReconnectToStreamRequest ? Promise.resolve(_this.prepareReconnectToStreamRequest({
12571
- id: chatId,
12572
- requestMetadata: undefined,
12573
- body: prepareRequestBody,
12574
- credentials: resolvedCredentials,
12575
- headers: resolvedHeaders,
12576
- api: _this.api
12577
- })) : Promise.resolve(null);
12578
- return preparePromise.then(function(prepared) {
12579
- if (prepared) {
12580
- if (prepared.api) api = prepared.api;
12581
- if (prepared.headers) {
12582
- headers = _instanceof(prepared.headers, Headers) ? Object.fromEntries(prepared.headers.entries()) : prepared.headers;
12583
- }
12584
- if (prepared.credentials) credentials = prepared.credentials;
12585
- }
12586
- // GET request for reconnection
12587
- return fetchFn("".concat(api, "?chatId=").concat(chatId), {
12588
- method: 'GET',
12589
- headers: headers,
12590
- credentials: credentials
12591
- }).then(function(response) {
12592
- if (!response.ok) {
12593
- // 404 means no stream to reconnect to, which is not an error
12594
- if (response.status === 404) {
12595
- return null;
12596
- }
12597
- throw new Error("HTTP error: ".concat(response.status, " ").concat(response.statusText));
12598
- }
12599
- if (!response.body) {
12600
- return null;
12601
- }
12602
- return _this.processResponseStream(response.body);
12603
- });
12604
- });
12605
- });
12606
- }
12607
- }
12608
- ]);
12609
- return HttpChatTransport;
12610
- }();
12611
- /**
12612
- * Default chat transport implementation using NDJSON streaming.
12613
- */ var DefaultChatTransport = /*#__PURE__*/ function(HttpChatTransport) {
12614
- _inherits(DefaultChatTransport, HttpChatTransport);
12615
- function DefaultChatTransport() {
12616
- var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
12617
- _class_call_check(this, DefaultChatTransport);
12618
- return _call_super(this, DefaultChatTransport, [
12619
- options
12620
- ]);
12621
- }
12622
- _create_class(DefaultChatTransport, [
12623
- {
12624
- key: "processResponseStream",
12625
- value: function processResponseStream(stream) {
12626
- return parseJsonEventStream(stream);
12627
- }
12628
- }
12629
- ]);
12630
- return DefaultChatTransport;
12631
- }(HttpChatTransport);
12632
-
12633
- function sendChatMessageFeedback(param) {
12634
- var agentId = param.agentId, vote = param.vote, messageId = param.messageId, appId = param.appId, apiKey = param.apiKey;
12635
- return fetch("https://".concat(appId, ".algolia.net/agent-studio/1/feedback"), {
12636
- method: 'POST',
12637
- body: JSON.stringify({
12638
- messageId: messageId,
12639
- agentId: agentId,
12640
- vote: vote
12641
- }),
12642
- headers: {
12643
- 'x-algolia-application-id': appId,
12644
- 'x-algolia-api-key': apiKey,
12645
- 'content-type': 'application/json'
12646
- }
12647
- }).then(function(response) {
12648
- if (response.status >= 300) {
12649
- return response.json().then(function(data) {
12650
- throw new Error("Feedback request failed with status ".concat(response.status, ": ").concat(data.message));
12651
- });
12652
- }
12653
- return response.json();
12654
- });
12655
- }
12656
-
12657
- /**
12658
- * Clears the refinements of a SearchParameters object based on rules provided.
12659
- * The included attributes list is applied before the excluded attributes list. If the list
12660
- * is not provided, this list of all the currently refined attributes is used as included attributes.
12661
- * @returns search parameters with refinements cleared
12662
- */ function clearRefinements(param) {
12663
- var helper = param.helper, _param_attributesToClear = param.attributesToClear, attributesToClear = _param_attributesToClear === void 0 ? [] : _param_attributesToClear;
12664
- var finalState = helper.state.setPage(0);
12665
- finalState = attributesToClear.reduce(function(state, attribute) {
12666
- if (finalState.isNumericRefined(attribute)) {
12667
- return state.removeNumericRefinement(attribute);
12668
- }
12669
- if (finalState.isHierarchicalFacet(attribute)) {
12670
- return state.removeHierarchicalFacetRefinement(attribute);
12671
- }
12672
- if (finalState.isDisjunctiveFacet(attribute)) {
12673
- return state.removeDisjunctiveFacetRefinement(attribute);
12674
- }
12675
- if (finalState.isConjunctiveFacet(attribute)) {
12676
- return state.removeFacetRefinement(attribute);
12677
- }
12678
- return state;
12679
- }, finalState);
12680
- if (attributesToClear.indexOf('query') !== -1) {
12681
- finalState = finalState.setQuery('');
12682
- }
12683
- return finalState;
12684
- }
12685
-
12686
- function unescapeFacetValue(value) {
12687
- if (typeof value === 'string') {
12688
- return value.replace(/^\\-/, '-');
12689
- }
12690
- return value;
12691
- }
12692
- function escapeFacetValue(value) {
12693
- if (typeof value === 'number' && value < 0 || typeof value === 'string') {
12694
- return String(value).replace(/^-/, '\\-');
12695
- }
12696
- return value;
12697
- }
12698
-
12699
- function getRefinement(state, type, attribute, name) {
12700
- var resultsFacets = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : [];
12701
- var res = {
12702
- type: type,
12703
- attribute: attribute,
12704
- name: name,
12705
- escapedValue: escapeFacetValue(name)
12706
- };
12707
- var facet = find(resultsFacets, function(resultsFacet) {
12708
- return resultsFacet.name === attribute;
12709
- });
12710
- var count;
12711
- if (type === 'hierarchical') {
12712
- var _loop = function _loop(i) {
12713
- facet = facet && facet.data && find(Object.keys(facet.data).map(getFacetRefinement(facet.data)), function(refinement) {
12714
- return refinement.name === nameParts[i];
12715
- });
12716
- };
12717
- var facetDeclaration = state.getHierarchicalFacetByName(attribute);
12718
- var nameParts = name.split(facetDeclaration.separator);
12719
- var getFacetRefinement = function getFacetRefinement(facetData) {
12720
- return function(refinementKey) {
12721
- return facetData[refinementKey];
12722
- };
12723
- };
12724
- for(var i = 0; facet !== undefined && i < nameParts.length; ++i)_loop(i);
12725
- count = facet && facet.count;
12726
- } else {
12727
- count = facet && facet.data && facet.data[res.name];
12728
- }
12729
- if (count !== undefined) {
12730
- res.count = count;
12731
- }
12732
- if (facet && facet.exhaustive !== undefined) {
12733
- res.exhaustive = facet.exhaustive;
12734
- }
12735
- return res;
12736
- }
12737
- function getRefinements(_results, state) {
12738
- var includesQuery = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
12739
- var results = _results || {};
12740
- var refinements = [];
12741
- var _state_facetsRefinements = state.facetsRefinements, facetsRefinements = _state_facetsRefinements === void 0 ? {} : _state_facetsRefinements, _state_facetsExcludes = state.facetsExcludes, facetsExcludes = _state_facetsExcludes === void 0 ? {} : _state_facetsExcludes, _state_disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements, disjunctiveFacetsRefinements = _state_disjunctiveFacetsRefinements === void 0 ? {} : _state_disjunctiveFacetsRefinements, _state_hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements, hierarchicalFacetsRefinements = _state_hierarchicalFacetsRefinements === void 0 ? {} : _state_hierarchicalFacetsRefinements, _state_numericRefinements = state.numericRefinements, numericRefinements = _state_numericRefinements === void 0 ? {} : _state_numericRefinements, _state_tagRefinements = state.tagRefinements, tagRefinements = _state_tagRefinements === void 0 ? [] : _state_tagRefinements;
12742
- Object.keys(facetsRefinements).forEach(function(attribute) {
12743
- var refinementNames = facetsRefinements[attribute];
12744
- refinementNames.forEach(function(refinementName) {
12745
- refinements.push(getRefinement(state, 'facet', attribute, refinementName, results.facets));
12746
- });
12747
- });
12748
- Object.keys(facetsExcludes).forEach(function(attribute) {
12749
- var refinementNames = facetsExcludes[attribute];
12750
- refinementNames.forEach(function(refinementName) {
12751
- refinements.push({
12752
- type: 'exclude',
12753
- attribute: attribute,
12754
- name: refinementName,
12755
- exclude: true
12756
- });
12757
- });
12758
- });
12759
- Object.keys(disjunctiveFacetsRefinements).forEach(function(attribute) {
12760
- var refinementNames = disjunctiveFacetsRefinements[attribute];
12761
- refinementNames.forEach(function(refinementName) {
12762
- refinements.push(getRefinement(state, 'disjunctive', attribute, // they can be escaped on negative numeric values with `escapeFacetValue`.
12763
- unescapeFacetValue(refinementName), results.disjunctiveFacets));
12764
- });
12765
- });
12766
- Object.keys(hierarchicalFacetsRefinements).forEach(function(attribute) {
12767
- var refinementNames = hierarchicalFacetsRefinements[attribute];
12768
- refinementNames.forEach(function(refinement) {
12769
- refinements.push(getRefinement(state, 'hierarchical', attribute, refinement, results.hierarchicalFacets));
12770
- });
12771
- });
12772
- Object.keys(numericRefinements).forEach(function(attribute) {
12773
- var operators = numericRefinements[attribute];
12774
- Object.keys(operators).forEach(function(operatorOriginal) {
12775
- var operator = operatorOriginal;
12776
- var valueOrValues = operators[operator];
12777
- var refinementNames = Array.isArray(valueOrValues) ? valueOrValues : [
12778
- valueOrValues
12779
- ];
12780
- refinementNames.forEach(function(refinementName) {
12781
- refinements.push({
12782
- type: 'numeric',
12783
- attribute: attribute,
12784
- name: "".concat(refinementName),
12785
- numericValue: refinementName,
12786
- operator: operator
13577
+ // Build default request options
13578
+ var api = _this.api;
13579
+ var headers = _object_spread({}, _instanceof(resolvedHeaders, Headers) ? Object.fromEntries(resolvedHeaders.entries()) : resolvedHeaders, _instanceof(requestHeaders, Headers) ? Object.fromEntries(requestHeaders.entries()) : requestHeaders);
13580
+ var credentials = resolvedCredentials;
13581
+ // Apply custom preparation if provided
13582
+ var prepareRequestBody = _object_spread({}, resolvedBody, requestBody);
13583
+ var preparePromise = _this.prepareReconnectToStreamRequest ? Promise.resolve(_this.prepareReconnectToStreamRequest({
13584
+ id: chatId,
13585
+ requestMetadata: undefined,
13586
+ body: prepareRequestBody,
13587
+ credentials: resolvedCredentials,
13588
+ headers: resolvedHeaders,
13589
+ api: _this.api
13590
+ })) : Promise.resolve(null);
13591
+ return preparePromise.then(function(prepared) {
13592
+ if (prepared) {
13593
+ if (prepared.api) api = prepared.api;
13594
+ if (prepared.headers) {
13595
+ headers = _instanceof(prepared.headers, Headers) ? Object.fromEntries(prepared.headers.entries()) : prepared.headers;
13596
+ }
13597
+ if (prepared.credentials) credentials = prepared.credentials;
13598
+ }
13599
+ // GET request for reconnection
13600
+ return fetchFn("".concat(api, "?chatId=").concat(chatId), {
13601
+ method: 'GET',
13602
+ headers: headers,
13603
+ credentials: credentials
13604
+ }).then(function(response) {
13605
+ if (!response.ok) {
13606
+ // 404 means no stream to reconnect to, which is not an error
13607
+ if (response.status === 404) {
13608
+ return null;
13609
+ }
13610
+ throw new Error("HTTP error: ".concat(response.status, " ").concat(response.statusText));
13611
+ }
13612
+ if (!response.body) {
13613
+ return null;
13614
+ }
13615
+ return _this.processResponseStream(response.body);
13616
+ });
13617
+ });
12787
13618
  });
12788
- });
12789
- });
12790
- });
12791
- tagRefinements.forEach(function(refinementName) {
12792
- refinements.push({
12793
- type: 'tag',
12794
- attribute: '_tags',
12795
- name: refinementName
12796
- });
12797
- });
12798
- if (includesQuery && state.query && state.query.trim()) {
12799
- refinements.push({
12800
- attribute: 'query',
12801
- type: 'query',
12802
- name: state.query,
12803
- query: state.query
12804
- });
13619
+ }
13620
+ }
13621
+ ]);
13622
+ return HttpChatTransport;
13623
+ }();
13624
+ /**
13625
+ * Default chat transport implementation using NDJSON streaming.
13626
+ */ var DefaultChatTransport = /*#__PURE__*/ function(HttpChatTransport) {
13627
+ _inherits(DefaultChatTransport, HttpChatTransport);
13628
+ function DefaultChatTransport() {
13629
+ var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
13630
+ _class_call_check(this, DefaultChatTransport);
13631
+ return _call_super(this, DefaultChatTransport, [
13632
+ options
13633
+ ]);
12805
13634
  }
12806
- return refinements;
12807
- }
13635
+ _create_class(DefaultChatTransport, [
13636
+ {
13637
+ key: "processResponseStream",
13638
+ value: function processResponseStream(stream) {
13639
+ return parseJsonEventStream(stream);
13640
+ }
13641
+ }
13642
+ ]);
13643
+ return DefaultChatTransport;
13644
+ }(HttpChatTransport);
12808
13645
 
12809
13646
  var withUsage$n = createDocumentationMessageGenerator({
12810
13647
  name: 'chat',
@@ -12993,6 +13830,14 @@
12993
13830
  return new Chat(_object_spread_props(_object_spread({}, options), {
12994
13831
  transport: transport,
12995
13832
  sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls,
13833
+ shouldRepairToolInput: function shouldRepairToolInput(toolName) {
13834
+ var tool = tools[toolName];
13835
+ if (!tool && toolName.startsWith("".concat(SearchIndexToolType, "_"))) {
13836
+ tool = tools[SearchIndexToolType];
13837
+ }
13838
+ if (!tool) return true;
13839
+ return Boolean(tool.streamInput);
13840
+ },
12996
13841
  onToolCall: function onToolCall(param) {
12997
13842
  var toolCall = param.toolCall;
12998
13843
  var tool = tools[toolCall.toolName];
@@ -13527,25 +14372,6 @@
13527
14372
  return useConnector(connectCurrentRefinements, props, additionalWidgetProperties);
13528
14373
  }
13529
14374
 
13530
- function addAbsolutePosition(hits, page, hitsPerPage) {
13531
- return hits.map(function(hit, idx) {
13532
- return _object_spread_props(_object_spread({}, hit), {
13533
- __position: hitsPerPage * page + idx + 1
13534
- });
13535
- });
13536
- }
13537
-
13538
- function addQueryID(hits, queryID) {
13539
- if (!queryID) {
13540
- return hits;
13541
- }
13542
- return hits.map(function(hit) {
13543
- return _object_spread_props(_object_spread({}, hit), {
13544
- __queryID: queryID
13545
- });
13546
- });
13547
- }
13548
-
13549
14375
  var withUsage$k = createDocumentationMessageGenerator({
13550
14376
  name: 'frequently-bought-together',
13551
14377
  connector: true
@@ -13635,67 +14461,6 @@
13635
14461
  return useConnector(connectFrequentlyBoughtTogether, props, additionalWidgetProperties);
13636
14462
  }
13637
14463
 
13638
- var latLngRegExp = /^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)$/;
13639
- function aroundLatLngToPosition(value) {
13640
- var pattern = value.match(latLngRegExp);
13641
- // Since the value provided is the one send with the request, the API should
13642
- // throw an error due to the wrong format. So throw an error should be safe.
13643
- if (!pattern) {
13644
- throw new Error('Invalid value for "aroundLatLng" parameter: "'.concat(value, '"'));
13645
- }
13646
- return {
13647
- lat: parseFloat(pattern[1]),
13648
- lng: parseFloat(pattern[2])
13649
- };
13650
- }
13651
- function insideBoundingBoxArrayToBoundingBox(value) {
13652
- var _value = _sliced_to_array(value, 1), tmp = _value[0], _ref = _sliced_to_array(tmp === void 0 ? [
13653
- undefined,
13654
- undefined,
13655
- undefined,
13656
- undefined
13657
- ] : tmp, 4), neLat = _ref[0], neLng = _ref[1], swLat = _ref[2], swLng = _ref[3];
13658
- // Since the value provided is the one send with the request, the API should
13659
- // throw an error due to the wrong format. So throw an error should be safe.
13660
- if (!neLat || !neLng || !swLat || !swLng) {
13661
- throw new Error('Invalid value for "insideBoundingBox" parameter: ['.concat(value, "]"));
13662
- }
13663
- return {
13664
- northEast: {
13665
- lat: neLat,
13666
- lng: neLng
13667
- },
13668
- southWest: {
13669
- lat: swLat,
13670
- lng: swLng
13671
- }
13672
- };
13673
- }
13674
- function insideBoundingBoxStringToBoundingBox(value) {
13675
- var _value_split_map = _sliced_to_array(value.split(',').map(parseFloat), 4), neLat = _value_split_map[0], neLng = _value_split_map[1], swLat = _value_split_map[2], swLng = _value_split_map[3];
13676
- // Since the value provided is the one send with the request, the API should
13677
- // throw an error due to the wrong format. So throw an error should be safe.
13678
- if (!neLat || !neLng || !swLat || !swLng) {
13679
- throw new Error('Invalid value for "insideBoundingBox" parameter: "'.concat(value, '"'));
13680
- }
13681
- return {
13682
- northEast: {
13683
- lat: neLat,
13684
- lng: neLng
13685
- },
13686
- southWest: {
13687
- lat: swLat,
13688
- lng: swLng
13689
- }
13690
- };
13691
- }
13692
- function insideBoundingBoxToBoundingBox(value) {
13693
- if (Array.isArray(value)) {
13694
- return insideBoundingBoxArrayToBoundingBox(value);
13695
- }
13696
- return insideBoundingBoxStringToBoundingBox(value);
13697
- }
13698
-
13699
14464
  var withUsage$j = createDocumentationMessageGenerator({
13700
14465
  name: 'geo-search',
13701
14466
  connector: true
@@ -13893,51 +14658,6 @@
13893
14658
  return useConnector(connectGeoSearch, props, additionalWidgetProperties);
13894
14659
  }
13895
14660
 
13896
- function isFacetRefined(helper, facet, value) {
13897
- if (helper.state.isHierarchicalFacet(facet)) {
13898
- return helper.state.isHierarchicalFacetRefined(facet, value);
13899
- } else if (helper.state.isConjunctiveFacet(facet)) {
13900
- return helper.state.isFacetRefined(facet, value);
13901
- } else {
13902
- return helper.state.isDisjunctiveFacetRefined(facet, value);
13903
- }
13904
- }
13905
-
13906
- function createSendEventForFacet(param) {
13907
- var instantSearchInstance = param.instantSearchInstance, helper = param.helper, attr = param.attribute, widgetType = param.widgetType;
13908
- var sendEventForFacet = function sendEventForFacet() {
13909
- for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
13910
- args[_key] = arguments[_key];
13911
- }
13912
- var _args = _sliced_to_array(args, 4), facetValue = _args[1], tmp = _args[2], eventName = tmp === void 0 ? 'Filter Applied' : tmp, tmp1 = _args[3], additionalData = tmp1 === void 0 ? {} : tmp1;
13913
- var _args__split = _sliced_to_array(args[0].split(':'), 2), eventType = _args__split[0], eventModifier = _args__split[1];
13914
- var attribute = typeof attr === 'string' ? attr : attr(facetValue);
13915
- if (args.length === 1 && _type_of(args[0]) === 'object') {
13916
- instantSearchInstance.sendEventToInsights(args[0]);
13917
- } else if (eventType === 'click' && args.length >= 2 && args.length <= 4) {
13918
- if (!isFacetRefined(helper, attribute, facetValue)) {
13919
- var _helper_lastResults;
13920
- // send event only when the facet is being checked "ON"
13921
- instantSearchInstance.sendEventToInsights({
13922
- insightsMethod: 'clickedFilters',
13923
- widgetType: widgetType,
13924
- eventType: eventType,
13925
- eventModifier: eventModifier,
13926
- payload: _object_spread({
13927
- eventName: eventName,
13928
- index: ((_helper_lastResults = helper.lastResults) === null || _helper_lastResults === void 0 ? void 0 : _helper_lastResults.index) || helper.state.index,
13929
- filters: [
13930
- "".concat(attribute, ":").concat(facetValue)
13931
- ]
13932
- }, additionalData),
13933
- attribute: attribute
13934
- });
13935
- }
13936
- } else ;
13937
- };
13938
- return sendEventForFacet;
13939
- }
13940
-
13941
14661
  var withUsage$i = createDocumentationMessageGenerator({
13942
14662
  name: 'hierarchical-menu',
13943
14663
  connector: true
@@ -14394,17 +15114,6 @@
14394
15114
  return useConnector(connectHitsPerPage, props, additionalWidgetProperties);
14395
15115
  }
14396
15116
 
14397
- /**
14398
- * Recurse over all child indices
14399
- */ function walkIndex(indexWidget, callback) {
14400
- callback(indexWidget);
14401
- indexWidget.getWidgets().forEach(function(widget) {
14402
- if (isIndexWidget(widget)) {
14403
- walkIndex(widget, callback);
14404
- }
14405
- });
14406
- }
14407
-
14408
15117
  var withUsage$f = createDocumentationMessageGenerator({
14409
15118
  name: 'infinite-hits',
14410
15119
  connector: true
@@ -14573,19 +15282,16 @@
14573
15282
  });
14574
15283
  /*
14575
15284
  With dynamic widgets, facets are not included in the state before their relevant widgets are mounted. Until then, we need to bail out of writing this incomplete state representation in cache.
14576
- */ var hasDynamicWidgets = false;
15285
+ */ var hasTwoPassWidgets = false;
14577
15286
  walkIndex(instantSearchInstance.mainIndex, function(indexWidget) {
14578
- if (!hasDynamicWidgets && indexWidget.getWidgets().some(function(param) {
14579
- var $$type = param.$$type;
14580
- return $$type === 'ais.dynamicWidgets';
14581
- })) {
14582
- hasDynamicWidgets = true;
15287
+ if (!hasTwoPassWidgets && indexWidget.getWidgets().some(isTwoPassWidget)) {
15288
+ hasTwoPassWidgets = true;
14583
15289
  }
14584
15290
  });
14585
15291
  var hasNoFacets = !((_state_disjunctiveFacets = state.disjunctiveFacets) === null || _state_disjunctiveFacets === void 0 ? void 0 : _state_disjunctiveFacets.length) && !(state.facets || []).filter(function(f) {
14586
15292
  return f !== '*';
14587
15293
  }).length && !((_state_hierarchicalFacets = state.hierarchicalFacets) === null || _state_hierarchicalFacets === void 0 ? void 0 : _state_hierarchicalFacets.length);
14588
- if (cachedHits[page] === undefined && !results.__isArtificial && instantSearchInstance.status === 'idle' && !(hasDynamicWidgets && hasNoFacets)) {
15294
+ if (cachedHits[page] === undefined && !results.__isArtificial && instantSearchInstance.status === 'idle' && !(hasTwoPassWidgets && hasNoFacets)) {
14589
15295
  cachedHits[page] = transformedHits;
14590
15296
  cache.write({
14591
15297
  state: normalizeState(state),
@@ -14846,14 +15552,6 @@
14846
15552
  return useConnector(connectMenu, props, additionalWidgetProperties);
14847
15553
  }
14848
15554
 
14849
- // This is the `Number.isFinite()` polyfill recommended by MDN.
14850
- // We do not provide any tests for this function.
14851
- // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill
14852
- // @MAJOR Replace with the native `Number.isFinite` method
14853
- function isFiniteNumber(value) {
14854
- return typeof value === 'number' && isFinite(value);
14855
- }
14856
-
14857
15555
  var withUsage$d = createDocumentationMessageGenerator({
14858
15556
  name: 'numeric-menu',
14859
15557
  connector: true
@@ -15114,21 +15812,6 @@
15114
15812
  return useConnector(connectNumericMenu, props, additionalWidgetProperties);
15115
15813
  }
15116
15814
 
15117
- function range(param) {
15118
- var _param_start = param.start, start = _param_start === void 0 ? 0 : _param_start, end = param.end, _param_step = param.step, step = _param_step === void 0 ? 1 : _param_step;
15119
- // We can't divide by 0 so we re-assign the step to 1 if it happens.
15120
- var limitStep = step === 0 ? 1 : step;
15121
- // In some cases the array to create has a decimal length.
15122
- // We therefore need to round the value.
15123
- // Example:
15124
- // { start: 1, end: 5000, step: 500 }
15125
- // => Array length = (5000 - 1) / 500 = 9.998
15126
- var arrayLength = Math.round((end - start) / limitStep);
15127
- return _to_consumable_array(Array(arrayLength)).map(function(_, current) {
15128
- return start + current * limitStep;
15129
- });
15130
- }
15131
-
15132
15815
  var Paginator = /*#__PURE__*/ function() {
15133
15816
  function Paginator(params) {
15134
15817
  _class_call_check(this, Paginator);
@@ -15305,12 +15988,6 @@
15305
15988
  return useConnector(connectPagination, props, additionalWidgetProperties);
15306
15989
  }
15307
15990
 
15308
- function toArray(value) {
15309
- return Array.isArray(value) ? value : [
15310
- value
15311
- ];
15312
- }
15313
-
15314
15991
  function usePoweredBy() {
15315
15992
  var hostname = safelyRunOnBrowser(function(param) {
15316
15993
  var window = param.window;
@@ -16301,7 +16978,8 @@
16301
16978
  },
16302
16979
  getWidgetSearchParameters: function getWidgetSearchParameters(searchParameters, param) {
16303
16980
  var uiState = param.uiState;
16304
- var sortByValue = uiState.sortBy || connectorState.initialValue || searchParameters.index;
16981
+ var isUiStateSortByInItems = !uiState.sortBy || Object.prototype.hasOwnProperty.call(connectorState.itemsLookup, uiState.sortBy);
16982
+ var sortByValue = (isUiStateSortByInItems ? uiState.sortBy : undefined) || connectorState.initialValue || searchParameters.index;
16305
16983
  if (isValidStrategy(connectorState.itemsLookup, sortByValue)) {
16306
16984
  var item = connectorState.itemsLookup[sortByValue];
16307
16985
  // Strategy-based: set the sortBy parameter for composition API
@@ -17402,13 +18080,19 @@
17402
18080
  var resultsCount = (searchResults === null || searchResults === void 0 ? void 0 : (_searchResults__rawResults = searchResults._rawResults) === null || _searchResults__rawResults === void 0 ? void 0 : _searchResults__rawResults.length) || 0;
17403
18081
  var requestParams = resultsCount ? requestParamsList === null || requestParamsList === void 0 ? void 0 : requestParamsList.slice(requestParamsIndex, requestParamsIndex + resultsCount) : [];
17404
18082
  requestParamsIndex += resultsCount;
17405
- initialResults[widget.getIndexId()] = _object_spread({}, searchResults && {
18083
+ initialResults[widget.getIndexId()] = _object_spread({}, searchResults && _object_spread({
17406
18084
  state: _object_spread_props(_object_spread({}, searchResults._state), {
17407
18085
  clickAnalytics: requestParams === null || requestParams === void 0 ? void 0 : (_requestParams_ = requestParams[0]) === null || _requestParams_ === void 0 ? void 0 : _requestParams_.clickAnalytics,
17408
18086
  userToken: requestParams === null || requestParams === void 0 ? void 0 : (_requestParams_1 = requestParams[0]) === null || _requestParams_1 === void 0 ? void 0 : _requestParams_1.userToken
17409
18087
  }),
17410
18088
  results: searchResults._rawResults
17411
- }, recommendResults && {
18089
+ }, searchResults.feeds && searchResults.feeds.length > 0 && {
18090
+ compositionFeedsResults: searchResults.feeds.map(function(feed) {
18091
+ return _object_spread_props(_object_spread({}, feed._rawResults[0]), {
18092
+ feedID: feed.feedID
18093
+ });
18094
+ })
18095
+ }), recommendResults && {
17412
18096
  recommendResults: {
17413
18097
  // We have to stringify + parse because of some explicitly undefined values.
17414
18098
  params: JSON.parse(JSON.stringify(recommendResults._state.params)),
@@ -17452,12 +18136,9 @@
17452
18136
  notifyServer: createNotifyServer()
17453
18137
  }).then(function(serverState) {
17454
18138
  var shouldRefetch = false;
17455
- // <DynamicWidgets> requires another query to retrieve the dynamic widgets
17456
- // to render.
18139
+ // Two-pass widgets require another query to discover and mount child widgets.
17457
18140
  walkIndex(searchRef.current.mainIndex, function(index) {
17458
- shouldRefetch = shouldRefetch || index.getWidgets().some(function(widget) {
17459
- return widget.$$type === 'ais.dynamicWidgets';
17460
- });
18141
+ shouldRefetch = shouldRefetch || index.getWidgets().some(isTwoPassWidget);
17461
18142
  });
17462
18143
  if (shouldRefetch) {
17463
18144
  resetWidgetId();
@@ -17506,6 +18187,7 @@
17506
18187
 
17507
18188
  exports.Configure = Configure;
17508
18189
  exports.DynamicWidgets = DynamicWidgets;
18190
+ exports.Feeds = Feeds;
17509
18191
  exports.Index = Index;
17510
18192
  exports.InstantSearch = InstantSearch;
17511
18193
  exports.InstantSearchRSCContext = InstantSearchRSCContext;
@@ -17521,6 +18203,7 @@
17521
18203
  exports.useConnector = useConnector;
17522
18204
  exports.useCurrentRefinements = useCurrentRefinements;
17523
18205
  exports.useDynamicWidgets = useDynamicWidgets;
18206
+ exports.useFeeds = useFeeds;
17524
18207
  exports.useFilterSuggestions = useFilterSuggestions;
17525
18208
  exports.useFrequentlyBoughtTogether = useFrequentlyBoughtTogether;
17526
18209
  exports.useGeoSearch = useGeoSearch;