react-instantsearch 7.31.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 7.31.0 | © Algolia, Inc. and contributors; MIT License | https://github.com/algolia/instantsearch */
1
+ /*! React InstantSearch 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.31.0';
27
+ var version$2 = '7.32.0';
28
28
 
29
29
  function _define_property(obj, key, value) {
30
30
  if (key in obj) {
@@ -3919,7 +3919,7 @@
3919
3919
  function requireVersion() {
3920
3920
  if (hasRequiredVersion) return version$1;
3921
3921
  hasRequiredVersion = 1;
3922
- version$1 = '3.28.2';
3922
+ version$1 = '3.29.0';
3923
3923
  return version$1;
3924
3924
  }
3925
3925
 
@@ -5293,7 +5293,6 @@
5293
5293
  var derivedStateQueries = requestBuilder._getCompositionQueries(derivedState);
5294
5294
  states.push({
5295
5295
  state: derivedState,
5296
- queriesCount: derivedStateQueries.length,
5297
5296
  helper: derivedHelper
5298
5297
  });
5299
5298
  derivedHelper.emit('search', {
@@ -5423,7 +5422,7 @@
5423
5422
  var state = s.state;
5424
5423
  var queriesCount = s.queriesCount;
5425
5424
  var helper = s.helper;
5426
- var specificResults = results.splice(0, queriesCount);
5425
+ var specificResults = queriesCount !== undefined ? results.splice(0, queriesCount) : results;
5427
5426
  if (!state.index) {
5428
5427
  helper.emit('result', {
5429
5428
  results: null,
@@ -5431,8 +5430,24 @@
5431
5430
  });
5432
5431
  return;
5433
5432
  }
5434
- helper.lastResults = new SearchResults(state, specificResults, self._searchResultsOptions);
5435
- 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
+ }
5436
5451
  helper.emit('result', {
5437
5452
  results: helper.lastResults,
5438
5453
  state: state
@@ -5965,7 +5980,7 @@
5965
5980
  }
5966
5981
  }
5967
5982
 
5968
- var withUsage$t = createDocumentationMessageGenerator({
5983
+ var withUsage$u = createDocumentationMessageGenerator({
5969
5984
  name: 'configure',
5970
5985
  connector: true
5971
5986
  });
@@ -5981,7 +5996,7 @@
5981
5996
  var renderFn = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : noop, unmountFn = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop;
5982
5997
  return function(widgetParams) {
5983
5998
  if (!widgetParams || !isPlainObject(widgetParams.searchParameters)) {
5984
- throw new Error(withUsage$t('The `searchParameters` option expects an object.'));
5999
+ throw new Error(withUsage$u('The `searchParameters` option expects an object.'));
5985
6000
  }
5986
6001
  var connectorState = {};
5987
6002
  function refine(helper) {
@@ -6252,131 +6267,1239 @@
6252
6267
  return stableValue;
6253
6268
  }
6254
6269
 
6255
- var useKey = 'use';
6256
- // @TODO: Remove this file and import directly from React when available.
6257
- var use = React__namespace[useKey];
6270
+ var id$1 = 0;
6271
+ function addWidgetId(widget) {
6272
+ if (widget.dependsOn !== 'recommend') {
6273
+ return;
6274
+ }
6275
+ widget.$$id = id$1++;
6276
+ }
6277
+ function resetWidgetId() {
6278
+ id$1 = 0;
6279
+ }
6258
6280
 
6259
- /**
6260
- * `useLayoutEffect` that doesn't show a warning when server-side rendering.
6261
- *
6262
- * It uses `useEffect` on the server (no-op), and `useLayoutEffect` on the browser.
6263
- */ var useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
6281
+ function _array_without_holes(arr) {
6282
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
6283
+ }
6264
6284
 
6265
- var InstantSearchRSCContext = /*#__PURE__*/ React.createContext({
6266
- countRef: {
6267
- current: 0
6268
- },
6269
- waitForResultsRef: null,
6270
- ignoreMultipleHooksWarning: false
6271
- });
6285
+ function _non_iterable_spread() {
6286
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
6287
+ }
6272
6288
 
