{"version":3,"file":"index.cjs","sources":["../src/context.ts","../src/loader.ts"],"sourcesContent":["import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {\n  CacheLong,\n  CacheNone,\n  type CachingStrategy,\n  createWithCache,\n  type WithCache,\n} from '@shopify/hydrogen'\n\nimport {\n  type ClientConfig,\n  createClient,\n  type QueryParams,\n  type QueryWithoutParams,\n  type ResponseQueryOptions,\n  SanityClient,\n} from './client'\nimport {hashQuery} from './utils'\n\nconst DEFAULT_CACHE_STRATEGY = CacheLong()\n\ntype WaitUntil = (promise: Promise<unknown>) => void\n\nexport type CreateSanityContextOptions = {\n  request: Request\n\n  cache?: Cache | undefined\n  waitUntil?: WaitUntil | undefined\n\n  /**\n   * Sanity client or configuration to use.\n   */\n  client: SanityClient | ClientConfig\n\n  /**\n   * The default caching strategy to use for `loadQuery` subrequests.\n   * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n   *\n   * Defaults to `CacheLong`\n   */\n  defaultStrategy?: CachingStrategy | null\n\n  /**\n   * Configuration for enabling preview mode.\n   */\n  preview?: {enabled: boolean; token: string; studioUrl: string}\n}\n\ninterface RequestInit {\n  hydrogen?: {\n    /**\n     * The caching strategy to use for the subrequest.\n     * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n     */\n    cache?: CachingStrategy\n\n    /**\n     * Optional debugging information to be displayed in the subrequest profiler.\n     * @see https://shopify.dev/docs/custom-storefronts/hydrogen/debugging/subrequest-profiler#how-to-provide-more-debug-information-for-a-request\n     */\n    debug?: {\n      displayName: string\n    }\n  }\n}\n\ntype HydrogenResponseQueryOptions = Omit<ResponseQueryOptions, 'next' | 'cache'> & {\n  hydrogen?: 'hydrogen' extends keyof RequestInit ? RequestInit['hydrogen'] : never\n}\n\ntype LoadQueryOptions<T> = Pick<\n  HydrogenResponseQueryOptions,\n  'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'\n> & {\n  hydrogen?: {\n    /**\n     * Whether to cache the result of the query or not.\n     * @defaultValue () => true\n     */\n    shouldCacheResult?: (value: QueryResponseInitial<T>) => boolean\n  }\n}\n\nexport type SanityContext = {\n  /**\n   * Query Sanity using the loader.\n   * @see https://www.sanity.io/docs/loaders\n   */\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  loadQuery<T = any>(\n    query: string,\n    params?: QueryParams,\n    options?: LoadQueryOptions<T>,\n  ): Promise<QueryResponseInitial<T>>\n\n  client: SanityClient\n\n  preview?: CreateSanityContextOptions['preview']\n}\n\n/**\n * @public\n */\nexport function createSanityContext(options: CreateSanityContextOptions): SanityContext {\n  const {cache, waitUntil = () => Promise.resolve(), request, preview, defaultStrategy} = options\n  const withCache = cache ? createWithCache({cache, waitUntil, request}) : null\n  let client =\n    options.client instanceof SanityClient ? options.client : createClient(options.client)\n\n  if (client.config().apiVersion === '1') {\n    console.warn(\n      'No API version specified, defaulting to `v2022-03-07` which supports perspectives.\\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog',\n    )\n    client = client.withConfig({apiVersion: 'v2022-03-07'})\n  }\n\n  if (preview && preview.enabled) {\n    if (!preview.token) {\n      throw new Error('Enabling preview mode requires a token.')\n    }\n\n    const previewClient = client.withConfig({\n      useCdn: false,\n      token: preview.token,\n      perspective: 'previewDrafts' as const,\n      stega: {\n        ...client.config().stega,\n        enabled: true,\n        studioUrl: preview.studioUrl,\n      },\n    })\n\n    setServerClient(previewClient)\n  } else {\n    setServerClient(client)\n  }\n\n  const sanity = {\n    async loadQuery<T>(\n      query: string,\n      params: QueryParams | QueryWithoutParams,\n      loaderOptions?: LoadQueryOptions<T>,\n    ): Promise<QueryResponseInitial<T>> {\n      if (!withCache) {\n        return await loadQuery<T>(query, params, loaderOptions)\n      }\n\n      // Don't store response if preview is enabled\n      const cacheStrategy =\n        preview && preview.enabled\n          ? CacheNone()\n          : loaderOptions?.hydrogen?.cache || defaultStrategy || DEFAULT_CACHE_STRATEGY\n\n      const queryHash = await hashQuery(query, params)\n      const shouldCacheResult = loaderOptions?.hydrogen?.shouldCacheResult ?? (() => true)\n\n      const runWithCache = async function runWithCache({\n        addDebugData,\n      }: Parameters<Parameters<WithCache['run']>[1]>[0]): Promise<QueryResponseInitial<T>> {\n        // eslint-disable-next-line no-process-env\n        if (process.env.NODE_ENV === 'development') {\n          // Name displayed in the subrequest profiler\n          const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'\n\n          addDebugData({\n            displayName,\n          })\n        }\n\n        return await loadQuery<T>(query, params, loaderOptions)\n      }\n\n      return await ('run' in withCache\n        ? withCache.run({cacheKey: queryHash, cacheStrategy, shouldCacheResult}, runWithCache)\n        : // @ts-expect-error for compatibility, remove in next major\n          withCache(queryHash, cacheStrategy, runWithCache))\n    },\n    client,\n    preview,\n  }\n\n  return sanity\n}\n","import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {CacheLong, CacheNone, type CachingStrategy, type WithCache} from '@shopify/hydrogen'\n\nimport {\n  type ClientConfig,\n  createClient,\n  type QueryParams,\n  type QueryWithoutParams,\n  type ResponseQueryOptions,\n  SanityClient,\n} from './client'\nimport {hashQuery} from './utils'\n\nconst DEFAULT_CACHE_STRATEGY = CacheLong()\n\nexport type CreateSanityLoaderOptions = {\n  /**\n   * Cache control utility from `@shopify/hydrogen`.\n   * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching/third-party\n   */\n  withCache: WithCache\n\n  /**\n   * Sanity client or configuration to use.\n   */\n  client: SanityClient | ClientConfig\n\n  /**\n   * The default caching strategy to use for `loadQuery` subrequests.\n   * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n   *\n   * Defaults to `CacheLong`\n   */\n  strategy?: CachingStrategy | null\n\n  /**\n   * Configuration for enabling preview mode.\n   */\n  preview?: {enabled: boolean; token: string; studioUrl: string}\n}\n\ninterface RequestInit {\n  hydrogen?: {\n    /**\n     * The caching strategy to use for the subrequest.\n     * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n     */\n    cache?: CachingStrategy\n\n    /**\n     * Optional debugging information to be displayed in the subrequest profiler.\n     * @see https://shopify.dev/docs/custom-storefronts/hydrogen/debugging/subrequest-profiler#how-to-provide-more-debug-information-for-a-request\n     */\n    debug?: {\n      displayName: string\n    }\n  }\n}\n\ntype HydrogenResponseQueryOptions = Omit<ResponseQueryOptions, 'next' | 'cache'> & {\n  hydrogen?: 'hydrogen' extends keyof RequestInit ? RequestInit['hydrogen'] : never\n}\n\ntype LoadQueryOptions<T> = Pick<\n  HydrogenResponseQueryOptions,\n  'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'\n> & {\n  hydrogen?: {\n    /**\n     * Whether to cache the result of the query or not.\n     * @defaultValue () => true\n     */\n    shouldCacheResult?: (value: QueryResponseInitial<T>) => boolean\n  }\n}\n\nexport type SanityLoader = {\n  /**\n   * Query Sanity using the loader.\n   * @see https://www.sanity.io/docs/loaders\n   */\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  loadQuery<T = any>(\n    query: string,\n    params?: QueryParams,\n    options?: LoadQueryOptions<T>,\n  ): Promise<QueryResponseInitial<T>>\n\n  client: SanityClient\n\n  preview?: CreateSanityLoaderOptions['preview']\n}\n\n/**\n * @deprecated Use `createSanityContext` instead\n */\nexport function createSanityLoader(options: CreateSanityLoaderOptions): SanityLoader {\n  const {withCache, preview, strategy} = options\n  let client =\n    options.client instanceof SanityClient ? options.client : createClient(options.client)\n\n  if (client.config().apiVersion === '1') {\n    console.warn(\n      'No API version specified, defaulting to `v2022-03-07` which supports perspectives.\\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog',\n    )\n    client = client.withConfig({apiVersion: 'v2022-03-07'})\n  }\n\n  if (preview && preview.enabled) {\n    if (!preview.token) {\n      throw new Error('Enabling preview mode requires a token.')\n    }\n\n    const previewClient = client.withConfig({\n      useCdn: false,\n      token: preview.token,\n      perspective: 'previewDrafts' as const,\n      stega: {\n        ...client.config().stega,\n        enabled: true,\n        studioUrl: preview.studioUrl,\n      },\n    })\n\n    setServerClient(previewClient)\n  } else {\n    setServerClient(client)\n  }\n\n  const sanity = {\n    async loadQuery<T>(\n      query: string,\n      params: QueryParams | QueryWithoutParams,\n      loaderOptions?: LoadQueryOptions<T>,\n    ): Promise<QueryResponseInitial<T>> {\n      // Don't store response if preview is enabled\n      const cacheStrategy =\n        preview && preview.enabled\n          ? CacheNone()\n          : loaderOptions?.hydrogen?.cache || strategy || DEFAULT_CACHE_STRATEGY\n\n      const queryHash = await hashQuery(query, params)\n\n      const shouldCacheResult = loaderOptions?.hydrogen?.shouldCacheResult ?? (() => true)\n\n      const runWithCache = async function runWithCache({\n        addDebugData,\n      }: Parameters<Parameters<WithCache['run']>[1]>[0]): Promise<QueryResponseInitial<T>> {\n        // eslint-disable-next-line no-process-env\n        if (process.env.NODE_ENV === 'development') {\n          // Name displayed in the subrequest profiler\n          const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'\n\n          addDebugData({\n            displayName,\n          })\n        }\n\n        return await loadQuery<T>(query, params, loaderOptions)\n      }\n\n      return await ('run' in withCache\n        ? withCache.run({cacheKey: queryHash, cacheStrategy, shouldCacheResult}, runWithCache)\n        : // @ts-expect-error for compatibility, remove in next major\n          withCache(queryHash, cacheStrategy, runWithCache))\n    },\n    client,\n    preview,\n  }\n\n  return sanity\n}\n"],"names":["DEFAULT_CACHE_STRATEGY","CacheLong","Object","defineProperty","exports","enumerable","get","client","SanityClient","createClient","createSanityContext","options","cache","waitUntil","Promise","resolve","request","preview","defaultStrategy","withCache","createWithCache","config","apiVersion","console","warn","withConfig","enabled","token","Error","previewClient","useCdn","perspective","stega","studioUrl","setServerClient","loadQuery","query","params","loaderOptions","cacheStrategy","CacheNone","hydrogen","queryHash","hashQuery","shouldCacheResult","runWithCache","async","addDebugData","process","env","NODE_ENV","displayName","debug","run","cacheKey","createSanityLoader","strategy"],"mappings":"0MAmBA,MA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