next-sanity 12.4.0 → 12.4.2

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.
Files changed (34) hide show
  1. package/dist/PresentationComlink.js.map +1 -1
  2. package/dist/SanityLive.js +9 -9
  3. package/dist/SanityLive.js.map +1 -1
  4. package/dist/isCorsOriginError.js.map +1 -1
  5. package/dist/live/client-components/index.d.ts +6 -20
  6. package/dist/live/client-components/index.d.ts.map +1 -1
  7. package/dist/live/client-components/index.js +1 -1
  8. package/dist/live/client-components/index.js.map +1 -1
  9. package/dist/live/conditions/default/index.d.ts +83 -5
  10. package/dist/live/conditions/default/index.d.ts.map +1 -1
  11. package/dist/live/conditions/default/index.js +78 -0
  12. package/dist/live/conditions/default/index.js.map +1 -1
  13. package/dist/live/conditions/next-js/index.d.ts +83 -5
  14. package/dist/live/conditions/next-js/index.d.ts.map +1 -1
  15. package/dist/live/conditions/next-js/index.js +78 -0
  16. package/dist/live/conditions/next-js/index.js.map +1 -1
  17. package/dist/live/conditions/react-server/index.d.ts +88 -2
  18. package/dist/live/conditions/react-server/index.d.ts.map +1 -0
  19. package/dist/live/conditions/react-server/index.js +148 -68
  20. package/dist/live/conditions/react-server/index.js.map +1 -1
  21. package/dist/live/server-actions/index.d.ts +11 -0
  22. package/dist/live/server-actions/index.d.ts.map +1 -0
  23. package/dist/live/server-actions/{index.default.js → index.js} +7 -1
  24. package/dist/live/server-actions/index.js.map +1 -0
  25. package/dist/{defineLive.d.ts → types.d.ts} +39 -26
  26. package/dist/types.d.ts.map +1 -0
  27. package/dist/visual-editing/server-actions/index.d.ts +2 -2
  28. package/dist/visual-editing/server-actions/index.js +3 -3
  29. package/dist/visual-editing/server-actions/index.js.map +1 -1
  30. package/package.json +4 -6
  31. package/dist/defineLive.d.ts.map +0 -1
  32. package/dist/live/server-actions/index.default.d.ts +0 -5
  33. package/dist/live/server-actions/index.default.d.ts.map +0 -1
  34. package/dist/live/server-actions/index.default.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"PresentationComlink.js","names":[],"sources":["../src/live/client-components/PresentationComlink.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\nimport {\n createNode,\n createNodeMachine,\n // type Node,\n} from '@sanity/comlink'\nimport {\n createCompatibilityActors,\n type LoaderControllerMsg,\n type LoaderNodeMsg,\n} from '@sanity/presentation-comlink'\nimport {setPerspectiveCookie} from 'next-sanity/live/server-actions'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useEffectEvent} from 'react'\n\nimport {setComlink, setComlinkClientConfig} from '../hooks/context'\n\nfunction PresentationComlink(props: {\n projectId: string\n dataset: string\n // handleDraftModeAction: (secret: string) => Promise<void | string>\n draftModeEnabled: boolean\n draftModePerspective: ClientPerspective\n}): React.JSX.Element | null {\n const {projectId, dataset, draftModeEnabled, draftModePerspective} = props\n const router = useRouter()\n\n // const [presentationComlink, setPresentationComlink] = useState<Node<\n // LoaderControllerMsg,\n // LoaderNodeMsg\n // > | null>(null)\n\n useEffect(() => {\n setComlinkClientConfig(projectId, dataset)\n }, [dataset, projectId])\n\n const handlePerspectiveChange = useEffectEvent(\n (perspective: ClientPerspective, signal: AbortSignal) => {\n if (draftModeEnabled && perspective !== draftModePerspective) {\n setPerspectiveCookie(perspective)\n .then(() => {\n if (signal.aborted) return\n router.refresh()\n })\n .catch((reason) => console.error('Failed to set the preview perspective cookie', reason))\n }\n },\n )\n\n // const [status, setStatus] = useState('disconnected')\n useEffect(() => {\n const comlink = createNode<LoaderNodeMsg, LoaderControllerMsg>(\n {\n name: 'loaders',\n connectTo: 'presentation',\n },\n createNodeMachine<LoaderNodeMsg, LoaderControllerMsg>().provide({\n actors: createCompatibilityActors<LoaderNodeMsg>(),\n }),\n )\n\n // comlink.onStatus((status) => {\n // setStatus(status)\n // })\n\n let controller: AbortController | undefined\n comlink.on('loader/perspective', (data) => {\n controller?.abort()\n controller = new AbortController()\n handlePerspectiveChange(data.perspective, controller.signal)\n })\n\n const stop = comlink.start()\n // setPresentationComlink(comlink)\n setComlink(comlink)\n // console.log('setting comlink', comlink)\n return () => {\n // console.log('stopping comlink')\n stop()\n }\n }, [])\n\n // @TODO come back to this later\n // const handleEnableDraftMode = useEffectEvent(async (signal: AbortSignal) => {\n // if (signal.aborted) return\n // const {secret} = await (presentationComlink?.fetch(\n // {\n // type: 'loader/fetch-preview-url-secret' as const,\n // data: {projectId, dataset},\n // },\n // {signal},\n // ) || {secret: null})\n // if (signal.aborted) return\n // const error = await handleDraftModeAction(secret!)\n // // eslint-disable-next-line no-console\n // // @TODO call another server action here that can tell us if draft mode is actually enabled\n // if (error) {\n // // @TODO use sonnet or whatever to push a toast with the error\n // // eslint-disable-next-line no-console\n // console.error('Error enabling draft mode', error)\n // return\n // }\n // // console.log('Draft mode enabled?', {enabled})\n // if (signal.aborted) return\n // router.refresh()\n // })\n // const connected = status === 'connected'\n // useEffect(() => {\n // if (connected && !draftModeEnabled) {\n // const controller = new AbortController()\n // handleEnableDraftMode(controller.signal).catch((reason) => {\n // // eslint-disable-next-line no-console\n // console.error('Failed to enable draft mode', reason)\n // return handleEnableDraftMode(controller.signal)\n // })\n // return () => {\n // controller.abort()\n // }\n // }\n // return undefined\n // }, [connected, draftModeEnabled, handleEnableDraftMode])\n\n return null\n}\nPresentationComlink.displayName = 'PresentationComlink'\n\nexport default PresentationComlink\n"],"mappings":";;;;;;AAiBA,SAAS,oBAAoB,OAMA;CAC3B,MAAM,EAAC,WAAW,SAAS,kBAAkB,yBAAwB;CACrE,MAAM,SAAS,WAAW;AAO1B,iBAAgB;AACd,yBAAuB,WAAW,QAAQ;IACzC,CAAC,SAAS,UAAU,CAAC;CAExB,MAAM,0BAA0B,gBAC7B,aAAgC,WAAwB;AACvD,MAAI,oBAAoB,gBAAgB,qBACtC,sBAAqB,YAAY,CAC9B,WAAW;AACV,OAAI,OAAO,QAAS;AACpB,UAAO,SAAS;IAChB,CACD,OAAO,WAAW,QAAQ,MAAM,gDAAgD,OAAO,CAAC;GAGhG;AAGD,iBAAgB;EACd,MAAM,UAAU,WACd;GACE,MAAM;GACN,WAAW;GACZ,EACD,mBAAuD,CAAC,QAAQ,EAC9D,QAAQ,2BAA0C,EACnD,CAAC,CACH;EAMD,IAAI;AACJ,UAAQ,GAAG,uBAAuB,SAAS;AACzC,eAAY,OAAO;AACnB,gBAAa,IAAI,iBAAiB;AAClC,2BAAwB,KAAK,aAAa,WAAW,OAAO;IAC5D;EAEF,MAAM,OAAO,QAAQ,OAAO;AAE5B,aAAW,QAAQ;AAEnB,eAAa;AAEX,SAAM;;IAEP,EAAE,CAAC;AA0CN,QAAO;;AAET,oBAAoB,cAAc"}
