@shopify/hydrogen 2026.10.1 → 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 +8 -5
- package/dist/client/client.mjs +45 -12
- package/dist/client/client.mjs.map +1 -1
- package/dist/client/i18n-variables.d.mts +13 -0
- package/dist/client/i18n-variables.mjs +92 -0
- package/dist/client/i18n-variables.mjs.map +1 -0
- package/dist/client/types.d.mts +21 -8
- 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 +111 -24
- package/dist/core/cart/cart.mjs.map +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/cart/queries.d.mts +57 -57
- 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/queries.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/proxy.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 +13 -2
- package/dist/core/request-routing/registered-routes.mjs +33 -9
- package/dist/core/request-routing/registered-routes.mjs.map +1 -1
- package/dist/core/request-routing/route-types.d.mts +18 -8
- 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/perfkit.mjs +8 -2
- package/dist/core/shopify-scripts/perfkit.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/core/utils/load-script.mjs +6 -6
- package/dist/core/utils/load-script.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 +45 -12
- package/dist/development/client/client.mjs.map +1 -1
- package/dist/development/client/i18n-variables.d.mts +13 -0
- package/dist/development/client/i18n-variables.mjs +92 -0
- package/dist/development/client/i18n-variables.mjs.map +1 -0
- package/dist/development/client/types.d.mts +21 -8
- 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 +111 -24
- package/dist/development/core/cart/cart.mjs.map +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/proxy.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 +13 -2
- package/dist/development/core/request-routing/registered-routes.mjs +33 -9
- package/dist/development/core/request-routing/registered-routes.mjs.map +1 -1
- package/dist/development/core/request-routing/route-types.d.mts +18 -8
- 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/perfkit.mjs +8 -2
- package/dist/development/core/shopify-scripts/perfkit.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/core/utils/load-script.mjs +6 -6
- package/dist/development/core/utils/load-script.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 +39 -1
- package/dist/development/react/cart.mjs +79 -25
- package/dist/development/react/cart.mjs.map +1 -1
- package/dist/development/react/index.d.mts +2 -2
- package/dist/globals.d.mts +8 -4
- package/dist/graphql/type-resolver.d.mts +39 -1
- package/dist/react/cart.mjs +79 -25
- package/dist/react/cart.mjs.map +1 -1
- package/dist/react/index.d.mts +2 -2
- package/dist/vite/index.d.mts +11 -1
- package/dist/vite/index.mjs +21 -1
- package/dist/vite/index.mjs.map +1 -0
- 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-cart-ui/SKILL.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 +24 -6
- package/skills/hydrogen-request-handlers/references/content-security-policy.md +103 -0
- package/skills/hydrogen-request-handlers/references/frameworks.md +9 -12
- package/skills/hydrogen-request-handlers/references/nextjs.md +7 -3
- package/skills/hydrogen-request-handlers/references/nuxt.md +7 -7
- 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 +29 -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
|
@@ -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 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 COUNTRY_VAR_RE = /\\$country\\s*:/;\nconst LANGUAGE_VAR_RE = /\\$language\\s*:/;\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 if (COUNTRY_VAR_RE.test(queryText)) {\n variables.country = resolvedI18n.country;\n }\n if (LANGUAGE_VAR_RE.test(queryText)) {\n variables.language = resolvedI18n.language;\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":";;;;;;;;AA4CA,MAAM,iBAAiB;AACvB,MAAM,kBAAkB;AACxB,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;AACF,MAAM,gDAAgC,IAAI,SAAsC;AAChF,MAAM,sBAAsB,QAAQ;AAIpC,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,OAAO,gBAAgB,WACzB,OAAM,IAAI,MACR,sFACD;CAEH,MAAM,gBAAgB,OAAO,QACzB,qBAAqB;EACnB,OAAO,OAAO;EACd,WAAW,OAAO;EAClB,OAAO;EACR,CAAC,GACF;CAEJ,MAAM,cAAc,OAAO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AAQ,QAAQ,MAAM,QAAQ,KAAK,IAAI,YAAY,KACjF,QAAO;AAGT,UAAO,oBAAoB,KAAK,IAAI;;EAKtC,wBAAwB,YAAY,QAAQ,sBAAsB;EACnE;;AAGH,SAAS,yBAAyB,QAAgB,MAAwB;AACxE,QAAO;EACL;EACA;EACA,KAAK;EACL,KAAK;EACL,CAAC,GAAG,KAAK,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,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AU,MAAM,IAAI,CAAC,IAAI,MAAM,CAAC,aAAa,IAAI,GAAG,CACrF,IAAI;;AAIX,SAAS,yBAAyB,QAAgB,MAAwB;AACxE,QAAO;EACL;EACA;EACA,KAAK;EACL,KAAK;EACL,CAAC,GAAG,KAAK,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"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
//#region src/client/i18n-variables.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Variables the client fills from `requestContext.locale`, with the named type
|
|
4
|
+
* each must be declared as. Same-named variables of any other type belong to
|
|
5
|
+
* the caller.
|
|
6
|
+
*/
|
|
7
|
+
declare const I18N_VARIABLE_TYPES: {
|
|
8
|
+
readonly country: "CountryCode";
|
|
9
|
+
readonly language: "LanguageCode";
|
|
10
|
+
};
|
|
11
|
+
//#endregion
|
|
12
|
+
export { I18N_VARIABLE_TYPES };
|
|
13
|
+
//# sourceMappingURL=i18n-variables.d.mts.map
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
//#region src/client/i18n-variables.ts
|
|
2
|
+
/**
|
|
3
|
+
* Variables the client fills from `requestContext.locale`, with the named type
|
|
4
|
+
* each must be declared as. Same-named variables of any other type belong to
|
|
5
|
+
* the caller.
|
|
6
|
+
*/
|
|
7
|
+
const I18N_VARIABLE_TYPES = {
|
|
8
|
+
country: "CountryCode",
|
|
9
|
+
language: "LanguageCode"
|
|
10
|
+
};
|
|
11
|
+
const TOKEN_RE = /"""(?:\\"""|[^])*?"""|"(?:\\.|[^"\\\n\r])*"|#[^\n\r]*|[_A-Za-z][_0-9A-Za-z]*|[^\s,]/g;
|
|
12
|
+
const NAME_RE = /^[_A-Za-z]/;
|
|
13
|
+
const OPERATION_TYPES = new Set([
|
|
14
|
+
"query",
|
|
15
|
+
"mutation",
|
|
16
|
+
"subscription"
|
|
17
|
+
]);
|
|
18
|
+
const OPENING = new Set([
|
|
19
|
+
"(",
|
|
20
|
+
"[",
|
|
21
|
+
"{"
|
|
22
|
+
]);
|
|
23
|
+
const CLOSING = new Set([
|
|
24
|
+
")",
|
|
25
|
+
"]",
|
|
26
|
+
"}"
|
|
27
|
+
]);
|
|
28
|
+
/**
|
|
29
|
+
* Returns the i18n variables that the document's first operation declares as
|
|
30
|
+
* `$country: CountryCode` or `$language: LanguageCode`, nullable or non-null.
|
|
31
|
+
* This is the same rule the `graphql()` variables type applies.
|
|
32
|
+
*/
|
|
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) {
|
|
42
|
+
const names = [];
|
|
43
|
+
for (const [name, colon, ...rest] of readFirstOperationVariables(tokenize(source))) {
|
|
44
|
+
if (colon !== ":" || !isKeyOf(types, name)) continue;
|
|
45
|
+
const typeEnd = rest.findIndex((token) => token === "=" || token === "@");
|
|
46
|
+
const type = rest.slice(0, typeEnd === -1 ? void 0 : typeEnd).join("");
|
|
47
|
+
const expected = types[name];
|
|
48
|
+
if (type === expected || type === `${expected}!`) names.push(name);
|
|
49
|
+
}
|
|
50
|
+
return names;
|
|
51
|
+
}
|
|
52
|
+
function isKeyOf(types, name) {
|
|
53
|
+
return name !== void 0 && Object.hasOwn(types, name);
|
|
54
|
+
}
|
|
55
|
+
function* tokenize(source) {
|
|
56
|
+
for (const [token] of source.matchAll(TOKEN_RE)) if (token[0] !== "#") yield token;
|
|
57
|
+
}
|
|
58
|
+
function readFirstOperationVariables(tokens) {
|
|
59
|
+
let depth = 0;
|
|
60
|
+
let inFragment = false;
|
|
61
|
+
for (const token of tokens) {
|
|
62
|
+
if (depth === 0 && !inFragment) {
|
|
63
|
+
if (OPERATION_TYPES.has(token)) return readOperationVariables(tokens);
|
|
64
|
+
if (token === "{") return [];
|
|
65
|
+
inFragment = token === "fragment";
|
|
66
|
+
}
|
|
67
|
+
if (OPENING.has(token)) depth++;
|
|
68
|
+
else if (CLOSING.has(token) && --depth === 0 && token === "}") inFragment = false;
|
|
69
|
+
}
|
|
70
|
+
return [];
|
|
71
|
+
}
|
|
72
|
+
function readOperationVariables(tokens) {
|
|
73
|
+
let next = tokens.next().value;
|
|
74
|
+
if (next && NAME_RE.test(next)) next = tokens.next().value;
|
|
75
|
+
return next === "(" ? readVariableDefinitions(tokens) : [];
|
|
76
|
+
}
|
|
77
|
+
function readVariableDefinitions(tokens) {
|
|
78
|
+
const definitions = [];
|
|
79
|
+
let depth = 0;
|
|
80
|
+
for (const token of tokens) {
|
|
81
|
+
if (depth === 0 && token === ")") break;
|
|
82
|
+
if (depth === 0 && token === "$") definitions.push([]);
|
|
83
|
+
else definitions.at(-1)?.push(token);
|
|
84
|
+
if (OPENING.has(token)) depth++;
|
|
85
|
+
else if (CLOSING.has(token)) depth--;
|
|
86
|
+
}
|
|
87
|
+
return definitions;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
//#endregion
|
|
91
|
+
export { getI18nVariableNames };
|
|
92
|
+
//# sourceMappingURL=i18n-variables.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
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;E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E,KAAK,MAAM;AACpC,MAAI,QAAQ,IAAI,MAAM,CAAE;WACf,QAAQ,IAAI,MAAM,CAAE;;AAE/B,QAAO"}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { CacheInstance, WaitUntil } from "../core/cache/run-with-cache.mjs";
|
|
2
2
|
import { I18nConfig, ShopifyRequestContext, ShopifyRequestContextWithBuyerIp } from "../core/request-context.mjs";
|
|
3
|
-
import {
|
|
3
|
+
import { introspection } from "../graphql/generated/graphql-env.mjs";
|
|
4
|
+
import { InferOperationKind, InferResult, InferVariableNamesByEnumValue, InferVariableNamesDeclaredAs, InferVariables } from "../graphql/type-resolver.mjs";
|
|
4
5
|
import { AnyStorefrontQueryString, SourceOf, StorefrontQueryString } from "../graphql/graphql.mjs";
|
|
6
|
+
import { I18N_VARIABLE_TYPES } from "./i18n-variables.mjs";
|
|
5
7
|
import { ResultOf, TadaDocumentNode, VariablesOf } from "gql.tada";
|
|
6
8
|
|
|
7
9
|
//#region src/client/types.d.ts
|
|
@@ -67,7 +69,10 @@ type CommonOptions = {
|
|
|
67
69
|
defaultTimeoutInMs?: number;
|
|
68
70
|
/**
|
|
69
71
|
* The cache that stores query results. The client caches only queries that pass a `cache`
|
|
70
|
-
* 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.
|
|
71
76
|
*/
|
|
72
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. */
|
|
73
78
|
waitUntil?: WaitUntil;
|
|
@@ -140,9 +145,11 @@ type CreateStorefrontClientArgs<RequestContext extends ShopifyRequestContext = S
|
|
|
140
145
|
cache?: CacheConfig;
|
|
141
146
|
};
|
|
142
147
|
};
|
|
143
|
-
type
|
|
144
|
-
|
|
145
|
-
type
|
|
148
|
+
type I18nVariableTypes = typeof I18N_VARIABLE_TYPES;
|
|
149
|
+
type I18nVariableNamesByValue<Variables> = InferVariableNamesByEnumValue<Variables, I18nVariableTypes, introspection>;
|
|
150
|
+
type I18nVariableNamesOfDoc<Doc> = [SourceText<Doc>] extends [never] ? I18nVariableNamesByValue<VariablesOfDoc<Doc>> : string extends SourceText<Doc> ? I18nVariableNamesByValue<VariablesOfDoc<Doc>> : InferVariableNamesDeclaredAs<SourceText<Doc>, I18nVariableTypes>;
|
|
151
|
+
/** Variables the caller passes: everything except the i18n variables the client injects. */
|
|
152
|
+
type UserVariables<Doc> = Omit<VariablesOfDoc<Doc>, I18nVariableNamesOfDoc<Doc>>;
|
|
146
153
|
/** Resolves to `true` when an object type has no required keys. */
|
|
147
154
|
type HasNoRequiredKeys<T> = Record<string, never> extends T ? true : false;
|
|
148
155
|
/**
|
|
@@ -209,12 +216,18 @@ type ClientType = /** Runs in the browser with a public access token or none. */
|
|
|
209
216
|
* typed result.
|
|
210
217
|
*/
|
|
211
218
|
type StorefrontClient<Extra extends Record<string, unknown> = {}, Type extends ClientType = ClientType, RequestContext extends ShopifyRequestContext = ShopifyRequestContext> = {
|
|
212
|
-
/** 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
|
+
*/
|
|
213
225
|
i18n: RequestContext["i18n"];
|
|
214
226
|
/**
|
|
215
227
|
* Runs a Storefront API query or mutation and returns a typed result. Pass a `gql` document or a
|
|
216
|
-
* plain query string. When the operation declares `$country` or
|
|
217
|
-
* variable from the request context and overrides
|
|
228
|
+
* plain query string. When the operation declares `$country: CountryCode` or
|
|
229
|
+
* `$language: LanguageCode`, the client sets the variable from the request context and overrides
|
|
230
|
+
* any value you pass. Variables with other types stay caller-owned.
|
|
218
231
|
*
|
|
219
232
|
* The method throws an error when a query passes a `cache` strategy and the client has no cache,
|
|
220
233
|
* or when the strategy uses `private` mode. A catch block for `StorefrontApiError` doesn't catch
|
|
@@ -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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AI;;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,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,IAAI;AAEJ,MAAI;AACF,YAAS,MAAM,aACb;IACE,KAAK,aAAa;IAClB,UAAU,aAAa;IACxB,EACD,OAAO,YAAY;IACjB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