6273
- function useRSCContext() {
6274
- return React.useContext(InstantSearchRSCContext);
6289
+ function _to_consumable_array(arr) {
6290
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
6275
6291
  }
6276
6292
 
6277
- function useWidget(param) {
6278
- var widget = param.widget, parentIndex = param.parentIndex, props = param.props, shouldSsr = param.shouldSsr, skipSuspense = param.skipSuspense;
6279
- var _waitForResultsRef_current, _waitForResultsRef_current1;
6280
- var _useRSCContext = useRSCContext(), waitForResultsRef = _useRSCContext.waitForResultsRef, countRef = _useRSCContext.countRef;
6281
- _useRSCContext.ignoreMultipleHooksWarning;
6282
- var prevPropsRef = React.useRef(props);
6283
- React.useEffect(function() {
6284
- prevPropsRef.current = props;
6285
- }, [
6286
- props
6287
- ]);
6288
- var prevWidgetRef = React.useRef(widget);
6289
- React.useEffect(function() {
6290
- prevWidgetRef.current = widget;
6291
- }, [
6292
- widget
6293
- ]);
6294
- var cleanupTimerRef = React.useRef(null);
6295
- var shouldAddWidgetEarly = shouldSsr && !parentIndex.getWidgets().includes(widget);
6296
- var search = useInstantSearchContext();
6297
- // This effect is responsible for adding, removing, and updating the widget.
6298
- // We need to support scenarios where the widget is remounted quickly, like in
6299
- // Strict Mode, so that we don't lose its state, and therefore that we don't
6300
- // break routing.
6301
- useIsomorphicLayoutEffect(function() {
6302
- var previousWidget = prevWidgetRef.current;
6303
- // Scenario 1: the widget is added for the first time.
6304
- if (!cleanupTimerRef.current) {
6305
- if (!shouldSsr) {
6306
- parentIndex.addWidgets([
6307
- widget
6308
- ]);
6309
- }
6310
- } else {
6311
- // We cancel the original effect cleanup because it may not be necessary if
6312
- // props haven't changed. (We manually call it if it is below.)
6313
- clearTimeout(cleanupTimerRef.current);
6314
- // Warning: if an unstable function prop is provided, `dequal` is not able
6315
- // to keep its reference and therefore will consider that props did change.
6316
- // This could unsollicitely remove/add the widget, therefore forget its state,
6317
- // and could be a source of confusion.
6318
- // If users face this issue, we should advise them to provide stable function
6319
- // references.
6320
- var arePropsEqual = dequal(props, prevPropsRef.current);
6321
- // If props did change, then we execute the cleanup function instantly
6322
- // and then add the widget back. This lets us add the widget without
6323
- // waiting for the scheduled cleanup function to finish (that we canceled
6324
- // above).
6325
- if (!arePropsEqual) {
6326
- parentIndex.removeWidgets([
6327
- previousWidget
6328
- ]);
6329
- parentIndex.addWidgets([
6330
- widget
6331
- ]);
6332
- }
6293
+ function getObjectType(object) {
6294
+ return Object.prototype.toString.call(object).slice(8, -1);
6295
+ }
6296
+
6297
+ function checkRendering(rendering, usage) {
6298
+ if (rendering === undefined || typeof rendering !== 'function') {
6299
+ throw new Error("The render function is not valid (received type ".concat(getObjectType(rendering), ").\n\n").concat(usage));
6300
+ }
6301
+ }
6302
+
6303
+ /**
6304
+ * Clears the refinements of a SearchParameters object based on rules provided.
6305
+ * The included attributes list is applied before the excluded attributes list. If the list
6306
+ * is not provided, this list of all the currently refined attributes is used as included attributes.
6307
+ * @returns search parameters with refinements cleared
6308
+ */ function clearRefinements(param) {
6309
+ var helper = param.helper, _param_attributesToClear = param.attributesToClear, attributesToClear = _param_attributesToClear === void 0 ? [] : _param_attributesToClear;
6310
+ var finalState = helper.state.setPage(0);
6311
+ finalState = attributesToClear.reduce(function(state, attribute) {
6312
+ if (finalState.isNumericRefined(attribute)) {
6313
+ return state.removeNumericRefinement(attribute);
6333
6314
  }
6334
- return function() {
6335
- // We don't remove the widget right away, but rather schedule it so that
6336
- // we're able to cancel it in the next effect.
6337
- cleanupTimerRef.current = setTimeout(function() {
6338
- search._schedule(function() {
6339
- if (search._preventWidgetCleanup) return;
6340
- parentIndex.removeWidgets([
6341
- previousWidget
6342
- ]);
6343
- });
6344
- });
6345
- };
6346
- }, [
6347
- parentIndex,
6348
- widget,
6349
- shouldSsr,
6350
- search,
6351
- props
6352
- ]);
6353
- if (shouldAddWidgetEarly || (waitForResultsRef === null || waitForResultsRef === void 0 ? void 0 : (_waitForResultsRef_current = waitForResultsRef.current) === null || _waitForResultsRef_current === void 0 ? void 0 : _waitForResultsRef_current.status) === 'pending') {
6354
- parentIndex.addWidgets([
6355
- widget
6356
- ]);
6315
+ if (finalState.isHierarchicalFacet(attribute)) {
6316
+ return state.removeHierarchicalFacetRefinement(attribute);
6317
+ }
6318
+ if (finalState.isDisjunctiveFacet(attribute)) {
6319
+ return state.removeDisjunctiveFacetRefinement(attribute);
6320
+ }
6321
+ if (finalState.isConjunctiveFacet(attribute)) {
6322
+ return state.removeFacetRefinement(attribute);
6323
+ }
6324
+ return state;
6325
+ }, finalState);
6326
+ if (attributesToClear.indexOf('query') !== -1) {
6327
+ finalState = finalState.setQuery('');
6357
6328
  }
6358
- if ((waitForResultsRef === null || waitForResultsRef === void 0 ? void 0 : waitForResultsRef.current) && !skipSuspense) {
6359
- var _search_helper;
6360
- use(waitForResultsRef.current);
6361
- // If we made a second request because of DynamicWidgets, we need to wait for the second result,
6362
- // except for DynamicWidgets itself which needs to render its children after the first result.
6363
- if (widget.$$type !== 'ais.dynamicWidgets' && ((_search_helper = search.helper) === null || _search_helper === void 0 ? void 0 : _search_helper.lastResults)) {
6364
- use(waitForResultsRef.current);
6329
+ return finalState;
6330
+ }
6331
+
6332
+ function _extends() {
6333
+ _extends = Object.assign || function assign(target) {
6334
+ for (var i = 1; i < arguments.length; i++) {
6335
+ var source = arguments[i];
6336
+ for (var key in source) if (Object.prototype.hasOwnProperty.call(source, key)) target[key] = source[key];
6365
6337
  }
6338
+
6339
+ return target;
6340
+ };
6341
+
6342
+ return _extends.apply(this, arguments);
6343
+ }
6344
+
6345
+ function _object_destructuring_empty(o) {
6346
+ if (o === null || o === void 0) throw new TypeError("Cannot destructure " + o);
6347
+
6348
+ return o;
6349
+ }
6350
+
6351
+ /**
6352
+ * This implementation is taken from Lodash implementation.
6353
+ * See: https://github.com/lodash/lodash/blob/4.17.11-npm/escape.js
6354
+ */ // Used to map characters to HTML entities.
6355
+ var htmlEntities = {
6356
+ '&': '&amp;',
6357
+ '<': '&lt;',
6358
+ '>': '&gt;',
6359
+ '"': '&quot;',
6360
+ "'": '&#39;'
6361
+ };
6362
+ // Used to match HTML entities and HTML characters.
6363
+ var regexUnescapedHtml = /[&<>"']/g;
6364
+ var regexHasUnescapedHtml = RegExp(regexUnescapedHtml.source);
6365
+ /**
6366
+ * Converts the characters "&", "<", ">", '"', and "'" in `string` to their
6367
+ * corresponding HTML entities.
6368
+ */ function escape$1(value) {
6369
+ return value && regexHasUnescapedHtml.test(value) ? value.replace(regexUnescapedHtml, function(character) {
6370
+ return htmlEntities[character];
6371
+ }) : value;
6372
+ }
6373
+ /**
6374
+ * This implementation is taken from Lodash implementation.
6375
+ * See: https://github.com/lodash/lodash/blob/4.17.11-npm/unescape.js
6376
+ */ // Used to map HTML entities to characters.
6377
+ var htmlCharacters = {
6378
+ '&amp;': '&',
6379
+ '&lt;': '<',
6380
+ '&gt;': '>',
6381
+ '&quot;': '"',
6382
+ '&#39;': "'"
6383
+ };
6384
+ // Used to match HTML entities and HTML characters.
6385
+ var regexEscapedHtml = /&(amp|quot|lt|gt|#39);/g;
6386
+ var regexHasEscapedHtml = RegExp(regexEscapedHtml.source);
6387
+ /**
6388
+ * Converts the HTML entities "&", "<", ">", '"', and "'" in `string` to their
6389
+ * characters.
6390
+ */ function unescape$1(value) {
6391
+ return value && regexHasEscapedHtml.test(value) ? value.replace(regexEscapedHtml, function(character) {
6392
+ return htmlCharacters[character];
6393
+ }) : value;
6394
+ }
6395
+
6396
+ var TAG_PLACEHOLDER = {
6397
+ highlightPreTag: '__ais-highlight__',
6398
+ highlightPostTag: '__/ais-highlight__'
6399
+ };
6400
+ var TAG_REPLACEMENT = {
6401
+ highlightPreTag: '<mark>',
6402
+ highlightPostTag: '</mark>'
6403
+ };
6404
+ // @MAJOR: in the future, this should only escape, not replace
6405
+ function replaceTagsAndEscape(value) {
6406
+ return escape$1(value).replace(new RegExp(TAG_PLACEHOLDER.highlightPreTag, 'g'), TAG_REPLACEMENT.highlightPreTag).replace(new RegExp(TAG_PLACEHOLDER.highlightPostTag, 'g'), TAG_REPLACEMENT.highlightPostTag);
6407
+ }
6408
+ function recursiveEscape(input) {
6409
+ if (isPlainObject(input) && typeof input.value !== 'string') {
6410
+ return Object.keys(input).reduce(function(acc, key) {
6411
+ return _object_spread_props(_object_spread({}, acc), _define_property({}, key, recursiveEscape(input[key])));
6412
+ }, {});
6366
6413
  }
6367
- if ((waitForResultsRef === null || waitForResultsRef === void 0 ? void 0 : (_waitForResultsRef_current1 = waitForResultsRef.current) === null || _waitForResultsRef_current1 === void 0 ? void 0 : _waitForResultsRef_current1.status) === 'fulfilled') {
6368
- countRef.current += 1;
6414
+ if (Array.isArray(input)) {
6415
+ return input.map(recursiveEscape);
6369
6416
  }
6417
+ return _object_spread_props(_object_spread({}, input), {
6418
+ value: replaceTagsAndEscape(input.value)
6419
+ });
6370
6420
  }
6371
-
6372
- function useConnector(connector) {
6373
- 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;
6374
- var _ref = [
6375
- _1,
6376
- _2
6377
- ], _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, [
6378
- "skipSuspense"
6379
- ]);
6421
+ function escapeHits(hits) {
6422
+ if (hits.__escaped === undefined) {
6423
+ // We don't override the value on hit because it will mutate the raw results
6424
+ // instead we make a shallow copy and we assign the escaped values on it.
6425
+ hits = hits.map(function(_0) {
6426
+ _object_destructuring_empty(_0);
6427
+ var hit = _extends({}, _0);
6428
+ if (hit._highlightResult) {
6429
+ hit._highlightResult = recursiveEscape(hit._highlightResult);
6430
+ }
6431
+ if (hit._snippetResult) {
6432
+ hit._snippetResult = recursiveEscape(hit._snippetResult);
6433
+ }
6434
+ return hit;
6435
+ });
6436
+ hits.__escaped = true;
6437
+ }
6438
+ return hits;
6439
+ }
6440
+ function escapeFacets(facetHits) {
6441
+ return facetHits.map(function(h) {
6442
+ return _object_spread_props(_object_spread({}, h), {
6443
+ highlighted: replaceTagsAndEscape(h.highlighted)
6444
+ });
6445
+ });
6446
+ }
6447
+
6448
+ function concatHighlightedParts(parts) {
6449
+ var highlightPreTag = TAG_REPLACEMENT.highlightPreTag, highlightPostTag = TAG_REPLACEMENT.highlightPostTag;
6450
+ return parts.map(function(part) {
6451
+ return part.isHighlighted ? highlightPreTag + part.value + highlightPostTag : part.value;
6452
+ }).join('');
6453
+ }
6454
+
6455
+ function isFacetRefined(helper, facet, value) {
6456
+ if (helper.state.isHierarchicalFacet(facet)) {
6457
+ return helper.state.isHierarchicalFacetRefined(facet, value);
6458
+ } else if (helper.state.isConjunctiveFacet(facet)) {
6459
+ return helper.state.isFacetRefined(facet, value);
6460
+ } else {
6461
+ return helper.state.isDisjunctiveFacetRefined(facet, value);
6462
+ }
6463
+ }
6464
+
6465
+ function createSendEventForFacet(param) {
6466
+ var instantSearchInstance = param.instantSearchInstance, helper = param.helper, attr = param.attribute, widgetType = param.widgetType;
6467
+ var sendEventForFacet = function sendEventForFacet() {
6468
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
6469
+ args[_key] = arguments[_key];
6470
+ }
6471
+ 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;
6472
+ var _args__split = _sliced_to_array(args[0].split(':'), 2), eventType = _args__split[0], eventModifier = _args__split[1];
6473
+ var attribute = typeof attr === 'string' ? attr : attr(facetValue);
6474
+ if (args.length === 1 && _type_of(args[0]) === 'object') {
6475
+ instantSearchInstance.sendEventToInsights(args[0]);
6476
+ } else if (eventType === 'click' && args.length >= 2 && args.length <= 4) {
6477
+ if (!isFacetRefined(helper, attribute, facetValue)) {
6478
+ var _helper_lastResults;
6479
+ // send event only when the facet is being checked "ON"
6480
+ instantSearchInstance.sendEventToInsights({
6481
+ insightsMethod: 'clickedFilters',
6482
+ widgetType: widgetType,
6483
+ eventType: eventType,
6484
+ eventModifier: eventModifier,
6485
+ payload: _object_spread({
6486
+ eventName: eventName,
6487
+ index: ((_helper_lastResults = helper.lastResults) === null || _helper_lastResults === void 0 ? void 0 : _helper_lastResults.index) || helper.state.index,
6488
+ filters: [
6489
+ "".concat(attribute, ":").concat(facetValue)
6490
+ ]
6491
+ }, additionalData),
6492
+ attribute: attribute
6493
+ });
6494
+ }
6495
+ } else ;
6496
+ };
6497
+ return sendEventForFacet;
6498
+ }
6499
+
6500
+ function serializePayload(payload) {
6501
+ return btoa(encodeURIComponent(JSON.stringify(payload)));
6502
+ }
6503
+
6504
+ function chunk(arr) {
6505
+ var chunkSize = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 20;
6506
+ var chunks = [];
6507
+ for(var i = 0; i < Math.ceil(arr.length / chunkSize); i++){
6508
+ chunks.push(arr.slice(i * chunkSize, (i + 1) * chunkSize));
6509
+ }
6510
+ return chunks;
6511
+ }
6512
+ function _buildEventPayloadsForHits(param) {
6513
+ var helper = param.helper, widgetType = param.widgetType;
6514
+ param.methodName;
6515
+ var args = param.args, instantSearchInstance = param.instantSearchInstance;
6516
+ // when there's only one argument, that means it's custom
6517
+ if (args.length === 1 && _type_of(args[0]) === 'object') {
6518
+ return [
6519
+ args[0]
6520
+ ];
6521
+ }
6522
+ var _args__split = _sliced_to_array(args[0].split(':'), 2), eventType = _args__split[0], eventModifier = _args__split[1];
6523
+ var hits = args[1];
6524
+ var eventName = args[2];
6525
+ var additionalData = args[3] || {};
6526
+ if (!hits) {
6527
+ {
6528
+ return [];
6529
+ }
6530
+ }
6531
+ if ((eventType === 'click' || eventType === 'conversion') && !eventName) {
6532
+ {
6533
+ return [];
6534
+ }
6535
+ }
6536
+ var hitsArray = Array.isArray(hits) ? hits : [
6537
+ hits
6538
+ ];
6539
+ if (hitsArray.length === 0) {
6540
+ return [];
6541
+ }
6542
+ var queryID = hitsArray[0].__queryID;
6543
+ var hitsChunks = chunk(hitsArray);
6544
+ var objectIDsByChunk = hitsChunks.map(function(batch) {
6545
+ return batch.map(function(hit) {
6546
+ return hit.objectID;
6547
+ });
6548
+ });
6549
+ var positionsByChunk = hitsChunks.map(function(batch) {
6550
+ return batch.map(function(hit) {
6551
+ return hit.__position;
6552
+ });
6553
+ });
6554
+ if (eventType === 'view') {
6555
+ if (instantSearchInstance.status !== 'idle') {
6556
+ return [];
6557
+ }
6558
+ return hitsChunks.map(function(batch, i) {
6559
+ var _helper_lastResults;
6560
+ return {
6561
+ insightsMethod: 'viewedObjectIDs',
6562
+ widgetType: widgetType,
6563
+ eventType: eventType,
6564
+ payload: _object_spread({
6565
+ eventName: eventName || 'Hits Viewed',
6566
+ index: ((_helper_lastResults = helper.lastResults) === null || _helper_lastResults === void 0 ? void 0 : _helper_lastResults.index) || helper.state.index,
6567
+ objectIDs: objectIDsByChunk[i]
6568
+ }, additionalData),
6569
+ hits: batch,
6570
+ eventModifier: eventModifier
6571
+ };
6572
+ });
6573
+ } else if (eventType === 'click') {
6574
+ return hitsChunks.map(function(batch, i) {
6575
+ var _helper_lastResults;
6576
+ return {
6577
+ insightsMethod: 'clickedObjectIDsAfterSearch',
6578
+ widgetType: widgetType,
6579
+ eventType: eventType,
6580
+ payload: _object_spread({
6581
+ eventName: eventName || 'Hit Clicked',
6582
+ index: ((_helper_lastResults = helper.lastResults) === null || _helper_lastResults === void 0 ? void 0 : _helper_lastResults.index) || helper.state.index,
6583
+ queryID: queryID,
6584
+ objectIDs: objectIDsByChunk[i],
6585
+ positions: positionsByChunk[i]
6586
+ }, additionalData),
6587
+ hits: batch,
6588
+ eventModifier: eventModifier
6589
+ };
6590
+ });
6591
+ } else if (eventType === 'conversion') {
6592
+ return hitsChunks.map(function(batch, i) {
6593
+ var _helper_lastResults;
6594
+ return {
6595
+ insightsMethod: 'convertedObjectIDsAfterSearch',
6596
+ widgetType: widgetType,
6597
+ eventType: eventType,
6598
+ payload: _object_spread({
6599
+ eventName: eventName || 'Hit Converted',
6600
+ index: ((_helper_lastResults = helper.lastResults) === null || _helper_lastResults === void 0 ? void 0 : _helper_lastResults.index) || helper.state.index,
6601
+ queryID: queryID,
6602
+ objectIDs: objectIDsByChunk[i]
6603
+ }, additionalData),
6604
+ hits: batch,
6605
+ eventModifier: eventModifier
6606
+ };
6607
+ });
6608
+ } else {
6609
+ return [];
6610
+ }
6611
+ }
6612
+ function createSendEventForHits(param) {
6613
+ var instantSearchInstance = param.instantSearchInstance, helper = param.helper, widgetType = param.widgetType;
6614
+ var sentEvents = {};
6615
+ var timer = undefined;
6616
+ var sendEventForHits = function sendEventForHits() {
6617
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
6618
+ args[_key] = arguments[_key];
6619
+ }
6620
+ var payloads = _buildEventPayloadsForHits({
6621
+ widgetType: widgetType,
6622
+ helper: helper,
6623
+ methodName: 'sendEvent',
6624
+ args: args,
6625
+ instantSearchInstance: instantSearchInstance
6626
+ });
6627
+ payloads.forEach(function(payload) {
6628
+ if (payload.eventType === 'click' && payload.eventModifier === 'internal' && sentEvents[payload.eventType]) {
6629
+ return;
6630
+ }
6631
+ sentEvents[payload.eventType] = true;
6632
+ instantSearchInstance.sendEventToInsights(payload);
6633
+ });
6634
+ clearTimeout(timer);
6635
+ timer = setTimeout(function() {
6636
+ sentEvents = {};
6637
+ }, 0);
6638
+ };
6639
+ return sendEventForHits;
6640
+ }
6641
+ function createBindEventForHits(param) {
6642
+ var helper = param.helper, widgetType = param.widgetType, instantSearchInstance = param.instantSearchInstance;
6643
+ var bindEventForHits = function bindEventForHits() {
6644
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
6645
+ args[_key] = arguments[_key];
6646
+ }
6647
+ var payloads = _buildEventPayloadsForHits({
6648
+ widgetType: widgetType,
6649
+ helper: helper,
6650
+ methodName: 'bindEvent',
6651
+ args: args,
6652
+ instantSearchInstance: instantSearchInstance
6653
+ });
6654
+ return payloads.length ? "data-insights-event=".concat(serializePayload(payloads)) : '';
6655
+ };
6656
+ return bindEventForHits;
6657
+ }
6658
+
6659
+ var indexWidgetTypes = [
6660
+ 'ais.index',
6661
+ 'ais.feedContainer'
6662
+ ];
6663
+
6664
+ function isIndexWidget(widget) {
6665
+ return indexWidgetTypes.includes(widget.$$type);
6666
+ }
6667
+
6668
+ function setIndexHelperState(finalUiState, indexWidget) {
6669
+ var nextIndexUiState = finalUiState[indexWidget.getIndexId()] || {};
6670
+ indexWidget.getHelper().setState(indexWidget.getWidgetSearchParameters(indexWidget.getHelper().state, {
6671
+ uiState: nextIndexUiState
6672
+ }));
6673
+ indexWidget.getWidgets().filter(isIndexWidget).forEach(function(widget) {
6674
+ return setIndexHelperState(finalUiState, widget);
6675
+ });
6676
+ }
6677
+
6678
+ var nextMicroTask = Promise.resolve();
6679
+ function defer(callback) {
6680
+ var progress = null;
6681
+ var cancelled = false;
6682
+ var fn = function fn() {
6683
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
6684
+ args[_key] = arguments[_key];
6685
+ }
6686
+ if (progress !== null) {
6687
+ return;
6688
+ }
6689
+ progress = nextMicroTask.then(function() {
6690
+ progress = null;
6691
+ if (cancelled) {
6692
+ cancelled = false;
6693
+ return;
6694
+ }
6695
+ callback.apply(void 0, _to_consumable_array(args));
6696
+ });
6697
+ };
6698
+ fn.wait = function() {
6699
+ if (progress === null) {
6700
+ throw new Error('The deferred function should be called before calling `wait()`');
6701
+ }
6702
+ return progress;
6703
+ };
6704
+ fn.cancel = function() {
6705
+ if (progress === null) {
6706
+ return;
6707
+ }
6708
+ cancelled = true;
6709
+ };
6710
+ return fn;
6711
+ }
6712
+
6713
+ function sendChatMessageFeedback(param) {
6714
+ var agentId = param.agentId, vote = param.vote, messageId = param.messageId, appId = param.appId, apiKey = param.apiKey;
6715
+ return fetch("https://".concat(appId, ".algolia.net/agent-studio/1/feedback"), {
6716
+ method: 'POST',
6717
+ body: JSON.stringify({
6718
+ messageId: messageId,
6719
+ agentId: agentId,
6720
+ vote: vote
6721
+ }),
6722
+ headers: {
6723
+ 'x-algolia-application-id': appId,
6724
+ 'x-algolia-api-key': apiKey,
6725
+ 'content-type': 'application/json'
6726
+ }
6727
+ }).then(function(response) {
6728
+ if (response.status >= 300) {
6729
+ return response.json().then(function(data) {
6730
+ throw new Error("Feedback request failed with status ".concat(response.status, ": ").concat(data.message));
6731
+ });
6732
+ }
6733
+ return response.json();
6734
+ });
6735
+ }
6736
+
6737
+ function unescapeFacetValue(value) {
6738
+ if (typeof value === 'string') {
6739
+ return value.replace(/^\\-/, '-');
6740
+ }
6741
+ return value;
6742
+ }
6743
+ function escapeFacetValue(value) {
6744
+ if (typeof value === 'number' && value < 0 || typeof value === 'string') {
6745
+ return String(value).replace(/^-/, '\\-');
6746
+ }
6747
+ return value;
6748
+ }
6749
+
6750
+ // We aren't using the native `Array.prototype.find` because the refactor away from Lodash is not
6751
+ // published as a major version.
6752
+ // Relying on the `find` polyfill on user-land, which before was only required for niche use-cases,
6753
+ // was decided as too risky.
6754
+ // @MAJOR Replace with the native `Array.prototype.find` method
6755
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
6756
+ function find$1(items, predicate) {
6757
+ var value;
6758
+ for(var i = 0; i < items.length; i++){
6759
+ value = items[i];
6760
+ // inlined for performance: if (Call(predicate, thisArg, [value, i, list])) {
6761
+ if (predicate(value, i, items)) {
6762
+ return value;
6763
+ }
6764
+ }
6765
+ return undefined;
6766
+ }
6767
+
6768
+ var latLngRegExp = /^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)$/;
6769
+ function aroundLatLngToPosition(value) {
6770
+ var pattern = value.match(latLngRegExp);
6771
+ // Since the value provided is the one send with the request, the API should
6772
+ // throw an error due to the wrong format. So throw an error should be safe.
6773
+ if (!pattern) {
6774
+ throw new Error('Invalid value for "aroundLatLng" parameter: "'.concat(value, '"'));
6775
+ }
6776
+ return {
6777
+ lat: parseFloat(pattern[1]),
6778
+ lng: parseFloat(pattern[2])
6779
+ };
6780
+ }
6781
+ function insideBoundingBoxArrayToBoundingBox(value) {
6782
+ var _value = _sliced_to_array(value, 1), tmp = _value[0], _ref = _sliced_to_array(tmp === void 0 ? [
6783
+ undefined,
6784
+ undefined,
6785
+ undefined,
6786
+ undefined
6787
+ ] : tmp, 4), neLat = _ref[0], neLng = _ref[1], swLat = _ref[2], swLng = _ref[3];
6788
+ // Since the value provided is the one send with the request, the API should
6789
+ // throw an error due to the wrong format. So throw an error should be safe.
6790
+ if (!neLat || !neLng || !swLat || !swLng) {
6791
+ throw new Error('Invalid value for "insideBoundingBox" parameter: ['.concat(value, "]"));
6792
+ }
6793
+ return {
6794
+ northEast: {
6795
+ lat: neLat,
6796
+ lng: neLng
6797
+ },
6798
+ southWest: {
6799
+ lat: swLat,
6800
+ lng: swLng
6801
+ }
6802
+ };
6803
+ }
6804
+ function insideBoundingBoxStringToBoundingBox(value) {
6805
+ 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];
6806
+ // Since the value provided is the one send with the request, the API should
6807
+ // throw an error due to the wrong format. So throw an error should be safe.
6808
+ if (!neLat || !neLng || !swLat || !swLng) {
6809
+ throw new Error('Invalid value for "insideBoundingBox" parameter: "'.concat(value, '"'));
6810
+ }
6811
+ return {
6812
+ northEast: {
6813
+ lat: neLat,
6814
+ lng: neLng
6815
+ },
6816
+ southWest: {
6817
+ lat: swLat,
6818
+ lng: swLng
6819
+ }
6820
+ };
6821
+ }
6822
+ function insideBoundingBoxToBoundingBox(value) {
6823
+ if (Array.isArray(value)) {
6824
+ return insideBoundingBoxArrayToBoundingBox(value);
6825
+ }
6826
+ return insideBoundingBoxStringToBoundingBox(value);
6827
+ }
6828
+
6829
+ function getAlgoliaAgent(client) {
6830
+ var clientTyped = client;
6831
+ return clientTyped.transporter && clientTyped.transporter.userAgent ? clientTyped.transporter.userAgent.value : clientTyped._ua;
6832
+ }
6833
+
6834
+ // typed as any, since it accepts the _real_ js clients, not the interface we otherwise expect
6835
+ function getAppIdAndApiKey(searchClient) {
6836
+ if (searchClient.appId && searchClient.apiKey) {
6837
+ // searchClient v5
6838
+ return [
6839
+ searchClient.appId,
6840
+ searchClient.apiKey
6841
+ ];
6842
+ } else if (searchClient.transporter) {
6843
+ // searchClient v4 or v5
6844
+ var transporter = searchClient.transporter;
6845
+ var headers = transporter.headers || transporter.baseHeaders;
6846
+ var queryParameters = transporter.queryParameters || transporter.baseQueryParameters;
6847
+ var APP_ID = 'x-algolia-application-id';
6848
+ var API_KEY = 'x-algolia-api-key';
6849
+ var appId = headers[APP_ID] || queryParameters[APP_ID];
6850
+ var apiKey = headers[API_KEY] || queryParameters[API_KEY];
6851
+ return [
6852
+ appId,
6853
+ apiKey
6854
+ ];
6855
+ } else {
6856
+ // searchClient v3
6857
+ return [
6858
+ searchClient.applicationID,
6859
+ searchClient.apiKey
6860
+ ];
6861
+ }
6862
+ }
6863
+
6864
+ function getHighlightedParts(highlightedValue) {
6865
+ // @MAJOR: this should use TAG_PLACEHOLDER
6866
+ var highlightPostTag = TAG_REPLACEMENT.highlightPostTag, highlightPreTag = TAG_REPLACEMENT.highlightPreTag;
6867
+ var splitByPreTag = highlightedValue.split(highlightPreTag);
6868
+ var firstValue = splitByPreTag.shift();
6869
+ var elements = !firstValue ? [] : [
6870
+ {
6871
+ value: firstValue,
6872
+ isHighlighted: false
6873
+ }
6874
+ ];
6875
+ splitByPreTag.forEach(function(split) {
6876
+ var splitByPostTag = split.split(highlightPostTag);
6877
+ elements.push({
6878
+ value: splitByPostTag[0],
6879
+ isHighlighted: true
6880
+ });
6881
+ if (splitByPostTag[1] !== '') {
6882
+ elements.push({
6883
+ value: splitByPostTag[1],
6884
+ isHighlighted: false
6885
+ });
6886
+ }
6887
+ });
6888
+ return elements;
6889
+ }
6890
+
6891
+ var hasAlphanumeric = new RegExp(/\w/i);
6892
+ function getHighlightFromSiblings(parts, i) {
6893
+ var _parts_, _parts_1;
6894
+ var current = parts[i];
6895
+ var isNextHighlighted = ((_parts_ = parts[i + 1]) === null || _parts_ === void 0 ? void 0 : _parts_.isHighlighted) || true;
6896
+ var isPreviousHighlighted = ((_parts_1 = parts[i - 1]) === null || _parts_1 === void 0 ? void 0 : _parts_1.isHighlighted) || true;
6897
+ if (!hasAlphanumeric.test(unescape$1(current.value)) && isPreviousHighlighted === isNextHighlighted) {
6898
+ return isPreviousHighlighted;
6899
+ }
6900
+ return current.isHighlighted;
6901
+ }
6902
+
6903
+ function getPropertyByPath(object, path) {
6904
+ var parts = Array.isArray(path) ? path : path.split('.');
6905
+ return parts.reduce(function(current, key) {
6906
+ return current && current[key];
6907
+ }, object);
6908
+ }
6909
+
6910
+ function getRefinement(state, type, attribute, name) {
6911
+ var resultsFacets = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : [];
6912
+ var res = {
6913
+ type: type,
6914
+ attribute: attribute,
6915
+ name: name,
6916
+ escapedValue: escapeFacetValue(name)
6917
+ };
6918
+ var facet = find$1(resultsFacets, function(resultsFacet) {
6919
+ return resultsFacet.name === attribute;
6920
+ });
6921
+ var count;
6922
+ if (type === 'hierarchical') {
6923
+ var _loop = function _loop(i) {
6924
+ facet = facet && facet.data && find$1(Object.keys(facet.data).map(getFacetRefinement(facet.data)), function(refinement) {
6925
+ return refinement.name === nameParts[i];
6926
+ });
6927
+ };
6928
+ var facetDeclaration = state.getHierarchicalFacetByName(attribute);
6929
+ var nameParts = name.split(facetDeclaration.separator);
6930
+ var getFacetRefinement = function getFacetRefinement(facetData) {
6931
+ return function(refinementKey) {
6932
+ return facetData[refinementKey];
6933
+ };
6934
+ };
6935
+ for(var i = 0; facet !== undefined && i < nameParts.length; ++i)_loop(i);
6936
+ count = facet && facet.count;
6937
+ } else {
6938
+ count = facet && facet.data && facet.data[res.name];
6939
+ }
6940
+ if (count !== undefined) {
6941
+ res.count = count;
6942
+ }
6943
+ if (facet && facet.exhaustive !== undefined) {
6944
+ res.exhaustive = facet.exhaustive;
6945
+ }
6946
+ return res;
6947
+ }
6948
+ function getRefinements(_results, state) {
6949
+ var includesQuery = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
6950
+ var results = _results || {};
6951
+ var refinements = [];
6952
+ 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;
6953
+ Object.keys(facetsRefinements).forEach(function(attribute) {
6954
+ var refinementNames = facetsRefinements[attribute];
6955
+ refinementNames.forEach(function(refinementName) {
6956
+ refinements.push(getRefinement(state, 'facet', attribute, refinementName, results.facets));
6957
+ });
6958
+ });
6959
+ Object.keys(facetsExcludes).forEach(function(attribute) {
6960
+ var refinementNames = facetsExcludes[attribute];
6961
+ refinementNames.forEach(function(refinementName) {
6962
+ refinements.push({
6963
+ type: 'exclude',
6964
+ attribute: attribute,
6965
+ name: refinementName,
6966
+ exclude: true
6967
+ });
6968
+ });
6969
+ });
6970
+ Object.keys(disjunctiveFacetsRefinements).forEach(function(attribute) {
6971
+ var refinementNames = disjunctiveFacetsRefinements[attribute];
6972
+ refinementNames.forEach(function(refinementName) {
6973
+ refinements.push(getRefinement(state, 'disjunctive', attribute, // they can be escaped on negative numeric values with `escapeFacetValue`.
6974
+ unescapeFacetValue(refinementName), results.disjunctiveFacets));
6975
+ });
6976
+ });
6977
+ Object.keys(hierarchicalFacetsRefinements).forEach(function(attribute) {
6978
+ var refinementNames = hierarchicalFacetsRefinements[attribute];
6979
+ refinementNames.forEach(function(refinement) {
6980
+ refinements.push(getRefinement(state, 'hierarchical', attribute, refinement, results.hierarchicalFacets));
6981
+ });
6982
+ });
6983
+ Object.keys(numericRefinements).forEach(function(attribute) {
6984
+ var operators = numericRefinements[attribute];
6985
+ Object.keys(operators).forEach(function(operatorOriginal) {
6986
+ var operator = operatorOriginal;
6987
+ var valueOrValues = operators[operator];
6988
+ var refinementNames = Array.isArray(valueOrValues) ? valueOrValues : [
6989
+ valueOrValues
6990
+ ];
6991
+ refinementNames.forEach(function(refinementName) {
6992
+ refinements.push({
6993
+ type: 'numeric',
6994
+ attribute: attribute,
6995
+ name: "".concat(refinementName),
6996
+ numericValue: refinementName,
6997
+ operator: operator
6998
+ });
6999
+ });
7000
+ });
7001
+ });
7002
+ tagRefinements.forEach(function(refinementName) {
7003
+ refinements.push({
7004
+ type: 'tag',
7005
+ attribute: '_tags',
7006
+ name: refinementName
7007
+ });
7008
+ });
7009
+ if (includesQuery && state.query && state.query.trim()) {
7010
+ refinements.push({
7011
+ attribute: 'query',
7012
+ type: 'query',
7013
+ name: state.query,
7014
+ query: state.query
7015
+ });
7016
+ }
7017
+ return refinements;
7018
+ }
7019
+
7020
+ function getWidgetAttribute$1(widget, initOptions) {
7021
+ var _widget_getWidgetRenderState;
7022
+ var renderState = (_widget_getWidgetRenderState = widget.getWidgetRenderState) === null || _widget_getWidgetRenderState === void 0 ? void 0 : _widget_getWidgetRenderState.call(widget, initOptions);
7023
+ var attribute = null;
7024
+ if (renderState && renderState.widgetParams) {
7025
+ // casting as widgetParams is checked just before
7026
+ var widgetParams = renderState.widgetParams;
7027
+ if (widgetParams.attribute) {
7028
+ attribute = widgetParams.attribute;
7029
+ } else if (Array.isArray(widgetParams.attributes)) {
7030
+ attribute = widgetParams.attributes[0];
7031
+ }
7032
+ }
7033
+ if (typeof attribute !== 'string') {
7034
+ 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."));
7035
+ }
7036
+ return attribute;
7037
+ }
7038
+
7039
+ function addAbsolutePosition(hits, page, hitsPerPage) {
7040
+ return hits.map(function(hit, idx) {
7041
+ return _object_spread_props(_object_spread({}, hit), {
7042
+ __position: hitsPerPage * page + idx + 1
7043
+ });
7044
+ });
7045
+ }
7046
+
7047
+ function addQueryID(hits, queryID) {
7048
+ if (!queryID) {
7049
+ return hits;
7050
+ }
7051
+ return hits.map(function(hit) {
7052
+ return _object_spread_props(_object_spread({}, hit), {
7053
+ __queryID: queryID
7054
+ });
7055
+ });
7056
+ }
7057
+
7058
+ function hydrateRecommendCache(helper, initialResults) {
7059
+ var recommendCache = Object.keys(initialResults).reduce(function(acc, indexName) {
7060
+ var initialResult = initialResults[indexName];
7061
+ if (initialResult.recommendResults) {
7062
+ // @MAJOR: Use `Object.assign` instead of spread operator
7063
+ return _object_spread({}, acc, initialResult.recommendResults.results);
7064
+ }
7065
+ return acc;
7066
+ }, {});
7067
+ helper._recommendCache = recommendCache;
7068
+ }
7069
+
7070
+ function getServerResults(entry) {
7071
+ var _entry_compositionFeedsResults;
7072
+ return ((_entry_compositionFeedsResults = entry.compositionFeedsResults) === null || _entry_compositionFeedsResults === void 0 ? void 0 : _entry_compositionFeedsResults.length) ? entry.compositionFeedsResults : entry.results || [];
7073
+ }
7074
+ function hydrateSearchClient(client, results) {
7075
+ if (!results) {
7076
+ return;
7077
+ }
7078
+ // Disable cache hydration on:
7079
+ // - Algoliasearch API Client < v4 with cache disabled
7080
+ // - Third party clients (detected by the `addAlgoliaAgent` function missing)
7081
+ if ((!('transporter' in client) || client._cacheHydrated) && (!client._useCache || typeof client.addAlgoliaAgent !== 'function')) {
7082
+ return;
7083
+ }
7084
+ var cachedRequest = [
7085
+ Object.keys(results).reduce(function(acc, key) {
7086
+ var entry = results[key];
7087
+ var state = entry.state, requestParams = entry.requestParams;
7088
+ var serverResults = getServerResults(entry);
7089
+ var mappedResults = serverResults && state ? serverResults.map(function(result, idx) {
7090
+ return _object_spread({
7091
+ indexName: state.index || result.index
7092
+ }, (requestParams === null || requestParams === void 0 ? void 0 : requestParams[idx]) || result.params ? {
7093
+ params: serializeQueryParameters((requestParams === null || requestParams === void 0 ? void 0 : requestParams[idx]) || deserializeQueryParameters(result.params))
7094
+ } : {});
7095
+ }) : [];
7096
+ return acc.concat(mappedResults);
7097
+ }, [])
7098
+ ];
7099
+ var cachedResults = Object.keys(results).reduce(function(acc, key) {
7100
+ var res = getServerResults(results[key]);
7101
+ if (!res) {
7102
+ return acc;
7103
+ }
7104
+ return acc.concat(res);
7105
+ }, []);
7106
+ // Algoliasearch API Client >= v4
7107
+ // To hydrate the client we need to populate the cache with the data from
7108
+ // the server (done in `hydrateSearchClientWithMultiIndexRequest` or
7109
+ // `hydrateSearchClientWithSingleIndexRequest`). But since there is no way
7110
+ // for us to compute the key the same way as `algoliasearch-client` we need
7111
+ // to populate it on a custom key and override the `search` method to
7112
+ // search on it first.
7113
+ if ('transporter' in client && !client._cacheHydrated) {
7114
+ client._cacheHydrated = true;
7115
+ var baseMethod = client.search.bind(client);
7116
+ client.search = function(requests) {
7117
+ for(var _len = arguments.length, methodArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
7118
+ methodArgs[_key - 1] = arguments[_key];
7119
+ }
7120
+ var requestsWithSerializedParams = Array.isArray(requests) ? requests.map(function(request) {
7121
+ return _object_spread_props(_object_spread({}, request), {
7122
+ params: serializeQueryParameters(request.params)
7123
+ });
7124
+ }) : serializeQueryParameters(requests.requestBody.params);
7125
+ return client.transporter.responsesCache.get({
7126
+ method: 'search',
7127
+ args: [
7128
+ requestsWithSerializedParams
7129
+ ].concat(_to_consumable_array(methodArgs))
7130
+ }, function() {
7131
+ return baseMethod.apply(void 0, [
7132
+ requests
7133
+ ].concat(_to_consumable_array(methodArgs)));
7134
+ });
7135
+ };
7136
+ client.transporter.responsesCache.set({
7137
+ method: 'search',
7138
+ args: cachedRequest
7139
+ }, {
7140
+ results: cachedResults
7141
+ });
7142
+ }
7143
+ // Algoliasearch API Client < v4
7144
+ // Prior to client v4 we didn't have a proper API to hydrate the client
7145
+ // cache from the outside. The following code populates the cache with
7146
+ // a single-index result. You can find more information about the
7147
+ // computation of the key inside the client (see link below).
7148
+ // https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240
7149
+ if (!('transporter' in client)) {
7150
+ var cacheKey = "/1/indexes/*/queries_body_".concat(JSON.stringify({
7151
+ requests: cachedRequest
7152
+ }));
7153
+ client.cache = _object_spread_props(_object_spread({}, client.cache), _define_property({}, cacheKey, JSON.stringify({
7154
+ results: Object.keys(results).map(function(key) {
7155
+ return getServerResults(results[key]);
7156
+ })
7157
+ })));
7158
+ }
7159
+ }
7160
+ function deserializeQueryParameters(parameters) {
7161
+ return parameters.split('&').reduce(function(acc, parameter) {
7162
+ var _parameter_split = _sliced_to_array(parameter.split('='), 2), key = _parameter_split[0], value = _parameter_split[1];
7163
+ acc[key] = value ? decodeURIComponent(value) : '';
7164
+ return acc;
7165
+ }, {});
7166
+ }
7167
+ // This function is copied from the algoliasearch v4 API Client. If modified,
7168
+ // consider updating it also in `serializeQueryParameters` from `@algolia/transporter`.
7169
+ function serializeQueryParameters(parameters) {
7170
+ var isObjectOrArray = function isObjectOrArray(value) {
7171
+ return Object.prototype.toString.call(value) === '[object Object]' || Object.prototype.toString.call(value) === '[object Array]';
7172
+ };
7173
+ var encode = function encode(format) {
7174
+ for(var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
7175
+ args[_key - 1] = arguments[_key];
7176
+ }
7177
+ var i = 0;
7178
+ return format.replace(/%s/g, function() {
7179
+ return encodeURIComponent(args[i++]);
7180
+ });
7181
+ };
7182
+ return Object.keys(parameters).map(function(key) {
7183
+ return encode('%s=%s', key, isObjectOrArray(parameters[key]) ? JSON.stringify(parameters[key]) : parameters[key]);
7184
+ }).join('&');
7185
+ }
7186
+
7187
+ function isPrimitive(obj) {
7188
+ return obj !== Object(obj);
7189
+ }
7190
+ function isEqual(first, second) {
7191
+ if (first === second) {
7192
+ return true;
7193
+ }
7194
+ if (isPrimitive(first) || isPrimitive(second) || typeof first === 'function' || typeof second === 'function') {
7195
+ return first === second;
7196
+ }
7197
+ if (Object.keys(first).length !== Object.keys(second).length) {
7198
+ return false;
7199
+ }
7200
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
7201
+ try {
7202
+ // @TODO avoid for..of because of the large polyfill
7203
+ // eslint-disable-next-line instantsearch/no-for-of
7204
+ for(var _iterator = Object.keys(first)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
7205
+ var key = _step.value;
7206
+ if (!(key in second)) {
7207
+ return false;
7208
+ }
7209
+ if (!isEqual(first[key], second[key])) {
7210
+ return false;
7211
+ }
7212
+ }
7213
+ } catch (err) {
7214
+ _didIteratorError = true;
7215
+ _iteratorError = err;
7216
+ } finally{
7217
+ try {
7218
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
7219
+ _iterator.return();
7220
+ }
7221
+ } finally{
7222
+ if (_didIteratorError) {
7223
+ throw _iteratorError;
7224
+ }
7225
+ }
7226
+ }
7227
+ return true;
7228
+ }
7229
+
7230
+ // This is the `Number.isFinite()` polyfill recommended by MDN.
7231
+ // We do not provide any tests for this function.
7232
+ // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill
7233
+ // @MAJOR Replace with the native `Number.isFinite` method
7234
+ function isFiniteNumber(value) {
7235
+ return typeof value === 'number' && isFinite(value);
7236
+ }
7237
+
7238
+ /**
7239
+ * Recurse over all child indices
7240
+ */ function walkIndex(indexWidget, callback) {
7241
+ callback(indexWidget);
7242
+ indexWidget.getWidgets().forEach(function(widget) {
7243
+ if (isIndexWidget(widget)) {
7244
+ walkIndex(widget, callback);
7245
+ }
7246
+ });
7247
+ }
7248
+
7249
+ /**
7250
+ * Returns true if the widget requires a second SSR pass to discover and
7251
+ * mount child widgets (e.g. DynamicWidgets, Feeds).
7252
+ */ function isTwoPassWidget(widget) {
7253
+ return widget.$$type === 'ais.dynamicWidgets' || widget.$$type === 'ais.feeds';
7254
+ }
7255
+
7256
+ /**
7257
+ * Logs a warning
7258
+ * This is used to log issues in development environment only.
7259
+ */ var warn = noop;
7260
+
7261
+ function range(param) {
7262
+ 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;
7263
+ // We can't divide by 0 so we re-assign the step to 1 if it happens.
7264
+ var limitStep = step === 0 ? 1 : step;
7265
+ // In some cases the array to create has a decimal length.
7266
+ // We therefore need to round the value.
7267
+ // Example:
7268
+ // { start: 1, end: 5000, step: 500 }
7269
+ // => Array length = (5000 - 1) / 500 = 9.998
7270
+ var arrayLength = Math.round((end - start) / limitStep);
7271
+ return _to_consumable_array(Array(arrayLength)).map(function(_, current) {
7272
+ return start + current * limitStep;
7273
+ });
7274
+ }
7275
+
7276
+ function createInitArgs(instantSearchInstance, parent, uiState) {
7277
+ var helper = parent.getHelper();
7278
+ return {
7279
+ uiState: uiState,
7280
+ helper: helper,
7281
+ parent: parent,
7282
+ instantSearchInstance: instantSearchInstance,
7283
+ state: helper.state,
7284
+ renderState: instantSearchInstance.renderState,
7285
+ templatesConfig: instantSearchInstance.templatesConfig,
7286
+ createURL: parent.createURL,
7287
+ scopedResults: [],
7288
+ searchMetadata: {
7289
+ isSearchStalled: instantSearchInstance.status === 'stalled'
7290
+ },
7291
+ status: instantSearchInstance.status,
7292
+ error: instantSearchInstance.error
7293
+ };
7294
+ }
7295
+ function createRenderArgs(instantSearchInstance, parent, widget) {
7296
+ var results = parent.getResultsForWidget(widget);
7297
+ var helper = parent.getHelper();
7298
+ return {
7299
+ helper: helper,
7300
+ parent: parent,
7301
+ instantSearchInstance: instantSearchInstance,
7302
+ results: results,
7303
+ scopedResults: parent.getScopedResults(),
7304
+ state: results && '_state' in results ? results._state : helper.state,
7305
+ renderState: instantSearchInstance.renderState,
7306
+ templatesConfig: instantSearchInstance.templatesConfig,
7307
+ createURL: parent.createURL,
7308
+ searchMetadata: {
7309
+ isSearchStalled: instantSearchInstance.status === 'stalled'
7310
+ },
7311
+ status: instantSearchInstance.status,
7312
+ error: instantSearchInstance.error
7313
+ };
7314
+ }
7315
+ function storeRenderState(param) {
7316
+ var renderState = param.renderState, instantSearchInstance = param.instantSearchInstance, parent = param.parent;
7317
+ var parentIndexName = parent ? parent.getIndexId() : instantSearchInstance.mainIndex.getIndexId();
7318
+ instantSearchInstance.renderState = _object_spread_props(_object_spread({}, instantSearchInstance.renderState), _define_property({}, parentIndexName, _object_spread({}, instantSearchInstance.renderState[parentIndexName], renderState)));
7319
+ }
7320
+
7321
+ function resolveSearchParameters(current) {
7322
+ var parent = current.getParent();
7323
+ var states = [
7324
+ current.getHelper().state
7325
+ ];
7326
+ while(parent !== null){
7327
+ states = [
7328
+ parent.getHelper().state
7329
+ ].concat(states);
7330
+ parent = parent.getParent();
7331
+ }
7332
+ return states;
7333
+ }
7334
+
7335
+ function reverseHighlightedParts(parts) {
7336
+ if (!parts.some(function(part) {
7337
+ return part.isHighlighted;
7338
+ })) {
7339
+ return parts.map(function(part) {
7340
+ return _object_spread_props(_object_spread({}, part), {
7341
+ isHighlighted: false
7342
+ });
7343
+ });
7344
+ }
7345
+ return parts.map(function(part, i) {
7346
+ return _object_spread_props(_object_spread({}, part), {
7347
+ isHighlighted: !getHighlightFromSiblings(parts, i)
7348
+ });
7349
+ });
7350
+ }
7351
+
7352
+ // eslint-disable-next-line no-restricted-globals
7353
+ /**
7354
+ * Runs code on browser environments safely.
7355
+ */ function safelyRunOnBrowser(callback) {
7356
+ var fallback = (arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
7357
+ fallback: function fallback() {
7358
+ return undefined;
7359
+ }
7360
+ }).fallback;
7361
+ // eslint-disable-next-line no-restricted-globals
7362
+ if (typeof window === 'undefined') {
7363
+ return fallback();
7364
+ }
7365
+ // eslint-disable-next-line no-restricted-globals
7366
+ return callback({
7367
+ window: window
7368
+ });
7369
+ }
7370
+
7371
+ function toArray(value) {
7372
+ return Array.isArray(value) ? value : [
7373
+ value
7374
+ ];
7375
+ }
7376
+
7377
+ var useKey = 'use';
7378
+ // @TODO: Remove this file and import directly from React when available.
7379
+ var use = React__namespace[useKey];
7380
+
7381
+ /**
7382
+ * `useLayoutEffect` that doesn't show a warning when server-side rendering.
7383
+ *
7384
+ * It uses `useEffect` on the server (no-op), and `useLayoutEffect` on the browser.
7385
+ */ var useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
7386
+
7387
+ var InstantSearchRSCContext = /*#__PURE__*/ React.createContext({
7388
+ countRef: {
7389
+ current: 0
7390
+ },
7391
+ waitForResultsRef: null,
7392
+ ignoreMultipleHooksWarning: false
7393
+ });
7394
+
7395
+ function useRSCContext() {
7396
+ return React.useContext(InstantSearchRSCContext);
7397
+ }
7398
+
7399
+ function useWidget(param) {
7400
+ var widget = param.widget, parentIndex = param.parentIndex, props = param.props, shouldSsr = param.shouldSsr, skipSuspense = param.skipSuspense;
7401
+ var _waitForResultsRef_current, _waitForResultsRef_current1;
7402
+ var _useRSCContext = useRSCContext(), waitForResultsRef = _useRSCContext.waitForResultsRef, countRef = _useRSCContext.countRef;
7403
+ _useRSCContext.ignoreMultipleHooksWarning;
7404
+ var prevPropsRef = React.useRef(props);
7405
+ React.useEffect(function() {
7406
+ prevPropsRef.current = props;
7407
+ }, [
7408
+ props
7409
+ ]);
7410
+ var prevWidgetRef = React.useRef(widget);
7411
+ React.useEffect(function() {
7412
+ prevWidgetRef.current = widget;
7413
+ }, [
7414
+ widget
7415
+ ]);
7416
+ var cleanupTimerRef = React.useRef(null);
7417
+ var shouldAddWidgetEarly = shouldSsr && !parentIndex.getWidgets().includes(widget);
7418
+ var search = useInstantSearchContext();
7419
+ // This effect is responsible for adding, removing, and updating the widget.
7420
+ // We need to support scenarios where the widget is remounted quickly, like in
7421
+ // Strict Mode, so that we don't lose its state, and therefore that we don't
7422
+ // break routing.
7423
+ useIsomorphicLayoutEffect(function() {
7424
+ var previousWidget = prevWidgetRef.current;
7425
+ // Scenario 1: the widget is added for the first time.
7426
+ if (!cleanupTimerRef.current) {
7427
+ if (!shouldSsr) {
7428
+ parentIndex.addWidgets([
7429
+ widget
7430
+ ]);
7431
+ }
7432
+ } else {
7433
+ // We cancel the original effect cleanup because it may not be necessary if
7434
+ // props haven't changed. (We manually call it if it is below.)
7435
+ clearTimeout(cleanupTimerRef.current);
7436
+ // Warning: if an unstable function prop is provided, `dequal` is not able
7437
+ // to keep its reference and therefore will consider that props did change.
7438
+ // This could unsollicitely remove/add the widget, therefore forget its state,
7439
+ // and could be a source of confusion.
7440
+ // If users face this issue, we should advise them to provide stable function
7441
+ // references.
7442
+ var arePropsEqual = dequal(props, prevPropsRef.current);
7443
+ // If props did change, then we execute the cleanup function instantly
7444
+ // and then add the widget back. This lets us add the widget without
7445
+ // waiting for the scheduled cleanup function to finish (that we canceled
7446
+ // above).
7447
+ if (!arePropsEqual) {
7448
+ parentIndex.removeWidgets([
7449
+ previousWidget
7450
+ ]);
7451
+ parentIndex.addWidgets([
7452
+ widget
7453
+ ]);
7454
+ }
7455
+ }
7456
+ return function() {
7457
+ // We don't remove the widget right away, but rather schedule it so that
7458
+ // we're able to cancel it in the next effect.
7459
+ cleanupTimerRef.current = setTimeout(function() {
7460
+ search._schedule(function() {
7461
+ if (search._preventWidgetCleanup) return;
7462
+ parentIndex.removeWidgets([
7463
+ previousWidget
7464
+ ]);
7465
+ });
7466
+ });
7467
+ };
7468
+ }, [
7469
+ parentIndex,
7470
+ widget,
7471
+ shouldSsr,
7472
+ search,
7473
+ props
7474
+ ]);
7475
+ if (shouldAddWidgetEarly || (waitForResultsRef === null || waitForResultsRef === void 0 ? void 0 : (_waitForResultsRef_current = waitForResultsRef.current) === null || _waitForResultsRef_current === void 0 ? void 0 : _waitForResultsRef_current.status) === 'pending') {
7476
+ parentIndex.addWidgets([
7477
+ widget
7478
+ ]);
7479
+ }
7480
+ if ((waitForResultsRef === null || waitForResultsRef === void 0 ? void 0 : waitForResultsRef.current) && !skipSuspense) {
7481
+ var _search_helper;
7482
+ use(waitForResultsRef.current);
7483
+ // If we made a second request because of two-pass widgets, we need to
7484
+ // wait for the second result — except for the two-pass widgets themselves
7485
+ // which need to render their children after the first result.
7486
+ if (!isTwoPassWidget(widget) && ((_search_helper = search.helper) === null || _search_helper === void 0 ? void 0 : _search_helper.lastResults)) {
7487
+ use(waitForResultsRef.current);
7488
+ }
7489
+ }
7490
+ if ((waitForResultsRef === null || waitForResultsRef === void 0 ? void 0 : (_waitForResultsRef_current1 = waitForResultsRef.current) === null || _waitForResultsRef_current1 === void 0 ? void 0 : _waitForResultsRef_current1.status) === 'fulfilled') {
7491
+ countRef.current += 1;
7492
+ }
7493
+ }
7494
+
7495
+ function useConnector(connector) {
7496
+ 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;
7497
+ var _ref = [
7498
+ _1,
7499
+ _2
7500
+ ], _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, [
7501
+ "skipSuspense"
7502
+ ]);
6380
7503
  var serverContext = useInstantSearchServerContext();
6381
7504
  var ssrContext = useInstantSearchSSRContext();
6382
7505
  var search = useInstantSearchContext();
@@ -6490,49 +7613,20 @@
6490
7613
  }, additionalWidgetProperties);