1
+ {"version":3,"file":"PresentationComlink.js","names":[],"sources":["../src/live/client-components/PresentationComlink.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\nimport {createNode, createNodeMachine} from '@sanity/comlink'\nimport {\n createCompatibilityActors,\n type LoaderControllerMsg,\n type LoaderNodeMsg,\n} from '@sanity/presentation-comlink'\nimport {setPerspectiveCookie} from 'next-sanity/live/server-actions'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useEffectEvent} from 'react'\n\nimport {setComlink, setComlinkClientConfig} from '../hooks/context'\n\nfunction PresentationComlink(props: {\n projectId: string\n dataset: string\n draftModeEnabled: boolean\n draftModePerspective: ClientPerspective\n}): React.JSX.Element | null {\n const {projectId, dataset, draftModeEnabled, draftModePerspective} = props\n const router = useRouter()\n\n useEffect(() => {\n setComlinkClientConfig(projectId, dataset)\n }, [dataset, projectId])\n\n const handlePerspectiveChange = useEffectEvent(\n (perspective: ClientPerspective, signal: AbortSignal) => {\n if (draftModeEnabled && perspective !== draftModePerspective) {\n setPerspectiveCookie(perspective)\n .then(() => {\n if (signal.aborted) return\n router.refresh()\n })\n .catch((reason) => console.error('Failed to set the preview perspective cookie', reason))\n }\n },\n )\n\n useEffect(() => {\n const comlink = createNode<LoaderNodeMsg, LoaderControllerMsg>(\n {\n name: 'loaders',\n connectTo: 'presentation',\n },\n createNodeMachine<LoaderNodeMsg, LoaderControllerMsg>().provide({\n actors: createCompatibilityActors<LoaderNodeMsg>(),\n }),\n )\n\n let controller: AbortController | undefined\n comlink.on('loader/perspective', (data) => {\n controller?.abort()\n controller = new AbortController()\n handlePerspectiveChange(data.perspective, controller.signal)\n })\n\n const stop = comlink.start()\n setComlink(comlink)\n return () => {\n stop()\n }\n }, [])\n\n return null\n}\nPresentationComlink.displayName = 'PresentationComlink'\n\nexport default PresentationComlink\n"],"mappings":";;;;;;AAaA,SAAS,oBAAoB,OAKA;CAC3B,MAAM,EAAC,WAAW,SAAS,kBAAkB,yBAAwB;CACrE,MAAM,SAAS,WAAW;AAE1B,iBAAgB;AACd,yBAAuB,WAAW,QAAQ;IACzC,CAAC,SAAS,UAAU,CAAC;CAExB,MAAM,0BAA0B,gBAC7B,aAAgC,WAAwB;AACvD,MAAI,oBAAoB,gBAAgB,qBACtC,sBAAqB,YAAY,CAC9B,WAAW;AACV,OAAI,OAAO,QAAS;AACpB,UAAO,SAAS;IAChB,CACD,OAAO,WAAW,QAAQ,MAAM,gDAAgD,OAAO,CAAC;GAGhG;AAED,iBAAgB;EACd,MAAM,UAAU,WACd;GACE,MAAM;GACN,WAAW;GACZ,EACD,mBAAuD,CAAC,QAAQ,EAC9D,QAAQ,2BAA0C,EACnD,CAAC,CACH;EAED,IAAI;AACJ,UAAQ,GAAG,uBAAuB,SAAS;AACzC,eAAY,OAAO;AACnB,gBAAa,IAAI,iBAAiB;AAClC,2BAAwB,KAAK,aAAa,WAAW,OAAO;IAC5D;EAEF,MAAM,OAAO,QAAQ,OAAO;AAC5B,aAAW,QAAQ;AACnB,eAAa;AACX,SAAM;;IAEP,EAAE,CAAC;AAEN,QAAO;;AAET,oBAAoB,cAAc"}
@@ -12,16 +12,8 @@ const RefreshOnFocus = dynamic(() => import("./RefreshOnFocus.js"));
12
12
  const RefreshOnMount = dynamic(() => import("./RefreshOnMount.js"));
13
13
  const RefreshOnInterval = dynamic(() => import("./RefreshOnInterval.js"));
14
14
  const RefreshOnReconnect = dynamic(() => import("./RefreshOnReconnect.js"));
