@shopify/hydrogen 2026.10.2 → 2026.10.3
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.
- package/README.md +3 -5
- package/dist/cli/index.mjs +2 -2
- package/dist/client/client.mjs +44 -9
- package/dist/client/client.mjs.map +1 -1
- package/dist/client/i18n-variables.d.mts +1 -1
- package/dist/client/i18n-variables.mjs +14 -6
- package/dist/client/i18n-variables.mjs.map +1 -1
- package/dist/client/types.d.mts +12 -6
- package/dist/core/cache/fetch-with-cache.mjs +8 -1
- package/dist/core/cache/fetch-with-cache.mjs.map +1 -1
- package/dist/core/cart/cart.mjs +1 -1
- package/dist/core/cart/cookie.mjs +6 -1
- package/dist/core/cart/cookie.mjs.map +1 -1
- package/dist/core/cart/form.d.mts +17 -5
- package/dist/core/cart/form.mjs +5 -0
- package/dist/core/cart/form.mjs.map +1 -1
- package/dist/core/cart/index.d.mts +1 -1
- package/dist/core/collection/url.mjs +8 -1
- package/dist/core/collection/url.mjs.map +1 -1
- package/dist/core/constants.mjs +2 -1
- package/dist/core/constants.mjs.map +1 -1
- package/dist/core/csp/index.d.mts +56 -0
- package/dist/core/csp/index.mjs +117 -0
- package/dist/core/csp/index.mjs.map +1 -0
- package/dist/core/csp/types.d.mts +52 -0
- package/dist/core/headers.mjs +2 -2
- package/dist/core/headers.mjs.map +1 -1
- package/dist/core/i18n/define.d.mts +54 -0
- package/dist/core/i18n/define.mjs +135 -0
- package/dist/core/i18n/define.mjs.map +1 -0
- package/dist/core/i18n/errors.d.mts +18 -0
- package/dist/core/i18n/errors.mjs +24 -0
- package/dist/core/i18n/errors.mjs.map +1 -0
- package/dist/core/i18n/href.d.mts +28 -0
- package/dist/core/i18n/href.mjs +45 -0
- package/dist/core/i18n/href.mjs.map +1 -0
- package/dist/core/i18n/locale.d.mts +21 -0
- package/dist/core/i18n/locale.mjs +36 -0
- package/dist/core/i18n/locale.mjs.map +1 -0
- package/dist/core/i18n/match.d.mts +37 -0
- package/dist/core/i18n/match.mjs +82 -0
- package/dist/core/i18n/match.mjs.map +1 -0
- package/dist/core/i18n/types.d.mts +80 -0
- package/dist/core/index.d.mts +14 -5
- package/dist/core/index.mjs +9 -2
- package/dist/core/predictive-search/index.d.mts +2 -2
- package/dist/core/predictive-search/server-handlers.d.mts +27 -6
- package/dist/core/predictive-search/server-handlers.mjs +1 -4
- package/dist/core/predictive-search/server-handlers.mjs.map +1 -1
- package/dist/core/predictive-search/url.d.mts +2 -2
- package/dist/core/predictive-search/url.mjs.map +1 -1
- package/dist/core/product/accept-variant-id.mjs +1 -1
- package/dist/core/product/accept-variant-id.mjs.map +1 -1
- package/dist/core/request-context.d.mts +61 -35
- package/dist/core/request-context.mjs +11 -7
- package/dist/core/request-context.mjs.map +1 -1
- package/dist/core/request-routing/handle-shopify-routes.mjs.map +1 -1
- package/dist/core/request-routing/interceptors/api-proxy.mjs +9 -1
- package/dist/core/request-routing/interceptors/api-proxy.mjs.map +1 -1
- package/dist/core/request-routing/interceptors/checkout.mjs +11 -5
- package/dist/core/request-routing/interceptors/checkout.mjs.map +1 -1
- package/dist/core/request-routing/interceptors/standard-routes.mjs +1 -1
- package/dist/core/request-routing/interceptors/standard-routes.mjs.map +1 -1
- package/dist/core/request-routing/interceptors/url-redirects.mjs +2 -1
- package/dist/core/request-routing/interceptors/url-redirects.mjs.map +1 -1
- package/dist/core/request-routing/registered-routes.d.mts +10 -3
- package/dist/core/request-routing/registered-routes.mjs +13 -3
- package/dist/core/request-routing/registered-routes.mjs.map +1 -1
- package/dist/core/request-routing/route-types.d.mts +2 -2
- package/dist/core/shop-pay/shop-pay.mjs +5 -4
- package/dist/core/shop-pay/shop-pay.mjs.map +1 -1
- package/dist/core/shopify-scripts/analytics.mjs +3 -5
- package/dist/core/shopify-scripts/analytics.mjs.map +1 -1
- package/dist/core/shopify-scripts/constants.mjs +3 -1
- package/dist/core/shopify-scripts/constants.mjs.map +1 -1
- package/dist/core/shopify-scripts/global.mjs +13 -11
- package/dist/core/shopify-scripts/global.mjs.map +1 -1
- package/dist/core/shopify-scripts/hashes.d.mts +17 -0
- package/dist/core/shopify-scripts/hashes.mjs +12 -0
- package/dist/core/shopify-scripts/hashes.mjs.map +1 -0
- package/dist/core/shopify-scripts/index.d.mts +1 -0
- package/dist/core/shopify-scripts/index.mjs +12 -9
- package/dist/core/shopify-scripts/index.mjs.map +1 -1
- package/dist/core/shopify-scripts/page-view.mjs +4 -1
- package/dist/core/shopify-scripts/page-view.mjs.map +1 -1
- package/dist/core/shopify-scripts/types.d.mts +4 -2
- package/dist/core/shopify-scripts/utils/inline-script.mjs +4 -1
- package/dist/core/shopify-scripts/utils/inline-script.mjs.map +1 -1
- package/dist/core/standard-routes/build.d.mts +7 -2
- package/dist/core/standard-routes/build.mjs +10 -3
- package/dist/core/standard-routes/build.mjs.map +1 -1
- package/dist/core/standard-routes/match.mjs +11 -1
- package/dist/core/standard-routes/match.mjs.map +1 -1
- package/dist/core/standard-routes/path.mjs +14 -3
- package/dist/core/standard-routes/path.mjs.map +1 -1
- package/dist/core/standard-routes/types.d.mts +6 -1
- package/dist/core/url.mjs +5 -3
- package/dist/core/url.mjs.map +1 -1
- package/dist/customer-account/client.d.mts +14 -10
- package/dist/customer-account/client.mjs +4 -5
- package/dist/customer-account/client.mjs.map +1 -1
- package/dist/customer-account/graphql.d.mts +7 -1
- package/dist/customer-account/graphql.mjs +6 -7
- package/dist/customer-account/graphql.mjs.map +1 -1
- package/dist/customer-account/session.mjs +3 -4
- package/dist/customer-account/session.mjs.map +1 -1
- package/dist/development/client/client.mjs +44 -9
- package/dist/development/client/client.mjs.map +1 -1
- package/dist/development/client/i18n-variables.d.mts +1 -1
- package/dist/development/client/i18n-variables.mjs +13 -5
- package/dist/development/client/i18n-variables.mjs.map +1 -1
- package/dist/development/client/types.d.mts +12 -6
- package/dist/development/core/cache/fetch-with-cache.mjs +8 -1
- package/dist/development/core/cache/fetch-with-cache.mjs.map +1 -1
- package/dist/development/core/cart/cart.mjs +1 -1
- package/dist/development/core/cart/cookie.mjs +6 -1
- package/dist/development/core/cart/cookie.mjs.map +1 -1
- package/dist/development/core/cart/form.d.mts +17 -5
- package/dist/development/core/cart/form.mjs +5 -0
- package/dist/development/core/cart/form.mjs.map +1 -1
- package/dist/development/core/cart/index.d.mts +1 -1
- package/dist/development/core/cart/queries.d.mts +57 -57
- package/dist/development/core/collection/url.mjs +8 -1
- package/dist/development/core/collection/url.mjs.map +1 -1
- package/dist/development/core/constants.mjs +2 -1
- package/dist/development/core/constants.mjs.map +1 -1
- package/dist/development/core/csp/index.d.mts +56 -0
- package/dist/development/core/csp/index.mjs +128 -0
- package/dist/development/core/csp/index.mjs.map +1 -0
- package/dist/development/core/csp/types.d.mts +52 -0
- package/dist/development/core/development.d.mts +14 -5
- package/dist/development/core/development.mjs +9 -2
- package/dist/development/core/headers.mjs +2 -2
- package/dist/development/core/headers.mjs.map +1 -1
- package/dist/development/core/i18n/define.d.mts +54 -0
- package/dist/development/core/i18n/define.mjs +135 -0
- package/dist/development/core/i18n/define.mjs.map +1 -0
- package/dist/development/core/i18n/errors.d.mts +18 -0
- package/dist/development/core/i18n/errors.mjs +24 -0
- package/dist/development/core/i18n/errors.mjs.map +1 -0
- package/dist/development/core/i18n/href.d.mts +28 -0
- package/dist/development/core/i18n/href.mjs +45 -0
- package/dist/development/core/i18n/href.mjs.map +1 -0
- package/dist/development/core/i18n/locale.d.mts +21 -0
- package/dist/development/core/i18n/locale.mjs +36 -0
- package/dist/development/core/i18n/locale.mjs.map +1 -0
- package/dist/development/core/i18n/match.d.mts +37 -0
- package/dist/development/core/i18n/match.mjs +82 -0
- package/dist/development/core/i18n/match.mjs.map +1 -0
- package/dist/development/core/i18n/types.d.mts +80 -0
- package/dist/development/core/index.d.mts +13 -4
- package/dist/development/core/predictive-search/index.d.mts +2 -2
- package/dist/development/core/predictive-search/queries.d.mts +2 -2
- package/dist/development/core/predictive-search/server-handlers.d.mts +27 -6
- package/dist/development/core/predictive-search/server-handlers.mjs +1 -4
- package/dist/development/core/predictive-search/server-handlers.mjs.map +1 -1
- package/dist/development/core/predictive-search/url.d.mts +2 -2
- package/dist/development/core/predictive-search/url.mjs.map +1 -1
- package/dist/development/core/product/accept-variant-id.mjs +1 -1
- package/dist/development/core/product/accept-variant-id.mjs.map +1 -1
- package/dist/development/core/request-context.d.mts +61 -35
- package/dist/development/core/request-context.mjs +11 -7
- package/dist/development/core/request-context.mjs.map +1 -1
- package/dist/development/core/request-routing/handle-shopify-routes.mjs.map +1 -1
- package/dist/development/core/request-routing/interceptors/api-proxy.mjs +9 -1
- package/dist/development/core/request-routing/interceptors/api-proxy.mjs.map +1 -1
- package/dist/development/core/request-routing/interceptors/checkout.mjs +11 -5
- package/dist/development/core/request-routing/interceptors/checkout.mjs.map +1 -1
- package/dist/development/core/request-routing/interceptors/standard-routes.mjs +1 -1
- package/dist/development/core/request-routing/interceptors/standard-routes.mjs.map +1 -1
- package/dist/development/core/request-routing/interceptors/url-redirects.mjs +2 -1
- package/dist/development/core/request-routing/interceptors/url-redirects.mjs.map +1 -1
- package/dist/development/core/request-routing/registered-routes.d.mts +10 -3
- package/dist/development/core/request-routing/registered-routes.mjs +13 -3
- package/dist/development/core/request-routing/registered-routes.mjs.map +1 -1
- package/dist/development/core/request-routing/route-types.d.mts +2 -2
- package/dist/development/core/shop-pay/shop-pay.mjs +5 -4
- package/dist/development/core/shop-pay/shop-pay.mjs.map +1 -1
- package/dist/development/core/shopify-scripts/analytics.mjs +3 -5
- package/dist/development/core/shopify-scripts/analytics.mjs.map +1 -1
- package/dist/development/core/shopify-scripts/constants.mjs +3 -1
- package/dist/development/core/shopify-scripts/constants.mjs.map +1 -1
- package/dist/development/core/shopify-scripts/global.mjs +13 -11
- package/dist/development/core/shopify-scripts/global.mjs.map +1 -1
- package/dist/development/core/shopify-scripts/hashes.d.mts +17 -0
- package/dist/development/core/shopify-scripts/hashes.mjs +12 -0
- package/dist/development/core/shopify-scripts/hashes.mjs.map +1 -0
- package/dist/development/core/shopify-scripts/index.d.mts +1 -0
- package/dist/development/core/shopify-scripts/index.mjs +12 -9
- package/dist/development/core/shopify-scripts/index.mjs.map +1 -1
- package/dist/development/core/shopify-scripts/page-view.mjs +4 -1
- package/dist/development/core/shopify-scripts/page-view.mjs.map +1 -1
- package/dist/development/core/shopify-scripts/types.d.mts +4 -2
- package/dist/development/core/shopify-scripts/utils/inline-script.mjs +4 -1
- package/dist/development/core/shopify-scripts/utils/inline-script.mjs.map +1 -1
- package/dist/development/core/standard-routes/build.d.mts +7 -2
- package/dist/development/core/standard-routes/build.mjs +10 -3
- package/dist/development/core/standard-routes/build.mjs.map +1 -1
- package/dist/development/core/standard-routes/match.mjs +11 -1
- package/dist/development/core/standard-routes/match.mjs.map +1 -1
- package/dist/development/core/standard-routes/path.mjs +14 -3
- package/dist/development/core/standard-routes/path.mjs.map +1 -1
- package/dist/development/core/standard-routes/types.d.mts +6 -1
- package/dist/development/core/url.mjs +5 -3
- package/dist/development/core/url.mjs.map +1 -1
- package/dist/development/customer-account/session.mjs.map +1 -1
- package/dist/development/globals.d.mts +8 -4
- package/dist/development/graphql/type-resolver.d.mts +13 -1
- package/dist/development/react/index.d.mts +2 -2
- package/dist/globals.d.mts +8 -4
- package/dist/graphql/type-resolver.d.mts +13 -1
- package/dist/react/index.d.mts +2 -2
- package/dist/vite/index.mjs +1 -1
- package/dist/vue/shopify-scripts.d.mts +1 -1
- package/package.json +13 -3
- package/skills/hydrogen-analytics/SKILL.md +2 -2
- package/skills/hydrogen-analytics/references/react.md +2 -2
- package/skills/hydrogen-markets/SKILL.md +127 -93
- package/skills/hydrogen-markets/references/nextjs.md +77 -87
- package/skills/hydrogen-oxygen/references/react-router.md +1 -2
- package/skills/hydrogen-predictive-search/SKILL.md +18 -1
- package/skills/hydrogen-request-handlers/SKILL.md +23 -5
- package/skills/hydrogen-request-handlers/references/content-security-policy.md +103 -0
- package/skills/hydrogen-request-handlers/references/frameworks.md +8 -6
- package/skills/hydrogen-request-handlers/references/nextjs.md +7 -3
- package/skills/hydrogen-request-handlers/references/nuxt.md +7 -5
- package/skills/hydrogen-robots-txt/SKILL.md +87 -0
- package/skills/hydrogen-routing/SKILL.md +36 -14
- package/skills/hydrogen-setup/SKILL.md +2 -2
- package/skills/hydrogen-setup/references/analytics.md +5 -5
- package/skills/hydrogen-setup/steps/2-scaffold.md +3 -0
- package/skills/hydrogen-setup/steps/7-shopify-runtime-scripts.md +4 -3
- package/skills/hydrogen-setup/steps/9-account-page.md +1 -1
- package/skills/hydrogen-smoke-test/SKILL.md +9 -2
- package/skills/hydrogen-storefront-client/SKILL.md +27 -9
- package/skills/hydrogen-storefront-client/references/astro.md +8 -3
- package/skills/hydrogen-storefront-client/references/caching.md +2 -0
- package/skills/hydrogen-storefront-client/references/nextjs.md +8 -3
- package/skills/hydrogen-storefront-client/references/nuxt.md +9 -5
- package/skills/hydrogen-storefront-client/references/react-router.md +6 -3
- package/skills/hydrogen-storefront-client/references/solidstart.md +6 -2
- package/skills/hydrogen-storefront-client/references/sveltekit.md +10 -4
- package/skills/migrate-to-hydrogen-2026-10/SKILL.md +20 -22
- package/skills/migrate-to-hydrogen-2026-10/references/sitemap-and-seo.md +1 -0
- package/skills/migrate-to-hydrogen-2026-10/references/typescript-and-gql-tada.md +1 -1
package/README.md
CHANGED
|
@@ -64,14 +64,12 @@ The editor plugin generates `storefront-graphql-env.d.ts` and `customer-account-
|
|
|
64
64
|
Use `@shopify/hydrogen/customer-account` for type-safe Customer Account API requests from server code:
|
|
65
65
|
|
|
66
66
|
```ts
|
|
67
|
-
import { createShopifyRequestContext } from "@shopify/hydrogen";
|
|
67
|
+
import { createShopifyRequestContext, defineShopifyI18n } from "@shopify/hydrogen";
|
|
68
68
|
import * as CAAPI from "@shopify/hydrogen/customer-account";
|
|
69
69
|
|
|
70
70
|
const CUSTOMER_QUERY = CAAPI.gql(`query { customer { firstName emailAddress { emailAddress } } }`);
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
i18n: { country: "US", language: "EN" },
|
|
74
|
-
});
|
|
71
|
+
const i18n = defineShopifyI18n({ defaultLocale: { country: "US", language: "EN" } });
|
|
72
|
+
const requestContext = createShopifyRequestContext({ request, i18n });
|
|
75
73
|
|
|
76
74
|
const customerAccount = CAAPI.createCustomerAccountClient({
|
|
77
75
|
shopId: env.SHOP_ID,
|
package/dist/cli/index.mjs
CHANGED
|
@@ -976,8 +976,8 @@ function spawnRunCommand(command, args, options) {
|
|
|
976
976
|
});
|
|
977
977
|
});
|
|
978
978
|
}
|
|
979
|
-
const TEMPLATE_TARBALL_URL = "https://codeload.github.com/Shopify/hydrogen/tar.gz/dist
|
|
980
|
-
const TEMPLATE_TARBALL_PREFIX = "hydrogen-dist
|
|
979
|
+
const TEMPLATE_TARBALL_URL = "https://codeload.github.com/Shopify/hydrogen/tar.gz/dist";
|
|
980
|
+
const TEMPLATE_TARBALL_PREFIX = "hydrogen-dist/templates/react-router/";
|
|
981
981
|
const TEMPLATE_TARBALL_STRIP_COMPONENTS = TEMPLATE_TARBALL_PREFIX.split("/").filter(Boolean).length;
|
|
982
982
|
async function promptSetupChoice(log) {
|
|
983
983
|
log("\nNo project found in this directory.\n");
|
package/dist/client/client.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { normalizeStoreDomain } from "../core/url.mjs";
|
|
2
2
|
import { getHydrogenCacheStatus } from "../core/cache/cache-status.mjs";
|
|
3
3
|
import { createFetchWithCache } from "../core/cache/fetch-with-cache.mjs";
|
|
4
|
-
import { DEFAULT_TIMEOUT_IN_MS, STOREFRONT_API_VERSION } from "../core/constants.mjs";
|
|
4
|
+
import { DEFAULT_TIMEOUT_IN_MS, HYDROGEN_USER_AGENT, STOREFRONT_API_VERSION } from "../core/constants.mjs";
|
|
5
5
|
import { HYDROGEN_VERSION_HEADER, REQUEST_GROUP_ID_HEADER, SDK_VARIANT_HEADER, SDK_VARIANT_SOURCE_HEADER, SDK_VERSION_HEADER, SHOPIFY_STOREFRONT_S_HEADER, SHOPIFY_STOREFRONT_Y_HEADER, SHOPIFY_UNIQUE_TOKEN_HEADER, SHOPIFY_VISIT_TOKEN_HEADER, STOREFRONT_ACCESS_TOKEN_HEADER, STOREFRONT_BUYER_IP_HEADER, STOREFRONT_ID_HEADER, STOREFRONT_PRIVATE_TOKEN_HEADER } from "../core/headers.mjs";
|
|
6
6
|
import { StorefrontApiError, StorefrontTimeoutError } from "./errors.mjs";
|
|
7
7
|
import { getI18nVariableNames } from "./i18n-variables.mjs";
|
|
@@ -26,8 +26,17 @@ const REQUEST_IDENTITY_HEADERS = new Set([
|
|
|
26
26
|
SHOPIFY_STOREFRONT_Y_HEADER.toLowerCase(),
|
|
27
27
|
SHOPIFY_STOREFRONT_S_HEADER.toLowerCase()
|
|
28
28
|
]);
|
|
29
|
+
const REDIRECT_STATUSES = new Set([
|
|
30
|
+
301,
|
|
31
|
+
302,
|
|
32
|
+
303,
|
|
33
|
+
307,
|
|
34
|
+
308
|
|
35
|
+
]);
|
|
29
36
|
const CACHE_ENABLED_GRAPHQL_CLIENTS = /* @__PURE__ */ new WeakSet();
|
|
30
37
|
const SHOULD_CACHE_RESULT = Symbol();
|
|
38
|
+
const PRIVATE_RESPONSE_DIRECTIVES = new Set(["private", "no-store"]);
|
|
39
|
+
const STOREFRONT_PRIVATE_RESPONSE_PERSONALIZATION_REASON = "storefront-api-private-response";
|
|
31
40
|
var StorefrontCacheConfigError = class extends Error {};
|
|
32
41
|
function withStorefrontClientCache(client, options, strategy, shouldCacheResult) {
|
|
33
42
|
if (!CACHE_ENABLED_GRAPHQL_CLIENTS.has(client.graphql)) return options;
|
|
@@ -56,6 +65,7 @@ function createStorefrontClient(args) {
|
|
|
56
65
|
const timeoutInMs = config.defaultTimeoutInMs ?? 3e4;
|
|
57
66
|
if (timeoutInMs < 0 || Number.isNaN(timeoutInMs)) throw new Error("defaultTimeoutInMs must be a non-negative number");
|
|
58
67
|
const staticHeaders = { "content-type": "application/json" };
|
|
68
|
+
if (typeof document === "undefined") staticHeaders["user-agent"] = HYDROGEN_USER_AGENT;
|
|
59
69
|
if (config.storefrontId) staticHeaders[STOREFRONT_ID_HEADER] = config.storefrontId;
|
|
60
70
|
switch (clientType) {
|
|
61
71
|
case "private":
|
|
@@ -70,7 +80,7 @@ function createStorefrontClient(args) {
|
|
|
70
80
|
break;
|
|
71
81
|
default: throw new Error(`Unsupported client type: ${clientType}`);
|
|
72
82
|
}
|
|
73
|
-
const
|
|
83
|
+
const locale = requestContext.locale;
|
|
74
84
|
const requestHeaders = new Headers(staticHeaders);
|
|
75
85
|
requestContext.applyStorefrontRequestHeaders(requestHeaders);
|
|
76
86
|
if (clientType === "private") {
|
|
@@ -84,7 +94,7 @@ function createStorefrontClient(args) {
|
|
|
84
94
|
if (typeof queryText !== "string") throw new StorefrontApiError("Expected gql() to return a string at runtime. Check gql.tada version compatibility.");
|
|
85
95
|
if (opts.cache && !config.cache) throw new StorefrontCacheConfigError("Storefront API cache options require a cache configured in createStorefrontClient().");
|
|
86
96
|
if (opts.cache?.mode === "private") throw new StorefrontCacheConfigError("Storefront API cache mode 'private' is not supported yet. Use Cache() without private mode, or cache buyer-specific work with createRunWithCache() and an explicit private key.");
|
|
87
|
-
const variables = buildVariables(queryText, opts.variables,
|
|
97
|
+
const variables = buildVariables(queryText, opts.variables, locale);
|
|
88
98
|
const externalSignals = [requestContext.signal, opts.signal].filter((signal) => Boolean(signal));
|
|
89
99
|
const earlyAbortSignal = externalSignals.find((signal) => signal.aborted);
|
|
90
100
|
if (earlyAbortSignal) throw earlyAbortSignal.reason ?? new DOMException("signal is aborted without reason", "AbortError");
|
|
@@ -105,13 +115,26 @@ function createStorefrontClient(args) {
|
|
|
105
115
|
query: queryText,
|
|
106
116
|
variables
|
|
107
117
|
}),
|
|
118
|
+
redirect: "manual",
|
|
108
119
|
signal: externalSignals.length > 0 ? AbortSignal.any(externalSignals) : void 0
|
|
109
120
|
};
|
|
110
121
|
const response = await resolvedFetch(apiUrl, init, createStorefrontCacheOptions(apiUrl, init, queryText, opts.cache, opts[SHOULD_CACHE_RESULT], timeoutInMs > 0 ? timeoutInMs : DEFAULT_TIMEOUT_IN_MS));
|
|
111
122
|
responseHeaders = response.headers;
|
|
112
|
-
if (getHydrogenCacheStatus(responseHeaders) !== "hit") requestContext.captureSubrequestHeaders(responseHeaders);
|
|
113
123
|
requestId = responseHeaders.get("x-request-id") ?? void 0;
|
|
114
124
|
status = response.status;
|
|
125
|
+
const isOpaqueRedirect = response.type === "opaqueredirect";
|
|
126
|
+
if (isOpaqueRedirect || REDIRECT_STATUSES.has(status)) {
|
|
127
|
+
response.body?.cancel().catch(() => {});
|
|
128
|
+
const locationOrigin = getLocationOrigin(responseHeaders.get("location"), apiUrl);
|
|
129
|
+
throw new StorefrontApiError(isOpaqueRedirect ? "SFAPI responded with a redirect; redirects are not followed" : `SFAPI responded with a redirect (${status}${locationOrigin ? ` to ${locationOrigin}` : ""}); redirects are not followed`, {
|
|
130
|
+
status: isOpaqueRedirect ? void 0 : status,
|
|
131
|
+
requestId,
|
|
132
|
+
queryText,
|
|
133
|
+
variables
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
if (getHydrogenCacheStatus(responseHeaders) !== "hit") requestContext.captureSubrequestHeaders(responseHeaders);
|
|
137
|
+
if (isPrivateResponse(responseHeaders)) requestContext.markResponseAsPersonalized(STOREFRONT_PRIVATE_RESPONSE_PERSONALIZATION_REASON);
|
|
115
138
|
if (!response.ok) {
|
|
116
139
|
const bodyHint = await response.text().catch(() => "");
|
|
117
140
|
throw new StorefrontApiError(`SFAPI responded with ${status}${bodyHint ? `: ${bodyHint.slice(0, 200)}` : ""}`, {
|
|
@@ -161,7 +184,8 @@ function createStorefrontClient(args) {
|
|
|
161
184
|
}
|
|
162
185
|
const client = {
|
|
163
186
|
type: clientType,
|
|
164
|
-
i18n,
|
|
187
|
+
i18n: locale,
|
|
188
|
+
locale,
|
|
165
189
|
graphql,
|
|
166
190
|
apiUrl,
|
|
167
191
|
storeUrl,
|
|
@@ -171,9 +195,17 @@ function createStorefrontClient(args) {
|
|
|
171
195
|
if (config.cache) CACHE_ENABLED_GRAPHQL_CLIENTS.add(client.graphql);
|
|
172
196
|
return client;
|
|
173
197
|
}
|
|
174
|
-
function
|
|
198
|
+
function getLocationOrigin(location, baseUrl) {
|
|
199
|
+
if (!location) return void 0;
|
|
200
|
+
try {
|
|
201
|
+
return new URL(location, baseUrl).origin;
|
|
202
|
+
} catch {
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
function buildVariables(queryText, userVariables, locale) {
|
|
175
207
|
const variables = { ...userVariables };
|
|
176
|
-
for (const name of getI18nVariableNames(queryText)) variables[name] =
|
|
208
|
+
for (const name of getI18nVariableNames(queryText)) variables[name] = locale[name];
|
|
177
209
|
return variables;
|
|
178
210
|
}
|
|
179
211
|
function createStorefrontCacheOptions(apiUrl, init, queryText, strategy, shouldCacheResult, backgroundTimeoutInMs) {
|
|
@@ -182,8 +214,8 @@ function createStorefrontCacheOptions(apiUrl, init, queryText, strategy, shouldC
|
|
|
182
214
|
return {
|
|
183
215
|
key: createStorefrontCacheKey(apiUrl, init),
|
|
184
216
|
strategy,
|
|
185
|
-
shouldCacheResponse: async ({ json }) => {
|
|
186
|
-
if (!json) return false;
|
|
217
|
+
shouldCacheResponse: async ({ headers, json }) => {
|
|
218
|
+
if (!json || isPrivateResponse(headers)) return false;
|
|
187
219
|
const body = await json().catch(() => void 0);
|
|
188
220
|
if (typeof body !== "object" || body == null || Array.isArray(body) || "errors" in body) return false;
|
|
189
221
|
return shouldCacheResult?.(body) ?? true;
|
|
@@ -191,6 +223,9 @@ function createStorefrontCacheOptions(apiUrl, init, queryText, strategy, shouldC
|
|
|
191
223
|
backgroundSignal: () => AbortSignal.timeout(backgroundTimeoutInMs)
|
|
192
224
|
};
|
|
193
225
|
}
|
|
226
|
+
function isPrivateResponse(headers) {
|
|
227
|
+
return headers.get("cache-control")?.split(",").some((directive) => PRIVATE_RESPONSE_DIRECTIVES.has(directive.split("=")[0]?.trim().toLowerCase() ?? "")) ?? false;
|
|
228
|
+
}
|
|
194
229
|
function createStorefrontCacheKey(apiUrl, init) {
|
|
195
230
|
return [
|
|
196
231
|
"storefront-api",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.mjs","names":[],"sources":["../../src/client/client.ts"],"sourcesContent":["import type { TadaDocumentNode } from \"gql.tada\";\n\nimport { getHydrogenCacheStatus } from \"../core/cache/cache-status\";\nimport { createFetchWithCache } from \"../core/cache/fetch-with-cache\";\nimport type { FetchCacheOptions, FetchCacheResponseContext } from \"../core/cache/fetch-with-cache\";\nimport type { CacheInstance } from \"../core/cache/run-with-cache\";\nimport type { CachingStrategy } from \"../core/cache/strategies\";\nimport { DEFAULT_TIMEOUT_IN_MS, STOREFRONT_API_VERSION } from \"../core/constants\";\nimport {\n HYDROGEN_VERSION_HEADER,\n REQUEST_GROUP_ID_HEADER,\n SDK_VARIANT_HEADER,\n SDK_VARIANT_SOURCE_HEADER,\n SDK_VERSION_HEADER,\n SHOPIFY_STOREFRONT_S_HEADER,\n SHOPIFY_STOREFRONT_Y_HEADER,\n STOREFRONT_ACCESS_TOKEN_HEADER,\n STOREFRONT_BUYER_IP_HEADER,\n STOREFRONT_ID_HEADER,\n STOREFRONT_PRIVATE_TOKEN_HEADER,\n SHOPIFY_UNIQUE_TOKEN_HEADER,\n SHOPIFY_VISIT_TOKEN_HEADER,\n} from \"../core/headers\";\nimport type { I18nConfig, ShopifyRequestContext } from \"../core/request-context\";\nimport { normalizeStoreDomain } from \"../core/url\";\nimport type { AnyStorefrontQueryString } from \"../graphql\";\nimport { StorefrontApiError, StorefrontTimeoutError } from \"./errors\";\nimport { getI18nVariableNames } from \"./i18n-variables\";\nimport type {\n ClientType,\n CreateStorefrontClientArgs,\n GraphQLFormattedError,\n StorefrontClient,\n StorefrontGraphqlResult,\n} from \"./types\";\n\ntype DocLike = TadaDocumentNode<unknown, unknown> | AnyStorefrontQueryString;\ntype FetchInput = Parameters<typeof globalThis.fetch>[0];\ntype FetchInit = Parameters<typeof globalThis.fetch>[1];\ntype ResolvedStorefrontFetch = (\n input: FetchInput,\n init: FetchInit,\n cacheOptions: FetchCacheOptions | undefined,\n) => Promise<Response>;\n\nconst REQUEST_CACHE_KEY_HEADERS = new Set([\n \"content-type\",\n \"user-agent\",\n SDK_VARIANT_HEADER.toLowerCase(),\n SDK_VARIANT_SOURCE_HEADER.toLowerCase(),\n SDK_VERSION_HEADER.toLowerCase(),\n HYDROGEN_VERSION_HEADER.toLowerCase(),\n STOREFRONT_ACCESS_TOKEN_HEADER.toLowerCase(),\n STOREFRONT_PRIVATE_TOKEN_HEADER.toLowerCase(),\n]);\nconst REQUEST_IDENTITY_HEADERS = new Set([\n \"cookie\",\n REQUEST_GROUP_ID_HEADER.toLowerCase(),\n STOREFRONT_BUYER_IP_HEADER.toLowerCase(),\n SHOPIFY_UNIQUE_TOKEN_HEADER.toLowerCase(),\n SHOPIFY_VISIT_TOKEN_HEADER.toLowerCase(),\n SHOPIFY_STOREFRONT_Y_HEADER.toLowerCase(),\n SHOPIFY_STOREFRONT_S_HEADER.toLowerCase(),\n]);\nconst CACHE_ENABLED_GRAPHQL_CLIENTS = new WeakSet<StorefrontClient[\"graphql\"]>();\nconst SHOULD_CACHE_RESULT = Symbol();\n\ntype ShouldCacheResult = (body: object) => boolean;\n\nclass StorefrontCacheConfigError extends Error {}\n\nexport function withStorefrontClientCache<TOptions extends object>(\n client: Pick<StorefrontClient, \"graphql\">,\n options: TOptions,\n strategy: CachingStrategy,\n shouldCacheResult?: ShouldCacheResult,\n): TOptions {\n if (!CACHE_ENABLED_GRAPHQL_CLIENTS.has(client.graphql)) return options;\n\n return { ...options, cache: strategy, [SHOULD_CACHE_RESULT]: shouldCacheResult };\n}\n\n/**\n * Creates a Storefront API client that runs typed queries and mutations against your store.\n *\n * Set `type` based on where your code runs and whether customer context is available:\n *\n * | | `public` | `private` | `private_no_buyer_context` |\n * |------------------|------------------------------|-------------------------------|------------------------------|\n * | Runs in | Browser or mobile | Server-side rendering | Background server code |\n * | Token | Public access token, or none | Private access token | Private access token |\n * | Customer context | Browser request context | You forward trusted `buyerIp` | None |\n * | Best for | Client-side fetches | SSR with customer context | Webhooks, background jobs |\n *\n * Pass a request context from `createShopifyRequestContext`. The client forwards the incoming\n * request's cookies and `Sec-GPC` header to the Storefront API, and fills `$country`\n * and `$language` variables from the context's locale. The client reads the request headers once,\n * when you create the client. Create a client for each incoming request, and create a client at\n * module scope only with a static request context.\n *\n * Keep private clients in server code, where the token can't reach browsers. The function throws an\n * error when you create either private client type in a browser. The function throws a `TypeError`\n * when the request context of a `private` client has no `buyerIp`.\n *\n * @see [Storefront API authentication](https://shopify.dev/docs/api/storefront#authentication)\n * @publicDocs\n */\nexport function createStorefrontClient<\n const Type extends ClientType,\n const RequestContext extends ShopifyRequestContext,\n const CacheConfig extends CacheInstance | undefined = undefined,\n>(\n args: CreateStorefrontClientArgs<RequestContext, Type, CacheConfig>,\n): StorefrontClient<\n // Tuple-wrapped to stay non-distributive so an explicit\n // `CacheInstance | undefined` type argument yields one client type, not a\n // union. Note a *value* of that type still unlocks cache options: optional\n // property inference strips `undefined` before it reaches CacheConfig, so\n // definiteness is undecidable here — the runtime guard rejects cache\n // options when no cache instance was actually configured.\n [CacheConfig] extends [CacheInstance] ? { cache?: CachingStrategy } : {},\n Type,\n RequestContext\n>;\n/**\n * @param args The client type, request context, and store configuration for the new client.\n * @returns The client, with a `graphql()` method that runs queries and mutations.\n */\nexport function createStorefrontClient(args: CreateStorefrontClientArgs): StorefrontClient {\n const { config, requestContext, type: clientType } = args;\n\n if (!config.storeDomain) {\n throw new Error(\"storeDomain is required and must be non-empty\");\n }\n\n const storeUrl = normalizeStoreDomain(config.storeDomain);\n const apiVersion = config.apiVersion ?? STOREFRONT_API_VERSION;\n const apiUrl = `${storeUrl}/api/${apiVersion}/graphql.json`;\n\n const originFetch = config.fetch ?? globalThis.fetch;\n if (typeof originFetch !== \"function\") {\n throw new Error(\n \"No fetch function available. Pass a fetch option or ensure globalThis.fetch exists.\",\n );\n }\n const resolvedFetch = config.cache\n ? createFetchWithCache({\n cache: config.cache,\n waitUntil: config.waitUntil,\n fetch: originFetch as typeof globalThis.fetch,\n })\n : originFetch;\n\n const timeoutInMs = config.defaultTimeoutInMs ?? DEFAULT_TIMEOUT_IN_MS;\n if (timeoutInMs < 0 || Number.isNaN(timeoutInMs)) {\n throw new Error(\"defaultTimeoutInMs must be a non-negative number\");\n }\n\n const staticHeaders: Record<string, string> = {\n \"content-type\": \"application/json\",\n };\n if (config.storefrontId) {\n staticHeaders[STOREFRONT_ID_HEADER] = config.storefrontId;\n }\n\n switch (clientType) {\n case \"private\":\n case \"private_no_buyer_context\":\n if (typeof document !== \"undefined\") {\n throw new Error(\n \"private storefront tokens cannot be used in a browser context. Use a publicStorefrontToken instead.\",\n );\n }\n if (!config.privateStorefrontToken) {\n throw new Error(\"privateStorefrontToken is required\");\n }\n staticHeaders[STOREFRONT_PRIVATE_TOKEN_HEADER] = config.privateStorefrontToken;\n break;\n case \"public\":\n if (config.publicStorefrontToken !== undefined && !config.publicStorefrontToken) {\n throw new Error(\"publicStorefrontToken must be non-empty when provided\");\n }\n if (config.publicStorefrontToken) {\n staticHeaders[STOREFRONT_ACCESS_TOKEN_HEADER] = config.publicStorefrontToken;\n }\n break;\n default:\n clientType satisfies never;\n throw new Error(`Unsupported client type: ${clientType}`);\n }\n\n const i18n = requestContext.i18n;\n const requestHeaders = new Headers(staticHeaders);\n requestContext.applyStorefrontRequestHeaders(requestHeaders);\n\n if (clientType === \"private\") {\n const { buyerIp } = requestContext;\n if (!buyerIp) {\n throw new TypeError(\"requestContext.buyerIp is required for private Storefront API clients\");\n }\n requestHeaders.set(STOREFRONT_BUYER_IP_HEADER, buyerIp);\n }\n\n async function graphql(\n doc: DocLike | string,\n ...rest: [options?: Record<string, unknown>]\n ): Promise<StorefrontGraphqlResult<DocLike>> {\n const opts = (rest[0] ?? {}) as {\n variables?: Record<string, unknown>;\n signal?: AbortSignal;\n cache?: CachingStrategy;\n [SHOULD_CACHE_RESULT]?: ShouldCacheResult;\n };\n\n const queryText = typeof doc === \"string\" ? doc : (doc as unknown as string);\n if (typeof queryText !== \"string\") {\n throw new StorefrontApiError(\n \"Expected gql() to return a string at runtime. Check gql.tada version compatibility.\",\n );\n }\n\n if (opts.cache && !config.cache) {\n throw new StorefrontCacheConfigError(\n \"Storefront API cache options require a cache configured in createStorefrontClient().\",\n );\n }\n\n if (opts.cache?.mode === \"private\") {\n throw new StorefrontCacheConfigError(\n \"Storefront API cache mode 'private' is not supported yet. Use Cache() without private mode, or cache buyer-specific work with createRunWithCache() and an explicit private key.\",\n );\n }\n\n const variables = buildVariables(queryText, opts.variables, i18n);\n const externalSignals = [requestContext.signal, opts.signal].filter(\n (signal): signal is AbortSignal => Boolean(signal),\n );\n\n const earlyAbortSignal = externalSignals.find((signal) => signal.aborted);\n if (earlyAbortSignal) {\n throw (\n earlyAbortSignal.reason ??\n new DOMException(\"signal is aborted without reason\", \"AbortError\")\n );\n }\n\n let requestId: string | undefined;\n let responseHeaders: Headers;\n let responseText: string;\n let status: number;\n let timeoutSignal: AbortSignal | undefined;\n\n if (timeoutInMs > 0) {\n timeoutSignal = AbortSignal.timeout(timeoutInMs);\n externalSignals.push(timeoutSignal);\n }\n\n try {\n const init: PlainRequestInit = {\n method: \"POST\",\n headers: new Headers(requestHeaders),\n body: JSON.stringify({ query: queryText, variables }),\n signal: externalSignals.length > 0 ? AbortSignal.any(externalSignals) : undefined,\n };\n\n const cacheOptions = createStorefrontCacheOptions(\n apiUrl,\n init,\n queryText,\n opts.cache,\n opts[SHOULD_CACHE_RESULT],\n timeoutInMs > 0 ? timeoutInMs : DEFAULT_TIMEOUT_IN_MS,\n );\n const response = await (resolvedFetch as ResolvedStorefrontFetch)(apiUrl, init, cacheOptions);\n\n responseHeaders = response.headers;\n const hydrogenCacheStatus = getHydrogenCacheStatus(responseHeaders);\n if (hydrogenCacheStatus !== \"hit\") {\n requestContext.captureSubrequestHeaders(responseHeaders);\n }\n\n requestId = responseHeaders.get(\"x-request-id\") ?? undefined;\n status = response.status;\n\n if (!response.ok) {\n const bodyHint = await response.text().catch(() => \"\");\n throw new StorefrontApiError(\n `SFAPI responded with ${status}${bodyHint ? `: ${bodyHint.slice(0, 200)}` : \"\"}`,\n { status, requestId, queryText, variables },\n );\n }\n\n responseText = await response.text();\n } catch (error) {\n if (error instanceof StorefrontApiError) throw error;\n if (error instanceof StorefrontTimeoutError) throw error;\n if (error instanceof StorefrontCacheConfigError) throw error;\n if (\n error instanceof DOMException &&\n error.name === \"TimeoutError\" &&\n timeoutSignal?.aborted\n ) {\n throw new StorefrontTimeoutError(timeoutInMs);\n }\n if (error instanceof DOMException && error.name === \"AbortError\") {\n throw error;\n }\n throw new StorefrontApiError(\"SFAPI request failed\", { cause: error });\n }\n\n let json: unknown;\n try {\n json = JSON.parse(responseText);\n } catch (cause) {\n throw new StorefrontApiError(\n `Failed to parse SFAPI response as JSON (${apiUrl}, status ${status})` +\n (responseText ? `: ${responseText.slice(0, 200)}` : \"\"),\n { status, requestId, cause, queryText, variables },\n );\n }\n\n if (typeof json !== \"object\" || json === null || Array.isArray(json)) {\n throw new StorefrontApiError(\n `SFAPI returned unexpected JSON type: ${Array.isArray(json) ? \"array\" : typeof json}`,\n { status, requestId, queryText, variables },\n );\n }\n\n const body = json as { data?: unknown; errors?: GraphQLFormattedError[] };\n // Branch to populate the two arms of the StorefrontGraphqlResult union: callers\n // narrowing on `errors` get a non-null `data` only when no errors are present.\n if (body.errors) {\n return {\n data: body.data ?? null,\n errors: body.errors,\n headers: responseHeaders,\n };\n }\n return {\n data: body.data,\n headers: responseHeaders,\n };\n }\n\n const client: StorefrontClient = {\n type: clientType,\n i18n,\n graphql: graphql as StorefrontClient[\"graphql\"],\n apiUrl,\n storeUrl,\n storefrontId: config.storefrontId,\n requestContext,\n };\n\n if (config.cache) CACHE_ENABLED_GRAPHQL_CLIENTS.add(client.graphql);\n\n return client;\n}\n\nfunction buildVariables(\n queryText: string,\n userVariables: Record<string, unknown> | undefined,\n resolvedI18n: I18nConfig,\n): Record<string, unknown> {\n const variables: Record<string, unknown> = { ...userVariables };\n\n for (const name of getI18nVariableNames(queryText)) {\n variables[name] = resolvedI18n[name];\n }\n\n return variables;\n}\n\ntype PlainRequestInit = RequestInit & { headers: Headers; body: string; method: string };\n\nfunction createStorefrontCacheOptions(\n apiUrl: string,\n init: PlainRequestInit,\n queryText: string,\n strategy: CachingStrategy | undefined,\n shouldCacheResult: ShouldCacheResult | undefined,\n backgroundTimeoutInMs: number,\n): FetchCacheOptions | undefined {\n if (!strategy) return undefined;\n\n // Runtime only needs a safety belt for untyped callers. False positives are\n // acceptable because they bypass cache rather than risking mutation caching.\n if (/\\bmutation\\b/.test(queryText)) return undefined;\n\n return {\n key: createStorefrontCacheKey(apiUrl, init),\n strategy,\n shouldCacheResponse: async ({ json }: FetchCacheResponseContext) => {\n if (!json) return false;\n\n const body = await json().catch(() => undefined);\n if (typeof body !== \"object\" || body == null || Array.isArray(body) || \"errors\" in body) {\n return false;\n }\n\n return shouldCacheResult?.(body) ?? true;\n },\n // A refresh outlives the request that triggered it, so request and caller\n // aborts must not cancel it. It still needs a deadline, even when the caller\n // disabled the client timeout to own the foreground one.\n backgroundSignal: () => AbortSignal.timeout(backgroundTimeoutInMs),\n };\n}\n\nfunction createStorefrontCacheKey(apiUrl: string, init: PlainRequestInit) {\n return [\n \"storefront-api\",\n apiUrl,\n init.method,\n init.body,\n [...init.headers]\n .filter(([name]) => {\n const normalized = name.toLowerCase();\n return (\n REQUEST_CACHE_KEY_HEADERS.has(normalized) && !REQUEST_IDENTITY_HEADERS.has(normalized)\n );\n })\n .toSorted(([left], [right]) => left.localeCompare(right))\n .map(([name, value]) => `${name}:${value}`)\n .join(\"\\n\"),\n ] as const;\n}\n"],"mappings":";;;;;;;;;AA6CA,M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QAAQ,CACd,QAAQ,CAAC,UAAU;GAClB,MAAM,aAAa,KAAK,aAAa;AACrC,UACE,0BAA0B,IAAI,WAAW,IAAI,CAAC,yBAAyB,IAAI,WAAW;IAExF,CACD,UAAU,CAAC,OAAO,CAAC,WAAW,KAAK,cAAc,MAAM,CAAC,CACxD,KAAK,CAAC,MAAM,WAAW,GAAG,KAAK,GAAG,QAAQ,CAC1C,KAAK,KAAK;EACd"}
|
|
1
|
+
{"version":3,"file":"client.mjs","names":[],"sources":["../../src/client/client.ts"],"sourcesContent":["import type { TadaDocumentNode } from \"gql.tada\";\n\nimport { getHydrogenCacheStatus } from \"../core/cache/cache-status\";\nimport { createFetchWithCache } from \"../core/cache/fetch-with-cache\";\nimport type { FetchCacheOptions, FetchCacheResponseContext } from \"../core/cache/fetch-with-cache\";\nimport type { CacheInstance } from \"../core/cache/run-with-cache\";\nimport type { CachingStrategy } from \"../core/cache/strategies\";\nimport {\n DEFAULT_TIMEOUT_IN_MS,\n HYDROGEN_USER_AGENT,\n STOREFRONT_API_VERSION,\n} from \"../core/constants\";\nimport {\n HYDROGEN_VERSION_HEADER,\n REQUEST_GROUP_ID_HEADER,\n SDK_VARIANT_HEADER,\n SDK_VARIANT_SOURCE_HEADER,\n SDK_VERSION_HEADER,\n SHOPIFY_STOREFRONT_S_HEADER,\n SHOPIFY_STOREFRONT_Y_HEADER,\n STOREFRONT_ACCESS_TOKEN_HEADER,\n STOREFRONT_BUYER_IP_HEADER,\n STOREFRONT_ID_HEADER,\n STOREFRONT_PRIVATE_TOKEN_HEADER,\n SHOPIFY_UNIQUE_TOKEN_HEADER,\n SHOPIFY_VISIT_TOKEN_HEADER,\n} from \"../core/headers\";\nimport type { ShopifyLocale } from \"../core/i18n/types\";\nimport type { ShopifyRequestContext } from \"../core/request-context\";\nimport { normalizeStoreDomain } from \"../core/url\";\nimport type { AnyStorefrontQueryString } from \"../graphql\";\nimport { StorefrontApiError, StorefrontTimeoutError } from \"./errors\";\nimport { getI18nVariableNames } from \"./i18n-variables\";\nimport type {\n ClientType,\n CreateStorefrontClientArgs,\n GraphQLFormattedError,\n StorefrontClient,\n StorefrontGraphqlResult,\n} from \"./types\";\n\ntype DocLike = TadaDocumentNode<unknown, unknown> | AnyStorefrontQueryString;\ntype FetchInput = Parameters<typeof globalThis.fetch>[0];\ntype FetchInit = Parameters<typeof globalThis.fetch>[1];\ntype ResolvedStorefrontFetch = (\n input: FetchInput,\n init: FetchInit,\n cacheOptions: FetchCacheOptions | undefined,\n) => Promise<Response>;\n\nconst REQUEST_CACHE_KEY_HEADERS = new Set([\n \"content-type\",\n \"user-agent\",\n SDK_VARIANT_HEADER.toLowerCase(),\n SDK_VARIANT_SOURCE_HEADER.toLowerCase(),\n SDK_VERSION_HEADER.toLowerCase(),\n HYDROGEN_VERSION_HEADER.toLowerCase(),\n STOREFRONT_ACCESS_TOKEN_HEADER.toLowerCase(),\n STOREFRONT_PRIVATE_TOKEN_HEADER.toLowerCase(),\n]);\nconst REQUEST_IDENTITY_HEADERS = new Set([\n \"cookie\",\n REQUEST_GROUP_ID_HEADER.toLowerCase(),\n STOREFRONT_BUYER_IP_HEADER.toLowerCase(),\n SHOPIFY_UNIQUE_TOKEN_HEADER.toLowerCase(),\n SHOPIFY_VISIT_TOKEN_HEADER.toLowerCase(),\n SHOPIFY_STOREFRONT_Y_HEADER.toLowerCase(),\n SHOPIFY_STOREFRONT_S_HEADER.toLowerCase(),\n]);\n// 304 Not Modified is a 3xx but not a redirect, so it falls through to the non-OK handling.\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\nconst CACHE_ENABLED_GRAPHQL_CLIENTS = new WeakSet<StorefrontClient[\"graphql\"]>();\nconst SHOULD_CACHE_RESULT = Symbol();\nconst PRIVATE_RESPONSE_DIRECTIVES = new Set([\"private\", \"no-store\"]);\nconst STOREFRONT_PRIVATE_RESPONSE_PERSONALIZATION_REASON = \"storefront-api-private-response\";\n\ntype ShouldCacheResult = (body: object) => boolean;\n\nclass StorefrontCacheConfigError extends Error {}\n\nexport function withStorefrontClientCache<TOptions extends object>(\n client: Pick<StorefrontClient, \"graphql\">,\n options: TOptions,\n strategy: CachingStrategy,\n shouldCacheResult?: ShouldCacheResult,\n): TOptions {\n if (!CACHE_ENABLED_GRAPHQL_CLIENTS.has(client.graphql)) return options;\n\n return { ...options, cache: strategy, [SHOULD_CACHE_RESULT]: shouldCacheResult };\n}\n\n/**\n * Creates a Storefront API client that runs typed queries and mutations against your store.\n *\n * Set `type` based on where your code runs and whether customer context is available:\n *\n * | | `public` | `private` | `private_no_buyer_context` |\n * |------------------|------------------------------|-------------------------------|------------------------------|\n * | Runs in | Browser or mobile | Server-side rendering | Background server code |\n * | Token | Public access token, or none | Private access token | Private access token |\n * | Customer context | Browser request context | You forward trusted `buyerIp` | None |\n * | Best for | Client-side fetches | SSR with customer context | Webhooks, background jobs |\n *\n * Pass a request context from `createShopifyRequestContext`. The client forwards the incoming\n * request's cookies and `Sec-GPC` header to the Storefront API, and fills `$country`\n * and `$language` variables from the context's locale. The client reads the request headers once,\n * when you create the client. Create a client for each incoming request, and create a client at\n * module scope only with a static request context.\n *\n * Keep private clients in server code, where the token can't reach browsers. The function throws an\n * error when you create either private client type in a browser. The function throws a `TypeError`\n * when the request context of a `private` client has no `buyerIp`.\n *\n * @see [Storefront API authentication](https://shopify.dev/docs/api/storefront#authentication)\n * @publicDocs\n */\nexport function createStorefrontClient<\n const Type extends ClientType,\n const RequestContext extends ShopifyRequestContext,\n const CacheConfig extends CacheInstance | undefined = undefined,\n>(\n args: CreateStorefrontClientArgs<RequestContext, Type, CacheConfig>,\n): StorefrontClient<\n // Tuple-wrapped to stay non-distributive so an explicit\n // `CacheInstance | undefined` type argument yields one client type, not a\n // union. Note a *value* of that type still unlocks cache options: optional\n // property inference strips `undefined` before it reaches CacheConfig, so\n // definiteness is undecidable here — the runtime guard rejects cache\n // options when no cache instance was actually configured.\n [CacheConfig] extends [CacheInstance] ? { cache?: CachingStrategy } : {},\n Type,\n RequestContext\n>;\n/**\n * @param args The client type, request context, and store configuration for the new client.\n * @returns The client, with a `graphql()` method that runs queries and mutations.\n */\nexport function createStorefrontClient(args: CreateStorefrontClientArgs): StorefrontClient {\n const { config, requestContext, type: clientType } = args;\n\n if (!config.storeDomain) {\n throw new Error(\"storeDomain is required and must be non-empty\");\n }\n\n const storeUrl = normalizeStoreDomain(config.storeDomain);\n const apiVersion = config.apiVersion ?? STOREFRONT_API_VERSION;\n const apiUrl = `${storeUrl}/api/${apiVersion}/graphql.json`;\n\n const originFetch = config.fetch ?? globalThis.fetch;\n if (typeof originFetch !== \"function\") {\n throw new Error(\n \"No fetch function available. Pass a fetch option or ensure globalThis.fetch exists.\",\n );\n }\n const resolvedFetch = config.cache\n ? createFetchWithCache({\n cache: config.cache,\n waitUntil: config.waitUntil,\n fetch: originFetch as typeof globalThis.fetch,\n })\n : originFetch;\n\n const timeoutInMs = config.defaultTimeoutInMs ?? DEFAULT_TIMEOUT_IN_MS;\n if (timeoutInMs < 0 || Number.isNaN(timeoutInMs)) {\n throw new Error(\"defaultTimeoutInMs must be a non-negative number\");\n }\n\n const staticHeaders: Record<string, string> = {\n \"content-type\": \"application/json\",\n };\n // Browsers drop a script-set User-Agent or send a CORS preflight for it.\n if (typeof document === \"undefined\") {\n staticHeaders[\"user-agent\"] = HYDROGEN_USER_AGENT;\n }\n if (config.storefrontId) {\n staticHeaders[STOREFRONT_ID_HEADER] = config.storefrontId;\n }\n\n switch (clientType) {\n case \"private\":\n case \"private_no_buyer_context\":\n if (typeof document !== \"undefined\") {\n throw new Error(\n \"private storefront tokens cannot be used in a browser context. Use a publicStorefrontToken instead.\",\n );\n }\n if (!config.privateStorefrontToken) {\n throw new Error(\"privateStorefrontToken is required\");\n }\n staticHeaders[STOREFRONT_PRIVATE_TOKEN_HEADER] = config.privateStorefrontToken;\n break;\n case \"public\":\n if (config.publicStorefrontToken !== undefined && !config.publicStorefrontToken) {\n throw new Error(\"publicStorefrontToken must be non-empty when provided\");\n }\n if (config.publicStorefrontToken) {\n staticHeaders[STOREFRONT_ACCESS_TOKEN_HEADER] = config.publicStorefrontToken;\n }\n break;\n default:\n clientType satisfies never;\n throw new Error(`Unsupported client type: ${clientType}`);\n }\n\n const locale = requestContext.locale;\n const requestHeaders = new Headers(staticHeaders);\n requestContext.applyStorefrontRequestHeaders(requestHeaders);\n\n if (clientType === \"private\") {\n const { buyerIp } = requestContext;\n if (!buyerIp) {\n throw new TypeError(\"requestContext.buyerIp is required for private Storefront API clients\");\n }\n requestHeaders.set(STOREFRONT_BUYER_IP_HEADER, buyerIp);\n }\n\n async function graphql(\n doc: DocLike | string,\n ...rest: [options?: Record<string, unknown>]\n ): Promise<StorefrontGraphqlResult<DocLike>> {\n const opts = (rest[0] ?? {}) as {\n variables?: Record<string, unknown>;\n signal?: AbortSignal;\n cache?: CachingStrategy;\n [SHOULD_CACHE_RESULT]?: ShouldCacheResult;\n };\n\n const queryText = typeof doc === \"string\" ? doc : (doc as unknown as string);\n if (typeof queryText !== \"string\") {\n throw new StorefrontApiError(\n \"Expected gql() to return a string at runtime. Check gql.tada version compatibility.\",\n );\n }\n\n if (opts.cache && !config.cache) {\n throw new StorefrontCacheConfigError(\n \"Storefront API cache options require a cache configured in createStorefrontClient().\",\n );\n }\n\n if (opts.cache?.mode === \"private\") {\n throw new StorefrontCacheConfigError(\n \"Storefront API cache mode 'private' is not supported yet. Use Cache() without private mode, or cache buyer-specific work with createRunWithCache() and an explicit private key.\",\n );\n }\n\n const variables = buildVariables(queryText, opts.variables, locale);\n const externalSignals = [requestContext.signal, opts.signal].filter(\n (signal): signal is AbortSignal => Boolean(signal),\n );\n\n const earlyAbortSignal = externalSignals.find((signal) => signal.aborted);\n if (earlyAbortSignal) {\n throw (\n earlyAbortSignal.reason ??\n new DOMException(\"signal is aborted without reason\", \"AbortError\")\n );\n }\n\n let requestId: string | undefined;\n let responseHeaders: Headers;\n let responseText: string;\n let status: number;\n let timeoutSignal: AbortSignal | undefined;\n\n if (timeoutInMs > 0) {\n timeoutSignal = AbortSignal.timeout(timeoutInMs);\n externalSignals.push(timeoutSignal);\n }\n\n try {\n const init: PlainRequestInit = {\n method: \"POST\",\n headers: new Headers(requestHeaders),\n body: JSON.stringify({ query: queryText, variables }),\n // Never follow redirects: runtimes forward custom Shopify credential headers across\n // origins, so a 3xx fails closed through the redirect check below.\n redirect: \"manual\",\n signal: externalSignals.length > 0 ? AbortSignal.any(externalSignals) : undefined,\n };\n\n const cacheOptions = createStorefrontCacheOptions(\n apiUrl,\n init,\n queryText,\n opts.cache,\n opts[SHOULD_CACHE_RESULT],\n timeoutInMs > 0 ? timeoutInMs : DEFAULT_TIMEOUT_IN_MS,\n );\n const response = await (resolvedFetch as ResolvedStorefrontFetch)(apiUrl, init, cacheOptions);\n\n responseHeaders = response.headers;\n requestId = responseHeaders.get(\"x-request-id\") ?? undefined;\n status = response.status;\n\n // Reject redirects before capturing headers so a rejected response can't set cookies.\n // Browsers hide a manual redirect's status behind an opaque response, so leave it out.\n const isOpaqueRedirect = response.type === \"opaqueredirect\";\n if (isOpaqueRedirect || REDIRECT_STATUSES.has(status)) {\n // Don't await: a cancel waits on any unread clone (tee) a custom fetch kept.\n void response.body?.cancel().catch(() => {});\n // Name only the target origin, which diagnoses a misconfigured `storeDomain` (e.g. an\n // `http://` domain redirected to https) without logging the target's path or query.\n const locationOrigin = getLocationOrigin(responseHeaders.get(\"location\"), apiUrl);\n throw new StorefrontApiError(\n isOpaqueRedirect\n ? \"SFAPI responded with a redirect; redirects are not followed\"\n : `SFAPI responded with a redirect (${status}${locationOrigin ? ` to ${locationOrigin}` : \"\"}); redirects are not followed`,\n { status: isOpaqueRedirect ? undefined : status, requestId, queryText, variables },\n );\n }\n\n const hydrogenCacheStatus = getHydrogenCacheStatus(responseHeaders);\n if (hydrogenCacheStatus !== \"hit\") {\n requestContext.captureSubrequestHeaders(responseHeaders);\n }\n if (isPrivateResponse(responseHeaders)) {\n requestContext.markResponseAsPersonalized(\n STOREFRONT_PRIVATE_RESPONSE_PERSONALIZATION_REASON,\n );\n }\n\n if (!response.ok) {\n const bodyHint = await response.text().catch(() => \"\");\n throw new StorefrontApiError(\n `SFAPI responded with ${status}${bodyHint ? `: ${bodyHint.slice(0, 200)}` : \"\"}`,\n { status, requestId, queryText, variables },\n );\n }\n\n responseText = await response.text();\n } catch (error) {\n if (error instanceof StorefrontApiError) throw error;\n if (error instanceof StorefrontTimeoutError) throw error;\n if (error instanceof StorefrontCacheConfigError) throw error;\n if (\n error instanceof DOMException &&\n error.name === \"TimeoutError\" &&\n timeoutSignal?.aborted\n ) {\n throw new StorefrontTimeoutError(timeoutInMs);\n }\n if (error instanceof DOMException && error.name === \"AbortError\") {\n throw error;\n }\n throw new StorefrontApiError(\"SFAPI request failed\", { cause: error });\n }\n\n let json: unknown;\n try {\n json = JSON.parse(responseText);\n } catch (cause) {\n throw new StorefrontApiError(\n `Failed to parse SFAPI response as JSON (${apiUrl}, status ${status})` +\n (responseText ? `: ${responseText.slice(0, 200)}` : \"\"),\n { status, requestId, cause, queryText, variables },\n );\n }\n\n if (typeof json !== \"object\" || json === null || Array.isArray(json)) {\n throw new StorefrontApiError(\n `SFAPI returned unexpected JSON type: ${Array.isArray(json) ? \"array\" : typeof json}`,\n { status, requestId, queryText, variables },\n );\n }\n\n const body = json as { data?: unknown; errors?: GraphQLFormattedError[] };\n // Branch to populate the two arms of the StorefrontGraphqlResult union: callers\n // narrowing on `errors` get a non-null `data` only when no errors are present.\n if (body.errors) {\n return {\n data: body.data ?? null,\n errors: body.errors,\n headers: responseHeaders,\n };\n }\n return {\n data: body.data,\n headers: responseHeaders,\n };\n }\n\n const client: StorefrontClient = {\n type: clientType,\n i18n: locale,\n locale,\n graphql: graphql as StorefrontClient[\"graphql\"],\n apiUrl,\n storeUrl,\n storefrontId: config.storefrontId,\n requestContext,\n };\n\n if (config.cache) CACHE_ENABLED_GRAPHQL_CLIENTS.add(client.graphql);\n\n return client;\n}\n\nfunction getLocationOrigin(location: string | null, baseUrl: string): string | undefined {\n if (!location) return undefined;\n try {\n return new URL(location, baseUrl).origin;\n } catch {\n return undefined;\n }\n}\n\nfunction buildVariables(\n queryText: string,\n userVariables: Record<string, unknown> | undefined,\n locale: ShopifyLocale,\n): Record<string, unknown> {\n const variables: Record<string, unknown> = { ...userVariables };\n\n for (const name of getI18nVariableNames(queryText)) {\n variables[name] = locale[name];\n }\n\n return variables;\n}\n\ntype PlainRequestInit = RequestInit & { headers: Headers; body: string; method: string };\n\nfunction createStorefrontCacheOptions(\n apiUrl: string,\n init: PlainRequestInit,\n queryText: string,\n strategy: CachingStrategy | undefined,\n shouldCacheResult: ShouldCacheResult | undefined,\n backgroundTimeoutInMs: number,\n): FetchCacheOptions | undefined {\n if (!strategy) return undefined;\n\n // Runtime only needs a safety belt for untyped callers. False positives are\n // acceptable because they bypass cache rather than risking mutation caching.\n if (/\\bmutation\\b/.test(queryText)) return undefined;\n\n return {\n key: createStorefrontCacheKey(apiUrl, init),\n strategy,\n shouldCacheResponse: async ({ headers, json }: FetchCacheResponseContext) => {\n if (!json || isPrivateResponse(headers)) return false;\n\n const body = await json().catch(() => undefined);\n if (typeof body !== \"object\" || body == null || Array.isArray(body) || \"errors\" in body) {\n return false;\n }\n\n return shouldCacheResult?.(body) ?? true;\n },\n // A refresh outlives the request that triggered it, so request and caller\n // aborts must not cancel it. It still needs a deadline, even when the caller\n // disabled the client timeout to own the foreground one.\n backgroundSignal: () => AbortSignal.timeout(backgroundTimeoutInMs),\n };\n}\n\nfunction isPrivateResponse(headers: Headers): boolean {\n return (\n headers\n .get(\"cache-control\")\n ?.split(\",\")\n .some((directive) =>\n PRIVATE_RESPONSE_DIRECTIVES.has(directive.split(\"=\")[0]?.trim().toLowerCase() ?? \"\"),\n ) ?? false\n );\n}\n\nfunction createStorefrontCacheKey(apiUrl: string, init: PlainRequestInit) {\n return [\n \"storefront-api\",\n apiUrl,\n init.method,\n init.body,\n [...init.headers]\n .filter(([name]) => {\n const normalized = name.toLowerCase();\n return (\n REQUEST_CACHE_KEY_HEADERS.has(normalized) && !REQUEST_IDENTITY_HEADERS.has(normalized)\n );\n })\n .toSorted(([left], [right]) => left.localeCompare(right))\n .map(([name, value]) => `${name}:${value}`)\n .join(\"\\n\"),\n ] as const;\n}\n"],"mappings":";;;;;;;;;AAkDA,MAAM,4BAA4B,IAAI,IAAI;CACxC;CACA;CACA,mBAAmB,aAAa;CAChC,0BAA0B,aAAa;CACvC,mBAAmB,aAAa;CAChC,wBAAwB,aAAa;CACrC,+BAA+B,aAAa;CAC5C,gCAAgC,aAAa;CAC9C,CAAC;AACF,MAAM,2BAA2B,IAAI,IAAI;CACvC;CACA,wBAAwB,aAAa;CACrC,2BAA2B,aAAa;CACxC,4BAA4B,aAAa;CACzC,2BAA2B,aAAa;CACxC,4BAA4B,aAAa;CACzC,4BAA4B,aAAa;CAC1C,CAAC;AAEF,MAAM,oBAAoB,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;CAAI,CAAC;AAC5D,MAAM,gDAAgC,IAAI,SAAsC;AAChF,MAAM,sBAAsB,QAAQ;AACpC,MAAM,8BAA8B,IAAI,IAAI,CAAC,WAAW,WAAW,CAAC;AACpE,MAAM,qDAAqD;AAI3D,IAAM,6BAAN,cAAyC,MAAM;AAE/C,SAAgB,0BACd,QACA,SACA,UACA,mBACU;AACV,KAAI,CAAC,8BAA8B,IAAI,OAAO,QAAQ,CAAE,QAAO;AAE/D,QAAO;EAAE,GAAG;EAAS,OAAO;GAAW,sBAAsB;EAAmB;;;;;;AAiDlF,SAAgB,uBAAuB,MAAoD;CACzF,MAAM,EAAE,QAAQ,gBAAgB,MAAM,eAAe;AAErD,KAAI,CAAC,OAAO,YACV,OAAM,IAAI,MAAM,gDAAgD;CAGlE,MAAM,WAAW,qBAAqB,OAAO,YAAY;CAEzD,MAAM,SAAS,GAAG,SAAS,OADR,OAAO,wBACmB;CAE7C,MAAM,cAAc,OAAO,SAAS,WAAW;AAC/C,KAAI,OA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C,UACE,0BAA0B,IAAI,WAAW,IAAI,CAAC,yBAAyB,IAAI,WAAW;IAExF,CACD,UAAU,CAAC,OAAO,CAAC,WAAW,KAAK,cAAc,MAAM,CAAC,CACxD,KAAK,CAAC,MAAM,WAAW,GAAG,KAAK,GAAG,QAAQ,CAC1C,KAAK,KAAK;EACd"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
//#region src/client/i18n-variables.d.ts
|
|
2
2
|
/**
|
|
3
|
-
* Variables the client fills from `requestContext.
|
|
3
|
+
* Variables the client fills from `requestContext.locale`, with the named type
|
|
4
4
|
* each must be declared as. Same-named variables of any other type belong to
|
|
5
5
|
* the caller.
|
|
6
6
|
*/
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
//#region src/client/i18n-variables.ts
|
|
2
2
|
/**
|
|
3
|
-
* Variables the client fills from `requestContext.
|
|
3
|
+
* Variables the client fills from `requestContext.locale`, with the named type
|
|
4
4
|
* each must be declared as. Same-named variables of any other type belong to
|
|
5
5
|
* the caller.
|
|
6
6
|
*/
|
|
@@ -31,18 +31,26 @@ const CLOSING = new Set([
|
|
|
31
31
|
* This is the same rule the `graphql()` variables type applies.
|
|
32
32
|
*/
|
|
33
33
|
function getI18nVariableNames(source) {
|
|
34
|
+
return getVariableNamesDeclaredAs(source, I18N_VARIABLE_TYPES);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Returns the names in `types` that the document's first operation declares
|
|
38
|
+
* with the mapped named type, nullable or non-null. List types never match.
|
|
39
|
+
* The runtime counterpart of `InferVariableNamesDeclaredAs`.
|
|
40
|
+
*/
|
|
41
|
+
function getVariableNamesDeclaredAs(source, types) {
|
|
34
42
|
const names = [];
|
|
35
43
|
for (const [name, colon, ...rest] of readFirstOperationVariables(tokenize(source))) {
|
|
36
|
-
if (colon !== ":" || !
|
|
44
|
+
if (colon !== ":" || !isKeyOf(types, name)) continue;
|
|
37
45
|
const typeEnd = rest.findIndex((token) => token === "=" || token === "@");
|
|
38
46
|
const type = rest.slice(0, typeEnd === -1 ? void 0 : typeEnd).join("");
|
|
39
|
-
const expected =
|
|
47
|
+
const expected = types[name];
|
|
40
48
|
if (type === expected || type === `${expected}!`) names.push(name);
|
|
41
49
|
}
|
|
42
50
|
return names;
|
|
43
51
|
}
|
|
44
|
-
function
|
|
45
|
-
return name !== void 0 && Object.hasOwn(
|
|
52
|
+
function isKeyOf(types, name) {
|
|
53
|
+
return name !== void 0 && Object.hasOwn(types, name);
|
|
46
54
|
}
|
|
47
55
|
function* tokenize(source) {
|
|
48
56
|
for (const [token] of source.matchAll(TOKEN_RE)) if (token[0] !== "#") yield token;
|
|
@@ -80,5 +88,5 @@ function readVariableDefinitions(tokens) {
|
|
|
80
88
|
}
|
|
81
89
|
|
|
82
90
|
//#endregion
|
|
83
|
-
export { getI18nVariableNames };
|
|
91
|
+
export { getI18nVariableNames, getVariableNamesDeclaredAs };
|
|
84
92
|
//# sourceMappingURL=i18n-variables.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"i18n-variables.mjs","names":[],"sources":["../../src/client/i18n-variables.ts"],"sourcesContent":["/**\n * Variables the client fills from `requestContext.
|
|
1
|
+
{"version":3,"file":"i18n-variables.mjs","names":[],"sources":["../../src/client/i18n-variables.ts"],"sourcesContent":["/**\n * Variables the client fills from `requestContext.locale`, with the named type\n * each must be declared as. Same-named variables of any other type belong to\n * the caller.\n */\nexport const I18N_VARIABLE_TYPES = {\n country: \"CountryCode\",\n language: \"LanguageCode\",\n} as const;\n\nexport type I18nVariableName = keyof typeof I18N_VARIABLE_TYPES;\n\n// Significant GraphQL tokens plus comments, which are dropped. Matching whole\n// strings keeps their contents from being read as declarations.\nconst TOKEN_RE =\n /\"\"\"(?:\\\\\"\"\"|[^])*?\"\"\"|\"(?:\\\\.|[^\"\\\\\\n\\r])*\"|#[^\\n\\r]*|[_A-Za-z][_0-9A-Za-z]*|[^\\s,]/g;\nconst NAME_RE = /^[_A-Za-z]/;\nconst OPERATION_TYPES = new Set([\"query\", \"mutation\", \"subscription\"]);\nconst OPENING = new Set([\"(\", \"[\", \"{\"]);\nconst CLOSING = new Set([\")\", \"]\", \"}\"]);\n\n/**\n * Returns the i18n variables that the document's first operation declares as\n * `$country: CountryCode` or `$language: LanguageCode`, nullable or non-null.\n * This is the same rule the `graphql()` variables type applies.\n */\nexport function getI18nVariableNames(source: string): I18nVariableName[] {\n return getVariableNamesDeclaredAs(source, I18N_VARIABLE_TYPES);\n}\n\n/**\n * Returns the names in `types` that the document's first operation declares\n * with the mapped named type, nullable or non-null. List types never match.\n * The runtime counterpart of `InferVariableNamesDeclaredAs`.\n */\nexport function getVariableNamesDeclaredAs<Types extends Readonly<Record<string, string>>>(\n source: string,\n types: Types,\n): Array<keyof Types & string> {\n const names: Array<keyof Types & string> = [];\n for (const [name, colon, ...rest] of readFirstOperationVariables(tokenize(source))) {\n if (colon !== \":\" || !isKeyOf(types, name)) continue;\n const typeEnd = rest.findIndex((token) => token === \"=\" || token === \"@\");\n const type = rest.slice(0, typeEnd === -1 ? undefined : typeEnd).join(\"\");\n const expected = types[name];\n if (type === expected || type === `${expected}!`) names.push(name);\n }\n return names;\n}\n\nfunction isKeyOf<Types extends object>(\n types: Types,\n name: string | undefined,\n): name is keyof Types & string {\n return name !== undefined && Object.hasOwn(types, name);\n}\n\nfunction* tokenize(source: string): Generator<string> {\n for (const [token] of source.matchAll(TOKEN_RE)) {\n if (token[0] !== \"#\") yield token;\n }\n}\n\nfunction readFirstOperationVariables(tokens: Generator<string>): string[][] {\n let depth = 0;\n let inFragment = false;\n for (const token of tokens) {\n if (depth === 0 && !inFragment) {\n if (OPERATION_TYPES.has(token)) return readOperationVariables(tokens);\n if (token === \"{\") return [];\n inFragment = token === \"fragment\";\n }\n if (OPENING.has(token)) depth++;\n else if (CLOSING.has(token) && --depth === 0 && token === \"}\") inFragment = false;\n }\n return [];\n}\n\nfunction readOperationVariables(tokens: Generator<string>): string[][] {\n let next = tokens.next().value;\n if (next && NAME_RE.test(next)) next = tokens.next().value;\n return next === \"(\" ? readVariableDefinitions(tokens) : [];\n}\n\n// Default values and directive arguments can nest `$` and `)`, so only depth 0 delimits definitions.\nfunction readVariableDefinitions(tokens: Generator<string>): string[][] {\n const definitions: string[][] = [];\n let depth = 0;\n for (const token of tokens) {\n if (depth === 0 && token === \")\") break;\n if (depth === 0 && token === \"$\") definitions.push([]);\n else definitions.at(-1)?.push(token);\n if (OPENING.has(token)) depth++;\n else if (CLOSING.has(token)) depth--;\n }\n return definitions;\n}\n"],"mappings":";;;;;;AAKA,MAAa,sBAAsB;CACjC,SAAS;CACT,UAAU;CACX;AAMD,MAAM,WACJ;AACF,MAAM,UAAU;AAChB,MAAM,kBAAkB,IAAI,IAAI;CAAC;CAAS;CAAY;CAAe,CAAC;AACtE,MAAM,UAAU,IAAI,IAAI;CAAC;CAAK;CAAK;CAAI,CAAC;AACxC,MAAM,UAAU,IAAI,IAAI;CAAC;CAAK;CAAK;CAAI,CAAC;;;;;;AAOxC,SAAgB,qBAAqB,QAAoC;AACvE,QAAO,2BAA2B,QAAQ,oBAAoB;;;;;;;AAQhE,SAAgB,2BACd,QACA,OAC6B;CAC7B,MAAM,QAAqC,EAAE;AAC7C,MAAK,MAAM,CAAC,MAAM,OAAO,GAAG,SAAS,4BAA4B,SAAS,OAAO,CAAC,EAAE;AAClF,MAAI,UAAU,OAAO,CAAC,QAAQ,OAAO,KAAK,CAAE;EAC5C,MAAM,UAAU,KAAK,WAAW,UAAU,UAAU,OAAO,UAAU,IAAI;EACzE,MAAM,OAAO,KAAK,MAAM,GAAG,YAAY,KAAK,SAAY,QAAQ,CAAC,KAAK,GAAG;EACzE,MAAM,WAAW,MAAM;AACvB,MAAI,SAAS,YAAY,SAAS,GAAG,SAAS,GAAI,OAAM,KAAK,KAAK;;AAEpE,QAAO;;AAGT,SAAS,QACP,OACA,MAC8B;AAC9B,QAAO,SAAS,UAAa,OAAO,OAAO,OAAO,KAAK;;AAGzD,UAAU,SAAS,QAAmC;AACpD,MAAK,MAAM,CAAC,UAAU,OAAO,SAAS,SAAS,CAC7C,KAAI,MAAM,OAAO,IAAK,OAAM;;AAIhC,SAAS,4BAA4B,QAAuC;CAC1E,IAAI,QAAQ;CACZ,IAAI,aAAa;AACjB,MAAK,MAAM,SAAS,QAAQ;AAC1B,MAAI,UAAU,KAAK,CAAC,YAAY;AAC9B,OAAI,gBAAgB,IAAI,MAAM,CAAE,QAAO,uBAAuB,OAAO;AACrE,OAAI,UAAU,IAAK,QAAO,EAAE;AAC5B,gBAAa,UAAU;;AAEzB,MAAI,QAAQ,IAAI,MAAM,CAAE;WACf,QAAQ,IAAI,MAAM,IAAI,EAAE,UAAU,KAAK,UAAU,IAAK,cAAa;;AAE9E,QAAO,EAAE;;AAGX,SAAS,uBAAuB,QAAuC;CACrE,IAAI,OAAO,OAAO,MAAM,CAAC;AACzB,KAAI,QAAQ,QAAQ,KAAK,KAAK,CAAE,QAAO,OAAO,MAAM,CAAC;AACrD,QAAO,SAAS,MAAM,wBAAwB,OAAO,GAAG,EAAE;;AAI5D,SAAS,wBAAwB,QAAuC;CACtE,MAAM,cAA0B,EAAE;CAClC,IAAI,QAAQ;AACZ,MAAK,MAAM,SAAS,QAAQ;AAC1B,MAAI,UAAU,KAAK,UAAU,IAAK;AAClC,MAAI,UAAU,KAAK,UAAU,IAAK,aAAY,KAAK,EAAE,CAAC;MACjD,aAAY,GAAG,GAAG,EAAE,KAAK,MAAM;AACpC,MAAI,QAAQ,IAAI,MAAM,CAAE;WACf,QAAQ,IAAI,MAAM,CAAE;;AAE/B,QAAO"}
|
package/dist/client/types.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { CacheInstance, WaitUntil } from "../core/cache/run-with-cache.mjs";
|
|
2
2
|
import { I18nConfig, ShopifyRequestContext, ShopifyRequestContextWithBuyerIp } from "../core/request-context.mjs";
|
|
3
3
|
import { introspection } from "../graphql/generated/graphql-env.mjs";
|
|
4
|
-
import { InferOperationKind, InferResult, InferVariableNamesDeclaredAs, InferVariables } from "../graphql/type-resolver.mjs";
|
|
4
|
+
import { InferOperationKind, InferResult, InferVariableNamesByEnumValue, InferVariableNamesDeclaredAs, InferVariables } from "../graphql/type-resolver.mjs";
|
|
5
5
|
import { AnyStorefrontQueryString, SourceOf, StorefrontQueryString } from "../graphql/graphql.mjs";
|
|
6
6
|
import { I18N_VARIABLE_TYPES } from "./i18n-variables.mjs";
|
|
7
7
|
import { ResultOf, TadaDocumentNode, VariablesOf } from "gql.tada";
|
|
@@ -69,7 +69,10 @@ type CommonOptions = {
|
|
|
69
69
|
defaultTimeoutInMs?: number;
|
|
70
70
|
/**
|
|
71
71
|
* The cache that stores query results. The client caches only queries that pass a `cache`
|
|
72
|
-
* strategy. The client never caches mutations
|
|
72
|
+
* strategy. The client never caches mutations, results with GraphQL errors, or responses whose
|
|
73
|
+
* `Cache-Control` header contains `private` or `no-store`. A response with either directive also
|
|
74
|
+
* makes the final response private when you call `applyResponseHeaders()`, whether or not the
|
|
75
|
+
* query passes a `cache` strategy.
|
|
73
76
|
*/
|
|
74
77
|
cache?: CacheInstance; /** Keeps the runtime alive while the client writes to the cache in the background, such as a worker's `waitUntil` function. Without the function, each cached query waits for its cache write before it resolves. */
|
|
75
78
|
waitUntil?: WaitUntil;
|
|
@@ -143,9 +146,7 @@ type CreateStorefrontClientArgs<RequestContext extends ShopifyRequestContext = S
|
|
|
143
146
|
};
|
|
144
147
|
};
|
|
145
148
|
type I18nVariableTypes = typeof I18N_VARIABLE_TYPES;
|
|
146
|
-
type
|
|
147
|
-
type IsExactly<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
|
|
148
|
-
type I18nVariableNamesByValue<Variables> = { [K in keyof Variables & keyof I18nVariableTypes]-?: IsExactly<NonNullable<Variables[K]>, I18nEnum<K>> extends true ? K : never }[keyof Variables & keyof I18nVariableTypes];
|
|
149
|
+
type I18nVariableNamesByValue<Variables> = InferVariableNamesByEnumValue<Variables, I18nVariableTypes, introspection>;
|
|
149
150
|
type I18nVariableNamesOfDoc<Doc> = [SourceText<Doc>] extends [never] ? I18nVariableNamesByValue<VariablesOfDoc<Doc>> : string extends SourceText<Doc> ? I18nVariableNamesByValue<VariablesOfDoc<Doc>> : InferVariableNamesDeclaredAs<SourceText<Doc>, I18nVariableTypes>;
|
|
150
151
|
/** Variables the caller passes: everything except the i18n variables the client injects. */
|
|
151
152
|
type UserVariables<Doc> = Omit<VariablesOfDoc<Doc>, I18nVariableNamesOfDoc<Doc>>;
|
|
@@ -215,7 +216,12 @@ type ClientType = /** Runs in the browser with a public access token or none. */
|
|
|
215
216
|
* typed result.
|
|
216
217
|
*/
|
|
217
218
|
type StorefrontClient<Extra extends Record<string, unknown> = {}, Type extends ClientType = ClientType, RequestContext extends ShopifyRequestContext = ShopifyRequestContext> = {
|
|
218
|
-
/** The client type that you passed to `createStorefrontClient`. */type: Type; /** The
|
|
219
|
+
/** The client type that you passed to `createStorefrontClient`. */type: Type; /** The locale resolved for this request. The client sends its country and language for `$country` and `$language` variables. */
|
|
220
|
+
locale: RequestContext["locale"];
|
|
221
|
+
/**
|
|
222
|
+
* The locale resolved for this request.
|
|
223
|
+
* @deprecated Use `locale` instead. Removed in the next major release.
|
|
224
|
+
*/
|
|
219
225
|
i18n: RequestContext["i18n"];
|
|
220
226
|
/**
|
|
221
227
|
* Runs a Storefront API query or mutation and returns a typed result. Pass a `gql` document or a
|
|
@@ -56,6 +56,10 @@ function createFetchWithCache({ fetch: customFetch, ...options }) {
|
|
|
56
56
|
...init,
|
|
57
57
|
signal: cacheOptions.backgroundSignal()
|
|
58
58
|
} : init);
|
|
59
|
+
if (isOpaqueResponse(response)) {
|
|
60
|
+
passthroughResponse = response;
|
|
61
|
+
throw new UnserializableResponseError();
|
|
62
|
+
}
|
|
59
63
|
if (!response.ok) {
|
|
60
64
|
if (isStaleIfErrorStatus(response.status)) {
|
|
61
65
|
if (!canSerializeBodyAsText(response)) {
|
|
@@ -170,7 +174,7 @@ function getSerializableHeaders(headers, cacheable) {
|
|
|
170
174
|
return [...headers].filter(([key]) => !excludedCachedResponseHeaders.has(key.toLowerCase()));
|
|
171
175
|
}
|
|
172
176
|
function annotateResponse(response, cacheStatus, options) {
|
|
173
|
-
if (options.annotateCacheStatus === false) return response;
|
|
177
|
+
if (options.annotateCacheStatus === false || isOpaqueResponse(response)) return response;
|
|
174
178
|
const headers = new Headers(response.headers);
|
|
175
179
|
headers.append("Cache-Status", cacheStatus);
|
|
176
180
|
return new Response(response.body, {
|
|
@@ -189,6 +193,9 @@ function getCacheStatusHeader(value) {
|
|
|
189
193
|
function isJsonResponse(response) {
|
|
190
194
|
return response.headers.get("content-type")?.toLowerCase().includes("json") ?? false;
|
|
191
195
|
}
|
|
196
|
+
function isOpaqueResponse(response) {
|
|
197
|
+
return response.type === "opaque" || response.type === "opaqueredirect";
|
|
198
|
+
}
|
|
192
199
|
function isStaleIfErrorStatus(status) {
|
|
193
200
|
return staleIfErrorStatuses.has(status);
|
|
194
201
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch-with-cache.mjs","names":[],"sources":["../../../src/core/cache/fetch-with-cache.ts"],"sourcesContent":["import { HYDROGEN_CACHE_STATUS_PRODUCT } from \"./cache-status\";\nimport { type CacheKey } from \"./key\";\nimport {\n type CreateRunWithCacheOptions,\n type RunWithCache,\n type RunWithCacheResult,\n StaleFallbackDisabledError,\n createRunWithCache,\n} from \"./run-with-cache\";\nimport { type SerializableCacheValue } from \"./store\";\nimport { NO_STORE, type CachingStrategy } from \"./strategies\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\ntype FetchInput = Parameters<typeof fetch>[0];\ntype FetchInit = Parameters<typeof fetch>[1];\n\ntype SerializableResponse = SerializableCacheValue & {\n body: string;\n cacheable: boolean;\n headers: [string, string][];\n status: number;\n statusText: string;\n};\n\nexport type FetchCacheResponseContext = {\n ok: boolean;\n status: number;\n statusText: string;\n headers: Headers;\n url: string;\n text(): Promise<string>;\n json?: () => Promise<unknown>;\n};\n\nexport type FetchCacheOptions = {\n /** Identifies the cached response. */\n key: CacheKey;\n /** Sets how long the response stays fresh, stale while revalidating, and stale after an error. */\n strategy: CachingStrategy;\n /** Set to `false` to leave the `Cache-Status` header off the response. */\n annotateCacheStatus?: boolean;\n /**\n * Decides whether to cache an OK response with a text body. Return `false` to skip caching the\n * response. Hydrogen never caches a response with an error status or a non-text body.\n */\n shouldCacheResponse?: (context: FetchCacheResponseContext) => MaybePromise<boolean>;\n /**\n * Creates the signal for a stale-while-revalidate refresh, which runs after\n * the caller already has the stale response. Without it, the refresh reuses\n * `init.signal`.\n */\n backgroundSignal?: () => AbortSignal;\n};\n\n/** A fetch function that caches the response when you pass cache options as the third argument. */\ntype FetchWithCache = {\n (input: FetchInput, init?: FetchInit): Promise<Response>;\n (input: FetchInput, init: FetchInit | undefined, options: FetchCacheOptions): Promise<Response>;\n};\n\n/** Pass a cache and an optional `waitUntil` function, or pass `runWithCache` from `createRunWithCache` to share its cache. Set `fetch` to replace the global fetch function. */\ntype CreateFetchWithCacheOptions = (\n | CreateRunWithCacheOptions\n | {\n runWithCache: RunWithCache;\n }\n) & {\n fetch?: typeof fetch;\n};\n\nconst excludedCachedResponseHeaders = new Set([\"set-cookie\", \"server-timing\"]);\nconst staleIfErrorStatuses = new Set([500, 502, 503, 504]);\n\nclass UnserializableResponseError extends StaleFallbackDisabledError {\n constructor() {\n super(\"Response body is not serializable for cache.\");\n }\n}\n\nclass StaleFallbackEligibleResponseError extends Error {\n constructor() {\n super(\"Origin returned an unserializable response eligible for stale-if-error fallback.\");\n }\n}\n\nclass ServerResponseError extends Error {\n readonly response: SerializableResponse;\n\n constructor(response: SerializableResponse) {\n super(\"Origin returned a response eligible for stale-if-error fallback.\");\n this.response = response;\n }\n}\n\n/**\n * Creates a fetch function that caches responses from third-party APIs. Call the function like\n * `fetch()`, and pass a `key` and `strategy` in the third argument to cache the response. Calls\n * without the third argument skip the cache. Return `false` from a `shouldCacheResponse` option to\n * skip caching one response.\n *\n * The function caches only OK responses with no body or with a JSON, text, XML, HTML, GraphQL, or JavaScript content type. Other responses skip the cache. The function removes the `set-cookie` and `server-timing` headers from each cached response, including the response that a cache miss returns. With `staleIfError`, the function serves a stale entry only after a `500`, `502`, `503`, or `504` status, or when the fetch throws.\n *\n * @param options - A cache, or the function from `createRunWithCache` to share its cache, plus an optional fetch function.\n * @returns A fetch function that adds a `Cache-Status` header to calls with cache options, unless `annotateCacheStatus` is `false`.\n * @publicDocs\n */\nexport function createFetchWithCache({\n fetch: customFetch,\n ...options\n}: CreateFetchWithCacheOptions): FetchWithCache {\n const resolvedFetch = customFetch ?? globalThis.fetch;\n const runWithCache =\n \"runWithCache\" in options ? options.runWithCache : createRunWithCache(options);\n\n return async function fetchWithCache(\n input: FetchInput,\n init?: FetchInit,\n cacheOptions?: FetchCacheOptions,\n ): Promise<Response> {\n if (!cacheOptions) return resolvedFetch(input, init);\n\n if (cacheOptions.strategy.mode === NO_STORE) {\n return annotateResponse(\n await resolvedFetch(input, init),\n getCacheStatusHeader(\"fwd=bypass\"),\n cacheOptions,\n );\n }\n\n let passthroughResponse: Response | undefined;\n let result: RunWithCacheResult<SerializableResponse>;\n\n try {\n result = await runWithCache<SerializableResponse>(\n {\n key: cacheOptions.key,\n strategy: cacheOptions.strategy,\n },\n async (context) => {\n const response = await resolvedFetch(\n input,\n context?.background && cacheOptions.backgroundSignal\n ? { ...init, signal: cacheOptions.backgroundSignal() }\n : init,\n );\n\n if (!response.ok) {\n if (isStaleIfErrorStatus(response.status)) {\n if (!canSerializeBodyAsText(response)) {\n passthroughResponse = response;\n throw new StaleFallbackEligibleResponseError();\n }\n\n throw new ServerResponseError(\n await serializeResponse(response, {\n cacheable: false,\n fallbackOnError: true,\n }),\n );\n }\n\n return {\n data: await serializeResponse(response, {\n cacheable: false,\n fallbackOnError: true,\n }),\n shouldCache: false,\n };\n }\n\n if (!canSerializeBodyAsText(response)) {\n passthroughResponse = response;\n\n // Signal bypass so the original streaming response can be returned\n // to this caller without attempting to serialize it for storage.\n throw new UnserializableResponseError();\n }\n\n const bodyReader = createBodyReader(response);\n const shouldCache = await shouldCacheResponse(response, bodyReader, cacheOptions);\n\n if (!shouldCache) {\n return {\n data: await serializeResponse(response, {\n bodyReader,\n cacheable: false,\n fallbackOnError: true,\n }),\n shouldCache: false,\n };\n }\n\n const data = await serializeResponse(response, {\n bodyReader,\n cacheable: true,\n fallbackOnError: true,\n });\n\n return {\n data,\n shouldCache: data.cacheable,\n };\n },\n );\n } catch (error) {\n if (error instanceof ServerResponseError) {\n return annotateResponse(\n fromSerializableResponse(error.response),\n getCacheStatusHeader(\"fwd=bypass\"),\n cacheOptions,\n );\n }\n\n if (error instanceof UnserializableResponseError) {\n return annotateResponse(\n // The raw Response body is not cache-serializable, so return the\n // original response. Refetch defensively if the response was not kept.\n passthroughResponse ?? (await resolvedFetch(input, init)),\n getCacheStatusHeader(\"fwd=bypass\"),\n cacheOptions,\n );\n }\n\n if (error instanceof StaleFallbackEligibleResponseError) {\n return annotateResponse(\n // Return the original unserializable response. This error type can\n // also trigger stale-if-error fallback when a stale entry exists.\n passthroughResponse ?? (await resolvedFetch(input, init)),\n getCacheStatusHeader(\"fwd=bypass\"),\n cacheOptions,\n );\n }\n\n throw error;\n }\n\n return annotateResponse(\n fromSerializableResponse(result.data),\n result.cacheStatus === \"hit\"\n ? getCacheStatusHeader(\"hit\")\n : getNonHitCacheStatusHeader(result.data.cacheable, result.cacheStatus),\n cacheOptions,\n );\n };\n}\n\nfunction shouldCacheResponse(\n response: Response,\n bodyReader: BodyReader,\n options: FetchCacheOptions,\n): MaybePromise<boolean> {\n const context: FetchCacheResponseContext = {\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n headers: new Headers(response.headers),\n url: response.url,\n text: bodyReader.text,\n };\n\n if (isJsonResponse(response)) {\n context.json = bodyReader.json;\n }\n\n return options.shouldCacheResponse?.(context) ?? true;\n}\n\ntype BodyReader = {\n text(): Promise<string>;\n json(): Promise<unknown>;\n};\n\ntype SerializeResponseOptions = {\n bodyReader?: BodyReader;\n cacheable: boolean;\n fallbackOnError?: boolean;\n};\n\nfunction createBodyReader(response: Response): BodyReader {\n let bodyText: Promise<string> | undefined;\n let bodyJson: Promise<unknown> | undefined;\n\n const text = () => {\n bodyText ??= response.text();\n return bodyText;\n };\n\n return {\n text,\n json() {\n bodyJson ??= text().then((value) => JSON.parse(value));\n return bodyJson;\n },\n };\n}\n\nasync function serializeResponse(\n response: Response,\n { bodyReader, cacheable, fallbackOnError = false }: SerializeResponseOptions,\n): Promise<SerializableResponse> {\n if (!canSerializeBodyAsText(response)) return emptySerializableResponse(response);\n\n try {\n return {\n body: await (bodyReader ?? createBodyReader(response)).text(),\n cacheable,\n headers: getSerializableHeaders(response.headers, cacheable),\n status: response.status,\n statusText: response.statusText,\n };\n } catch (error) {\n if (!fallbackOnError) throw error;\n return emptySerializableResponse(response);\n }\n}\n\nfunction fromSerializableResponse(response: SerializableResponse): Response {\n return new Response(response.body, {\n headers: response.headers,\n status: response.status,\n statusText: response.statusText,\n });\n}\n\nfunction emptySerializableResponse(response: Response): SerializableResponse {\n return {\n body: \"\",\n cacheable: false,\n headers: [],\n status: response.status,\n statusText: response.statusText,\n };\n}\n\nfunction getSerializableHeaders(headers: Headers, cacheable: boolean): [string, string][] {\n if (!cacheable) return [...headers];\n\n // Cacheable serialized responses can be returned to future requests, so\n // per-request headers must not be copied.\n return [...headers].filter(([key]) => !excludedCachedResponseHeaders.has(key.toLowerCase()));\n}\n\nfunction annotateResponse(\n response: Response,\n cacheStatus: string,\n options: FetchCacheOptions,\n): Response {\n if (options.annotateCacheStatus === false) return response;\n\n const headers = new Headers(response.headers);\n headers.append(\"Cache-Status\", cacheStatus);\n\n return new Response(response.body, {\n headers,\n status: response.status,\n statusText: response.statusText,\n });\n}\n\nfunction getNonHitCacheStatusHeader(shouldCache: boolean, cacheStatus: \"miss\" | \"bypass\"): string {\n if (cacheStatus === \"bypass\") return getCacheStatusHeader(\"fwd=bypass\");\n return shouldCache\n ? getCacheStatusHeader(\"fwd=uri-miss; stored\")\n : getCacheStatusHeader(\"fwd=bypass\");\n}\n\nfunction getCacheStatusHeader(value: string): string {\n return `${HYDROGEN_CACHE_STATUS_PRODUCT}; ${value}`;\n}\n\nfunction isJsonResponse(response: Response): boolean {\n return response.headers.get(\"content-type\")?.toLowerCase().includes(\"json\") ?? false;\n}\n\nfunction isStaleIfErrorStatus(status: number): boolean {\n return staleIfErrorStatuses.has(status);\n}\n\nfunction canSerializeBodyAsText(response: Response): boolean {\n if (response.body == null) return true;\n\n const contentType = response.headers.get(\"content-type\");\n return contentType != null && /\\b(json|text|xml|html|graphql|javascript)\\b/i.test(contentType);\n}\n"],"mappings":";;;;;AAuEA,MAAM,gCAAgC,IAAI,IAAI,CAAC,cAAc,gBAAgB,CAAC;AAC9E,MAAM,uBAAuB,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAI,CAAC;AAE1D,IAAM,8BAAN,cAA0C,2BAA2B;CACnE,cAAc;AACZ,QAAM,+CAA+C;;;AAIzD,IAAM,qCAAN,cAAiD,MAAM;CACrD,cAAc;AACZ,QAAM,mFAAmF;;;AAI7F,IAAM,sBAAN,cAAkC,MAAM;CACtC,AAAS;CAET,YAAY,UAAgC;AAC1C,QAAM,mEAAmE;AACzE,OAAK,WAAW;;;;;;;;;;;;;;;AAgBpB,SAAgB,qBAAqB,EACnC,OAAO,aACP,GAAG,WAC2C;CAC9C,MAAM,gBAAgB,eAAe,WAAW;CAChD,MAAM,eACJ,kBAAkB,UAAU,QAAQ,eAAe,mBAAmB,QAAQ;AAEhF,QAAO,eAAe,eACpB,OACA,MACA,cACmB;AACnB,MAAI,CAAC,aAAc,QAAO,cAAc,OAAO,KAAK;AAEpD,MAAI,aAAa,SAAS,oBACxB,QAAO,iBACL,MAAM,cAAc,OAAO,KAAK,EAChC,qBAAqB,aAAa,EAClC,aACD;EAGH,IAAI;EACJ,IA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,EAAE;EACX,QAAQ,SAAS;EACjB,YAAY,SAAS;EACtB;;AAGH,SAAS,uBAAuB,SAAkB,WAAwC;AACxF,KAAI,CAAC,UAAW,QAAO,CAAC,GAAG,QAAQ;AAInC,QAAO,CAAC,GAAG,QAAQ,CAAC,QAAQ,CAAC,SAAS,CAAC,8BAA8B,IAAI,IAAI,aAAa,CAAC,CAAC;;AAG9F,SAAS,iBACP,UACA,aACA,SACU;AACV,KAAI,QAAQ,wBAAwB,MAAO,QAAO;CAElD,MAAM,UAAU,IAAI,QAAQ,SAAS,QAAQ;AAC7C,SAAQ,OAAO,gBAAgB,YAAY;AAE3C,QAAO,IAAI,SAAS,SAAS,MAAM;EACjC;EACA,QAAQ,SAAS;EACjB,YAAY,SAAS;EACtB,CAAC;;AAGJ,SAAS,2BAA2B,aAAsB,aAAwC;AAChG,KAAI,gBAAgB,SAAU,QAAO,qBAAqB,aAAa;AACvE,QAAO,cACH,qBAAqB,uBAAuB,GAC5C,qBAAqB,aAAa;;AAGxC,SAAS,qBAAqB,OAAuB;AACnD,QAAO,GAAG,8BAA8B,IAAI;;AAG9C,SAAS,eAAe,UAA6B;AACnD,QAAO,SAAS,QAAQ,IAAI,eAAe,EAAE,aAAa,CAAC,SAAS,OAAO,IAAI;;AAGjF,SAAS,qBAAqB,QAAyB;AACrD,QAAO,qBAAqB,IAAI,OAAO;;AAGzC,SAAS,uBAAuB,UAA6B;AAC3D,KAAI,SAAS,QAAQ,KAAM,QAAO;CAElC,MAAM,cAAc,SAAS,QAAQ,IAAI,eAAe;AACxD,QAAO,eAAe,QAAQ,+CAA+C,KAAK,YAAY"}
|
|
1
|
+
{"version":3,"file":"fetch-with-cache.mjs","names":[],"sources":["../../../src/core/cache/fetch-with-cache.ts"],"sourcesContent":["import { HYDROGEN_CACHE_STATUS_PRODUCT } from \"./cache-status\";\nimport { type CacheKey } from \"./key\";\nimport {\n type CreateRunWithCacheOptions,\n type RunWithCache,\n type RunWithCacheResult,\n StaleFallbackDisabledError,\n createRunWithCache,\n} from \"./run-with-cache\";\nimport { type SerializableCacheValue } from \"./store\";\nimport { NO_STORE, type CachingStrategy } from \"./strategies\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\ntype FetchInput = Parameters<typeof fetch>[0];\ntype FetchInit = Parameters<typeof fetch>[1];\n\ntype SerializableResponse = SerializableCacheValue & {\n body: string;\n cacheable: boolean;\n headers: [string, string][];\n status: number;\n statusText: string;\n};\n\nexport type FetchCacheResponseContext = {\n ok: boolean;\n status: number;\n statusText: string;\n headers: Headers;\n url: string;\n text(): Promise<string>;\n json?: () => Promise<unknown>;\n};\n\nexport type FetchCacheOptions = {\n /** Identifies the cached response. */\n key: CacheKey;\n /** Sets how long the response stays fresh, stale while revalidating, and stale after an error. */\n strategy: CachingStrategy;\n /** Set to `false` to leave the `Cache-Status` header off the response. */\n annotateCacheStatus?: boolean;\n /**\n * Decides whether to cache an OK response with a text body. Return `false` to skip caching the\n * response. Hydrogen never caches a response with an error status or a non-text body.\n */\n shouldCacheResponse?: (context: FetchCacheResponseContext) => MaybePromise<boolean>;\n /**\n * Creates the signal for a stale-while-revalidate refresh, which runs after\n * the caller already has the stale response. Without it, the refresh reuses\n * `init.signal`.\n */\n backgroundSignal?: () => AbortSignal;\n};\n\n/** A fetch function that caches the response when you pass cache options as the third argument. */\ntype FetchWithCache = {\n (input: FetchInput, init?: FetchInit): Promise<Response>;\n (input: FetchInput, init: FetchInit | undefined, options: FetchCacheOptions): Promise<Response>;\n};\n\n/** Pass a cache and an optional `waitUntil` function, or pass `runWithCache` from `createRunWithCache` to share its cache. Set `fetch` to replace the global fetch function. */\ntype CreateFetchWithCacheOptions = (\n | CreateRunWithCacheOptions\n | {\n runWithCache: RunWithCache;\n }\n) & {\n fetch?: typeof fetch;\n};\n\nconst excludedCachedResponseHeaders = new Set([\"set-cookie\", \"server-timing\"]);\nconst staleIfErrorStatuses = new Set([500, 502, 503, 504]);\n\nclass UnserializableResponseError extends StaleFallbackDisabledError {\n constructor() {\n super(\"Response body is not serializable for cache.\");\n }\n}\n\nclass StaleFallbackEligibleResponseError extends Error {\n constructor() {\n super(\"Origin returned an unserializable response eligible for stale-if-error fallback.\");\n }\n}\n\nclass ServerResponseError extends Error {\n readonly response: SerializableResponse;\n\n constructor(response: SerializableResponse) {\n super(\"Origin returned a response eligible for stale-if-error fallback.\");\n this.response = response;\n }\n}\n\n/**\n * Creates a fetch function that caches responses from third-party APIs. Call the function like\n * `fetch()`, and pass a `key` and `strategy` in the third argument to cache the response. Calls\n * without the third argument skip the cache. Return `false` from a `shouldCacheResponse` option to\n * skip caching one response.\n *\n * The function caches only OK responses with no body or with a JSON, text, XML, HTML, GraphQL, or JavaScript content type. Other responses skip the cache. The function removes the `set-cookie` and `server-timing` headers from each cached response, including the response that a cache miss returns. With `staleIfError`, the function serves a stale entry only after a `500`, `502`, `503`, or `504` status, or when the fetch throws.\n *\n * @param options - A cache, or the function from `createRunWithCache` to share its cache, plus an optional fetch function.\n * @returns A fetch function that adds a `Cache-Status` header to calls with cache options, unless `annotateCacheStatus` is `false`.\n * @publicDocs\n */\nexport function createFetchWithCache({\n fetch: customFetch,\n ...options\n}: CreateFetchWithCacheOptions): FetchWithCache {\n const resolvedFetch = customFetch ?? globalThis.fetch;\n const runWithCache =\n \"runWithCache\" in options ? options.runWithCache : createRunWithCache(options);\n\n return async function fetchWithCache(\n input: FetchInput,\n init?: FetchInit,\n cacheOptions?: FetchCacheOptions,\n ): Promise<Response> {\n if (!cacheOptions) return resolvedFetch(input, init);\n\n if (cacheOptions.strategy.mode === NO_STORE) {\n return annotateResponse(\n await resolvedFetch(input, init),\n getCacheStatusHeader(\"fwd=bypass\"),\n cacheOptions,\n );\n }\n\n let passthroughResponse: Response | undefined;\n let result: RunWithCacheResult<SerializableResponse>;\n\n try {\n result = await runWithCache<SerializableResponse>(\n {\n key: cacheOptions.key,\n strategy: cacheOptions.strategy,\n },\n async (context) => {\n const response = await resolvedFetch(\n input,\n context?.background && cacheOptions.backgroundSignal\n ? { ...init, signal: cacheOptions.backgroundSignal() }\n : init,\n );\n\n // Opaque responses, such as a browser manual redirect, hide their status and body,\n // so return them unchanged instead of serializing them.\n if (isOpaqueResponse(response)) {\n passthroughResponse = response;\n throw new UnserializableResponseError();\n }\n\n if (!response.ok) {\n if (isStaleIfErrorStatus(response.status)) {\n if (!canSerializeBodyAsText(response)) {\n passthroughResponse = response;\n throw new StaleFallbackEligibleResponseError();\n }\n\n throw new ServerResponseError(\n await serializeResponse(response, {\n cacheable: false,\n fallbackOnError: true,\n }),\n );\n }\n\n return {\n data: await serializeResponse(response, {\n cacheable: false,\n fallbackOnError: true,\n }),\n shouldCache: false,\n };\n }\n\n if (!canSerializeBodyAsText(response)) {\n passthroughResponse = response;\n\n // Signal bypass so the original streaming response can be returned\n // to this caller without attempting to serialize it for storage.\n throw new UnserializableResponseError();\n }\n\n const bodyReader = createBodyReader(response);\n const shouldCache = await shouldCacheResponse(response, bodyReader, cacheOptions);\n\n if (!shouldCache) {\n return {\n data: await serializeResponse(response, {\n bodyReader,\n cacheable: false,\n fallbackOnError: true,\n }),\n shouldCache: false,\n };\n }\n\n const data = await serializeResponse(response, {\n bodyReader,\n cacheable: true,\n fallbackOnError: true,\n });\n\n return {\n data,\n shouldCache: data.cacheable,\n };\n },\n );\n } catch (error) {\n if (error instanceof ServerResponseError) {\n return annotateResponse(\n fromSerializableResponse(error.response),\n getCacheStatusHeader(\"fwd=bypass\"),\n cacheOptions,\n );\n }\n\n if (error instanceof UnserializableResponseError) {\n return annotateResponse(\n // The raw Response body is not cache-serializable, so return the\n // original response. Refetch defensively if the response was not kept.\n passthroughResponse ?? (await resolvedFetch(input, init)),\n getCacheStatusHeader(\"fwd=bypass\"),\n cacheOptions,\n );\n }\n\n if (error instanceof StaleFallbackEligibleResponseError) {\n return annotateResponse(\n // Return the original unserializable response. This error type can\n // also trigger stale-if-error fallback when a stale entry exists.\n passthroughResponse ?? (await resolvedFetch(input, init)),\n getCacheStatusHeader(\"fwd=bypass\"),\n cacheOptions,\n );\n }\n\n throw error;\n }\n\n return annotateResponse(\n fromSerializableResponse(result.data),\n result.cacheStatus === \"hit\"\n ? getCacheStatusHeader(\"hit\")\n : getNonHitCacheStatusHeader(result.data.cacheable, result.cacheStatus),\n cacheOptions,\n );\n };\n}\n\nfunction shouldCacheResponse(\n response: Response,\n bodyReader: BodyReader,\n options: FetchCacheOptions,\n): MaybePromise<boolean> {\n const context: FetchCacheResponseContext = {\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n headers: new Headers(response.headers),\n url: response.url,\n text: bodyReader.text,\n };\n\n if (isJsonResponse(response)) {\n context.json = bodyReader.json;\n }\n\n return options.shouldCacheResponse?.(context) ?? true;\n}\n\ntype BodyReader = {\n text(): Promise<string>;\n json(): Promise<unknown>;\n};\n\ntype SerializeResponseOptions = {\n bodyReader?: BodyReader;\n cacheable: boolean;\n fallbackOnError?: boolean;\n};\n\nfunction createBodyReader(response: Response): BodyReader {\n let bodyText: Promise<string> | undefined;\n let bodyJson: Promise<unknown> | undefined;\n\n const text = () => {\n bodyText ??= response.text();\n return bodyText;\n };\n\n return {\n text,\n json() {\n bodyJson ??= text().then((value) => JSON.parse(value));\n return bodyJson;\n },\n };\n}\n\nasync function serializeResponse(\n response: Response,\n { bodyReader, cacheable, fallbackOnError = false }: SerializeResponseOptions,\n): Promise<SerializableResponse> {\n if (!canSerializeBodyAsText(response)) return emptySerializableResponse(response);\n\n try {\n return {\n body: await (bodyReader ?? createBodyReader(response)).text(),\n cacheable,\n headers: getSerializableHeaders(response.headers, cacheable),\n status: response.status,\n statusText: response.statusText,\n };\n } catch (error) {\n if (!fallbackOnError) throw error;\n return emptySerializableResponse(response);\n }\n}\n\nfunction fromSerializableResponse(response: SerializableResponse): Response {\n return new Response(response.body, {\n headers: response.headers,\n status: response.status,\n statusText: response.statusText,\n });\n}\n\nfunction emptySerializableResponse(response: Response): SerializableResponse {\n return {\n body: \"\",\n cacheable: false,\n headers: [],\n status: response.status,\n statusText: response.statusText,\n };\n}\n\nfunction getSerializableHeaders(headers: Headers, cacheable: boolean): [string, string][] {\n if (!cacheable) return [...headers];\n\n // Cacheable serialized responses can be returned to future requests, so\n // per-request headers must not be copied.\n return [...headers].filter(([key]) => !excludedCachedResponseHeaders.has(key.toLowerCase()));\n}\n\nfunction annotateResponse(\n response: Response,\n cacheStatus: string,\n options: FetchCacheOptions,\n): Response {\n // An opaque response has status 0, which `new Response()` rejects.\n if (options.annotateCacheStatus === false || isOpaqueResponse(response)) return response;\n\n const headers = new Headers(response.headers);\n headers.append(\"Cache-Status\", cacheStatus);\n\n return new Response(response.body, {\n headers,\n status: response.status,\n statusText: response.statusText,\n });\n}\n\nfunction getNonHitCacheStatusHeader(shouldCache: boolean, cacheStatus: \"miss\" | \"bypass\"): string {\n if (cacheStatus === \"bypass\") return getCacheStatusHeader(\"fwd=bypass\");\n return shouldCache\n ? getCacheStatusHeader(\"fwd=uri-miss; stored\")\n : getCacheStatusHeader(\"fwd=bypass\");\n}\n\nfunction getCacheStatusHeader(value: string): string {\n return `${HYDROGEN_CACHE_STATUS_PRODUCT}; ${value}`;\n}\n\nfunction isJsonResponse(response: Response): boolean {\n return response.headers.get(\"content-type\")?.toLowerCase().includes(\"json\") ?? false;\n}\n\nfunction isOpaqueResponse(response: Response): boolean {\n return response.type === \"opaque\" || response.type === \"opaqueredirect\";\n}\n\nfunction isStaleIfErrorStatus(status: number): boolean {\n return staleIfErrorStatuses.has(status);\n}\n\nfunction canSerializeBodyAsText(response: Response): boolean {\n if (response.body == null) return true;\n\n const contentType = response.headers.get(\"content-type\");\n return contentType != null && /\\b(json|text|xml|html|graphql|javascript)\\b/i.test(contentType);\n}\n"],"mappings":";;;;;AAuEA,MAAM,gCAAgC,IAAI,IAAI,CAAC,cAAc,gBAAgB,CAAC;AAC9E,MAAM,uBAAuB,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAI,CAAC;AAE1D,IAAM,8BAAN,cAA0C,2BAA2B;CACnE,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B,aAAa;AACvE,QAAO,cACH,qBAAqB,uBAAuB,GAC5C,qBAAqB,aAAa;;AAGxC,SAAS,qBAAqB,OAAuB;AACnD,QAAO,GAAG,8BAA8B,IAAI;;AAG9C,SAAS,eAAe,UAA6B;AACnD,QAAO,SAAS,QAAQ,IAAI,eAAe,EAAE,aAAa,CAAC,SAAS,OAAO,IAAI;;AAGjF,SAAS,iBAAiB,UAA6B;AACrD,QAAO,SAAS,SAAS,YAAY,SAAS,SAAS;;AAGzD,SAAS,qBAAqB,QAAyB;AACrD,QAAO,qBAAqB,IAAI,OAAO;;AAGzC,SAAS,uBAAuB,UAA6B;AAC3D,KAAI,SAAS,QAAQ,KAAM,QAAO;CAElC,MAAM,cAAc,SAAS,QAAQ,IAAI,eAAe;AACxD,QAAO,eAAe,QAAQ,+CAA+C,KAAK,YAAY"}
|
package/dist/core/cart/cart.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { getLogger } from "../logging/logging.mjs";
|
|
2
|
-
import { createObservable } from "../observable.mjs";
|
|
3
2
|
import { CONSENT_TRACKING_API_LOADED_EVENT, SHOPIFY_STOREFRONT_STANDARD_ACTIONS_SCRIPT, VISITOR_CONSENT_COLLECTED_EVENT } from "../shopify-scripts/constants.mjs";
|
|
3
|
+
import { createObservable } from "../observable.mjs";
|
|
4
4
|
import { getCartAttributeFormEntries } from "./form.mjs";
|
|
5
5
|
import { DEFAULT_MINIMUM_QUANTITY, sanitizeQuantity } from "./quantity.mjs";
|
|
6
6
|
import { createCartState, createEmptyCartState, createEmptyErrorGroup } from "./state.mjs";
|
|
@@ -11,7 +11,12 @@ function getCartIdFromCookie(input) {
|
|
|
11
11
|
if (!header) return null;
|
|
12
12
|
const match = header.match(new RegExp(`(?:^|;\\s*)${COOKIE_NAME}=([^;]*)`));
|
|
13
13
|
if (!match || !match[1]) return null;
|
|
14
|
-
|
|
14
|
+
let token;
|
|
15
|
+
try {
|
|
16
|
+
token = decodeURIComponent(match[1]);
|
|
17
|
+
} catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
15
20
|
if (!token) return null;
|
|
16
21
|
return normalizeCartId(token);
|
|
17
22
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cookie.mjs","names":[],"sources":["../../../src/core/cart/cookie.ts"],"sourcesContent":["const COOKIE_NAME = \"cart\";\nconst MAX_AGE_IN_SECONDS = 1209600; // 14 days\nconst CART_GID_PREFIX = \"gid://shopify/Cart/\";\n\ntype CartCookieSource = Request | { cookie?: string };\n\nexport function normalizeCartId(cartId: string | null | undefined): string | null {\n if (!cartId) return null;\n return cartId.startsWith(CART_GID_PREFIX) ? cartId : CART_GID_PREFIX + cartId;\n}\n\nexport function getCartIdFromCookie(input: CartCookieSource): string | null {\n const header = input instanceof Request ? input.headers.get(\"cookie\") : input.cookie;\n if (!header) return null;\n\n const match = header.match(new RegExp(`(?:^|;\\\\s*)${COOKIE_NAME}=([^;]*)`));\n if (!match || !match[1]) return null;\n\n
|
|
1
|
+
{"version":3,"file":"cookie.mjs","names":[],"sources":["../../../src/core/cart/cookie.ts"],"sourcesContent":["const COOKIE_NAME = \"cart\";\nconst MAX_AGE_IN_SECONDS = 1209600; // 14 days\nconst CART_GID_PREFIX = \"gid://shopify/Cart/\";\n\ntype CartCookieSource = Request | { cookie?: string };\n\nexport function normalizeCartId(cartId: string | null | undefined): string | null {\n if (!cartId) return null;\n return cartId.startsWith(CART_GID_PREFIX) ? cartId : CART_GID_PREFIX + cartId;\n}\n\nexport function getCartIdFromCookie(input: CartCookieSource): string | null {\n const header = input instanceof Request ? input.headers.get(\"cookie\") : input.cookie;\n if (!header) return null;\n\n const match = header.match(new RegExp(`(?:^|;\\\\s*)${COOKIE_NAME}=([^;]*)`));\n if (!match || !match[1]) return null;\n\n let token: string;\n try {\n token = decodeURIComponent(match[1]);\n } catch {\n // Treat a malformed cookie value as a missing cart instead of failing the request.\n return null;\n }\n if (!token) return null;\n\n return normalizeCartId(token);\n}\n\n/**\n * Creates the `Set-Cookie` header value that stores the cart ID in the `cart` cookie.\n *\n * The cookie holds the cart token without the `gid://shopify/Cart/` prefix and expires\n * after 14 days. The cookie sets `Path=/` and `SameSite=Lax`, and leaves out `HttpOnly`\n * and `Secure`. Append the value to the response headers to keep the response's\n * other cookies.\n *\n * @param cartId The cart GID or cart token to store.\n * @returns The header value that sets the `cart` cookie.\n * @example\n * ```ts\n * const cookie = createCartCookie(\"gid://shopify/Cart/abc123\");\n * // \"cart=abc123; Path=/; SameSite=Lax; Max-Age=1209600\"\n *\n * headers.append(\"Set-Cookie\", cookie);\n * ```\n * @publicDocs\n */\nexport function createCartCookie(cartId: string): string {\n const token = cartId.startsWith(CART_GID_PREFIX) ? cartId.slice(CART_GID_PREFIX.length) : cartId;\n const encoded = encodeURIComponent(token);\n return `${COOKIE_NAME}=${encoded}; Path=/; SameSite=Lax; Max-Age=${MAX_AGE_IN_SECONDS}`;\n}\n\nexport function createExpiredCartCookie(): string {\n return `${COOKIE_NAME}=; Path=/; SameSite=Lax; Max-Age=0`;\n}\n"],"mappings":";AAAA,MAAM,cAAc;AACpB,MAAM,qBAAqB;AAC3B,MAAM,kBAAkB;AAIxB,SAAgB,gBAAgB,QAAkD;AAChF,KAAI,CAAC,OAAQ,QAAO;AACpB,QAAO,OAAO,WAAW,gBAAgB,GAAG,SAAS,kBAAkB;;AAGzE,SAAgB,oBAAoB,OAAwC;CAC1E,MAAM,SAAS,iBAAiB,UAAU,MAAM,QAAQ,IAAI,SAAS,GAAG,MAAM;AAC9E,KAAI,CAAC,OAAQ,QAAO;CAEpB,MAAM,QAAQ,OAAO,MAAM,IAAI,OAAO,cAAc,YAAY,UAAU,CAAC;AAC3E,KAAI,CAAC,SAAS,CAAC,MAAM,GAAI,QAAO;CAEhC,IAAI;AACJ,KAAI;AACF,UAAQ,mBAAmB,MAAM,GAAG;SAC9B;AAEN,SAAO;;AAET,KAAI,CAAC,MAAO,QAAO;AAEnB,QAAO,gBAAgB,MAAM;;;;;;;;;;;;;;;;;;;;;AAsB/B,SAAgB,iBAAiB,QAAwB;CACvD,MAAM,QAAQ,OAAO,WAAW,gBAAgB,GAAG,OAAO,MAAM,GAAuB,GAAG;AAE1F,QAAO,GAAG,YAAY,GADN,mBAAmB,MACH,CAAC,kCAAkC;;AAGrE,SAAgB,0BAAkC;AAChD,QAAO,GAAG,YAAY"}
|
|
@@ -16,6 +16,21 @@ interface SetButtonAttributes {
|
|
|
16
16
|
/** Hides the button from view. */
|
|
17
17
|
hidden: true;
|
|
18
18
|
}
|
|
19
|
+
/**
|
|
20
|
+
* HTML attributes for the submit button that removes a line from the cart.
|
|
21
|
+
*
|
|
22
|
+
* `register("remove")` returns the attributes. Removing a line reads only the line ID, so the button skips form validation. Invalid text in the line's quantity input doesn't block the removal.
|
|
23
|
+
*
|
|
24
|
+
* @publicDocs
|
|
25
|
+
*/
|
|
26
|
+
interface RemoveButtonAttributes {
|
|
27
|
+
/** The form field that names the cart change. */
|
|
28
|
+
name: "intent";
|
|
29
|
+
/** Removes the line. */
|
|
30
|
+
value: "remove";
|
|
31
|
+
/** Submits the form without checking its fields, such as the quantity input's digits-only pattern. */
|
|
32
|
+
formNoValidate: true;
|
|
33
|
+
}
|
|
19
34
|
/**
|
|
20
35
|
* HTML attributes for a quantity input that submits the form when the customer changes the quantity.
|
|
21
36
|
*
|
|
@@ -157,10 +172,7 @@ type CartFormRegister = {
|
|
|
157
172
|
name: "intent";
|
|
158
173
|
value: "decrease";
|
|
159
174
|
};
|
|
160
|
-
(action: "remove"):
|
|
161
|
-
name: "intent";
|
|
162
|
-
value: "remove";
|
|
163
|
-
};
|
|
175
|
+
(action: "remove"): RemoveButtonAttributes;
|
|
164
176
|
(action: "set"): SetButtonAttributes;
|
|
165
177
|
(action: "discount-apply"): {
|
|
166
178
|
name: "intent";
|
|
@@ -201,5 +213,5 @@ type CartFormRegister = {
|
|
|
201
213
|
*/
|
|
202
214
|
declare function createCartFormRegister(): CartFormRegister;
|
|
203
215
|
//#endregion
|
|
204
|
-
export { CartFormRegister, QuantityInputAttributes, SetButtonAttributes, createCartFormRegister };
|
|
216
|
+
export { CartFormRegister, QuantityInputAttributes, RemoveButtonAttributes, SetButtonAttributes, createCartFormRegister };
|
|
205
217
|
//# sourceMappingURL=form.d.mts.map
|
package/dist/core/cart/form.mjs
CHANGED