hydrogen-sanity 4.2.1 → 4.3.1

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 CHANGED
@@ -204,7 +204,12 @@ const page = await context.sanity.loadQuery<HomePage>(query, params, {
204
204
  // display in the subrequest profiler, you can pass that here:
205
205
  // debug: {
206
206
  // displayName: 'query Homepage'
207
- // }
207
+ // },
208
+
209
+ // You can also pass a function do determine whether or not to cache the response
210
+ // shouldCacheResult(value){
211
+ // return true
212
+ // },
208
213
  },
209
214
 
210
215
  // ...as well as other request options
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@sanity/client"),t=require("@sanity/react-loader"),n=require("@shopify/hydrogen"),i=require("./_chunks-cjs/utils.cjs");const r=n.CacheLong();const a=n.CacheLong();Object.defineProperty(exports,"SanityClient",{enumerable:!0,get:function(){return e.SanityClient}}),Object.defineProperty(exports,"createClient",{enumerable:!0,get:function(){return e.createClient}}),exports.createSanityContext=function(a){const{cache:o,waitUntil:s=()=>Promise.resolve(),request:c,preview:l,defaultStrategy:u}=a,d=o?n.createWithCache({cache:o,waitUntil:s,request:c}):null;let p=a.client instanceof e.SanityClient?a.client:e.createClient(a.client);if("1"===p.config().apiVersion&&(console.warn("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"),p=p.withConfig({apiVersion:"v2022-03-07"})),l&&l.enabled){if(!l.token)throw new Error("Enabling preview mode requires a token.");const e=p.withConfig({useCdn:!1,token:l.token,perspective:"previewDrafts",stega:{...p.config().stega,enabled:!0,studioUrl:l.studioUrl}});t.setServerClient(e)}else t.setServerClient(p);return{async loadQuery(e,a,o){const s=l&&l.enabled?n.CacheNone():o?.hydrogen?.cache||u||r,c=await i.h(e,a);return await(d?d(c,s,(async({addDebugData:n})=>{if("development"===process.env.NODE_ENV){n({displayName:o?.hydrogen?.debug?.displayName||"query Sanity"})}return await t.loadQuery(e,a,o)})):t.loadQuery(e,a,o))},client:p,preview:l}},exports.createSanityLoader=function(r){const{withCache:o,preview:s,strategy:c}=r;let l=r.client instanceof e.SanityClient?r.client:e.createClient(r.client);if("1"===l.config().apiVersion&&(console.warn("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"),l=l.withConfig({apiVersion:"v2022-03-07"})),s&&s.enabled){if(!s.token)throw new Error("Enabling preview mode requires a token.");const e=l.withConfig({useCdn:!1,token:s.token,perspective:"previewDrafts",stega:{...l.config().stega,enabled:!0,studioUrl:s.studioUrl}});t.setServerClient(e)}else t.setServerClient(l);return{async loadQuery(e,r,l){const u=s&&s.enabled?n.CacheNone():l?.hydrogen?.cache||c||a,d=await i.h(e,r);return await o(d,u,(async({addDebugData:n})=>{if("development"===process.env.NODE_ENV){n({displayName:l?.hydrogen?.debug?.displayName||"query Sanity"})}return await t.loadQuery(e,r,l)}))},client:l,preview:s}};//# sourceMappingURL=index.cjs.map
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@sanity/client"),t=require("@sanity/react-loader"),n=require("@shopify/hydrogen"),i=require("./_chunks-cjs/utils.cjs");const r=n.CacheLong();const a=n.CacheLong();Object.defineProperty(exports,"SanityClient",{enumerable:!0,get:function(){return e.SanityClient}}),Object.defineProperty(exports,"createClient",{enumerable:!0,get:function(){return e.createClient}}),exports.createSanityContext=function(a){const{cache:o,waitUntil:s=()=>Promise.resolve(),request:c,preview:l,defaultStrategy:u}=a,d=o?n.createWithCache({cache:o,waitUntil:s,request:c}):null;let h=a.client instanceof e.SanityClient?a.client:e.createClient(a.client);if("1"===h.config().apiVersion&&(console.warn("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"),h=h.withConfig({apiVersion:"v2022-03-07"})),l&&l.enabled){if(!l.token)throw new Error("Enabling preview mode requires a token.");const e=h.withConfig({useCdn:!1,token:l.token,perspective:"previewDrafts",stega:{...h.config().stega,enabled:!0,studioUrl:l.studioUrl}});t.setServerClient(e)}else t.setServerClient(h);return{async loadQuery(e,a,o){if(!d)return await t.loadQuery(e,a,o);const s=l&&l.enabled?n.CacheNone():o?.hydrogen?.cache||u||r,c=await i.h(e,a),h=o?.hydrogen?.shouldCacheResult??(()=>!0),y=async function({addDebugData:n}){if("development"===process.env.NODE_ENV){n({displayName:o?.hydrogen?.debug?.displayName||"query Sanity"})}return await t.loadQuery(e,a,o)};return await("run"in d?d.run({cacheKey:c,cacheStrategy:s,shouldCacheResult:h},y):d(c,s,y))},client:h,preview:l}},exports.createSanityLoader=function(r){const{withCache:o,preview:s,strategy:c}=r;let l=r.client instanceof e.SanityClient?r.client:e.createClient(r.client);if("1"===l.config().apiVersion&&(console.warn("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"),l=l.withConfig({apiVersion:"v2022-03-07"})),s&&s.enabled){if(!s.token)throw new Error("Enabling preview mode requires a token.");const e=l.withConfig({useCdn:!1,token:s.token,perspective:"previewDrafts",stega:{...l.config().stega,enabled:!0,studioUrl:s.studioUrl}});t.setServerClient(e)}else t.setServerClient(l);return{async loadQuery(e,r,l){const u=s&&s.enabled?n.CacheNone():l?.hydrogen?.cache||c||a,d=await i.h(e,r),h=l?.hydrogen?.shouldCacheResult??(()=>!0),y=async function({addDebugData:n}){if("development"===process.env.NODE_ENV){n({displayName:l?.hydrogen?.debug?.displayName||"query Sanity"})}return await t.loadQuery(e,r,l)};return await("run"in o?o.run({cacheKey:d,cacheStrategy:u,shouldCacheResult:h},y):o(d,u,y))},client:l,preview:s}};//# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/context.ts","../src/loader.ts"],"sourcesContent":["import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {CacheLong, CacheNone, type CachingStrategy, createWithCache} 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 = Pick<\n HydrogenResponseQueryOptions,\n 'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'\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,\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,\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 || defaultStrategy || DEFAULT_CACHE_STRATEGY\n\n const queryHash = await hashQuery(query, params)\n\n return await (withCache\n ? withCache(queryHash, cacheStrategy, async ({addDebugData}) => {\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 : loadQuery<T>(query, params, loaderOptions))\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 = Pick<\n HydrogenResponseQueryOptions,\n 'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'\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,\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,\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 return await withCache(queryHash, cacheStrategy, async ({addDebugData}) => {\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 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","h","async","addDebugData","process","env","NODE_ENV","displayName","debug","createSanityLoader","strategy"],"mappings":"0MAaA,MAAMA,EAAyBC,EAAAA,YCA/B,MAAMD,EAAyBC,EAAAA,YA6I/BC,OAAAC,eAAAC,QAAA,eAAA,CAAAC,YAAA,EAAAC,IAAA,WAAA,OAAAC,EAAAC,YAAA,IAAAN,OAAAC,eAAAC,QAAA,eAAA,CAAAC,YAAA,EAAAC,IAAA,WAAA,OAAAC,EAAAE,YAAA,IAAAL,QAAAM,oBDjEO,SAA6BC,GAC5B,MAAAC,MAACA,YAAOC,EAAY,IAAMC,QAAQC,kBAAWC,UAASC,EAASC,gBAAAA,GAAmBP,EAClFQ,EAAYP,EAAQQ,kBAAgB,CAACR,QAAOC,YAAWG,YAAY,KACrET,IAAAA,EACFI,EAAQJ,kBAAkBC,EAAAA,aAAeG,EAAQJ,OAASE,EAAAA,aAAaE,EAAQJ,QASjF,GAPmC,MAA/BA,EAAOc,SAASC,aAClBC,QAAQC,KACN,gLAEFjB,EAASA,EAAOkB,WAAW,CAACH,WAAY,iBAGtCL,GAAWA,EAAQS,QAAS,CAC9B,IAAKT,EAAQU,MACL,MAAA,IAAIC,MAAM,2CAGZ,MAAAC,EAAgBtB,EAAOkB,WAAW,CACtCK,QAAQ,EACRH,MAAOV,EAAQU,MACfI,YAAa,gBACbC,MAAO,IACFzB,EAAOc,SAASW,MACnBN,SAAS,EACTO,UAAWhB,EAAQgB,aAIvBC,EAAAA,gBAAgBL,EAClB,MACEK,EAAAA,gBAAgB3B,GAGH,MAAA,CACb,eAAM4B,CACJC,EACAC,EACAC,GAGA,MAAMC,EACJtB,GAAWA,EAAQS,QACfc,EAAAA,YACAF,GAAeG,UAAU7B,OAASM,GAAmBlB,EAErD0C,QAAkBC,EAAAC,EAAUR,EAAOC,GAElC,aAAOlB,EACVA,EAAUuB,EAAWH,GAAeM,OAAQC,mBACtC,GAAyB,gBAAzBC,QAAQC,IAAIC,SAA4B,CAI7BH,EAAA,CACXI,YAHkBZ,GAAeG,UAAUU,OAAOD,aAAe,gBAIlE,CAGH,aAAaf,EAAAA,UAAaC,EAAOC,EAAQC,EAAa,IAExDH,EAAAA,UAAaC,EAAOC,EAAQC,GAClC,EAAA/B,OACAA,EACAU,UAIJ,ECHAb,QAAAgD,mBAlEO,SAA4BzC,GACjC,MAAMQ,UAACA,EAAAF,QAAWA,EAASoC,SAAAA,GAAY1C,EACnCJ,IAAAA,EACFI,EAAQJ,kBAAkBC,EAAAA,aAAeG,EAAQJ,OAASE,EAAAA,aAAaE,EAAQJ,QASjF,GAPmC,MAA/BA,EAAOc,SAASC,aAClBC,QAAQC,KACN,gLAEFjB,EAASA,EAAOkB,WAAW,CAACH,WAAY,iBAGtCL,GAAWA,EAAQS,QAAS,CAC9B,IAAKT,EAAQU,MACL,MAAA,IAAIC,MAAM,2CAGZ,MAAAC,EAAgBtB,EAAOkB,WAAW,CACtCK,QAAQ,EACRH,MAAOV,EAAQU,MACfI,YAAa,gBACbC,MAAO,IACFzB,EAAOc,SAASW,MACnBN,SAAS,EACTO,UAAWhB,EAAQgB,aAIvBC,EAAAA,gBAAgBL,EAClB,MACEK,EAAAA,gBAAgB3B,GAGH,MAAA,CACb,eAAM4B,CACJC,EACAC,EACAC,GAGA,MAAMC,EACJtB,GAAWA,EAAQS,QACfc,EAAAA,YACAF,GAAeG,UAAU7B,OAASyC,GAAYrD,EAE9C0C,QAAkBC,EAAAC,EAAUR,EAAOC,GAEzC,aAAalB,EAAUuB,EAAWH,GAAeM,OAAQC,mBAEnD,GAAyB,gBAAzBC,QAAQC,IAAIC,SAA4B,CAI7BH,EAAA,CACXI,YAHkBZ,GAAeG,UAAUU,OAAOD,aAAe,gBAIlE,CAGH,aAAaf,EAAAA,UAAaC,EAAOC,EAAQC,EAAa,GAE1D,EAAA/B,OACAA,EACAU,UAIJ"}
1
+ {"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,MAAMA,EAAyBC,EAAAA,YCN/B,MAAMD,EAAyBC,EAAAA,YA8J/BC,OAAAC,eAAAC,QAAA,eAAA,CAAAC,YAAA,EAAAC,IAAA,WAAA,OAAAC,EAAAC,YAAA,IAAAN,OAAAC,eAAAC,QAAA,eAAA,CAAAC,YAAA,EAAAC,IAAA,WAAA,OAAAC,EAAAE,YAAA,IAAAL,QAAAM,oBDpEO,SAA6BC,GAC5B,MAAAC,MAACA,YAAOC,EAAY,IAAMC,QAAQC,kBAAWC,UAASC,EAASC,gBAAAA,GAAmBP,EAClFQ,EAAYP,EAAQQ,kBAAgB,CAACR,QAAOC,YAAWG,YAAY,KACrET,IAAAA,EACFI,EAAQJ,kBAAkBC,EAAAA,aAAeG,EAAQJ,OAASE,EAAAA,aAAaE,EAAQJ,QASjF,GAPmC,MAA/BA,EAAOc,SAASC,aAClBC,QAAQC,KACN,gLAEFjB,EAASA,EAAOkB,WAAW,CAACH,WAAY,iBAGtCL,GAAWA,EAAQS,QAAS,CAC9B,IAAKT,EAAQU,MACL,MAAA,IAAIC,MAAM,2CAGZ,MAAAC,EAAgBtB,EAAOkB,WAAW,CACtCK,QAAQ,EACRH,MAAOV,EAAQU,MACfI,YAAa,gBACbC,MAAO,IACFzB,EAAOc,SAASW,MACnBN,SAAS,EACTO,UAAWhB,EAAQgB,aAIvBC,EAAAA,gBAAgBL,EAClB,MACEK,EAAAA,gBAAgB3B,GAGH,MAAA,CACb,eAAM4B,CACJC,EACAC,EACAC,GAEA,IAAKnB,EACH,aAAagB,EAAAA,UAAaC,EAAOC,EAAQC,GAIrC,MAAAC,EACJtB,GAAWA,EAAQS,QACfc,EAAAA,YACAF,GAAeG,UAAU7B,OAASM,GAAmBlB,EAErD0C,QAAkBC,EAAAA,EAAUP,EAAOC,GACnCO,EAAoBN,GAAeG,UAAUG,mBAAsB,MAAM,GAEzEC,EAAeC,gBAA4BC,aAC/CA,IAGI,GAAyB,gBAAzBC,QAAQC,IAAIC,SAA4B,CAI7BH,EAAA,CACXI,YAHkBb,GAAeG,UAAUW,OAAOD,aAAe,gBAIlE,CAGH,aAAahB,EAAAA,UAAaC,EAAOC,EAAQC,EAC3C,EAEO,aAAO,QAASnB,EACnBA,EAAUkC,IAAI,CAACC,SAAUZ,EAAWH,gBAAeK,qBAAoBC,GAEvE1B,EAAUuB,EAAWH,EAAeM,GAC1C,EAAAtC,OACAA,EACAU,UAIJ,ECXAb,QAAAmD,mBA3EO,SAA4B5C,GACjC,MAAMQ,UAACA,EAAAF,QAAWA,EAASuC,SAAAA,GAAY7C,EACnCJ,IAAAA,EACFI,EAAQJ,kBAAkBC,EAAAA,aAAeG,EAAQJ,OAASE,EAAAA,aAAaE,EAAQJ,QASjF,GAPmC,MAA/BA,EAAOc,SAASC,aAClBC,QAAQC,KACN,gLAEFjB,EAASA,EAAOkB,WAAW,CAACH,WAAY,iBAGtCL,GAAWA,EAAQS,QAAS,CAC9B,IAAKT,EAAQU,MACL,MAAA,IAAIC,MAAM,2CAGZ,MAAAC,EAAgBtB,EAAOkB,WAAW,CACtCK,QAAQ,EACRH,MAAOV,EAAQU,MACfI,YAAa,gBACbC,MAAO,IACFzB,EAAOc,SAASW,MACnBN,SAAS,EACTO,UAAWhB,EAAQgB,aAIvBC,EAAAA,gBAAgBL,EAClB,MACEK,EAAAA,gBAAgB3B,GAGH,MAAA,CACb,eAAM4B,CACJC,EACAC,EACAC,GAGM,MAAAC,EACJtB,GAAWA,EAAQS,QACfc,EAAAA,YACAF,GAAeG,UAAU7B,OAAS4C,GAAYxD,EAE9C0C,QAAkBC,EAAAA,EAAUP,EAAOC,GAEnCO,EAAoBN,GAAeG,UAAUG,mBAAsB,MAAM,GAEzEC,EAAeC,gBAA4BC,aAC/CA,IAGI,GAAyB,gBAAzBC,QAAQC,IAAIC,SAA4B,CAI7BH,EAAA,CACXI,YAHkBb,GAAeG,UAAUW,OAAOD,aAAe,gBAIlE,CAGH,aAAahB,EAAAA,UAAaC,EAAOC,EAAQC,EAC3C,EAEO,aAAO,QAASnB,EACnBA,EAAUkC,IAAI,CAACC,SAAUZ,EAAWH,gBAAeK,qBAAoBC,GAEvE1B,EAAUuB,EAAWH,EAAeM,GAC1C,EAAAtC,OACAA,EACAU,UAIJ"}
package/dist/index.d.cts CHANGED
@@ -79,15 +79,31 @@ declare type HydrogenResponseQueryOptions_2 = Omit<ResponseQueryOptions, 'next'
79
79
  hydrogen?: 'hydrogen' extends keyof RequestInit_3 ? RequestInit_3['hydrogen'] : never
