@shopify/hydrogen 2023.7.7 → 2023.7.9

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.
@@ -322,7 +322,8 @@ async function runWithCache(cacheKey, actionFn, {
322
322
  strategy = CacheShort(),
323
323
  cacheInstance,
324
324
  shouldCacheResult = () => true,
325
- waitUntil
325
+ waitUntil,
326
+ debugInfo
326
327
  }) {
327
328
  const startTime = Date.now();
328
329
  const key = hashKey([
@@ -335,7 +336,8 @@ async function runWithCache(cacheKey, actionFn, {
335
336
  url: getKeyUrl(key),
336
337
  startTime: overrideStartTime || startTime,
337
338
  cacheStatus,
338
- waitUntil
339
+ waitUntil,
340
+ ...debugInfo
339
341
  });
340
342
  } ;
341
343
  if (!cacheInstance || !strategy || strategy.mode === NO_STORE) {
@@ -389,7 +391,8 @@ async function fetchWithServerCache(url, requestInit, {
389
391
  cacheKey = [url, requestInit],
390
392
  shouldCacheResponse = () => true,
391
393
  waitUntil,
392
- returnType = "json"
394
+ returnType = "json",
395
+ debugInfo
393
396
  } = {}) {
394
397
  if (!cacheOptions && (!requestInit.method || requestInit.method === "GET")) {
395
398
  cacheOptions = CacheShort();
@@ -416,10 +419,16 @@ async function fetchWithServerCache(url, requestInit, {
416
419
  cacheInstance,
417
420
  waitUntil,
418
421
  strategy: cacheOptions ?? null,
422
+ debugInfo,
419
423
  shouldCacheResult: (result) => shouldCacheResponse(...fromSerializableResponse(result))
420
424
  }
421
425
  ).then(fromSerializableResponse);
422
426
  }
427
+ var getCallerStackLine = () => {
428
+ const stackInfo = { stack: "" };
429
+ Error.captureStackTrace(stackInfo);
430
+ return stackInfo.stack.split("\n").slice(3, 4).join("\n") || "";
431
+ } ;
423
432
 
424
433
  // src/constants.ts
425
434
  var STOREFRONT_REQUEST_GROUP_ID_HEADER = "Custom-Storefront-Request-Group-ID";
@@ -443,7 +452,7 @@ var warnOnce = (string) => {
443
452
  };
444
453
 
445
454
  // src/version.ts
446
- var LIB_VERSION = "2023.7.7";
455
+ var LIB_VERSION = "2023.7.9";
447
456
 
448
457
  // src/storefront.ts
449
458
  var StorefrontApiError = class extends Error {
@@ -505,7 +514,8 @@ function createStorefrontClient(options) {
505
514
  variables,
506
515
  cache: cacheOptions,
507
516
  headers = [],
508
- storefrontApiVersion
517
+ storefrontApiVersion,
518
+ stackLine
509
519
  }) {
510
520
  const userHeaders = headers instanceof Headers ? Object.fromEntries(headers.entries()) : Array.isArray(headers) ? Object.fromEntries(headers) : headers;
511
521
  query = query ?? mutation;
@@ -519,19 +529,34 @@ function createStorefrontClient(options) {
519
529
  }
520
530
  }
521
531
  const url = getStorefrontApiUrl({ storefrontApiVersion });
532
+ const graphqlData = JSON.stringify({ query, variables: queryVariables });
522
533
  const requestInit = {
523
534
  method: "POST",
524
535
  headers: { ...defaultHeaders, ...userHeaders },
525
- body: JSON.stringify({
526
- query,
527
- variables: queryVariables
528
- })
536
+ body: graphqlData
529
537
  };
538
+ const cacheKey = [
539
+ url,
540
+ {
541
+ method: requestInit.method,
542
+ headers: {
543
+ "content-type": defaultHeaders["content-type"],
544
+ "X-SDK-Variant": defaultHeaders["X-SDK-Variant"],
545
+ "X-SDK-Variant-Source": defaultHeaders["X-SDK-Variant-Source"],
546
+ "X-SDK-Version": defaultHeaders["X-SDK-Version"],
547
+ "X-Shopify-Storefront-Access-Token": defaultHeaders["X-Shopify-Storefront-Access-Token"],
548
+ "user-agent": defaultHeaders["user-agent"]
549
+ },
550
+ body: requestInit.body
551
+ }
552
+ ];
530
553
  const [body, response] = await fetchWithServerCache(url, requestInit, {
531
554
  cacheInstance: mutation ? void 0 : cache,
532
555
  cache: cacheOptions || CacheShort(),
556
+ cacheKey,
533
557
  shouldCacheResponse: checkGraphQLErrors,
534
- waitUntil
558
+ waitUntil,
559
+ debugInfo: { stackLine, graphql: graphqlData }
535
560
  });
536
561
  const errorOptions = {
537
562
  response,
@@ -582,7 +607,14 @@ function createStorefrontClient(options) {
582
607
  "[h2:error:storefront.query] Cannot execute mutations"
583
608
  );
584
609
  }
585
- return fetchStorefrontApi({ ...payload, query });
610
+ const result = fetchStorefrontApi({
611
+ ...payload,
612
+ query,
613
+ stackLine: getCallerStackLine?.()
614
+ });
615
+ result.catch(() => {
616
+ });
617
+ return result;
586
618
  },
587
619
  /**
588
620
  * Sends a GraphQL mutation to the Storefront API.
@@ -604,7 +636,14 @@ function createStorefrontClient(options) {
604
636
  "[h2:error:storefront.mutate] Cannot execute queries"
605
637
  );
606
638
  }
607
- return fetchStorefrontApi({ ...payload, mutation });
639
+ const result = fetchStorefrontApi({
640
+ ...payload,
641
+ mutation,
642
+ stackLine: getCallerStackLine?.()
643
+ });
644
+ result.catch(() => {
645
+ });
646
+ return result;
608
647
  },
609
648
  cache,
610
649
  CacheNone,
@@ -653,7 +692,7 @@ function throwError({
653
692
  throw new ErrorConstructor(
654
693
  `[h2:error:storefront.${type}] ` + errorMessage + (requestId ? ` - Request ID: ${requestId}` : ""),
655
694
  {
656
- cause: {
695
+ cause: JSON.stringify({
657
696
  errors,
658
697
  requestId,
659
698
  ...{
@@ -662,7 +701,7 @@ function throwError({
662
701
  variables: JSON.stringify(queryVariables)
663
702
  }
664
703
  }
665
- }
704
+ })
666
705
  }
667
706
  );
668
707
  }
@@ -674,7 +713,10 @@ function createWithCache(options) {
674
713
  return runWithCache(cacheKey, actionFn, {
675
714
  strategy,
676
715
  cacheInstance: cache,
677
- waitUntil
716
+ waitUntil,
717
+ debugInfo: {
718
+ stackLine: getCallerStackLine?.()
719
+ }
678
720
  });
679
721
  };
680
722
  }
@@ -1349,27 +1391,29 @@ function Pagination({
1349
1391
  [endCursor, hasPreviousPage, startCursor, nodes]
1350
1392
  );
1351
1393
  const NextLink = react.useMemo(
1352
- () => function NextLink2(props) {
1394
+ () => react.forwardRef(function NextLink2(props, ref) {
1353
1395
  return hasNextPage ? react.createElement(react$1.Link, {
1354
1396
  preventScrollReset: true,
1355
1397
  ...props,
1356
1398
  to: nextPageUrl,
1357
1399
  state,
1358
- replace: true
1400
+ replace: true,
1401
+ ref
1359
1402
  }) : null;
1360
- },
1403
+ }),
1361
1404
  [hasNextPage, nextPageUrl, state]
1362
1405
  );
1363
1406
  const PreviousLink = react.useMemo(
1364
- () => function PrevLink(props) {
1407
+ () => react.forwardRef(function PrevLink(props, ref) {
1365
1408
  return hasPreviousPage ? react.createElement(react$1.Link, {
1366
1409
  preventScrollReset: true,
1367
1410
  ...props,
1368
1411
  to: previousPageUrl,
1369
1412
  state,
1370
- replace: true
1413
+ replace: true,
1414
+ ref
1371
1415
  }) : null;
1372
- },
1416
+ }),
1373
1417
  [hasPreviousPage, previousPageUrl, state]
1374
1418
  );
1375
1419
  return children({
@@ -1490,7 +1534,7 @@ function usePagination(connection) {
1490
1534
  return { ...currentPageInfo, previousPageUrl, nextPageUrl, nodes };
1491
1535
  }
1492
1536
  function getPaginationVariables(request, options = { pageBy: 20 }) {
1493
- if (!(request instanceof Request)) {
1537
+ if (typeof request?.url === "undefined") {
1494
1538
  throw new Error(
1495
1539
  "getPaginationVariables must be called with the Request object passed to your loader function"
1496
1540
  );
@@ -2277,7 +2321,7 @@ function VariantSelector({
2277
2321
  );
2278
2322
  }
2279
2323
  var getSelectedProductOptions = (request) => {
2280
- if (!(request instanceof Request))
2324
+ if (typeof request?.url === "undefined")
2281
2325
  throw new TypeError(`Expected a Request instance, got ${typeof request}`);
2282
2326
  const searchParams = new URL(request.url).searchParams;
2283
2327
  const selectedOptions = [];
@@ -2372,6 +2416,38 @@ var Script = react.forwardRef(
2372
2416
  return /* @__PURE__ */ jsxRuntime.jsx("script", { suppressHydrationWarning: true, ...props, nonce, ref });
2373
2417
  }
2374
2418
  );
2419
+ function useOptimisticData(identifier) {
2420
+ const fetchers = react$1.useFetchers();
2421
+ const data = {};
2422
+ for (const fetcher of fetchers) {
2423
+ const formData = fetcher.submission?.formData;
2424
+ if (formData && formData.get("optimistic-identifier") === identifier) {
2425
+ try {
2426
+ if (formData.has("optimistic-data")) {
2427
+ const dataInForm = JSON.parse(
2428
+ String(formData.get("optimistic-data"))
2429
+ );
2430
+ Object.assign(data, dataInForm);
2431
+ }
2432
+ } catch {
2433
+ }
2434
+ }
2435
+ }
2436
+ return data;
2437
+ }
2438
+ function OptimisticInput({ id, data }) {
2439
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2440
+ /* @__PURE__ */ jsxRuntime.jsx("input", { type: "hidden", name: "optimistic-identifier", value: id }),
2441
+ /* @__PURE__ */ jsxRuntime.jsx(
2442
+ "input",
2443
+ {
2444
+ type: "hidden",
2445
+ name: "optimistic-data",
2446
+ value: JSON.stringify(data)
2447
+ }
2448
+ )
2449
+ ] });
2450
+ }
2375
2451
  //! @see: https://shopify.dev/docs/api/storefront/latest/mutations/cartCreate
2376
2452
  //! @see https://shopify.dev/docs/api/storefront/latest/queries/cart
2377
2453
  //! @see: https://shopify.dev/docs/api/storefront/latest/mutations/cartLinesAdd
@@ -2474,6 +2550,7 @@ exports.CacheNone = CacheNone;
2474
2550
  exports.CacheShort = CacheShort;
2475
2551
  exports.CartForm = CartForm;
2476
2552
  exports.InMemoryCache = InMemoryCache;
2553
+ exports.OptimisticInput = OptimisticInput;
2477
2554
  exports.Pagination = Pagination;
2478
2555
  exports.Script = Script;
2479
2556
  exports.Seo = Seo;
@@ -2503,5 +2580,6 @@ exports.graphiqlLoader = graphiqlLoader;
2503
2580
  exports.isStorefrontApiError = isStorefrontApiError;
2504
2581
  exports.storefrontRedirect = storefrontRedirect;
2505
2582
  exports.useNonce = useNonce;
2583
+ exports.useOptimisticData = useOptimisticData;
2506
2584
  //# sourceMappingURL=out.js.map
2507
2585
  //# sourceMappingURL=index.cjs.map