15
- function handleError(error) {
16
- if (isCorsOriginError(error)) console.warn(`Sanity Live is unable to connect to the Sanity API as the current origin - ${window.origin} - is not in the list of allowed CORS origins for this Sanity Project.`, error.addOriginUrl && `Add it here:`, error.addOriginUrl?.toString());
17
- else console.error(error);
18
- }
19
- function handleOnGoAway(event, intervalOnGoAway) {
20
- if (intervalOnGoAway) console.warn("Sanity Live connection closed, switching to long polling set to a interval of", intervalOnGoAway / 1e3, "seconds and the server gave this reason:", event.reason);
21
- else console.error("Sanity Live connection closed, automatic revalidation is disabled, the server gave this reason:", event.reason);
22
- }
23
15
  function SanityLive(props) {
24
- const { projectId, dataset, apiHost, apiVersion, useProjectHostname, token, requestTagPrefix, draftModeEnabled, draftModePerspective, refreshOnMount = false, refreshOnFocus = draftModeEnabled ? false : typeof window === "undefined" ? true : window.self === window.top, refreshOnReconnect = true, intervalOnGoAway = 3e4, requestTag = "next-loader.live", onError = handleError, onGoAway = handleOnGoAway, revalidateSyncTags: revalidateSyncTags$1 = revalidateSyncTags, waitFor } = props;
16
+ const { projectId, dataset, apiHost, apiVersion, useProjectHostname, token, requestTagPrefix, draftModeEnabled, draftModePerspective, requestTag = "next-loader.live", waitFor, revalidateSyncTags: revalidateSyncTags$1 = revalidateSyncTags, onError = handleError, intervalOnGoAway = 3e4, onGoAway = handleOnGoAway, refreshOnMount = false, refreshOnFocus = draftModeEnabled ? false : typeof window === "undefined" ? true : window.self === window.top, refreshOnReconnect = true } = props;
25
17
  const client = useMemo(() => createClient({
26
18
  projectId,
27
19
  dataset,
@@ -152,6 +144,14 @@ function SanityLive(props) {
152
144
  ] });
153
145
  }
154
146
  SanityLive.displayName = "SanityLiveClientComponent";
147
+ function handleError(error) {
148
+ if (isCorsOriginError(error)) console.warn(`Sanity Live is unable to connect to the Sanity API as the current origin - ${window.origin} - is not in the list of allowed CORS origins for this Sanity Project.`, error.addOriginUrl && `Add it here:`, error.addOriginUrl?.toString());
149
+ else console.error(error);
150
+ }
151
+ function handleOnGoAway(event, intervalOnGoAway) {
152
+ if (intervalOnGoAway) console.warn("Sanity Live connection closed, switching to long polling set to a interval of", intervalOnGoAway / 1e3, "seconds and the server gave this reason:", event.reason);
153
+ else console.error("Sanity Live connection closed, automatic revalidation is disabled, the server gave this reason:", event.reason);
154
+ }
155
155
  export { SanityLive as default };
156
156
 
157
157
  //# sourceMappingURL=SanityLive.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"SanityLive.js","names":["defaultRevalidateSyncTags","revalidateSyncTags"],"sources":["../src/live/client-components/SanityLive.tsx"],"sourcesContent":["import {\n createClient,\n type ClientPerspective,\n type InitializedClientConfig,\n type LiveEvent,\n type LiveEventGoAway,\n type SyncTag,\n} from '@sanity/client'\nimport {isMaybePresentation, isMaybePreviewWindow} from '@sanity/presentation-comlink'\nimport {revalidateSyncTags as defaultRevalidateSyncTags} from 'next-sanity/live/server-actions'\nimport dynamic from 'next/dynamic'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useMemo, useRef, useState, useEffectEvent, startTransition} from 'react'\n\nimport {isCorsOriginError} from '#live/isCorsOriginError'\n\nimport {setEnvironment, setPerspective} from '../hooks/context'\n\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'))\nconst RefreshOnFocus = dynamic(() => import('./RefreshOnFocus'))\nconst RefreshOnMount = dynamic(() => import('./RefreshOnMount'))\nconst RefreshOnInterval = dynamic(() => import('./RefreshOnInterval'))\nconst RefreshOnReconnect = dynamic(() => import('./RefreshOnReconnect'))\n\n/**\n * @public\n */\nexport interface SanityLiveProps extends Pick<\n InitializedClientConfig,\n | 'projectId'\n | 'dataset'\n | 'apiHost'\n | 'apiVersion'\n | 'useProjectHostname'\n | 'token'\n | 'requestTagPrefix'\n> {\n // handleDraftModeAction: (secret: string) => Promise<void | string>\n draftModeEnabled: boolean\n draftModePerspective?: ClientPerspective\n refreshOnMount?: boolean\n refreshOnFocus?: boolean\n refreshOnReconnect?: boolean\n requestTag: string | undefined\n /**\n * Handle errors from the Live Events subscription.\n * By default it's reported using `console.error`, you can override this prop to handle it in your own way.\n */\n onError?: (error: unknown) => void\n intervalOnGoAway?: number | false\n onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void\n revalidateSyncTags?: (tags: SyncTag[]) => Promise<void | 'refresh'>\n /**\n * Delays events until after a configured Sanity Function has processed them and called the callback endpoint.\n * When omitted, events are delivered immediately.\n *\n * @remarks\n * When set, any custom `revalidateSyncTags` will not be called — revalidation is handled by the Function instead.\n */\n waitFor?: 'function'\n}\n\nfunction handleError(error: unknown) {\n if (isCorsOriginError(error)) {\n console.warn(\n `Sanity Live is unable to connect to the Sanity API as the current origin - ${window.origin} - is not in the list of allowed CORS origins for this Sanity Project.`,\n error.addOriginUrl && `Add it here:`,\n error.addOriginUrl?.toString(),\n )\n } else {\n console.error(error)\n }\n}\n\nfunction handleOnGoAway(event: LiveEventGoAway, intervalOnGoAway: number | false) {\n if (intervalOnGoAway) {\n console.warn(\n 'Sanity Live connection closed, switching to long polling set to a interval of',\n intervalOnGoAway / 1000,\n 'seconds and the server gave this reason:',\n event.reason,\n )\n } else {\n console.error(\n 'Sanity Live connection closed, automatic revalidation is disabled, the server gave this reason:',\n event.reason,\n )\n }\n}\n\nfunction SanityLive(props: SanityLiveProps): React.JSX.Element | null {\n const {\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n token,\n requestTagPrefix,\n // handleDraftModeAction,\n draftModeEnabled,\n draftModePerspective,\n refreshOnMount = false,\n refreshOnFocus = draftModeEnabled\n ? false\n : typeof window === 'undefined'\n ? true\n : window.self === window.top,\n refreshOnReconnect = true,\n intervalOnGoAway = 30_000,\n requestTag = 'next-loader.live',\n onError = handleError,\n onGoAway = handleOnGoAway,\n revalidateSyncTags = defaultRevalidateSyncTags,\n waitFor,\n } = props\n\n const client = useMemo(\n () =>\n createClient({\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n ignoreBrowserTokenWarning: true,\n token,\n useCdn: false,\n requestTagPrefix,\n }),\n [apiHost, apiVersion, dataset, projectId, requestTagPrefix, token, useProjectHostname],\n )\n const [refreshOnInterval, setRefreshOnInterval] = useState<number | false>(false)\n\n /**\n * 1. Handle Live Events and call revalidateTag or router.refresh when needed\n */\n const router = useRouter()\n const handleLiveEvent = useEffectEvent((event: LiveEvent) => {\n if (process.env.NODE_ENV !== 'production' && event.type === 'welcome') {\n // oxlint-disable-next-line no-console\n console.info(\n 'Sanity is live with',\n token\n ? 'automatic revalidation for draft content changes as well as published content'\n : draftModeEnabled\n ? 'automatic revalidation for only published content. Provide a `browserToken` to `defineLive` to support draft content outside of Presentation Tool.'\n : 'automatic revalidation of published content',\n )\n // Disable long polling when welcome event is received, this is a no-op if long polling is already disabled\n startTransition(() => setRefreshOnInterval(false))\n } else if (event.type === 'message') {\n if (waitFor === 'function') {\n // Cache is already revalidated by the Sanity Function, just refresh the router\n startTransition(() => router.refresh())\n } else {\n void revalidateSyncTags(event.tags).then((result) => {\n if (result === 'refresh') startTransition(() => router.refresh())\n })\n }\n } else if (event.type === 'restart' || event.type === 'reconnect') {\n // Disable long polling when restart/reconnect event is received, this is a no-op if long polling is already disabled\n startTransition(() => setRefreshOnInterval(false))\n // @TODO add support for `onRestart` and `onReconnect` events so this can be customized\n startTransition(() => router.refresh())\n } else if (event.type === 'goaway') {\n onGoAway(event, intervalOnGoAway)\n startTransition(() => setRefreshOnInterval(intervalOnGoAway))\n }\n })\n useEffect(() => {\n const subscription = client.live\n .events({includeDrafts: !!token, tag: requestTag, waitFor})\n .subscribe({\n next: handleLiveEvent,\n error: (err: unknown) => {\n // console.error('What?', err)\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token, waitFor])\n\n /**\n * 2. Notify what perspective we're in, when in Draft Mode\n */\n useEffect(() => {\n if (draftModeEnabled && draftModePerspective) {\n setPerspective(draftModePerspective)\n } else {\n setPerspective('unknown')\n }\n }, [draftModeEnabled, draftModePerspective])\n\n const [loadComlink, setLoadComlink] = useState(false)\n /**\n * 3. Notify what environment we're in, when in Draft Mode\n */\n useEffect(() => {\n // If we might be in Presentation Tool, then skip detecting here as it's handled later\n if (isMaybePresentation()) return\n\n // If we're definitely not in Presentation Tool, then we can set the environment as stand-alone live preview\n // if we have both a browser token, and draft mode is enabled\n if (draftModeEnabled && token) {\n setEnvironment('live')\n return\n }\n // If we're in draft mode, but don't have a browser token, then we're in static mode\n // which means that published content is still live, but draft changes likely need manual refresh\n if (draftModeEnabled) {\n setEnvironment('static')\n return\n }\n\n // Fallback to `unknown` otherwise, as we simply don't know how it's setup\n setEnvironment('unknown')\n return\n }, [draftModeEnabled, token])\n\n /**\n * 4. If Presentation Tool is detected, load up the comlink and integrate with it\n */\n useEffect(() => {\n if (!isMaybePresentation()) return\n const controller = new AbortController()\n // Wait for a while to see if Presentation Tool is detected, before assuming the env to be stand-alone live preview\n const timeout = setTimeout(() => setEnvironment('live'), 3_000)\n window.addEventListener(\n 'message',\n ({data}: MessageEvent<unknown>) => {\n if (\n data &&\n typeof data === 'object' &&\n 'domain' in data &&\n data.domain === 'sanity/channels' &&\n 'from' in data &&\n data.from === 'presentation'\n ) {\n clearTimeout(timeout)\n setEnvironment(isMaybePreviewWindow() ? 'presentation-window' : 'presentation-iframe')\n setLoadComlink(true)\n controller.abort()\n }\n },\n {signal: controller.signal},\n )\n return () => {\n clearTimeout(timeout)\n controller.abort()\n }\n }, [])\n\n /**\n * 5. Warn if draft mode is being disabled\n * @TODO move logic into PresentationComlink, or maybe VisualEditing?\n */\n const draftModeEnabledWarnRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n useEffect(() => {\n if (!draftModeEnabled) return\n clearTimeout(draftModeEnabledWarnRef.current)\n return () => {\n draftModeEnabledWarnRef.current = setTimeout(() => {\n console.warn('Sanity Live: Draft mode was enabled, but is now being disabled')\n })\n }\n }, [draftModeEnabled])\n\n return (\n <>\n {draftModeEnabled && loadComlink && (\n <PresentationComlink\n projectId={projectId!}\n dataset={dataset!}\n // handleDraftModeAction={handleDraftModeAction}\n draftModeEnabled={draftModeEnabled}\n draftModePerspective={draftModePerspective!}\n />\n )}\n {!draftModeEnabled && refreshOnMount && <RefreshOnMount />}\n {refreshOnInterval && Number.isFinite(refreshOnInterval) && refreshOnInterval > 0 && (\n <RefreshOnInterval interval={refreshOnInterval} />\n )}\n {!draftModeEnabled && refreshOnFocus && <RefreshOnFocus />}\n {!draftModeEnabled && refreshOnReconnect && <RefreshOnReconnect />}\n </>\n )\n}\n\nSanityLive.displayName = 'SanityLiveClientComponent'\n\nexport default SanityLive\n"],"mappings":";;;;;;;;;AAkBA,MAAM,sBAAsB,cAAc,OAAO,4BAAyB;AAC1E,MAAM,iBAAiB,cAAc,OAAO,uBAAoB;AAChE,MAAM,iBAAiB,cAAc,OAAO,uBAAoB;AAChE,MAAM,oBAAoB,cAAc,OAAO,0BAAuB;AACtE,MAAM,qBAAqB,cAAc,OAAO,2BAAwB;AAwCxE,SAAS,YAAY,OAAgB;AACnC,KAAI,kBAAkB,MAAM,CAC1B,SAAQ,KACN,8EAA8E,OAAO,OAAO,yEAC5F,MAAM,gBAAgB,gBACtB,MAAM,cAAc,UAAU,CAC/B;KAED,SAAQ,MAAM,MAAM;;AAIxB,SAAS,eAAe,OAAwB,kBAAkC;AAChF,KAAI,iBACF,SAAQ,KACN,iFACA,mBAAmB,KACnB,4CACA,MAAM,OACP;KAED,SAAQ,MACN,mGACA,MAAM,OACP;;AAIL,SAAS,WAAW,OAAkD;CACpE,MAAM,EACJ,WACA,SACA,SACA,YACA,oBACA,OACA,kBAEA,kBACA,sBACA,iBAAiB,OACjB,iBAAiB,mBACb,QACA,OAAO,WAAW,cAChB,OACA,OAAO,SAAS,OAAO,KAC7B,qBAAqB,MACrB,mBAAmB,KACnB,aAAa,oBACb,UAAU,aACV,WAAW,gBACX,oBAAA,uBAAqBA,oBACrB,YACE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,oBAAC,oBAAD,EAAsB,CAAA;EACjE,EAAA,CAAA;;AAIP,WAAW,cAAc"}
1
+ {"version":3,"file":"SanityLive.js","names":["defaultRevalidateSyncTags","revalidateSyncTags"],"sources":["../src/live/client-components/SanityLive.tsx"],"sourcesContent":["import {\n createClient,\n type ClientPerspective,\n type InitializedClientConfig,\n type LiveEvent,\n type LiveEventGoAway,\n type SyncTag,\n} from '@sanity/client'\nimport {isMaybePresentation, isMaybePreviewWindow} from '@sanity/presentation-comlink'\nimport {revalidateSyncTags as defaultRevalidateSyncTags} from 'next-sanity/live/server-actions'\nimport dynamic from 'next/dynamic'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useMemo, useRef, useState, useEffectEvent, startTransition} from 'react'\n\nimport {isCorsOriginError} from '#live/isCorsOriginError'\n\nimport {setEnvironment, setPerspective} from '../hooks/context'\n\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'))\nconst RefreshOnFocus = dynamic(() => import('./RefreshOnFocus'))\nconst RefreshOnMount = dynamic(() => import('./RefreshOnMount'))\nconst RefreshOnInterval = dynamic(() => import('./RefreshOnInterval'))\nconst RefreshOnReconnect = dynamic(() => import('./RefreshOnReconnect'))\n\nexport interface SanityLiveProps extends Pick<\n InitializedClientConfig,\n | 'projectId'\n | 'dataset'\n | 'apiHost'\n | 'apiVersion'\n | 'useProjectHostname'\n | 'token'\n | 'requestTagPrefix'\n> {\n draftModeEnabled: boolean\n draftModePerspective?: ClientPerspective\n requestTag: string | undefined\n waitFor?: 'function'\n\n revalidateSyncTags?: (tags: SyncTag[]) => Promise<void | 'refresh'>\n onError?: (error: unknown) => void\n intervalOnGoAway?: number | false\n onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void\n\n refreshOnMount?: boolean\n refreshOnFocus?: boolean\n refreshOnReconnect?: boolean\n}\n\nfunction SanityLive(props: SanityLiveProps): React.JSX.Element | null {\n const {\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n token,\n requestTagPrefix,\n draftModeEnabled,\n draftModePerspective,\n requestTag = 'next-loader.live',\n waitFor,\n\n revalidateSyncTags = defaultRevalidateSyncTags,\n onError = handleError,\n intervalOnGoAway = 30_000,\n onGoAway = handleOnGoAway,\n\n refreshOnMount = false,\n refreshOnFocus = draftModeEnabled\n ? false\n : typeof window === 'undefined'\n ? true\n : window.self === window.top,\n refreshOnReconnect = true,\n } = props\n\n const client = useMemo(\n () =>\n createClient({\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n ignoreBrowserTokenWarning: true,\n token,\n useCdn: false,\n requestTagPrefix,\n }),\n [apiHost, apiVersion, dataset, projectId, requestTagPrefix, token, useProjectHostname],\n )\n\n const [refreshOnInterval, setRefreshOnInterval] = useState<number | false>(false)\n\n /**\n * 1. Handle Live Events and call revalidateTag or router.refresh when needed\n */\n const router = useRouter()\n const handleLiveEvent = useEffectEvent((event: LiveEvent) => {\n if (process.env.NODE_ENV !== 'production' && event.type === 'welcome') {\n // oxlint-disable-next-line no-console\n console.info(\n 'Sanity is live with',\n token\n ? 'automatic revalidation for draft content changes as well as published content'\n : draftModeEnabled\n ? 'automatic revalidation for only published content. Provide a `browserToken` to `defineLive` to support draft content outside of Presentation Tool.'\n : 'automatic revalidation of published content',\n )\n // Disable long polling when welcome event is received, this is a no-op if long polling is already disabled\n startTransition(() => setRefreshOnInterval(false))\n } else if (event.type === 'message') {\n if (waitFor === 'function') {\n // Cache is already revalidated by the Sanity Function, just refresh the router\n startTransition(() => router.refresh())\n } else {\n void revalidateSyncTags(event.tags).then((result) => {\n if (result === 'refresh') startTransition(() => router.refresh())\n })\n }\n } else if (event.type === 'restart' || event.type === 'reconnect') {\n // Disable long polling when restart/reconnect event is received, this is a no-op if long polling is already disabled\n startTransition(() => setRefreshOnInterval(false))\n // @TODO add support for `onRestart` and `onReconnect` events so this can be customized\n startTransition(() => router.refresh())\n } else if (event.type === 'goaway') {\n onGoAway(event, intervalOnGoAway)\n startTransition(() => setRefreshOnInterval(intervalOnGoAway))\n }\n })\n useEffect(() => {\n const subscription = client.live\n .events({includeDrafts: !!token, tag: requestTag, waitFor})\n .subscribe({\n next: handleLiveEvent,\n error: (err: unknown) => {\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token, waitFor])\n\n /**\n * 2. Notify what perspective we're in, when in Draft Mode\n */\n useEffect(() => {\n if (draftModeEnabled && draftModePerspective) {\n setPerspective(draftModePerspective)\n } else {\n setPerspective('unknown')\n }\n }, [draftModeEnabled, draftModePerspective])\n\n const [loadComlink, setLoadComlink] = useState(false)\n /**\n * 3. Notify what environment we're in, when in Draft Mode\n */\n useEffect(() => {\n // If we might be in Presentation Tool, then skip detecting here as it's handled later\n if (isMaybePresentation()) return\n\n // If we're definitely not in Presentation Tool, then we can set the environment as stand-alone live preview\n // if we have both a browser token, and draft mode is enabled\n if (draftModeEnabled && token) {\n setEnvironment('live')\n return\n }\n // If we're in draft mode, but don't have a browser token, then we're in static mode\n // which means that published content is still live, but draft changes likely need manual refresh\n if (draftModeEnabled) {\n setEnvironment('static')\n return\n }\n\n // Fallback to `unknown` otherwise, as we simply don't know how it's setup\n setEnvironment('unknown')\n return\n }, [draftModeEnabled, token])\n\n /**\n * 4. If Presentation Tool is detected, load up the comlink and integrate with it\n */\n useEffect(() => {\n if (!isMaybePresentation()) return\n const controller = new AbortController()\n // Wait for a while to see if Presentation Tool is detected, before assuming the env to be stand-alone live preview\n const timeout = setTimeout(() => setEnvironment('live'), 3_000)\n window.addEventListener(\n 'message',\n ({data}: MessageEvent<unknown>) => {\n if (\n data &&\n typeof data === 'object' &&\n 'domain' in data &&\n data.domain === 'sanity/channels' &&\n 'from' in data &&\n data.from === 'presentation'\n ) {\n clearTimeout(timeout)\n setEnvironment(isMaybePreviewWindow() ? 'presentation-window' : 'presentation-iframe')\n setLoadComlink(true)\n controller.abort()\n }\n },\n {signal: controller.signal},\n )\n return () => {\n clearTimeout(timeout)\n controller.abort()\n }\n }, [])\n\n /**\n * 5. Warn if draft mode is being disabled\n * @TODO move logic into PresentationComlink, or maybe VisualEditing?\n */\n const draftModeEnabledWarnRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n useEffect(() => {\n if (!draftModeEnabled) return\n clearTimeout(draftModeEnabledWarnRef.current)\n return () => {\n draftModeEnabledWarnRef.current = setTimeout(() => {\n console.warn('Sanity Live: Draft mode was enabled, but is now being disabled')\n })\n }\n }, [draftModeEnabled])\n\n return (\n <>\n {draftModeEnabled && loadComlink && (\n <PresentationComlink\n projectId={projectId!}\n dataset={dataset!}\n draftModeEnabled={draftModeEnabled}\n draftModePerspective={draftModePerspective!}\n />\n )}\n {!draftModeEnabled && refreshOnMount && <RefreshOnMount />}\n {refreshOnInterval && Number.isFinite(refreshOnInterval) && refreshOnInterval > 0 && (\n <RefreshOnInterval interval={refreshOnInterval} />\n )}\n {!draftModeEnabled && refreshOnFocus && <RefreshOnFocus />}\n {!draftModeEnabled && refreshOnReconnect && <RefreshOnReconnect />}\n </>\n )\n}\n\nSanityLive.displayName = 'SanityLiveClientComponent'\n\nexport default SanityLive\n\nfunction handleError(error: unknown) {\n if (isCorsOriginError(error)) {\n console.warn(\n `Sanity Live is unable to connect to the Sanity API as the current origin - ${window.origin} - is not in the list of allowed CORS origins for this Sanity Project.`,\n error.addOriginUrl && `Add it here:`,\n error.addOriginUrl?.toString(),\n )\n } else {\n console.error(error)\n }\n}\n\nfunction handleOnGoAway(event: LiveEventGoAway, intervalOnGoAway: number | false) {\n if (intervalOnGoAway) {\n console.warn(\n 'Sanity Live connection closed, switching to long polling set to a interval of',\n intervalOnGoAway / 1000,\n 'seconds and the server gave this reason:',\n event.reason,\n )\n } else {\n console.error(\n 'Sanity Live connection closed, automatic revalidation is disabled, the server gave this reason:',\n event.reason,\n )\n }\n}\n"],"mappings":";;;;;;;;;AAkBA,MAAM,sBAAsB,cAAc,OAAO,4BAAyB;AAC1E,MAAM,iBAAiB,cAAc,OAAO,uBAAoB;AAChE,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EAAiE;KAC9E;;IAEH,CAAC,iBAAiB,CAAC;AAEtB,QACE,qBAAA,UAAA,EAAA,UAAA;EACG,oBAAoB,eACnB,oBAAC,qBAAD;GACa;GACF;GACS;GACI;GACtB,CAAA;EAEH,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAD,EAAkB,CAAA;EACzD,qBAAqB,OAAO,SAAS,kBAAkB,IAAI,oBAAoB,KAC9E,oBAAC,mBAAD,EAAmB,UAAU,mBAAqB,CAAA;EAEnD,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAD,EAAkB,CAAA;EACzD,CAAC,oBAAoB,sBAAsB,oBAAC,oBAAD,EAAsB,CAAA;EACjE,EAAA,CAAA;;AAIP,WAAW,cAAc;AAIzB,SAAS,YAAY,OAAgB;AACnC,KAAI,kBAAkB,MAAM,CAC1B,SAAQ,KACN,8EAA8E,OAAO,OAAO,yEAC5F,MAAM,gBAAgB,gBACtB,MAAM,cAAc,UAAU,CAC/B;KAED,SAAQ,MAAM,MAAM;;AAIxB,SAAS,eAAe,OAAwB,kBAAkC;AAChF,KAAI,iBACF,SAAQ,KACN,iFACA,mBAAmB,KACnB,4CACA,MAAM,OACP;KAED,SAAQ,MACN,mGACA,MAAM,OACP"}
@@ -1 +1 @@
1
- {"version":3,"file":"isCorsOriginError.js","names":[],"sources":["../src/live/shared/isCorsOriginError.ts"],"sourcesContent":["import type {CorsOriginError} from '@sanity/client'\n\n/** @public */\nexport function isCorsOriginError(error: unknown): error is CorsOriginError {\n return error instanceof Error && error.name === 'CorsOriginError'\n}\n\nexport type {CorsOriginError}\n"],"mappings":";AAGA,SAAgB,kBAAkB,OAA0C;AAC1E,QAAO,iBAAiB,SAAS,MAAM,SAAS"}
1
+ {"version":3,"file":"isCorsOriginError.js","names":[],"sources":["../src/live/shared/isCorsOriginError.ts"],"sourcesContent":["import type {CorsOriginError} from '@sanity/client'\n\n/** @public */\nexport function isCorsOriginError(error: unknown): error is CorsOriginError {\n return error instanceof Error && error.name === 'CorsOriginError'\n}\n"],"mappings":";AAGA,SAAgB,kBAAkB,OAA0C;AAC1E,QAAO,iBAAiB,SAAS,MAAM,SAAS"}
@@ -1,33 +1,19 @@
1
1
  import { ClientPerspective, InitializedClientConfig, LiveEventGoAway, SyncTag } from "@sanity/client";
2
- /**
3
- * @public
4
- */
5
2
  interface SanityLiveProps extends Pick<InitializedClientConfig, "projectId" | "dataset" | "apiHost" | "apiVersion" | "useProjectHostname" | "token" | "requestTagPrefix"> {
6
3
  draftModeEnabled: boolean;
7
4
  draftModePerspective?: ClientPerspective;
8
- refreshOnMount?: boolean;
9
- refreshOnFocus?: boolean;
10
- refreshOnReconnect?: boolean;
11
5
  requestTag: string | undefined;
12
- /**
13
- * Handle errors from the Live Events subscription.
14
- * By default it's reported using `console.error`, you can override this prop to handle it in your own way.
15
- */
6
+ waitFor?: "function";
7
+ revalidateSyncTags?: (tags: SyncTag[]) => Promise<void | "refresh">;
16
8
  onError?: (error: unknown) => void;
17
9
  intervalOnGoAway?: number | false;
18
10
  onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void;
19
- revalidateSyncTags?: (tags: SyncTag[]) => Promise<void | "refresh">;
20
- /**
21
- * Delays events until after a configured Sanity Function has processed them and called the callback endpoint.
22
- * When omitted, events are delivered immediately.
23
- *
24
- * @remarks
25
- * When set, any custom `revalidateSyncTags` will not be called — revalidation is handled by the Function instead.
26
- */
27
- waitFor?: "function";
11
+ refreshOnMount?: boolean;
12
+ refreshOnFocus?: boolean;
13
+ refreshOnReconnect?: boolean;
28
14
  }
29
15
  /**
30
- * @alpha CAUTION: this is an internal component and does not follow semver. Using it directly is at your own risk.
16
+ * @internal CAUTION: this is an internal component and does not follow semver. Using it directly is at your own risk.
31
17
  */
32
18
  declare const SanityLive: React.ComponentType<SanityLiveProps>;
33
19
  export { SanityLive };
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/live/client-components/SanityLive.tsx","../../../src/live/client-components/index.ts"],"mappings":";;AA2BA;;UAAiB,eAAA,SAAwB,IAAA,CACvC,uBAAA;EAUA,gBAAA;EACA,oBAAA,GAAuB,iBAAA;EACvB,cAAA;EACA,cAAA;EACA,kBAAA;EACA,UAAA;;;;;EAKA,OAAA,IAAW,KAAA;EACX,gBAAA;EACA,QAAA,IAAY,KAAA,EAAO,eAAA,EAAiB,gBAAA;EACpC,kBAAA,IAAsB,IAAA,EAAM,OAAA,OAAc,OAAA;;;;;;;;EAQ1C,OAAA;AAAA;;AAhCF;;cCnBa,UAAA,EAAY,KAAA,CAAM,aAAA,CAAc,eAAA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/live/client-components/SanityLive.tsx","../../../src/live/client-components/index.ts"],"mappings":";UAwBiB,eAAA,SAAwB,IAAA,CACvC,uBAAA;EASA,gBAAA;EACA,oBAAA,GAAuB,iBAAA;EACvB,UAAA;EACA,OAAA;EAEA,kBAAA,IAAsB,IAAA,EAAM,OAAA,OAAc,OAAA;EAC1C,OAAA,IAAW,KAAA;EACX,gBAAA;EACA,QAAA,IAAY,KAAA,EAAO,eAAA,EAAiB,gBAAA;EAEpC,cAAA;EACA,cAAA;EACA,kBAAA;AAAA;;AAtBF;;cChBa,UAAA,EAAY,KAAA,CAAM,aAAA,CAAc,eAAA"}
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
  import dynamic from "next/dynamic";
3
3
  /**
4
- * @alpha CAUTION: this is an internal component and does not follow semver. Using it directly is at your own risk.
4
+ * @internal CAUTION: this is an internal component and does not follow semver. Using it directly is at your own risk.
5
5
  */
6
6
  const SanityLive = dynamic(() => import("../../SanityLive.js"), { ssr: false });
7
7
  export { SanityLive };
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/live/client-components/index.ts"],"sourcesContent":["'use client'\n\nimport dynamic from 'next/dynamic'\n\nimport type {SanityLiveProps} from './SanityLive'\n/**\n * @alpha CAUTION: this is an internal component and does not follow semver. Using it directly is at your own risk.\n */\nexport const SanityLive: React.ComponentType<SanityLiveProps> = dynamic(\n () => import('./SanityLive'),\n {ssr: false},\n)\n"],"mappings":";;;;;AAQA,MAAa,aAAmD,cACxD,OAAO,wBACb,EAAC,KAAK,OAAM,CACb"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/live/client-components/index.ts"],"sourcesContent":["'use client'\n\nimport dynamic from 'next/dynamic'\n\nimport type {SanityLiveProps} from './SanityLive'\n/**\n * @internal CAUTION: this is an internal component and does not follow semver. Using it directly is at your own risk.\n */\nexport const SanityLive: React.ComponentType<SanityLiveProps> = dynamic(\n () => import('./SanityLive'),\n {ssr: false},\n)\n"],"mappings":";;;;;AAQA,MAAa,aAAmD,cACxD,OAAO,wBACb,EAAC,KAAK,OAAM,CACb"}
@@ -1,11 +1,89 @@
1
1
  import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