6491
7614
  }
6492
7615
 
6493
- function Configure(props) {
6494
- useConfigure(_object_spread({}, props), {
6495
- $$widgetType: 'ais.configure'
6496
- });
6497
- return null;
6498
- }
6499
-
6500
- function getWidgetAttribute$1(widget, initOptions) {
6501
- var _widget_getWidgetRenderState;
6502
- var renderState = (_widget_getWidgetRenderState = widget.getWidgetRenderState) === null || _widget_getWidgetRenderState === void 0 ? void 0 : _widget_getWidgetRenderState.call(widget, initOptions);
6503
- var attribute = null;
6504
- if (renderState && renderState.widgetParams) {
6505
- // casting as widgetParams is checked just before
6506
- var widgetParams = renderState.widgetParams;
6507
- if (widgetParams.attribute) {
6508
- attribute = widgetParams.attribute;
6509
- } else if (Array.isArray(widgetParams.attributes)) {
6510
- attribute = widgetParams.attributes[0];
6511
- }
6512
- }
6513
- if (typeof attribute !== 'string') {
6514
- 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."));
6515
- }
6516
- return attribute;
6517
- }
6518
-
6519
- function getObjectType(object) {
6520
- return Object.prototype.toString.call(object).slice(8, -1);
6521
- }
6522
-
6523
- function checkRendering(rendering, usage) {
6524
- if (rendering === undefined || typeof rendering !== 'function') {
6525
- throw new Error("The render function is not valid (received type ".concat(getObjectType(rendering), ").\n\n").concat(usage));
6526
- }
7616
+ function Configure(props) {
7617
+ useConfigure(_object_spread({}, props), {
7618
+ $$widgetType: 'ais.configure'
7619
+ });
7620
+ return null;
6527
7621
  }
6528
7622
 
6529
- var withUsage$s = createDocumentationMessageGenerator({
7623
+ var withUsage$t = createDocumentationMessageGenerator({
6530
7624
  name: 'dynamic-widgets',
6531
7625
  connector: true
6532
7626
  });
6533
7627
  var connectDynamicWidgets = function connectDynamicWidgets(renderFn) {
6534
7628
  var unmountFn = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop;
6535
- checkRendering(renderFn, withUsage$s());
7629
+ checkRendering(renderFn, withUsage$t());
6536
7630
  return function(widgetParams) {
6537
7631
  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 ? [
6538
7632
  '*'
@@ -6542,10 +7636,10 @@
6542
7636
  if (!(widgets && Array.isArray(widgets) && widgets.every(function(widget) {
6543
7637
  return (typeof widget === "undefined" ? "undefined" : _type_of(widget)) === 'object';
6544
7638
  }))) {
6545
- throw new Error(withUsage$s('The `widgets` option expects an array of widgets.'));
7639
+ throw new Error(withUsage$t('The `widgets` option expects an array of widgets.'));
6546
7640
  }
6547
7641
  if (!Array.isArray(facets)) {
6548
- throw new Error(withUsage$s("The `facets` option only accepts an array of facets, you passed ".concat(JSON.stringify(facets))));
7642
+ throw new Error(withUsage$t("The `facets` option only accepts an array of facets, you passed ".concat(JSON.stringify(facets))));
6549
7643
  }
6550
7644
  var localWidgets = new Map();
6551
7645
  return {
@@ -6621,36 +7715,428 @@
6621
7715
  unmountFn();
6622
7716
  },
6623
7717
  getWidgetSearchParameters: function getWidgetSearchParameters(state) {
6624
- return facets.reduce(function(acc, curr) {
6625
- return acc.addFacet(curr);
6626
- }, state.setQueryParameters({
6627
- maxValuesPerFacet: Math.max(maxValuesPerFacet || 0, state.maxValuesPerFacet || 0)
6628
- }));
7718
+ return facets.reduce(function(acc, curr) {
7719
+ return acc.addFacet(curr);
7720
+ }, state.setQueryParameters({
7721
+ maxValuesPerFacet: Math.max(maxValuesPerFacet || 0, state.maxValuesPerFacet || 0)
7722
+ }));
7723
+ },
7724
+ getRenderState: function getRenderState(renderState, renderOptions) {
7725
+ return _object_spread_props(_object_spread({}, renderState), {
7726
+ dynamicWidgets: this.getWidgetRenderState(renderOptions)
7727
+ });
7728
+ },
7729
+ getWidgetRenderState: function getWidgetRenderState(param) {
7730
+ var results = param.results;
7731
+ param.state;
7732
+ var _ref;
7733
+ var _results_renderingContent_facetOrdering_facets, _results_renderingContent_facetOrdering, _results_renderingContent;
7734
+ if (!results) {
7735
+ return {
7736
+ attributesToRender: [],
7737
+ widgetParams: widgetParams
7738
+ };
7739
+ }
7740
+ var attributesToRender = transformItems((_ref = (_results_renderingContent = results.renderingContent) === null || _results_renderingContent === void 0 ? void 0 : (_results_renderingContent_facetOrdering = _results_renderingContent.facetOrdering) === null || _results_renderingContent_facetOrdering === void 0 ? void 0 : (_results_renderingContent_facetOrdering_facets = _results_renderingContent_facetOrdering.facets) === null || _results_renderingContent_facetOrdering_facets === void 0 ? void 0 : _results_renderingContent_facetOrdering_facets.order) !== null && _ref !== void 0 ? _ref : [], {
7741
+ results: results
7742
+ });
7743
+ if (!Array.isArray(attributesToRender)) {
7744
+ throw new Error(withUsage$t('The `transformItems` option expects a function that returns an Array.'));
7745
+ }
7746
+ return {
7747
+ attributesToRender: attributesToRender,
7748
+ widgetParams: widgetParams
7749
+ };
7750
+ }
7751
+ };
7752
+ };
7753
+ };
7754
+
7755
+ function useDynamicWidgets(props, additionalWidgetProperties) {
7756
+ return useConnector(connectDynamicWidgets, _object_spread_props(_object_spread({}, props), {
7757
+ // We don't rely on InstantSearch.js for rendering widgets because React
7758
+ // directly manipulates the children.
7759
+ widgets: []
7760
+ }), additionalWidgetProperties);
7761
+ }
7762
+
7763
+ function DefaultFallbackComponent() {
7764
+ return null;
7765
+ }
7766
+ function DynamicWidgets(_0) {
7767
+ var children = _0.children, tmp = _0.fallbackComponent, Fallback = tmp === void 0 ? DefaultFallbackComponent : tmp, props = _object_without_properties(_0, [
7768
+ "children",
7769
+ "fallbackComponent"
7770
+ ]);
7771
+ var FallbackComponent = React.useRef(Fallback);
7772
+ var attributesToRender = useDynamicWidgets(props, {
7773
+ $$widgetType: 'ais.dynamicWidgets'
7774
+ }).attributesToRender;
7775
+ var widgets = new Map();
7776
+ React.Children.forEach(children, function(child) {
7777
+ var attribute = getWidgetAttribute(child);
7778
+ invariant(attribute !== undefined);
7779
+ widgets.set(attribute, child);
7780
+ });
7781
+ return /*#__PURE__*/ React.createElement(React.Fragment, null, attributesToRender.map(function(attribute) {
7782
+ return /*#__PURE__*/ React.createElement(React.Fragment, {
7783
+ key: attribute
7784
+ }, widgets.get(attribute) || /*#__PURE__*/ React.createElement(FallbackComponent.current, {
7785
+ attribute: attribute
7786
+ }));
7787
+ }));
7788
+ }
7789
+ function isReactElement(element) {
7790
+ return (typeof element === "undefined" ? "undefined" : _type_of(element)) === 'object' && element.props;
7791
+ }
7792
+ function getWidgetAttribute(element) {
7793
+ if (!isReactElement(element)) {
7794
+ return undefined;
7795
+ }
7796
+ if (element.props.attribute) {
7797
+ return element.props.attribute;
7798
+ }
7799
+ if (Array.isArray(element.props.attributes)) {
7800
+ return element.props.attributes[0];
7801
+ }
7802
+ if (element.props.children) {
7803
+ invariant(React.Children.count(element.props.children) === 1);
7804
+ return getWidgetAttribute(React.Children.only(element.props.children));
7805
+ }
7806
+ return undefined;
7807
+ }
7808
+
7809
+ function createFeedContainer(feedID, parentIndex, instantSearchInstance) {
7810
+ var localWidgets = [];
7811
+ var initialized = false;
7812
+ var container = {
7813
+ $$type: 'ais.feedContainer',
7814
+ $$widgetType: 'ais.feedContainer',
7815
+ _isolated: true,
7816
+ getIndexName: function getIndexName() {
7817
+ return parentIndex.getIndexName();
7818
+ },
7819
+ getIndexId: function getIndexId() {
7820
+ return feedID;
7821
+ },
7822
+ getHelper: function getHelper() {
7823
+ return parentIndex.getHelper();
7824
+ },
7825
+ getResults: function getResults() {
7826
+ var parentResults = parentIndex.getResults();
7827
+ if (!parentResults) return null;
7828
+ if (!parentResults.feeds) {
7829
+ // Single-feed backward compat: no feeds array means the parent result
7830
+ // itself is the only feed.
7831
+ if (feedID === '') {
7832
+ parentResults._state = parentIndex.getHelper().state;
7833
+ return parentResults;
7834
+ }
7835
+ return null;
7836
+ }
7837
+ var feed = parentResults.feeds.find(function(f) {
7838
+ return f.feedID === feedID;
7839
+ });
7840
+ if (!feed) return null;
7841
+ // Optimistic state patching — same as index widget (index.ts:365-370)
7842
+ feed._state = parentIndex.getHelper().state;
7843
+ return feed;
7844
+ },
7845
+ getResultsForWidget: function getResultsForWidget() {
7846
+ return this.getResults();
7847
+ },
7848
+ getParent: function getParent() {
7849
+ return parentIndex;
7850
+ },
7851
+ getWidgets: function getWidgets() {
7852
+ return localWidgets;
7853
+ },
7854
+ getScopedResults: function getScopedResults() {
7855
+ return parentIndex.getScopedResults();
7856
+ },
7857
+ getPreviousState: function getPreviousState() {
7858
+ return null;
7859
+ },
7860
+ createURL: function createURL(nextState) {
7861
+ return parentIndex.createURL(nextState);
7862
+ },
7863
+ scheduleLocalSearch: function scheduleLocalSearch() {
7864
+ return parentIndex.scheduleLocalSearch();
7865
+ },
7866
+ addWidgets: function addWidgets(widgets) {
7867
+ var flatWidgets = widgets.reduce(function(acc, w) {
7868
+ return acc.concat(Array.isArray(w) ? w : [
7869
+ w
7870
+ ]);
7871
+ }, []);
7872
+ flatWidgets.forEach(function(widget) {
7873
+ widget.parent = container;
7874
+ });
7875
+ localWidgets = localWidgets.concat(flatWidgets);
7876
+ if (initialized) {
7877
+ flatWidgets.forEach(function(widget) {
7878
+ if (widget.getRenderState) {
7879
+ var renderState = widget.getRenderState(instantSearchInstance.renderState[container.getIndexId()] || {}, createInitArgs(instantSearchInstance, container, instantSearchInstance._initialUiState));
7880
+ storeRenderState({
7881
+ renderState: renderState,
7882
+ instantSearchInstance: instantSearchInstance,
7883
+ parent: container
7884
+ });
7885
+ }
7886
+ });
7887
+ flatWidgets.forEach(function(widget) {
7888
+ if (widget.init) {
7889
+ widget.init(createInitArgs(instantSearchInstance, container, instantSearchInstance._initialUiState));
7890
+ }
7891
+ });
7892
+ // Merge children's search params (e.g. disjunctiveFacets) into the
7893
+ // parent's helper state so they're included in the composition request.
7894
+ // uiState is {} because URL-derived refinements are already on the
7895
+ // parent state; children only need to declare structural params.
7896
+ var parentHelper = parentIndex.getHelper();
7897
+ var withChildParams = container.getWidgetSearchParameters(parentHelper.state, {
7898
+ uiState: {}
7899
+ });
7900
+ if (withChildParams !== parentHelper.state) {
7901
+ parentHelper.setState(withChildParams);
7902
+ }
7903
+ }
7904
+ return container;
7905
+ },
7906
+ removeWidgets: function removeWidgets(widgets) {
7907
+ var flatWidgets = widgets.reduce(function(acc, w) {
7908
+ return acc.concat(Array.isArray(w) ? w : [
7909
+ w
7910
+ ]);
7911
+ }, []);
7912
+ var helper = parentIndex.getHelper();
7913
+ if (!helper) {
7914
+ localWidgets = localWidgets.filter(function(w) {
7915
+ return !flatWidgets.includes(w);
7916
+ });
7917
+ return container;
7918
+ }
7919
+ // Chain through children's dispose so widgets clean up the
7920
+ // SearchParameters they declared (e.g. RefinementList removes its
7921
+ // disjunctiveFacet) instead of leaving them stale on the parent helper.
7922
+ var cleanedState = helper.state;
7923
+ flatWidgets.forEach(function(widget) {
7924
+ if (widget.dispose) {
7925
+ var next = widget.dispose({
7926
+ helper: helper,
7927
+ state: cleanedState,
7928
+ recommendState: helper.recommendState,
7929
+ parent: container
7930
+ });
7931
+ if (_instanceof(next, algoliasearchHelper.RecommendParameters)) ;
7932
+ else if (next) {
7933
+ cleanedState = next;
7934
+ }
7935
+ }
7936
+ });
7937
+ localWidgets = localWidgets.filter(function(w) {
7938
+ return !flatWidgets.includes(w);
7939
+ });
7940
+ if (cleanedState !== helper.state) {
7941
+ helper.setState(cleanedState);
7942
+ }
7943
+ return container;
7944
+ },
7945
+ init: function init() {
7946
+ initialized = true;
7947
+ localWidgets.forEach(function(widget) {
7948
+ if (widget.getRenderState) {
7949
+ var renderState = widget.getRenderState(instantSearchInstance.renderState[container.getIndexId()] || {}, createInitArgs(instantSearchInstance, container, instantSearchInstance._initialUiState));
7950
+ storeRenderState({
7951
+ renderState: renderState,
7952
+ instantSearchInstance: instantSearchInstance,
7953
+ parent: container
7954
+ });
7955
+ }
7956
+ });
7957
+ localWidgets.forEach(function(widget) {
7958
+ if (widget.init) {
7959
+ widget.init(createInitArgs(instantSearchInstance, container, instantSearchInstance._initialUiState));
7960
+ }
7961
+ });
7962
+ },
7963
+ render: function render() {
7964
+ localWidgets.forEach(function(widget) {
7965
+ if (widget.getRenderState) {
7966
+ var renderState = widget.getRenderState(instantSearchInstance.renderState[container.getIndexId()] || {}, createRenderArgs(instantSearchInstance, container, widget));
7967
+ storeRenderState({
7968
+ renderState: renderState,
7969
+ instantSearchInstance: instantSearchInstance,
7970
+ parent: container
7971
+ });
7972
+ }
7973
+ });
7974
+ localWidgets.forEach(function(widget) {
7975
+ if (widget.render) {
7976
+ widget.render(createRenderArgs(instantSearchInstance, container, widget));
7977
+ }
7978
+ });
7979
+ },
7980
+ dispose: function dispose(disposeOptions) {
7981
+ var _ref;
7982
+ var helper = parentIndex.getHelper();
7983
+ // Chain through children's dispose to return a cleaned state
7984
+ // (e.g. RefinementList.dispose removes its disjunctiveFacet declaration).
7985
+ // This mirrors how the index widget's removeWidgets chains dispose calls.
7986
+ 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;
7987
+ localWidgets.forEach(function(widget) {
7988
+ if (widget.dispose && helper) {
7989
+ var next = widget.dispose({
7990
+ helper: helper,
7991
+ state: cleanedState,
7992
+ recommendState: helper.recommendState,
7993
+ parent: container
7994
+ });
7995
+ if (_instanceof(next, algoliasearchHelper.RecommendParameters)) ;
7996
+ else if (next) {
7997
+ cleanedState = next;
7998
+ }
7999
+ }
8000
+ });
8001
+ localWidgets = [];
8002
+ initialized = false;
8003
+ return cleanedState;
8004
+ },
8005
+ getWidgetState: function getWidgetState(uiState) {
8006
+ return this.getWidgetUiState(uiState);
8007
+ },
8008
+ getWidgetUiState: function getWidgetUiState(uiState) {
8009
+ var helper = parentIndex.getHelper();
8010
+ var widgetUiStateOptions = {
8011
+ searchParameters: helper.state,
8012
+ helper: helper
8013
+ };
8014
+ return localWidgets.reduce(function(state, widget) {
8015
+ return widget.getWidgetUiState ? widget.getWidgetUiState(state, widgetUiStateOptions) : state;
8016
+ }, uiState);
8017
+ },
8018
+ getWidgetSearchParameters: function getWidgetSearchParameters(searchParameters, param) {
8019
+ var uiState = param.uiState;
8020
+ return localWidgets.reduce(function(params, widget) {
8021
+ return widget.getWidgetSearchParameters ? widget.getWidgetSearchParameters(params, {
8022
+ uiState: uiState
8023
+ }) : params;
8024
+ }, searchParameters);
8025
+ },
8026
+ refreshUiState: function refreshUiState() {
8027
+ // no-op: FeedContainer doesn't own UI state
8028
+ },
8029
+ setIndexUiState: function setIndexUiState() {
8030
+ // no-op: FeedContainer delegates to parent
8031
+ }
8032
+ };
8033
+ return container;
8034
+ }
8035
+
8036
+ function toFeedSearchResults(state, raw) {
8037
+ return Object.assign(new algoliasearchHelper.SearchResults(state, [
8038
+ raw
8039
+ ]), {
8040
+ feedID: raw.feedID
8041
+ });
8042
+ }
8043
+ /**
8044
+ * Rebuild `lastResults.feeds` from `_initialResults.compositionFeedsResults`
8045
+ * because the index-widget hydration only restores `lastResults` (the merged
8046
+ * view), not the per-feed breakdown that the Feeds connector needs.
8047
+ */ function hydrateFeedsFromInitialResultsIfNeeded(instantSearchInstance, parent) {
8048
+ var _instantSearchInstance__initialResults, _parent_getHelper;
8049
+ var initial = (_instantSearchInstance__initialResults = instantSearchInstance._initialResults) === null || _instantSearchInstance__initialResults === void 0 ? void 0 : _instantSearchInstance__initialResults[parent.getIndexId()];
8050
+ var compositionFeedsResults = (initial === null || initial === void 0 ? void 0 : initial.compositionFeedsResults) || [];
8051
+ if (compositionFeedsResults.length === 0) {
8052
+ return;
8053
+ }
8054
+ var lastResults = (_parent_getHelper = parent.getHelper()) === null || _parent_getHelper === void 0 ? void 0 : _parent_getHelper.lastResults;
8055
+ if (!lastResults) {
8056
+ return;
8057
+ }
8058
+ if (lastResults.feeds && lastResults.feeds.length > 0) {
8059
+ return;
8060
+ }
8061
+ lastResults.feeds = compositionFeedsResults.map(function(raw) {
8062
+ return toFeedSearchResults(lastResults._state, raw);
8063
+ });
8064
+ }
8065
+ var withUsage$s = createDocumentationMessageGenerator({
8066
+ name: 'feeds',
8067
+ connector: true
8068
+ });
8069
+ var connectFeeds = function connectFeeds(renderFn) {
8070
+ var unmountFn = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop;
8071
+ checkRendering(renderFn, withUsage$s());
8072
+ return function(widgetParams) {
8073
+ var searchScope = widgetParams.searchScope, _widgetParams_transformFeeds = widgetParams.transformFeeds, transformFeeds = _widgetParams_transformFeeds === void 0 ? function(feeds) {
8074
+ return feeds;
8075
+ } : _widgetParams_transformFeeds;
8076
+ if (searchScope !== 'global') {
8077
+ throw new Error(withUsage$s('The `searchScope` option currently only supports "global".'));
8078
+ }
8079
+ return {
8080
+ $$type: 'ais.feeds',
8081
+ $$widgetType: 'ais.feeds',
8082
+ init: function init(initOptions) {
8083
+ var instantSearchInstance = initOptions.instantSearchInstance;
8084
+ if (!instantSearchInstance.compositionID) {
8085
+ throw new Error(withUsage$s('The `feeds` widget requires a composition-based InstantSearch instance (compositionID must be set).'));
8086
+ }
8087
+ hydrateFeedsFromInitialResultsIfNeeded(instantSearchInstance, initOptions.parent);
8088
+ renderFn(_object_spread_props(_object_spread({}, this.getWidgetRenderState(initOptions)), {
8089
+ instantSearchInstance: instantSearchInstance
8090
+ }), true);
8091
+ },
8092
+ render: function render(renderOptions) {
8093
+ var instantSearchInstance = renderOptions.instantSearchInstance;
8094
+ renderFn(_object_spread_props(_object_spread({}, this.getWidgetRenderState(renderOptions)), {
8095
+ instantSearchInstance: instantSearchInstance
8096
+ }), false);
8097
+ },
8098
+ dispose: function dispose() {
8099
+ unmountFn();
8100
+ },
8101
+ getWidgetSearchParameters: function getWidgetSearchParameters(state) {
8102
+ return state;
6629
8103
  },
6630
8104
  getRenderState: function getRenderState(renderState, renderOptions) {
6631
8105
  return _object_spread_props(_object_spread({}, renderState), {
6632
- dynamicWidgets: this.getWidgetRenderState(renderOptions)
8106
+ feeds: this.getWidgetRenderState(renderOptions)
6633
8107
  });
6634
8108
  },
6635
8109
  getWidgetRenderState: function getWidgetRenderState(param) {
6636
8110
  var results = param.results;
6637
- param.state;
6638
- var _ref;
6639
- var _results_renderingContent_facetOrdering_facets, _results_renderingContent_facetOrdering, _results_renderingContent;
6640
8111
  if (!results) {
6641
8112
  return {
6642
- attributesToRender: [],
8113
+ feedIDs: [],
6643
8114
  widgetParams: widgetParams
6644
8115
  };
6645
8116
  }
6646
- var attributesToRender = transformItems((_ref = (_results_renderingContent = results.renderingContent) === null || _results_renderingContent === void 0 ? void 0 : (_results_renderingContent_facetOrdering = _results_renderingContent.facetOrdering) === null || _results_renderingContent_facetOrdering === void 0 ? void 0 : (_results_renderingContent_facetOrdering_facets = _results_renderingContent_facetOrdering.facets) === null || _results_renderingContent_facetOrdering_facets === void 0 ? void 0 : _results_renderingContent_facetOrdering_facets.order) !== null && _ref !== void 0 ? _ref : [], {
6647
- results: results
6648
- });
6649
- if (!Array.isArray(attributesToRender)) {
6650
- throw new Error(withUsage$s('The `transformItems` option expects a function that returns an Array.'));
8117
+ if (Array.isArray(results.feeds) && results.feeds.length > 0 && !results.feeds.every(function(feed) {
8118
+ return _instanceof(feed, algoliasearchHelper.SearchResults);
8119
+ })) {
8120
+ results.feeds = results.feeds.map(function(feed) {
8121
+ return _instanceof(feed, algoliasearchHelper.SearchResults) ? feed : toFeedSearchResults(results._state, feed);
8122
+ });
8123
+ }
8124
+ var feedIDs = results.feeds ? results.feeds.map(function(f) {
8125
+ return f.feedID;
8126
+ }) : [
8127
+ ''
8128
+ ];
8129
+ feedIDs = transformFeeds(feedIDs);
8130
+ if (!Array.isArray(feedIDs)) {
8131
+ throw new Error(withUsage$s('The `transformFeeds` option expects a function that returns an Array.'));
8132
+ }
8133
+ if (!feedIDs.every(function(feedID) {
8134
+ return typeof feedID === 'string';
8135
+ })) {
8136
+ throw new Error(withUsage$s('The `transformFeeds` option expects a function that returns an array of feed IDs (strings).'));
6651
8137
  }
6652
8138
  return {
6653
- attributesToRender: attributesToRender,
8139
+ feedIDs: feedIDs,
6654
8140
  widgetParams: widgetParams
6655
8141
  };
6656
8142
  }
@@ -6658,174 +8144,104 @@
6658
8144
  };
6659
8145
  };
6660
8146
 
6661
- function useDynamicWidgets(props, additionalWidgetProperties) {
6662
- return useConnector(connectDynamicWidgets, _object_spread_props(_object_spread({}, props), {
6663
- // We don't rely on InstantSearch.js for rendering widgets because React
6664
- // directly manipulates the children.
6665
- widgets: []
6666
- }), additionalWidgetProperties);
8147
+ function useFeeds(props, additionalWidgetProperties) {
8148
+ return useConnector(connectFeeds, props, additionalWidgetProperties);
6667
8149
  }
6668
8150
 
6669
- function DefaultFallbackComponent() {
6670
- return null;
6671
- }
6672
- function DynamicWidgets(_0) {
6673
- var children = _0.children, tmp = _0.fallbackComponent, Fallback = tmp === void 0 ? DefaultFallbackComponent : tmp, props = _object_without_properties(_0, [
6674
- "children",
6675
- "fallbackComponent"
8151
+ function Feeds(_0) {
8152
+ var renderFeed = _0.renderFeed, props = _object_without_properties(_0, [
8153
+ "renderFeed"
6676
8154
  ]);
6677
- var FallbackComponent = React.useRef(Fallback);
6678
- var attributesToRender = useDynamicWidgets(props, {
6679
- $$widgetType: 'ais.dynamicWidgets'
6680
- }).attributesToRender;
6681
- var widgets = new Map();
6682
- React.Children.forEach(children, function(child) {
6683
- var attribute = getWidgetAttribute(child);
6684
- invariant(attribute !== undefined);
6685
- widgets.set(attribute, child);
8155
+ var feedIDs = useFeeds(props, {
8156
+ $$widgetType: 'ais.feeds'
8157
+ }).feedIDs;
8158
+ var parentIndex = useIndexContext();
8159
+ var instantSearchInstance = useInstantSearchContext();
8160
+ var feedContainersRef = React.useRef(new Map());
8161
+ var removalTimerRef = React.useRef(null);
8162
+ var pendingRemovalsRef = React.useRef(new Map());
8163
+ // Create and register new FeedContainers synchronously so SSR and the first
8164
+ // client render can provide the matching feed index context to children.
8165
+ var toAdd = [];
8166
+ feedIDs.forEach(function(feedID) {
8167
+ if (!feedContainersRef.current.has(feedID)) {
8168
+ var pendingContainer = pendingRemovalsRef.current.get(feedID);
8169
+ if (pendingContainer) {
8170
+ pendingRemovalsRef.current.delete(feedID);
8171
+ feedContainersRef.current.set(feedID, pendingContainer);
8172
+ return;
8173
+ }
8174
+ var container = createFeedContainer(feedID, parentIndex, instantSearchInstance);
8175
+ feedContainersRef.current.set(feedID, container);
8176
+ toAdd.push(container);
8177
+ }
6686
8178
  });
6687
- return /*#__PURE__*/ React.createElement(React.Fragment, null, attributesToRender.map(function(attribute) {
6688
- return /*#__PURE__*/ React.createElement(React.Fragment, {
6689
- key: attribute
6690
- }, widgets.get(attribute) || /*#__PURE__*/ React.createElement(FallbackComponent.current, {
6691
- attribute: attribute
6692
- }));
6693
- }));
6694
- }
6695
- function isReactElement(element) {
6696
- return (typeof element === "undefined" ? "undefined" : _type_of(element)) === 'object' && element.props;
6697
- }
6698
- function getWidgetAttribute(element) {
6699
- if (!isReactElement(element)) {
6700
- return undefined;
6701
- }
6702
- if (element.props.attribute) {
6703
- return element.props.attribute;
6704
- }
6705
- if (Array.isArray(element.props.attributes)) {
6706
- return element.props.attributes[0];
6707
- }
6708
- if (element.props.children) {
6709
- invariant(React.Children.count(element.props.children) === 1);
6710
- return getWidgetAttribute(React.Children.only(element.props.children));
6711
- }
6712
- return undefined;
6713
- }
6714
-
6715
- function _array_without_holes(arr) {
6716
- if (Array.isArray(arr)) return _array_like_to_array(arr);
6717
- }
6718
-
6719
- function _non_iterable_spread() {
6720
- throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
6721
- }
6722
-
6723
- function _to_consumable_array(arr) {
6724
- return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
6725
- }
6726
-
6727
- var id$1 = 0;
6728
- function addWidgetId(widget) {
6729
- if (widget.dependsOn !== 'recommend') {
6730
- return;
8179
+ if (toAdd.length > 0) {
8180
+ parentIndex.addWidgets(toAdd);
6731
8181
  }
6732
- widget.$$id = id$1++;
6733
- }
6734
- function resetWidgetId() {
6735
- id$1 = 0;
6736
- }
6737
-
6738
- function isIndexWidget(widget) {
6739
- return widget.$$type === 'ais.index';
6740
- }
6741
-
6742
- var nextMicroTask = Promise.resolve();
6743
- function defer(callback) {
6744
- var progress = null;
6745
- var cancelled = false;
6746
- var fn = function fn() {
6747
- for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
6748
- args[_key] = arguments[_key];
6749
- }
6750
- if (progress !== null) {
6751
- return;
6752
- }
6753
- progress = nextMicroTask.then(function() {
6754
- progress = null;
6755
- if (cancelled) {
6756
- cancelled = false;
6757
- return;
8182
+ // Remove containers that are no longer in feedIDs (deferred to match useWidget pattern).
8183
+ React.useEffect(function() {
8184
+ var containers = feedContainersRef.current;
8185
+ var activeSet = new Set(feedIDs);
8186
+ var toRemove = [];
8187
+ containers.forEach(function(container, id) {
8188
+ if (!activeSet.has(id)) {
8189
+ toRemove.push([
8190
+ id,
8191
+ container
8192
+ ]);
8193
+ containers.delete(id);
6758
8194
  }
6759
- callback.apply(void 0, _to_consumable_array(args));
6760
8195
  });
6761
- };
6762
- fn.wait = function() {
6763
- if (progress === null) {
6764
- throw new Error('The deferred function should be called before calling `wait()`');
8196
+ if (toRemove.length > 0) {
8197
+ toRemove.forEach(function(param) {
8198
+ var _param = _sliced_to_array(param, 2), id = _param[0], container = _param[1];
8199
+ pendingRemovalsRef.current.set(id, container);
8200
+ });
8201
+ if (removalTimerRef.current !== null) {
8202
+ clearTimeout(removalTimerRef.current);
8203
+ }
8204
+ removalTimerRef.current = setTimeout(function() {
8205
+ var widgetsToRemove = Array.from(pendingRemovalsRef.current.values());
8206
+ pendingRemovalsRef.current.clear();
8207
+ removalTimerRef.current = null;
8208
+ if (widgetsToRemove.length > 0) {
8209
+ parentIndex.removeWidgets(widgetsToRemove);
8210
+ }
8211
+ }, 0);
6765
8212
  }
6766
- return progress;
6767
- };
6768
- fn.cancel = function() {
6769
- if (progress === null) {
6770
- return;
8213
+ }, [
8214
+ feedIDs,
8215
+ parentIndex
8216
+ ]);
8217
+ React.useEffect(function() {
8218
+ return function() {
8219
+ if (removalTimerRef.current !== null) {
8220
+ clearTimeout(removalTimerRef.current);
8221
+ removalTimerRef.current = null;
8222
+ }
8223
+ var containers = feedContainersRef.current;
8224
+ var toRemove = Array.from(new Set(_to_consumable_array(containers.values()).concat(_to_consumable_array(pendingRemovalsRef.current.values()))));
8225
+ pendingRemovalsRef.current.clear();
8226
+ containers.clear();
8227
+ if (toRemove.length > 0) {
8228
+ parentIndex.removeWidgets(toRemove);
8229
+ }
8230
+ };
8231
+ // eslint-disable-next-line react-hooks/exhaustive-deps
8232
+ }, []);
8233
+ return /*#__PURE__*/ React.createElement(React.Fragment, null, feedIDs.map(function(feedID) {
8234
+ var container = feedContainersRef.current.get(feedID);
8235
+ if (!container) {
8236
+ return null;
6771
8237
  }
6772
- cancelled = true;
6773
- };
6774
- return fn;
6775
- }
6776
-
6777
- function resolveSearchParameters(current) {
6778
- var parent = current.getParent();
6779
- var states = [
6780
- current.getHelper().state
6781
- ];
6782
- while(parent !== null){
6783
- states = [
6784
- parent.getHelper().state
6785
- ].concat(states);
6786
- parent = parent.getParent();
6787
- }
6788
- return states;
6789
- }
6790
-
6791
- function createInitArgs(instantSearchInstance, parent, uiState) {
6792
- var helper = parent.getHelper();
6793
- return {
6794
- uiState: uiState,
6795
- helper: helper,
6796
- parent: parent,
6797
- instantSearchInstance: instantSearchInstance,
6798
- state: helper.state,
6799
- renderState: instantSearchInstance.renderState,
6800
- templatesConfig: instantSearchInstance.templatesConfig,
6801
- createURL: parent.createURL,
6802
- scopedResults: [],
6803
- searchMetadata: {
6804
- isSearchStalled: instantSearchInstance.status === 'stalled'
6805
- },
6806
- status: instantSearchInstance.status,
6807
- error: instantSearchInstance.error
6808
- };
6809
- }
6810
- function createRenderArgs(instantSearchInstance, parent, widget) {
6811
- var results = parent.getResultsForWidget(widget);
6812
- var helper = parent.getHelper();
6813
- return {
6814
- helper: helper,
6815
- parent: parent,
6816
- instantSearchInstance: instantSearchInstance,
6817
- results: results,
6818
- scopedResults: parent.getScopedResults(),
6819
- state: results && '_state' in results ? results._state : helper.state,
6820
- renderState: instantSearchInstance.renderState,
6821
- templatesConfig: instantSearchInstance.templatesConfig,
6822
- createURL: parent.createURL,
6823
- searchMetadata: {
6824
- isSearchStalled: instantSearchInstance.status === 'stalled'
6825
- },
6826
- status: instantSearchInstance.status,
6827
- error: instantSearchInstance.error
6828
- };
8238
+ return /*#__PURE__*/ React.createElement(IndexContext.Provider, {
8239
+ key: feedID,
8240
+ value: container
8241
+ }, renderFeed({
8242
+ feedID: feedID
8243
+ }));
8244
+ }));
6829
8245
  }
6830
8246
 
6831
8247
  var withUsage$r = createDocumentationMessageGenerator({
@@ -7445,11 +8861,6 @@
7445
8861
  }
7446
8862
  };
7447
8863
  };
7448
- function storeRenderState(param) {
7449
- var renderState = param.renderState, instantSearchInstance = param.instantSearchInstance, parent = param.parent;
7450
- var parentIndexName = parent ? parent.getIndexId() : instantSearchInstance.mainIndex.getIndexId();
7451
- instantSearchInstance.renderState = _object_spread_props(_object_spread({}, instantSearchInstance.renderState), _define_property({}, parentIndexName, _object_spread({}, instantSearchInstance.renderState[parentIndexName], renderState)));
7452
- }
7453
8864
  /**
7454
8865
  * Walk up the parent chain to find the closest isolated index, or fall back to mainHelper
7455
8866
  */ function nearestIsolatedHelper(current, mainHelper) {
@@ -7613,99 +9024,32 @@
7613
9024
  */ function createUUID() {
7614
9025
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
7615
9026
  /* eslint-disable no-bitwise */ var r = Math.random() * 16 | 0;
7616
- var v = c === 'x' ? r : r & 0x3 | 0x8;
7617
- /* eslint-enable */ return v.toString(16);
7618
- });
7619
- }
7620
-
7621
- var ANONYMOUS_TOKEN_COOKIE_KEY = '_ALGOLIA';
7622
- function getCookie(name) {
7623
- if ((typeof document === "undefined" ? "undefined" : _type_of(document)) !== 'object' || typeof document.cookie !== 'string') {
7624
- return undefined;
7625
- }
7626
- var prefix = "".concat(name, "=");
7627
- var cookies = document.cookie.split(';');
7628
- for(var i = 0; i < cookies.length; i++){
7629
- var cookie = cookies[i];
7630
- while(cookie.charAt(0) === ' '){
7631
- cookie = cookie.substring(1);
7632
- }
7633
- if (cookie.indexOf(prefix) === 0) {
7634
- return cookie.substring(prefix.length, cookie.length);
7635
- }
7636
- }
7637
- return undefined;
7638
- }
7639
- function getInsightsAnonymousUserTokenInternal() {
7640
- return getCookie(ANONYMOUS_TOKEN_COOKIE_KEY);
7641
- }
7642
-
7643
- // eslint-disable-next-line no-restricted-globals
7644
- /**
7645
- * Runs code on browser environments safely.
7646
- */ function safelyRunOnBrowser(callback) {
7647
- var fallback = (arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
7648
- fallback: function fallback() {
7649
- return undefined;
7650
- }
7651
- }).fallback;
7652
- // eslint-disable-next-line no-restricted-globals
7653
- if (typeof window === 'undefined') {
7654
- return fallback();
7655
- }
7656
- // eslint-disable-next-line no-restricted-globals
7657
- return callback({
7658
- window: window
9027
+ var v = c === 'x' ? r : r & 0x3 | 0x8;
9028
+ /* eslint-enable */ return v.toString(16);
7659
9029
  });
7660
9030
  }
7661
9031
 
7662
- // typed as any, since it accepts the _real_ js clients, not the interface we otherwise expect
7663
- function getAppIdAndApiKey(searchClient) {
7664
- if (searchClient.appId && searchClient.apiKey) {
7665
- // searchClient v5
7666
- return [
7667
- searchClient.appId,
7668
- searchClient.apiKey
7669
- ];
7670
- } else if (searchClient.transporter) {
7671
- // searchClient v4 or v5
7672
- var transporter = searchClient.transporter;
7673
- var headers = transporter.headers || transporter.baseHeaders;
7674
- var queryParameters = transporter.queryParameters || transporter.baseQueryParameters;
7675
- var APP_ID = 'x-algolia-application-id';
7676
- var API_KEY = 'x-algolia-api-key';
7677
- var appId = headers[APP_ID] || queryParameters[APP_ID];
7678
- var apiKey = headers[API_KEY] || queryParameters[API_KEY];
7679
- return [
7680
- appId,
7681
- apiKey
7682
- ];
7683
- } else {
7684
- // searchClient v3
7685
- return [
7686
- searchClient.applicationID,
7687
- searchClient.apiKey
7688
- ];
9032
+ var ANONYMOUS_TOKEN_COOKIE_KEY = '_ALGOLIA';
9033
+ function getCookie(name) {
9034
+ if ((typeof document === "undefined" ? "undefined" : _type_of(document)) !== 'object' || typeof document.cookie !== 'string') {
9035
+ return undefined;
7689
9036
  }
7690
- }
7691
-
7692
- // We aren't using the native `Array.prototype.find` because the refactor away from Lodash is not
7693
- // published as a major version.
7694
- // Relying on the `find` polyfill on user-land, which before was only required for niche use-cases,
7695
- // was decided as too risky.
7696
- // @MAJOR Replace with the native `Array.prototype.find` method
7697
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
7698
- function find$1(items, predicate) {
7699
- var value;
7700
- for(var i = 0; i < items.length; i++){
7701
- value = items[i];
7702
- // inlined for performance: if (Call(predicate, thisArg, [value, i, list])) {
7703
- if (predicate(value, i, items)) {
7704
- return value;
9037
+ var prefix = "".concat(name, "=");
9038
+ var cookies = document.cookie.split(';');
9039
+ for(var i = 0; i < cookies.length; i++){
9040
+ var cookie = cookies[i];
9041
+ while(cookie.charAt(0) === ' '){
9042
+ cookie = cookie.substring(1);
9043
+ }
9044
+ if (cookie.indexOf(prefix) === 0) {
9045
+ return cookie.substring(prefix.length, cookie.length);
7705
9046
  }
7706
9047
  }
7707
9048
  return undefined;
7708
9049
  }
9050
+ function getInsightsAnonymousUserTokenInternal() {
9051
+ return getCookie(ANONYMOUS_TOKEN_COOKIE_KEY);
9052
+ }
7709
9053
 
7710
9054
  var ALGOLIA_INSIGHTS_VERSION = '2.17.2';
7711
9055
  var ALGOLIA_INSIGHTS_SRC = "https://cdn.jsdelivr.net/npm/search-insights@".concat(ALGOLIA_INSIGHTS_VERSION, "/dist/search-insights.min.js");
@@ -8021,11 +9365,6 @@
8021
9365
  return typeof userToken === 'number' ? userToken.toString() : userToken;
8022
9366
  }
8023
9367
 
8024
- function getAlgoliaAgent(client) {
8025
- var clientTyped = client;
8026
- return clientTyped.transporter && clientTyped.transporter.userAgent ? clientTyped.transporter.userAgent.value : clientTyped._ua;
8027
- }
8028
-
8029
9368
  function extractWidgetPayload(widgets, instantSearchInstance, payload) {
8030
9369
  var initOptions = createInitArgs(instantSearchInstance, instantSearchInstance.mainIndex, instantSearchInstance._initialUiState);
8031
9370
  widgets.forEach(function(widget) {
@@ -8046,7 +9385,7 @@
8046
9385
  widgetType: widget.$$widgetType,
8047
9386
  params: params
8048
9387
  });
8049
- if (widget.$$type === 'ais.index') {
9388
+ if (isIndexWidget(widget)) {
8050
9389
  extractWidgetPayload(widget.getWidgets(), instantSearchInstance, payload);
8051
9390
  }
8052
9391
  });
@@ -9261,55 +10600,16 @@
9261
10600
  routeToState: function routeToState() {
9262
10601
  var routeState = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
9263
10602
  return Object.keys(routeState).reduce(function(state, indexId) {
9264
- return _object_spread_props(_object_spread({}, state), _define_property({}, indexId, getIndexStateWithoutConfigure(routeState[indexId])));
10603
+ var indexState = routeState[indexId];
10604
+ if ((typeof indexState === "undefined" ? "undefined" : _type_of(indexState)) !== 'object' || indexState === null) {
10605
+ return state;
10606
+ }
10607
+ return _object_spread_props(_object_spread({}, state), _define_property({}, indexId, getIndexStateWithoutConfigure(indexState)));
9265
10608
  }, {});
9266
10609
  }
9267
10610
  };
9268
10611
  }
9269
10612
 
9270
- function isPrimitive(obj) {
9271
- return obj !== Object(obj);
9272
- }
9273
- function isEqual(first, second) {
9274
- if (first === second) {
9275
- return true;
9276
- }
9277
- if (isPrimitive(first) || isPrimitive(second) || typeof first === 'function' || typeof second === 'function') {
9278
- return first === second;
9279
- }
9280
- if (Object.keys(first).length !== Object.keys(second).length) {
9281
- return false;
9282
- }
9283
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
9284
- try {
9285
- // @TODO avoid for..of because of the large polyfill
9286
- // eslint-disable-next-line instantsearch/no-for-of
9287
- for(var _iterator = Object.keys(first)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
9288
- var key = _step.value;
9289
- if (!(key in second)) {
9290
- return false;
9291
- }
9292
- if (!isEqual(first[key], second[key])) {
9293
- return false;
9294
- }
9295
- }
9296
- } catch (err) {
9297
- _didIteratorError = true;
9298
- _iteratorError = err;
9299
- } finally{
9300
- try {
9301
- if (!_iteratorNormalCompletion && _iterator.return != null) {
9302
- _iterator.return();
9303
- }
9304
- } finally{
9305
- if (_didIteratorError) {
9306
- throw _iteratorError;
9307
- }
9308
- }
9309
- }
9310
- return true;
9311
- }
9312
-
9313
10613
  var createRouterMiddleware = function createRouterMiddleware() {
9314
10614
  var props = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
9315
10615
  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>.
@@ -9343,166 +10643,43 @@
9343
10643
  var uiState = param.uiState;
9344
10644
  var routeState = stateMapping.stateToRoute(uiState);
9345
10645
  if (lastRouteState === undefined || !isEqual(lastRouteState, routeState)) {
9346
- router.write(routeState);
9347
- lastRouteState = routeState;
9348
- }
9349
- },
9350
- subscribe: function subscribe() {
9351
- instantSearchInstance._initialUiState = _object_spread({}, initialUiState, stateMapping.routeToState(router.read()));
9352
- router.onUpdate(function(route) {
9353
- if (instantSearchInstance.mainIndex.getWidgets().length > 0) {
9354
- instantSearchInstance.setUiState(stateMapping.routeToState(route));
9355
- }
9356
- });
9357
- },
9358
- started: function started() {
9359
- var _router_start;
9360
- (_router_start = router.start) === null || _router_start === void 0 ? void 0 : _router_start.call(router);
9361
- },
9362
- unsubscribe: function unsubscribe() {
9363
- router.dispose();
9364
- }
9365
- };
9366
- };
9367
- };
9368
-
9369
- function formatNumber(value, numberLocale) {
9370
- return value.toLocaleString(numberLocale);
9371
- }
9372
-
9373
- var NAMESPACE = 'ais';
9374
- var component = function component(componentName) {
9375
- return function() {
9376
- var _ref = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, descendantName = _ref.descendantName, modifierName = _ref.modifierName;
9377
- var descendent = descendantName ? "-".concat(descendantName) : '';
9378
- var modifier = modifierName ? "--".concat(modifierName) : '';
9379
- return "".concat(NAMESPACE, "-").concat(componentName).concat(descendent).concat(modifier);
9380
- };
9381
- };
9382
-
9383
- function getPropertyByPath(object, path) {
9384
- var parts = Array.isArray(path) ? path : path.split('.');
9385
- return parts.reduce(function(current, key) {
9386
- return current && current[key];
9387
- }, object);
9388
- }
9389
-
9390
- function _extends() {
9391
- _extends = Object.assign || function assign(target) {
9392
- for (var i = 1; i < arguments.length; i++) {
9393
- var source = arguments[i];
9394
- for (var key in source) if (Object.prototype.hasOwnProperty.call(source, key)) target[key] = source[key];
9395
- }
9396
-
9397
- return target;
9398
- };
9399
-
9400
- return _extends.apply(this, arguments);
9401
- }
9402
-
9403
- function _object_destructuring_empty(o) {
9404
- if (o === null || o === void 0) throw new TypeError("Cannot destructure " + o);
9405
-
9406
- return o;
9407
- }
9408
-
9409
- /**
9410
- * This implementation is taken from Lodash implementation.
9411
- * See: https://github.com/lodash/lodash/blob/4.17.11-npm/escape.js
9412
- */ // Used to map characters to HTML entities.
9413
- var htmlEntities = {
9414
- '&': '&amp;',
9415
- '<': '&lt;',
9416
- '>': '&gt;',
9417
- '"': '&quot;',
9418
- "'": '&#39;'
9419
- };
9420
- // Used to match HTML entities and HTML characters.
9421
- var regexUnescapedHtml = /[&<>"']/g;
9422
- var regexHasUnescapedHtml = RegExp(regexUnescapedHtml.source);
9423
- /**
9424
- * Converts the characters "&", "<", ">", '"', and "'" in `string` to their
9425
- * corresponding HTML entities.
9426
- */ function escape$1(value) {
9427
- return value && regexHasUnescapedHtml.test(value) ? value.replace(regexUnescapedHtml, function(character) {
9428
- return htmlEntities[character];
9429
- }) : value;
9430
- }
9431
- /**
9432
- * This implementation is taken from Lodash implementation.
9433
- * See: https://github.com/lodash/lodash/blob/4.17.11-npm/unescape.js
9434
- */ // Used to map HTML entities to characters.
9435
- var htmlCharacters = {
9436
- '&amp;': '&',
9437
- '&lt;': '<',
9438
- '&gt;': '>',
9439
- '&quot;': '"',
9440
- '&#39;': "'"
9441
- };
9442
- // Used to match HTML entities and HTML characters.
9443
- var regexEscapedHtml = /&(amp|quot|lt|gt|#39);/g;
9444
- var regexHasEscapedHtml = RegExp(regexEscapedHtml.source);
9445
- /**
9446
- * Converts the HTML entities "&", "<", ">", '"', and "'" in `string` to their
9447
- * characters.
9448
- */ function unescape$1(value) {
9449
- return value && regexHasEscapedHtml.test(value) ? value.replace(regexEscapedHtml, function(character) {
9450
- return htmlCharacters[character];
9451
- }) : value;
9452
- }
9453
-
9454
- var TAG_PLACEHOLDER = {
9455
- highlightPreTag: '__ais-highlight__',
9456
- highlightPostTag: '__/ais-highlight__'
9457
- };
9458
- var TAG_REPLACEMENT = {
9459
- highlightPreTag: '<mark>',
9460
- highlightPostTag: '</mark>'
9461
- };
9462
- // @MAJOR: in the future, this should only escape, not replace
9463
- function replaceTagsAndEscape(value) {
9464
- return escape$1(value).replace(new RegExp(TAG_PLACEHOLDER.highlightPreTag, 'g'), TAG_REPLACEMENT.highlightPreTag).replace(new RegExp(TAG_PLACEHOLDER.highlightPostTag, 'g'), TAG_REPLACEMENT.highlightPostTag);
9465
- }
9466
- function recursiveEscape(input) {
9467
- if (isPlainObject(input) && typeof input.value !== 'string') {
9468
- return Object.keys(input).reduce(function(acc, key) {
9469
- return _object_spread_props(_object_spread({}, acc), _define_property({}, key, recursiveEscape(input[key])));
9470
- }, {});
9471
- }
9472
- if (Array.isArray(input)) {
9473
- return input.map(recursiveEscape);
9474
- }
9475
- return _object_spread_props(_object_spread({}, input), {
9476
- value: replaceTagsAndEscape(input.value)
9477
- });
9478
- }
9479
- function escapeHits(hits) {
9480
- if (hits.__escaped === undefined) {
9481
- // We don't override the value on hit because it will mutate the raw results
9482
- // instead we make a shallow copy and we assign the escaped values on it.
9483
- hits = hits.map(function(_0) {
9484
- _object_destructuring_empty(_0);
9485
- var hit = _extends({}, _0);
9486
- if (hit._highlightResult) {
9487
- hit._highlightResult = recursiveEscape(hit._highlightResult);
9488
- }
9489
- if (hit._snippetResult) {
9490
- hit._snippetResult = recursiveEscape(hit._snippetResult);
10646
+ router.write(routeState);
10647
+ lastRouteState = routeState;
10648
+ }
10649
+ },
10650
+ subscribe: function subscribe() {
10651
+ instantSearchInstance._initialUiState = _object_spread({}, initialUiState, stateMapping.routeToState(router.read()));
10652
+ router.onUpdate(function(route) {
10653
+ if (instantSearchInstance.mainIndex.getWidgets().length > 0) {
10654
+ instantSearchInstance.setUiState(stateMapping.routeToState(route));
10655
+ }
10656
+ });
10657
+ },
10658
+ started: function started() {
10659
+ var _router_start;
10660
+ (_router_start = router.start) === null || _router_start === void 0 ? void 0 : _router_start.call(router);
10661
+ },
10662
+ unsubscribe: function unsubscribe() {
10663
+ router.dispose();
9491
10664
  }
9492
- return hit;
9493
- });
9494
- hits.__escaped = true;
9495
- }
9496
- return hits;
9497
- }
9498
- function escapeFacets(facetHits) {
9499
- return facetHits.map(function(h) {
9500
- return _object_spread_props(_object_spread({}, h), {
9501
- highlighted: replaceTagsAndEscape(h.highlighted)
9502
- });
9503
- });
10665
+ };
10666
+ };
10667
+ };
10668
+
10669
+ function formatNumber(value, numberLocale) {
10670
+ return value.toLocaleString(numberLocale);
9504
10671
  }
9505
10672
 
10673
+ var NAMESPACE = 'ais';
10674
+ var component = function component(componentName) {
10675
+ return function() {
10676
+ var _ref = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, descendantName = _ref.descendantName, modifierName = _ref.modifierName;
10677
+ var descendent = descendantName ? "-".concat(descendantName) : '';
10678
+ var modifier = modifierName ? "--".concat(modifierName) : '';
10679
+ return "".concat(NAMESPACE, "-").concat(componentName).concat(descendent).concat(modifier);
10680
+ };
10681
+ };
10682
+
9506
10683
  var suit$3 = component('Highlight');
9507
10684
  /**
9508
10685
  * @deprecated use html tagged templates and the Highlight component instead
@@ -9517,69 +10694,6 @@
9517
10694
  return attributeValue.replace(new RegExp(TAG_REPLACEMENT.highlightPreTag, 'g'), "<".concat(highlightedTagName, ' class="').concat(className, '">')).replace(new RegExp(TAG_REPLACEMENT.highlightPostTag, 'g'), "</".concat(highlightedTagName, ">"));
9518
10695
  }
9519
10696
 
9520
- function concatHighlightedParts(parts) {
9521
- var highlightPreTag = TAG_REPLACEMENT.highlightPreTag, highlightPostTag = TAG_REPLACEMENT.highlightPostTag;
9522
- return parts.map(function(part) {
9523
- return part.isHighlighted ? highlightPreTag + part.value + highlightPostTag : part.value;
9524
- }).join('');
9525
- }
9526
-
9527
- var hasAlphanumeric = new RegExp(/\w/i);
9528
- function getHighlightFromSiblings(parts, i) {
9529
- var _parts_, _parts_1;
9530
- var current = parts[i];
9531
- var isNextHighlighted = ((_parts_ = parts[i + 1]) === null || _parts_ === void 0 ? void 0 : _parts_.isHighlighted) || true;
9532
- var isPreviousHighlighted = ((_parts_1 = parts[i - 1]) === null || _parts_1 === void 0 ? void 0 : _parts_1.isHighlighted) || true;
9533
- if (!hasAlphanumeric.test(unescape$1(current.value)) && isPreviousHighlighted === isNextHighlighted) {
9534
- return isPreviousHighlighted;
9535
- }
9536
- return current.isHighlighted;
9537
- }
9538
-
9539
- function reverseHighlightedParts(parts) {
9540
- if (!parts.some(function(part) {
9541
- return part.isHighlighted;
9542
- })) {
9543
- return parts.map(function(part) {
9544
- return _object_spread_props(_object_spread({}, part), {
9545
- isHighlighted: false
9546
- });
9547
- });
9548
- }
9549
- return parts.map(function(part, i) {
9550
- return _object_spread_props(_object_spread({}, part), {
9551
- isHighlighted: !getHighlightFromSiblings(parts, i)
9552
- });
9553
- });
9554
- }
9555
-
9556
- function getHighlightedParts(highlightedValue) {
9557
- // @MAJOR: this should use TAG_PLACEHOLDER
9558
- var highlightPostTag = TAG_REPLACEMENT.highlightPostTag, highlightPreTag = TAG_REPLACEMENT.highlightPreTag;
9559
- var splitByPreTag = highlightedValue.split(highlightPreTag);
9560
- var firstValue = splitByPreTag.shift();
9561
- var elements = !firstValue ? [] : [
9562
- {
9563
- value: firstValue,
9564
- isHighlighted: false
9565
- }
9566
- ];
9567
- splitByPreTag.forEach(function(split) {
9568
- var splitByPostTag = split.split(highlightPostTag);
9569
- elements.push({
9570
- value: splitByPostTag[0],
9571
- isHighlighted: true
9572
- });
9573
- if (splitByPostTag[1] !== '') {
9574
- elements.push({
9575
- value: splitByPostTag[1],
9576
- isHighlighted: false
9577
- });
9578
- }
9579
- });
9580
- return elements;
9581
- }
9582
-
9583
10697
  var suit$2 = component('ReverseHighlight');
9584
10698
  /**
9585
10699
  * @deprecated use html tagged templates and the ReverseHighlight component instead
@@ -9624,10 +10738,6 @@
9624
10738
  return reverseHighlightedValue.replace(new RegExp(TAG_REPLACEMENT.highlightPreTag, 'g'), "<".concat(highlightedTagName, ' class="').concat(className, '">')).replace(new RegExp(TAG_REPLACEMENT.highlightPostTag, 'g'), "</".concat(highlightedTagName, ">"));
9625
10739
  }
9626
10740
 
9627
- function serializePayload(payload) {
9628
- return btoa(encodeURIComponent(JSON.stringify(payload)));
9629
- }
9630
-
9631
10741
  /** @deprecated use bindEvent instead */ function writeDataAttributes(param) {
9632
10742
  var method = param.method, payload = param.payload;
9633
10743
  if ((typeof payload === "undefined" ? "undefined" : _type_of(payload)) !== 'object') {
@@ -9666,185 +10776,52 @@
9666
10776
  throw new Error('\nThe highlight helper expects a JSON object of the format:\n{ "attribute": "name", "highlightedTagName": "mark" }');
9667
10777
  }
9668
10778
  },
9669
- reverseHighlight: function reverseHighlight1(options, render) {
9670
- try {
9671
- var reverseHighlightOptions = JSON.parse(options);
9672
- return render(reverseHighlight(_object_spread_props(_object_spread({}, reverseHighlightOptions), {
9673
- hit: this
9674
- })));
9675
- } catch (error) {
9676
- throw new Error('\n The reverseHighlight helper expects a JSON object of the format:\n { "attribute": "name", "highlightedTagName": "mark" }');
9677
- }
9678
- },
9679
- snippet: function snippet1(options, render) {
9680
- try {
9681
- var snippetOptions = JSON.parse(options);
9682
- return render(snippet(_object_spread_props(_object_spread({}, snippetOptions), {
9683
- hit: this
9684
- })));
9685
- } catch (error) {
9686
- throw new Error('\nThe snippet helper expects a JSON object of the format:\n{ "attribute": "name", "highlightedTagName": "mark" }');
9687
- }
9688
- },
9689
- reverseSnippet: function reverseSnippet1(options, render) {
9690
- try {
9691
- var reverseSnippetOptions = JSON.parse(options);
9692
- return render(reverseSnippet(_object_spread_props(_object_spread({}, reverseSnippetOptions), {
9693
- hit: this
9694
- })));
9695
- } catch (error) {
9696
- throw new Error('\n The reverseSnippet helper expects a JSON object of the format:\n { "attribute": "name", "highlightedTagName": "mark" }');
9697
- }
9698
- },
9699
- insights: function insights1(options, render) {
9700
- try {
9701
- var _JSON_parse = JSON.parse(options), method = _JSON_parse.method, payload = _JSON_parse.payload;
9702
- return render(insights(method, _object_spread({
9703
- objectIDs: [
9704
- this.objectID
9705
- ]
9706
- }, payload)));
9707
- } catch (error) {
9708
- throw new Error('\nThe insights helper expects a JSON object of the format:\n{ "method": "method-name", "payload": { "eventName": "name of the event" } }');
9709
- }
9710
- }
9711
- };
9712
- }
9713
-
9714
- var version = '4.95.0';
9715
-
9716
- function hydrateSearchClient(client, results) {
9717
- if (!results) {
9718
- return;
9719
- }
9720
- // Disable cache hydration on:
9721
- // - Algoliasearch API Client < v4 with cache disabled
9722
- // - Third party clients (detected by the `addAlgoliaAgent` function missing)
9723
- if ((!('transporter' in client) || client._cacheHydrated) && (!client._useCache || typeof client.addAlgoliaAgent !== 'function')) {
9724
- return;
9725
- }
9726
- var cachedRequest = [
9727
- Object.keys(results).reduce(function(acc, key) {
9728
- var _results_key = results[key], state = _results_key.state, requestParams = _results_key.requestParams, serverResults = _results_key.results;
9729
- var mappedResults = serverResults && state ? serverResults.map(function(result, idx) {
9730
- return _object_spread({
9731
- indexName: state.index || result.index
9732
- }, (requestParams === null || requestParams === void 0 ? void 0 : requestParams[idx]) || result.params ? {
9733
- params: serializeQueryParameters((requestParams === null || requestParams === void 0 ? void 0 : requestParams[idx]) || deserializeQueryParameters(result.params))
9734
- } : {});
9735
- }) : [];
9736
- return acc.concat(mappedResults);
9737
- }, [])
9738
- ];
9739
- var cachedResults = Object.keys(results).reduce(function(acc, key) {
9740
- var res = results[key].results;
9741
- if (!res) {
9742
- return acc;
9743
- }
9744
- return acc.concat(res);
9745
- }, []);
9746
- // Algoliasearch API Client >= v4
9747
- // To hydrate the client we need to populate the cache with the data from
9748
- // the server (done in `hydrateSearchClientWithMultiIndexRequest` or
9749
- // `hydrateSearchClientWithSingleIndexRequest`). But since there is no way
9750
- // for us to compute the key the same way as `algoliasearch-client` we need
9751
- // to populate it on a custom key and override the `search` method to
9752
- // search on it first.
9753
- if ('transporter' in client && !client._cacheHydrated) {
9754
- client._cacheHydrated = true;
9755
- var baseMethod = client.search.bind(client);
9756
- client.search = function(requests) {
9757
- for(var _len = arguments.length, methodArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
9758
- methodArgs[_key - 1] = arguments[_key];
9759
- }
9760
- var requestsWithSerializedParams = Array.isArray(requests) ? requests.map(function(request) {
9761
- return _object_spread_props(_object_spread({}, request), {
9762
- params: serializeQueryParameters(request.params)
9763
- });
9764
- }) : serializeQueryParameters(requests.requestBody.params);
9765
- return client.transporter.responsesCache.get({
9766
- method: 'search',
9767
- args: [
9768
- requestsWithSerializedParams
9769
- ].concat(_to_consumable_array(methodArgs))
9770
- }, function() {
9771
- return baseMethod.apply(void 0, [
9772
- requests
9773
- ].concat(_to_consumable_array(methodArgs)));
9774
- });
9775
- };
9776
- client.transporter.responsesCache.set({
9777
- method: 'search',
9778
- args: cachedRequest
9779
- }, {
9780
- results: cachedResults
9781
- });
9782
- }
9783
- // Algoliasearch API Client < v4
9784
- // Prior to client v4 we didn't have a proper API to hydrate the client
9785
- // cache from the outside. The following code populates the cache with
9786
- // a single-index result. You can find more information about the
9787
- // computation of the key inside the client (see link below).
9788
- // https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240
9789
- if (!('transporter' in client)) {
9790
- var cacheKey = "/1/indexes/*/queries_body_".concat(JSON.stringify({
9791
- requests: cachedRequest
9792
- }));
9793
- client.cache = _object_spread_props(_object_spread({}, client.cache), _define_property({}, cacheKey, JSON.stringify({
9794
- results: Object.keys(results).map(function(key) {
9795
- return results[key].results;
9796
- })
9797
- })));
9798
- }
9799
- }
9800
- function deserializeQueryParameters(parameters) {
9801
- return parameters.split('&').reduce(function(acc, parameter) {
9802
- var _parameter_split = _sliced_to_array(parameter.split('='), 2), key = _parameter_split[0], value = _parameter_split[1];
9803
- acc[key] = value ? decodeURIComponent(value) : '';
9804
- return acc;
9805
- }, {});
9806
- }
9807
- // This function is copied from the algoliasearch v4 API Client. If modified,
9808
- // consider updating it also in `serializeQueryParameters` from `@algolia/transporter`.
9809
- function serializeQueryParameters(parameters) {
9810
- var isObjectOrArray = function isObjectOrArray(value) {
9811
- return Object.prototype.toString.call(value) === '[object Object]' || Object.prototype.toString.call(value) === '[object Array]';
9812
- };
9813
- var encode = function encode(format) {
9814
- for(var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
9815
- args[_key - 1] = arguments[_key];
10779
+ reverseHighlight: function reverseHighlight1(options, render) {
10780
+ try {
10781
+ var reverseHighlightOptions = JSON.parse(options);
10782
+ return render(reverseHighlight(_object_spread_props(_object_spread({}, reverseHighlightOptions), {
10783
+ hit: this
10784
+ })));
10785
+ } catch (error) {
10786
+ throw new Error('\n The reverseHighlight helper expects a JSON object of the format:\n { "attribute": "name", "highlightedTagName": "mark" }');
10787
+ }
10788
+ },
10789
+ snippet: function snippet1(options, render) {
10790
+ try {
10791
+ var snippetOptions = JSON.parse(options);
10792
+ return render(snippet(_object_spread_props(_object_spread({}, snippetOptions), {
10793
+ hit: this
10794
+ })));
10795
+ } catch (error) {
10796
+ throw new Error('\nThe snippet helper expects a JSON object of the format:\n{ "attribute": "name", "highlightedTagName": "mark" }');
10797
+ }
10798
+ },
10799
+ reverseSnippet: function reverseSnippet1(options, render) {
10800
+ try {
10801
+ var reverseSnippetOptions = JSON.parse(options);
10802
+ return render(reverseSnippet(_object_spread_props(_object_spread({}, reverseSnippetOptions), {
10803
+ hit: this
10804
+ })));
10805
+ } catch (error) {
10806
+ throw new Error('\n The reverseSnippet helper expects a JSON object of the format:\n { "attribute": "name", "highlightedTagName": "mark" }');
10807
+ }
10808
+ },
10809
+ insights: function insights1(options, render) {
10810
+ try {
10811
+ var _JSON_parse = JSON.parse(options), method = _JSON_parse.method, payload = _JSON_parse.payload;
10812
+ return render(insights(method, _object_spread({
10813
+ objectIDs: [
10814
+ this.objectID
10815
+ ]
10816
+ }, payload)));
10817
+ } catch (error) {
10818
+ throw new Error('\nThe insights helper expects a JSON object of the format:\n{ "method": "method-name", "payload": { "eventName": "name of the event" } }');
10819
+ }
9816
10820
  }
9817
- var i = 0;
9818
- return format.replace(/%s/g, function() {
9819
- return encodeURIComponent(args[i++]);
9820
- });
9821
10821
  };
9822
- return Object.keys(parameters).map(function(key) {
9823
- return encode('%s=%s', key, isObjectOrArray(parameters[key]) ? JSON.stringify(parameters[key]) : parameters[key]);
9824
- }).join('&');
9825
10822
  }
9826
10823
 
9827
- function hydrateRecommendCache(helper, initialResults) {
9828
- var recommendCache = Object.keys(initialResults).reduce(function(acc, indexName) {
9829
- var initialResult = initialResults[indexName];
9830
- if (initialResult.recommendResults) {
9831
- // @MAJOR: Use `Object.assign` instead of spread operator
9832
- return _object_spread({}, acc, initialResult.recommendResults.results);
9833
- }
9834
- return acc;
9835
- }, {});
9836
- helper._recommendCache = recommendCache;
9837
- }
9838
-
9839
- function setIndexHelperState(finalUiState, indexWidget) {
9840
- var nextIndexUiState = finalUiState[indexWidget.getIndexId()] || {};
9841
- indexWidget.getHelper().setState(indexWidget.getWidgetSearchParameters(indexWidget.getHelper().state, {
9842
- uiState: nextIndexUiState
9843
- }));
9844
- indexWidget.getWidgets().filter(isIndexWidget).forEach(function(widget) {
9845
- return setIndexHelperState(finalUiState, widget);
9846
- });
9847
- }
10824
+ var version = '4.96.0';
9848
10825
 
9849
10826
  var withUsage$q = createDocumentationMessageGenerator({
9850
10827
  name: 'instantsearch'
@@ -10847,193 +11824,19 @@
10847
11824
  var ssrSearchRef = React.useRef(null);
10848
11825
  // This is used to re-map the result index to the requesting widget
10849
11826
  var recommendIdx = React.useRef(0);
10850
- // When <DynamicWidgets> is mounted, a second provider is used above the user-land
10851
- // <InstantSearchSSRProvider> in `getServerState()`.
10852
- // To avoid the user's provider overriding the context value with an empty object,
10853
- // we skip this provider.
10854
- if (Object.keys(props).length === 0) {
10855
- return /*#__PURE__*/ React.createElement(React.Fragment, null, children);
10856
- }
10857
- return /*#__PURE__*/ React.createElement(InstantSearchSSRContext.Provider, {
10858
- value: _object_spread_props(_object_spread({}, props), {
10859
- ssrSearchRef: ssrSearchRef,
10860
- recommendIdx: recommendIdx
10861
- })
10862
- }, children);
10863
- }
10864
-
10865
- function chunk(arr) {
10866
- var chunkSize = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 20;
10867
- var chunks = [];
10868
- for(var i = 0; i < Math.ceil(arr.length / chunkSize); i++){
10869
- chunks.push(arr.slice(i * chunkSize, (i + 1) * chunkSize));
10870
- }
10871
- return chunks;
10872
- }
10873
- function _buildEventPayloadsForHits(param) {
10874
- var helper = param.helper, widgetType = param.widgetType;
10875
- param.methodName;
10876
- var args = param.args, instantSearchInstance = param.instantSearchInstance;
10877
- // when there's only one argument, that means it's custom
10878
- if (args.length === 1 && _type_of(args[0]) === 'object') {
10879
- return [
10880
- args[0]
10881
- ];
10882
- }
10883
- var _args__split = _sliced_to_array(args[0].split(':'), 2), eventType = _args__split[0], eventModifier = _args__split[1];
10884
- var hits = args[1];
10885
- var eventName = args[2];
10886
- var additionalData = args[3] || {};
10887
- if (!hits) {
10888
- {
10889
- return [];
10890
- }
10891
- }
10892
- if ((eventType === 'click' || eventType === 'conversion') && !eventName) {
10893
- {
10894
- return [];
10895
- }
10896
- }
10897
- var hitsArray = Array.isArray(hits) ? hits : [
10898
- hits
10899
- ];
10900
- if (hitsArray.length === 0) {
10901
- return [];
10902
- }
10903
- var queryID = hitsArray[0].__queryID;
10904
- var hitsChunks = chunk(hitsArray);
10905
- var objectIDsByChunk = hitsChunks.map(function(batch) {
10906
- return batch.map(function(hit) {
10907
- return hit.objectID;
10908
- });
10909
- });
10910
- var positionsByChunk = hitsChunks.map(function(batch) {
10911
- return batch.map(function(hit) {
10912
- return hit.__position;
10913
- });
10914
- });
10915
- if (eventType === 'view') {
10916
- if (instantSearchInstance.status !== 'idle') {
10917
- return [];
10918
- }
10919
- return hitsChunks.map(function(batch, i) {
10920
- var _helper_lastResults;
10921
- return {
10922
- insightsMethod: 'viewedObjectIDs',
10923
- widgetType: widgetType,
10924
- eventType: eventType,
10925
- payload: _object_spread({
10926
- eventName: eventName || 'Hits Viewed',
10927
- index: ((_helper_lastResults = helper.lastResults) === null || _helper_lastResults === void 0 ? void 0 : _helper_lastResults.index) || helper.state.index,
10928
- objectIDs: objectIDsByChunk[i]
10929
- }, additionalData),
10930
- hits: batch,
10931
- eventModifier: eventModifier
10932
- };
10933
- });
10934
- } else if (eventType === 'click') {
10935
- return hitsChunks.map(function(batch, i) {
10936
- var _helper_lastResults;
10937
- return {
10938
- insightsMethod: 'clickedObjectIDsAfterSearch',
10939
- widgetType: widgetType,
10940
- eventType: eventType,
10941
- payload: _object_spread({
10942
- eventName: eventName || 'Hit Clicked',
10943
- index: ((_helper_lastResults = helper.lastResults) === null || _helper_lastResults === void 0 ? void 0 : _helper_lastResults.index) || helper.state.index,
10944
- queryID: queryID,
10945
- objectIDs: objectIDsByChunk[i],
10946
- positions: positionsByChunk[i]
10947
- }, additionalData),
10948
- hits: batch,
10949
- eventModifier: eventModifier
10950
- };
10951
- });
10952
- } else if (eventType === 'conversion') {
10953
- return hitsChunks.map(function(batch, i) {
10954
- var _helper_lastResults;
10955
- return {
10956
- insightsMethod: 'convertedObjectIDsAfterSearch',
10957
- widgetType: widgetType,
10958
- eventType: eventType,
10959
- payload: _object_spread({
10960
- eventName: eventName || 'Hit Converted',
10961
- index: ((_helper_lastResults = helper.lastResults) === null || _helper_lastResults === void 0 ? void 0 : _helper_lastResults.index) || helper.state.index,
10962
- queryID: queryID,
10963
- objectIDs: objectIDsByChunk[i]
10964
- }, additionalData),
10965
- hits: batch,
10966
- eventModifier: eventModifier
10967
- };
10968
- });
10969
- } else {
10970
- return [];
10971
- }
10972
- }
10973
- function createSendEventForHits(param) {
10974
- var instantSearchInstance = param.instantSearchInstance, helper = param.helper, widgetType = param.widgetType;
10975
- var sentEvents = {};
10976
- var timer = undefined;
10977
- var sendEventForHits = function sendEventForHits() {
10978
- for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
10979
- args[_key] = arguments[_key];
10980
- }
10981
- var payloads = _buildEventPayloadsForHits({
10982
- widgetType: widgetType,
10983
- helper: helper,
10984
- methodName: 'sendEvent',
10985
- args: args,
10986
- instantSearchInstance: instantSearchInstance
10987
- });
10988
- payloads.forEach(function(payload) {
10989
- if (payload.eventType === 'click' && payload.eventModifier === 'internal' && sentEvents[payload.eventType]) {
10990
- return;
10991
- }
10992
- sentEvents[payload.eventType] = true;
10993
- instantSearchInstance.sendEventToInsights(payload);
10994
- });
10995
- clearTimeout(timer);
10996
- timer = setTimeout(function() {
10997
- sentEvents = {};
10998
- }, 0);
10999
- };
11000
- return sendEventForHits;
11001
- }
11002
- function createBindEventForHits(param) {
11003
- var helper = param.helper, widgetType = param.widgetType, instantSearchInstance = param.instantSearchInstance;
11004
- var bindEventForHits = function bindEventForHits() {
11005
- for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
11006
- args[_key] = arguments[_key];
11007
- }
11008
- var payloads = _buildEventPayloadsForHits({
11009
- widgetType: widgetType,
11010
- helper: helper,
11011
- methodName: 'bindEvent',
11012
- args: args,
11013
- instantSearchInstance: instantSearchInstance
11014
- });
11015
- return payloads.length ? "data-insights-event=".concat(serializePayload(payloads)) : '';
11016
- };
11017
- return bindEventForHits;
11018
- }
11019
-
11020
- function addQueryID(hits, queryID) {
11021
- if (!queryID) {
11022
- return hits;
11023
- }
11024
- return hits.map(function(hit) {
11025
- return _object_spread_props(_object_spread({}, hit), {
11026
- __queryID: queryID
11027
- });
11028
- });
11029
- }
11030
-
11031
- function addAbsolutePosition(hits, page, hitsPerPage) {
11032
- return hits.map(function(hit, idx) {
11033
- return _object_spread_props(_object_spread({}, hit), {
11034
- __position: hitsPerPage * page + idx + 1
11035
- });
11036
- });
11827
+ // When <DynamicWidgets> is mounted, a second provider is used above the user-land
11828
+ // <InstantSearchSSRProvider> in `getServerState()`.
11829
+ // To avoid the user's provider overriding the context value with an empty object,
11830
+ // we skip this provider.
11831
+ if (Object.keys(props).length === 0) {
11832
+ return /*#__PURE__*/ React.createElement(React.Fragment, null, children);
11833
+ }
11834
+ return /*#__PURE__*/ React.createElement(InstantSearchSSRContext.Provider, {
11835
+ value: _object_spread_props(_object_spread({}, props), {
11836
+ ssrSearchRef: ssrSearchRef,
11837
+ recommendIdx: recommendIdx
11838
+ })
11839
+ }, children);
11037
11840
  }
11038
11841
 
11039
11842
  var withUsage$p = createDocumentationMessageGenerator({
@@ -11900,6 +12703,7 @@
11900
12703
  var currentTextPartId;
11901
12704
  var currentReasoningPartId;
11902
12705
  var toolRawInputByCallId = {};
12706
+ var toolRawOutputByCallId = {};
11903
12707
  // Promise chain for handling tool calls that return promises
11904
12708
  var pendingToolCall = Promise.resolve();
11905
12709
  return new Promise(function(resolve) {
@@ -12144,24 +12948,69 @@
12144
12948
  }
12145
12949
  break;
12146
12950
  }
12147
- case 'tool-output-available':
12951
+ case 'data-tool-output-delta':
12148
12952
  {
12953
+ var _ref3, _ref4;
12149
12954
  if (!currentMessage) break;
12955
+ var _chunk_data = chunk.data, toolCallId = _chunk_data.toolCallId, toolName1 = _chunk_data.toolName, delta = _chunk_data.delta;
12150
12956
  var toolIndex1 = currentMessage.parts.findIndex(function(p) {
12151
- return 'toolCallId' in p && p.toolCallId === chunk.toolCallId;
12957
+ return 'toolCallId' in p && p.toolCallId === toolCallId;
12958
+ });
12959
+ var existingPart1 = toolIndex1 >= 0 ? currentMessage.parts[toolIndex1] : null;
12960
+ 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 : '';
12961
+ var nextRawOutput = "".concat(previousRawOutput).concat(delta);
12962
+ toolRawOutputByCallId[toolCallId] = nextRawOutput;
12963
+ var parsedOutput = parseToolInputDelta(nextRawOutput, existingPart1 === null || existingPart1 === void 0 ? void 0 : existingPart1.output);
12964
+ var nextToolPart1 = _object_spread_props(_object_spread({}, existingPart1 !== null && existingPart1 !== void 0 ? existingPart1 : {
12965
+ type: "tool-".concat(toolName1),
12966
+ toolCallId: toolCallId,
12967
+ input: undefined
12968
+ }), {
12969
+ state: 'output-available',
12970
+ output: parsedOutput,
12971
+ rawOutput: nextRawOutput,
12972
+ preliminary: true
12152
12973
  });
12153
12974
  if (toolIndex1 >= 0) {
12154
- delete toolRawInputByCallId[chunk.toolCallId];
12155
12975
  var updatedParts6 = _to_consumable_array(currentMessage.parts);
12156
- var existingPart1 = updatedParts6[toolIndex1];
12157
- updatedParts6[toolIndex1] = _object_spread_props(_object_spread({}, existingPart1), {
12976
+ updatedParts6[toolIndex1] = nextToolPart1;
12977
+ currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
12978
+ parts: updatedParts6
12979
+ });
12980
+ } else {
12981
+ currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
12982
+ parts: _to_consumable_array(currentMessage.parts).concat([
12983
+ nextToolPart1
12984
+ ])
12985
+ });
12986
+ }
12987
+ _this.state.replaceMessage(currentMessageIndex, currentMessage);
12988
+ break;
12989
+ }
12990
+ case 'tool-output-available':
12991
+ {
12992
+ if (!currentMessage) break;
12993
+ var toolIndex2 = currentMessage.parts.findIndex(function(p) {
12994
+ return 'toolCallId' in p && p.toolCallId === chunk.toolCallId;
12995
+ });
12996
+ if (toolIndex2 >= 0) {
12997
+ delete toolRawInputByCallId[chunk.toolCallId];
12998
+ delete toolRawOutputByCallId[chunk.toolCallId];
12999
+ var updatedParts7 = _to_consumable_array(currentMessage.parts);
13000
+ var existingPart2 = updatedParts7[toolIndex2];
13001
+ // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
13002
+ existingPart2.rawOutput;
13003
+ var rest = _object_without_properties(existingPart2, [
13004
+ "rawOutput"
13005
+ ]);
13006
+ updatedParts7[toolIndex2] = _object_spread_props(_object_spread({}, rest), {
12158
13007
  state: 'output-available',
12159
13008
  output: chunk.output,
12160
13009
  callProviderMetadata: chunk.callProviderMetadata,
12161
13010
  preliminary: chunk.preliminary
12162
13011
  });
12163
13012
  currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
12164
- parts: updatedParts6
13013
+ parts: updatedParts7
12165
13014
  });
12166
13015
  _this.state.replaceMessage(currentMessageIndex, currentMessage);
12167
13016
  }
@@ -12170,22 +13019,30 @@
12170
13019
  case 'tool-error':
12171
13020
  {
12172
13021
  if (!currentMessage) break;
12173
- var toolIndex2 = currentMessage.parts.findIndex(function(p) {
13022
+ var toolIndex3 = currentMessage.parts.findIndex(function(p) {
12174
13023
  return 'toolCallId' in p && p.toolCallId === chunk.toolCallId;
12175
13024
  });
12176
- if (toolIndex2 >= 0) {
13025
+ if (toolIndex3 >= 0) {
12177
13026
  var _chunk_input;
12178
13027
  delete toolRawInputByCallId[chunk.toolCallId];
12179
- var updatedParts7 = _to_consumable_array(currentMessage.parts);
12180
- var existingPart2 = updatedParts7[toolIndex2];
12181
- updatedParts7[toolIndex2] = _object_spread_props(_object_spread({}, existingPart2), {
13028
+ delete toolRawOutputByCallId[chunk.toolCallId];
13029
+ var updatedParts8 = _to_consumable_array(currentMessage.parts);
13030
+ var existingPart3 = updatedParts8[toolIndex3];
13031
+ // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
13032
+ existingPart3.rawOutput; // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
13033
+ existingPart3.preliminary;
13034
+ var rest1 = _object_without_properties(existingPart3, [
13035
+ "rawOutput",
13036
+ "preliminary"
13037
+ ]);
13038
+ updatedParts8[toolIndex3] = _object_spread_props(_object_spread({}, rest1), {
12182
13039
  state: 'output-error',
12183
13040
  errorText: chunk.errorText,
12184
- input: (_chunk_input = chunk.input) !== null && _chunk_input !== void 0 ? _chunk_input : existingPart2.input,
13041
+ input: (_chunk_input = chunk.input) !== null && _chunk_input !== void 0 ? _chunk_input : existingPart3.input,
12185
13042
  callProviderMetadata: chunk.callProviderMetadata
12186
13043
  });
12187
13044
  currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
12188
- parts: updatedParts7
13045
+ parts: updatedParts8
12189
13046
  });
12190
13047
  _this.state.replaceMessage(currentMessageIndex, currentMessage);
12191
13048
  }
@@ -12560,6 +13417,7 @@
12560
13417
  var MemorizeToolType = 'algolia_memorize';
12561
13418
  var MemorySearchToolType = 'algolia_memory_search';
12562
13419
  var PonderToolType = 'algolia_ponder';
13420
+ var DisplayResultsToolType = 'algolia_display_results';
12563
13421
 
12564
13422
  function flat(arr) {
12565
13423
  return arr.reduce(function(acc, array) {
@@ -12684,236 +13542,60 @@
12684
13542
  headers: resolvedHeaders,
12685
13543
  api: _this.api
12686
13544
  })) : Promise.resolve(null);
12687
- return preparePromise.then(function(prepared) {
12688
- if (prepared) {
12689
- if (prepared.api) api = prepared.api;
12690
- if (prepared.headers) {
12691
- headers = _instanceof(prepared.headers, Headers) ? Object.fromEntries(prepared.headers.entries()) : prepared.headers;
12692
- }
12693
- if (prepared.credentials) credentials = prepared.credentials;
12694
- }
12695
- // GET request for reconnection
12696
- return fetchFn("".concat(api, "?chatId=").concat(chatId), {
12697
- method: 'GET',
12698
- headers: headers,
12699
- credentials: credentials
12700
- }).then(function(response) {
12701
- if (!response.ok) {
12702
- // 404 means no stream to reconnect to, which is not an error
12703
- if (response.status === 404) {
12704
- return null;
12705
- }
12706
- throw new Error("HTTP error: ".concat(response.status, " ").concat(response.statusText));
12707
- }
12708
- if (!response.body) {
12709
- return null;
12710
- }
12711
- return _this.processResponseStream(response.body);
12712
- });
12713
- });
12714
- });
12715
- }
12716
- }
12717
- ]);
12718
- return HttpChatTransport;
12719
- }();
12720
- /**
12721
- * Default chat transport implementation using NDJSON streaming.
12722
- */ var DefaultChatTransport = /*#__PURE__*/ function(HttpChatTransport) {
12723
- _inherits(DefaultChatTransport, HttpChatTransport);
12724
- function DefaultChatTransport() {
12725
- var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
12726
- _class_call_check(this, DefaultChatTransport);
12727
- return _call_super(this, DefaultChatTransport, [
12728
- options
12729
- ]);
12730
- }
12731
- _create_class(DefaultChatTransport, [
12732
- {
12733
- key: "processResponseStream",
12734
- value: function processResponseStream(stream) {
12735
- return parseJsonEventStream(stream);
12736
- }
12737
- }
12738
- ]);
12739
- return DefaultChatTransport;
12740
- }(HttpChatTransport);
12741
-
12742
- function sendChatMessageFeedback(param) {
12743
- var agentId = param.agentId, vote = param.vote, messageId = param.messageId, appId = param.appId, apiKey = param.apiKey;
12744
- return fetch("https://".concat(appId, ".algolia.net/agent-studio/1/feedback"), {
12745
- method: 'POST',
12746
- body: JSON.stringify({
12747
- messageId: messageId,
12748
- agentId: agentId,
12749
- vote: vote
12750
- }),
12751
- headers: {
12752
- 'x-algolia-application-id': appId,
12753
- 'x-algolia-api-key': apiKey,
12754
- 'content-type': 'application/json'
12755
- }
12756
- }).then(function(response) {
12757
- if (response.status >= 300) {
12758
- return response.json().then(function(data) {
12759
- throw new Error("Feedback request failed with status ".concat(response.status, ": ").concat(data.message));
12760
- });
12761
- }
12762
- return response.json();
12763
- });
12764
- }
12765
-
12766
- /**
12767
- * Clears the refinements of a SearchParameters object based on rules provided.
12768
- * The included attributes list is applied before the excluded attributes list. If the list
12769
- * is not provided, this list of all the currently refined attributes is used as included attributes.
12770
- * @returns search parameters with refinements cleared
12771
- */ function clearRefinements(param) {
12772
- var helper = param.helper, _param_attributesToClear = param.attributesToClear, attributesToClear = _param_attributesToClear === void 0 ? [] : _param_attributesToClear;
12773
- var finalState = helper.state.setPage(0);
12774
- finalState = attributesToClear.reduce(function(state, attribute) {
12775
- if (finalState.isNumericRefined(attribute)) {
12776
- return state.removeNumericRefinement(attribute);
12777
- }
12778
- if (finalState.isHierarchicalFacet(attribute)) {
12779
- return state.removeHierarchicalFacetRefinement(attribute);
12780
- }
12781
- if (finalState.isDisjunctiveFacet(attribute)) {
12782
- return state.removeDisjunctiveFacetRefinement(attribute);
12783
- }
12784
- if (finalState.isConjunctiveFacet(attribute)) {
12785
- return state.removeFacetRefinement(attribute);
12786
- }
12787
- return state;
12788
- }, finalState);
12789
- if (attributesToClear.indexOf('query') !== -1) {
12790
- finalState = finalState.setQuery('');
12791
- }
12792
- return finalState;
12793
- }
12794
-
12795
- function unescapeFacetValue(value) {
12796
- if (typeof value === 'string') {
12797
- return value.replace(/^\\-/, '-');
12798
- }
12799
- return value;
12800
- }
12801
- function escapeFacetValue(value) {
12802
- if (typeof value === 'number' && value < 0 || typeof value === 'string') {
12803
- return String(value).replace(/^-/, '\\-');
12804
- }
12805
- return value;
12806
- }
12807
-
12808
- function getRefinement(state, type, attribute, name) {
12809
- var resultsFacets = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : [];
12810
- var res = {
12811
- type: type,
12812
- attribute: attribute,
12813
- name: name,
12814
- escapedValue: escapeFacetValue(name)
12815
- };
12816
- var facet = find$1(resultsFacets, function(resultsFacet) {
12817
- return resultsFacet.name === attribute;
12818
- });
12819
- var count;
12820
- if (type === 'hierarchical') {
12821
- var _loop = function _loop(i) {
12822
- facet = facet && facet.data && find$1(Object.keys(facet.data).map(getFacetRefinement(facet.data)), function(refinement) {
12823
- return refinement.name === nameParts[i];
12824
- });
12825
- };
12826
- var facetDeclaration = state.getHierarchicalFacetByName(attribute);
12827
- var nameParts = name.split(facetDeclaration.separator);
12828
- var getFacetRefinement = function getFacetRefinement(facetData) {
12829
- return function(refinementKey) {
12830
- return facetData[refinementKey];
12831
- };
12832
- };
12833
- for(var i = 0; facet !== undefined && i < nameParts.length; ++i)_loop(i);
12834
- count = facet && facet.count;
12835
- } else {
12836
- count = facet && facet.data && facet.data[res.name];
12837
- }
12838
- if (count !== undefined) {
12839
- res.count = count;
12840
- }
12841
- if (facet && facet.exhaustive !== undefined) {
12842
- res.exhaustive = facet.exhaustive;
12843
- }
12844
- return res;
12845
- }
12846
- function getRefinements(_results, state) {
12847
- var includesQuery = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
12848
- var results = _results || {};
12849
- var refinements = [];
12850
- 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;
12851
- Object.keys(facetsRefinements).forEach(function(attribute) {
12852
- var refinementNames = facetsRefinements[attribute];
12853
- refinementNames.forEach(function(refinementName) {
12854
- refinements.push(getRefinement(state, 'facet', attribute, refinementName, results.facets));
12855
- });
12856
- });
12857
- Object.keys(facetsExcludes).forEach(function(attribute) {
12858
- var refinementNames = facetsExcludes[attribute];
12859
- refinementNames.forEach(function(refinementName) {
12860
- refinements.push({
12861
- type: 'exclude',
12862
- attribute: attribute,
12863
- name: refinementName,
12864
- exclude: true
12865
- });
12866
- });
12867
- });
12868
- Object.keys(disjunctiveFacetsRefinements).forEach(function(attribute) {
12869
- var refinementNames = disjunctiveFacetsRefinements[attribute];
12870
- refinementNames.forEach(function(refinementName) {
12871
- refinements.push(getRefinement(state, 'disjunctive', attribute, // they can be escaped on negative numeric values with `escapeFacetValue`.
12872
- unescapeFacetValue(refinementName), results.disjunctiveFacets));
12873
- });
12874
- });
12875
- Object.keys(hierarchicalFacetsRefinements).forEach(function(attribute) {
12876
- var refinementNames = hierarchicalFacetsRefinements[attribute];
12877
- refinementNames.forEach(function(refinement) {
12878
- refinements.push(getRefinement(state, 'hierarchical', attribute, refinement, results.hierarchicalFacets));
12879
- });
12880
- });
12881
- Object.keys(numericRefinements).forEach(function(attribute) {
12882
- var operators = numericRefinements[attribute];
12883
- Object.keys(operators).forEach(function(operatorOriginal) {
12884
- var operator = operatorOriginal;
12885
- var valueOrValues = operators[operator];
12886
- var refinementNames = Array.isArray(valueOrValues) ? valueOrValues : [
12887
- valueOrValues
12888
- ];
12889
- refinementNames.forEach(function(refinementName) {
12890
- refinements.push({
12891
- type: 'numeric',
12892
- attribute: attribute,
12893
- name: "".concat(refinementName),
12894
- numericValue: refinementName,
12895
- operator: operator
13545
+ return preparePromise.then(function(prepared) {
13546
+ if (prepared) {
13547
+ if (prepared.api) api = prepared.api;
13548
+ if (prepared.headers) {
13549
+ headers = _instanceof(prepared.headers, Headers) ? Object.fromEntries(prepared.headers.entries()) : prepared.headers;
13550
+ }
13551
+ if (prepared.credentials) credentials = prepared.credentials;
13552
+ }
13553
+ // GET request for reconnection
13554
+ return fetchFn("".concat(api, "?chatId=").concat(chatId), {
13555
+ method: 'GET',
13556
+ headers: headers,
13557
+ credentials: credentials
13558
+ }).then(function(response) {
13559
+ if (!response.ok) {
13560
+ // 404 means no stream to reconnect to, which is not an error
13561
+ if (response.status === 404) {
13562
+ return null;
13563
+ }
13564
+ throw new Error("HTTP error: ".concat(response.status, " ").concat(response.statusText));
13565
+ }
13566
+ if (!response.body) {
13567
+ return null;
13568
+ }
13569
+ return _this.processResponseStream(response.body);
13570
+ });
13571
+ });
12896
13572
  });
12897
- });
12898
- });
12899
- });
12900
- tagRefinements.forEach(function(refinementName) {
12901
- refinements.push({
12902
- type: 'tag',
12903
- attribute: '_tags',
12904
- name: refinementName
12905
- });
12906
- });
12907
- if (includesQuery && state.query && state.query.trim()) {
12908
- refinements.push({
12909
- attribute: 'query',
12910
- type: 'query',
12911
- name: state.query,
12912
- query: state.query
12913
- });
13573
+ }
13574
+ }
13575
+ ]);
13576
+ return HttpChatTransport;
13577
+ }();
13578
+ /**
13579
+ * Default chat transport implementation using NDJSON streaming.
13580
+ */ var DefaultChatTransport = /*#__PURE__*/ function(HttpChatTransport) {
13581
+ _inherits(DefaultChatTransport, HttpChatTransport);
13582
+ function DefaultChatTransport() {
13583
+ var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
13584
+ _class_call_check(this, DefaultChatTransport);
13585
+ return _call_super(this, DefaultChatTransport, [
13586
+ options
13587
+ ]);
12914
13588
  }
12915
- return refinements;
12916
- }
13589
+ _create_class(DefaultChatTransport, [
13590
+ {
13591
+ key: "processResponseStream",
13592
+ value: function processResponseStream(stream) {
13593
+ return parseJsonEventStream(stream);
13594
+ }
13595
+ }
13596
+ ]);
13597
+ return DefaultChatTransport;
13598
+ }(HttpChatTransport);
12917
13599
 
