hydrogen-sanity 4.4.1 → 4.5.0

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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2025 Sanity.io <hello@sanity.io>
3
+ Copyright (c) 2026 Sanity.io <hello@sanity.io>
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -339,6 +339,17 @@ For users to enter preview mode, they will need to visit a route that performs s
339
339
  >
340
340
  > By default, `hydrogen-sanity` will enable stega-encoded Content Source Maps when preview mode is enabled.
341
341
  >
342
+ > If you need preview mode without stega encoding, you can disable it:
343
+ >
344
+ > ```ts
345
+ > preview: {
346
+ > token: env.SANITY_API_TOKEN,
347
+ > studioUrl: 'http://localhost:3333',
348
+ > session: previewSession,
349
+ > stega: false, // Disable stega encoding in preview mode
350
+ > }
351
+ > ```
352
+ >
342
353
  > You can learn more about Content Source Maps and working with stega-encoded strings in [the documentation](https://www.sanity.io/docs/stega).
343
354
 
344
355
  Add this route to your project like below, or view the source to copy and modify it in your project.
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="v2025-02-19",s=n.CacheLong();Object.defineProperty(exports,"SanityClient",{enumerable:!0,get:function(){return e.SanityClient}}),Object.defineProperty(exports,"createClient",{enumerable:!0,get:function(){return e.createClient}}),Object.defineProperty(exports,"validateApiPerspective",{enumerable:!0,get:function(){return e.validateApiPerspective}}),exports.createSanityContext=function(o){const{cache:a,waitUntil:c=()=>Promise.resolve(),request:l,preview:p,defaultStrategy:d}=o,u=a?n.createWithCache({cache:a,waitUntil:c,request:l}):null;let g=o.client instanceof e.SanityClient?o.client:e.createClient(o.client);"1"===g.config().apiVersion&&("development"===process.env.NODE_ENV&&console.warn(`\nNo API version specified, defaulting to \`${r}\` which supports perspectives and Content Releases.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog.\n `.trim()),g=g.withConfig({apiVersion:r}));let v=!1;if(p){if(!p.token)throw new Error("Enabling preview mode requires a token.");if(v="session"in p?p.session.get("projectId")===g.config().projectId:p.enabled,v){const e=g.config().apiVersion;let n;i.b(e)?n="session"in p?i.g(p.session):"drafts":("development"===process.env.NODE_ENV&&console.warn(`API version \`${e}\` does not support perspective stacks. Using \`previewDrafts\` perspective. Consider upgrading to \`v2025-02-19\` or later for full perspective support.`),n="previewDrafts");const r=g.withConfig({useCdn:!1,token:p.token,perspective:n,stega:{...g.config().stega,enabled:!0,studioUrl:p.studioUrl}});t.setServerClient(r)}else t.setServerClient(g)}else t.setServerClient(g);return{async loadQuery(e,r,o){if(!u)return await t.loadQuery(e,r,o);const a=v?n.CacheNone():o?.hydrogen?.cache||d||s,c=await i.h(e,r),l=o?.hydrogen?.shouldCacheResult??(()=>!0),p=async function(n){if("development"===process.env.NODE_ENV&&n?.addDebugData){const e=o?.hydrogen?.debug?.displayName||"query Sanity";n.addDebugData({displayName:e})}return await t.loadQuery(e,r,o)};return await("run"in u?u.run({cacheKey:c,cacheStrategy:a,shouldCacheResult:l},p):u(c,a,p))},client:g,preview:p?{...p,enabled:v}:void 0}},exports.createSanityLoader=function(o){const{withCache:a,preview:c,strategy:l}=o;let p=o.client instanceof e.SanityClient?o.client:e.createClient(o.client);"1"===p.config().apiVersion&&("development"===process.env.NODE_ENV&&console.warn(`\nNo API version specified, defaulting to \`${r}\` which supports perspectives and Content Releases.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog.\n `.trim()),p=p.withConfig({apiVersion:r}));let d=!1;if(c){if(!c.token)throw new Error("Enabling preview mode requires a token.");if(d="session"in c?c.session.get("projectId")===p.config().projectId:c.enabled,d){const e=p.config().apiVersion;let n;i.b(e)?n="session"in c?i.g(c.session):"drafts":("development"===process.env.NODE_ENV&&console.warn(`API version \`${e}\` does not support perspective stacks. Using \`previewDrafts\` perspective. Consider upgrading to \`v2025-02-19\` or later for full perspective support.`),n="previewDrafts");const r=p.withConfig({useCdn:!1,token:c.token,perspective:n,stega:{...p.config().stega,enabled:!0,studioUrl:c.studioUrl}});t.setServerClient(r)}else t.setServerClient(p)}else t.setServerClient(p);return{async loadQuery(e,r,o){const c=d?n.CacheNone():o?.hydrogen?.cache||l||s,p=await i.h(e,r),u=o?.hydrogen?.shouldCacheResult??(()=>!0),g=async function(n){if("development"===process.env.NODE_ENV&&n?.addDebugData){const e=o?.hydrogen?.debug?.displayName||"query Sanity";n.addDebugData({displayName:e})}return await t.loadQuery(e,r,o)};return await("run"in a?a.run({cacheKey:p,cacheStrategy:c,shouldCacheResult:u},g):a(p,c,g))},client:p,preview:c?{...c,enabled:d}:void 0}};//# 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="v2025-02-19",s=n.CacheLong();Object.defineProperty(exports,"SanityClient",{enumerable:!0,get:function(){return e.SanityClient}}),Object.defineProperty(exports,"createClient",{enumerable:!0,get:function(){return e.createClient}}),Object.defineProperty(exports,"validateApiPerspective",{enumerable:!0,get:function(){return e.validateApiPerspective}}),exports.createSanityContext=function(o){const{cache:a,waitUntil:c=()=>Promise.resolve(),request:l,preview:p,defaultStrategy:d}=o,u=a?n.createWithCache({cache:a,waitUntil:c,request:l}):null;let g=o.client instanceof e.SanityClient?o.client:e.createClient(o.client);"1"===g.config().apiVersion&&("development"===process.env.NODE_ENV&&console.warn(`\nNo API version specified, defaulting to \`${r}\` which supports perspectives and Content Releases.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog.\n `.trim()),g=g.withConfig({apiVersion:r}));let v=!1;if(p){if(!p.token)throw new Error("Enabling preview mode requires a token.");if(v="session"in p?p.session.get("projectId")===g.config().projectId:p.enabled,v){const e=g.config().apiVersion;let n;i.b(e)?n="session"in p?i.g(p.session):"drafts":("development"===process.env.NODE_ENV&&console.warn(`API version \`${e}\` does not support perspective stacks. Using \`previewDrafts\` perspective. Consider upgrading to \`v2025-02-19\` or later for full perspective support.`),n="previewDrafts");const r=!1!==p.stega,s=g.withConfig({useCdn:!1,token:p.token,perspective:n,stega:{enabled:r,studioUrl:p.studioUrl}});t.setServerClient(s)}else t.setServerClient(g)}else t.setServerClient(g);return{async loadQuery(e,r,o){if(!u)return await t.loadQuery(e,r,o);const a=v?n.CacheNone():o?.hydrogen?.cache||d||s,c=await i.h(e,r),l=o?.hydrogen?.shouldCacheResult??(()=>!0),p=async function(n){if("development"===process.env.NODE_ENV&&n?.addDebugData){const e=o?.hydrogen?.debug?.displayName||"query Sanity";n.addDebugData({displayName:e})}return await t.loadQuery(e,r,o)};return await("run"in u?u.run({cacheKey:c,cacheStrategy:a,shouldCacheResult:l},p):u(c,a,p))},client:g,preview:p?{...p,enabled:v}:void 0}},exports.createSanityLoader=function(o){const{withCache:a,preview:c,strategy:l}=o;let p=o.client instanceof e.SanityClient?o.client:e.createClient(o.client);"1"===p.config().apiVersion&&("development"===process.env.NODE_ENV&&console.warn(`\nNo API version specified, defaulting to \`${r}\` which supports perspectives and Content Releases.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog.\n `.trim()),p=p.withConfig({apiVersion:r}));let d=!1;if(c){if(!c.token)throw new Error("Enabling preview mode requires a token.");if(d="session"in c?c.session.get("projectId")===p.config().projectId:c.enabled,d){const e=p.config().apiVersion;let n;i.b(e)?n="session"in c?i.g(c.session):"drafts":("development"===process.env.NODE_ENV&&console.warn(`API version \`${e}\` does not support perspective stacks. Using \`previewDrafts\` perspective. Consider upgrading to \`v2025-02-19\` or later for full perspective support.`),n="previewDrafts");const r=!1!==c.stega,s=p.withConfig({useCdn:!1,token:c.token,perspective:n,stega:{enabled:r,studioUrl:c.studioUrl}});t.setServerClient(s)}else t.setServerClient(p)}else t.setServerClient(p);return{async loadQuery(e,r,o){const c=d?n.CacheNone():o?.hydrogen?.cache||l||s,p=await i.h(e,r),u=o?.hydrogen?.shouldCacheResult??(()=>!0),g=async function(n){if("development"===process.env.NODE_ENV&&n?.addDebugData){const e=o?.hydrogen?.debug?.displayName||"query Sanity";n.addDebugData({displayName:e})}return await t.loadQuery(e,r,o)};return await("run"in a?a.run({cacheKey:p,cacheStrategy:c,shouldCacheResult:u},g):a(p,c,g))},client:p,preview:c?{...c,enabled:d}:void 0}};//# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/constants.ts","../src/loader.ts","../src/context.ts"],"sourcesContent":["import {CacheLong, type CachingStrategy} from '@shopify/hydrogen'\n\nexport const DEFAULT_API_VERSION = 'v2025-02-19'\nexport const DEFAULT_CACHE_STRATEGY: CachingStrategy = CacheLong()\n","import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {\n CacheNone,\n type CachingStrategy,\n type HydrogenSession,\n type WithCache,\n} from '@shopify/hydrogen'\n\nimport {\n type ClientConfig,\n type ClientPerspective,\n createClient,\n type QueryParams,\n type QueryWithoutParams,\n type ResponseQueryOptions,\n SanityClient,\n} from './client'\nimport {DEFAULT_API_VERSION, DEFAULT_CACHE_STRATEGY} from './constants'\nimport type {SanityPreviewSession} from './preview/session'\nimport {getPerspective} from './utils'\nimport {hashQuery, supportsPerspectiveStack} from './utils'\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?:\n | {\n /**\n * @deprecated Use session-based preview detection instead.\n */\n enabled: boolean\n token: string\n studioUrl: string\n }\n | {\n token: string\n studioUrl: string\n session: SanityPreviewSession | HydrogenSession\n }\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 * NOTE: Only available in recent version of Hydrogen.\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 * Whether preview mode is currently enabled based on session detection\n */\n enabled: boolean\n }\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 if (process.env.NODE_ENV === 'development') {\n console.warn(\n `\nNo API version specified, defaulting to \\`${DEFAULT_API_VERSION}\\` which supports perspectives and Content Releases.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog.\n `.trim(),\n )\n }\n client = client.withConfig({apiVersion: DEFAULT_API_VERSION})\n }\n\n // Determine if preview is enabled using session-based detection or legacy enabled flag\n let isPreviewEnabled = false\n if (preview) {\n if (!preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n if ('session' in preview) {\n isPreviewEnabled = preview.session.get('projectId') === client.config().projectId\n } else {\n isPreviewEnabled = preview.enabled\n }\n\n if (isPreviewEnabled) {\n const apiVersion = client.config().apiVersion\n let perspective: ClientPerspective\n if (supportsPerspectiveStack(apiVersion)) {\n if ('session' in preview) {\n perspective = getPerspective(preview.session)\n } else {\n perspective = 'drafts'\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `API version \\`${apiVersion}\\` does not support perspective stacks. Using \\`previewDrafts\\` perspective. Consider upgrading to \\`v2025-02-19\\` or later for full perspective support.`,\n )\n }\n perspective = 'previewDrafts'\n }\n\n const previewClient = client.withConfig({\n useCdn: false,\n token: preview.token,\n perspective,\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 } 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 = isPreviewEnabled\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 args: Parameters<Parameters<WithCache['run']>[1]>[0],\n ): Promise<QueryResponseInitial<T>> {\n // eslint-disable-next-line no-process-env\n if (process.env.NODE_ENV === 'development' && args?.addDebugData) {\n // Name displayed in the subrequest profiler\n const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'\n\n args.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: preview ? {...preview, enabled: isPreviewEnabled} : undefined,\n }\n\n return sanity\n}\n","import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {\n CacheNone,\n type CachingStrategy,\n createWithCache,\n type HydrogenSession,\n type WithCache,\n} from '@shopify/hydrogen'\n\nimport {\n type ClientConfig,\n type ClientPerspective,\n createClient,\n type QueryParams,\n type QueryWithoutParams,\n type ResponseQueryOptions,\n SanityClient,\n} from './client'\nimport {DEFAULT_API_VERSION, DEFAULT_CACHE_STRATEGY} from './constants'\nimport type {SanityPreviewSession} from './preview/session'\nimport {getPerspective} from './utils'\nimport {hashQuery, supportsPerspectiveStack} from './utils'\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?:\n | {\n /**\n * @deprecated Use session-based preview detection instead.\n */\n enabled: boolean\n token: string\n studioUrl: string\n }\n | {\n token: string\n studioUrl: string\n session: SanityPreviewSession | HydrogenSession\n }\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 * NOTE: Only available in recent version of Hydrogen.\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 * Whether preview mode is currently enabled based on session detection\n */\n enabled: boolean\n }\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 if (process.env.NODE_ENV === 'development') {\n console.warn(\n `\nNo API version specified, defaulting to \\`${DEFAULT_API_VERSION}\\` which supports perspectives and Content Releases.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog.\n `.trim(),\n )\n }\n client = client.withConfig({apiVersion: DEFAULT_API_VERSION})\n }\n\n // Determine if preview is enabled using session-based detection or legacy enabled flag\n let isPreviewEnabled = false\n if (preview) {\n if (!preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n if ('session' in preview) {\n isPreviewEnabled = preview.session.get('projectId') === client.config().projectId\n } else {\n isPreviewEnabled = preview.enabled\n }\n\n if (isPreviewEnabled) {\n const apiVersion = client.config().apiVersion\n let perspective: ClientPerspective\n if (supportsPerspectiveStack(apiVersion)) {\n if ('session' in preview) {\n perspective = getPerspective(preview.session)\n } else {\n perspective = 'drafts'\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `API version \\`${apiVersion}\\` does not support perspective stacks. Using \\`previewDrafts\\` perspective. Consider upgrading to \\`v2025-02-19\\` or later for full perspective support.`,\n )\n }\n perspective = 'previewDrafts'\n }\n\n const previewClient = client.withConfig({\n useCdn: false,\n token: preview.token,\n perspective,\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 } 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 = isPreviewEnabled\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 args?: Parameters<Parameters<WithCache['run']>[1]>[0],\n ): Promise<QueryResponseInitial<T>> {\n // eslint-disable-next-line no-process-env\n if (process.env.NODE_ENV === 'development' && args?.addDebugData) {\n // Name displayed in the subrequest profiler\n const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'\n\n args.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: preview ? {...preview, enabled: isPreviewEnabled} : undefined,\n }\n\n return sanity\n}\n"],"names":["Object","defineProperty","exports","value","client","require","reactLoader","hydrogen","utils","DEFAULT_API_VERSION","DEFAULT_CACHE_STRATEGY","CacheLong","enumerable","get","SanityClient","createClient","validateApiPerspective","createSanityContext","options","cache","waitUntil","Promise","resolve","request","preview","defaultStrategy","withCache","createWithCache","client$1","config","apiVersion","process","env","NODE_ENV","console","warn","trim","withConfig","isPreviewEnabled","token","Error","session","projectId","enabled","perspective","supportsPerspectiveStack","getPerspective","g","previewClient","useCdn","stega","studioUrl","setServerClient","loadQuery","query","params","loaderOptions","cacheStrategy","CacheNone","queryHash","hashQuery","shouldCacheResult","runWithCache","async","args","addDebugData","displayName","debug","run","cacheKey","createSanityLoader","strategy"],"mappings":"aAEaA,OAAAC,eAAAC,QAAA,aAAA,CAAAC,OAAA,IAAA,IAAAC,EAAAC,QAAA,kBAAAC,EAAAD,QAAA,wBAAAE,EAAAF,QAAA,qBAAAG,EAAAH,QAAA,2BAAA,MAAAI,EAAsB,cACtBC,EAA0CC,EAAUA,YCoOjEX,OAAAC,eAAAC,QAAA,eAAA,CAAAU,YAAA,EAAAC,IAAA,WAAA,OAAAT,EAAAU,YAAA,IAAAd,OAAAC,eAAAC,QAAA,eAAA,CAAAU,YAAA,EAAAC,IAAA,WAAA,OAAAT,EAAAW,YAAA,IAAAf,OAAAC,eAAAC,QAAA,yBAAA,CAAAU,YAAA,EAAAC,IAAA,WAAA,OAAAT,EAAAY,sBAAA,IAAAd,QAAAe,oBC1GO,SAA6BC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M,MAAO,IACF9C,EAAOyB,SAASqB,MACnBP,SAAS,EACTQ,UAAW3B,EAAQ2B,aAIvBC,EAAAA,gBAAgBJ,EAClB,MACEI,EAAAA,gBAAgBhD,EAEpB,MACEgD,EAAAA,gBAAgBhD,GAGH,MAAA,CACb,eAAMiD,CACJC,EACAC,EACAC,GAGM,MAAAC,EAAgBnB,EAClBoB,EAAUA,YACVF,GAAejD,UAAUY,OAASoD,GAAY7D,EAE5CiD,QAAkBC,EAAAA,EAAUN,EAAOC,GAEnCM,EAAoBL,GAAejD,UAAUsD,mBAAA,MAA4B,GAEzEC,EAAeC,eACnBC,GAGA,GAA6B,gBAAzBjC,QAAQC,IAAIC,UAA8B+B,GAAMC,aAAc,CAEhE,MAAMC,EAAcV,GAAejD,UAAU4D,OAAOD,aAAe,eAEnEF,EAAKC,aAAa,CAChBC,eACD,CAGH,aAAab,EAAAA,UAAaC,EAAOC,EAAQC,EAC3C,EAEO,aAAO,QAAS9B,EACnBA,EAAU0C,IAAI,CAACC,SAAUV,EAAWF,gBAAeI,qBAAoBC,GAEvEpC,EAAUiC,EAAWF,EAAeK,GAC1C,EAAA1D,OACAA,EACAoB,QAASA,EAAU,IAAIA,EAASmB,QAASL,QAAoB,EAIjE"}
1
+ {"version":3,"file":"index.cjs","sources":["../src/constants.ts","../src/loader.ts","../src/context.ts"],"sourcesContent":["import {CacheLong, type CachingStrategy} from '@shopify/hydrogen'\n\nexport const DEFAULT_API_VERSION = 'v2025-02-19'\nexport const DEFAULT_CACHE_STRATEGY: CachingStrategy = CacheLong()\n","import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {\n CacheNone,\n type CachingStrategy,\n type HydrogenSession,\n type WithCache,\n} from '@shopify/hydrogen'\n\nimport {\n type ClientConfig,\n type ClientPerspective,\n createClient,\n type QueryParams,\n type QueryWithoutParams,\n type ResponseQueryOptions,\n SanityClient,\n} from './client'\nimport {DEFAULT_API_VERSION, DEFAULT_CACHE_STRATEGY} from './constants'\nimport type {SanityPreviewSession} from './preview/session'\nimport {getPerspective} from './utils'\nimport {hashQuery, supportsPerspectiveStack} from './utils'\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?:\n | {\n /**\n * @deprecated Use session-based preview detection instead.\n */\n enabled: boolean\n token: string\n studioUrl: string\n /**\n * Whether to enable stega encoding in preview mode.\n * @defaultValue true\n */\n stega?: boolean\n }\n | {\n token: string\n studioUrl: string\n session: SanityPreviewSession | HydrogenSession\n /**\n * Whether to enable stega encoding in preview mode.\n * @defaultValue true\n */\n stega?: boolean\n }\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 * NOTE: Only available in recent version of Hydrogen.\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 * Whether preview mode is currently enabled based on session detection\n */\n enabled: boolean\n }\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 if (process.env.NODE_ENV === 'development') {\n console.warn(\n `\nNo API version specified, defaulting to \\`${DEFAULT_API_VERSION}\\` which supports perspectives and Content Releases.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog.\n `.trim(),\n )\n }\n client = client.withConfig({apiVersion: DEFAULT_API_VERSION})\n }\n\n // Determine if preview is enabled using session-based detection or legacy enabled flag\n let isPreviewEnabled = false\n if (preview) {\n if (!preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n if ('session' in preview) {\n isPreviewEnabled = preview.session.get('projectId') === client.config().projectId\n } else {\n isPreviewEnabled = preview.enabled\n }\n\n if (isPreviewEnabled) {\n const apiVersion = client.config().apiVersion\n let perspective: ClientPerspective\n if (supportsPerspectiveStack(apiVersion)) {\n if ('session' in preview) {\n perspective = getPerspective(preview.session)\n } else {\n perspective = 'drafts'\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `API version \\`${apiVersion}\\` does not support perspective stacks. Using \\`previewDrafts\\` perspective. Consider upgrading to \\`v2025-02-19\\` or later for full perspective support.`,\n )\n }\n perspective = 'previewDrafts'\n }\n\n // Enable stega by default in preview mode, unless explicitly disabled via preview.stega\n const stegaEnabled = preview.stega !== false\n\n const previewClient = client.withConfig({\n useCdn: false,\n token: preview.token,\n perspective,\n stega: {\n enabled: stegaEnabled,\n studioUrl: preview.studioUrl,\n },\n })\n\n setServerClient(previewClient)\n } else {\n setServerClient(client)\n }\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 = isPreviewEnabled\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 args: Parameters<Parameters<WithCache['run']>[1]>[0],\n ): Promise<QueryResponseInitial<T>> {\n // eslint-disable-next-line no-process-env\n if (process.env.NODE_ENV === 'development' && args?.addDebugData) {\n // Name displayed in the subrequest profiler\n const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'\n\n args.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: preview ? {...preview, enabled: isPreviewEnabled} : undefined,\n }\n\n return sanity\n}\n","import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {\n CacheNone,\n type CachingStrategy,\n createWithCache,\n type HydrogenSession,\n type WithCache,\n} from '@shopify/hydrogen'\n\nimport {\n type ClientConfig,\n type ClientPerspective,\n createClient,\n type QueryParams,\n type QueryWithoutParams,\n type ResponseQueryOptions,\n SanityClient,\n} from './client'\nimport {DEFAULT_API_VERSION, DEFAULT_CACHE_STRATEGY} from './constants'\nimport type {SanityPreviewSession} from './preview/session'\nimport {getPerspective} from './utils'\nimport {hashQuery, supportsPerspectiveStack} from './utils'\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?:\n | {\n /**\n * @deprecated Use session-based preview detection instead.\n */\n enabled: boolean\n token: string\n studioUrl: string\n /**\n * Whether to enable stega encoding in preview mode.\n * @defaultValue true\n */\n stega?: boolean\n }\n | {\n token: string\n studioUrl: string\n session: SanityPreviewSession | HydrogenSession\n /**\n * Whether to enable stega encoding in preview mode.\n * @defaultValue true\n */\n stega?: boolean\n }\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 * NOTE: Only available in recent version of Hydrogen.\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 * Whether preview mode is currently enabled based on session detection\n */\n enabled: boolean\n }\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 if (process.env.NODE_ENV === 'development') {\n console.warn(\n `\nNo API version specified, defaulting to \\`${DEFAULT_API_VERSION}\\` which supports perspectives and Content Releases.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog.\n `.trim(),\n )\n }\n client = client.withConfig({apiVersion: DEFAULT_API_VERSION})\n }\n\n // Determine if preview is enabled using session-based detection or legacy enabled flag\n let isPreviewEnabled = false\n if (preview) {\n if (!preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n if ('session' in preview) {\n isPreviewEnabled = preview.session.get('projectId') === client.config().projectId\n } else {\n isPreviewEnabled = preview.enabled\n }\n\n if (isPreviewEnabled) {\n const apiVersion = client.config().apiVersion\n let perspective: ClientPerspective\n if (supportsPerspectiveStack(apiVersion)) {\n if ('session' in preview) {\n perspective = getPerspective(preview.session)\n } else {\n perspective = 'drafts'\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `API version \\`${apiVersion}\\` does not support perspective stacks. Using \\`previewDrafts\\` perspective. Consider upgrading to \\`v2025-02-19\\` or later for full perspective support.`,\n )\n }\n perspective = 'previewDrafts'\n }\n\n // Enable stega by default in preview mode, unless explicitly disabled via preview.stega\n const stegaEnabled = preview.stega !== false\n\n const previewClient = client.withConfig({\n useCdn: false,\n token: preview.token,\n perspective,\n stega: {\n enabled: stegaEnabled,\n studioUrl: preview.studioUrl,\n },\n })\n\n setServerClient(previewClient)\n } else {\n setServerClient(client)\n }\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 = isPreviewEnabled\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 args?: Parameters<Parameters<WithCache['run']>[1]>[0],\n ): Promise<QueryResponseInitial<T>> {\n // eslint-disable-next-line no-process-env\n if (process.env.NODE_ENV === 'development' && args?.addDebugData) {\n // Name displayed in the subrequest profiler\n const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'\n\n args.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: preview ? {...preview, enabled: isPreviewEnabled} : undefined,\n }\n\n return sanity\n}\n"],"names":["Object","defineProperty","exports","value","client","require","reactLoader","hydrogen","utils","DEFAULT_API_VERSION","DEFAULT_CACHE_STRATEGY","CacheLong","enumerable","get","SanityClient","createClient","validateApiPerspective","createSanityContext","options","cache","waitUntil","Promise","resolve","request","preview","defaultStrategy","withCache","createWithCache","client$1","config","apiVersion","process","env","NODE_ENV","console","warn","trim","withConfig","isPreviewEnabled","token","Error","session","projectId","enabled","perspective","supportsPerspectiveStack","getPerspective","g","stegaEnabled","stega","previewClient","useCdn","studioUrl","setServerClient","loadQuery","query","params","loaderOptions","cacheStrategy","CacheNone","queryHash","hashQuery","shouldCacheResult","runWithCache","async","args","addDebugData","displayName","debug","run","cacheKey","createSanityLoader","strategy"],"mappings":"aAEaA,OAAAC,eAAAC,QAAA,aAAA,CAAAC,OAAA,IAAA,IAAAC,EAAAC,QAAA,kBAAAC,EAAAD,QAAA,wBAAAE,EAAAF,QAAA,qBAAAG,EAAAH,QAAA,2BAAA,MAAAI,EAAsB,cACtBC,EAA0CC,EAAUA,YCgPjEX,OAAAC,eAAAC,QAAA,eAAA,CAAAU,YAAA,EAAAC,IAAA,WAAA,OAAAT,EAAAU,YAAA,IAAAd,OAAAC,eAAAC,QAAA,eAAA,CAAAU,YAAA,EAAAC,IAAA,WAAA,OAAAT,EAAAW,YAAA,IAAAf,OAAAC,eAAAC,QAAA,yBAAA,CAAAU,YAAA,EAAAC,IAAA,WAAA,OAAAT,EAAAY,sBAAA,IAAAd,QAAAe,oBC5GO,SAA6BC,GAC5B,MAAAC,MAACA,YAAOC,EAAY,IAAMC,QAAQC,kBAAWC,UAASC,EAASC,gBAAAA,GAAmBP,EAClFQ,EAAYP,EAAQQ,kBAAgB,CAACR,QAAOC,YAAWG,YAAY,KACrEnB,IAAAA,EACFc,EAAQd,kBAAkBU,EAAAA,aAAeI,EAAQd,OAASW,EAAAA,aAAaG,EAAQd,QAE9C,MAAxBwB,EAAAC,SAASC,aACW,gBAAzBC,QAAQC,IAAIC,UACdC,QAAQC,KACN,+CACoC1B,yJAEtC2B,QAGFhC,EAASA,EAAOiC,WAAW,CAACP,WAAYrB,KAI1C,IAAI6B,GAAmB,EACvB,GAAId,EAAS,CACX,IAAKA,EAAQe,MACL,MAAA,IAAIC,MAAM,2CASlB,GALEF,EADE,YAAad,EACIA,EAAQiB,QAAQ5B,IAAI,eAAiBT,EAAOyB,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,aAAa,CAChBC,eACD,CAGH,aAAab,EAAAA,UAAaC,EAAOC,EAAQC,EAC3C,EAEO,aAAO,QAAS/B,EACnBA,EAAU2C,IAAI,CAACC,SAAUV,EAAWF,gBAAeI,qBAAoBC,GAEvErC,EAAUkC,EAAWF,EAAeK,GAC1C,EAAA3D,OACAA,EACAoB,QAASA,EAAU,IAAIA,EAASmB,QAASL,QAAoB,EAIjE"}
package/dist/index.d.cts CHANGED
@@ -44,11 +44,21 @@ declare type CreateSanityContextOptions = {
44
44
  enabled: boolean
45
45
  token: string
46
46
  studioUrl: string
47
+ /**
48
+ * Whether to enable stega encoding in preview mode.
49
+ * @defaultValue true
50
+ */
51
+ stega?: boolean
47
52
  }
48
53
  | {
49
54
  token: string
50
55
  studioUrl: string
51
56
  session: SanityPreviewSession | HydrogenSession
57
+ /**
58
+ * Whether to enable stega encoding in preview mode.
59
+ * @defaultValue true
60
+ */
61
+ stega?: boolean
52
62
  }
53
63
  }