2
- import { n as DefinedSanityFetchType, r as DefinedSanityLiveProps, t as DefineSanityLiveOptions } from "../../../defineLive.js";
2
+ import { i as LivePerspective, n as DefinedFetchType, r as DefinedLiveProps, t as DefineLiveOptions } from "../../../types.js";
3
3
  /**
4
+ * Set up Sanity Live. `defineLive` returns `sanityFetch` and `<SanityLive />`,
5
+ * which connect your Sanity client to the Live Content API so pages can serve
6
+ * cached content and update in response to fine-grained content changes.
7
+ *
8
+ * @see [Live Content API](https://www.sanity.io/docs/content-lake/live-content-api)
9
+ * @see [Sanity Live](https://www.sanity.io/live)
10
+ *
11
+ * @example
12
+ * ```tsx
13
+ * import {createClient} from 'next-sanity'
14
+ * import {defineLive} from 'next-sanity/live'
15
+ *
16
+ * const client = createClient({
17
+ * projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
18
+ * dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
19
+ * useCdn: true,
20
+ * perspective: 'published',
21
+ * })
22
+ * const token = process.env.SANITY_API_READ_TOKEN
23
+ *
24
+ * export const {sanityFetch, SanityLive} = defineLive({
25
+ * client,
26
+ * browserToken: token,
27
+ * serverToken: token,
28
+ * })
29
+ * ```
30
+ *
31
+ * @example
32
+ * ```tsx
33
+ * // app/layout.tsx
34
+ * import {SanityLive} from '@/sanity/live'
35
+ *
36
+ * export default function RootLayout({children}: {children: React.ReactNode}) {
37
+ * return (
38
+ * <html lang="en">
39
+ * <body>
40
+ * {children}
41
+ * <SanityLive />
42
+ * </body>
43
+ * </html>
44
+ * )
45
+ * }
46
+ * ```
47
+ *
48
+ * @example
49
+ * ```tsx
50
+ * // app/[slug]/page.tsx
51
+ * import {defineQuery} from 'next-sanity'
52
+ * import {sanityFetch} from '@/sanity/live'
53
+ *
54
+ * const POSTS_SLUGS_QUERY = defineQuery(`
55
+ * *[_type == "post" && slug.current]{"slug": slug.current}
56
+ * `)
57
+ * const POST_QUERY = defineQuery(`
58
+ * *[_type == "post" && slug.current == $slug][0]
59
+ * `)
60
+ *
61
+ * export async function generateStaticParams() {
62
+ * const {data} = await sanityFetch({
63
+ * query: POSTS_SLUGS_QUERY,
64
+ * perspective: 'published',
65
+ * stega: false,
66
+ * })
67
+ *
68
+ * return data
69
+ * }
70
+ *
71
+ * export default async function Page(props: PageProps<'/[slug]'>) {
72
+ * const {slug} = await props.params
73
+ * const {data} = await sanityFetch({
74
+ * query: POST_QUERY,
75
+ * params: {slug},
76
+ * })
77
+ *
78
+ * return <pre>{JSON.stringify(data, null, 2)}</pre>
79
+ * }
80
+ * ```
81
+ *
4
82
  * @public
5
83
  */