12918
13600
  var withUsage$n = createDocumentationMessageGenerator({
12919
13601
  name: 'chat',
@@ -13733,67 +14415,6 @@
13733
14415
  return useConnector(connectFrequentlyBoughtTogether, props, additionalWidgetProperties);
13734
14416
  }
13735
14417
 
13736
- var latLngRegExp = /^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)$/;
13737
- function aroundLatLngToPosition(value) {
13738
- var pattern = value.match(latLngRegExp);
13739
- // Since the value provided is the one send with the request, the API should
13740
- // throw an error due to the wrong format. So throw an error should be safe.
13741
- if (!pattern) {
13742
- throw new Error('Invalid value for "aroundLatLng" parameter: "'.concat(value, '"'));
13743
- }
13744
- return {
13745
- lat: parseFloat(pattern[1]),
13746
- lng: parseFloat(pattern[2])
13747
- };
13748
- }
13749
- function insideBoundingBoxArrayToBoundingBox(value) {
13750
- var _value = _sliced_to_array(value, 1), tmp = _value[0], _ref = _sliced_to_array(tmp === void 0 ? [
13751
- undefined,
13752
- undefined,
13753
- undefined,
13754
- undefined
13755
- ] : tmp, 4), neLat = _ref[0], neLng = _ref[1], swLat = _ref[2], swLng = _ref[3];
13756
- // Since the value provided is the one send with the request, the API should
13757
- // throw an error due to the wrong format. So throw an error should be safe.
13758
- if (!neLat || !neLng || !swLat || !swLng) {
13759
- throw new Error('Invalid value for "insideBoundingBox" parameter: ['.concat(value, "]"));
13760
- }
13761
- return {
13762
- northEast: {
13763
- lat: neLat,
13764
- lng: neLng
13765
- },
13766
- southWest: {
13767
- lat: swLat,
13768
- lng: swLng
13769
- }
13770
- };
13771
- }
13772
- function insideBoundingBoxStringToBoundingBox(value) {
13773
- 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];
13774
- // Since the value provided is the one send with the request, the API should
13775
- // throw an error due to the wrong format. So throw an error should be safe.
13776
- if (!neLat || !neLng || !swLat || !swLng) {
13777
- throw new Error('Invalid value for "insideBoundingBox" parameter: "'.concat(value, '"'));
13778
- }
13779
- return {
13780
- northEast: {
13781
- lat: neLat,
13782
- lng: neLng
13783
- },
13784
- southWest: {
13785
- lat: swLat,
13786
- lng: swLng
13787
- }
13788
- };
13789
- }
13790
- function insideBoundingBoxToBoundingBox(value) {
13791
- if (Array.isArray(value)) {
13792
- return insideBoundingBoxArrayToBoundingBox(value);
13793
- }
13794
- return insideBoundingBoxStringToBoundingBox(value);
13795
- }
13796
-
13797
14418
  var withUsage$j = createDocumentationMessageGenerator({
13798
14419
  name: 'geo-search',
13799
14420
  connector: true
@@ -13991,51 +14612,6 @@
13991
14612
  return useConnector(connectGeoSearch, props, additionalWidgetProperties);
13992
14613
  }
13993
14614
 
13994
- function isFacetRefined(helper, facet, value) {
13995
- if (helper.state.isHierarchicalFacet(facet)) {
13996
- return helper.state.isHierarchicalFacetRefined(facet, value);
13997
- } else if (helper.state.isConjunctiveFacet(facet)) {
13998
- return helper.state.isFacetRefined(facet, value);
13999
- } else {
14000
- return helper.state.isDisjunctiveFacetRefined(facet, value);
14001
- }
14002
- }
14003
-
14004
- function createSendEventForFacet(param) {
14005
- var instantSearchInstance = param.instantSearchInstance, helper = param.helper, attr = param.attribute, widgetType = param.widgetType;
14006
- var sendEventForFacet = function sendEventForFacet() {
14007
- for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
14008
- args[_key] = arguments[_key];
14009
- }
14010
- 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;
14011
- var _args__split = _sliced_to_array(args[0].split(':'), 2), eventType = _args__split[0], eventModifier = _args__split[1];
14012
- var attribute = typeof attr === 'string' ? attr : attr(facetValue);
14013
- if (args.length === 1 && _type_of(args[0]) === 'object') {
14014
- instantSearchInstance.sendEventToInsights(args[0]);
14015
- } else if (eventType === 'click' && args.length >= 2 && args.length <= 4) {
14016
- if (!isFacetRefined(helper, attribute, facetValue)) {
14017
- var _helper_lastResults;
14018
- // send event only when the facet is being checked "ON"
14019
- instantSearchInstance.sendEventToInsights({
14020
- insightsMethod: 'clickedFilters',
14021
- widgetType: widgetType,
14022
- eventType: eventType,
14023
- eventModifier: eventModifier,
14024
- payload: _object_spread({
14025
- eventName: eventName,
14026
- index: ((_helper_lastResults = helper.lastResults) === null || _helper_lastResults === void 0 ? void 0 : _helper_lastResults.index) || helper.state.index,
14027
- filters: [
14028
- "".concat(attribute, ":").concat(facetValue)
14029
- ]
14030
- }, additionalData),
14031
- attribute: attribute
14032
- });
14033
- }
14034
- } else ;
14035
- };
14036
- return sendEventForFacet;
14037
- }
14038
-
14039
14615
  var withUsage$i = createDocumentationMessageGenerator({
14040
14616
  name: 'hierarchical-menu',
14041
14617
  connector: true
@@ -14492,17 +15068,6 @@
14492
15068
  return useConnector(connectHitsPerPage, props, additionalWidgetProperties);
14493
15069
  }
14494
15070
 
14495
- /**
14496
- * Recurse over all child indices
14497
- */ function walkIndex(indexWidget, callback) {
14498
- callback(indexWidget);
14499
- indexWidget.getWidgets().forEach(function(widget) {
14500
- if (isIndexWidget(widget)) {
14501
- walkIndex(widget, callback);
14502
- }
14503
- });
14504
- }
14505
-
14506
15071
  var withUsage$f = createDocumentationMessageGenerator({
14507
15072
  name: 'infinite-hits',
14508
15073
  connector: true
@@ -14671,19 +15236,16 @@
14671
15236
  });
14672
15237
  /*
14673
15238
  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.
14674
- */ var hasDynamicWidgets = false;
15239
+ */ var hasTwoPassWidgets = false;
14675
15240
  walkIndex(instantSearchInstance.mainIndex, function(indexWidget) {
14676
- if (!hasDynamicWidgets && indexWidget.getWidgets().some(function(param) {
14677
- var $$type = param.$$type;
14678
- return $$type === 'ais.dynamicWidgets';
14679
- })) {
14680
- hasDynamicWidgets = true;
15241
+ if (!hasTwoPassWidgets && indexWidget.getWidgets().some(isTwoPassWidget)) {
15242
+ hasTwoPassWidgets = true;
14681
15243
  }
14682
15244
  });
14683
15245
  var hasNoFacets = !((_state_disjunctiveFacets = state.disjunctiveFacets) === null || _state_disjunctiveFacets === void 0 ? void 0 : _state_disjunctiveFacets.length) && !(state.facets || []).filter(function(f) {
14684
15246
  return f !== '*';
14685
15247
  }).length && !((_state_hierarchicalFacets = state.hierarchicalFacets) === null || _state_hierarchicalFacets === void 0 ? void 0 : _state_hierarchicalFacets.length);
14686
- if (cachedHits[page] === undefined && !results.__isArtificial && instantSearchInstance.status === 'idle' && !(hasDynamicWidgets && hasNoFacets)) {
15248
+ if (cachedHits[page] === undefined && !results.__isArtificial && instantSearchInstance.status === 'idle' && !(hasTwoPassWidgets && hasNoFacets)) {
14687
15249
  cachedHits[page] = transformedHits;
14688
15250
  cache.write({
14689
15251
  state: normalizeState(state),
@@ -14944,14 +15506,6 @@
14944
15506
  return useConnector(connectMenu, props, additionalWidgetProperties);
14945
15507
  }
14946
15508
 
14947
- // This is the `Number.isFinite()` polyfill recommended by MDN.
14948
- // We do not provide any tests for this function.
14949
- // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill
14950
- // @MAJOR Replace with the native `Number.isFinite` method
14951
- function isFiniteNumber(value) {
14952
- return typeof value === 'number' && isFinite(value);
14953
- }
14954
-
14955
15509
  var withUsage$d = createDocumentationMessageGenerator({
14956
15510
  name: 'numeric-menu',
14957
15511
  connector: true
@@ -15212,21 +15766,6 @@
15212
15766
  return useConnector(connectNumericMenu, props, additionalWidgetProperties);
15213
15767
  }
15214
15768
 
15215
- function range(param) {
15216
- 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;
15217
- // We can't divide by 0 so we re-assign the step to 1 if it happens.
15218
- var limitStep = step === 0 ? 1 : step;
15219
- // In some cases the array to create has a decimal length.
15220
- // We therefore need to round the value.
15221
- // Example:
15222
- // { start: 1, end: 5000, step: 500 }
15223
- // => Array length = (5000 - 1) / 500 = 9.998
15224
- var arrayLength = Math.round((end - start) / limitStep);
15225
- return _to_consumable_array(Array(arrayLength)).map(function(_, current) {
15226
- return start + current * limitStep;
15227
- });
15228
- }
15229
-
15230
15769
  var Paginator = /*#__PURE__*/ function() {
15231
15770
  function Paginator(params) {
15232
15771
  _class_call_check(this, Paginator);
@@ -15403,17 +15942,6 @@
15403
15942
  return useConnector(connectPagination, props, additionalWidgetProperties);
15404
15943
  }
15405
15944
 
15406
- /**
15407
- * Logs a warning
15408
- * This is used to log issues in development environment only.
15409
- */ var warn = noop;
15410
-
15411
- function toArray(value) {
15412
- return Array.isArray(value) ? value : [
15413
- value
15414
- ];
15415
- }
15416
-
15417
15945
  function usePoweredBy() {
15418
15946
  var hostname = safelyRunOnBrowser(function(param) {
15419
15947
  var window = param.window;
@@ -16404,7 +16932,8 @@
16404
16932
  },
16405
16933
  getWidgetSearchParameters: function getWidgetSearchParameters(searchParameters, param) {
16406
16934
  var uiState = param.uiState;
16407
- var sortByValue = uiState.sortBy || connectorState.initialValue || searchParameters.index;
16935
+ var isUiStateSortByInItems = !uiState.sortBy || Object.prototype.hasOwnProperty.call(connectorState.itemsLookup, uiState.sortBy);
16936
+ var sortByValue = (isUiStateSortByInItems ? uiState.sortBy : undefined) || connectorState.initialValue || searchParameters.index;
16408
16937
  if (isValidStrategy(connectorState.itemsLookup, sortByValue)) {
16409
16938
  var item = connectorState.itemsLookup[sortByValue];
16410
16939
  // Strategy-based: set the sortBy parameter for composition API
@@ -17505,13 +18034,19 @@
17505
18034
  var resultsCount = (searchResults === null || searchResults === void 0 ? void 0 : (_searchResults__rawResults = searchResults._rawResults) === null || _searchResults__rawResults === void 0 ? void 0 : _searchResults__rawResults.length) || 0;
17506
18035
  var requestParams = resultsCount ? requestParamsList === null || requestParamsList === void 0 ? void 0 : requestParamsList.slice(requestParamsIndex, requestParamsIndex + resultsCount) : [];
17507
18036
  requestParamsIndex += resultsCount;
17508
- initialResults[widget.getIndexId()] = _object_spread({}, searchResults && {
18037
+ initialResults[widget.getIndexId()] = _object_spread({}, searchResults && _object_spread({
17509
18038
  state: _object_spread_props(_object_spread({}, searchResults._state), {
17510
18039
  clickAnalytics: requestParams === null || requestParams === void 0 ? void 0 : (_requestParams_ = requestParams[0]) === null || _requestParams_ === void 0 ? void 0 : _requestParams_.clickAnalytics,
17511
18040
  userToken: requestParams === null || requestParams === void 0 ? void 0 : (_requestParams_1 = requestParams[0]) === null || _requestParams_1 === void 0 ? void 0 : _requestParams_1.userToken
17512
18041
  }),
17513
18042
  results: searchResults._rawResults
17514
- }, recommendResults && {
18043
+ }, searchResults.feeds && searchResults.feeds.length > 0 && {
18044
+ compositionFeedsResults: searchResults.feeds.map(function(feed) {
18045
+ return _object_spread_props(_object_spread({}, feed._rawResults[0]), {
18046
+ feedID: feed.feedID
18047
+ });
18048
+ })
18049
+ }), recommendResults && {
17515
18050
  recommendResults: {
17516
18051
  // We have to stringify + parse because of some explicitly undefined values.
17517
18052
  params: JSON.parse(JSON.stringify(recommendResults._state.params)),
@@ -17555,12 +18090,9 @@
17555
18090
  notifyServer: createNotifyServer()
17556
18091
  }).then(function(serverState) {
17557
18092
  var shouldRefetch = false;
17558
- // <DynamicWidgets> requires another query to retrieve the dynamic widgets
17559
- // to render.
18093
+ // Two-pass widgets require another query to discover and mount child widgets.
17560
18094
  walkIndex(searchRef.current.mainIndex, function(index) {
17561
- shouldRefetch = shouldRefetch || index.getWidgets().some(function(widget) {
17562
- return widget.$$type === 'ais.dynamicWidgets';
17563
- });
18095
+ shouldRefetch = shouldRefetch || index.getWidgets().some(isTwoPassWidget);
17564
18096
  });
17565
18097
  if (shouldRefetch) {
17566
18098
  resetWidgetId();
@@ -19150,12 +19682,17 @@
19150
19682
  }, markdown);
19151
19683
  }
19152
19684
  if (startsWith(part.type, 'tool-')) {
19685
+ var _message_metadata;
19153
19686
  var toolName = part.type.replace('tool-', '');
19154
19687
  var tool = tools[toolName];
19155
19688
  // Compatibility shim with Algolia MCP Server search tool
19156
19689
  if (!tool && startsWith(toolName, "".concat(SearchIndexToolType, "_"))) {
19157
19690
  tool = tools[SearchIndexToolType];
19158
19691
  }
19692
+ var displayResultsEnabled = ((_message_metadata = message.metadata) === null || _message_metadata === void 0 ? void 0 : _message_metadata.displayResultsEnabled) === true;
19693
+ if (displayResultsEnabled && tool && tool === tools[SearchIndexToolType]) {
19694
+ return null;
19695
+ }
19159
19696
  if (tool) {
19160
19697
  var ToolLayoutComponent = tool.layoutComponent;
19161
19698
  var toolMessage = part;
@@ -20070,6 +20607,53 @@
20070
20607
  };
20071
20608
  }
20072
20609
 
20610
+ var DEFAULT_TRANSLATIONS$1 = {
20611
+ streamingLabel: 'Curating results…'
20612
+ };
20613
+ function createDisplayResultsToolComponent(param) {
20614
+ var createElement = param.createElement, Fragment = param.Fragment;
20615
+ return function DisplayResultsTool(userProps) {
20616
+ var toolProps = userProps.toolProps, GroupCarousel = userProps.groupCarouselComponent, userTranslations = userProps.translations;
20617
+ var message = toolProps.message, sendEvent = toolProps.sendEvent;
20618
+ var translations = _object_spread({}, DEFAULT_TRANSLATIONS$1, userTranslations);
20619
+ var output = message === null || message === void 0 ? void 0 : message.output;
20620
+ var intro = typeof (output === null || output === void 0 ? void 0 : output.intro) === 'string' ? output.intro : undefined;
20621
+ var groups = Array.isArray(output === null || output === void 0 ? void 0 : output.groups) ? output.groups : [];
20622
+ var isStreaming = (message === null || message === void 0 ? void 0 : message.state) === 'output-available' && message.preliminary === true;
20623
+ if (!intro && groups.length === 0) {
20624
+ return /*#__PURE__*/ createElement(Fragment, null);
20625
+ }
20626
+ return /*#__PURE__*/ createElement("div", {
20627
+ className: "ais-ChatToolDisplayResults"
20628
+ }, intro && /*#__PURE__*/ createElement("div", {
20629
+ className: "ais-ChatToolDisplayResults-intro"
20630
+ }, intro), groups.map(function(group, groupIndex) {
20631
+ var results = Array.isArray(group.results) ? group.results.filter(function(r) {
20632
+ return Boolean(r) && typeof r.objectID === 'string' && r.objectID !== '';
20633
+ }) : [];
20634
+ if (results.length === 0) return null;
20635
+ var items = results.map(function(result, idx) {
20636
+ return _object_spread_props(_object_spread({}, result), {
20637
+ __position: idx + 1
20638
+ });
20639
+ });
20640
+ return /*#__PURE__*/ createElement("div", {
20641
+ key: groupIndex,
20642
+ className: "ais-ChatToolDisplayResults-group"
20643
+ }, group.title && /*#__PURE__*/ createElement("div", {
20644
+ className: "ais-ChatToolDisplayResults-groupTitle"
20645
+ }, group.title), group.why && /*#__PURE__*/ createElement("div", {
20646
+ className: "ais-ChatToolDisplayResults-groupWhy"
20647
+ }, group.why), /*#__PURE__*/ createElement(GroupCarousel, {
20648
+ items: items,
20649
+ sendEvent: sendEvent
20650
+ }));
20651
+ }), isStreaming && /*#__PURE__*/ createElement("div", {
20652
+ className: "ais-ChatToolDisplayResults-streaming"
20653
+ }, translations.streamingLabel));
20654
+ };
20655
+ }
20656
+
20073
20657
  function createDefaultEmptyComponent(param) {
20074
20658
  var createElement = param.createElement, Fragment = param.Fragment;
20075
20659
  return function DefaultEmpty() {
@@ -21960,6 +22544,61 @@
21960
22544
  createElement: React.createElement
21961
22545
  });
21962
22546
 
22547
+ function createDisplayResultsTool(itemComponent) {
22548
+ var DisplayResultsUIComponent = createDisplayResultsToolComponent({
22549
+ createElement: React.createElement,
22550
+ Fragment: React.Fragment
22551
+ });
22552
+ var Button = createButtonComponent({
22553
+ createElement: React.createElement
22554
+ });
22555
+ var DisplayResultsLayoutComponent = function DisplayResultsLayoutComponent(toolProps) {
22556
+ return /*#__PURE__*/ React.createElement(DisplayResultsUIComponent, {
22557
+ toolProps: toolProps,
22558
+ groupCarouselComponent: function groupCarouselComponent(param) {
22559
+ var items = param.items, sendEvent = param.sendEvent;
22560
+ return /*#__PURE__*/ React.createElement(Carousel, {
22561
+ items: items,
22562
+ itemComponent: itemComponent,
22563
+ sendEvent: sendEvent,
22564
+ showNavigation: false,
22565
+ headerComponent: function headerComponent(param) {
22566
+ var canScrollLeft = param.canScrollLeft, canScrollRight = param.canScrollRight, scrollLeft = param.scrollLeft, scrollRight = param.scrollRight;
22567
+ return /*#__PURE__*/ React.createElement("div", {
22568
+ className: "ais-ChatToolDisplayResultsCarouselHeader"
22569
+ }, /*#__PURE__*/ React.createElement("div", {
22570
+ className: "ais-ChatToolDisplayResultsCarouselHeaderCount"
22571
+ }, items.length, " result", items.length > 1 ? 's' : ''), /*#__PURE__*/ React.createElement("div", {
22572
+ className: "ais-ChatToolDisplayResultsCarouselHeaderScrollButtons"
22573
+ }, /*#__PURE__*/ React.createElement(Button, {
22574
+ variant: "outline",
22575
+ size: "sm",
22576
+ iconOnly: true,
22577
+ onClick: scrollLeft,
22578
+ disabled: !canScrollLeft,
22579
+ className: "ais-ChatToolDisplayResultsCarouselHeaderScrollButton"
22580
+ }, /*#__PURE__*/ React.createElement(ChevronLeftIcon, {
22581
+ createElement: React.createElement
22582
+ })), /*#__PURE__*/ React.createElement(Button, {
22583
+ variant: "outline",
22584
+ size: "sm",
22585
+ iconOnly: true,
22586
+ onClick: scrollRight,
22587
+ disabled: !canScrollRight,
22588
+ className: "ais-ChatToolDisplayResultsCarouselHeaderScrollButton"
22589
+ }, /*#__PURE__*/ React.createElement(ChevronRightIcon, {
22590
+ createElement: React.createElement
22591
+ }))));
22592
+ }
22593
+ });
22594
+ }
22595
+ });
22596
+ };
22597
+ return {
22598
+ layoutComponent: DisplayResultsLayoutComponent
22599
+ };
22600
+ }
22601
+
21963
22602
  function createCarouselTool(showViewAll, itemComponent, getSearchPageURL) {
21964
22603
  var Button = createButtonComponent({
21965
22604
  createElement: React.createElement
@@ -22058,7 +22697,7 @@
22058
22697
  });
22059
22698
  function createDefaultTools(itemComponent, getSearchPageURL) {
22060
22699
  var _obj;
22061
- return _obj = {}, _define_property(_obj, SearchIndexToolType$1, createCarouselTool(true, itemComponent, getSearchPageURL)), _define_property(_obj, RecommendToolType, createCarouselTool(false, itemComponent, getSearchPageURL)), _define_property(_obj, MemorizeToolType, {}), _define_property(_obj, MemorySearchToolType, {}), _define_property(_obj, PonderToolType, {}), _obj;
22700
+ return _obj = {}, _define_property(_obj, SearchIndexToolType$1, createCarouselTool(true, itemComponent, getSearchPageURL)), _define_property(_obj, RecommendToolType, createCarouselTool(false, itemComponent, getSearchPageURL)), _define_property(_obj, DisplayResultsToolType, createDisplayResultsTool(itemComponent)), _define_property(_obj, MemorizeToolType, {}), _define_property(_obj, MemorySearchToolType, {}), _define_property(_obj, PonderToolType, {}), _obj;
22062
22701
  }
22063
22702
  function ChatInner(_0, _1) {
22064
22703
  var _ref = [
@@ -24029,8 +24668,10 @@
24029
24668
  exports.ClearRefinements = ClearRefinements;
24030
24669
  exports.Configure = Configure;
24031
24670
  exports.CurrentRefinements = CurrentRefinements;
24671
+ exports.DisplayResultsToolType = DisplayResultsToolType;
24032
24672
  exports.DynamicWidgets = DynamicWidgets;
24033
24673
  exports.EXPERIMENTAL_Autocomplete = EXPERIMENTAL_Autocomplete;
24674
+ exports.Feeds = Feeds;
24034
24675
  exports.FilterSuggestions = FilterSuggestions;
24035
24676
  exports.FrequentlyBoughtTogether = FrequentlyBoughtTogether;
24036
24677
  exports.HierarchicalMenu = HierarchicalMenu;
@@ -24074,6 +24715,7 @@
24074
24715
  exports.useConnector = useConnector;
24075
24716
  exports.useCurrentRefinements = useCurrentRefinements;
24076
24717
  exports.useDynamicWidgets = useDynamicWidgets;
24718
+ exports.useFeeds = useFeeds;
24077
24719
  exports.useFilterSuggestions = useFilterSuggestions;
24078
24720
  exports.useFrequentlyBoughtTogether = useFrequentlyBoughtTogether;
24079
24721
  exports.useGeoSearch = useGeoSearch;