80
80
  }
81
81
 
82
- declare type LoadQueryOptions = Pick<
82
+ declare type LoadQueryOptions<T> = Pick<
83
83
  HydrogenResponseQueryOptions,
84
84
  'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'
85
- >
85
+ > & {
86
+ hydrogen?: {
87
+ /**
88
+ * Whether to cache the result of the query or not.
89
+ * @defaultValue () => true
90
+ */
91
+ shouldCacheResult?: (value: QueryResponseInitial<T>) => boolean
92
+ }
93
+ }
86
94
 
87
- declare type LoadQueryOptions_2 = Pick<
95
+ declare type LoadQueryOptions_2<T> = Pick<
88
96
  HydrogenResponseQueryOptions_2,
89
97
  'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'
90
- >
98
+ > & {
99
+ hydrogen?: {
100
+ /**
101
+ * Whether to cache the result of the query or not.
102
+ * @defaultValue () => true
103
+ */
104
+ shouldCacheResult?: (value: QueryResponseInitial<T>) => boolean
105
+ }
106
+ }
91
107
 
92
108
  declare interface RequestInit_2 {
93
109
  hydrogen?: {
@@ -133,7 +149,7 @@ export declare type SanityContext = {
133
149
  loadQuery<T = any>(
134
150
  query: string,
135
151
  params?: QueryParams,
136
- options?: LoadQueryOptions,
152
+ options?: LoadQueryOptions<T>,
137
153
  ): Promise<QueryResponseInitial<T>>
138
154
  client: SanityClient
139
155
  preview?: CreateSanityContextOptions['preview']
@@ -147,7 +163,7 @@ export declare type SanityLoader = {
147
163
  loadQuery<T = any>(
148
164
  query: string,
149
165
  params?: QueryParams,
150
- options?: LoadQueryOptions_2,
166
+ options?: LoadQueryOptions_2<T>,
151
167
  ): Promise<QueryResponseInitial<T>>
152
168
  client: SanityClient
153
169
  preview?: CreateSanityLoaderOptions['preview']
package/dist/index.d.ts CHANGED
@@ -79,15 +79,31 @@ declare type HydrogenResponseQueryOptions_2 = Omit<ResponseQueryOptions, 'next'
79
79
  hydrogen?: 'hydrogen' extends keyof RequestInit_3 ? RequestInit_3['hydrogen'] : never
80
80
  }
81
81
 
82
- declare type LoadQueryOptions = Pick<
82
+ declare type LoadQueryOptions<T> = Pick<
83
83
  HydrogenResponseQueryOptions,
84
84
  'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'
85
- >
85
+ > & {
86
+ hydrogen?: {
87
+ /**
88
+ * Whether to cache the result of the query or not.
89
+ * @defaultValue () => true
90
+ */
91
+ shouldCacheResult?: (value: QueryResponseInitial<T>) => boolean
92
+ }
93
+ }
86
94
 
87
- declare type LoadQueryOptions_2 = Pick<
95
+ declare type LoadQueryOptions_2<T> = Pick<
88
96
  HydrogenResponseQueryOptions_2,
89
97
  'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'
90
- >
98
+ > & {
99
+ hydrogen?: {
100
+ /**
101
+ * Whether to cache the result of the query or not.
102
+ * @defaultValue () => true
103
+ */
104
+ shouldCacheResult?: (value: QueryResponseInitial<T>) => boolean
105
+ }
106
+ }
91
107
 
92
108
  declare interface RequestInit_2 {
93
109
  hydrogen?: {
@@ -133,7 +149,7 @@ export declare type SanityContext = {
133
149
  loadQuery<T = any>(
134
150
  query: string,
135
151
  params?: QueryParams,
136
- options?: LoadQueryOptions,
152
+ options?: LoadQueryOptions<T>,
137
153
  ): Promise<QueryResponseInitial<T>>
138
154
  client: SanityClient
139
155
  preview?: CreateSanityContextOptions['preview']
@@ -147,7 +163,7 @@ export declare type SanityLoader = {
147
163
  loadQuery<T = any>(
148
164
  query: string,
149
165
  params?: QueryParams,
150
- options?: LoadQueryOptions_2,
166
+ options?: LoadQueryOptions_2<T>,
151
167
  ): Promise<QueryResponseInitial<T>>
152
168
  client: SanityClient
153
169
  preview?: CreateSanityLoaderOptions['preview']
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{SanityClient as e,createClient as t}from"@sanity/client";import{SanityClient as n,createClient as i}from"@sanity/client";import{setServerClient as a,loadQuery as o}from"@sanity/react-loader";import{CacheLong as r,createWithCache as s,CacheNone as c}from"@shopify/hydrogen";import{h as l}from"./_chunks-es/utils.js";const p=r();function d(n){const{cache:i,waitUntil:r=()=>Promise.resolve(),request:d,preview:u,defaultStrategy:g}=n,w=i?s({cache:i,waitUntil:r,request:d}):null;let h=n.client instanceof e?n.client:t(n.client);if("1"===h.config().apiVersion&&(console.warn("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"),h=h.withConfig({apiVersion:"v2022-03-07"})),u&&u.enabled){if(!u.token)throw new Error("Enabling preview mode requires a token.");const e=h.withConfig({useCdn:!1,token:u.token,perspective:"previewDrafts",stega:{...h.config().stega,enabled:!0,studioUrl:u.studioUrl}});a(e)}else a(h);return{async loadQuery(e,t,n){const i=u&&u.enabled?c():n?.hydrogen?.cache||g||p,a=await l(e,t);return await(w?w(a,i,(async({addDebugData:i})=>{if("development"===process.env.NODE_ENV){i({displayName:n?.hydrogen?.debug?.displayName||"query Sanity"})}return await o(e,t,n)})):o(e,t,n))},client:h,preview:u}}const u=r();function g(n){const{withCache:i,preview:r,strategy:s}=n;let p=n.client instanceof e?n.client:t(n.client);if("1"===p.config().apiVersion&&(console.warn("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"),p=p.withConfig({apiVersion:"v2022-03-07"})),r&&r.enabled){if(!r.token)throw new Error("Enabling preview mode requires a token.");const e=p.withConfig({useCdn:!1,token:r.token,perspective:"previewDrafts",stega:{...p.config().stega,enabled:!0,studioUrl:r.studioUrl}});a(e)}else a(p);return{async loadQuery(e,t,n){const a=r&&r.enabled?c():n?.hydrogen?.cache||s||u,p=await l(e,t);return await i(p,a,(async({addDebugData:i})=>{if("development"===process.env.NODE_ENV){i({displayName:n?.hydrogen?.debug?.displayName||"query Sanity"})}return await o(e,t,n)}))},client:p,preview:r}}export{n as SanityClient,i as createClient,d as createSanityContext,g as createSanityLoader};//# sourceMappingURL=index.js.map
1
+ import{SanityClient as e,createClient as t}from"@sanity/client";import{SanityClient as n,createClient as i}from"@sanity/client";import{setServerClient as a,loadQuery as o}from"@sanity/react-loader";import{CacheLong as r,createWithCache as s,CacheNone as c}from"@shopify/hydrogen";import{h as l}from"./_chunks-es/utils.js";const u=r();function h(n){const{cache:i,waitUntil:r=()=>Promise.resolve(),request:h,preview:d,defaultStrategy:p}=n,g=i?s({cache:i,waitUntil:r,request:h}):null;let y=n.client instanceof e?n.client:t(n.client);if("1"===y.config().apiVersion&&(console.warn("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"),y=y.withConfig({apiVersion:"v2022-03-07"})),d&&d.enabled){if(!d.token)throw new Error("Enabling preview mode requires a token.");const e=y.withConfig({useCdn:!1,token:d.token,perspective:"previewDrafts",stega:{...y.config().stega,enabled:!0,studioUrl:d.studioUrl}});a(e)}else a(y);return{async loadQuery(e,t,n){if(!g)return await o(e,t,n);const i=d&&d.enabled?c():n?.hydrogen?.cache||p||u,a=await l(e,t),r=n?.hydrogen?.shouldCacheResult??(()=>!0),s=async function({addDebugData:i}){if("development"===process.env.NODE_ENV){i({displayName:n?.hydrogen?.debug?.displayName||"query Sanity"})}return await o(e,t,n)};return await("run"in g?g.run({cacheKey:a,cacheStrategy:i,shouldCacheResult:r},s):g(a,i,s))},client:y,preview:d}}const d=r();function p(n){const{withCache:i,preview:r,strategy:s}=n;let u=n.client instanceof e?n.client:t(n.client);if("1"===u.config().apiVersion&&(console.warn("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"),u=u.withConfig({apiVersion:"v2022-03-07"})),r&&r.enabled){if(!r.token)throw new Error("Enabling preview mode requires a token.");const e=u.withConfig({useCdn:!1,token:r.token,perspective:"previewDrafts",stega:{...u.config().stega,enabled:!0,studioUrl:r.studioUrl}});a(e)}else a(u);return{async loadQuery(e,t,n){const a=r&&r.enabled?c():n?.hydrogen?.cache||s||d,u=await l(e,t),h=n?.hydrogen?.shouldCacheResult??(()=>!0),p=async function({addDebugData:i}){if("development"===process.env.NODE_ENV){i({displayName:n?.hydrogen?.debug?.displayName||"query Sanity"})}return await o(e,t,n)};return await("run"in i?i.run({cacheKey:u,cacheStrategy:a,shouldCacheResult:h},p):i(u,a,p))},client:u,preview:r}}export{n as SanityClient,i as createClient,h as createSanityContext,p as createSanityLoader};//# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/context.ts","../src/loader.ts"],"sourcesContent":["import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {CacheLong, CacheNone, type CachingStrategy, createWithCache} 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 = Pick<\n HydrogenResponseQueryOptions,\n 'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'\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,\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,\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 || defaultStrategy || DEFAULT_CACHE_STRATEGY\n\n const queryHash = await hashQuery(query, params)\n\n return await (withCache\n ? withCache(queryHash, cacheStrategy, async ({addDebugData}) => {\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 : loadQuery<T>(query, params, loaderOptions))\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 = Pick<\n HydrogenResponseQueryOptions,\n 'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'\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,\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,\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 return await withCache(queryHash, cacheStrategy, async ({addDebugData}) => {\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 client,\n preview,\n }\n\n return sanity\n}\n"],"names":["DEFAULT_CACHE_STRATEGY","CacheLong","createSanityContext","options","cache","waitUntil","Promise","resolve","request","preview","defaultStrategy","withCache","createWithCache","client","SanityClient","createClient","config","apiVersion","console","warn","withConfig","enabled","token","Error","previewClient","useCdn","perspective","stega","studioUrl","setServerClient","loadQuery","query","params","loaderOptions","cacheStrategy","CacheNone","hydrogen","queryHash","hashQuery","async","addDebugData","process","env","NODE_ENV","displayName","debug","createSanityLoader","strategy"],"mappings":"kUAaA,MAAMA,EAAyBC,IA4ExB,SAASC,EAAoBC,GAC5B,MAAAC,MAACA,YAAOC,EAAY,IAAMC,QAAQC,kBAAWC,UAASC,EAASC,gBAAAA,GAAmBP,EAClFQ,EAAYP,EAAQQ,EAAgB,CAACR,QAAOC,YAAWG,YAAY,KACrE,IAAAK,EACFV,EAAQU,kBAAkBC,EAAeX,EAAQU,OAASE,EAAaZ,EAAQU,QASjF,GAPmC,MAA/BA,EAAOG,SAASC,aAClBC,QAAQC,KACN,gLAEFN,EAASA,EAAOO,WAAW,CAACH,WAAY,iBAGtCR,GAAWA,EAAQY,QAAS,CAC9B,IAAKZ,EAAQa,MACL,MAAA,IAAIC,MAAM,2CAGZ,MAAAC,EAAgBX,EAAOO,WAAW,CACtCK,QAAQ,EACRH,MAAOb,EAAQa,MACfI,YAAa,gBACbC,MAAO,IACFd,EAAOG,SAASW,MACnBN,SAAS,EACTO,UAAWnB,EAAQmB,aAIvBC,EAAgBL,EAClB,MACEK,EAAgBhB,GAGH,MAAA,CACb,eAAMiB,CACJC,EACAC,EACAC,GAGA,MAAMC,EACJzB,GAAWA,EAAQY,QACfc,IACAF,GAAeG,UAAUhC,OAASM,GAAmBV,EAErDqC,QAAkBC,EAAUP,EAAOC,GAElC,aAAOrB,EACVA,EAAU0B,EAAWH,GAAeK,OAAQC,mBACtC,GAAyB,gBAAzBC,QAAQC,IAAIC,SAA4B,CAI7BH,EAAA,CACXI,YAHkBX,GAAeG,UAAUS,OAAOD,aAAe,gBAIlE,CAGH,aAAad,EAAaC,EAAOC,EAAQC,EAAa,IAExDH,EAAaC,EAAOC,EAAQC,GAClC,EACApB,SACAJ,UAIJ,CChJA,MAAMT,EAAyBC,IA2ExB,SAAS6C,EAAmB3C,GACjC,MAAMQ,UAACA,EAAAF,QAAWA,EAASsC,SAAAA,GAAY5C,EACnC,IAAAU,EACFV,EAAQU,kBAAkBC,EAAeX,EAAQU,OAASE,EAAaZ,EAAQU,QASjF,GAPmC,MAA/BA,EAAOG,SAASC,aAClBC,QAAQC,KACN,gLAEFN,EAASA,EAAOO,WAAW,CAACH,WAAY,iBAGtCR,GAAWA,EAAQY,QAAS,CAC9B,IAAKZ,EAAQa,MACL,MAAA,IAAIC,MAAM,2CAGZ,MAAAC,EAAgBX,EAAOO,WAAW,CACtCK,QAAQ,EACRH,MAAOb,EAAQa,MACfI,YAAa,gBACbC,MAAO,IACFd,EAAOG,SAASW,MACnBN,SAAS,EACTO,UAAWnB,EAAQmB,aAIvBC,EAAgBL,EAClB,MACEK,EAAgBhB,GAGH,MAAA,CACb,eAAMiB,CACJC,EACAC,EACAC,GAGA,MAAMC,EACJzB,GAAWA,EAAQY,QACfc,IACAF,GAAeG,UAAUhC,OAAS2C,GAAY/C,EAE9CqC,QAAkBC,EAAUP,EAAOC,GAEzC,aAAarB,EAAU0B,EAAWH,GAAeK,OAAQC,mBAEnD,GAAyB,gBAAzBC,QAAQC,IAAIC,SAA4B,CAI7BH,EAAA,CACXI,YAHkBX,GAAeG,UAAUS,OAAOD,aAAe,gBAIlE,CAGH,aAAad,EAAaC,EAAOC,EAAQC,EAAa,GAE1D,EACApB,SACAJ,UAIJ"}
1
+ {"version":3,"file":"index.js","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","createSanityContext","options","cache","waitUntil","Promise","resolve","request","preview","defaultStrategy","withCache","createWithCache","client","SanityClient","createClient","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":"kUAmBA,MAAMA,EAAyBC,IAoFxB,SAASC,EAAoBC,GAC5B,MAAAC,MAACA,YAAOC,EAAY,IAAMC,QAAQC,kBAAWC,UAASC,EAASC,gBAAAA,GAAmBP,EAClFQ,EAAYP,EAAQQ,EAAgB,CAACR,QAAOC,YAAWG,YAAY,KACrE,IAAAK,EACFV,EAAQU,kBAAkBC,EAAeX,EAAQU,OAASE,EAAaZ,EAAQU,QASjF,GAPmC,MAA/BA,EAAOG,SAASC,aAClBC,QAAQC,KACN,gLAEFN,EAASA,EAAOO,WAAW,CAACH,WAAY,iBAGtCR,GAAWA,EAAQY,QAAS,CAC9B,IAAKZ,EAAQa,MACL,MAAA,IAAIC,MAAM,2CAGZ,MAAAC,EAAgBX,EAAOO,WAAW,CACtCK,QAAQ,EACRH,MAAOb,EAAQa,MACfI,YAAa,gBACbC,MAAO,IACFd,EAAOG,SAASW,MACnBN,SAAS,EACTO,UAAWnB,EAAQmB,aAIvBC,EAAgBL,EAClB,MACEK,EAAgBhB,GAGH,MAAA,CACb,eAAMiB,CACJC,EACAC,EACAC,GAEA,IAAKtB,EACH,aAAamB,EAAaC,EAAOC,EAAQC,GAIrC,MAAAC,EACJzB,GAAWA,EAAQY,QACfc,IACAF,GAAeG,UAAUhC,OAASM,GAAmBV,EAErDqC,QAAkBC,EAAUP,EAAOC,GACnCO,EAAoBN,GAAeG,UAAUG,mBAAsB,MAAM,GAEzEC,EAAeC,gBAA4BC,aAC/CA,IAGI,GAAyB,gBAAzBC,QAAQC,IAAIC,SAA4B,CAI7BH,EAAA,CACXI,YAHkBb,GAAeG,UAAUW,OAAOD,aAAe,gBAIlE,CAGH,aAAahB,EAAaC,EAAOC,EAAQC,EAC3C,EAEO,aAAO,QAAStB,EACnBA,EAAUqC,IAAI,CAACC,SAAUZ,EAAWH,gBAAeK,qBAAoBC,GAEvE7B,EAAU0B,EAAWH,EAAeM,GAC1C,EACA3B,SACAJ,UAIJ,CCzKA,MAAMT,EAAyBC,IAmFxB,SAASiD,EAAmB/C,GACjC,MAAMQ,UAACA,EAAAF,QAAWA,EAAS0C,SAAAA,GAAYhD,EACnC,IAAAU,EACFV,EAAQU,kBAAkBC,EAAeX,EAAQU,OAASE,EAAaZ,EAAQU,QASjF,GAPmC,MAA/BA,EAAOG,SAASC,aAClBC,QAAQC,KACN,gLAEFN,EAASA,EAAOO,WAAW,CAACH,WAAY,iBAGtCR,GAAWA,EAAQY,QAAS,CAC9B,IAAKZ,EAAQa,MACL,MAAA,IAAIC,MAAM,2CAGZ,MAAAC,EAAgBX,EAAOO,WAAW,CACtCK,QAAQ,EACRH,MAAOb,EAAQa,MACfI,YAAa,gBACbC,MAAO,IACFd,EAAOG,SAASW,MACnBN,SAAS,EACTO,UAAWnB,EAAQmB,aAIvBC,EAAgBL,EAClB,MACEK,EAAgBhB,GAGH,MAAA,CACb,eAAMiB,CACJC,EACAC,EACAC,GAGM,MAAAC,EACJzB,GAAWA,EAAQY,QACfc,IACAF,GAAeG,UAAUhC,OAAS+C,GAAYnD,EAE9CqC,QAAkBC,EAAUP,EAAOC,GAEnCO,EAAoBN,GAAeG,UAAUG,mBAAsB,MAAM,GAEzEC,EAAeC,gBAA4BC,aAC/CA,IAGI,GAAyB,gBAAzBC,QAAQC,IAAIC,SAA4B,CAI7BH,EAAA,CACXI,YAHkBb,GAAeG,UAAUW,OAAOD,aAAe,gBAIlE,CAGH,aAAahB,EAAaC,EAAOC,EAAQC,EAC3C,EAEO,aAAO,QAAStB,EACnBA,EAAUqC,IAAI,CAACC,SAAUZ,EAAWH,gBAAeK,qBAAoBC,GAEvE7B,EAAU0B,EAAWH,EAAeM,GAC1C,EACA3B,SACAJ,UAIJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hydrogen-sanity",
3
- "version": "4.2.1",
3
+ "version": "4.3.1",
4
4
  "description": "Sanity.io toolkit for Hydrogen",
5
5
  "keywords": [
6
6
  "sanity",
@@ -89,10 +89,10 @@
89
89
  "groq": "^3.62.3"
90
90
  },
91
91
  "devDependencies": {
92
- "@sanity/pkg-utils": "^6.11.7",
92
+ "@sanity/pkg-utils": "^6.11.8",
93
93
  "@sanity/plugin-kit": "^4.0.18",
94
94
  "@sanity/semantic-release-preset": "^4.1.8",
95
- "@shopify/hydrogen": "~2024.7.9",
95
+ "@shopify/hydrogen": "~2024.10.0",
96
96
  "@shopify/remix-oxygen": "^2.0.9",
97
97
  "@types/react": "^18.3.12",
98
98
  "@typescript-eslint/eslint-plugin": "^7.18.0",
@@ -113,7 +113,7 @@
113
113
  },
114
114
  "peerDependencies": {
115
115
  "@sanity/client": "^6.18.0",
116
- "@shopify/hydrogen": "^2023.7.0 || ~2024.1.0 || ~2024.4.0 || ~2024.7.0",
116
+ "@shopify/hydrogen": "^2023.7.0 || ~2024.1.0 || ~2024.4.0 || ~2024.7.0 || ~2024.10.0",
117
117
  "@shopify/remix-oxygen": "^1.0.0 || ^2.0.0",
118
118
  "groq": "^3.41.0",
119
119
  "react": "^18.0.0",
@@ -1,5 +1,5 @@
1
1
  import type {QueryStore} from '@sanity/react-loader'
2
- import {CacheShort, WithCache} from '@shopify/hydrogen'
2
+ import {CacheShort, type WithCache} from '@shopify/hydrogen'
3
3
  import groq from 'groq'
4
4
  import {beforeEach, describe, expect, it, vi} from 'vitest'
5
5
 
@@ -25,9 +25,11 @@ let withCache = vi.hoisted<WithCache | null>(() => null)
25
25
 
26
26
  vi.mock('@shopify/hydrogen', async (importOriginal) => {
27
27
  const module = await importOriginal<typeof import('@shopify/hydrogen')>()
28
- withCache = vi
29
- .fn()
30
- .mockImplementation(module.createWithCache({cache, waitUntil: () => Promise.resolve()}))
28
+ withCache = module.createWithCache({
29
+ cache,
30
+ waitUntil: () => Promise.resolve(),
31
+ request: new Request('https://example.com'),
32
+ })
31
33
 
32
34
  return {
33
35
  ...module,
@@ -44,6 +46,8 @@ vi.mock('@sanity/react-loader', async (importOriginal) => {
44
46
  }
45
47
  })
46
48
 
49
+ const runWithCache = vi.spyOn(withCache!, 'run')
50
+
47
51
  const client = createClient({projectId: 'my-project-id', dataset: 'my-dataset'})
48
52
 
49
53
  const query = groq`true`
@@ -73,8 +77,12 @@ describe('the Sanity request context', () => {
73
77
  })
74
78
 
75
79
  await contextWithDefaultStrategy.loadQuery<boolean>(query, params)
76
- expect(withCache).toHaveBeenCalledWith(hashedQuery, defaultStrategy, expect.any(Function))
77
- expect(cache.put).toHaveBeenCalled()
80
+ expect(runWithCache).toHaveBeenNthCalledWith(
81
+ 1,
82
+ expect.objectContaining({cacheKey: hashedQuery, cacheStrategy: defaultStrategy}),
83
+ expect.any(Function),
84
+ )
85
+ expect(cache.put).toHaveBeenCalledOnce()
78
86
  })
79
87
 
80
88
  it('queries should use the cache strategy passed in `loadQuery`', async () => {
@@ -82,8 +90,12 @@ describe('the Sanity request context', () => {
82
90
  await sanityContext.loadQuery<boolean>(query, params, {
83
91
  hydrogen: {cache: strategy},
84
92
  })
85
- expect(withCache).toHaveBeenCalledWith(hashedQuery, strategy, expect.any(Function))
86
- expect(cache.put).toHaveBeenCalled()
93
+ expect(runWithCache).toHaveBeenNthCalledWith(
94
+ 1,
95
+ expect.objectContaining({cacheKey: hashedQuery, cacheStrategy: strategy}),
96
+ expect.any(Function),
97
+ )
98
+ expect(cache.put).toHaveBeenCalledOnce()
87
99
  })
88
100
  })
89
101
 
@@ -122,6 +134,6 @@ describe('when configured for preview', () => {
122
134
  it(`shouldn't cache queries`, async () => {
123
135
  await previewContext.loadQuery<boolean>(query)
124
136
  expect(loadQuery).toHaveBeenCalledOnce()
125
- expect(cache.put).not.toHaveBeenCalled()
137
+ expect(cache.put).not.toHaveBeenCalledOnce()
126
138
  })
127
139
  })
package/src/context.ts CHANGED
@@ -1,5 +1,11 @@
1
1
  import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'
2
- import {CacheLong, CacheNone, type CachingStrategy, createWithCache} from '@shopify/hydrogen'
2
+ import {
3
+ CacheLong,
4
+ CacheNone,
5
+ type CachingStrategy,
6
+ createWithCache,
7
+ type WithCache,
8
+ } from '@shopify/hydrogen'
3
9
 
4
10
  import {
5
11
  type ClientConfig,
@@ -62,10 +68,18 @@ type HydrogenResponseQueryOptions = Omit<ResponseQueryOptions, 'next' | 'cache'>
62
68
  hydrogen?: 'hydrogen' extends keyof RequestInit ? RequestInit['hydrogen'] : never
63
69
  }
64
70
 
65
- type LoadQueryOptions = Pick<
71
+ type LoadQueryOptions<T> = Pick<
66
72
  HydrogenResponseQueryOptions,
67
73
  'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'
68
- >
74
+ > & {
75
+ hydrogen?: {
76
+ /**
77
+ * Whether to cache the result of the query or not.
78
+ * @defaultValue () => true
79
+ */
80
+ shouldCacheResult?: (value: QueryResponseInitial<T>) => boolean
81
+ }
82
+ }
69
83
 
70
84
  export type SanityContext = {
71
85
  /**
@@ -76,7 +90,7 @@ export type SanityContext = {
76
90
  loadQuery<T = any>(
77
91
  query: string,
78
92
  params?: QueryParams,
79
- options?: LoadQueryOptions,
93
+ options?: LoadQueryOptions<T>,
80
94
  ): Promise<QueryResponseInitial<T>>
81
95
 
82
96
  client: SanityClient
@@ -125,8 +139,12 @@ export function createSanityContext(options: CreateSanityContextOptions): Sanity
125
139
  async loadQuery<T>(
126
140
  query: string,
127
141
  params: QueryParams | QueryWithoutParams,
128
- loaderOptions?: LoadQueryOptions,
142
+ loaderOptions?: LoadQueryOptions<T>,
129
143
  ): Promise<QueryResponseInitial<T>> {
144
+ if (!withCache) {
145
+ return await loadQuery<T>(query, params, loaderOptions)
146
+ }
147
+
130
148
  // Don't store response if preview is enabled
131
149
  const cacheStrategy =
132
150
  preview && preview.enabled
@@ -134,21 +152,28 @@ export function createSanityContext(options: CreateSanityContextOptions): Sanity
134
152
  : loaderOptions?.hydrogen?.cache || defaultStrategy || DEFAULT_CACHE_STRATEGY
135
153
 
136
154
  const queryHash = await hashQuery(query, params)
155
+ const shouldCacheResult = loaderOptions?.hydrogen?.shouldCacheResult ?? (() => true)
156
+
157
+ const runWithCache = async function runWithCache({
158
+ addDebugData,
159
+ }: Parameters<Parameters<WithCache['run']>[1]>[0]): Promise<QueryResponseInitial<T>> {
160
+ // eslint-disable-next-line no-process-env
161
+ if (process.env.NODE_ENV === 'development') {
162
+ // Name displayed in the subrequest profiler
163
+ const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'
164
+
165
+ addDebugData({
166
+ displayName,
167
+ })
168
+ }
137
169
 
138
- return await (withCache
139
- ? withCache(queryHash, cacheStrategy, async ({addDebugData}) => {
140
- if (process.env.NODE_ENV === 'development') {
141
- // Name displayed in the subrequest profiler
142
- const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'
143
-
144
- addDebugData({
145
- displayName,
146
- })
147
- }
170
+ return await loadQuery<T>(query, params, loaderOptions)
171
+ }
148
172
 
149
- return await loadQuery<T>(query, params, loaderOptions)
150
- })
151
- : loadQuery<T>(query, params, loaderOptions))
173
+ return await ('run' in withCache
174
+ ? withCache.run({cacheKey: queryHash, cacheStrategy, shouldCacheResult}, runWithCache)
175
+ : // @ts-expect-error for compatibility, remove in next major
176
+ withCache(queryHash, cacheStrategy, runWithCache))
152
177
  },
153
178
  client,
154
179
  preview,
@@ -33,8 +33,8 @@ function waitUntil() {
33
33
  return Promise.resolve()
34
34
  }
35
35
 
36
- type WithCache = ReturnType<typeof createWithCache>
37
- const withCache: WithCache = vi.fn().mockImplementation(createWithCache({cache, waitUntil}))
36
+ const withCache = createWithCache({cache, waitUntil, request: new Request('https://example.com')})
37
+ const runWithCache = vi.spyOn(withCache, 'run')
38
38
 
39
39
  const client = createClient({projectId: 'my-project-id', dataset: 'my-dataset'})
40
40
 
@@ -63,15 +63,23 @@ describe('the loader', () => {
63
63
  })
64
64
 
65
65
  await loaderWithDefaultStrategy.loadQuery<boolean>(query, params)
66
- expect(withCache).toHaveBeenCalledWith(hashedQuery, strategy, expect.any(Function))
67
- expect(cache.put).toHaveBeenCalled()
66
+ expect(runWithCache).toHaveBeenNthCalledWith(
67
+ 1,
68
+ expect.objectContaining({cacheKey: hashedQuery, cacheStrategy: strategy}),
69
+ expect.any(Function),
70
+ )
71
+ expect(cache.put).toHaveBeenCalledOnce()
68
72
  })
69
73
 
70
74
  it('queries should use the cache strategy passed in `loadQuery`', async () => {
71
75
  const strategy = CacheShort()
72
76
  await loader.loadQuery<boolean>(query, params, {hydrogen: {cache: strategy}})
73
- expect(withCache).toHaveBeenCalledWith(hashedQuery, strategy, expect.any(Function))
74
- expect(cache.put).toHaveBeenCalled()
77
+ expect(runWithCache).toHaveBeenNthCalledWith(
78
+ 1,
79
+ expect.objectContaining({cacheKey: hashedQuery, cacheStrategy: strategy}),
80
+ expect.any(Function),
81
+ )
82
+ expect(cache.put).toHaveBeenCalledOnce()
75
83
  })
76
84
  })
77
85
 
@@ -108,6 +116,6 @@ describe('when configured for preview', () => {
108
116
  it(`shouldn't cache queries`, async () => {
109
117
  await previewLoader.loadQuery<boolean>(query)
110
118
  expect(loadQuery).toHaveBeenCalledOnce()
111
- expect(cache.put).not.toHaveBeenCalled()
119
+ expect(cache.put).not.toHaveBeenCalledOnce()
112
120
  })
113
121
  })
package/src/loader.ts CHANGED
@@ -61,10 +61,18 @@ type HydrogenResponseQueryOptions = Omit<ResponseQueryOptions, 'next' | 'cache'>
61
61
  hydrogen?: 'hydrogen' extends keyof RequestInit ? RequestInit['hydrogen'] : never
62
62
  }
63
63
 
64
- type LoadQueryOptions = Pick<
64
+ type LoadQueryOptions<T> = Pick<
65
65
  HydrogenResponseQueryOptions,
66
66
  'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'
67
- >
67
+ > & {
68
+ hydrogen?: {
69
+ /**
70
+ * Whether to cache the result of the query or not.
71
+ * @defaultValue () => true
72
+ */
73
+ shouldCacheResult?: (value: QueryResponseInitial<T>) => boolean
74
+ }
75
+ }
68
76
 
69
77
  export type SanityLoader = {
70
78
  /**
@@ -75,7 +83,7 @@ export type SanityLoader = {
75
83
  loadQuery<T = any>(
76
84
  query: string,
77
85
  params?: QueryParams,
78
- options?: LoadQueryOptions,
86
+ options?: LoadQueryOptions<T>,
79
87
  ): Promise<QueryResponseInitial<T>>
80
88
 
81
89
  client: SanityClient
@@ -123,7 +131,7 @@ export function createSanityLoader(options: CreateSanityLoaderOptions): SanityLo
123
131
  async loadQuery<T>(
124
132
  query: string,
125
133
  params: QueryParams | QueryWithoutParams,
126
- loaderOptions?: LoadQueryOptions,
134
+ loaderOptions?: LoadQueryOptions<T>,
127
135
  ): Promise<QueryResponseInitial<T>> {
128
136
  // Don't store response if preview is enabled
129
137
  const cacheStrategy =
@@ -133,7 +141,11 @@ export function createSanityLoader(options: CreateSanityLoaderOptions): SanityLo
133
141
 
134
142
  const queryHash = await hashQuery(query, params)
135
143
 
136
- return await withCache(queryHash, cacheStrategy, async ({addDebugData}) => {
144
+ const shouldCacheResult = loaderOptions?.hydrogen?.shouldCacheResult ?? (() => true)
145
+
146
+ const runWithCache = async function runWithCache({
147
+ addDebugData,
148
+ }: Parameters<Parameters<WithCache['run']>[1]>[0]): Promise<QueryResponseInitial<T>> {
137
149
  // eslint-disable-next-line no-process-env
138
150
  if (process.env.NODE_ENV === 'development') {
139
151
  // Name displayed in the subrequest profiler
@@ -145,7 +157,12 @@ export function createSanityLoader(options: CreateSanityLoaderOptions): SanityLo
145
157
  }
146
158
 
147
159
  return await loadQuery<T>(query, params, loaderOptions)
148
- })
160
+ }
161
+
162
+ return await ('run' in withCache
163
+ ? withCache.run({cacheKey: queryHash, cacheStrategy, shouldCacheResult}, runWithCache)
164
+ : // @ts-expect-error for compatibility, remove in next major
165
+ withCache(queryHash, cacheStrategy, runWithCache))
149
166
  },
150
167
  client,
151
168
  preview,