next-sanity 12.3.2 → 12.3.4
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/dist/PresentationComlink.js.map +1 -1
- package/dist/RefreshOnFocus.js.map +1 -1
- package/dist/RefreshOnMount.js.map +1 -1
- package/dist/RefreshOnReconnect.js.map +1 -1
- package/dist/defineLive.d.ts +1 -36
- package/dist/defineLive.d.ts.map +1 -1
- package/dist/isCorsOriginError.d.ts.map +1 -1
- package/dist/isCorsOriginError.js.map +1 -1
- package/dist/live/client-components/index.d.ts.map +1 -0
- package/dist/live/client-components/{live/index.js → index.js} +6 -6
- package/dist/live/client-components/index.js.map +1 -0
- package/dist/live/conditions/default/index.d.ts +11 -0
- package/dist/live/conditions/default/index.d.ts.map +1 -0
- package/dist/{live.server-only.js → live/conditions/default/index.js} +2 -2
- package/dist/live/conditions/default/index.js.map +1 -0
- package/dist/live/conditions/react-server/index.d.ts +3 -0
- package/dist/{live.js → live/conditions/react-server/index.js} +47 -88
- package/dist/live/conditions/react-server/index.js.map +1 -0
- package/dist/live/server-actions/{index.d.ts → index.default.d.ts} +1 -1
- package/dist/live/server-actions/index.default.d.ts.map +1 -0
- package/dist/live/server-actions/{index.js → index.default.js} +2 -2
- package/dist/live/server-actions/index.default.js.map +1 -0
- package/dist/{utils.js → sanitizePerspective.js} +1 -2
- package/dist/sanitizePerspective.js.map +1 -0
- package/package.json +10 -9
- package/dist/SanityLiveStream.js +0 -72
- package/dist/SanityLiveStream.js.map +0 -1
- package/dist/live/client-components/live/index.d.ts.map +0 -1
- package/dist/live/client-components/live/index.js.map +0 -1
- package/dist/live/client-components/live-stream/index.d.ts +0 -19
- package/dist/live/client-components/live-stream/index.d.ts.map +0 -1
- package/dist/live/client-components/live-stream/index.js +0 -15
- package/dist/live/client-components/live-stream/index.js.map +0 -1
- package/dist/live/server-actions/index.d.ts.map +0 -1
- package/dist/live/server-actions/index.js.map +0 -1
- package/dist/live.d.ts +0 -3
- package/dist/live.js.map +0 -1
- package/dist/live.server-only.d.ts +0 -12
- package/dist/live.server-only.d.ts.map +0 -1
- package/dist/live.server-only.js.map +0 -1
- package/dist/utils.js.map +0 -1
- /package/dist/live/client-components/{live/index.d.ts → index.d.ts} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PresentationComlink.js","names":[],"sources":["../src/live/client-components/
|
|
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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RefreshOnFocus.js","names":[],"sources":["../src/live/client-components/
|
|
1
|
+
{"version":3,"file":"RefreshOnFocus.js","names":[],"sources":["../src/live/client-components/RefreshOnFocus.tsx"],"sourcesContent":["import {useRouter} from 'next/navigation'\nimport {useEffect} from 'react'\n\nconst focusThrottleInterval = 5_000\n\nexport default function RefreshOnFocus(): null {\n const router = useRouter()\n\n useEffect(() => {\n const controller = new AbortController()\n let nextFocusRevalidatedAt = 0\n const callback = () => {\n const now = Date.now()\n if (now > nextFocusRevalidatedAt && document.visibilityState !== 'hidden') {\n router.refresh()\n nextFocusRevalidatedAt = now + focusThrottleInterval\n }\n }\n const {signal} = controller\n document.addEventListener('visibilitychange', callback, {passive: true, signal})\n window.addEventListener('focus', callback, {passive: true, signal})\n return () => controller.abort()\n }, [router])\n\n return null\n}\nRefreshOnFocus.displayName = 'RefreshOnFocus'\n"],"mappings":";;AAGA,MAAM,wBAAwB;AAE9B,SAAwB,iBAAuB;CAC7C,MAAM,SAAS,WAAW;AAE1B,iBAAgB;EACd,MAAM,aAAa,IAAI,iBAAiB;EACxC,IAAI,yBAAyB;EAC7B,MAAM,iBAAiB;GACrB,MAAM,MAAM,KAAK,KAAK;AACtB,OAAI,MAAM,0BAA0B,SAAS,oBAAoB,UAAU;AACzE,WAAO,SAAS;AAChB,6BAAyB,MAAM;;;EAGnC,MAAM,EAAC,WAAU;AACjB,WAAS,iBAAiB,oBAAoB,UAAU;GAAC,SAAS;GAAM;GAAO,CAAC;AAChF,SAAO,iBAAiB,SAAS,UAAU;GAAC,SAAS;GAAM;GAAO,CAAC;AACnE,eAAa,WAAW,OAAO;IAC9B,CAAC,OAAO,CAAC;AAEZ,QAAO;;AAET,eAAe,cAAc"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RefreshOnMount.js","names":[],"sources":["../src/live/client-components/
|
|
1
|
+
{"version":3,"file":"RefreshOnMount.js","names":[],"sources":["../src/live/client-components/RefreshOnMount.tsx"],"sourcesContent":["/**\n * Handles refreshing the page when the page is mounted,\n * in case the content changes at a high enough frequency that by\n * the time the page started streaming, and the <SanityLive> component sets\n * up the EventSource connection, content might have changed.\n */\n\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useReducer} from 'react'\n\nexport default function RefreshOnMount(): null {\n const router = useRouter()\n const [mounted, mount] = useReducer(() => true, false)\n\n useEffect(() => {\n if (!mounted) {\n mount()\n router.refresh()\n }\n }, [mounted, router])\n\n return null\n}\nRefreshOnMount.displayName = 'RefreshOnMount'\n"],"mappings":";;;;;;;;AAUA,SAAwB,iBAAuB;CAC7C,MAAM,SAAS,WAAW;CAC1B,MAAM,CAAC,SAAS,SAAS,iBAAiB,MAAM,MAAM;AAEtD,iBAAgB;AACd,MAAI,CAAC,SAAS;AACZ,UAAO;AACP,UAAO,SAAS;;IAEjB,CAAC,SAAS,OAAO,CAAC;AAErB,QAAO;;AAET,eAAe,cAAc"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RefreshOnReconnect.js","names":[],"sources":["../src/live/client-components/
|
|
1
|
+
{"version":3,"file":"RefreshOnReconnect.js","names":[],"sources":["../src/live/client-components/RefreshOnReconnect.tsx"],"sourcesContent":["import {useRouter} from 'next/navigation'\nimport {useEffect} from 'react'\n\nexport default function RefreshOnReconnect(): null {\n const router = useRouter()\n\n useEffect(() => {\n const controller = new AbortController()\n const {signal} = controller\n window.addEventListener('online', () => router.refresh(), {passive: true, signal})\n return () => controller.abort()\n }, [router])\n\n return null\n}\nRefreshOnReconnect.displayName = 'RefreshOnReconnect'\n"],"mappings":";;AAGA,SAAwB,qBAA2B;CACjD,MAAM,SAAS,WAAW;AAE1B,iBAAgB;EACd,MAAM,aAAa,IAAI,iBAAiB;EACxC,MAAM,EAAC,WAAU;AACjB,SAAO,iBAAiB,gBAAgB,OAAO,SAAS,EAAE;GAAC,SAAS;GAAM;GAAO,CAAC;AAClF,eAAa,WAAW,OAAO;IAC9B,CAAC,OAAO,CAAC;AAEZ,QAAO;;AAET,mBAAmB,cAAc"}
|
package/dist/defineLive.d.ts
CHANGED
|
@@ -32,37 +32,6 @@ type DefinedSanityFetchType = <const QueryString extends string>(options: {
|
|
|
32
32
|
/**
|
|
33
33
|
* @public
|
|
34
34
|
*/
|
|
35
|
-
type DefinedSanityLiveStreamType = <const QueryString extends string>(props: {
|
|
36
|
-
query: QueryString;
|
|
37
|
-
params?: QueryParams | Promise<QueryParams>;
|
|
38
|
-
/**
|
|
39
|
-
* Add custom `next.tags` to the underlying fetch request.
|
|
40
|
-
* @see https://nextjs.org/docs/app/api-reference/functions/fetch#optionsnexttags
|
|
41
|
-
* This can be used in conjunction with custom fallback revalidation strategies, as well as with custom Server Actions that mutate data and want to render with fresh data right away (faster than the Live Event latency).
|
|
42
|
-
* @defaultValue `['sanity']`
|
|
43
|
-
*/
|
|
44
|
-
tags?: string[];
|
|
45
|
-
perspective?: Exclude<ClientPerspective, "raw">;
|
|
46
|
-
stega?: boolean;
|
|
47
|
-
/**
|
|
48
|
-
* @deprecated use `requestTag` instead
|
|
49
|
-
*/
|
|
50
|
-
tag?: never;
|
|
51
|
-
/**
|
|
52
|
-
* This request tag is used to identify the request when viewing request logs from your Sanity Content Lake.
|
|
53
|
-
* @see https://www.sanity.io/docs/reference-api-request-tags
|
|
54
|
-
* @defaultValue 'next-loader.live-stream.fetch'
|
|
55
|
-
*/
|
|
56
|
-
requestTag?: string;
|
|
57
|
-
children: (result: {
|
|
58
|
-
data: ClientReturn<QueryString>;
|
|
59
|
-
sourceMap: ContentSourceMap | null;
|
|
60
|
-
tags: string[];
|
|
61
|
-
}) => Promise<Awaited<React.ReactNode>>;
|
|
62
|
-
}) => React.ReactNode;
|
|
63
|
-
/**
|
|
64
|
-
* @public
|
|
65
|
-
*/
|
|
66
35
|
interface DefinedSanityLiveProps {
|
|
67
36
|
/**
|
|
68
37
|
* Automatic refresh of RSC when the component <SanityLive /> is mounted.
|
|
@@ -172,10 +141,6 @@ declare function defineLive(config: DefineSanityLiveOptions): {
|
|
|
172
141
|
* @public
|
|
173
142
|
*/
|
|
174
143
|
SanityLive: React.ComponentType<DefinedSanityLiveProps>;
|
|
175
|
-
/**
|
|
176
|
-
* @alpha experimental, it may change or even be removed at any time
|
|
177
|
-
*/
|
|
178
|
-
SanityLiveStream: DefinedSanityLiveStreamType;
|
|
179
144
|
};
|
|
180
|
-
export { defineLive as
|
|
145
|
+
export { defineLive as i, DefinedSanityFetchType as n, DefinedSanityLiveProps as r, DefineSanityLiveOptions as t };
|
|
181
146
|
//# sourceMappingURL=defineLive.d.ts.map
|
package/dist/defineLive.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"defineLive.d.ts","names":[],"sources":["../src/live/defineLive.tsx"],"mappings":";;AAoBA;;KAAY,sBAAA,sCAA4D,OAAA;EACtE,KAAA,EAAO,WAAA;EACP,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AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"isCorsOriginError.d.ts","names":[],"sources":["../src/isCorsOriginError.ts"],"mappings":";;iBAGgB,iBAAA,CAAkB,KAAA,YAAiB,KAAA,IAAS,eAAA"}
|
|
1
|
+
{"version":3,"file":"isCorsOriginError.d.ts","names":[],"sources":["../src/live/shared/isCorsOriginError.ts"],"mappings":";;iBAGgB,iBAAA,CAAkB,KAAA,YAAiB,KAAA,IAAS,eAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"isCorsOriginError.js","names":[],"sources":["../src/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\nexport type {CorsOriginError}\n"],"mappings":";AAGA,SAAgB,kBAAkB,OAA0C;AAC1E,QAAO,iBAAiB,SAAS,MAAM,SAAS"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/live/client-components/SanityLive.tsx"],"mappings":";;AA0BA;;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;;;;iBAkCc,UAAA,CAAW,KAAA,EAAO,eAAA,GAAkB,KAAA,CAAM,GAAA,CAAI,OAAA"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { d as setEnvironment, f as setPerspective } from "
|
|
3
|
-
import { t as isCorsOriginError } from "
|
|
2
|
+
import { d as setEnvironment, f as setPerspective } from "../../context.js";
|
|
3
|
+
import { t as isCorsOriginError } from "../../isCorsOriginError.js";
|
|
4
4
|
import { useRouter } from "next/navigation";
|
|
5
5
|
import { useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
|
|
6
6
|
import { isMaybePresentation, isMaybePreviewWindow } from "@sanity/presentation-comlink";
|
|
@@ -8,10 +8,10 @@ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
|
8
8
|
import { createClient } from "@sanity/client";
|
|
9
9
|
import { revalidateSyncTags } from "next-sanity/live/server-actions";
|
|
10
10
|
import dynamic from "next/dynamic";
|
|
11
|
-
const PresentationComlink = dynamic(() => import("
|
|
12
|
-
const RefreshOnMount = dynamic(() => import("
|
|
13
|
-
const RefreshOnFocus = dynamic(() => import("
|
|
14
|
-
const RefreshOnReconnect = dynamic(() => import("
|
|
11
|
+
const PresentationComlink = dynamic(() => import("../../PresentationComlink.js"), { ssr: false });
|
|
12
|
+
const RefreshOnMount = dynamic(() => import("../../RefreshOnMount.js"), { ssr: false });
|
|
13
|
+
const RefreshOnFocus = dynamic(() => import("../../RefreshOnFocus.js"), { ssr: false });
|
|
14
|
+
const RefreshOnReconnect = dynamic(() => import("../../RefreshOnReconnect.js"), { ssr: false });
|
|
15
15
|
function handleError(error) {
|
|
16
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
17
|
else console.error(error);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.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} from 'react'\n\nimport {isCorsOriginError} from '#live/isCorsOriginError'\n\nimport {setEnvironment, setPerspective} from '../hooks/context'\n\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'), {ssr: false})\nconst RefreshOnMount = dynamic(() => import('./RefreshOnMount'), {ssr: false})\nconst RefreshOnFocus = dynamic(() => import('./RefreshOnFocus'), {ssr: false})\nconst RefreshOnReconnect = dynamic(() => import('./RefreshOnReconnect'), {ssr: false})\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\n/**\n * @public\n */\nexport function 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 [longPollingInterval, setLongPollingInterval] = 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 setLongPollingInterval(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 router.refresh()\n } else {\n void revalidateSyncTags(event.tags).then((result) => {\n if (result === 'refresh') router.refresh()\n })\n }\n } else if (event.type === 'restart' || event.type === 'reconnect') {\n router.refresh()\n } else if (event.type === 'goaway') {\n onGoAway(event, intervalOnGoAway)\n setLongPollingInterval(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 /**\n * 6. Handle switching to long polling when needed\n */\n useEffect(() => {\n if (!longPollingInterval) return\n const interval = setInterval(() => router.refresh(), longPollingInterval)\n return () => clearInterval(interval)\n }, [longPollingInterval, router])\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 {!draftModeEnabled && refreshOnFocus && <RefreshOnFocus />}\n {!draftModeEnabled && refreshOnReconnect && <RefreshOnReconnect />}\n </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AAa,QAAQ;AACrB,mBAAe,sBAAsB,GAAG,wBAAwB,sBAAsB;AACtF,mBAAe,KAAK;AACpB,eAAW,OAAO;;KAGtB,EAAC,QAAQ,WAAW,QAAO,CAC5B;AACD,eAAa;AACX,gBAAa,QAAQ;AACrB,cAAW,OAAO;;IAEnB,EAAE,CAAC;;;;;CAMN,MAAM,0BAA0B,OAAkD,KAAA,EAAU;AAC5F,iBAAgB;AACd,MAAI,CAAC,iBAAkB;AACvB,eAAa,wBAAwB,QAAQ;AAC7C,eAAa;AACX,2BAAwB,UAAU,iBAAiB;AACjD,YAAQ,KAAK,iEAAiE;KAC9E;;IAEH,CAAC,iBAAiB,CAAC;;;;AAKtB,iBAAgB;AACd,MAAI,CAAC,oBAAqB;EAC1B,MAAM,WAAW,kBAAkB,OAAO,SAAS,EAAE,oBAAoB;AACzE,eAAa,cAAc,SAAS;IACnC,CAAC,qBAAqB,OAAO,CAAC;AAEjC,QACE,qBAAA,UAAA,EAAA,UAAA;EACG,oBAAoB,eACnB,oBAAC,qBAAD;GACa;GACF;GAES;GACI;GACtB,CAAA;EAEH,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAD,EAAkB,CAAA;EACzD,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAD,EAAkB,CAAA;EACzD,CAAC,oBAAoB,sBAAsB,oBAAC,oBAAD,EAAsB,CAAA;EACjE,EAAA,CAAA"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
|
|
2
|
+
import { n as DefinedSanityFetchType, r as DefinedSanityLiveProps, t as DefineSanityLiveOptions } from "../../../defineLive.js";
|
|
3
|
+
/**
|
|
4
|
+
* @public
|
|
5
|
+
*/
|
|
6
|
+
declare function defineLive(_config: DefineSanityLiveOptions): {
|
|
7
|
+
sanityFetch: DefinedSanityFetchType;
|
|
8
|
+
SanityLive: React.ComponentType<DefinedSanityLiveProps>;
|
|
9
|
+
};
|
|
10
|
+
export { type DefineSanityLiveOptions, type DefinedSanityFetchType, type DefinedSanityLiveProps, defineLive, isCorsOriginError };
|
|
11
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +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,4 +1,4 @@
|
|
|
1
|
-
import { t as isCorsOriginError } from "
|
|
1
|
+
import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
|
|
2
2
|
/**
|
|
3
3
|
* @public
|
|
4
4
|
*/
|
|
@@ -7,4 +7,4 @@ function defineLive(_config) {
|
|
|
7
7
|
}
|
|
8
8
|
export { defineLive, isCorsOriginError };
|
|
9
9
|
|
|
10
|
-
//# sourceMappingURL=
|
|
10
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +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"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
|
|
2
|
+
import { i as defineLive, n as DefinedSanityFetchType, r as DefinedSanityLiveProps, t as DefineSanityLiveOptions } from "../../../defineLive.js";
|
|
3
|
+
export { type DefineSanityLiveOptions, type DefinedSanityFetchType, type DefinedSanityLiveProps, defineLive, isCorsOriginError };
|
|
@@ -1,20 +1,13 @@
|
|
|
1
|
-
import { t as isCorsOriginError } from "
|
|
2
|
-
import { t as sanitizePerspective } from "
|
|
1
|
+
import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
|
|
2
|
+
import { t as sanitizePerspective } from "../../../sanitizePerspective.js";
|
|
3
3
|
import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
|
|
4
4
|
import { cookies, draftMode } from "next/headers";
|
|
5
5
|
import { jsx } from "react/jsx-runtime";
|
|
6
6
|
import "@sanity/client";
|
|
7
|
-
import SanityLiveClientComponent from "next-sanity/live/client-components
|
|
8
|
-
import SanityLiveStreamClientComponent from "next-sanity/live/client-components/live-stream";
|
|
7
|
+
import SanityLiveClientComponent from "next-sanity/live/client-components";
|
|
9
8
|
import { PHASE_PRODUCTION_BUILD } from "next/constants";
|
|
10
9
|
import { preconnect, prefetchDNS } from "react-dom";
|
|
11
10
|
/**
|
|
12
|
-
* @internal
|
|
13
|
-
*/
|
|
14
|
-
async function resolveCookiePerspective() {
|
|
15
|
-
return (await draftMode()).isEnabled ? (await cookies()).has(perspectiveCookieName) ? sanitizePerspective((await cookies()).get(perspectiveCookieName)?.value, "drafts") : "drafts" : "published";
|
|
16
|
-
}
|
|
17
|
-
/**
|
|
18
11
|
* @public
|
|
19
12
|
*/
|
|
20
13
|
function defineLive(config) {
|
|
@@ -28,48 +21,47 @@ function defineLive(config) {
|
|
|
28
21
|
});
|
|
29
22
|
const { token: originalToken } = client.config();
|
|
30
23
|
const studioUrlDefined = typeof client.config().stega.studioUrl !== "undefined";
|
|
31
|
-
const sanityFetch = async function sanityFetch({ query, params = {}, stega: _stega, tags = [], perspective: _perspective, tag, requestTag = tag ?? "next-loader.fetch" }) {
|
|
32
|
-
const stega = _stega ?? (stegaEnabled && studioUrlDefined && (await draftMode()).isEnabled);
|
|
33
|
-
const perspective = _perspective ?? await resolveCookiePerspective();
|
|
34
|
-
const useCdn = perspective === "published";
|
|
35
|
-
const revalidate = fetchOptions?.revalidate !== void 0 ? fetchOptions.revalidate : process.env.NODE_ENV === "production" ? false : void 0;
|
|
36
|
-
const isBuildPhase = process.env["NEXT_PHASE"] === PHASE_PRODUCTION_BUILD;
|
|
37
|
-
const cacheMode = useCdn && !isBuildPhase ? "noStale" : void 0;
|
|
38
|
-
const { syncTags } = await client.fetch(query, await params, {
|
|
39
|
-
filterResponse: false,
|
|
40
|
-
perspective,
|
|
41
|
-
stega: false,
|
|
42
|
-
returnQuery: false,
|
|
43
|
-
next: {
|
|
44
|
-
revalidate,
|
|
45
|
-
tags: [...tags, "sanity:fetch-sync-tags"]
|
|
46
|
-
},
|
|
47
|
-
useCdn,
|
|
48
|
-
cacheMode,
|
|
49
|
-
tag: [requestTag, "fetch-sync-tags"].filter(Boolean).join(".")
|
|
50
|
-
});
|
|
51
|
-
const cacheTags = [...tags, ...syncTags?.map((tag) => `sanity:${tag}`) || []];
|
|
52
|
-
const { result, resultSourceMap } = await client.fetch(query, await params, {
|
|
53
|
-
filterResponse: false,
|
|
54
|
-
perspective,
|
|
55
|
-
stega,
|
|
56
|
-
token: perspective !== "published" && serverToken ? serverToken : originalToken,
|
|
57
|
-
next: {
|
|
58
|
-
revalidate,
|
|
59
|
-
tags: cacheTags
|
|
60
|
-
},
|
|
61
|
-
useCdn,
|
|
62
|
-
cacheMode,
|
|
63
|
-
tag: requestTag
|
|
64
|
-
});
|
|
65
|
-
return {
|
|
66
|
-
data: result,
|
|
67
|
-
sourceMap: resultSourceMap || null,
|
|
68
|
-
tags: cacheTags
|
|
69
|
-
};
|
|
70
|
-
};
|
|
71
24
|
return {
|
|
72
|
-
sanityFetch,
|
|
25
|
+
sanityFetch: async function sanityFetch({ query, params = {}, stega: _stega, tags = [], perspective: _perspective, tag, requestTag = tag ?? "next-loader.fetch" }) {
|
|
26
|
+
const stega = _stega ?? (stegaEnabled && studioUrlDefined && (await draftMode()).isEnabled);
|
|
27
|
+
const perspective = _perspective ?? await resolveCookiePerspective();
|
|
28
|
+
const useCdn = perspective === "published";
|
|
29
|
+
const revalidate = fetchOptions?.revalidate !== void 0 ? fetchOptions.revalidate : process.env.NODE_ENV === "production" ? false : void 0;
|
|
30
|
+
const isBuildPhase = process.env["NEXT_PHASE"] === PHASE_PRODUCTION_BUILD;
|
|
31
|
+
const cacheMode = useCdn && !isBuildPhase ? "noStale" : void 0;
|
|
32
|
+
const { syncTags } = await client.fetch(query, await params, {
|
|
33
|
+
filterResponse: false,
|
|
34
|
+
perspective,
|
|
35
|
+
stega: false,
|
|
36
|
+
returnQuery: false,
|
|
37
|
+
next: {
|
|
38
|
+
revalidate,
|
|
39
|
+
tags: [...tags, "sanity:fetch-sync-tags"]
|
|
40
|
+
},
|
|
41
|
+
useCdn,
|
|
42
|
+
cacheMode,
|
|
43
|
+
tag: [requestTag, "fetch-sync-tags"].filter(Boolean).join(".")
|
|
44
|
+
});
|
|
45
|
+
const cacheTags = [...tags, ...syncTags?.map((tag) => `sanity:${tag}`) || []];
|
|
46
|
+
const { result, resultSourceMap } = await client.fetch(query, await params, {
|
|
47
|
+
filterResponse: false,
|
|
48
|
+
perspective,
|
|
49
|
+
stega,
|
|
50
|
+
token: perspective !== "published" && serverToken ? serverToken : originalToken,
|
|
51
|
+
next: {
|
|
52
|
+
revalidate,
|
|
53
|
+
tags: cacheTags
|
|
54
|
+
},
|
|
55
|
+
useCdn,
|
|
56
|
+
cacheMode,
|
|
57
|
+
tag: requestTag
|
|
58
|
+
});
|
|
59
|
+
return {
|
|
60
|
+
data: result,
|
|
61
|
+
sourceMap: resultSourceMap || null,
|
|
62
|
+
tags: cacheTags
|
|
63
|
+
};
|
|
64
|
+
},
|
|
73
65
|
SanityLive: async function SanityLive(props) {
|
|
74
66
|
const { refreshOnMount, refreshOnFocus, refreshOnReconnect, tag, requestTag = tag, onError, onGoAway, intervalOnGoAway, revalidateSyncTags, waitFor } = props;
|
|
75
67
|
const { projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix } = client.config();
|
|
@@ -97,45 +89,12 @@ function defineLive(config) {
|
|
|
97
89
|
revalidateSyncTags,
|
|
98
90
|
waitFor
|
|
99
91
|
});
|
|
100
|
-
},
|
|
101
|
-
SanityLiveStream: async function SanityLiveStream(props) {
|
|
102
|
-
const { query, params, perspective: _perspective, stega: _stega, tags, children, tag, requestTag = tag ?? "next-loader.live-stream.fetch" } = props;
|
|
103
|
-
const { data, sourceMap, tags: cacheTags } = await sanityFetch({
|
|
104
|
-
query,
|
|
105
|
-
params,
|
|
106
|
-
tags,
|
|
107
|
-
perspective: _perspective,
|
|
108
|
-
stega: _stega,
|
|
109
|
-
requestTag
|
|
110
|
-
});
|
|
111
|
-
const { isEnabled: isDraftModeEnabled } = await draftMode();
|
|
112
|
-
if (isDraftModeEnabled) {
|
|
113
|
-
const stega = _stega ?? (stegaEnabled && studioUrlDefined && (await draftMode()).isEnabled);
|
|
114
|
-
const perspective = _perspective ?? await resolveCookiePerspective();
|
|
115
|
-
const { projectId, dataset } = client.config();
|
|
116
|
-
return /* @__PURE__ */ jsx(SanityLiveStreamClientComponent, {
|
|
117
|
-
projectId,
|
|
118
|
-
dataset,
|
|
119
|
-
query,
|
|
120
|
-
params: await params,
|
|
121
|
-
perspective,
|
|
122
|
-
stega,
|
|
123
|
-
initial: children({
|
|
124
|
-
data,
|
|
125
|
-
sourceMap,
|
|
126
|
-
tags: cacheTags
|
|
127
|
-
}),
|
|
128
|
-
children
|
|
129
|
-
});
|
|
130
|
-
}
|
|
131
|
-
return children({
|
|
132
|
-
data,
|
|
133
|
-
sourceMap,
|
|
134
|
-
tags: cacheTags
|
|
135
|
-
});
|
|
136
92
|
}
|
|
137
93
|
};
|
|
138
94
|
}
|
|
95
|
+
async function resolveCookiePerspective() {
|
|
96
|
+
return (await draftMode()).isEnabled ? (await cookies()).has(perspectiveCookieName) ? sanitizePerspective((await cookies()).get(perspectiveCookieName)?.value, "drafts") : "drafts" : "published";
|
|
97
|
+
}
|
|
139
98
|
export { defineLive, isCorsOriginError };
|
|
140
99
|
|
|
141
|
-
//# sourceMappingURL=
|
|
100
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/live/conditions/react-server/defineLive.tsx"],"sourcesContent":["import {\n type ClientPerspective,\n type ClientReturn,\n type ContentSourceMap,\n type LiveEventGoAway,\n type QueryParams,\n type SanityClient,\n type SyncTag,\n} from '@sanity/client'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport SanityLiveClientComponent from 'next-sanity/live/client-components'\nimport {PHASE_PRODUCTION_BUILD} from 'next/constants'\nimport {draftMode, cookies} from 'next/headers'\nimport {prefetchDNS, preconnect} from 'react-dom'\n\nimport {sanitizePerspective} from '#live/sanitizePerspective'\n\n/**\n * @public\n */\nexport type DefinedSanityFetchType = <const QueryString extends string>(options: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n /**\n * Add custom `next.tags` to the underlying fetch request.\n * @see https://nextjs.org/docs/app/api-reference/functions/fetch#optionsnexttags\n * This can be used in conjunction with custom fallback revalidation strategies, as well as with custom Server Actions that mutate data and want to render with fresh data right away (faster than the Live Event latency).\n * @defaultValue `['sanity']`\n */\n tags?: string[]\n perspective?: Exclude<ClientPerspective, 'raw'>\n stega?: boolean\n /**\n * @deprecated use `requestTag` instead\n */\n tag?: never\n /**\n * This request tag is used to identify the request when viewing request logs from your Sanity Content Lake.\n * @see https://www.sanity.io/docs/reference-api-request-tags\n * @defaultValue 'next-loader.fetch'\n */\n requestTag?: string\n}) => Promise<{\n data: ClientReturn<QueryString>\n sourceMap: ContentSourceMap | null\n tags: string[]\n}>\n\n/**\n * @public\n */\nexport interface DefinedSanityLiveProps {\n /**\n * Automatic refresh of RSC when the component <SanityLive /> is mounted.\n * Note that this is different from revalidation, which is based on tags and causes `sanityFetch` calls to be re-fetched.\n * @defaultValue `true`\n */\n refreshOnMount?: boolean\n /**\n * Automatically refresh when window gets focused\n * Note that this is different from revalidation, which is based on tags and causes `sanityFetch` calls to be re-fetched.\n * @defaultValue `false` if draftMode().isEnabled, otherwise `true` if not inside an iframe\n */\n refreshOnFocus?: boolean\n /**\n * Automatically refresh when the browser regains a network connection (via navigator.onLine)\n * Note that this is different from revalidation, which is based on tags and causes `sanityFetch` calls to be re-fetched.\n * @defaultValue `true`\n */\n refreshOnReconnect?: boolean\n /**\n * Automatically refresh on an interval when the Live Event API emits a `goaway` event, which indicates that the connection is rejected or closed.\n * This typically happens if the connection limit is reached, or if the connection is idle for too long.\n * To disable this long polling fallback behavior set `intervalOnGoAway` to `false` or `0`.\n * You can also use `onGoAway` to handle the `goaway` event in your own way, and read the reason why the event was emitted.\n * @defaultValue `30_000` 30 seconds interval\n */\n intervalOnGoAway?: number | false\n\n /**\n * Delays events until after a Sanity Function has processed them and called the callback endpoint.\n * When omitted, events are delivered immediately.\n */\n waitFor?: 'function'\n\n /**\n * @deprecated use `requestTag` instead\n */\n tag?: never\n\n /**\n * This request tag is used to identify the request when viewing request logs from your Sanity Content Lake.\n * @see https://www.sanity.io/docs/reference-api-request-tags\n * @defaultValue 'next-loader.live'\n */\n requestTag?: string\n\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\n /**\n * Handle the `goaway` event if the connection is rejected/closed.\n * `event.reason` will be a string of why the event was emitted, for example `'connection limit reached'`.\n * When this happens the `<SanityLive />` will fallback to long polling with a default interval of 30 seconds, providing your own `onGoAway` handler does not change this behavior.\n * If you want to disable long polling set `intervalOnGoAway` to `false` or `0`.\n */\n onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void\n\n /**\n * Override how cache tags are invalidated, you need to pass a server action here.\n * You can also pass a `use client` function here, and have `router.refresh()` be called if the promise resolves to `'refresh'`.\n */\n revalidateSyncTags?: (tags: SyncTag[]) => Promise<void | 'refresh'>\n}\n\n/**\n * @public\n */\nexport interface DefineSanityLiveOptions {\n /**\n * Required for `sanityFetch` and `SanityLive` to work\n */\n client: SanityClient\n /**\n * Optional. If provided then the token needs to have permissions to query documents with `drafts.` prefixes in order for `perspective: 'drafts'` to work.\n * This token is not shared with the browser.\n */\n serverToken?: string | false\n /**\n * Optional. This token is shared with the browser, and should only have access to query published documents.\n * It is used to setup a `Live Draft Content` EventSource connection, and enables live previewing drafts stand-alone, outside of Presentation Tool.\n */\n browserToken?: string | false\n /**\n * Fetch options used by `sanityFetch`\n * @deprecated this option is removed in the next major version, use `export const revalidate` on the `page.tsx` or `layout.tsx` instead\n */\n fetchOptions?: {\n /**\n * Optional, enables time based revalidation in addition to the EventSource connection.\n * @defaultValue `false`\n */\n revalidate?: number | false\n }\n /**\n * Optional. Include stega encoding when draft mode is enabled.\n * @defaultValue `true`\n */\n stega?: boolean\n}\n\n/**\n * @public\n */\nexport function defineLive(config: DefineSanityLiveOptions): {\n /**\n * Use this function to fetch data from Sanity in your React Server Components.\n * @public\n */\n sanityFetch: DefinedSanityFetchType\n /**\n * Render this in your root layout.tsx to make your page revalidate on new content live, automatically.\n * @public\n */\n SanityLive: React.ComponentType<DefinedSanityLiveProps>\n} {\n const {\n client: _client,\n serverToken,\n browserToken,\n fetchOptions,\n stega: stegaEnabled = true,\n } = config\n\n if (!_client) {\n throw new Error('`client` is required for `defineLive` to function')\n }\n\n if (process.env.NODE_ENV !== 'production' && !serverToken && serverToken !== false) {\n console.warn(\n 'No `serverToken` provided to `defineLive`. This means that only published content will be fetched and respond to live events. You can silence this warning by setting `serverToken: false`.',\n )\n }\n\n if (process.env.NODE_ENV !== 'production' && !browserToken && browserToken !== false) {\n console.warn(\n 'No `browserToken` provided to `defineLive`. This means that live previewing drafts will only work when using the Presentation Tool in your Sanity Studio. To support live previewing drafts stand-alone, provide a `browserToken`. It is shared with the browser so it should only have Viewer rights or lower. You can silence this warning by setting `browserToken: false`.',\n )\n }\n\n const client = _client.withConfig({allowReconfigure: false, useCdn: false})\n const {token: originalToken} = client.config()\n const studioUrlDefined = typeof client.config().stega.studioUrl !== 'undefined'\n\n const sanityFetch: DefinedSanityFetchType = async function sanityFetch<\n const QueryString extends string,\n >({\n query,\n params = {},\n stega: _stega,\n tags = [],\n perspective: _perspective,\n tag,\n requestTag = tag ?? 'next-loader.fetch',\n }: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n stega?: boolean\n tags?: string[]\n perspective?: Exclude<ClientPerspective, 'raw'>\n tag?: string\n requestTag?: string\n }) {\n const stega = _stega ?? (stegaEnabled && studioUrlDefined && (await draftMode()).isEnabled)\n const perspective = _perspective ?? (await resolveCookiePerspective())\n const useCdn = perspective === 'published'\n const revalidate =\n fetchOptions?.revalidate !== undefined\n ? fetchOptions.revalidate\n : process.env.NODE_ENV === 'production'\n ? false\n : undefined\n const isBuildPhase = process.env['NEXT_PHASE'] === PHASE_PRODUCTION_BUILD\n const cacheMode = useCdn && !isBuildPhase ? 'noStale' : undefined\n\n const {syncTags} = await client.fetch(query, await params, {\n filterResponse: false,\n perspective: perspective as ClientPerspective,\n stega: false,\n returnQuery: false,\n next: {revalidate, tags: [...tags, 'sanity:fetch-sync-tags']},\n useCdn,\n cacheMode,\n tag: [requestTag, 'fetch-sync-tags'].filter(Boolean).join('.'),\n })\n\n const cacheTags = [...tags, ...(syncTags?.map((tag) => `sanity:${tag}`) || [])]\n\n const {result, resultSourceMap} = await client.fetch(query, await params, {\n filterResponse: false,\n perspective: perspective as ClientPerspective,\n stega,\n token: perspective !== 'published' && serverToken ? serverToken : originalToken,\n next: {revalidate, tags: cacheTags},\n useCdn,\n cacheMode,\n tag: requestTag,\n })\n return {data: result, sourceMap: resultSourceMap || null, tags: cacheTags}\n }\n\n const SanityLive: React.ComponentType<DefinedSanityLiveProps> = async function SanityLive(props) {\n const {\n refreshOnMount,\n refreshOnFocus,\n refreshOnReconnect,\n tag,\n requestTag = tag,\n onError,\n onGoAway,\n intervalOnGoAway,\n revalidateSyncTags,\n waitFor,\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n const {isEnabled: isDraftModeEnabled} = await draftMode()\n\n // Preconnect to the Live Event API origin, or at least prefetch the DNS if preconenct is not supported\n const {origin} = new URL(client.getUrl('', false))\n preconnect(origin)\n prefetchDNS(origin)\n\n return (\n <SanityLiveClientComponent\n projectId={projectId}\n dataset={dataset}\n apiHost={apiHost}\n apiVersion={apiVersion}\n useProjectHostname={useProjectHostname}\n requestTagPrefix={requestTagPrefix}\n requestTag={requestTag}\n token={typeof browserToken === 'string' && isDraftModeEnabled ? browserToken : undefined}\n draftModeEnabled={isDraftModeEnabled}\n draftModePerspective={await resolveCookiePerspective()}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n revalidateSyncTags={revalidateSyncTags}\n waitFor={waitFor}\n />\n )\n }\n\n return {\n sanityFetch,\n SanityLive,\n }\n}\n\nasync function resolveCookiePerspective(): Promise<Exclude<ClientPerspective, 'raw'>> {\n return (await draftMode()).isEnabled\n ? (await cookies()).has(perspectiveCookieName)\n ? sanitizePerspective((await cookies()).get(perspectiveCookieName)?.value, 'drafts')\n : 'drafts'\n : 'published'\n}\n"],"mappings":";;;;;;;;;;;;AA6JA,SAAgB,WAAW,QAWzB;CACA,MAAM,EACJ,QAAQ,SACR,aACA,cACA,cACA,OAAO,eAAe,SACpB;AAEJ,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,oDAAoD;AAGtE,KAAI,QAAQ,IAAI,aAAa,gBAAgB,CAAC,eAAe,gBAAgB,MAC3E,SAAQ,KACN,8LACD;AAGH,KAAI,QAAQ,IAAI,aAAa,gBAAgB,CA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AQ,WAAW,mBAAmB;IAAM,MAAM;IAAU;;EAmD1E,YAAA,eAhD6E,WAAW,OAAO;GAC/F,MAAM,EACJ,gBACA,gBACA,oBACA,KACA,aAAa,KACb,SACA,UACA,kBACA,oBACA,YACE;GACJ,MAAM,EAAC,WAAW,SAAS,SAAS,YAAY,oBAAoB,qBAClE,OAAO,QAAQ;GACjB,MAAM,EAAC,WAAW,uBAAsB,MAAM,WAAW;GAGzD,MAAM,EAAC,WAAU,IAAI,IAAI,OAAO,OAAO,IAAI,MAAM,CAAC;AAClD,cAAW,OAAO;AAClB,eAAY,OAAO;AAEnB,UACE,oBAAC,2BAAD;IACa;IACF;IACA;IACG;IACQ;IACF;IACN;IACZ,OAAO,OAAO,iBAAiB,YAAY,qBAAqB,eAAe,KAAA;IAC/E,kBAAkB;IAClB,sBAAsB,MAAM,0BAA0B;IACtC;IACA;IACI;IACX;IACC;IACQ;IACE;IACX;IACT,CAAA;;EAOL;;AAGH,eAAe,2BAAuE;AACpF,SAAQ,MAAM,WAAW,EAAE,aACtB,MAAM,SAAS,EAAE,IAAI,sBAAsB,GAC1C,qBAAqB,MAAM,SAAS,EAAE,IAAI,sBAAsB,EAAE,OAAO,SAAS,GAClF,WACF"}
|
|
@@ -2,4 +2,4 @@ import { ClientPerspective, SyncTag } from "@sanity/client";
|
|
|
2
2
|
declare function revalidateSyncTags(tags: SyncTag[]): Promise<void>;
|
|
3
3
|
declare function setPerspectiveCookie(perspective: ClientPerspective): Promise<void>;
|
|
4
4
|
export { revalidateSyncTags, setPerspectiveCookie };
|
|
5
|
-
//# sourceMappingURL=index.d.ts.map
|
|
5
|
+
//# sourceMappingURL=index.default.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.default.d.ts","names":[],"sources":["../../../src/live/server-actions/index.default.ts"],"mappings":";iBASsB,kBAAA,CAAmB,IAAA,EAAM,OAAA,KAAY,OAAA;AAAA,iBAWrC,oBAAA,CAAqB,WAAA,EAAa,iBAAA,GAAoB,OAAA"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use server";
|
|
2
|
-
import { t as sanitizePerspective } from "../../
|
|
2
|
+
import { t as sanitizePerspective } from "../../sanitizePerspective.js";
|
|
3
3
|
import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
|
|
4
4
|
import { cookies, draftMode } from "next/headers";
|
|
5
5
|
import { revalidateTag } from "next/cache";
|
|
@@ -24,4 +24,4 @@ async function setPerspectiveCookie(perspective) {
|
|
|
24
24
|
}
|
|
25
25
|
export { revalidateSyncTags, setPerspectiveCookie };
|
|
26
26
|
|
|
27
|
-
//# sourceMappingURL=index.js.map
|
|
27
|
+
//# sourceMappingURL=index.default.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.default.js","names":[],"sources":["../../../src/live/server-actions/index.default.ts"],"sourcesContent":["'use server'\n\nimport type {ClientPerspective, SyncTag} from '@sanity/client'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {revalidateTag} from 'next/cache'\nimport {cookies, draftMode} from 'next/headers'\n\nimport {sanitizePerspective} from '#live/sanitizePerspective'\n\nexport async function revalidateSyncTags(tags: SyncTag[]): Promise<void> {\n revalidateTag('sanity:fetch-sync-tags', 'max')\n\n for (const _tag of tags) {\n const tag = `sanity:${_tag}`\n revalidateTag(tag, {expire: 0})\n // oxlint-disable-next-line no-console\n console.log(`<SanityLive /> revalidated tag: ${tag}`)\n }\n}\n\nexport async function setPerspectiveCookie(perspective: ClientPerspective): Promise<void> {\n if (!(await draftMode()).isEnabled) {\n // throw new Error('Draft mode is not enabled, setting perspective cookie is not allowed')\n return\n }\n const sanitizedPerspective = sanitizePerspective(perspective, 'drafts')\n if (perspective !== sanitizedPerspective) {\n throw new Error(`Invalid perspective`, {cause: perspective})\n }\n\n ;(await cookies()).set(\n perspectiveCookieName,\n Array.isArray(sanitizedPerspective) ? sanitizedPerspective.join(',') : sanitizedPerspective,\n {\n httpOnly: true,\n path: '/',\n secure: true,\n sameSite: 'none',\n },\n )\n}\n"],"mappings":";;;;;AASA,eAAsB,mBAAmB,MAAgC;AACvE,eAAc,0BAA0B,MAAM;AAE9C,MAAK,MAAM,QAAQ,MAAM;EACvB,MAAM,MAAM,UAAU;AACtB,gBAAc,KAAK,EAAC,QAAQ,GAAE,CAAC;AAE/B,UAAQ,IAAI,mCAAmC,MAAM;;;AAIzD,eAAsB,qBAAqB,aAA+C;AACxF,KAAI,EAAE,MAAM,WAAW,EAAE,UAEvB;CAEF,MAAM,uBAAuB,oBAAoB,aAAa,SAAS;AACvE,KAAI,gBAAgB,qBAClB,OAAM,IAAI,MAAM,uBAAuB,EAAC,OAAO,aAAY,CAAC;AAG7D,EAAC,MAAM,SAAS,EAAE,IACjB,uBACA,MAAM,QAAQ,qBAAqB,GAAG,qBAAqB,KAAK,IAAI,GAAG,sBACvE;EACE,UAAU;EACV,MAAM;EACN,QAAQ;EACR,UAAU;EACX,CACF"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { validateApiPerspective } from "@sanity/client";
|
|
2
|
-
/** @internal */
|
|
3
2
|
function sanitizePerspective(_perspective, fallback) {
|
|
4
3
|
const perspective = typeof _perspective === "string" && _perspective.includes(",") ? _perspective.split(",") : _perspective;
|
|
5
4
|
try {
|
|
@@ -12,4 +11,4 @@ function sanitizePerspective(_perspective, fallback) {
|
|
|
12
11
|
}
|
|
13
12
|
export { sanitizePerspective as t };
|
|
14
13
|
|
|
15
|
-
//# sourceMappingURL=
|
|
14
|
+
//# sourceMappingURL=sanitizePerspective.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sanitizePerspective.js","names":[],"sources":["../src/live/shared/sanitizePerspective.ts"],"sourcesContent":["import {validateApiPerspective, type ClientPerspective} from '@sanity/client'\n\nexport function sanitizePerspective(\n _perspective: unknown,\n fallback: 'drafts' | 'published',\n): Exclude<ClientPerspective, 'raw'> {\n const perspective =\n typeof _perspective === 'string' && _perspective.includes(',')\n ? _perspective.split(',')\n : _perspective\n try {\n validateApiPerspective(perspective)\n return perspective === 'raw' ? fallback : perspective\n } catch (err) {\n console.warn(`Invalid perspective:`, _perspective, perspective, err)\n return fallback\n }\n}\n"],"mappings":";AAEA,SAAgB,oBACd,cACA,UACmC;CACnC,MAAM,cACJ,OAAO,iBAAiB,YAAY,aAAa,SAAS,IAAI,GAC1D,aAAa,MAAM,IAAI,GACvB;AACN,KAAI;AACF,yBAAuB,YAAY;AACnC,SAAO,gBAAgB,QAAQ,WAAW;UACnC,KAAK;AACZ,UAAQ,KAAK,wBAAwB,cAAc,aAAa,IAAI;AACpE,SAAO"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "next-sanity",
|
|
3
|
-
"version": "12.3.
|
|
3
|
+
"version": "12.3.4",
|
|
4
4
|
"description": "Sanity.io toolkit for Next.js",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"live",
|
|
@@ -33,7 +33,8 @@
|
|
|
33
33
|
"next-js": "./src/_env/next-js.ts",
|
|
34
34
|
"react-server": "./src/_env/react-server.ts",
|
|
35
35
|
"default": "./src/_env/default.ts"
|
|
36
|
-
}
|
|
36
|
+
},
|
|
37
|
+
"#live/*": "./src/live/shared/*.ts"
|
|
37
38
|
},
|
|
38
39
|
"exports": {
|
|
39
40
|
".": "./dist/index.js",
|
|
@@ -41,12 +42,13 @@
|
|
|
41
42
|
"./hooks": "./dist/hooks/index.js",
|
|
42
43
|
"./image": "./dist/image/index.js",
|
|
43
44
|
"./live": {
|
|
44
|
-
"react-server": "./dist/live.js",
|
|
45
|
-
"default": "./dist/live.
|
|
45
|
+
"react-server": "./dist/live/conditions/react-server/index.js",
|
|
46
|
+
"default": "./dist/live/conditions/default/index.js"
|
|
47
|
+
},
|
|
48
|
+
"./live/client-components": "./dist/live/client-components/index.js",
|
|
49
|
+
"./live/server-actions": {
|
|
50
|
+
"default": "./dist/live/server-actions/index.default.js"
|
|
46
51
|
},
|
|
47
|
-
"./live/client-components/live": "./dist/live/client-components/live/index.js",
|
|
48
|
-
"./live/client-components/live-stream": "./dist/live/client-components/live-stream/index.js",
|
|
49
|
-
"./live/server-actions": "./dist/live/server-actions/index.js",
|
|
50
52
|
"./studio": "./dist/studio/index.js",
|
|
51
53
|
"./studio/client-component": "./dist/studio/client-component/index.js",
|
|
52
54
|
"./visual-editing": "./dist/visual-editing/index.js",
|
|
@@ -65,8 +67,7 @@
|
|
|
65
67
|
"@sanity/webhook": "^4.0.4",
|
|
66
68
|
"dequal": "^2.0.3",
|
|
67
69
|
"groq": "^5.23.0",
|
|
68
|
-
"history": "^5.3.0"
|
|
69
|
-
"server-only": "^0.0.1"
|
|
70
|
+
"history": "^5.3.0"
|
|
70
71
|
},
|
|
71
72
|
"devDependencies": {
|
|
72
73
|
"@sanity/tsconfig": "^2.1.0",
|
package/dist/SanityLiveStream.js
DELETED
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
import { r as comlinkListeners, t as comlink } from "./context.js";
|
|
2
|
-
import { use, useCallback, useEffect, useEffectEvent, useState, useSyncExternalStore } from "react";
|
|
3
|
-
import { stegaEncodeSourceMap } from "@sanity/client/stega";
|
|
4
|
-
import { dequal } from "dequal/lite";
|
|
5
|
-
import { Fragment, jsx } from "react/jsx-runtime";
|
|
6
|
-
import "@sanity/client";
|
|
7
|
-
const LISTEN_HEARTBEAT_INTERVAL = 1e4;
|
|
8
|
-
/**
|
|
9
|
-
* @public
|
|
10
|
-
*/
|
|
11
|
-
function SanityLiveStream(props) {
|
|
12
|
-
const { query, dataset, params = {}, perspective, projectId, stega } = props;
|
|
13
|
-
const comlink$1 = useSyncExternalStore(useCallback((listener) => {
|
|
14
|
-
comlinkListeners.add(listener);
|
|
15
|
-
return () => comlinkListeners.delete(listener);
|
|
16
|
-
}, []), () => comlink, () => null);
|
|
17
|
-
const [children, setChildren] = useState(void 0);
|
|
18
|
-
const handleQueryHeartbeat = useEffectEvent((comlink) => {
|
|
19
|
-
comlink.post("loader/query-listen", {
|
|
20
|
-
projectId,
|
|
21
|
-
dataset,
|
|
22
|
-
perspective,
|
|
23
|
-
query,
|
|
24
|
-
params,
|
|
25
|
-
heartbeat: LISTEN_HEARTBEAT_INTERVAL
|
|
26
|
-
});
|
|
27
|
-
});
|
|
28
|
-
const handleQueryChange = useEffectEvent((event) => {
|
|
29
|
-
if (dequal({
|
|
30
|
-
projectId,
|
|
31
|
-
dataset,
|
|
32
|
-
query,
|
|
33
|
-
params
|
|
34
|
-
}, {
|
|
35
|
-
projectId: event.projectId,
|
|
36
|
-
dataset: event.dataset,
|
|
37
|
-
query: event.query,
|
|
38
|
-
params: event.params
|
|
39
|
-
})) {
|
|
40
|
-
const { result, resultSourceMap, tags } = event;
|
|
41
|
-
const data = stega ? stegaEncodeSourceMap(result, resultSourceMap, {
|
|
42
|
-
enabled: true,
|
|
43
|
-
studioUrl: "/"
|
|
44
|
-
}) : result;
|
|
45
|
-
console.groupCollapsed("rendering with server action");
|
|
46
|
-
props.children({
|
|
47
|
-
data,
|
|
48
|
-
sourceMap: resultSourceMap,
|
|
49
|
-
tags: tags || []
|
|
50
|
-
}).then((children) => {
|
|
51
|
-
console.log("setChildren(children)");
|
|
52
|
-
setChildren(children);
|
|
53
|
-
}, (reason) => {
|
|
54
|
-
console.error("rendering with server action: render children error", reason);
|
|
55
|
-
}).finally(() => console.groupEnd());
|
|
56
|
-
}
|
|
57
|
-
});
|
|
58
|
-
useEffect(() => {
|
|
59
|
-
if (!comlink$1) return;
|
|
60
|
-
const unsubscribe = comlink$1.on("loader/query-change", handleQueryChange);
|
|
61
|
-
const interval = setInterval(() => handleQueryHeartbeat(comlink$1), LISTEN_HEARTBEAT_INTERVAL);
|
|
62
|
-
return () => {
|
|
63
|
-
clearInterval(interval);
|
|
64
|
-
unsubscribe();
|
|
65
|
-
};
|
|
66
|
-
}, [comlink$1]);
|
|
67
|
-
if (!comlink$1 || children === void 0) return use(props.initial);
|
|
68
|
-
return /* @__PURE__ */ jsx(Fragment, { children });
|
|
69
|
-
}
|
|
70
|
-
export { SanityLiveStream as default };
|
|
71
|
-
|
|
72
|
-
//# sourceMappingURL=SanityLiveStream.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"SanityLiveStream.js","names":["comlink","comlinkSnapshot"],"sources":["../src/live/client-components/live-stream/SanityLiveStream.tsx"],"sourcesContent":["// oxlint-disable no-unsafe-type-assertion\nimport {\n type ClientPerspective,\n type ContentSourceMap,\n type InitializedClientConfig,\n type QueryParams,\n} from '@sanity/client'\nimport {stegaEncodeSourceMap} from '@sanity/client/stega'\nimport type {LoaderControllerMsg} from '@sanity/presentation-comlink'\nimport {dequal} from 'dequal/lite'\nimport {use, useCallback, useEffect, useState, useSyncExternalStore, useEffectEvent} from 'react'\n\nimport {comlinkListeners, comlink as comlinkSnapshot} from '../../hooks/context'\n\n/**\n * @public\n */\nexport interface SanityLiveStreamProps extends Pick<\n InitializedClientConfig,\n 'projectId' | 'dataset'\n> {\n query: string\n params?: QueryParams\n perspective?: Exclude<ClientPerspective, 'raw'>\n stega?: boolean\n initial: Promise<React.ReactNode>\n children: (result: {\n data: unknown\n sourceMap: ContentSourceMap | null\n tags: string[]\n }) => Promise<React.ReactNode>\n}\n\nconst LISTEN_HEARTBEAT_INTERVAL = 10_000\n\n/**\n * @public\n */\nexport default function SanityLiveStream(props: SanityLiveStreamProps): React.JSX.Element | null {\n const {query, dataset, params = {}, perspective, projectId, stega} = props\n\n const subscribe = useCallback((listener: () => void) => {\n comlinkListeners.add(listener)\n return () => comlinkListeners.delete(listener)\n }, [])\n\n const comlink = useSyncExternalStore(\n subscribe,\n () => comlinkSnapshot,\n () => null,\n )\n const [children, setChildren] = useState<React.ReactNode | undefined>(undefined)\n\n const handleQueryHeartbeat = useEffectEvent((comlink: NonNullable<typeof comlinkSnapshot>) => {\n comlink.post('loader/query-listen', {\n projectId: projectId!,\n dataset: dataset!,\n perspective: perspective! as ClientPerspective,\n query,\n params: params,\n heartbeat: LISTEN_HEARTBEAT_INTERVAL,\n })\n })\n const handleQueryChange = useEffectEvent(\n (event: Extract<LoaderControllerMsg, {type: 'loader/query-change'}>['data']) => {\n if (\n dequal(\n {\n projectId,\n dataset,\n query,\n params,\n },\n {\n projectId: event.projectId,\n dataset: event.dataset,\n query: event.query,\n params: event.params,\n },\n )\n ) {\n const {result, resultSourceMap, tags} = event\n const data = stega\n ? stegaEncodeSourceMap(result, resultSourceMap, {enabled: true, studioUrl: '/'})\n : result\n // console.log('server function streaming is disabled', {\n // startTransition,\n // setPromise,\n // data,\n // resultSourceMap,\n // tags,\n // })\n // console.log('rendering with server action')\n // startTransition(() =>\n // setPromise(\n // props.children({\n // data,\n // sourceMap: resultSourceMap!,\n // tags: tags || [],\n // }) as Promise<React.JSX.Element>,\n // ),\n // )\n // oxlint-disable-next-line no-console\n console.groupCollapsed('rendering with server action')\n ;(\n props.children({\n data,\n sourceMap: resultSourceMap!,\n tags: tags || [],\n }) as Promise<React.JSX.Element>\n )\n .then(\n (children) => {\n // oxlint-disable-next-line no-console\n console.log('setChildren(children)')\n // startTransition(() => setChildren(children))\n setChildren(children)\n },\n (reason: unknown) => {\n console.error('rendering with server action: render children error', reason)\n },\n )\n // oxlint-disable-next-line no-console\n .finally(() => console.groupEnd())\n }\n },\n )\n useEffect(() => {\n if (!comlink) return\n\n const unsubscribe = comlink.on('loader/query-change', handleQueryChange)\n const interval = setInterval(() => handleQueryHeartbeat(comlink), LISTEN_HEARTBEAT_INTERVAL)\n return () => {\n clearInterval(interval)\n unsubscribe()\n }\n }, [comlink])\n\n if (!comlink || children === undefined) {\n return use(props.initial) as React.JSX.Element\n }\n\n return <>{children}</>\n}\n"],"mappings":";;;;;;AAiCA,MAAM,4BAA4B;;;;AAKlC,SAAwB,iBAAiB,OAAwD;CAC/F,MAAM,EAAC,OAAO,SAAS,SAAS,EAAE,EAAE,aAAa,WAAW,UAAS;CAOrE,MAAMA,YAAU,q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["../../../../src/live/client-components/live/SanityLive.tsx"],"mappings":";;AAyBA;;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;;;;iBAkCc,UAAA,CAAW,KAAA,EAAO,eAAA,GAAkB,KAAA,CAAM,GAAA,CAAI,OAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["defaultRevalidateSyncTags","revalidateSyncTags"],"sources":["../../../../src/live/client-components/live/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} from 'react'\n\nimport {isCorsOriginError} from '../../../isCorsOriginError'\nimport {setEnvironment, setPerspective} from '../../hooks/context'\n\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'), {ssr: false})\nconst RefreshOnMount = dynamic(() => import('./RefreshOnMount'), {ssr: false})\nconst RefreshOnFocus = dynamic(() => import('./RefreshOnFocus'), {ssr: false})\nconst RefreshOnReconnect = dynamic(() => import('./RefreshOnReconnect'), {ssr: false})\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\n/**\n * @public\n */\nexport function 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 [longPollingInterval, setLongPollingInterval] = 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 setLongPollingInterval(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 router.refresh()\n } else {\n void revalidateSyncTags(event.tags).then((result) => {\n if (result === 'refresh') router.refresh()\n })\n }\n } else if (event.type === 'restart' || event.type === 'reconnect') {\n router.refresh()\n } else if (event.type === 'goaway') {\n onGoAway(event, intervalOnGoAway)\n setLongPollingInterval(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 /**\n * 6. Handle switching to long polling when needed\n */\n useEffect(() => {\n if (!longPollingInterval) return\n const interval = setInterval(() => router.refresh(), longPollingInterval)\n return () => clearInterval(interval)\n }, [longPollingInterval, router])\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 {!draftModeEnabled && refreshOnFocus && <RefreshOnFocus />}\n {!draftModeEnabled && refreshOnReconnect && <RefreshOnReconnect />}\n </>\n )\n}\n"],"mappings":";;;;;;;;;;AAiBA,MAAM,sBAAsB,cAAc,OAAO,oCAA0B,EAAC,KAAK,OAAM,CAAC;AACxF,MAAM,iBAAiB,cAAc,OAAO,+BAAqB,EAAC,KAAK,OAAM,CAAC;AAC9E,MAAM,iBAAiB,cAAc,OAAO,+BAAqB,EAAC,KAAK,OAAM,CAAC;AAC9E,MAAM,qBAAqB,cAAc,OAAO,mCAAyB,EAAC,KAAK,OAAM,CAAC;AAwCtF,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;;;;;AAOL,SAAgB,WAAW,OAAkD;CAC3E,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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sB,CAAA;EACjE,EAAA,CAAA"}
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import { ClientPerspective, ContentSourceMap, InitializedClientConfig, QueryParams } from "@sanity/client";
|
|
2
|
-
/**
|
|
3
|
-
* @public
|
|
4
|
-
*/
|
|
5
|
-
interface SanityLiveStreamProps extends Pick<InitializedClientConfig, "projectId" | "dataset"> {
|
|
6
|
-
query: string;
|
|
7
|
-
params?: QueryParams;
|
|
8
|
-
perspective?: Exclude<ClientPerspective, "raw">;
|
|
9
|
-
stega?: boolean;
|
|
10
|
-
initial: Promise<React.ReactNode>;
|
|
11
|
-
children: (result: {
|
|
12
|
-
data: unknown;
|
|
13
|
-
sourceMap: ContentSourceMap | null;
|
|
14
|
-
tags: string[];
|
|
15
|
-
}) => Promise<React.ReactNode>;
|
|
16
|
-
}
|
|
17
|
-
declare function SanityLiveStreamLazyClientComponent(props: SanityLiveStreamProps): React.ReactNode;
|
|
18
|
-
export { type SanityLiveStreamProps, SanityLiveStreamLazyClientComponent as default };
|
|
19
|
-
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/live/client-components/live-stream/SanityLiveStream.tsx","../../../../src/live/client-components/live-stream/SanityLiveStreamLazy.tsx"],"mappings":";;AAiBA;;UAAiB,qBAAA,SAA8B,IAAA,CAC7C,uBAAA;EAGA,KAAA;EACA,MAAA,GAAS,WAAA;EACT,WAAA,GAAc,OAAA,CAAQ,iBAAA;EACtB,KAAA;EACA,OAAA,EAAS,OAAA,CAAQ,KAAA,CAAM,SAAA;EACvB,QAAA,GAAW,MAAA;IACT,IAAA;IACA,SAAA,EAAW,gBAAA;IACX,IAAA;EAAA,MACI,OAAA,CAAQ,KAAA,CAAM,SAAA;AAAA;AAAA,iBClBN,mCAAA,CAAoC,KAAA,EAAO,qBAAA,GAAwB,KAAA,CAAM,SAAA"}
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
"use client";
|
|
2
|
-
import { jsx } from "react/jsx-runtime";
|
|
3
|
-
import dynamic from "next/dynamic";
|
|
4
|
-
/**
|
|
5
|
-
* This file works around a new restriction in Next v15 where server components are not allowed
|
|
6
|
-
* to use dynamic(() => import('...), {ssr: false})
|
|
7
|
-
* only Client Components can set ssr: false.
|
|
8
|
-
*/
|
|
9
|
-
const SanityLiveStreamClientComponent = dynamic(() => import("../../../SanityLiveStream.js"), { ssr: false });
|
|
10
|
-
function SanityLiveStreamLazyClientComponent(props) {
|
|
11
|
-
return /* @__PURE__ */ jsx(SanityLiveStreamClientComponent, { ...props });
|
|
12
|
-
}
|
|
13
|
-
export { SanityLiveStreamLazyClientComponent as default };
|
|
14
|
-
|
|
15
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/live/client-components/live-stream/SanityLiveStreamLazy.tsx"],"sourcesContent":["/**\n * This file works around a new restriction in Next v15 where server components are not allowed\n * to use dynamic(() => import('...), {ssr: false})\n * only Client Components can set ssr: false.\n */\n\nimport dynamic from 'next/dynamic'\n\nimport type {SanityLiveStreamProps} from './SanityLiveStream'\n\nconst SanityLiveStreamClientComponent = dynamic(() => import('./SanityLiveStream'), {ssr: false})\n\nexport function SanityLiveStreamLazyClientComponent(props: SanityLiveStreamProps): React.ReactNode {\n return <SanityLiveStreamClientComponent {...props} />\n}\n"],"mappings":";;;;;;;;AAUA,MAAM,kCAAkC,cAAc,OAAO,iCAAuB,EAAC,KAAK,OAAM,CAAC;AAEjG,SAAgB,oCAAoC,OAA+C;AACjG,QAAO,oBAAC,iCAAD,EAAiC,GAAI,OAAS,CAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/live/server-actions/index.ts"],"mappings":";iBASsB,kBAAA,CAAmB,IAAA,EAAM,OAAA,KAAY,OAAA;AAAA,iBAWrC,oBAAA,CAAqB,WAAA,EAAa,iBAAA,GAAoB,OAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/live/server-actions/index.ts"],"sourcesContent":["'use server'\n\nimport type {ClientPerspective, SyncTag} from '@sanity/client'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {revalidateTag} from 'next/cache'\nimport {cookies, draftMode} from 'next/headers'\n\nimport {sanitizePerspective} from '../utils'\n\nexport async function revalidateSyncTags(tags: SyncTag[]): Promise<void> {\n revalidateTag('sanity:fetch-sync-tags', 'max')\n\n for (const _tag of tags) {\n const tag = `sanity:${_tag}`\n revalidateTag(tag, {expire: 0})\n // oxlint-disable-next-line no-console\n console.log(`<SanityLive /> revalidated tag: ${tag}`)\n }\n}\n\nexport async function setPerspectiveCookie(perspective: ClientPerspective): Promise<void> {\n if (!(await draftMode()).isEnabled) {\n // throw new Error('Draft mode is not enabled, setting perspective cookie is not allowed')\n return\n }\n const sanitizedPerspective = sanitizePerspective(perspective, 'drafts')\n if (perspective !== sanitizedPerspective) {\n throw new Error(`Invalid perspective`, {cause: perspective})\n }\n\n ;(await cookies()).set(\n perspectiveCookieName,\n Array.isArray(sanitizedPerspective) ? sanitizedPerspective.join(',') : sanitizedPerspective,\n {\n httpOnly: true,\n path: '/',\n secure: true,\n sameSite: 'none',\n },\n )\n}\n"],"mappings":";;;;;AASA,eAAsB,mBAAmB,MAAgC;AACvE,eAAc,0BAA0B,MAAM;AAE9C,MAAK,MAAM,QAAQ,MAAM;EACvB,MAAM,MAAM,UAAU;AACtB,gBAAc,KAAK,EAAC,QAAQ,GAAE,CAAC;AAE/B,UAAQ,IAAI,mCAAmC,MAAM;;;AAIzD,eAAsB,qBAAqB,aAA+C;AACxF,KAAI,EAAE,MAAM,WAAW,EAAE,UAEvB;CAEF,MAAM,uBAAuB,oBAAoB,aAAa,SAAS;AACvE,KAAI,gBAAgB,qBAClB,OAAM,IAAI,MAAM,uBAAuB,EAAC,OAAO,aAAY,CAAC;AAG7D,EAAC,MAAM,SAAS,EAAE,IACjB,uBACA,MAAM,QAAQ,qBAAqB,GAAG,qBAAqB,KAAK,IAAI,GAAG,sBACvE;EACE,UAAU;EACV,MAAM;EACN,QAAQ;EACR,UAAU;EACX,CACF"}
|
package/dist/live.d.ts
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import { t as isCorsOriginError } from "./isCorsOriginError.js";
|
|
2
|
-
import { a as defineLive, i as DefinedSanityLiveStreamType, n as DefinedSanityFetchType, r as DefinedSanityLiveProps, t as DefineSanityLiveOptions } from "./defineLive.js";
|
|
3
|
-
export { type DefineSanityLiveOptions, type DefinedSanityFetchType, type DefinedSanityLiveProps, type DefinedSanityLiveStreamType, defineLive, isCorsOriginError };
|
package/dist/live.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"live.js","names":[],"sources":["../src/live/resolveCookiePerspective.ts","../src/live/defineLive.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {cookies, draftMode} from 'next/headers'\n\nimport {sanitizePerspective} from './utils'\n\n/**\n * @internal\n */\nexport async function resolveCookiePerspective(): Promise<Exclude<ClientPerspective, 'raw'>> {\n return (await draftMode()).isEnabled\n ? (await cookies()).has(perspectiveCookieName)\n ? sanitizePerspective((await cookies()).get(perspectiveCookieName)?.value, 'drafts')\n : 'drafts'\n : 'published'\n}\n","import {\n type ClientPerspective,\n type ClientReturn,\n type ContentSourceMap,\n type LiveEventGoAway,\n type QueryParams,\n type SanityClient,\n type SyncTag,\n} from '@sanity/client'\nimport SanityLiveClientComponent from 'next-sanity/live/client-components/live'\nimport SanityLiveStreamClientComponent from 'next-sanity/live/client-components/live-stream'\nimport {PHASE_PRODUCTION_BUILD} from 'next/constants'\nimport {draftMode} from 'next/headers'\nimport {prefetchDNS, preconnect} from 'react-dom'\n\nimport {resolveCookiePerspective} from './resolveCookiePerspective'\n\n/**\n * @public\n */\nexport type DefinedSanityFetchType = <const QueryString extends string>(options: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n /**\n * Add custom `next.tags` to the underlying fetch request.\n * @see https://nextjs.org/docs/app/api-reference/functions/fetch#optionsnexttags\n * This can be used in conjunction with custom fallback revalidation strategies, as well as with custom Server Actions that mutate data and want to render with fresh data right away (faster than the Live Event latency).\n * @defaultValue `['sanity']`\n */\n tags?: string[]\n perspective?: Exclude<ClientPerspective, 'raw'>\n stega?: boolean\n /**\n * @deprecated use `requestTag` instead\n */\n tag?: never\n /**\n * This request tag is used to identify the request when viewing request logs from your Sanity Content Lake.\n * @see https://www.sanity.io/docs/reference-api-request-tags\n * @defaultValue 'next-loader.fetch'\n */\n requestTag?: string\n}) => Promise<{\n data: ClientReturn<QueryString>\n sourceMap: ContentSourceMap | null\n tags: string[]\n}>\n\n/**\n * @public\n */\nexport type DefinedSanityLiveStreamType = <const QueryString extends string>(props: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n /**\n * Add custom `next.tags` to the underlying fetch request.\n * @see https://nextjs.org/docs/app/api-reference/functions/fetch#optionsnexttags\n * This can be used in conjunction with custom fallback revalidation strategies, as well as with custom Server Actions that mutate data and want to render with fresh data right away (faster than the Live Event latency).\n * @defaultValue `['sanity']`\n */\n tags?: string[]\n perspective?: Exclude<ClientPerspective, 'raw'>\n stega?: boolean\n /**\n * @deprecated use `requestTag` instead\n */\n tag?: never\n /**\n * This request tag is used to identify the request when viewing request logs from your Sanity Content Lake.\n * @see https://www.sanity.io/docs/reference-api-request-tags\n * @defaultValue 'next-loader.live-stream.fetch'\n */\n requestTag?: string\n children: (result: {\n data: ClientReturn<QueryString>\n sourceMap: ContentSourceMap | null\n tags: string[]\n }) => Promise<Awaited<React.ReactNode>>\n}) => React.ReactNode\n\n/**\n * @public\n */\nexport interface DefinedSanityLiveProps {\n /**\n * Automatic refresh of RSC when the component <SanityLive /> is mounted.\n * Note that this is different from revalidation, which is based on tags and causes `sanityFetch` calls to be re-fetched.\n * @defaultValue `true`\n */\n refreshOnMount?: boolean\n /**\n * Automatically refresh when window gets focused\n * Note that this is different from revalidation, which is based on tags and causes `sanityFetch` calls to be re-fetched.\n * @defaultValue `false` if draftMode().isEnabled, otherwise `true` if not inside an iframe\n */\n refreshOnFocus?: boolean\n /**\n * Automatically refresh when the browser regains a network connection (via navigator.onLine)\n * Note that this is different from revalidation, which is based on tags and causes `sanityFetch` calls to be re-fetched.\n * @defaultValue `true`\n */\n refreshOnReconnect?: boolean\n /**\n * Automatically refresh on an interval when the Live Event API emits a `goaway` event, which indicates that the connection is rejected or closed.\n * This typically happens if the connection limit is reached, or if the connection is idle for too long.\n * To disable this long polling fallback behavior set `intervalOnGoAway` to `false` or `0`.\n * You can also use `onGoAway` to handle the `goaway` event in your own way, and read the reason why the event was emitted.\n * @defaultValue `30_000` 30 seconds interval\n */\n intervalOnGoAway?: number | false\n\n /**\n * Delays events until after a Sanity Function has processed them and called the callback endpoint.\n * When omitted, events are delivered immediately.\n */\n waitFor?: 'function'\n\n /**\n * @deprecated use `requestTag` instead\n */\n tag?: never\n\n /**\n * This request tag is used to identify the request when viewing request logs from your Sanity Content Lake.\n * @see https://www.sanity.io/docs/reference-api-request-tags\n * @defaultValue 'next-loader.live'\n */\n requestTag?: string\n\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\n /**\n * Handle the `goaway` event if the connection is rejected/closed.\n * `event.reason` will be a string of why the event was emitted, for example `'connection limit reached'`.\n * When this happens the `<SanityLive />` will fallback to long polling with a default interval of 30 seconds, providing your own `onGoAway` handler does not change this behavior.\n * If you want to disable long polling set `intervalOnGoAway` to `false` or `0`.\n */\n onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void\n\n /**\n * Override how cache tags are invalidated, you need to pass a server action here.\n * You can also pass a `use client` function here, and have `router.refresh()` be called if the promise resolves to `'refresh'`.\n */\n revalidateSyncTags?: (tags: SyncTag[]) => Promise<void | 'refresh'>\n}\n\n/**\n * @public\n */\nexport interface DefineSanityLiveOptions {\n /**\n * Required for `sanityFetch` and `SanityLive` to work\n */\n client: SanityClient\n /**\n * Optional. If provided then the token needs to have permissions to query documents with `drafts.` prefixes in order for `perspective: 'drafts'` to work.\n * This token is not shared with the browser.\n */\n serverToken?: string | false\n /**\n * Optional. This token is shared with the browser, and should only have access to query published documents.\n * It is used to setup a `Live Draft Content` EventSource connection, and enables live previewing drafts stand-alone, outside of Presentation Tool.\n */\n browserToken?: string | false\n /**\n * Fetch options used by `sanityFetch`\n * @deprecated this option is removed in the next major version, use `export const revalidate` on the `page.tsx` or `layout.tsx` instead\n */\n fetchOptions?: {\n /**\n * Optional, enables time based revalidation in addition to the EventSource connection.\n * @defaultValue `false`\n */\n revalidate?: number | false\n }\n /**\n * Optional. Include stega encoding when draft mode is enabled.\n * @defaultValue `true`\n */\n stega?: boolean\n}\n\n/**\n * @public\n */\nexport function defineLive(config: DefineSanityLiveOptions): {\n /**\n * Use this function to fetch data from Sanity in your React Server Components.\n * @public\n */\n sanityFetch: DefinedSanityFetchType\n /**\n * Render this in your root layout.tsx to make your page revalidate on new content live, automatically.\n * @public\n */\n SanityLive: React.ComponentType<DefinedSanityLiveProps>\n /**\n * @alpha experimental, it may change or even be removed at any time\n */\n SanityLiveStream: DefinedSanityLiveStreamType\n} {\n const {\n client: _client,\n serverToken,\n browserToken,\n fetchOptions,\n stega: stegaEnabled = true,\n } = config\n\n if (!_client) {\n throw new Error('`client` is required for `defineLive` to function')\n }\n\n if (process.env.NODE_ENV !== 'production' && !serverToken && serverToken !== false) {\n console.warn(\n 'No `serverToken` provided to `defineLive`. This means that only published content will be fetched and respond to live events. You can silence this warning by setting `serverToken: false`.',\n )\n }\n\n if (process.env.NODE_ENV !== 'production' && !browserToken && browserToken !== false) {\n console.warn(\n 'No `browserToken` provided to `defineLive`. This means that live previewing drafts will only work when using the Presentation Tool in your Sanity Studio. To support live previewing drafts stand-alone, provide a `browserToken`. It is shared with the browser so it should only have Viewer rights or lower. You can silence this warning by setting `browserToken: false`.',\n )\n }\n\n const client = _client.withConfig({allowReconfigure: false, useCdn: false})\n const {token: originalToken} = client.config()\n const studioUrlDefined = typeof client.config().stega.studioUrl !== 'undefined'\n\n const sanityFetch: DefinedSanityFetchType = async function sanityFetch<\n const QueryString extends string,\n >({\n query,\n params = {},\n stega: _stega,\n tags = [],\n perspective: _perspective,\n tag,\n requestTag = tag ?? 'next-loader.fetch',\n }: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n stega?: boolean\n tags?: string[]\n perspective?: Exclude<ClientPerspective, 'raw'>\n tag?: string\n requestTag?: string\n }) {\n const stega = _stega ?? (stegaEnabled && studioUrlDefined && (await draftMode()).isEnabled)\n const perspective = _perspective ?? (await resolveCookiePerspective())\n const useCdn = perspective === 'published'\n const revalidate =\n fetchOptions?.revalidate !== undefined\n ? fetchOptions.revalidate\n : process.env.NODE_ENV === 'production'\n ? false\n : undefined\n const isBuildPhase = process.env['NEXT_PHASE'] === PHASE_PRODUCTION_BUILD\n const cacheMode = useCdn && !isBuildPhase ? 'noStale' : undefined\n\n const {syncTags} = await client.fetch(query, await params, {\n filterResponse: false,\n perspective: perspective as ClientPerspective,\n stega: false,\n returnQuery: false,\n next: {revalidate, tags: [...tags, 'sanity:fetch-sync-tags']},\n useCdn,\n cacheMode,\n tag: [requestTag, 'fetch-sync-tags'].filter(Boolean).join('.'),\n })\n\n const cacheTags = [...tags, ...(syncTags?.map((tag) => `sanity:${tag}`) || [])]\n\n const {result, resultSourceMap} = await client.fetch(query, await params, {\n filterResponse: false,\n perspective: perspective as ClientPerspective,\n stega,\n token: perspective !== 'published' && serverToken ? serverToken : originalToken,\n next: {revalidate, tags: cacheTags},\n useCdn,\n cacheMode,\n tag: requestTag,\n })\n return {data: result, sourceMap: resultSourceMap || null, tags: cacheTags}\n }\n\n const SanityLive: React.ComponentType<DefinedSanityLiveProps> = async function SanityLive(props) {\n const {\n refreshOnMount,\n refreshOnFocus,\n refreshOnReconnect,\n tag,\n requestTag = tag,\n onError,\n onGoAway,\n intervalOnGoAway,\n revalidateSyncTags,\n waitFor,\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n const {isEnabled: isDraftModeEnabled} = await draftMode()\n\n // Preconnect to the Live Event API origin, or at least prefetch the DNS if preconenct is not supported\n const {origin} = new URL(client.getUrl('', false))\n preconnect(origin)\n prefetchDNS(origin)\n\n return (\n <SanityLiveClientComponent\n projectId={projectId}\n dataset={dataset}\n apiHost={apiHost}\n apiVersion={apiVersion}\n useProjectHostname={useProjectHostname}\n requestTagPrefix={requestTagPrefix}\n requestTag={requestTag}\n token={typeof browserToken === 'string' && isDraftModeEnabled ? browserToken : undefined}\n draftModeEnabled={isDraftModeEnabled}\n draftModePerspective={await resolveCookiePerspective()}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n revalidateSyncTags={revalidateSyncTags}\n waitFor={waitFor}\n />\n )\n }\n\n const SanityLiveStream: DefinedSanityLiveStreamType = async function SanityLiveStream(props) {\n const {\n query,\n params,\n perspective: _perspective,\n stega: _stega,\n tags,\n children,\n tag,\n requestTag = tag ?? 'next-loader.live-stream.fetch',\n } = props\n const {\n data,\n sourceMap,\n tags: cacheTags,\n } = await sanityFetch({\n query,\n params,\n tags,\n perspective: _perspective,\n stega: _stega,\n requestTag,\n })\n const {isEnabled: isDraftModeEnabled} = await draftMode()\n\n if (isDraftModeEnabled) {\n const stega = _stega ?? (stegaEnabled && studioUrlDefined && (await draftMode()).isEnabled)\n const perspective = _perspective ?? (await resolveCookiePerspective())\n const {projectId, dataset} = client.config()\n return (\n <SanityLiveStreamClientComponent\n projectId={projectId}\n dataset={dataset}\n query={query}\n params={await params}\n perspective={perspective}\n stega={stega}\n initial={children({data, sourceMap, tags: cacheTags})}\n // oxlint-disable-next-line react/no-children-prop\n children={\n // oxlint-disable-next-line no-unsafe-type-assertion\n children as unknown as any\n }\n />\n )\n }\n\n return children({data, sourceMap, tags: cacheTags})\n }\n\n return {\n sanityFetch,\n SanityLive,\n SanityLiveStream,\n }\n}\n"],"mappings":";;;;;;;;;;;;;AASA,eAAsB,2BAAuE;AAC3F,SAAQ,MAAM,WAAW,EAAE,aACtB,MAAM,SAAS,EAAE,IAAI,sBAAsB,GAC1C,qBAAqB,MAAM,SAAS,EAAE,IAAI,sBAAsB,EAAE,OAAO,SAAS,GAClF,WACF;;;;;AC+KN,SAAgB,WAAW,QAezB;CACA,MAAM,EACJ,QAAQ,SACR,aACA,cACA,cACA,OAAO,eAAe,SACpB;AAEJ,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,oDAAoD;AAGtE,KAAI,QAAQ,IAAI,aAAa,gBAAgB,CAAC,eAAe,gBAAgB,MAC3E,SAAQ,KACN,8LACD;AAGH,KAAI,QAAQ,IAAI,aAAa,gBAAgB,CAAC,gBAAgB,iBAAiB,MAC7E,SAAQ,KACN,iXACD;CAGH,MAAM,SAAS,QAAQ,WAAW;EAAC,kBAAkB;EAAO,QAAQ;EAAM,CAAC;CAC3E,MAAM,EAAC,OAAO,kBAAiB,OAAO,QAAQ;CAC9C,MAAM,mBAAmB,OAAO,OAAO,QAAQ,CAAC,MAAM,cAAc;CAEpE,MAAM,cAAsC,eAAe,YAEzD,EACA,OACA,SAAS,EAAE,EACX,OAAO,QACP,OAAO,EAAE,EACT,aAAa,cACb,KACA,aAAa,OAAO,uBASnB;EACD,MAAM,QAAQ,WAAW,gBAAgB,qBAAqB,MAAM,WAAW,EAAE;EACjF,MAAM,cAAc,gBAAiB,MAAM,0BAA0B;EACrE,MAAM,SAAS,gBAAgB;EAC/B,MAAM,aACJ,cAAc,eAAe,KAAA,IACzB,aAAa,aACb,QAAQ,IAAI,a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ACtC;IACA;IACI;IACX;IACC;IACQ;IACE;IACX;IACT,CAAA;;EAyDJ,kBAAA,eArDmE,iBAAiB,OAAO;GAC3F,MAAM,EACJ,OACA,QACA,aAAa,cACb,OAAO,QACP,MACA,UACA,KACA,aAAa,OAAO,oCAClB;GACJ,MAAM,EACJ,MACA,WACA,MAAM,cACJ,MAAM,YAAY;IACpB;IACA;IACA;IACA,aAAa;IACb,OAAO;IACP;IACD,CAAC;GACF,MAAM,EAAC,WAAW,uBAAsB,MAAM,WAAW;AAEzD,OAAI,oBAAoB;IACtB,MAAM,QAAQ,WAAW,gBAAgB,qBAAqB,MAAM,WAAW,EAAE;IACjF,MAAM,cAAc,gBAAiB,MAAM,0BAA0B;IACrE,MAAM,EAAC,WAAW,YAAW,OAAO,QAAQ;AAC5C,WACE,oBAAC,iCAAD;KACa;KACF;KACF;KACP,QAAQ,MAAM;KACD;KACN;KACP,SAAS,SAAS;MAAC;MAAM;MAAW,MAAM;MAAU,CAAC;KAInD;KAEF,CAAA;;AAIN,UAAO,SAAS;IAAC;IAAM;IAAW,MAAM;IAAU,CAAC;;EAOpD"}
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import { t as isCorsOriginError } from "./isCorsOriginError.js";
|
|
2
|
-
import { i as DefinedSanityLiveStreamType, n as DefinedSanityFetchType, r as DefinedSanityLiveProps, t as DefineSanityLiveOptions } from "./defineLive.js";
|
|
3
|
-
/**
|
|
4
|
-
* @public
|
|
5
|
-
*/
|
|
6
|
-
declare function defineLive(_config: DefineSanityLiveOptions): {
|
|
7
|
-
sanityFetch: DefinedSanityFetchType;
|
|
8
|
-
SanityLive: React.ComponentType<DefinedSanityLiveProps>;
|
|
9
|
-
SanityLiveStream: DefinedSanityLiveStreamType;
|
|
10
|
-
};
|
|
11
|
-
export { type DefineSanityLiveOptions, type DefinedSanityFetchType, type DefinedSanityLiveProps, type DefinedSanityLiveStreamType, defineLive, isCorsOriginError };
|
|
12
|
-
//# sourceMappingURL=live.server-only.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"live.server-only.d.ts","names":[],"sources":["../src/live.server-only.ts"],"mappings":";;;;AAUA;iBAAgB,UAAA,CAAW,OAAA,EAAS,uBAAA;EAClC,WAAA,EAAa,sBAAA;EACb,UAAA,EAAY,KAAA,CAAM,aAAA,CAAc,sBAAA;EAChC,gBAAA,EAAkB,2BAAA;AAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"live.server-only.js","names":[],"sources":["../src/live.server-only.ts"],"sourcesContent":["import type {\n DefineSanityLiveOptions,\n DefinedSanityFetchType,\n DefinedSanityLiveProps,\n DefinedSanityLiveStreamType,\n} from './live/defineLive'\n\n/**\n * @public\n */\nexport function defineLive(_config: DefineSanityLiveOptions): {\n sanityFetch: DefinedSanityFetchType\n SanityLive: React.ComponentType<DefinedSanityLiveProps>\n SanityLiveStream: DefinedSanityLiveStreamType\n} {\n throw new Error('defineLive can only be used in React Server Components')\n}\n\n/**\n * @public\n */\nexport type {\n DefineSanityLiveOptions,\n DefinedSanityFetchType,\n DefinedSanityLiveProps,\n DefinedSanityLiveStreamType,\n}\n\n// @TODO deprecate, so that we can simplify this branching and just use `import 'server-only'` instead\nexport {isCorsOriginError} from './isCorsOriginError'\n"],"mappings":";;;;AAUA,SAAgB,WAAW,SAIzB;AACA,OAAM,IAAI,MAAM,yDAAyD"}
|
package/dist/utils.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[],"sources":["../src/live/utils.ts"],"sourcesContent":["import {validateApiPerspective, type ClientPerspective} from '@sanity/client'\n\n/** @internal */\nexport function sanitizePerspective(\n _perspective: unknown,\n fallback: 'drafts' | 'published',\n): Exclude<ClientPerspective, 'raw'> {\n const perspective =\n typeof _perspective === 'string' && _perspective.includes(',')\n ? _perspective.split(',')\n : _perspective\n try {\n validateApiPerspective(perspective)\n return perspective === 'raw' ? fallback : perspective\n } catch (err) {\n console.warn(`Invalid perspective:`, _perspective, perspective, err)\n return fallback\n }\n}\n"],"mappings":";;AAGA,SAAgB,oBACd,cACA,UACmC;CACnC,MAAM,cACJ,OAAO,iBAAiB,YAAY,aAAa,SAAS,IAAI,GAC1D,aAAa,MAAM,IAAI,GACvB;AACN,KAAI;AACF,yBAAuB,YAAY;AACnC,SAAO,gBAAgB,QAAQ,WAAW;UACnC,KAAK;AACZ,UAAQ,KAAK,wBAAwB,cAAc,aAAa,IAAI;AACpE,SAAO"}
|
|
File without changes
|