54
64
 
@@ -85,11 +95,21 @@ declare type CreateSanityLoaderOptions = {
85
95
  enabled: boolean
86
96
  token: string
87
97
  studioUrl: string
98
+ /**
99
+ * Whether to enable stega encoding in preview mode.
100
+ * @defaultValue true
101
+ */
102
+ stega?: boolean
88
103
  }
89
104
  | {
90
105
  token: string
91
106
  studioUrl: string
92
107
  session: SanityPreviewSession | HydrogenSession
108
+ /**
109
+ * Whether to enable stega encoding in preview mode.
110
+ * @defaultValue true
111
+ */
112
+ stega?: boolean
93
113
  }
94
114
  }
95
115
 
package/dist/index.d.ts CHANGED
@@ -44,11 +44,21 @@ declare type CreateSanityContextOptions = {
44
44
  enabled: boolean
45
45
  token: string
46
46
  studioUrl: string
47
+ /**
48
+ * Whether to enable stega encoding in preview mode.
49
+ * @defaultValue true
50
+ */
51
+ stega?: boolean
47
52
  }
48
53
  | {
49
54
  token: string
50
55
  studioUrl: string
51
56
  session: SanityPreviewSession | HydrogenSession
57
+ /**
58
+ * Whether to enable stega encoding in preview mode.
59
+ * @defaultValue true
60
+ */
61
+ stega?: boolean
52
62
  }