6
- declare function defineLive(_config: DefineSanityLiveOptions): {
7
- sanityFetch: DefinedSanityFetchType;
8
- SanityLive: React.ComponentType<DefinedSanityLiveProps>;
84
+ declare function defineLive(_config: DefineLiveOptions): {
85
+ sanityFetch: DefinedFetchType;
86
+ SanityLive: React.ComponentType<DefinedLiveProps>;
9
87
  };
10
- export { type DefineSanityLiveOptions, type DefinedSanityFetchType, type DefinedSanityLiveProps, defineLive, isCorsOriginError };
88
+ export { type DefineLiveOptions as DefineSanityLiveOptions, type DefinedFetchType as DefinedSanityFetchType, type DefinedLiveProps as DefinedSanityLiveProps, type LivePerspective, defineLive, isCorsOriginError };
11
89
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/live/conditions/default/index.ts"],"mappings":";;;;AASA;iBAAgB,UAAA,CAAW,OAAA,EAAS,uBAAA;EAClC,WAAA,EAAa,sBAAA;EACb,UAAA,EAAY,KAAA,CAAM,aAAA,CAAc,sBAAA;AAAA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/live/conditions/default/index.ts"],"mappings":";;;;AAmFA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,UAAA,CAAW,OAAA,EAAS,iBAAA;EAClC,WAAA,EAAa,gBAAA;EACb,UAAA,EAAY,KAAA,CAAM,aAAA,CAAc,gBAAA;AAAA"}
@@ -1,5 +1,83 @@
1
1
  import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
2
2
  /**
3
+ * Set up Sanity Live. `defineLive` returns `sanityFetch` and `<SanityLive />`,
4
+ * which connect your Sanity client to the Live Content API so pages can serve
5
+ * cached content and update in response to fine-grained content changes.
6
+ *
7
+ * @see [Live Content API](https://www.sanity.io/docs/content-lake/live-content-api)
8
+ * @see [Sanity Live](https://www.sanity.io/live)
9
+ *
10
+ * @example
11
+ * ```tsx
12
+ * import {createClient} from 'next-sanity'
13
+ * import {defineLive} from 'next-sanity/live'
14
+ *
15
+ * const client = createClient({
16
+ * projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
17
+ * dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
18
+ * useCdn: true,
19
+ * perspective: 'published',
20
+ * })
21
+ * const token = process.env.SANITY_API_READ_TOKEN
22
+ *
23
+ * export const {sanityFetch, SanityLive} = defineLive({
24
+ * client,
25
+ * browserToken: token,
26
+ * serverToken: token,
27
+ * })
28
+ * ```
29
+ *
30
+ * @example
31
+ * ```tsx
32
+ * // app/layout.tsx
33
+ * import {SanityLive} from '@/sanity/live'
34
+ *
35
+ * export default function RootLayout({children}: {children: React.ReactNode}) {
36
+ * return (
37
+ * <html lang="en">
38
+ * <body>
39
+ * {children}
40
+ * <SanityLive />
41
+ * </body>
42
+ * </html>
43
+ * )
44
+ * }
45
+ * ```
46
+ *
47
+ * @example
48
+ * ```tsx
49
+ * // app/[slug]/page.tsx
50
+ * import {defineQuery} from 'next-sanity'
51
+ * import {sanityFetch} from '@/sanity/live'
52
+ *
53
+ * const POSTS_SLUGS_QUERY = defineQuery(`
54
+ * *[_type == "post" && slug.current]{"slug": slug.current}
55
+ * `)
56
+ * const POST_QUERY = defineQuery(`
57
+ * *[_type == "post" && slug.current == $slug][0]
58
+ * `)
59
+ *
60
+ * export async function generateStaticParams() {
61
+ * const {data} = await sanityFetch({
62
+ * query: POSTS_SLUGS_QUERY,
63
+ * perspective: 'published',
64
+ * stega: false,
65
+ * })
66
+ *
67
+ * return data
68
+ * }
69
+ *
70
+ * export default async function Page(props: PageProps<'/[slug]'>) {
71
+ * const {slug} = await props.params
72
+ * const {data} = await sanityFetch({
73
+ * query: POST_QUERY,
74
+ * params: {slug},
75
+ * })
76
+ *
77
+ * return <pre>{JSON.stringify(data, null, 2)}</pre>
78
+ * }
79
+ * ```
80
+ *
3
81
  * @public
4
82
  */
5
83
  function defineLive(_config) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../src/live/conditions/default/index.ts"],"sourcesContent":["import type {\n DefineSanityLiveOptions,\n DefinedSanityFetchType,\n DefinedSanityLiveProps,\n} from '../react-server/defineLive'\n\n/**\n * @public\n */\nexport function defineLive(_config: DefineSanityLiveOptions): {\n sanityFetch: DefinedSanityFetchType\n SanityLive: React.ComponentType<DefinedSanityLiveProps>\n} {\n throw new Error('defineLive can only be used in React Server Components')\n}\n\n/**\n * @public\n */\nexport type {DefineSanityLiveOptions, DefinedSanityFetchType, DefinedSanityLiveProps}\n\nexport {isCorsOriginError} from '#live/isCorsOriginError'\n"],"mappings":";;;;AASA,SAAgB,WAAW,SAGzB;AACA,OAAM,IAAI,MAAM,yDAAyD"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../src/live/conditions/default/index.ts"],"sourcesContent":["import type {DefinedFetchType, DefinedLiveProps, DefineLiveOptions} from '#live/types'\n\n/**\n * Set up Sanity Live. `defineLive` returns `sanityFetch` and `<SanityLive />`,\n * which connect your Sanity client to the Live Content API so pages can serve\n * cached content and update in response to fine-grained content changes.\n *\n * @see [Live Content API](https://www.sanity.io/docs/content-lake/live-content-api)\n * @see [Sanity Live](https://www.sanity.io/live)\n *\n * @example\n * ```tsx\n * import {createClient} from 'next-sanity'\n * import {defineLive} from 'next-sanity/live'\n *\n * const client = createClient({\n * projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,\n * dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,\n * useCdn: true,\n * perspective: 'published',\n * })\n * const token = process.env.SANITY_API_READ_TOKEN\n *\n * export const {sanityFetch, SanityLive} = defineLive({\n * client,\n * browserToken: token,\n * serverToken: token,\n * })\n * ```\n *\n * @example\n * ```tsx\n * // app/layout.tsx\n * import {SanityLive} from '@/sanity/live'\n *\n * export default function RootLayout({children}: {children: React.ReactNode}) {\n * return (\n * <html lang=\"en\">\n * <body>\n * {children}\n * <SanityLive />\n * </body>\n * </html>\n * )\n * }\n * ```\n *\n * @example\n * ```tsx\n * // app/[slug]/page.tsx\n * import {defineQuery} from 'next-sanity'\n * import {sanityFetch} from '@/sanity/live'\n *\n * const POSTS_SLUGS_QUERY = defineQuery(`\n * *[_type == \"post\" && slug.current]{\"slug\": slug.current}\n * `)\n * const POST_QUERY = defineQuery(`\n * *[_type == \"post\" && slug.current == $slug][0]\n * `)\n *\n * export async function generateStaticParams() {\n * const {data} = await sanityFetch({\n * query: POSTS_SLUGS_QUERY,\n * perspective: 'published',\n * stega: false,\n * })\n *\n * return data\n * }\n *\n * export default async function Page(props: PageProps<'/[slug]'>) {\n * const {slug} = await props.params\n * const {data} = await sanityFetch({\n * query: POST_QUERY,\n * params: {slug},\n * })\n *\n * return <pre>{JSON.stringify(data, null, 2)}</pre>\n * }\n * ```\n *\n * @public\n */\nexport function defineLive(_config: DefineLiveOptions): {\n sanityFetch: DefinedFetchType\n SanityLive: React.ComponentType<DefinedLiveProps>\n} {\n throw new Error('defineLive can only be used in React Server Components')\n}\n\nexport type {\n DefinedFetchType as DefinedSanityFetchType,\n DefinedLiveProps as DefinedSanityLiveProps,\n DefineLiveOptions as DefineSanityLiveOptions,\n LivePerspective,\n} from '#live/types'\n\nexport {isCorsOriginError} from '#live/isCorsOriginError'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmFA,SAAgB,WAAW,SAGzB;AACA,OAAM,IAAI,MAAM,yDAAyD"}
