@merchi/cart 1.4.63 → 1.4.64

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.
@@ -0,0 +1,2 @@
1
+ /** A startup optimization only; explicit cart operations remain available. */
2
+ export declare function isAutomatedClient(userAgent?: string): boolean;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.isAutomatedClient = isAutomatedClient;
7
+ /** A startup optimization only; explicit cart operations remain available. */
8
+ function isAutomatedClient() {
9
+ var userAgent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : typeof navigator === 'undefined' ? '' : navigator.userAgent;
10
+ return /HeadlessChrome|bot|crawler|spider|slurp|SEBot-WA/i.test(userAgent);
11
+ }
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@merchi/cart",
3
- "version": "1.4.63",
3
+ "version": "1.4.64",
4
4
  "description": "Merchi's cart",
5
5
  "source": "src/index.ts",
6
6
  "main": "lib/index.js",
@@ -9,6 +9,7 @@ import { tabIdClearCart, tabIdItems } from './utilities/tabs';
9
9
 
10
10
  const mockGet = jest.fn();
11
11
  const mockPost = jest.fn();
12
+ const mockCreateItem = jest.fn();
12
13
 
13
14
  jest.mock('@merchi/sdk', () => ({
14
15
  Merchi: jest.fn().mockImplementation(() => ({
@@ -16,13 +17,16 @@ jest.mock('@merchi/sdk', () => ({
16
17
  authenticatedFetch: (...args: unknown[]) => mockPost(...args),
17
18
  })),
18
19
  }));
19
- jest.mock('./utilities/product', () => ({ makeProduct: jest.fn() }));
20
+ jest.mock('./utilities/product', () => ({ makeProduct: jest.fn(json => json) }));
21
+ jest.mock('./utilities/job', () => ({ makeJob: jest.fn(json => json) }));
20
22
  jest.mock('./utilities/cart', () => ({
21
- makeCart: () => ({
23
+ makeCart: (json: any) => ({
24
+ ...json,
22
25
  toFormData: () => new FormData(),
23
26
  fromJson: jest.fn(),
24
27
  toJson: () => ({ id: 99, token: 'new-token', isTest: false }),
25
28
  }),
29
+ makeCartItem: () => ({ create: mockCreateItem }),
26
30
  stripeIsValidAndActive: () => true,
27
31
  }));
28
32
  jest.mock('./utilities/cookie', () => ({
@@ -40,6 +44,7 @@ jest.mock('./utilities/job_source', () => ({
40
44
  }));
41
45
  jest.mock('./utilities/reportFailure', () => ({
42
46
  reportCartFailure: jest.fn(),
47
+ reportAddCartItemFailure: jest.fn((error, onError) => onError(error)),
43
48
  CART_FAILURE_SOURCES: { load: 'cart.load', create: 'cart.create' },
44
49
  }));
45
50
 
@@ -52,8 +57,20 @@ function Probe() {
52
57
  describe('cart load and replacement failures', () => {
53
58
  let root: Root;
54
59
  let container: HTMLDivElement;
60
+ const userAgentDescriptor = Object.getOwnPropertyDescriptor(navigator, 'userAgent');
61
+ const headlessUserAgent = 'Mozilla/5.0 (X11; Linux x86_64) HeadlessChrome/153.0.8010.0 Safari/537.36';
62
+ function setUserAgent(value: string) {
63
+ Object.defineProperty(navigator, 'userAgent', { configurable: true, value });
64
+ }
55
65
  beforeEach(() => {
56
66
  jest.clearAllMocks();
67
+ mockGet.mockReset();
68
+ mockPost.mockReset();
69
+ mockCreateItem.mockReset();
70
+ mockCreateItem.mockImplementation(function (this: any) {
71
+ return Promise.resolve({ toJson: () => ({ id: 7, cart: { id: this.cart.id } }) });
72
+ });
73
+ (getCartCookie as jest.Mock).mockReset();
57
74
  (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
58
75
  container = document.createElement('div');
59
76
  document.body.appendChild(container);
@@ -64,6 +81,8 @@ describe('cart load and replacement failures', () => {
64
81
  afterEach(async () => {
65
82
  await act(async () => root.unmount());
66
83
  container.remove();
84
+ if (userAgentDescriptor) Object.defineProperty(navigator, 'userAgent', userAgentDescriptor);
85
+ else delete (navigator as any).userAgent;
67
86
  });
68
87
  async function mount(error: unknown) {
69
88
  mockGet.mockRejectedValue(error);
@@ -84,6 +103,160 @@ describe('cart load and replacement failures', () => {
84
103
  });
85
104
  await act(async () => context.setActiveTabIndex(tabIdClearCart));
86
105
  }
106
+ it.each([
107
+ 'Mozilla/5.0 (X11; Linux x86_64) HeadlessChrome/153.0.8010.0 Safari/537.36',
108
+ 'Mozilla/5.0 (compatible; Baiduspider-render/2.0)',
109
+ ])('does not create an unused cart on automated startup: %s', async userAgent => {
110
+ setUserAgent(userAgent);
111
+ (getCartCookie as jest.Mock).mockResolvedValue(undefined);
112
+ await act(async () => root.render(
113
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
114
+ ));
115
+ expect(mockGet).not.toHaveBeenCalled();
116
+ expect(mockPost).not.toHaveBeenCalled();
117
+ expect(context.fetchingCart).toBe(false);
118
+ expect(reportCartFailure).not.toHaveBeenCalled();
119
+ });
120
+ it('allows explicit cart opening and concurrent callers in an automated browser', async () => {
121
+ setUserAgent(headlessUserAgent);
122
+ (getCartCookie as jest.Mock).mockResolvedValue(undefined);
123
+ await act(async () => root.render(
124
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
125
+ ));
126
+ expect(mockPost).not.toHaveBeenCalled();
127
+ await act(async () => {
128
+ context.toggleCartModal();
129
+ await Promise.all([(window as any).getCart(), (window as any).refetchCart()]);
130
+ });
131
+ expect(mockPost).toHaveBeenCalledTimes(1);
132
+ expect(context.cart.id).toBe(99);
133
+ });
134
+ it('creates once when explicit interaction joins a pending passive cookie lookup', async () => {
135
+ setUserAgent(headlessUserAgent);
136
+ let finishCookie!: (value: undefined) => void;
137
+ (getCartCookie as jest.Mock).mockImplementationOnce(
138
+ () => new Promise(resolve => { finishCookie = resolve; }),
139
+ ).mockResolvedValue(undefined);
140
+ await act(async () => root.render(
141
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
142
+ ));
143
+ let first!: Promise<void>, second!: Promise<void>;
144
+ await act(async () => {
145
+ first = (window as any).getCart();
146
+ second = (window as any).getCart();
147
+ context.toggleCartModal();
148
+ });
149
+ expect(mockPost).not.toHaveBeenCalled();
150
+ await act(async () => { finishCookie(undefined); await Promise.all([first, second]); });
151
+ expect(mockPost).toHaveBeenCalledTimes(1);
152
+ expect(context.cart.id).toBe(99);
153
+ });
154
+ it('restores saved carts for automated clients without duplicating an active read', async () => {
155
+ setUserAgent(headlessUserAgent);
156
+ let finish!: (value: unknown) => void;
157
+ mockGet.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
158
+ await act(async () => root.render(
159
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
160
+ ));
161
+ let read!: Promise<void>;
162
+ await act(async () => { read = (window as any).getCart(); context.toggleCartModal(); });
163
+ expect(mockGet).toHaveBeenCalledTimes(1);
164
+ await act(async () => {
165
+ finish({ toJson: () => ({ id: 42, isTest: false, cartItems: [{ id: 7 }] }) });
166
+ await read;
167
+ });
168
+ expect(mockPost).not.toHaveBeenCalled();
169
+ expect(context.cart.cartItems).toHaveLength(1);
170
+ });
171
+ it('keeps explicit retry available after an automated client creation fails', async () => {
172
+ setUserAgent(headlessUserAgent);
173
+ (getCartCookie as jest.Mock).mockResolvedValue(undefined);
174
+ mockPost.mockRejectedValueOnce(new TypeError('Failed to fetch'));
175
+ await act(async () => root.render(
176
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
177
+ ));
178
+ expect(mockPost).not.toHaveBeenCalled();
179
+ await act(async () => { await (window as any).getCart(); });
180
+ expect(mockPost).toHaveBeenCalledTimes(1);
181
+ expect(context.fetchingCart).toBe(false);
182
+ await act(async () => { await (window as any).getCart(); });
183
+ expect(mockPost).toHaveBeenCalledTimes(2);
184
+ expect(context.cart.id).toBe(99);
185
+ });
186
+ it('initializes a cart for a direct item operation without a storefront readiness helper', async () => {
187
+ setUserAgent(headlessUserAgent);
188
+ (getCartCookie as jest.Mock).mockResolvedValue(undefined);
189
+ await act(async () => root.render(
190
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
191
+ ));
192
+ const onSuccess = jest.fn(), onError = jest.fn();
193
+ await act(async () => {
194
+ await (window as any).addCartItem({ product: { id: 44 }, quantity: 100 }, onSuccess, onError);
195
+ });
196
+ expect(mockPost).toHaveBeenCalledTimes(1);
197
+ expect(mockCreateItem).toHaveBeenCalledTimes(1);
198
+ expect(onSuccess).toHaveBeenCalledWith({ id: 7, cart: { id: 99 } });
199
+ expect(onError).not.toHaveBeenCalled();
200
+ });
201
+ it('rejects a direct item operation when initialization fails without posting an item', async () => {
202
+ setUserAgent(headlessUserAgent);
203
+ (getCartCookie as jest.Mock).mockResolvedValue(undefined);
204
+ mockPost.mockRejectedValueOnce(new TypeError('Failed to fetch'));
205
+ await act(async () => root.render(
206
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
207
+ ));
208
+ const onSuccess = jest.fn(), onError = jest.fn();
209
+ await act(async () => {
210
+ await (window as any).addCartItem({ product: { id: 44 }, quantity: 100 }, onSuccess, onError);
211
+ });
212
+ expect(mockPost).toHaveBeenCalledTimes(1);
213
+ expect(mockCreateItem).not.toHaveBeenCalled();
214
+ expect(onSuccess).not.toHaveBeenCalled();
215
+ expect(onError).toHaveBeenCalledTimes(1);
216
+ expect(context.fetchingCart).toBe(false);
217
+ });
218
+ it('waits for ordinary startup before concurrent direct item operations', async () => {
219
+ (getCartCookie as jest.Mock).mockResolvedValue(undefined);
220
+ let finish!: (value: unknown) => void;
221
+ mockPost.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
222
+ await act(async () => root.render(
223
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
224
+ ));
225
+ const onSuccess = jest.fn(), onError = jest.fn();
226
+ let first!: Promise<void>, second!: Promise<void>;
227
+ await act(async () => {
228
+ const job = { product: { id: 44 }, quantity: 100 };
229
+ first = (window as any).addCartItem(job, onSuccess, onError);
230
+ second = (window as any).addCartItem(job, onSuccess, onError);
231
+ });
232
+ expect(mockCreateItem).not.toHaveBeenCalled();
233
+ await act(async () => {
234
+ finish({ cart: { id: 99, token: 'new-token' } });
235
+ await Promise.all([first, second]);
236
+ });
237
+ expect(mockPost).toHaveBeenCalledTimes(1);
238
+ expect(onSuccess.mock.calls.map(call => call[0].cart.id)).toEqual([99, 99]);
239
+ expect(onError).not.toHaveBeenCalled();
240
+ });
241
+ it('does not automatically repeat a failed item write after explicit initialization', async () => {
242
+ setUserAgent(headlessUserAgent);
243
+ (getCartCookie as jest.Mock).mockResolvedValue(undefined);
244
+ mockCreateItem.mockRejectedValueOnce(new TypeError('Failed to fetch'));
245
+ await act(async () => root.render(
246
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
247
+ ));
248
+ const onSuccess = jest.fn(), onError = jest.fn();
249
+ const job = { product: { id: 44 }, quantity: 100 };
250
+ await act(async () => { await (window as any).addCartItem(job, onSuccess, onError); });
251
+ expect(mockPost).toHaveBeenCalledTimes(1);
252
+ expect(mockCreateItem).toHaveBeenCalledTimes(1);
253
+ expect(onSuccess).not.toHaveBeenCalled();
254
+ expect(onError).toHaveBeenCalledTimes(1);
255
+ await act(async () => { await (window as any).addCartItem(job, onSuccess, onError); });
256
+ expect(mockPost).toHaveBeenCalledTimes(1);
257
+ expect(mockCreateItem).toHaveBeenCalledTimes(2);
258
+ expect(onSuccess).toHaveBeenCalledWith({ id: 7, cart: { id: 99 } });
259
+ });
87
260
  it('shares cold initialization with opening the modal and concurrent getCart callers', async () => {
88
261
  (getCartCookie as jest.Mock).mockResolvedValue(undefined);
89
262
  let finish!: (value: unknown) => void;
@@ -22,6 +22,7 @@ import {
22
22
  import { makeUser } from './utilities/user';
23
23
  import { persistTestCheckoutFlag, readTestCheckoutFlag } from './utilities/test_checkout';
24
24
  import { reportAddCartItemFailure, reportCartFailure, CART_FAILURE_SOURCES } from './utilities/reportFailure';
25
+ import { isAutomatedClient } from './utilities/automatedClient';
25
26
  import { canReplaceMissingCart } from './utilities/cartLoadFailure';
26
27
  import {
27
28
  appendJobSourceToFormData,
@@ -596,7 +597,9 @@ const CartProvider = ({
596
597
  const [fetchingCart, setFetchingCart] = useState(false);
597
598
  const [cartSettingsInvalid, setCartSettingsInvalid] = useState(false);
598
599
  const appliedHandoffCart = useRef<string | null>(null);
599
- const cartInitializations = useRef(new Map<number | undefined, Promise<void>>());
600
+ const cartInitializations = useRef(new Map<
601
+ number | undefined, Promise<{ skippedCreation: boolean; cart?: any }>
602
+ >());
600
603
 
601
604
  async function attachSavedClientIfNeeded(cartJson: any) {
602
605
  if (cartJson?.client?.id) {
@@ -650,12 +653,18 @@ const CartProvider = ({
650
653
  cartJson = await attachSavedClientIfNeeded(cartJson);
651
654
  setCart({...cartJson});
652
655
  if (callback) callback();
656
+ return cartJson;
653
657
  } catch (e: any) {
654
658
  reportCartFailure(e, CART_FAILURE_SOURCES.create);
655
659
  alertError(e?.errorMessage || e?.message || 'Unable to fetch cart.');
656
660
  } finally {
657
661
  setFetchingCart(false);
658
662
  }
663
+ return undefined;
664
+ }
665
+
666
+ async function requestNewCart(callback?: () => void) {
667
+ await createCartAndCookie(callback);
659
668
  }
660
669
 
661
670
  async function getCart(cartIdAndToken: Array<string>) {
@@ -669,8 +678,7 @@ const CartProvider = ({
669
678
  let cartJson = await cart.toJson();
670
679
  const isTest = readTestCheckoutFlag();
671
680
  if (Boolean(cartJson.isTest) !== isTest) {
672
- await createCartAndCookie();
673
- return;
681
+ return await createCartAndCookie();
674
682
  }
675
683
  const jobSource = jobSourceFieldsForApi(captureAndReadJobSource());
676
684
  if (cartNeedsSourceUpdate(cartJson, jobSource)) {
@@ -688,6 +696,7 @@ const CartProvider = ({
688
696
  if (stripeIsValidAndActive(cartJson) || isTest) {
689
697
  cartJson = await attachSavedClientIfNeeded(cartJson);
690
698
  setCart({...cartJson});
699
+ return cartJson;
691
700
  } else {
692
701
  console.error(
693
702
  `MErhci cart error: Stripe payment ` +
@@ -699,7 +708,7 @@ const CartProvider = ({
699
708
  }
700
709
  } catch(e: any){
701
710
  if (canReplaceMissingCart(e)) {
702
- await createCartAndCookie();
711
+ return await createCartAndCookie();
703
712
  } else {
704
713
  // A network/server/auth failure does not mean the saved cart is gone.
705
714
  // Preserve its cookie and contents so the shopper can retry the read.
@@ -709,6 +718,7 @@ const CartProvider = ({
709
718
  } finally {
710
719
  setFetchingCart(false);
711
720
  }
721
+ return undefined;
712
722
  }
713
723
 
714
724
  // A checkout link can name the cart. Remember it once, then keep using the cookie
@@ -723,24 +733,32 @@ const CartProvider = ({
723
733
  await setCartCookie(Number(domainId), { id: handoff[0], token: handoff[1] });
724
734
  }
725
735
 
726
- function actionGetMerchiCart() {
727
- const active = cartInitializations.current.get(domainId);
728
- if (active) return active;
736
+ function actionGetMerchiCart(allowCreation = true): Promise<any> {
737
+ let active = cartInitializations.current.get(domainId);
729
738
  // Mount, modal opening and explicit callers may run before React commits
730
739
  // fetchingCart. Share the whole cookie lookup/read-or-create operation.
731
- const initialization = Promise.resolve().then(async () => {
732
- await adoptHandoffCart();
733
- const cartIdAndToken = await getCartCookie((domainId as number));
734
- if (cartIdAndToken) {
735
- await getCart(cartIdAndToken);
736
- } else {
737
- await createCartAndCookie();
738
- }
739
- }).finally(() => {
740
- cartInitializations.current.delete(domainId);
740
+ if (!active) {
741
+ active = Promise.resolve().then(async () => {
742
+ await adoptHandoffCart();
743
+ const cartIdAndToken = await getCartCookie((domainId as number));
744
+ if (cartIdAndToken) {
745
+ return { skippedCreation: false, cart: await getCart(cartIdAndToken) };
746
+ } else if (allowCreation) {
747
+ return { skippedCreation: false, cart: await createCartAndCookie() };
748
+ }
749
+ return { skippedCreation: true };
750
+ }).finally(() => {
751
+ cartInitializations.current.delete(domainId);
752
+ });
753
+ cartInitializations.current.set(domainId, active);
754
+ }
755
+ return active.then(result => {
756
+ // An explicit caller can join passive startup before its cookie lookup
757
+ // finishes. Once that no-op completes, create through the same shared
758
+ // initialization path so concurrent explicit callers still issue one POST.
759
+ if (result.skippedCreation && allowCreation) return actionGetMerchiCart();
760
+ return result.cart;
741
761
  });
742
- cartInitializations.current.set(domainId, initialization);
743
- return initialization;
744
762
  }
745
763
 
746
764
  async function clearCart(callback?: () => void) {
@@ -855,25 +873,30 @@ const CartProvider = ({
855
873
  onError: (e: any) => void,
856
874
  ) {
857
875
  setFetchingCart(true);
858
- const jobEnt = makeJob(jobJson, true);
859
- const cartToken = await getCartCookieToken((domainId as number));
860
- const cartEnt = makeCart(cart, false, cartToken);
861
- const cartItemEnt = makeCartItem({}, true);
862
- const cartItemProduct = makeProduct({ id: (jobEnt.product as any).id });
863
-
864
- cartItemEnt.cart = cartEnt;
865
- cartItemEnt.quantity = jobEnt.quantity;
866
- cartItemEnt.product = cartItemProduct;
867
- cartItemEnt.variations = jobEnt.variations;
868
- cartItemEnt.variationsGroups = jobEnt.variationsGroups;
869
- cartItemEnt.taxType = jobEnt.taxType;
870
- cartItemEnt.ownDrafts = jobEnt.ownDrafts;
871
- cartItemEnt.clientFiles = jobEnt.clientFiles;
872
- cartItemEnt.tags = jobEnt.tags;
873
- if (typeof jobJson.designInputNotes === 'string' && jobJson.designInputNotes) {
874
- cartItemEnt.notes = jobJson.designInputNotes;
875
- }
876
876
  try {
877
+ const jobEnt = makeJob(jobJson, true);
878
+ const cartItemProduct = makeProduct({ id: (jobEnt.product as any).id });
879
+ // Legacy clients can call addCartItem directly, without first opening
880
+ // the cart or waiting for React to commit the initialized cart state.
881
+ const readyCart = cart?.id ? cart : await actionGetMerchiCart();
882
+ if (!readyCart?.id) throw new Error('Unable to initialize cart. Please try again.');
883
+ setFetchingCart(true);
884
+ const cartToken = await getCartCookieToken((domainId as number));
885
+ const cartEnt = makeCart(readyCart, false, cartToken);
886
+ const cartItemEnt = makeCartItem({}, true);
887
+
888
+ cartItemEnt.cart = cartEnt;
889
+ cartItemEnt.quantity = jobEnt.quantity;
890
+ cartItemEnt.product = cartItemProduct;
891
+ cartItemEnt.variations = jobEnt.variations;
892
+ cartItemEnt.variationsGroups = jobEnt.variationsGroups;
893
+ cartItemEnt.taxType = jobEnt.taxType;
894
+ cartItemEnt.ownDrafts = jobEnt.ownDrafts;
895
+ cartItemEnt.clientFiles = jobEnt.clientFiles;
896
+ cartItemEnt.tags = jobEnt.tags;
897
+ if (typeof jobJson.designInputNotes === 'string' && jobJson.designInputNotes) {
898
+ cartItemEnt.notes = jobJson.designInputNotes;
899
+ }
877
900
  const item = await cartItemEnt.create();
878
901
  const itemJson = await item.toJson();
879
902
  onSuccess(itemJson);
@@ -904,17 +927,17 @@ const CartProvider = ({
904
927
  if (typeof window !== 'undefined') {
905
928
  (window as any).addCartItem = addCartItem;
906
929
  (window as any).toggleCartOpen = toggleCartModal;
907
- (window as any).getCart = () => actionGetMerchiCart();
930
+ (window as any).getCart = async () => { await actionGetMerchiCart(); };
908
931
  (window as any).getMerchiCartValues = getMerchiCartValues;
909
932
  (window as any).isMerchiCartFetching = isMerchiCartFetching;
910
933
  (window as any).setCartComplete = setCartComplete;
911
934
  (window as any).refetchCart = refetchCart;
912
- (window as any).createCartAndCookie = createCartAndCookie;
935
+ (window as any).createCartAndCookie = requestNewCart;
913
936
  }
914
937
 
915
938
  useEffect(() => {
916
939
  persistTestCheckoutFlag();
917
- if (domainId) actionGetMerchiCart();
940
+ if (domainId) actionGetMerchiCart(!isAutomatedClient());
918
941
  if (domainId && includeTheme) actionFetchTheme();
919
942
  }, [domainId]);
920
943
  return (
@@ -1051,7 +1074,7 @@ const CartProvider = ({
1051
1074
 
1052
1075
  setCartComplete, // creates a token and cart and then reloads the page
1053
1076
  refetchCart, // used to refetch the cart
1054
- createCartAndCookie, // creates a new cart and cookie
1077
+ createCartAndCookie: requestNewCart, // creates a new cart and cookie
1055
1078
 
1056
1079
  loading,
1057
1080
 
@@ -0,0 +1,21 @@
1
+ import { isAutomatedClient } from './automatedClient';
2
+
3
+ describe('automated startup hint', () => {
4
+ it.each([
5
+ 'Mozilla/5.0 (X11; Linux x86_64) HeadlessChrome/153.0.8010.0 Safari/537.36',
6
+ 'Mozilla/5.0 (compatible; Baiduspider-render/2.0)',
7
+ 'Mozilla/5.0 (compatible; bingbot/2.0)',
8
+ 'Mozilla/5.0 (compatible; Googlebot/2.1)',
9
+ 'Mozilla/5.0 (compatible; SEBot-WA/1.0)',
10
+ ])('recognizes an automated visitor: %s', userAgent => {
11
+ expect(isAutomatedClient(userAgent)).toBe(true);
12
+ });
13
+ it.each([
14
+ '',
15
+ 'Mozilla/5.0 Chrome/153.0.0.0 Safari/537.36',
16
+ 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) Version/26.6.1 Mobile/15E148 Safari/604.1',
17
+ 'Mozilla/5.0 (Linux; Android 15) Chrome/153.0.0.0 Mobile Safari/537.36 [FBAN/FB4A]',
18
+ ])('keeps ordinary startup behavior: %s', userAgent => {
19
+ expect(isAutomatedClient(userAgent)).toBe(false);
20
+ });
21
+ });
@@ -0,0 +1,6 @@
1
+ /** A startup optimization only; explicit cart operations remain available. */
2
+ export function isAutomatedClient(
3
+ userAgent = typeof navigator === 'undefined' ? '' : navigator.userAgent,
4
+ ): boolean {
5
+ return /HeadlessChrome|bot|crawler|spider|slurp|SEBot-WA/i.test(userAgent);
6
+ }