53
63
  }
54
64
 
@@ -85,11 +95,21 @@ declare type CreateSanityLoaderOptions = {
85
95
  enabled: boolean
86
96
  token: string
87
97
  studioUrl: string
98
+ /**
99
+ * Whether to enable stega encoding in preview mode.
100
+ * @defaultValue true
101
+ */
102
+ stega?: boolean
88
103
  }
89
104
  | {
90
105
  token: string
91
106
  studioUrl: string
92
107
  session: SanityPreviewSession | HydrogenSession
108
+ /**
109
+ * Whether to enable stega encoding in preview mode.
110
+ * @defaultValue true
111
+ */
112
+ stega?: boolean
93
113
  }
94
114
  }
95
115
 
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{SanityClient as e,createClient as n}from"@sanity/client";import{SanityClient as t,createClient as s,validateApiPerspective as i}from"@sanity/client";import{setServerClient as o,loadQuery as r}from"@sanity/react-loader";import{CacheLong as a,createWithCache as c,CacheNone as l}from"@shopify/hydrogen";import{b as p,g as d,h as u}from"./_chunks-es/utils.js";const g="v2025-02-19",f=a();function h(t){const{cache:s,waitUntil:i=()=>Promise.resolve(),request:a,preview:h,defaultStrategy:v}=t,w=s?c({cache:s,waitUntil:i,request:a}):null;let y=t.client instanceof e?t.client:n(t.client);"1"===y.config().apiVersion&&("development"===process.env.NODE_ENV&&console.warn(`\nNo API version specified, defaulting to \`${g}\` which supports perspectives and Content Releases.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog.\n `.trim()),y=y.withConfig({apiVersion:g}));let m=!1;if(h){if(!h.token)throw new Error("Enabling preview mode requires a token.");if(m="session"in h?h.session.get("projectId")===y.config().projectId:h.enabled,m){const e=y.config().apiVersion;let n;p(e)?n="session"in h?d(h.session):"drafts":("development"===process.env.NODE_ENV&&console.warn(`API version \`${e}\` does not support perspective stacks. Using \`previewDrafts\` perspective. Consider upgrading to \`v2025-02-19\` or later for full perspective support.`),n="previewDrafts");const t=y.withConfig({useCdn:!1,token:h.token,perspective:n,stega:{...y.config().stega,enabled:!0,studioUrl:h.studioUrl}});o(t)}else o(y)}else o(y);return{async loadQuery(e,n,t){if(!w)return await r(e,n,t);const s=m?l():t?.hydrogen?.cache||v||f,i=await u(e,n),o=t?.hydrogen?.shouldCacheResult??(()=>!0),a=async function(s){if("development"===process.env.NODE_ENV&&s?.addDebugData){const e=t?.hydrogen?.debug?.displayName||"query Sanity";s.addDebugData({displayName:e})}return await r(e,n,t)};return await("run"in w?w.run({cacheKey:i,cacheStrategy:s,shouldCacheResult:o},a):w(i,s,a))},client:y,preview:h?{...h,enabled:m}:void 0}}function v(t){const{withCache:s,preview:i,strategy:a}=t;let c=t.client instanceof e?t.client:n(t.client);"1"===c.config().apiVersion&&("development"===process.env.NODE_ENV&&console.warn(`\nNo API version specified, defaulting to \`${g}\` which supports perspectives and Content Releases.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog.\n `.trim()),c=c.withConfig({apiVersion:g}));let h=!1;if(i){if(!i.token)throw new Error("Enabling preview mode requires a token.");if(h="session"in i?i.session.get("projectId")===c.config().projectId:i.enabled,h){const e=c.config().apiVersion;let n;p(e)?n="session"in i?d(i.session):"drafts":("development"===process.env.NODE_ENV&&console.warn(`API version \`${e}\` does not support perspective stacks. Using \`previewDrafts\` perspective. Consider upgrading to \`v2025-02-19\` or later for full perspective support.`),n="previewDrafts");const t=c.withConfig({useCdn:!1,token:i.token,perspective:n,stega:{...c.config().stega,enabled:!0,studioUrl:i.studioUrl}});o(t)}else o(c)}else o(c);return{async loadQuery(e,n,t){const i=h?l():t?.hydrogen?.cache||a||f,o=await u(e,n),c=t?.hydrogen?.shouldCacheResult??(()=>!0),p=async function(s){if("development"===process.env.NODE_ENV&&s?.addDebugData){const e=t?.hydrogen?.debug?.displayName||"query Sanity";s.addDebugData({displayName:e})}return await r(e,n,t)};return await("run"in s?s.run({cacheKey:o,cacheStrategy:i,shouldCacheResult:c},p):s(o,i,p))},client:c,preview:i?{...i,enabled:h}:void 0}}export{t as SanityClient,s as createClient,h as createSanityContext,v as createSanityLoader,i as validateApiPerspective};//# sourceMappingURL=index.js.map
1
+ import{SanityClient as e,createClient as n}from"@sanity/client";import{SanityClient as t,createClient as s,validateApiPerspective as i}from"@sanity/client";import{setServerClient as o,loadQuery as r}from"@sanity/react-loader";import{CacheLong as a,createWithCache as c,CacheNone as l}from"@shopify/hydrogen";import{b as p,g as d,h as u}from"./_chunks-es/utils.js";const g="v2025-02-19",f=a();function h(t){const{cache:s,waitUntil:i=()=>Promise.resolve(),request:a,preview:h,defaultStrategy:v}=t,w=s?c({cache:s,waitUntil:i,request:a}):null;let y=t.client instanceof e?t.client:n(t.client);"1"===y.config().apiVersion&&("development"===process.env.NODE_ENV&&console.warn(`\nNo API version specified, defaulting to \`${g}\` which supports perspectives and Content Releases.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog.\n `.trim()),y=y.withConfig({apiVersion:g}));let m=!1;if(h){if(!h.token)throw new Error("Enabling preview mode requires a token.");if(m="session"in h?h.session.get("projectId")===y.config().projectId:h.enabled,m){const e=y.config().apiVersion;let n;p(e)?n="session"in h?d(h.session):"drafts":("development"===process.env.NODE_ENV&&console.warn(`API version \`${e}\` does not support perspective stacks. Using \`previewDrafts\` perspective. Consider upgrading to \`v2025-02-19\` or later for full perspective support.`),n="previewDrafts");const t=!1!==h.stega,s=y.withConfig({useCdn:!1,token:h.token,perspective:n,stega:{enabled:t,studioUrl:h.studioUrl}});o(s)}else o(y)}else o(y);return{async loadQuery(e,n,t){if(!w)return await r(e,n,t);const s=m?l():t?.hydrogen?.cache||v||f,i=await u(e,n),o=t?.hydrogen?.shouldCacheResult??(()=>!0),a=async function(s){if("development"===process.env.NODE_ENV&&s?.addDebugData){const e=t?.hydrogen?.debug?.displayName||"query Sanity";s.addDebugData({displayName:e})}return await r(e,n,t)};return await("run"in w?w.run({cacheKey:i,cacheStrategy:s,shouldCacheResult:o},a):w(i,s,a))},client:y,preview:h?{...h,enabled:m}:void 0}}function v(t){const{withCache:s,preview:i,strategy:a}=t;let c=t.client instanceof e?t.client:n(t.client);"1"===c.config().apiVersion&&("development"===process.env.NODE_ENV&&console.warn(`\nNo API version specified, defaulting to \`${g}\` which supports perspectives and Content Releases.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog.\n `.trim()),c=c.withConfig({apiVersion:g}));let h=!1;if(i){if(!i.token)throw new Error("Enabling preview mode requires a token.");if(h="session"in i?i.session.get("projectId")===c.config().projectId:i.enabled,h){const e=c.config().apiVersion;let n;p(e)?n="session"in i?d(i.session):"drafts":("development"===process.env.NODE_ENV&&console.warn(`API version \`${e}\` does not support perspective stacks. Using \`previewDrafts\` perspective. Consider upgrading to \`v2025-02-19\` or later for full perspective support.`),n="previewDrafts");const t=!1!==i.stega,s=c.withConfig({useCdn:!1,token:i.token,perspective:n,stega:{enabled:t,studioUrl:i.studioUrl}});o(s)}else o(c)}else o(c);return{async loadQuery(e,n,t){const i=h?l():t?.hydrogen?.cache||a||f,o=await u(e,n),c=t?.hydrogen?.shouldCacheResult??(()=>!0),p=async function(s){if("development"===process.env.NODE_ENV&&s?.addDebugData){const e=t?.hydrogen?.debug?.displayName||"query Sanity";s.addDebugData({displayName:e})}return await r(e,n,t)};return await("run"in s?s.run({cacheKey:o,cacheStrategy:i,shouldCacheResult:c},p):s(o,i,p))},client:c,preview:i?{...i,enabled:h}:void 0}}export{t as SanityClient,s as createClient,h as createSanityContext,v as createSanityLoader,i as validateApiPerspective};//# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/constants.ts","../src/context.ts","../src/loader.ts"],"sourcesContent":["import {CacheLong, type CachingStrategy} from '@shopify/hydrogen'\n\nexport const DEFAULT_API_VERSION = 'v2025-02-19'\nexport const DEFAULT_CACHE_STRATEGY: CachingStrategy = CacheLong()\n","import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {\n CacheNone,\n type CachingStrategy,\n createWithCache,\n type HydrogenSession,\n type WithCache,\n} from '@shopify/hydrogen'\n\nimport {\n type ClientConfig,\n type ClientPerspective,\n createClient,\n type QueryParams,\n type QueryWithoutParams,\n type ResponseQueryOptions,\n SanityClient,\n} from './client'\nimport {DEFAULT_API_VERSION, DEFAULT_CACHE_STRATEGY} from './constants'\nimport type {SanityPreviewSession} from './preview/session'\nimport {getPerspective} from './utils'\nimport {hashQuery, supportsPerspectiveStack} from './utils'\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?:\n | {\n /**\n * @deprecated Use session-based preview detection instead.\n */\n enabled: boolean\n token: string\n studioUrl: string\n }\n | {\n token: string\n studioUrl: string\n session: SanityPreviewSession | HydrogenSession\n }\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 * NOTE: Only available in recent version of Hydrogen.\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 * Whether preview mode is currently enabled based on session detection\n */\n enabled: boolean\n }\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 if (process.env.NODE_ENV === 'development') {\n console.warn(\n `\nNo API version specified, defaulting to \\`${DEFAULT_API_VERSION}\\` which supports perspectives and Content Releases.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog.\n `.trim(),\n )\n }\n client = client.withConfig({apiVersion: DEFAULT_API_VERSION})\n }\n\n // Determine if preview is enabled using session-based detection or legacy enabled flag\n let isPreviewEnabled = false\n if (preview) {\n if (!preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n if ('session' in preview) {\n isPreviewEnabled = preview.session.get('projectId') === client.config().projectId\n } else {\n isPreviewEnabled = preview.enabled\n }\n\n if (isPreviewEnabled) {\n const apiVersion = client.config().apiVersion\n let perspective: ClientPerspective\n if (supportsPerspectiveStack(apiVersion)) {\n if ('session' in preview) {\n perspective = getPerspective(preview.session)\n } else {\n perspective = 'drafts'\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `API version \\`${apiVersion}\\` does not support perspective stacks. Using \\`previewDrafts\\` perspective. Consider upgrading to \\`v2025-02-19\\` or later for full perspective support.`,\n )\n }\n perspective = 'previewDrafts'\n }\n\n const previewClient = client.withConfig({\n useCdn: false,\n token: preview.token,\n perspective,\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 } 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 = isPreviewEnabled\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 args?: Parameters<Parameters<WithCache['run']>[1]>[0],\n ): Promise<QueryResponseInitial<T>> {\n // eslint-disable-next-line no-process-env\n if (process.env.NODE_ENV === 'development' && args?.addDebugData) {\n // Name displayed in the subrequest profiler\n const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'\n\n args.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: preview ? {...preview, enabled: isPreviewEnabled} : undefined,\n }\n\n return sanity\n}\n","import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {\n CacheNone,\n type CachingStrategy,\n type HydrogenSession,\n type WithCache,\n} from '@shopify/hydrogen'\n\nimport {\n type ClientConfig,\n type ClientPerspective,\n createClient,\n type QueryParams,\n type QueryWithoutParams,\n type ResponseQueryOptions,\n SanityClient,\n} from './client'\nimport {DEFAULT_API_VERSION, DEFAULT_CACHE_STRATEGY} from './constants'\nimport type {SanityPreviewSession} from './preview/session'\nimport {getPerspective} from './utils'\nimport {hashQuery, supportsPerspectiveStack} from './utils'\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?:\n | {\n /**\n * @deprecated Use session-based preview detection instead.\n */\n enabled: boolean\n token: string\n studioUrl: string\n }\n | {\n token: string\n studioUrl: string\n session: SanityPreviewSession | HydrogenSession\n }\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 * NOTE: Only available in recent version of Hydrogen.\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 * Whether preview mode is currently enabled based on session detection\n */\n enabled: boolean\n }\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 if (process.env.NODE_ENV === 'development') {\n console.warn(\n `\nNo API version specified, defaulting to \\`${DEFAULT_API_VERSION}\\` which supports perspectives and Content Releases.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog.\n `.trim(),\n )\n }\n client = client.withConfig({apiVersion: DEFAULT_API_VERSION})\n }\n\n // Determine if preview is enabled using session-based detection or legacy enabled flag\n let isPreviewEnabled = false\n if (preview) {\n if (!preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n if ('session' in preview) {\n isPreviewEnabled = preview.session.get('projectId') === client.config().projectId\n } else {\n isPreviewEnabled = preview.enabled\n }\n\n if (isPreviewEnabled) {\n const apiVersion = client.config().apiVersion\n let perspective: ClientPerspective\n if (supportsPerspectiveStack(apiVersion)) {\n if ('session' in preview) {\n perspective = getPerspective(preview.session)\n } else {\n perspective = 'drafts'\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `API version \\`${apiVersion}\\` does not support perspective stacks. Using \\`previewDrafts\\` perspective. Consider upgrading to \\`v2025-02-19\\` or later for full perspective support.`,\n )\n }\n perspective = 'previewDrafts'\n }\n\n const previewClient = client.withConfig({\n useCdn: false,\n token: preview.token,\n perspective,\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 } 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 = isPreviewEnabled\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 args: Parameters<Parameters<WithCache['run']>[1]>[0],\n ): Promise<QueryResponseInitial<T>> {\n // eslint-disable-next-line no-process-env\n if (process.env.NODE_ENV === 'development' && args?.addDebugData) {\n // Name displayed in the subrequest profiler\n const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'\n\n args.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: preview ? {...preview, enabled: isPreviewEnabled} : undefined,\n }\n\n return sanity\n}\n"],"names":["SanityClient","createClient","validateApiPerspective","setServerClient","loadQuery","CacheLong","createWithCache","CacheNone","supportsPerspectiveStack","getPerspective","hashQuery","DEFAULT_API_VERSION","DEFAULT_CACHE_STRATEGY","createSanityContext","options","cache","waitUntil","Promise","resolve","request","preview","defaultStrategy","withCache","client","config","apiVersion","process","env","NODE_ENV","console","warn","trim","withConfig","isPreviewEnabled","token","Error","session","get","projectId","enabled","perspective","previewClient","useCdn","stega","studioUrl","query","params","loaderOptions","cacheStrategy","hydrogen","queryHash","shouldCacheResult","runWithCache","async","args","addDebugData","displayName","debug","run","cacheKey","createSanityLoader","strategy"],"mappings":"uBAEaA,kBAAA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AAQ,EACRR,MAAOd,EAAQc,MACfM,cACAG,MAAO,IACFpB,EAAOC,SAASmB,MACnBJ,SAAS,EACTK,UAAWxB,EAAQwB,aAIvBzC,EAAgBsC,EAClB,MACEtC,EAAgBoB,EAEpB,MACEpB,EAAgBoB,GAGH,MAAA,CACb,eAAMnB,CACJyC,EACAC,EACAC,GAGM,MAAAC,EAAgBf,EAClB1B,IACAwC,GAAeE,UAAUlC,OAAS8C,GAAYjD,EAE5CsC,QAAkBxC,EAAUmC,EAAOC,GAEnCK,EAAoBJ,GAAeE,UAAUE,yBAA4B,GAEzEC,EAAeC,eACnBC,GAGA,GAA6B,gBAAzB5B,QAAQC,IAAIC,UAA8B0B,GAAMC,aAAc,CAEhE,MAAMC,EAAcT,GAAeE,UAAUQ,OAAOD,aAAe,eAEnEF,EAAKC,aAAa,CAChBC,eACD,CAGH,aAAapD,EAAayC,EAAOC,EAAQC,EAC3C,EAEO,aAAO,QAASzB,EACnBA,EAAUoC,IAAI,CAACC,SAAUT,EAAWF,gBAAeG,qBAAoBC,GAEvE9B,EAAU4B,EAAWF,EAAeI,GAC1C,EACA7B,SACAH,QAASA,EAAU,IAAIA,EAASmB,QAASN,QAAoB,EAIjE"}
1
+ {"version":3,"file":"index.js","sources":["../src/constants.ts","../src/context.ts","../src/loader.ts"],"sourcesContent":["import {CacheLong, type CachingStrategy} from '@shopify/hydrogen'\n\nexport const DEFAULT_API_VERSION = 'v2025-02-19'\nexport const DEFAULT_CACHE_STRATEGY: CachingStrategy = CacheLong()\n","import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {\n CacheNone,\n type CachingStrategy,\n createWithCache,\n type HydrogenSession,\n type WithCache,\n} from '@shopify/hydrogen'\n\nimport {\n type ClientConfig,\n type ClientPerspective,\n createClient,\n type QueryParams,\n type QueryWithoutParams,\n type ResponseQueryOptions,\n SanityClient,\n} from './client'\nimport {DEFAULT_API_VERSION, DEFAULT_CACHE_STRATEGY} from './constants'\nimport type {SanityPreviewSession} from './preview/session'\nimport {getPerspective} from './utils'\nimport {hashQuery, supportsPerspectiveStack} from './utils'\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?:\n | {\n /**\n * @deprecated Use session-based preview detection instead.\n */\n enabled: boolean\n token: string\n studioUrl: string\n /**\n * Whether to enable stega encoding in preview mode.\n * @defaultValue true\n */\n stega?: boolean\n }\n | {\n token: string\n studioUrl: string\n session: SanityPreviewSession | HydrogenSession\n /**\n * Whether to enable stega encoding in preview mode.\n * @defaultValue true\n */\n stega?: boolean\n }\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 * NOTE: Only available in recent version of Hydrogen.\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 * Whether preview mode is currently enabled based on session detection\n */\n enabled: boolean\n }\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 if (process.env.NODE_ENV === 'development') {\n console.warn(\n `\nNo API version specified, defaulting to \\`${DEFAULT_API_VERSION}\\` which supports perspectives and Content Releases.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog.\n `.trim(),\n )\n }\n client = client.withConfig({apiVersion: DEFAULT_API_VERSION})\n }\n\n // Determine if preview is enabled using session-based detection or legacy enabled flag\n let isPreviewEnabled = false\n if (preview) {\n if (!preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n if ('session' in preview) {\n isPreviewEnabled = preview.session.get('projectId') === client.config().projectId\n } else {\n isPreviewEnabled = preview.enabled\n }\n\n if (isPreviewEnabled) {\n const apiVersion = client.config().apiVersion\n let perspective: ClientPerspective\n if (supportsPerspectiveStack(apiVersion)) {\n if ('session' in preview) {\n perspective = getPerspective(preview.session)\n } else {\n perspective = 'drafts'\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `API version \\`${apiVersion}\\` does not support perspective stacks. Using \\`previewDrafts\\` perspective. Consider upgrading to \\`v2025-02-19\\` or later for full perspective support.`,\n )\n }\n perspective = 'previewDrafts'\n }\n\n // Enable stega by default in preview mode, unless explicitly disabled via preview.stega\n const stegaEnabled = preview.stega !== false\n\n const previewClient = client.withConfig({\n useCdn: false,\n token: preview.token,\n perspective,\n stega: {\n enabled: stegaEnabled,\n studioUrl: preview.studioUrl,\n },\n })\n\n setServerClient(previewClient)\n } else {\n setServerClient(client)\n }\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 = isPreviewEnabled\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 args?: Parameters<Parameters<WithCache['run']>[1]>[0],\n ): Promise<QueryResponseInitial<T>> {\n // eslint-disable-next-line no-process-env\n if (process.env.NODE_ENV === 'development' && args?.addDebugData) {\n // Name displayed in the subrequest profiler\n const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'\n\n args.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: preview ? {...preview, enabled: isPreviewEnabled} : undefined,\n }\n\n return sanity\n}\n","import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {\n CacheNone,\n type CachingStrategy,\n type HydrogenSession,\n type WithCache,\n} from '@shopify/hydrogen'\n\nimport {\n type ClientConfig,\n type ClientPerspective,\n createClient,\n type QueryParams,\n type QueryWithoutParams,\n type ResponseQueryOptions,\n SanityClient,\n} from './client'\nimport {DEFAULT_API_VERSION, DEFAULT_CACHE_STRATEGY} from './constants'\nimport type {SanityPreviewSession} from './preview/session'\nimport {getPerspective} from './utils'\nimport {hashQuery, supportsPerspectiveStack} from './utils'\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?:\n | {\n /**\n * @deprecated Use session-based preview detection instead.\n */\n enabled: boolean\n token: string\n studioUrl: string\n /**\n * Whether to enable stega encoding in preview mode.\n * @defaultValue true\n */\n stega?: boolean\n }\n | {\n token: string\n studioUrl: string\n session: SanityPreviewSession | HydrogenSession\n /**\n * Whether to enable stega encoding in preview mode.\n * @defaultValue true\n */\n stega?: boolean\n }\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 * NOTE: Only available in recent version of Hydrogen.\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 * Whether preview mode is currently enabled based on session detection\n */\n enabled: boolean\n }\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 if (process.env.NODE_ENV === 'development') {\n console.warn(\n `\nNo API version specified, defaulting to \\`${DEFAULT_API_VERSION}\\` which supports perspectives and Content Releases.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog.\n `.trim(),\n )\n }\n client = client.withConfig({apiVersion: DEFAULT_API_VERSION})\n }\n\n // Determine if preview is enabled using session-based detection or legacy enabled flag\n let isPreviewEnabled = false\n if (preview) {\n if (!preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n if ('session' in preview) {\n isPreviewEnabled = preview.session.get('projectId') === client.config().projectId\n } else {\n isPreviewEnabled = preview.enabled\n }\n\n if (isPreviewEnabled) {\n const apiVersion = client.config().apiVersion\n let perspective: ClientPerspective\n if (supportsPerspectiveStack(apiVersion)) {\n if ('session' in preview) {\n perspective = getPerspective(preview.session)\n } else {\n perspective = 'drafts'\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `API version \\`${apiVersion}\\` does not support perspective stacks. Using \\`previewDrafts\\` perspective. Consider upgrading to \\`v2025-02-19\\` or later for full perspective support.`,\n )\n }\n perspective = 'previewDrafts'\n }\n\n // Enable stega by default in preview mode, unless explicitly disabled via preview.stega\n const stegaEnabled = preview.stega !== false\n\n const previewClient = client.withConfig({\n useCdn: false,\n token: preview.token,\n perspective,\n stega: {\n enabled: stegaEnabled,\n studioUrl: preview.studioUrl,\n },\n })\n\n setServerClient(previewClient)\n } else {\n setServerClient(client)\n }\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 = isPreviewEnabled\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 args: Parameters<Parameters<WithCache['run']>[1]>[0],\n ): Promise<QueryResponseInitial<T>> {\n // eslint-disable-next-line no-process-env\n if (process.env.NODE_ENV === 'development' && args?.addDebugData) {\n // Name displayed in the subrequest profiler\n const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'\n\n args.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: preview ? {...preview, enabled: isPreviewEnabled} : undefined,\n }\n\n return sanity\n}\n"],"names":["SanityClient","createClient","validateApiPerspective","setServerClient","loadQuery","CacheLong","createWithCache","CacheNone","supportsPerspectiveStack","getPerspective","hashQuery","DEFAULT_API_VERSION","DEFAULT_CACHE_STRATEGY","createSanityContext","options","cache","waitUntil","Promise","resolve","request","preview","defaultStrategy","withCache","client","config","apiVersion","process","env","NODE_ENV","console","warn","trim","withConfig","isPreviewEnabled","token","Error","session","get","projectId","enabled","perspective","stegaEnabled","stega","previewClient","useCdn","studioUrl","query","params","loaderOptions","cacheStrategy","hydrogen","queryHash","shouldCacheResult","runWithCache","async","args","addDebugData","displayName","debug","run","cacheKey","createSanityLoader","strategy"],"mappings":"uBAEaA,kBAAAC,MAAA,wCAAAD,kBAAAC,4BAAAC,MAAA,2CAAAC,eAAAC,MAAA,2CAAAC,qBAAAC,eAAAC,MAAA,gCAAAC,OAAAC,OAAAC,MAAA,wBAAA,MAAAC,EAAsB,cACtBC,EAA0CP,ICoIhD,SAASQ,EAAoBC,GAC5B,MAAAC,MAACA,YAAOC,EAAY,IAAMC,QAAQC,kBAAWC,UAASC,EAASC,gBAAAA,GAAmBP,EAClFQ,EAAYP,EAAQT,EAAgB,CAACS,QAAOC,YAAWG,YAAY,KACrE,IAAAI,EACFT,EAAQS,kBAAkBvB,EAAec,EAAQS,OAAStB,EAAaa,EAAQS,QAE9C,MAAxBA,EAAAC,SAASC,aACW,gBAAzBC,QAAQC,IAAIC,UACdC,QAAQC,KACN,+CACoCnB,yJAEtCoB,QAGFR,EAASA,EAAOS,WAAW,CAACP,WAAYd,KAI1C,IAAIsB,GAAmB,EACvB,GAAIb,EAAS,CACX,IAAKA,EAAQc,MACL,MAAA,IAAIC,MAAM,2CASlB,GALEF,EADE,YAAab,EACIA,EAAQgB,QAAQC,IAAI,eAAiBd,EAAOC,SAASc,UAErDlB,EAAQmB,QAGzBN,EAAkB,CACd,MAAAR,EAAaF,EAAOC,SAASC,WAC/B,IAAAe,EACAhC,EAAyBiB,GAEzBe,EADE,YAAapB,EACDX,EAAeW,EAAQgB,SAEvB,UAGa,gBAAzBV,QAAQC,IAAIC,UACdC,QAAQC,KACN,iBAAiBL,8JAGrBe,EAAc,iBAIhB,MAAMC,GAAiC,IAAlBrB,EAAQsB,MAEvBC,EAAgBpB,EAAOS,WAAW,CACtCY,QAAQ,EACRV,MAAOd,EAAQc,MACfM,cACAE,MAAO,CACLH,QAASE,EACTI,UAAW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IAAAe,EACAhC,EAAyBiB,GAEzBe,EADE,YAAapB,EACDX,EAAeW,EAAQgB,SAEvB,UAGa,gBAAzBV,QAAQC,IAAIC,UACdC,QAAQC,KACN,iBAAiBL,8JAGrBe,EAAc,iBAIhB,MAAMC,GAAiC,IAAlBrB,EAAQsB,MAEvBC,EAAgBpB,EAAOS,WAAW,CACtCY,QAAQ,EACRV,MAAOd,EAAQc,MACfM,cACAE,MAAO,CACLH,QAASE,EACTI,UAAWzB,EAAQyB,aAIvB1C,EAAgBwC,EAClB,MACExC,EAAgBoB,EAEpB,MACEpB,EAAgBoB,GAGH,MAAA,CACb,eAAMnB,CACJ0C,EACAC,EACAC,GAGM,MAAAC,EAAgBhB,EAClB1B,IACAyC,GAAeE,UAAUnC,OAAS+C,GAAYlD,EAE5CuC,QAAkBzC,EAAUoC,EAAOC,GAEnCK,EAAoBJ,GAAeE,UAAUE,yBAA4B,GAEzEC,EAAeC,eACnBC,GAGA,GAA6B,gBAAzB7B,QAAQC,IAAIC,UAA8B2B,GAAMC,aAAc,CAEhE,MAAMC,EAAcT,GAAeE,UAAUQ,OAAOD,aAAe,eAEnEF,EAAKC,aAAa,CAChBC,eACD,CAGH,aAAarD,EAAa0C,EAAOC,EAAQC,EAC3C,EAEO,aAAO,QAAS1B,EACnBA,EAAUqC,IAAI,CAACC,SAAUT,EAAWF,gBAAeG,qBAAoBC,GAEvE/B,EAAU6B,EAAWF,EAAeI,GAC1C,EACA9B,SACAH,QAASA,EAAU,IAAIA,EAASmB,QAASN,QAAoB,EAIjE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hydrogen-sanity",
3
- "version": "4.4.1",
3
+ "version": "4.5.0",
4
4
  "description": "Sanity.io toolkit for Hydrogen",
5
5
  "keywords": [
6
6
  "sanity",
@@ -20,6 +20,7 @@ const cache = vi.hoisted<Cache>(() => ({
20
20
 
21
21
  // Mock the Sanity loader
22
22
  const loadQuery = vi.hoisted<QueryStore['loadQuery']>(() => vi.fn().mockResolvedValue(null))
23
+ const setServerClient = vi.hoisted(() => vi.fn())
23
24
 
24
25
  let withCache = vi.hoisted<WithCache | null>(() => null)
25
26
 
@@ -43,6 +44,7 @@ vi.mock('@sanity/react-loader', async (importOriginal) => {
43
44
  return {
44
45
  ...module,
45
46
  loadQuery,
47
+ setServerClient,
46
48
  }
47
49
  })
48
50
 
@@ -208,3 +210,81 @@ describe('session-based preview detection', () => {
208
210
  expect(mockSession.get).toHaveBeenCalledWith('projectId')
209
211
  })
210
212
  })
213
+
214
+ describe('stega configuration in preview mode', () => {
215
+ const request = new Request('https://example.com')
216
+
217
+ beforeEach(() => {
218
+ vi.clearAllMocks()
219
+ })
220
+
221
+ it('should enable stega by default when preview is enabled', () => {
222
+ createSanityContext({
223
+ request,
224
+ cache,
225
+ client,
226
+ preview: {
227
+ enabled: true,
228
+ token: 'my-token',
229
+ studioUrl: 'https://my-studio.sanity.studio',
230
+ },
231
+ })
232
+
233
+ expect(setServerClient).toHaveBeenCalledOnce()
234
+ const previewClient = setServerClient.mock.calls[0][0]
235
+ expect(previewClient.config().stega?.enabled).toBe(true)
236
+ })
237
+
238
+ it('should use studioUrl from preview config', () => {
239
+ createSanityContext({
240
+ request,
241
+ cache,
242
+ client,
243
+ preview: {
244
+ enabled: true,
245
+ token: 'my-token',
246
+ studioUrl: 'https://my-studio.sanity.studio',
247
+ },
248
+ })
249
+
250
+ expect(setServerClient).toHaveBeenCalledOnce()
251
+ const previewClient = setServerClient.mock.calls[0][0]
252
+ expect(previewClient.config().stega?.studioUrl).toBe('https://my-studio.sanity.studio')
253
+ })
254
+
255
+ it('should allow user to disable stega via preview.stega option', () => {
256
+ createSanityContext({
257
+ request,
258
+ cache,
259
+ client,
260
+ preview: {
261
+ enabled: true,
262
+ token: 'my-token',
263
+ studioUrl: 'https://my-studio.sanity.studio',
264
+ stega: false,
265
+ },
266
+ })
267
+
268
+ expect(setServerClient).toHaveBeenCalledOnce()
269
+ const previewClient = setServerClient.mock.calls[0][0]
270
+ expect(previewClient.config().stega?.enabled).toBe(false)
271
+ })
272
+
273
+ it('should enable stega when preview.stega is explicitly true', () => {
274
+ createSanityContext({
275
+ request,
276
+ cache,
277
+ client,
278
+ preview: {
279
+ enabled: true,
280
+ token: 'my-token',
281
+ studioUrl: 'https://my-studio.sanity.studio',
282
+ stega: true,
283
+ },
284
+ })
285
+
286
+ expect(setServerClient).toHaveBeenCalledOnce()
287
+ const previewClient = setServerClient.mock.calls[0][0]
288
+ expect(previewClient.config().stega?.enabled).toBe(true)
289
+ })
290
+ })
package/src/context.ts CHANGED
@@ -53,11 +53,21 @@ export type CreateSanityContextOptions = {
53
53
  enabled: boolean
54
54
  token: string
55
55
  studioUrl: string
56
+ /**
57
+ * Whether to enable stega encoding in preview mode.
58
+ * @defaultValue true
59
+ */
60
+ stega?: boolean
56
61
  }
57
62
  | {
58
63
  token: string
59
64
  studioUrl: string
60
65
  session: SanityPreviewSession | HydrogenSession
66
+ /**
67
+ * Whether to enable stega encoding in preview mode.
68
+ * @defaultValue true
69
+ */
70
+ stega?: boolean
61
71
  }
62
72
  }
63
73
 
@@ -172,13 +182,15 @@ You can find the latest version in the Sanity changelog: https://www.sanity.io/c
172
182
  perspective = 'previewDrafts'
173
183
  }
174
184
 
185
+ // Enable stega by default in preview mode, unless explicitly disabled via preview.stega
186
+ const stegaEnabled = preview.stega !== false
187
+
175
188
  const previewClient = client.withConfig({
176
189
  useCdn: false,
177
190
  token: preview.token,
178
191
  perspective,
179
192
  stega: {
180
- ...client.config().stega,
181
- enabled: true,
193
+ enabled: stegaEnabled,
182
194
  studioUrl: preview.studioUrl,
183
195
  },
184
196
  })
@@ -8,6 +8,7 @@ import {createSanityLoader} from './loader'
8
8
  import {hashQuery} from './utils'
9
9
 
10
10
  const loadQuery = vi.hoisted<QueryStore['loadQuery']>(() => vi.fn().mockResolvedValue(null))
11
+ const setServerClient = vi.hoisted(() => vi.fn())
11
12
 
12
13
  vi.mock('@sanity/react-loader', async (importOriginal) => {
13
14
  const module = await importOriginal<typeof import('@sanity/react-loader')>()
@@ -15,6 +16,7 @@ vi.mock('@sanity/react-loader', async (importOriginal) => {
15
16
  return {
16
17
  ...module,
17
18
  loadQuery,
19
+ setServerClient,
18
20
  }
19
21
  })
20
22
 
@@ -185,3 +187,75 @@ describe('session-based preview detection', () => {
185
187
  expect(loader.preview?.enabled).toBe(false)
186
188
  })
187
189
  })
190
+
191
+ describe('stega configuration in preview mode', () => {
192
+ beforeEach(() => {
193
+ vi.clearAllMocks()
194
+ })
195
+
196
+ it('should enable stega by default when preview is enabled', () => {
197
+ createSanityLoader({
198
+ withCache,
199
+ client,
200
+ preview: {
201
+ enabled: true,
202
+ token: 'my-token',
203
+ studioUrl: 'https://my-studio.sanity.studio',
204
+ },
205
+ })
206
+
207
+ expect(setServerClient).toHaveBeenCalledOnce()
208
+ const previewClient = setServerClient.mock.calls[0][0]
209
+ expect(previewClient.config().stega?.enabled).toBe(true)
210
+ })
211
+
212
+ it('should use studioUrl from preview config', () => {
213
+ createSanityLoader({
214
+ withCache,
215
+ client,
216
+ preview: {
217
+ enabled: true,
218
+ token: 'my-token',
219
+ studioUrl: 'https://my-studio.sanity.studio',
220
+ },
221
+ })
222
+
223
+ expect(setServerClient).toHaveBeenCalledOnce()
224
+ const previewClient = setServerClient.mock.calls[0][0]
225
+ expect(previewClient.config().stega?.studioUrl).toBe('https://my-studio.sanity.studio')
226
+ })
227
+
228
+ it('should allow user to disable stega via preview.stega option', () => {
229
+ createSanityLoader({
230
+ withCache,
231
+ client,
232
+ preview: {
233
+ enabled: true,
234
+ token: 'my-token',
235
+ studioUrl: 'https://my-studio.sanity.studio',
236
+ stega: false,
237
+ },
238
+ })
239
+
240
+ expect(setServerClient).toHaveBeenCalledOnce()
241
+ const previewClient = setServerClient.mock.calls[0][0]
242
+ expect(previewClient.config().stega?.enabled).toBe(false)
243
+ })
244
+
245
+ it('should enable stega when preview.stega is explicitly true', () => {
246
+ createSanityLoader({
247
+ withCache,
248
+ client,
249
+ preview: {
250
+ enabled: true,
251
+ token: 'my-token',
252
+ studioUrl: 'https://my-studio.sanity.studio',
253
+ stega: true,
254
+ },
255
+ })
256
+
257
+ expect(setServerClient).toHaveBeenCalledOnce()
258
+ const previewClient = setServerClient.mock.calls[0][0]
259
+ expect(previewClient.config().stega?.enabled).toBe(true)
260
+ })
261
+ })
package/src/loader.ts CHANGED
@@ -51,11 +51,21 @@ export type CreateSanityLoaderOptions = {
51
51
  enabled: boolean
52
52
  token: string
53
53
  studioUrl: string
54
+ /**
55
+ * Whether to enable stega encoding in preview mode.
56
+ * @defaultValue true
57
+ */
58
+ stega?: boolean
54
59
  }
55
60
  | {
56
61
  token: string
57
62
  studioUrl: string
58
63
  session: SanityPreviewSession | HydrogenSession
64
+ /**
65
+ * Whether to enable stega encoding in preview mode.
66
+ * @defaultValue true
67
+ */
68
+ stega?: boolean
59
69
  }
60
70
  }
61
71
 
@@ -169,13 +179,15 @@ You can find the latest version in the Sanity changelog: https://www.sanity.io/c
169
179
  perspective = 'previewDrafts'
170
180
  }
171
181
 
182
+ // Enable stega by default in preview mode, unless explicitly disabled via preview.stega
183
+ const stegaEnabled = preview.stega !== false
184
+
172
185
  const previewClient = client.withConfig({
173
186
  useCdn: false,
174
187
  token: preview.token,
175
188
  perspective,
176
189
  stega: {
177
- ...client.config().stega,
178
- enabled: true,
190
+ enabled: stegaEnabled,
179
191
  studioUrl: preview.studioUrl,
180
192
  },
181
193
  })