@@ -1,11 +1,89 @@
1
1
  import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
2
- import { n as DefinedSanityFetchType, r as DefinedSanityLiveProps, t as DefineSanityLiveOptions } from "../../../defineLive.js";
2
+ import { i as LivePerspective, n as DefinedFetchType, r as DefinedLiveProps, t as DefineLiveOptions } from "../../../types.js";
3
3
  /**
4
+ * Set up Sanity Live. `defineLive` returns `sanityFetch` and `<SanityLive />`,
5
+ * which connect your Sanity client to the Live Content API so pages can serve
6
+ * cached content and update in response to fine-grained content changes.
7
+ *
8
+ * @see [Live Content API](https://www.sanity.io/docs/content-lake/live-content-api)
9
+ * @see [Sanity Live](https://www.sanity.io/live)
10
+ *
11
+ * @example
12
+ * ```tsx
13
+ * import {createClient} from 'next-sanity'
14
+ * import {defineLive} from 'next-sanity/live'
15
+ *
16
+ * const client = createClient({
17
+ * projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
18
+ * dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
19
+ * useCdn: true,
20
+ * perspective: 'published',
21
+ * })
22
+ * const token = process.env.SANITY_API_READ_TOKEN
23
+ *
24
+ * export const {sanityFetch, SanityLive} = defineLive({
25
+ * client,
26
+ * browserToken: token,
27
+ * serverToken: token,
28
+ * })
29
+ * ```
30
+ *
31
+ * @example
32
+ * ```tsx
33
+ * // app/layout.tsx
34
+ * import {SanityLive} from '@/sanity/live'
35
+ *
36
+ * export default function RootLayout({children}: {children: React.ReactNode}) {
37
+ * return (
38
+ * <html lang="en">
39
+ * <body>
40
+ * {children}
41
+ * <SanityLive />
42
+ * </body>
43
+ * </html>
44
+ * )
45
+ * }
46
+ * ```
47
+ *
48
+ * @example
49
+ * ```tsx
50
+ * // app/[slug]/page.tsx
51
+ * import {defineQuery} from 'next-sanity'
52
+ * import {sanityFetch} from '@/sanity/live'
53
+ *
54
+ * const POSTS_SLUGS_QUERY = defineQuery(`
55
+ * *[_type == "post" && slug.current]{"slug": slug.current}
56
+ * `)
57
+ * const POST_QUERY = defineQuery(`
58
+ * *[_type == "post" && slug.current == $slug][0]
59
+ * `)
60
+ *
61
+ * export async function generateStaticParams() {
62
+ * const {data} = await sanityFetch({
63
+ * query: POSTS_SLUGS_QUERY,
64
+ * perspective: 'published',
65
+ * stega: false,
66
+ * })
67
+ *
68
+ * return data
69
+ * }
70
+ *
71
+ * export default async function Page(props: PageProps<'/[slug]'>) {
72
+ * const {slug} = await props.params
73
+ * const {data} = await sanityFetch({
74
+ * query: POST_QUERY,
75
+ * params: {slug},
76
+ * })
77
+ *
78
+ * return <pre>{JSON.stringify(data, null, 2)}</pre>
79
+ * }
80
+ * ```
81
+ *
4
82
  * @public
5
83
  */
6
- declare function defineLive(_config: DefineSanityLiveOptions): {
7
- sanityFetch: DefinedSanityFetchType;
8
- SanityLive: React.ComponentType<DefinedSanityLiveProps>;
84
+ declare function defineLive(_config: DefineLiveOptions): {
85
+ sanityFetch: DefinedFetchType;
86
+ SanityLive: React.ComponentType<DefinedLiveProps>;
9
87
  };
10
- export { type DefineSanityLiveOptions, type DefinedSanityFetchType, type DefinedSanityLiveProps, defineLive, isCorsOriginError };
88
+ export { type DefineLiveOptions as DefineSanityLiveOptions, type DefinedFetchType as DefinedSanityFetchType, type DefinedLiveProps as DefinedSanityLiveProps, type LivePerspective, defineLive, isCorsOriginError };
11
89
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/live/conditions/next-js/index.ts"],"mappings":";;;;AASA;iBAAgB,UAAA,CAAW,OAAA,EAAS,uBAAA;EAClC,WAAA,EAAa,sBAAA;EACb,UAAA,EAAY,KAAA,CAAM,aAAA,CAAc,sBAAA;AAAA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/live/conditions/next-js/index.ts"],"mappings":";;;;AAmFA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,UAAA,CAAW,OAAA,EAAS,iBAAA;EAClC,WAAA,EAAa,gBAAA;EACb,UAAA,EAAY,KAAA,CAAM,aAAA,CAAc,gBAAA;AAAA"}
@@ -1,5 +1,83 @@
1
1
  import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
2
2
  /**
3
+ * Set up Sanity Live. `defineLive` returns `sanityFetch` and `<SanityLive />`,
4
+ * which connect your Sanity client to the Live Content API so pages can serve
5
+ * cached content and update in response to fine-grained content changes.
6
+ *
7
+ * @see [Live Content API](https://www.sanity.io/docs/content-lake/live-content-api)
8
+ * @see [Sanity Live](https://www.sanity.io/live)
9
+ *
10
+ * @example
11
+ * ```tsx
12
+ * import {createClient} from 'next-sanity'
13
+ * import {defineLive} from 'next-sanity/live'
14
+ *
15
+ * const client = createClient({
16
+ * projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
17
+ * dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
18
+ * useCdn: true,
19
+ * perspective: 'published',
20
+ * })
21
+ * const token = process.env.SANITY_API_READ_TOKEN
22
+ *
23
+ * export const {sanityFetch, SanityLive} = defineLive({
24
+ * client,
25
+ * browserToken: token,
26
+ * serverToken: token,
27
+ * })
28
+ * ```
29
+ *
30
+ * @example
31
+ * ```tsx
32
+ * // app/layout.tsx
33
+ * import {SanityLive} from '@/sanity/live'
34
+ *
35
+ * export default function RootLayout({children}: {children: React.ReactNode}) {
36
+ * return (
37
+ * <html lang="en">
38
+ * <body>
39
+ * {children}
40
+ * <SanityLive />
41
+ * </body>
42
+ * </html>
43
+ * )
44
+ * }
45
+ * ```
46
+ *
47
+ * @example
48
+ * ```tsx
49
+ * // app/[slug]/page.tsx
50
+ * import {defineQuery} from 'next-sanity'
51
+ * import {sanityFetch} from '@/sanity/live'
52
+ *
53
+ * const POSTS_SLUGS_QUERY = defineQuery(`
54
+ * *[_type == "post" && slug.current]{"slug": slug.current}
55
+ * `)
56
+ * const POST_QUERY = defineQuery(`
57
+ * *[_type == "post" && slug.current == $slug][0]
58
+ * `)
59
+ *
60
+ * export async function generateStaticParams() {
61
+ * const {data} = await sanityFetch({
62
+ * query: POSTS_SLUGS_QUERY,
63
+ * perspective: 'published',
64
+ * stega: false,
65
+ * })
66
+ *
67
+ * return data
68
+ * }
69
+ *
70
+ * export default async function Page(props: PageProps<'/[slug]'>) {
71
+ * const {slug} = await props.params
72
+ * const {data} = await sanityFetch({
73
+ * query: POST_QUERY,
74
+ * params: {slug},
75
+ * })
76
+ *
77
+ * return <pre>{JSON.stringify(data, null, 2)}</pre>
78
+ * }
79
+ * ```
80
+ *
3
81
  * @public
4
82
  */
5
83
  function defineLive(_config) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../src/live/conditions/next-js/index.ts"],"sourcesContent":["import type {\n DefineSanityLiveOptions,\n DefinedSanityFetchType,\n DefinedSanityLiveProps,\n} from '../react-server/defineLive'\n\n/**\n * @public\n */\nexport function defineLive(_config: DefineSanityLiveOptions): {\n sanityFetch: DefinedSanityFetchType\n SanityLive: React.ComponentType<DefinedSanityLiveProps>\n} {\n throw new Error('defineLive does not yet support `cacheComponents: true`. Wait for the next major version of next-sanity, or use the prerelease with `pnpm install next-sanity@cache-components`')\n}\n\n/**\n * @public\n */\nexport type {DefineSanityLiveOptions, DefinedSanityFetchType, DefinedSanityLiveProps}\n\nexport {isCorsOriginError} from '#live/isCorsOriginError'\n"],"mappings":";;;;AASA,SAAgB,WAAW,SAGzB;AACA,OAAM,IAAI,MAAM,kLAAkL"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../src/live/conditions/next-js/index.ts"],"sourcesContent":["import type {DefinedFetchType, DefinedLiveProps, DefineLiveOptions} from '#live/types'\n\n/**\n * Set up Sanity Live. `defineLive` returns `sanityFetch` and `<SanityLive />`,\n * which connect your Sanity client to the Live Content API so pages can serve\n * cached content and update in response to fine-grained content changes.\n *\n * @see [Live Content API](https://www.sanity.io/docs/content-lake/live-content-api)\n * @see [Sanity Live](https://www.sanity.io/live)\n *\n * @example\n * ```tsx\n * import {createClient} from 'next-sanity'\n * import {defineLive} from 'next-sanity/live'\n *\n * const client = createClient({\n * projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,\n * dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,\n * useCdn: true,\n * perspective: 'published',\n * })\n * const token = process.env.SANITY_API_READ_TOKEN\n *\n * export const {sanityFetch, SanityLive} = defineLive({\n * client,\n * browserToken: token,\n * serverToken: token,\n * })\n * ```\n *\n * @example\n * ```tsx\n * // app/layout.tsx\n * import {SanityLive} from '@/sanity/live'\n *\n * export default function RootLayout({children}: {children: React.ReactNode}) {\n * return (\n * <html lang=\"en\">\n * <body>\n * {children}\n * <SanityLive />\n * </body>\n * </html>\n * )\n * }\n * ```\n *\n * @example\n * ```tsx\n * // app/[slug]/page.tsx\n * import {defineQuery} from 'next-sanity'\n * import {sanityFetch} from '@/sanity/live'\n *\n * const POSTS_SLUGS_QUERY = defineQuery(`\n * *[_type == \"post\" && slug.current]{\"slug\": slug.current}\n * `)\n * const POST_QUERY = defineQuery(`\n * *[_type == \"post\" && slug.current == $slug][0]\n * `)\n *\n * export async function generateStaticParams() {\n * const {data} = await sanityFetch({\n * query: POSTS_SLUGS_QUERY,\n * perspective: 'published',\n * stega: false,\n * })\n *\n * return data\n * }\n *\n * export default async function Page(props: PageProps<'/[slug]'>) {\n * const {slug} = await props.params\n * const {data} = await sanityFetch({\n * query: POST_QUERY,\n * params: {slug},\n * })\n *\n * return <pre>{JSON.stringify(data, null, 2)}</pre>\n * }\n * ```\n *\n * @public\n */\nexport function defineLive(_config: DefineLiveOptions): {\n sanityFetch: DefinedFetchType\n SanityLive: React.ComponentType<DefinedLiveProps>\n} {\n throw new Error(\n 'defineLive does not yet support `cacheComponents: true`. Wait for the next major version of next-sanity, or use the prerelease with `pnpm install next-sanity@cache-components`',\n )\n}\n\nexport type {\n DefinedFetchType as DefinedSanityFetchType,\n DefinedLiveProps as DefinedSanityLiveProps,\n DefineLiveOptions as DefineSanityLiveOptions,\n LivePerspective,\n} from '#live/types'\n\nexport {isCorsOriginError} from '#live/isCorsOriginError'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmFA,SAAgB,WAAW,SAGzB;AACA,OAAM,IAAI,MACR,kLACD"}