next-sanity 13.0.0-cache-components.38 → 13.0.0-cache-components.39
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/SanityLive.js +2 -2
- package/dist/SanityLive.js.map +1 -1
- package/dist/VisualEditing.js +6 -3
- package/dist/VisualEditing.js.map +1 -1
- package/dist/live/conditions/default/index.d.ts +8 -4
- package/dist/live/conditions/default/index.d.ts.map +1 -1
- package/dist/live/conditions/default/index.js +5 -2
- package/dist/live/conditions/default/index.js.map +1 -1
- package/dist/live/conditions/next-js/index.d.ts +2 -2
- package/dist/live/conditions/next-js/index.js.map +1 -1
- package/dist/live/conditions/react-server/index.d.ts +2 -2
- package/dist/live/conditions/react-server/index.js.map +1 -1
- package/dist/parseTags.d.ts +3 -24
- package/dist/parseTags.d.ts.map +1 -1
- package/dist/resolvePerspectiveFromCookies.js +2 -25
- package/dist/resolvePerspectiveFromCookies.js.map +1 -1
- package/dist/types.d.ts +4 -4
- package/dist/visual-editing/client-component/index.d.ts.map +1 -1
- package/dist/visual-editing/server-actions/index.d.ts +1 -6
- package/dist/visual-editing/server-actions/index.d.ts.map +1 -1
- package/dist/visual-editing/server-actions/index.js +1 -7
- package/dist/visual-editing/server-actions/index.js.map +1 -1
- package/package.json +1 -1
package/dist/SanityLive.js
CHANGED
|
@@ -83,9 +83,9 @@ function SanityLive(props) {
|
|
|
83
83
|
includeDrafts
|
|
84
84
|
]);
|
|
85
85
|
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
86
|
-
refreshOnFocus && /* @__PURE__ */ jsx(RefreshOnFocus, {}),
|
|
87
|
-
refreshOnInterval && Number.isFinite(refreshOnInterval) && refreshOnInterval > 0 && /* @__PURE__ */ jsx(RefreshOnInterval, { interval: refreshOnInterval }),
|
|
88
86
|
refreshOnMount && /* @__PURE__ */ jsx(RefreshOnMount, {}),
|
|
87
|
+
refreshOnInterval && Number.isFinite(refreshOnInterval) && refreshOnInterval > 0 && /* @__PURE__ */ jsx(RefreshOnInterval, { interval: refreshOnInterval }),
|
|
88
|
+
refreshOnFocus && /* @__PURE__ */ jsx(RefreshOnFocus, {}),
|
|
89
89
|
refreshOnReconnect && /* @__PURE__ */ jsx(RefreshOnReconnect, {})
|
|
90
90
|
] });
|
|
91
91
|
}
|
package/dist/SanityLive.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SanityLive.js","names":[],"sources":["../src/live/client-components/SanityLive.tsx"],"sourcesContent":["import {createClient, type InitializedClientConfig, type LiveEvent} from '@sanity/client'\nimport dynamic from 'next/dynamic'\nimport {useRouter} from 'next/navigation'\nimport {startTransition, useEffect, useEffectEvent, useMemo, useState} from 'react'\n\nimport {cacheTagPrefixes} from '#live/constants'\nimport {isCorsOriginError} from '#live/isCorsOriginError'\nimport type {\n SanityLiveAction,\n SanityLiveActionContext,\n SanityLiveOnError,\n SanityLiveOnGoaway,\n SanityLiveOnReconnect,\n SanityLiveOnRestart,\n SanityLiveOnWelcome,\n} from '#live/types'\n\nconst RefreshOnFocus = dynamic(() => import('./RefreshOnFocus'))\nconst RefreshOnMount = dynamic(() => import('./RefreshOnMount'))\nconst RefreshOnInterval = dynamic(() => import('./RefreshOnInterval'))\nconst RefreshOnReconnect = dynamic(() => import('./RefreshOnReconnect'))\n\ninterface SanityClientConfig extends Pick<\n InitializedClientConfig,\n | 'projectId'\n | 'dataset'\n | 'apiHost'\n | 'apiVersion'\n | 'useProjectHostname'\n | 'token'\n | 'requestTagPrefix'\n> {}\n\nexport interface SanityLiveProps {\n config: SanityClientConfig\n includeDrafts?: boolean\n requestTag: string\n\n action: SanityLiveAction\n onError: SanityLiveOnError | false | undefined\n onWelcome: SanityLiveOnWelcome | false | undefined\n onReconnect: SanityLiveOnReconnect | false | undefined\n onRestart: SanityLiveOnRestart | false | undefined\n onGoAway: SanityLiveOnGoaway | false | undefined\n\n refreshOnMount?: boolean\n refreshOnFocus?: boolean\n refreshOnReconnect?: boolean\n}\n\nfunction SanityLive(props: SanityLiveProps): React.JSX.Element | null {\n const {\n config,\n includeDrafts = false,\n action,\n onError,\n onWelcome = handleWelcome,\n onReconnect,\n onRestart,\n onGoAway = handleGoaway,\n refreshOnMount = false,\n refreshOnFocus = false,\n refreshOnReconnect = true,\n requestTag,\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, token, requestTagPrefix} =\n config\n const actionContext = {includeDrafts} satisfies SanityLiveActionContext\n\n const client = useMemo(\n () =>\n createClient({\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n ignoreBrowserTokenWarning: true,\n token,\n useCdn: false,\n requestTagPrefix,\n }),\n [apiHost, apiVersion, dataset, projectId, requestTagPrefix, token, useProjectHostname],\n )\n\n const [refreshOnInterval, setRefreshOnInterval] = useState<number | false>(false)\n\n const [error, setError] = useState<unknown>(null)\n if (error) {\n // Throw during render to bubble up to the nearest <ErrorBoundary>, if `onError` is provided we won't rethrow\n throw error\n }\n const handleError = useEffectEvent((error: unknown) => {\n if (onError) {\n void onError(error, actionContext)\n } else {\n setError(\n isCorsOriginError(error)\n ? new Error(\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.${error.addOriginUrl ? ` Add it here: ${error.addOriginUrl}` : ''}`,\n {cause: error},\n )\n : error,\n )\n }\n })\n\n const router = useRouter()\n const handleLiveEvent = useEffectEvent((event: LiveEvent) => {\n switch (event.type) {\n case 'welcome': {\n // Disable long polling when welcome event is received, this is a no-op if long polling is already disabled\n startTransition(() => setRefreshOnInterval(false))\n\n if (onWelcome) {\n startTransition(() => onWelcome(event, actionContext))\n }\n break\n }\n case 'message': {\n startTransition(() =>\n action(\n event.tags.map(\n (tag) =>\n `${includeDrafts ? cacheTagPrefixes.drafts : cacheTagPrefixes.published}${tag}`,\n ),\n ).then((result) => {\n if (result === 'refresh') {\n startTransition(() => router.refresh())\n }\n }),\n )\n break\n }\n case 'restart': {\n // Disable long polling when restart event is received, this is a no-op if long polling is already disabled\n startTransition(() => setRefreshOnInterval(false))\n\n if (onRestart) {\n startTransition(() => onRestart(event, actionContext))\n }\n break\n }\n case 'reconnect': {\n // Disable long polling when reconnect event is received, this is a no-op if long polling is already disabled\n startTransition(() => setRefreshOnInterval(false))\n\n if (onReconnect) {\n startTransition(() => onReconnect(event, actionContext))\n }\n break\n }\n case 'goaway': {\n if (onGoAway) {\n startTransition(() =>\n onGoAway(event, actionContext, (interval) =>\n startTransition(() => setRefreshOnInterval(interval)),\n ),\n )\n } else if (!onGoAway) {\n handleError(\n new Error(\n `Sanity Live connection closed, automatic revalidation is disabled, the server gave this reason: ${event.reason}`,\n {cause: event},\n ),\n )\n }\n break\n }\n default:\n handleError(new Error(`Unknown live event type`, {cause: event}))\n break\n }\n })\n useEffect(() => {\n const subscription = client.live\n .events({includeDrafts, tag: requestTag})\n .subscribe({next: handleLiveEvent, error: handleError})\n return () => subscription.unsubscribe()\n }, [client.live, requestTag, includeDrafts])\n\n return (\n <>\n {
|
|
1
|
+
{"version":3,"file":"SanityLive.js","names":[],"sources":["../src/live/client-components/SanityLive.tsx"],"sourcesContent":["import {createClient, type InitializedClientConfig, type LiveEvent} from '@sanity/client'\nimport dynamic from 'next/dynamic'\nimport {useRouter} from 'next/navigation'\nimport {startTransition, useEffect, useEffectEvent, useMemo, useState} from 'react'\n\nimport {cacheTagPrefixes} from '#live/constants'\nimport {isCorsOriginError} from '#live/isCorsOriginError'\nimport type {\n SanityLiveAction,\n SanityLiveActionContext,\n SanityLiveOnError,\n SanityLiveOnGoaway,\n SanityLiveOnReconnect,\n SanityLiveOnRestart,\n SanityLiveOnWelcome,\n} from '#live/types'\n\nconst RefreshOnFocus = dynamic(() => import('./RefreshOnFocus'))\nconst RefreshOnMount = dynamic(() => import('./RefreshOnMount'))\nconst RefreshOnInterval = dynamic(() => import('./RefreshOnInterval'))\nconst RefreshOnReconnect = dynamic(() => import('./RefreshOnReconnect'))\n\ninterface SanityClientConfig extends Pick<\n InitializedClientConfig,\n | 'projectId'\n | 'dataset'\n | 'apiHost'\n | 'apiVersion'\n | 'useProjectHostname'\n | 'token'\n | 'requestTagPrefix'\n> {}\n\nexport interface SanityLiveProps {\n config: SanityClientConfig\n includeDrafts?: boolean\n requestTag: string\n\n action: SanityLiveAction\n onError: SanityLiveOnError | false | undefined\n onWelcome: SanityLiveOnWelcome | false | undefined\n onReconnect: SanityLiveOnReconnect | false | undefined\n onRestart: SanityLiveOnRestart | false | undefined\n onGoAway: SanityLiveOnGoaway | false | undefined\n\n refreshOnMount?: boolean\n refreshOnFocus?: boolean\n refreshOnReconnect?: boolean\n}\n\nfunction SanityLive(props: SanityLiveProps): React.JSX.Element | null {\n const {\n config,\n includeDrafts = false,\n action,\n onError,\n onWelcome = handleWelcome,\n onReconnect,\n onRestart,\n onGoAway = handleGoaway,\n refreshOnMount = false,\n refreshOnFocus = false,\n refreshOnReconnect = true,\n requestTag,\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, token, requestTagPrefix} =\n config\n const actionContext = {includeDrafts} satisfies SanityLiveActionContext\n\n const client = useMemo(\n () =>\n createClient({\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n ignoreBrowserTokenWarning: true,\n token,\n useCdn: false,\n requestTagPrefix,\n }),\n [apiHost, apiVersion, dataset, projectId, requestTagPrefix, token, useProjectHostname],\n )\n\n const [refreshOnInterval, setRefreshOnInterval] = useState<number | false>(false)\n\n const [error, setError] = useState<unknown>(null)\n if (error) {\n // Throw during render to bubble up to the nearest <ErrorBoundary>, if `onError` is provided we won't rethrow\n throw error\n }\n const handleError = useEffectEvent((error: unknown) => {\n if (onError) {\n void onError(error, actionContext)\n } else {\n setError(\n isCorsOriginError(error)\n ? new Error(\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.${error.addOriginUrl ? ` Add it here: ${error.addOriginUrl}` : ''}`,\n {cause: error},\n )\n : error,\n )\n }\n })\n\n const router = useRouter()\n const handleLiveEvent = useEffectEvent((event: LiveEvent) => {\n switch (event.type) {\n case 'welcome': {\n // Disable long polling when welcome event is received, this is a no-op if long polling is already disabled\n startTransition(() => setRefreshOnInterval(false))\n\n if (onWelcome) {\n startTransition(() => onWelcome(event, actionContext))\n }\n break\n }\n case 'message': {\n startTransition(() =>\n action(\n event.tags.map(\n (tag) =>\n `${includeDrafts ? cacheTagPrefixes.drafts : cacheTagPrefixes.published}${tag}`,\n ),\n ).then((result) => {\n if (result === 'refresh') {\n startTransition(() => router.refresh())\n }\n }),\n )\n break\n }\n case 'restart': {\n // Disable long polling when restart event is received, this is a no-op if long polling is already disabled\n startTransition(() => setRefreshOnInterval(false))\n\n if (onRestart) {\n startTransition(() => onRestart(event, actionContext))\n }\n break\n }\n case 'reconnect': {\n // Disable long polling when reconnect event is received, this is a no-op if long polling is already disabled\n startTransition(() => setRefreshOnInterval(false))\n\n if (onReconnect) {\n startTransition(() => onReconnect(event, actionContext))\n }\n break\n }\n case 'goaway': {\n if (onGoAway) {\n startTransition(() =>\n onGoAway(event, actionContext, (interval) =>\n startTransition(() => setRefreshOnInterval(interval)),\n ),\n )\n } else if (!onGoAway) {\n handleError(\n new Error(\n `Sanity Live connection closed, automatic revalidation is disabled, the server gave this reason: ${event.reason}`,\n {cause: event},\n ),\n )\n }\n break\n }\n default:\n handleError(new Error(`Unknown live event type`, {cause: event}))\n break\n }\n })\n useEffect(() => {\n const subscription = client.live\n .events({includeDrafts, tag: requestTag})\n .subscribe({next: handleLiveEvent, error: handleError})\n return () => subscription.unsubscribe()\n }, [client.live, requestTag, includeDrafts])\n\n return (\n <>\n {refreshOnMount && <RefreshOnMount />}\n {refreshOnInterval && Number.isFinite(refreshOnInterval) && refreshOnInterval > 0 && (\n <RefreshOnInterval interval={refreshOnInterval} />\n )}\n {refreshOnFocus && <RefreshOnFocus />}\n {refreshOnReconnect && <RefreshOnReconnect />}\n </>\n )\n}\n\nSanityLive.displayName = 'SanityLiveClientComponent'\n\nexport default SanityLive\n\nconst handleWelcome: SanityLiveOnWelcome = (_, {includeDrafts}) => {\n // oxlint-disable-next-line no-console\n console.info(\n `<SanityLive${includeDrafts ? ' includeDrafts' : ''}> is connected and listening for live events to ${includeDrafts ? 'all content including drafts and version documents in content releases' : 'published content'}`,\n )\n}\n\nconst handleGoaway: SanityLiveOnGoaway = (event, {includeDrafts}, setLongPollingInterval) => {\n const interval = 30_000\n console.warn(\n `<SanityLive${includeDrafts ? ' includeDrafts' : ''}> connection is closed after receiving a 'goaway' event, the server gave this reason:`,\n event.reason,\n `Content will now be refreshed every ${interval / 1_000} seconds`,\n )\n setLongPollingInterval(interval)\n}\n"],"mappings":";;;;;;;AAiBA,MAAM,iBAAiB,cAAc,OAAO,uBAAoB;AAChE,MAAM,iBAAiB,cAAc,OAAO,uBAAoB;AAChE,MAAM,oBAAoB,cAAc,OAAO,0BAAuB;AACtE,MAAM,qBAAqB,cAAc,OAAO,2BAAwB;AA8BxE,SAAS,WAAW,OAAkD;CACpE,MAAM,EACJ,QACA,gBAAgB,OAChB,QACA,SACA,YAAY,eACZ,aACA,WACA,WAAW,cACX,iBAAiB,OACjB,iBAAiB,OACjB,qBAAqB,MACrB,eACE;CACJ,MAAM,EAAC,WAAW,SAAS,SAAS,YAAY,oBAAoB,OAAO,qBACzE;CACF,MAAM,gBAAgB,EAAC,eAAc;CAErC,MAAM,SAAS,cAEX,aAAa;EACX;EACA;EACA;EACA;EACA;EACA,2BAA2B;EAC3B;EACA,QAAQ;EACR;EACD,CAAC,EACJ;EAAC;EAAS;EAAY;EAAS;EAAW;EAAkB;EAAO;EAAmB,CACvF;CAED,MAAM,CAAC,mBAAmB,wBAAwB,SAAyB,MAAM;CAEjF,MAAM,CAAC,OAAO,YAAY,SAAkB,KAAK;AACjD,KAAI,MAEF,OAAM;CAER,MAAM,cAAc,gBAAgB,UAAmB;AACrD,MAAI,QACG,SAAQ,OAAO,cAAc;MAElC,UACE,kBAAkB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BAAC,gBAAD,EAAkB,CAAA;EACpC,qBAAqB,OAAO,SAAS,kBAAkB,IAAI,oBAAoB,KAC9E,oBAAC,mBAAD,EAAmB,UAAU,mBAAqB,CAAA;EAEnD,kBAAkB,oBAAC,gBAAD,EAAkB,CAAA;EACpC,sBAAsB,oBAAC,oBAAD,EAAsB,CAAA;EAC5C,EAAA,CAAA;;AAIP,WAAW,cAAc;AAIzB,MAAM,iBAAsC,GAAG,EAAC,oBAAmB;AAEjE,SAAQ,KACN,cAAc,gBAAgB,mBAAmB,GAAG,kDAAkD,gBAAgB,2EAA2E,sBAClM;;AAGH,MAAM,gBAAoC,OAAO,EAAC,iBAAgB,2BAA2B;CAC3F,MAAM,WAAW;AACjB,SAAQ,KACN,cAAc,gBAAgB,mBAAmB,GAAG,wFACpD,MAAM,QACN,uCAAuC,WAAW,IAAM,UACzD;AACD,wBAAuB,SAAS"}
|
package/dist/VisualEditing.js
CHANGED
|
@@ -2,7 +2,6 @@ import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
|
|
2
2
|
import { VisualEditing as VisualEditing$1 } from "@sanity/visual-editing/react";
|
|
3
3
|
import { jsx } from "react/jsx-runtime";
|
|
4
4
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
5
|
-
import { actionRefresh } from "next-sanity/visual-editing/server-actions";
|
|
6
5
|
/**
|
|
7
6
|
* From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/path-has-prefix.ts#L10-L17
|
|
8
7
|
* Checks if a given path starts with a given prefix. It ensures it matches
|
|
@@ -125,15 +124,19 @@ function VisualEditing(props) {
|
|
|
125
124
|
]);
|
|
126
125
|
const handleRefresh = useCallback((payload) => {
|
|
127
126
|
switch (payload.source) {
|
|
128
|
-
case "manual":
|
|
127
|
+
case "manual":
|
|
128
|
+
routerRef.current.refresh();
|
|
129
|
+
break;
|
|
129
130
|
case "mutation":
|
|
130
131
|
if (payload.livePreviewEnabled) {
|
|
131
132
|
console.debug("Live preview is setup, mutation is skipped assuming its handled by the live preview");
|
|
132
133
|
return false;
|
|
133
134
|
}
|
|
134
|
-
|
|
135
|
+
routerRef.current.refresh();
|
|
136
|
+
break;
|
|
135
137
|
default: throw new Error("Unknown refresh source", { cause: payload });
|
|
136
138
|
}
|
|
139
|
+
return false;
|
|
137
140
|
}, []);
|
|
138
141
|
return /* @__PURE__ */ jsx(VisualEditing$1, {
|
|
139
142
|
plugins,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"VisualEditing.js","names":["VisualEditingComponent"],"sources":["../src/visual-editing/client-component/utils.ts","../src/visual-editing/client-component/VisualEditing.tsx"],"sourcesContent":["/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/path-has-prefix.ts#L10-L17\n * Checks if a given path starts with a given prefix. It ensures it matches\n * exactly without containing extra chars. e.g. prefix /docs should replace\n * for /docs, /docs/, /docs/a but not /docsss\n * @param path The path to check.\n * @param prefix The prefix to check against.\n */\nfunction pathHasPrefix(path: string, prefix: string): boolean {\n if (typeof path !== 'string') {\n return false\n }\n\n const {pathname} = parsePath(path)\n return pathname === prefix || pathname.startsWith(`${prefix}/`)\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/parse-path.ts#L6-L22\n * Given a path this function will find the pathname, query and hash and return\n * them. This is useful to parse full paths on the client side.\n * @param path A path to parse e.g. /foo/bar?id=1#hash\n */\nfunction parsePath(path: string): {\n pathname: string\n query: string\n hash: string\n} {\n const hashIndex = path.indexOf('#')\n const queryIndex = path.indexOf('?')\n const hasQuery = queryIndex > -1 && (hashIndex < 0 || queryIndex < hashIndex)\n\n if (hasQuery || hashIndex > -1) {\n return {\n pathname: path.substring(0, hasQuery ? queryIndex : hashIndex),\n query: hasQuery ? path.substring(queryIndex, hashIndex > -1 ? hashIndex : undefined) : '',\n hash: hashIndex > -1 ? path.slice(hashIndex) : '',\n }\n }\n\n return {pathname: path, query: '', hash: ''}\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/add-path-prefix.ts#L3C1-L14C2\n * Adds the provided prefix to the given path. It first ensures that the path\n * is indeed starting with a slash.\n */\nexport function addPathPrefix(path: string, prefix?: string): string {\n if (!path.startsWith('/') || !prefix) {\n return path\n }\n // If the path is exactly '/' then return just the prefix\n if (path === '/' && prefix) {\n return prefix\n }\n\n const {pathname, query, hash} = parsePath(path)\n return `${prefix}${pathname}${query}${hash}`\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/remove-path-prefix.ts#L3-L39\n * Given a path and a prefix it will remove the prefix when it exists in the\n * given path. It ensures it matches exactly without containing extra chars\n * and if the prefix is not there it will be noop.\n *\n * @param path The path to remove the prefix from.\n * @param prefix The prefix to be removed.\n */\nexport function removePathPrefix(path: string, prefix: string): string {\n // If the path doesn't start with the prefix we can return it as is. This\n // protects us from situations where the prefix is a substring of the path\n // prefix such as:\n //\n // For prefix: /blog\n //\n // /blog -> true\n // /blog/ -> true\n // /blog/1 -> true\n // /blogging -> false\n // /blogging/ -> false\n // /blogging/1 -> false\n if (!pathHasPrefix(path, prefix)) {\n return path\n }\n\n // Remove the prefix from the path via slicing.\n const withoutPrefix = path.slice(prefix.length)\n\n // If the path without the prefix starts with a `/` we can return it as is.\n if (withoutPrefix.startsWith('/')) {\n return withoutPrefix\n }\n\n // If the path without the prefix doesn't start with a `/` we need to add it\n // back to the path to make sure it's a valid path.\n return `/${withoutPrefix}`\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/dfe7fc03e2268e7cb765dce6a89e02c831c922d5/packages/next/src/client/normalize-trailing-slash.ts#L16\n * Normalizes the trailing slash of a path according to the `trailingSlash` option\n * in `next.config.js`.\n */\nexport const normalizePathTrailingSlash = (path: string, trailingSlash: boolean): string => {\n const {pathname, query, hash} = parsePath(path)\n if (trailingSlash) {\n if (pathname.endsWith('/')) {\n return `${pathname}${query}${hash}`\n }\n return `${pathname}/${query}${hash}`\n }\n\n return `${removeTrailingSlash(pathname)}${query}${hash}`\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/dfe7fc03e2268e7cb765dce6a89e02c831c922d5/packages/next/src/shared/lib/router/utils/remove-trailing-slash.ts#L8\n * Removes the trailing slash for a given route or page path. Preserves the\n * root page. Examples:\n * - `/foo/bar/` -> `/foo/bar`\n * - `/foo/bar` -> `/foo/bar`\n * - `/` -> `/`\n */\nfunction removeTrailingSlash(route: string) {\n return route.replace(/\\/$/, '') || '/'\n}\n","import {\n type HistoryAdapter,\n type HistoryAdapterNavigate,\n type HistoryRefresh,\n VisualEditing as VisualEditingComponent,\n type VisualEditingOptions,\n} from '@sanity/visual-editing/react'\nimport {actionRefresh} from 'next-sanity/visual-editing/server-actions'\nimport {usePathname, useRouter, useSearchParams} from 'next/navigation'\nimport {useCallback, useEffect, useMemo, useRef, useState} from 'react'\n\nimport {addPathPrefix, normalizePathTrailingSlash, removePathPrefix} from './utils'\n\n/**\n * @public\n */\nexport interface VisualEditingProps extends Omit<VisualEditingOptions, 'history'> {\n /**\n * @deprecated The histoy adapter is already implemented\n */\n history?: never\n /**\n * If next.config.ts is configured with a basePath we try to configure it automatically,\n * you can disable this by setting basePath to ''.\n * @example basePath=\"/my-custom-base-path\"\n * @alpha experimental and may change without notice\n * @defaultValue process.env.__NEXT_ROUTER_BASEPATH || ''\n */\n basePath?: string\n /**\n * If next.config.ts is configured with a `trailingSlash` we try to detect it automatically,\n * it can be controlled manually by passing a boolean.\n * @example trailingSlash={true}\n * @alpha experimental and may change without notice\n * @defaultValue Boolean(process.env.__NEXT_TRAILING_SLASH)\n */\n trailingSlash?: boolean\n}\n\nexport default function VisualEditing(props: VisualEditingProps): React.JSX.Element | null {\n const {\n basePath = '',\n plugins,\n components,\n refresh,\n trailingSlash = false,\n zIndex,\n onPerspectiveChange,\n } = props\n\n const router = useRouter()\n const routerRef = useRef(router)\n const [navigate, setNavigate] = useState<HistoryAdapterNavigate | undefined>()\n\n useEffect(() => {\n routerRef.current = router\n }, [router])\n\n const history = useMemo<HistoryAdapter>(\n () => ({\n subscribe: (_navigate) => {\n setNavigate(() => _navigate)\n return () => setNavigate(undefined)\n },\n update: (update) => {\n switch (update.type) {\n case 'push':\n return routerRef.current.push(removePathPrefix(update.url, basePath))\n case 'pop':\n return routerRef.current.back()\n case 'replace':\n return routerRef.current.replace(removePathPrefix(update.url, basePath))\n default:\n throw new Error(`Unknown update type`, {cause: update})\n }\n },\n }),\n [basePath],\n )\n\n const pathname = usePathname()\n const searchParams = useSearchParams()\n useEffect(() => {\n if (navigate) {\n navigate({\n type: 'push',\n url: normalizePathTrailingSlash(\n addPathPrefix(\n `${pathname}${searchParams?.size ? `?${searchParams.toString()}` : ''}`,\n basePath,\n ),\n trailingSlash,\n ),\n })\n }\n }, [basePath, navigate, pathname, searchParams, trailingSlash])\n\n const handleRefresh = useCallback((payload: HistoryRefresh): false | Promise<void> => {\n switch (payload.source) {\n case 'manual':\n return actionRefresh(payload)\n case 'mutation': {\n if (payload.livePreviewEnabled) {\n // oxlint-disable-next-line no-console\n console.debug(\n 'Live preview is setup, mutation is skipped assuming its handled by the live preview',\n )\n return false\n }\n return actionRefresh(payload)\n }\n default:\n throw new Error('Unknown refresh source', {cause: payload})\n }\n }, [])\n\n return (\n <VisualEditingComponent\n plugins={plugins}\n components={components}\n history={history}\n portal\n refresh={refresh ?? handleRefresh}\n onPerspectiveChange={onPerspectiveChange}\n zIndex={zIndex}\n />\n )\n}\n"],"mappings":";;;;;;;;;;;;;AAQA,SAAS,cAAc,MAAc,QAAyB;AAC5D,KAAI,OAAO,SAAS,SAClB,QAAO;CAGT,MAAM,EAAC,aAAY,UAAU,KA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ACE,oBAACA,iBAAD;EACW;EACG;EACH;EACT,QAAA;EACA,SAAS,WAAW;EACC;EACb;EACR,CAAA"}
|
|
1
|
+
{"version":3,"file":"VisualEditing.js","names":["VisualEditingComponent"],"sources":["../src/visual-editing/client-component/utils.ts","../src/visual-editing/client-component/VisualEditing.tsx"],"sourcesContent":["/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/path-has-prefix.ts#L10-L17\n * Checks if a given path starts with a given prefix. It ensures it matches\n * exactly without containing extra chars. e.g. prefix /docs should replace\n * for /docs, /docs/, /docs/a but not /docsss\n * @param path The path to check.\n * @param prefix The prefix to check against.\n */\nfunction pathHasPrefix(path: string, prefix: string): boolean {\n if (typeof path !== 'string') {\n return false\n }\n\n const {pathname} = parsePath(path)\n return pathname === prefix || pathname.startsWith(`${prefix}/`)\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/parse-path.ts#L6-L22\n * Given a path this function will find the pathname, query and hash and return\n * them. This is useful to parse full paths on the client side.\n * @param path A path to parse e.g. /foo/bar?id=1#hash\n */\nfunction parsePath(path: string): {\n pathname: string\n query: string\n hash: string\n} {\n const hashIndex = path.indexOf('#')\n const queryIndex = path.indexOf('?')\n const hasQuery = queryIndex > -1 && (hashIndex < 0 || queryIndex < hashIndex)\n\n if (hasQuery || hashIndex > -1) {\n return {\n pathname: path.substring(0, hasQuery ? queryIndex : hashIndex),\n query: hasQuery ? path.substring(queryIndex, hashIndex > -1 ? hashIndex : undefined) : '',\n hash: hashIndex > -1 ? path.slice(hashIndex) : '',\n }\n }\n\n return {pathname: path, query: '', hash: ''}\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/add-path-prefix.ts#L3C1-L14C2\n * Adds the provided prefix to the given path. It first ensures that the path\n * is indeed starting with a slash.\n */\nexport function addPathPrefix(path: string, prefix?: string): string {\n if (!path.startsWith('/') || !prefix) {\n return path\n }\n // If the path is exactly '/' then return just the prefix\n if (path === '/' && prefix) {\n return prefix\n }\n\n const {pathname, query, hash} = parsePath(path)\n return `${prefix}${pathname}${query}${hash}`\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/remove-path-prefix.ts#L3-L39\n * Given a path and a prefix it will remove the prefix when it exists in the\n * given path. It ensures it matches exactly without containing extra chars\n * and if the prefix is not there it will be noop.\n *\n * @param path The path to remove the prefix from.\n * @param prefix The prefix to be removed.\n */\nexport function removePathPrefix(path: string, prefix: string): string {\n // If the path doesn't start with the prefix we can return it as is. This\n // protects us from situations where the prefix is a substring of the path\n // prefix such as:\n //\n // For prefix: /blog\n //\n // /blog -> true\n // /blog/ -> true\n // /blog/1 -> true\n // /blogging -> false\n // /blogging/ -> false\n // /blogging/1 -> false\n if (!pathHasPrefix(path, prefix)) {\n return path\n }\n\n // Remove the prefix from the path via slicing.\n const withoutPrefix = path.slice(prefix.length)\n\n // If the path without the prefix starts with a `/` we can return it as is.\n if (withoutPrefix.startsWith('/')) {\n return withoutPrefix\n }\n\n // If the path without the prefix doesn't start with a `/` we need to add it\n // back to the path to make sure it's a valid path.\n return `/${withoutPrefix}`\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/dfe7fc03e2268e7cb765dce6a89e02c831c922d5/packages/next/src/client/normalize-trailing-slash.ts#L16\n * Normalizes the trailing slash of a path according to the `trailingSlash` option\n * in `next.config.js`.\n */\nexport const normalizePathTrailingSlash = (path: string, trailingSlash: boolean): string => {\n const {pathname, query, hash} = parsePath(path)\n if (trailingSlash) {\n if (pathname.endsWith('/')) {\n return `${pathname}${query}${hash}`\n }\n return `${pathname}/${query}${hash}`\n }\n\n return `${removeTrailingSlash(pathname)}${query}${hash}`\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/dfe7fc03e2268e7cb765dce6a89e02c831c922d5/packages/next/src/shared/lib/router/utils/remove-trailing-slash.ts#L8\n * Removes the trailing slash for a given route or page path. Preserves the\n * root page. Examples:\n * - `/foo/bar/` -> `/foo/bar`\n * - `/foo/bar` -> `/foo/bar`\n * - `/` -> `/`\n */\nfunction removeTrailingSlash(route: string) {\n return route.replace(/\\/$/, '') || '/'\n}\n","import {\n type HistoryAdapter,\n type HistoryAdapterNavigate,\n type HistoryRefresh,\n VisualEditing as VisualEditingComponent,\n type VisualEditingOptions,\n} from '@sanity/visual-editing/react'\nimport {usePathname, useRouter, useSearchParams} from 'next/navigation'\nimport {useCallback, useEffect, useMemo, useRef, useState} from 'react'\n\nimport {addPathPrefix, normalizePathTrailingSlash, removePathPrefix} from './utils'\n\n/**\n * @public\n */\nexport interface VisualEditingProps extends Omit<VisualEditingOptions, 'history'> {\n /**\n * @deprecated The histoy adapter is already implemented\n */\n history?: never\n /**\n * If next.config.ts is configured with a basePath we try to configure it automatically,\n * you can disable this by setting basePath to ''.\n * @example basePath=\"/my-custom-base-path\"\n * @alpha experimental and may change without notice\n * @defaultValue process.env.__NEXT_ROUTER_BASEPATH || ''\n */\n basePath?: string\n /**\n * If next.config.ts is configured with a `trailingSlash` we try to detect it automatically,\n * it can be controlled manually by passing a boolean.\n * @example trailingSlash={true}\n * @alpha experimental and may change without notice\n * @defaultValue Boolean(process.env.__NEXT_TRAILING_SLASH)\n */\n trailingSlash?: boolean\n}\n\nexport default function VisualEditing(props: VisualEditingProps): React.JSX.Element | null {\n const {\n basePath = '',\n plugins,\n components,\n refresh,\n trailingSlash = false,\n zIndex,\n onPerspectiveChange,\n } = props\n\n const router = useRouter()\n const routerRef = useRef(router)\n const [navigate, setNavigate] = useState<HistoryAdapterNavigate | undefined>()\n\n useEffect(() => {\n routerRef.current = router\n }, [router])\n\n const history = useMemo<HistoryAdapter>(\n () => ({\n subscribe: (_navigate) => {\n setNavigate(() => _navigate)\n return () => setNavigate(undefined)\n },\n update: (update) => {\n switch (update.type) {\n case 'push':\n return routerRef.current.push(removePathPrefix(update.url, basePath))\n case 'pop':\n return routerRef.current.back()\n case 'replace':\n return routerRef.current.replace(removePathPrefix(update.url, basePath))\n default:\n throw new Error(`Unknown update type`, {cause: update})\n }\n },\n }),\n [basePath],\n )\n\n const pathname = usePathname()\n const searchParams = useSearchParams()\n useEffect(() => {\n if (navigate) {\n navigate({\n type: 'push',\n url: normalizePathTrailingSlash(\n addPathPrefix(\n `${pathname}${searchParams?.size ? `?${searchParams.toString()}` : ''}`,\n basePath,\n ),\n trailingSlash,\n ),\n })\n }\n }, [basePath, navigate, pathname, searchParams, trailingSlash])\n\n const handleRefresh = useCallback((payload: HistoryRefresh): false => {\n switch (payload.source) {\n case 'manual':\n routerRef.current.refresh()\n break\n case 'mutation': {\n if (payload.livePreviewEnabled) {\n // oxlint-disable-next-line no-console\n console.debug(\n 'Live preview is setup, mutation is skipped assuming its handled by the live preview',\n )\n return false\n }\n routerRef.current.refresh()\n break\n }\n default:\n throw new Error('Unknown refresh source', {cause: payload})\n }\n return false\n }, [])\n\n return (\n <VisualEditingComponent\n plugins={plugins}\n components={components}\n history={history}\n portal\n refresh={refresh ?? handleRefresh}\n onPerspectiveChange={onPerspectiveChange}\n zIndex={zIndex}\n />\n )\n}\n"],"mappings":";;;;;;;;;;;;AAQA,SAAS,cAAc,MAAc,QAAyB;AAC5D,KAAI,OAAO,SAAS,SAClB,QAAO;CAGT,MAAM,EAAC,aAAY,UAAU,KAAK;AAClC,QAAO,aAAa,UAAU,SAAS,WAAW,GAAG,OAAO,GAAG;;;;;;;;AASjE,SAAS,UAAU,MAIjB;CACA,MAAM,YAAY,KAAK,QAAQ,IAAI;CACnC,MAAM,aAAa,KAAK,QAAQ,IAAI;CACpC,MAAM,WAAW,aAAa,OAAO,YAAY,KAAK,aAAa;AAEnE,KAAI,YAAY,YAAY,GAC1B,QAAO;EACL,UAAU,KAAK,UAAU,GAA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,MAAM,UAAU,eACP;EACL,YAAY,cAAc;AACxB,qBAAkB,UAAU;AAC5B,gBAAa,YAAY,KAAA,EAAU;;EAErC,SAAS,WAAW;AAClB,WAAQ,OAAO,MAAf;IACE,KAAK,OACH,QAAO,UAAU,QAAQ,KAAK,iBAAiB,OAAO,KAAK,SAAS,CAAC;IACvE,KAAK,MACH,QAAO,UAAU,QAAQ,MAAM;IACjC,KAAK,UACH,QAAO,UAAU,QAAQ,QAAQ,iBAAiB,OAAO,KAAK,SAAS,CAAC;IAC1E,QACE,OAAM,IAAI,MAAM,uBAAuB,EAAC,OAAO,QAAO,CAAC;;;EAG9D,GACD,CAAC,SAAS,CACX;CAED,MAAM,WAAW,aAAa;CAC9B,MAAM,eAAe,iBAAiB;AACtC,iBAAgB;AACd,MAAI,SACF,UAAS;GACP,MAAM;GACN,KAAK,2BACH,cACE,GAAG,WAAW,cAAc,OAAO,IAAI,aAAa,UAAU,KAAK,MACnE,SACD,EACD,cACD;GACF,CAAC;IAEH;EAAC;EAAU;EAAU;EAAU;EAAc;EAAc,CAAC;CAE/D,MAAM,gBAAgB,aAAa,YAAmC;AACpE,UAAQ,QAAQ,QAAhB;GACE,KAAK;AACH,cAAU,QAAQ,SAAS;AAC3B;GACF,KAAK;AACH,QAAI,QAAQ,oBAAoB;AAE9B,aAAQ,MACN,sFACD;AACD,YAAO;;AAET,cAAU,QAAQ,SAAS;AAC3B;GAEF,QACE,OAAM,IAAI,MAAM,0BAA0B,EAAC,OAAO,SAAQ,CAAC;;AAE/D,SAAO;IACN,EAAE,CAAC;AAEN,QACE,oBAACA,iBAAD;EACW;EACG;EACH;EACT,QAAA;EACA,SAAS,WAAW;EACC;EACb;EACR,CAAA"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
|
|
2
|
-
import { d as StrictDefinedFetchType, f as StrictDefinedLiveProps, i as
|
|
2
|
+
import { d as StrictDefinedFetchType, f as StrictDefinedLiveProps, i as LivePerspective, n as DefinedFetchType, r as DefinedLiveProps, t as DefineLiveOptions } from "../../../types.js";
|
|
3
3
|
import { n as ResolvePerspectiveFromCookies, t as parseTags } from "../../../parseTags.js";
|
|
4
4
|
/**
|
|
5
|
+
* One
|
|
5
6
|
* @public
|
|
6
7
|
*/
|
|
7
8
|
declare function defineLive(config: DefineLiveOptions & {
|
|
@@ -10,6 +11,10 @@ declare function defineLive(config: DefineLiveOptions & {
|
|
|
10
11
|
sanityFetch: StrictDefinedFetchType;
|
|
11
12
|
SanityLive: React.ComponentType<StrictDefinedLiveProps>;
|
|
12
13
|
};
|
|
14
|
+
/**
|
|
15
|
+
* Two
|
|
16
|
+
* @public
|
|
17
|
+
*/
|
|
13
18
|
declare function defineLive(config: DefineLiveOptions & {
|
|
14
19
|
strict?: false;
|
|
15
20
|
}): {
|
|
@@ -17,9 +22,8 @@ declare function defineLive(config: DefineLiveOptions & {
|
|
|
17
22
|
SanityLive: React.ComponentType<DefinedLiveProps>;
|
|
18
23
|
};
|
|
19
24
|
/**
|
|
20
|
-
*
|
|
21
|
-
* @public
|
|
25
|
+
* @alias {@link resolvePerspectiveFromCookies}
|
|
22
26
|
*/
|
|
23
27
|
declare const resolvePerspectiveFromCookies: ResolvePerspectiveFromCookies;
|
|
24
|
-
export { type
|
|
28
|
+
export { type LivePerspective, defineLive, isCorsOriginError, parseTags, resolvePerspectiveFromCookies };
|
|
25
29
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/live/conditions/default/index.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/live/conditions/default/index.ts"],"mappings":";;;AAsBA;;;;AAAA,iBAAgB,UAAA,CAAW,MAAA,EAAQ,iBAAA;EAAqB,MAAA;AAAA;EACtD,WAAA,EAAa,sBAAA;EACb,UAAA,EAAY,KAAA,CAAM,aAAA,CAAc,sBAAA;AAAA;;;;;iBAMlB,UAAA,CAAW,MAAA,EAAQ,iBAAA;EAAqB,MAAA;AAAA;EACtD,WAAA,EAAa,gBAAA;EACb,UAAA,EAAY,KAAA,CAAM,aAAA,CAAc,gBAAA;AAAA;AAFlC;;;AAAA,cAea,6BAAA,EAA+B,6BAAA"}
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
|
|
2
2
|
import { t as parseTags } from "../../../parseTags.js";
|
|
3
|
+
/**
|
|
4
|
+
* Three
|
|
5
|
+
* @public
|
|
6
|
+
*/
|
|
3
7
|
function defineLive(_config) {
|
|
4
8
|
throw new Error(`defineLive can't be imported by a client component`);
|
|
5
9
|
}
|
|
6
10
|
/**
|
|
7
|
-
*
|
|
8
|
-
* @public
|
|
11
|
+
* @alias {@link resolvePerspectiveFromCookies}
|
|
9
12
|
*/
|
|
10
13
|
const resolvePerspectiveFromCookies = () => {
|
|
11
14
|
throw new Error(`resolvePerspectiveFromCookies can't be imported by a client component`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/live/conditions/default/index.ts"],"sourcesContent":["// This is the fallback export condition for `import 'next-sanity/live'`,\n// it should have the same type definitions as the other conditions so that userland don't have to worry about setting the right\n// `customCondition` in their `tsconfig.json` in order to get accurate typings.\n// The implementation here though should all throw errors, as importing this file means userland made a mistake and somehow a client component is\n// trying to pull in something it shouldn't.\n\nimport type {ResolvePerspectiveFromCookies} from '#live/resolvePerspectiveFromCookies'\nimport type {\n DefinedFetchType,\n DefinedLiveProps,\n DefineLiveOptions,\n StrictDefinedFetchType,\n StrictDefinedLiveProps,\n} from '#live/types'\n\nexport {isCorsOriginError} from '#live/isCorsOriginError'\nexport {parseTags} from '#live/parseTags'\n\n/**\n * @public\n */\nexport function defineLive(config: DefineLiveOptions & {strict: true}): {\n sanityFetch: StrictDefinedFetchType\n SanityLive: React.ComponentType<StrictDefinedLiveProps>\n}\nexport function defineLive(config: DefineLiveOptions & {strict?: false}): {\n sanityFetch: DefinedFetchType\n SanityLive: React.ComponentType<DefinedLiveProps>\n}\nexport function defineLive(_config: DefineLiveOptions): never {\n throw new Error(`defineLive can't be imported by a client component`)\n}\n\n/**\n *
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/live/conditions/default/index.ts"],"sourcesContent":["// This is the fallback export condition for `import 'next-sanity/live'`,\n// it should have the same type definitions as the other conditions so that userland don't have to worry about setting the right\n// `customCondition` in their `tsconfig.json` in order to get accurate typings.\n// The implementation here though should all throw errors, as importing this file means userland made a mistake and somehow a client component is\n// trying to pull in something it shouldn't.\n\nimport type {ResolvePerspectiveFromCookies} from '#live/resolvePerspectiveFromCookies'\nimport type {\n DefinedFetchType,\n DefinedLiveProps,\n DefineLiveOptions,\n StrictDefinedFetchType,\n StrictDefinedLiveProps,\n} from '#live/types'\n\nexport {isCorsOriginError} from '#live/isCorsOriginError'\nexport {parseTags} from '#live/parseTags'\n\n/**\n * One\n * @public\n */\nexport function defineLive(config: DefineLiveOptions & {strict: true}): {\n sanityFetch: StrictDefinedFetchType\n SanityLive: React.ComponentType<StrictDefinedLiveProps>\n}\n/**\n * Two\n * @public\n */\nexport function defineLive(config: DefineLiveOptions & {strict?: false}): {\n sanityFetch: DefinedFetchType\n SanityLive: React.ComponentType<DefinedLiveProps>\n}\n/**\n * Three\n * @public\n */\nexport function defineLive(_config: DefineLiveOptions): never {\n throw new Error(`defineLive can't be imported by a client component`)\n}\n\n/**\n * @alias {@link resolvePerspectiveFromCookies}\n */\nexport const resolvePerspectiveFromCookies: ResolvePerspectiveFromCookies = () => {\n throw new Error(`resolvePerspectiveFromCookies can't be imported by a client component`)\n}\n\nexport type {LivePerspective} from '#live/types'\n"],"mappings":";;;;;;AAsCA,SAAgB,WAAW,SAAmC;AAC5D,OAAM,IAAI,MAAM,qDAAqD;;;;;AAMvE,MAAa,sCAAqE;AAChF,OAAM,IAAI,MAAM,wEAAwE"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
|
|
2
|
-
import { d as StrictDefinedFetchType, f as StrictDefinedLiveProps, i as
|
|
2
|
+
import { d as StrictDefinedFetchType, f as StrictDefinedLiveProps, i as LivePerspective, n as DefinedFetchType, r as DefinedLiveProps, t as DefineLiveOptions } from "../../../types.js";
|
|
3
3
|
import { r as resolvePerspectiveFromCookies, t as parseTags } from "../../../parseTags.js";
|
|
4
4
|
declare function defineLive(config: DefineLiveOptions & {
|
|
5
5
|
strict: true;
|
|
@@ -13,5 +13,5 @@ declare function defineLive(config: DefineLiveOptions & {
|
|
|
13
13
|
sanityFetch: DefinedFetchType;
|
|
14
14
|
SanityLive: React.ComponentType<DefinedLiveProps>;
|
|
15
15
|
};
|
|
16
|
-
export { type
|
|
16
|
+
export { type LivePerspective, defineLive, isCorsOriginError, parseTags, resolvePerspectiveFromCookies };
|
|
17
17
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["SanityLive","SanityLiveClientComponent"],"sources":["../../../../src/live/conditions/next-js/defineLive.tsx"],"sourcesContent":["import {SanityLive as SanityLiveClientComponent} from 'next-sanity/live/client-components'\nimport {actionRefresh, actionUpdateTags} from 'next-sanity/live/server-actions'\nimport {cacheLife, cacheTag} from 'next/cache'\nimport {PHASE_PRODUCTION_BUILD} from 'next/constants'\nimport {preconnect} from 'react-dom'\n\nimport {cacheTagPrefixes, revalidate} from '#live/constants'\nimport {validateStrictFetchOptions, validateStrictSanityLiveProps} from '#live/strictValidation'\nimport type {\n DefinedFetchType,\n DefinedLiveProps,\n DefineLiveOptions,\n StrictDefinedFetchType,\n StrictDefinedLiveProps,\n} from '#live/types'\n\nexport function defineLive(config: DefineLiveOptions & {strict: true}): {\n sanityFetch: StrictDefinedFetchType\n SanityLive: React.ComponentType<StrictDefinedLiveProps>\n}\nexport function defineLive(config: DefineLiveOptions & {strict?: false}): {\n sanityFetch: DefinedFetchType\n SanityLive: React.ComponentType<DefinedLiveProps>\n}\nexport function defineLive(config: DefineLiveOptions) {\n const {client: _client, serverToken, browserToken, strict = false} = 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: true})\n const {token: originalToken, perspective: originalPerspective = 'published'} = client.config()\n\n const sanityFetch: DefinedFetchType = async function sanityFetch({\n query,\n params = {},\n perspective: _perspective,\n stega: _stega,\n tags: customCacheTags = [],\n requestTag = 'next-loader.fetch.cache-components',\n }) {\n if (strict) {\n validateStrictFetchOptions({perspective: _perspective, stega: _stega})\n }\n const perspective = _perspective ?? originalPerspective\n const stega = _stega ?? false\n const useCdn = perspective === 'published'\n const isBuildPhase = process.env['NEXT_PHASE'] === PHASE_PRODUCTION_BUILD\n const cacheMode = useCdn && !isBuildPhase ? 'noStale' : undefined\n\n const cacheTagPrefix =\n perspective === 'published' ? cacheTagPrefixes.published : cacheTagPrefixes.drafts\n const {result, resultSourceMap, syncTags} = await client.fetch(query, await params, {\n filterResponse: false,\n returnQuery: false,\n perspective,\n useCdn,\n stega,\n cacheMode,\n tag: requestTag,\n token: perspective === 'published' ? originalToken : serverToken || originalToken, // @TODO can pass undefined instead of config.token here?\n })\n const tags = [...customCacheTags, ...(syncTags || []).map((tag) => `${cacheTagPrefix}${tag}`)]\n /**\n * The tags used here, are expired later on in the `expireTags` Server Action with the `expireTag` function from `next/cache`\n */\n cacheTag(...tags)\n /**\n * Sanity Live handles on-demand revalidation, so the default 15min time based revalidation is too short,\n * userland can still set a shorter revalidate time by calling `cacheLife` themselves.\n */\n cacheLife({revalidate})\n\n return {data: result, sourceMap: resultSourceMap || null, tags}\n }\n\n const SanityLive: React.ComponentType<DefinedLiveProps> = function SanityLive(props) {\n if (strict) {\n validateStrictSanityLiveProps(props)\n }\n const {\n includeDrafts = false,\n action = actionUpdateTags,\n onReconnect = actionRefresh,\n onRestart = actionRefresh,\n\n onWelcome,\n onError,\n onGoAway,\n\n refreshOnMount = false,\n refreshOnFocus = false,\n refreshOnReconnect = false,\n requestTag = 'next-loader.live.cache-components',\n } = props\n\n const shouldIncludeDrafts = typeof browserToken === 'string' && includeDrafts\n\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n\n // Preconnect to the Live Event API origin early, as the Sanity API is almost always on a different origin than the app\n const {origin} = new URL(client.getUrl('', false))\n preconnect(origin)\n\n return (\n <SanityLiveClientComponent\n config={{\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n requestTagPrefix,\n token: shouldIncludeDrafts ? browserToken : undefined,\n }}\n includeDrafts={shouldIncludeDrafts}\n action={action}\n onReconnect={onReconnect}\n onRestart={onRestart}\n onWelcome={onWelcome}\n onError={onError}\n onGoAway={onGoAway}\n requestTag={requestTag}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n />\n )\n }\n SanityLive.displayName = 'SanityLiveServerComponent'\n\n return {
|
|
1
|
+
{"version":3,"file":"index.js","names":["SanityLive","SanityLiveClientComponent"],"sources":["../../../../src/live/conditions/next-js/defineLive.tsx"],"sourcesContent":["import {SanityLive as SanityLiveClientComponent} from 'next-sanity/live/client-components'\nimport {actionRefresh, actionUpdateTags} from 'next-sanity/live/server-actions'\nimport {cacheLife, cacheTag} from 'next/cache'\nimport {PHASE_PRODUCTION_BUILD} from 'next/constants'\nimport {preconnect} from 'react-dom'\n\nimport {cacheTagPrefixes, revalidate} from '#live/constants'\nimport {validateStrictFetchOptions, validateStrictSanityLiveProps} from '#live/strictValidation'\nimport type {\n DefinedFetchType,\n DefinedLiveProps,\n DefineLiveOptions,\n StrictDefinedFetchType,\n StrictDefinedLiveProps,\n} from '#live/types'\n\nexport function defineLive(config: DefineLiveOptions & {strict: true}): {\n sanityFetch: StrictDefinedFetchType\n SanityLive: React.ComponentType<StrictDefinedLiveProps>\n}\nexport function defineLive(config: DefineLiveOptions & {strict?: false}): {\n sanityFetch: DefinedFetchType\n SanityLive: React.ComponentType<DefinedLiveProps>\n}\nexport function defineLive(config: DefineLiveOptions) {\n const {client: _client, serverToken, browserToken, strict = false} = 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: true})\n const {token: originalToken, perspective: originalPerspective = 'published'} = client.config()\n\n const sanityFetch: DefinedFetchType = async function sanityFetch({\n query,\n params = {},\n perspective: _perspective,\n stega: _stega,\n tags: customCacheTags = [],\n requestTag = 'next-loader.fetch.cache-components',\n }) {\n if (strict) {\n validateStrictFetchOptions({perspective: _perspective, stega: _stega})\n }\n const perspective = _perspective ?? originalPerspective\n const stega = _stega ?? false\n const useCdn = perspective === 'published'\n const isBuildPhase = process.env['NEXT_PHASE'] === PHASE_PRODUCTION_BUILD\n const cacheMode = useCdn && !isBuildPhase ? 'noStale' : undefined\n\n const cacheTagPrefix =\n perspective === 'published' ? cacheTagPrefixes.published : cacheTagPrefixes.drafts\n const {result, resultSourceMap, syncTags} = await client.fetch(query, await params, {\n filterResponse: false,\n returnQuery: false,\n perspective,\n useCdn,\n stega,\n cacheMode,\n tag: requestTag,\n token: perspective === 'published' ? originalToken : serverToken || originalToken, // @TODO can pass undefined instead of config.token here?\n })\n const tags = [...customCacheTags, ...(syncTags || []).map((tag) => `${cacheTagPrefix}${tag}`)]\n /**\n * The tags used here, are expired later on in the `expireTags` Server Action with the `expireTag` function from `next/cache`\n */\n cacheTag(...tags)\n /**\n * Sanity Live handles on-demand revalidation, so the default 15min time based revalidation is too short,\n * userland can still set a shorter revalidate time by calling `cacheLife` themselves.\n */\n cacheLife({revalidate})\n\n return {data: result, sourceMap: resultSourceMap || null, tags}\n }\n\n const SanityLive: React.ComponentType<DefinedLiveProps> = function SanityLive(props) {\n if (strict) {\n validateStrictSanityLiveProps(props)\n }\n const {\n includeDrafts = false,\n action = actionUpdateTags,\n onReconnect = actionRefresh,\n onRestart = actionRefresh,\n\n onWelcome,\n onError,\n onGoAway,\n\n refreshOnMount = false,\n refreshOnFocus = false,\n refreshOnReconnect = false,\n requestTag = 'next-loader.live.cache-components',\n } = props\n\n const shouldIncludeDrafts = typeof browserToken === 'string' && includeDrafts\n\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n\n // Preconnect to the Live Event API origin early, as the Sanity API is almost always on a different origin than the app\n const {origin} = new URL(client.getUrl('', false))\n preconnect(origin)\n\n return (\n <SanityLiveClientComponent\n config={{\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n requestTagPrefix,\n token: shouldIncludeDrafts ? browserToken : undefined,\n }}\n includeDrafts={shouldIncludeDrafts}\n action={action}\n onReconnect={onReconnect}\n onRestart={onRestart}\n onWelcome={onWelcome}\n onError={onError}\n onGoAway={onGoAway}\n requestTag={requestTag}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n />\n )\n }\n SanityLive.displayName = 'SanityLiveServerComponent'\n\n return {sanityFetch, SanityLive}\n}\n"],"mappings":";;;;;;;;;;AAwBA,SAAgB,WAAW,QAA2B;CACpD,MAAM,EAAC,QAAQ,SAAS,aAAa,cAAc,SAAS,UAAS;AAErE,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;EAAK,CAAC;CAC1E,MAAM,EAAC,OAAO,eAAe,aAAa,sBAAsB,gBAAe,OAAO,QAAQ;CAE9F,MAAM,cAAgC,eAAe,YAAY,EAC/D,OACA,SAAS,EAAE,EACX,aAAa,cACb,OAAO,QACP,MAAM,kBAAkB,EAAE,EAC1B,aAAa,wCACZ;AACD,MAAI,OACF,4BAA2B;GAAC,aAAa;GAAc,OAAO;GAAO,CAAC;EAExE,MAAM,cAAc,gBAAgB;EACpC,MAAM,QAAQ,UAAU;EACxB,MAAM,SAAS,gBAAgB;EAC/B,MAAM,eAAe,QAAQ,IAAI,kBAAkB;EACnD,MAAM,YAAY,UAAU,CAAC,eAAe,YAAY,KAAA;EAExD,MAAM,iBACJ,gBAAgB,cAAc,iBAAiB,YAAY,iBAAiB;EAC9E,MAAM,EAAC,QAAQ,iBAAiB,aAAY,MAAM,OAAO,MAAM,OAAO,MAAM,QAAQ;GAClF,gBAAgB;GAChB,aAAa;GACb;GACA;GACA;GACA;GACA,KAAK;GACL,OAAO,gBAAgB,cAAc,gBAAgB,eAAe;GACrE,CAAC;EACF,MAAM,OAAO,CAAC,GAAG,iBAAiB,IAAI,YAAY,EAAE,EAAE,KAAK,QAAQ,GAAG,iBAAiB,MAAM,CAAC;;;;AAI9F,WAAS,GAAG,KAAK;;;;;AAKjB,YAAU,EAAC,YAAW,CAAC;AAEvB,SAAO;GAAC,MAAM;GAAQ,WAAW,mBAAmB;GAAM;GAAK;;CAGjE,MAAMA,eAAoD,SAASA,aAAW,OAAO;AACnF,MAAI,OACF,+BAA8B,MAAM;EAEtC,MAAM,EACJ,gBAAgB,OAChB,SAAS,kBACT,cAAc,eACd,YAAY,eAEZ,WACA,SACA,UAEA,iBAAiB,OACjB,iBAAiB,OACjB,qBAAqB,OACrB,aAAa,wCACX;EAEJ,MAAM,sBAAsB,OAAO,iBAAiB,YAAY;EAEhE,MAAM,EAAC,WAAW,SAAS,SAAS,YAAY,oBAAoB,qBAClE,OAAO,QAAQ;EAGjB,MAAM,EAAC,WAAU,IAAI,IAAI,OAAO,OAAO,IAAI,MAAM,CAAC;AAClD,aAAW,OAAO;AAElB,SACE,oBAACC,YAAD;GACE,QAAQ;IACN;IACA;IACA;IACA;IACA;IACA;IACA,OAAO,sBAAsB,eAAe,KAAA;IAC7C;GACD,eAAe;GACP;GACK;GACF;GACA;GACF;GACC;GACE;GACI;GACA;GACI;GACpB,CAAA;;AAGN,cAAW,cAAc;AAEzB,QAAO;EAAC;EAAa,YAAA;EAAW"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
|
|
2
|
-
import { d as StrictDefinedFetchType, f as StrictDefinedLiveProps, i as
|
|
2
|
+
import { d as StrictDefinedFetchType, f as StrictDefinedLiveProps, i as LivePerspective, n as DefinedFetchType, r as DefinedLiveProps, t as DefineLiveOptions } from "../../../types.js";
|
|
3
3
|
import { r as resolvePerspectiveFromCookies, t as parseTags } from "../../../parseTags.js";
|
|
4
4
|
declare function defineLive(config: DefineLiveOptions & {
|
|
5
5
|
strict: true;
|
|
@@ -13,5 +13,5 @@ declare function defineLive(config: DefineLiveOptions & {
|
|
|
13
13
|
sanityFetch: DefinedFetchType;
|
|
14
14
|
SanityLive: React.ComponentType<DefinedLiveProps>;
|
|
15
15
|
};
|
|
16
|
-
export { type
|
|
16
|
+
export { type LivePerspective, defineLive, isCorsOriginError, parseTags, resolvePerspectiveFromCookies };
|
|
17
17
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["SanityLive","SanityLiveClientComponent"],"sources":["../../../../src/live/conditions/react-server/defineLive.tsx"],"sourcesContent":["import {type ClientPerspective, type QueryParams} from '@sanity/client'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {SanityLive as SanityLiveClientComponent} from 'next-sanity/live/client-components'\nimport {actionRefresh, actionUpdateTags} from 'next-sanity/live/server-actions'\nimport {PHASE_PRODUCTION_BUILD} from 'next/constants'\nimport {cookies, draftMode} from 'next/headers'\nimport {preconnect} from 'react-dom'\n\nimport {cacheTagPrefixes} from '#live/constants'\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {validateStrictFetchOptions, validateStrictSanityLiveProps} from '#live/strictValidation'\nimport type {\n DefinedFetchType,\n DefinedLiveProps,\n DefineLiveOptions,\n StrictDefinedFetchType,\n StrictDefinedLiveProps,\n} from '#live/types'\n\nexport function defineLive(config: DefineLiveOptions & {strict: true}): {\n sanityFetch: StrictDefinedFetchType\n SanityLive: React.ComponentType<StrictDefinedLiveProps>\n}\nexport function defineLive(config: DefineLiveOptions & {strict?: false}): {\n sanityFetch: DefinedFetchType\n SanityLive: React.ComponentType<DefinedLiveProps>\n}\nexport function defineLive(config: DefineLiveOptions) {\n const {\n client: _client,\n serverToken,\n browserToken,\n stega: stegaEnabled = true,\n strict = false,\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, perspective: originalPerspective = 'published'} = client.config()\n const studioUrlDefined = typeof client.config().stega.studioUrl !== 'undefined'\n\n const sanityFetch: DefinedFetchType = 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 if (strict) {\n validateStrictFetchOptions({perspective: _perspective, stega: _stega})\n }\n const stega = strict\n ? _stega!\n : (_stega ?? (stegaEnabled && studioUrlDefined && (await draftMode()).isEnabled))\n const perspective = strict\n ? _perspective!\n : (_perspective ??\n (await resolveCookiePerspective(\n originalPerspective === 'raw' ? 'published' : originalPerspective,\n )))\n const useCdn = perspective === 'published'\n const isBuildPhase = process.env['NEXT_PHASE'] === PHASE_PRODUCTION_BUILD\n const cacheMode = useCdn && !isBuildPhase ? 'noStale' : undefined\n const revalidate = false\n const cacheTagPrefix =\n perspective === 'published' ? cacheTagPrefixes.published : cacheTagPrefixes.drafts\n\n // fetch the tags first, with revalidate to 1s to ensure we get the latest tags, eventually\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: {\n revalidate,\n tags: [...tags, 'fetch-sync-tags'].map((tag) => `${cacheTagPrefix}${tag}`),\n },\n useCdn,\n cacheMode,\n tag: [requestTag, 'fetch-sync-tags'].filter(Boolean).join('.'),\n })\n\n const cacheTags = [...tags, ...(syncTags?.map((tag) => `${cacheTagPrefix}${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<DefinedLiveProps> = async function SanityLive(props) {\n if (strict) {\n validateStrictSanityLiveProps(props)\n }\n const {\n includeDrafts = (await draftMode()).isEnabled,\n action = actionUpdateTags,\n onReconnect = actionRefresh,\n onRestart = actionRefresh,\n\n onWelcome = false,\n onError = false,\n onGoAway = false,\n\n refreshOnMount,\n refreshOnFocus,\n refreshOnReconnect,\n requestTag = 'next-loader.live',\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n const shouldIncludeDrafts = typeof browserToken === 'string' && includeDrafts\n\n // Preconnect to the Live Event API origin early, as the Sanity API is almost always on a different origin than the app\n const {origin} = new URL(client.getUrl('', false))\n preconnect(origin)\n\n return (\n <SanityLiveClientComponent\n config={{\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n requestTagPrefix,\n token: shouldIncludeDrafts ? browserToken : undefined,\n }}\n includeDrafts={shouldIncludeDrafts}\n action={action}\n onReconnect={onReconnect}\n onRestart={onRestart}\n onWelcome={onWelcome}\n onError={onError}\n onGoAway={onGoAway}\n requestTag={requestTag}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n />\n )\n }\n SanityLive.displayName = 'SanityLiveServerComponent'\n\n return {
|
|
1
|
+
{"version":3,"file":"index.js","names":["SanityLive","SanityLiveClientComponent"],"sources":["../../../../src/live/conditions/react-server/defineLive.tsx"],"sourcesContent":["import {type ClientPerspective, type QueryParams} from '@sanity/client'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {SanityLive as SanityLiveClientComponent} from 'next-sanity/live/client-components'\nimport {actionRefresh, actionUpdateTags} from 'next-sanity/live/server-actions'\nimport {PHASE_PRODUCTION_BUILD} from 'next/constants'\nimport {cookies, draftMode} from 'next/headers'\nimport {preconnect} from 'react-dom'\n\nimport {cacheTagPrefixes} from '#live/constants'\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {validateStrictFetchOptions, validateStrictSanityLiveProps} from '#live/strictValidation'\nimport type {\n DefinedFetchType,\n DefinedLiveProps,\n DefineLiveOptions,\n StrictDefinedFetchType,\n StrictDefinedLiveProps,\n} from '#live/types'\n\nexport function defineLive(config: DefineLiveOptions & {strict: true}): {\n sanityFetch: StrictDefinedFetchType\n SanityLive: React.ComponentType<StrictDefinedLiveProps>\n}\nexport function defineLive(config: DefineLiveOptions & {strict?: false}): {\n sanityFetch: DefinedFetchType\n SanityLive: React.ComponentType<DefinedLiveProps>\n}\nexport function defineLive(config: DefineLiveOptions) {\n const {\n client: _client,\n serverToken,\n browserToken,\n stega: stegaEnabled = true,\n strict = false,\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, perspective: originalPerspective = 'published'} = client.config()\n const studioUrlDefined = typeof client.config().stega.studioUrl !== 'undefined'\n\n const sanityFetch: DefinedFetchType = 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 if (strict) {\n validateStrictFetchOptions({perspective: _perspective, stega: _stega})\n }\n const stega = strict\n ? _stega!\n : (_stega ?? (stegaEnabled && studioUrlDefined && (await draftMode()).isEnabled))\n const perspective = strict\n ? _perspective!\n : (_perspective ??\n (await resolveCookiePerspective(\n originalPerspective === 'raw' ? 'published' : originalPerspective,\n )))\n const useCdn = perspective === 'published'\n const isBuildPhase = process.env['NEXT_PHASE'] === PHASE_PRODUCTION_BUILD\n const cacheMode = useCdn && !isBuildPhase ? 'noStale' : undefined\n const revalidate = false\n const cacheTagPrefix =\n perspective === 'published' ? cacheTagPrefixes.published : cacheTagPrefixes.drafts\n\n // fetch the tags first, with revalidate to 1s to ensure we get the latest tags, eventually\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: {\n revalidate,\n tags: [...tags, 'fetch-sync-tags'].map((tag) => `${cacheTagPrefix}${tag}`),\n },\n useCdn,\n cacheMode,\n tag: [requestTag, 'fetch-sync-tags'].filter(Boolean).join('.'),\n })\n\n const cacheTags = [...tags, ...(syncTags?.map((tag) => `${cacheTagPrefix}${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<DefinedLiveProps> = async function SanityLive(props) {\n if (strict) {\n validateStrictSanityLiveProps(props)\n }\n const {\n includeDrafts = (await draftMode()).isEnabled,\n action = actionUpdateTags,\n onReconnect = actionRefresh,\n onRestart = actionRefresh,\n\n onWelcome = false,\n onError = false,\n onGoAway = false,\n\n refreshOnMount,\n refreshOnFocus,\n refreshOnReconnect,\n requestTag = 'next-loader.live',\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n const shouldIncludeDrafts = typeof browserToken === 'string' && includeDrafts\n\n // Preconnect to the Live Event API origin early, as the Sanity API is almost always on a different origin than the app\n const {origin} = new URL(client.getUrl('', false))\n preconnect(origin)\n\n return (\n <SanityLiveClientComponent\n config={{\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n requestTagPrefix,\n token: shouldIncludeDrafts ? browserToken : undefined,\n }}\n includeDrafts={shouldIncludeDrafts}\n action={action}\n onReconnect={onReconnect}\n onRestart={onRestart}\n onWelcome={onWelcome}\n onError={onError}\n onGoAway={onGoAway}\n requestTag={requestTag}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n />\n )\n }\n SanityLive.displayName = 'SanityLiveServerComponent'\n\n return {sanityFetch, SanityLive}\n}\n\nasync function resolveCookiePerspective(\n fallback: Exclude<ClientPerspective, 'raw'>,\n): 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 : fallback\n}\n"],"mappings":";;;;;;;;;;;;;AA2BA,SAAgB,WAAW,QAA2B;CACpD,MAAM,EACJ,QAAQ,SACR,aACA,cACA,OAAO,eAAe,MACtB,SAAS,UACP;AAEJ,KAAI,CAAC,QACH,OAAM,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|
import { cookies } from "next/headers";
|
|
2
2
|
import { ClientPerspective, SyncTag } from "@sanity/client";
|
|
3
3
|
/**
|
|
4
|
-
* @deprecated - refactor to exporting the same function instead
|
|
5
|
-
*/
|
|
6
|
-
type ResolvePerspectiveFromCookies = (options: {
|
|
7
|
-
/**
|
|
8
|
-
* You must await the cookies() function from next/headers
|
|
9
|
-
* and pass it here.
|
|
10
|
-
* Example:
|
|
11
|
-
* ```ts
|
|
12
|
-
* import { cookies } from 'next/headers'
|
|
13
|
-
*
|
|
14
|
-
* const perspective = await resolvePerspectiveFromCookies({cookies: await cookies()})
|
|
15
|
-
* ```
|
|
16
|
-
*/
|
|
17
|
-
cookies: Awaited<ReturnType<typeof cookies>>;
|
|
18
|
-
}) => Promise<Exclude<ClientPerspective, "raw">>;
|
|
19
|
-
/**
|
|
20
|
-
* Reads the active draft-mode perspective from the cookie set by
|
|
21
|
-
* {@link "next-sanity/draft-mode".defineEnableDraftMode | `defineEnableDraftMode`}, falling back to `'drafts'`
|
|
22
|
-
* when the cookie is missing or contains an invalid value.
|
|
23
|
-
*
|
|
24
4
|
* This helper is intended for use with Next.js Cache Components (`cacheComponents: true`),
|
|
25
5
|
* where `cookies()` and `draftMode()` cannot be called inside `'use cache'` boundaries.
|
|
26
6
|
* Resolve the perspective once outside the cache boundary and pass it in as a prop / cache key.
|
|
@@ -39,11 +19,10 @@ type ResolvePerspectiveFromCookies = (options: {
|
|
|
39
19
|
*
|
|
40
20
|
* @public
|
|
41
21
|
*/
|
|
42
|
-
|
|
43
|
-
cookies: jar
|
|
44
|
-
}: {
|
|
22
|
+
type ResolvePerspectiveFromCookies = (options: {
|
|
45
23
|
cookies: Awaited<ReturnType<typeof cookies>>;
|
|
46
|
-
})
|
|
24
|
+
}) => Promise<Exclude<ClientPerspective, "raw">>;
|
|
25
|
+
declare const resolvePerspectiveFromCookies: ResolvePerspectiveFromCookies;
|
|
47
26
|
declare const cacheTagPrefixes: {
|
|
48
27
|
published: string;
|
|
49
28
|
drafts: string;
|
package/dist/parseTags.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parseTags.d.ts","names":[],"sources":["../src/live/shared/resolvePerspectiveFromCookies.ts","../src/live/shared/constants.ts","../src/live/shared/parseTags.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"parseTags.d.ts","names":[],"sources":["../src/live/shared/resolvePerspectiveFromCookies.ts","../src/live/shared/constants.ts","../src/live/shared/parseTags.ts"],"mappings":";;;AAyBA;;;;;;;;;;;;;;;;;;KAAY,6BAAA,IAAiC,OAAA;EAC3C,OAAA,EAAS,OAAA,CAAQ,UAAA,QAAkB,OAAA;AAAA,MAC/B,OAAA,CAAQ,OAAA,CAAQ,iBAAA;AAAA,cAET,6BAAA,EAA8B,6BAAA;AAAA,cCtB9B,gBAAA;EACX,SAAA;EACA,MAAA;AAAA;AAAA,UCLQ,mBAAA;EACR,IAAA,YAAgB,gBAAA,CAAiB,SAAA,GAAY,OAAA;EAC7C,MAAA,SAAe,gBAAA,CAAiB,SAAA;EAChC,UAAA;AAAA;AAAA,UAEQ,eAAA;EACR,IAAA,YAAgB,gBAAA,CAAiB,MAAA,GAAS,OAAA;EAC1C,MAAA,SAAe,gBAAA,CAAiB,MAAA;EAChC,UAAA;AAAA;AAAA,KAEG,UAAA,GAAa,mBAAA,GAAsB,eAAA;;;;;;;;;;;;AFexC;;;;;;ACtBA;;;;iBC8BgB,SAAA,CAAU,UAAA,YAAsB,UAAA"}
|
|
@@ -8,32 +8,9 @@ function validateStrictFetchOptions(options) {
|
|
|
8
8
|
if (typeof options.perspective === "undefined" || options.perspective === null) throw new Error(`sanityFetch() requires an explicit \`perspective\` option when \`strict: true\` is set on \`defineLive\`.\n\nMore information: ${generateHelpUrl("next-sanity-fetch-strict")}`, { cause: options });
|
|
9
9
|
if (typeof options.stega !== "boolean") throw new Error(`sanityFetch() requires an explicit \`stega\` option (true or false) when \`strict: true\` is set on \`defineLive\`.\n\nMore information: ${generateHelpUrl("next-sanity-fetch-strict")}`, { cause: options });
|
|
10
10
|
}
|
|
11
|
-
|
|
12
|
-
* Reads the active draft-mode perspective from the cookie set by
|
|
13
|
-
* {@link "next-sanity/draft-mode".defineEnableDraftMode | `defineEnableDraftMode`}, falling back to `'drafts'`
|
|
14
|
-
* when the cookie is missing or contains an invalid value.
|
|
15
|
-
*
|
|
16
|
-
* This helper is intended for use with Next.js Cache Components (`cacheComponents: true`),
|
|
17
|
-
* where `cookies()` and `draftMode()` cannot be called inside `'use cache'` boundaries.
|
|
18
|
-
* Resolve the perspective once outside the cache boundary and pass it in as a prop / cache key.
|
|
19
|
-
*
|
|
20
|
-
* The caller is responsible for awaiting `cookies()` from `next/headers` and passing the
|
|
21
|
-
* resulting cookie store as the `cookies` option — this keeps the helper free of dynamic APIs
|
|
22
|
-
* so it can be invoked from anywhere a `ReadonlyRequestCookies` instance is available.
|
|
23
|
-
*
|
|
24
|
-
* @example
|
|
25
|
-
* ```ts
|
|
26
|
-
* import {cookies} from 'next/headers'
|
|
27
|
-
* import {resolvePerspectiveFromCookies} from 'next-sanity/live'
|
|
28
|
-
*
|
|
29
|
-
* const perspective = await resolvePerspectiveFromCookies({cookies: await cookies()})
|
|
30
|
-
* ```
|
|
31
|
-
*
|
|
32
|
-
* @public
|
|
33
|
-
*/
|
|
34
|
-
async function resolvePerspectiveFromCookies({ cookies: jar }) {
|
|
11
|
+
const resolvePerspectiveFromCookies = async function resolvePerspectiveFromCookies({ cookies: jar }) {
|
|
35
12
|
return jar.has(perspectiveCookieName) ? sanitizePerspective(jar.get(perspectiveCookieName)?.value, "drafts") : "drafts";
|
|
36
|
-
}
|
|
13
|
+
};
|
|
37
14
|
export { validateStrictFetchOptions as n, validateStrictSanityLiveProps as r, resolvePerspectiveFromCookies as t };
|
|
38
15
|
|
|
39
16
|
//# sourceMappingURL=resolvePerspectiveFromCookies.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolvePerspectiveFromCookies.js","names":[],"sources":["../src/live/shared/strictValidation.ts","../src/live/shared/resolvePerspectiveFromCookies.ts"],"sourcesContent":["import {generateHelpUrl} from '@sanity/generate-help-url'\n\nexport function validateStrictSanityLiveProps(props: {includeDrafts?: unknown}): void {\n if (typeof props.includeDrafts !== 'boolean') {\n throw new Error(\n `<SanityLive> requires an explicit \\`includeDrafts\\` prop (true or false) when \\`strict: true\\` is set on \\`defineLive\\`.\\n\\nMore information: ${generateHelpUrl('next-sanity-live-strict')}`,\n {cause: props},\n )\n }\n}\n\nexport function validateStrictFetchOptions(options: {\n perspective?: unknown\n stega?: unknown\n}): void {\n if (typeof options.perspective === 'undefined' || options.perspective === null) {\n throw new Error(\n `sanityFetch() requires an explicit \\`perspective\\` option when \\`strict: true\\` is set on \\`defineLive\\`.\\n\\nMore information: ${generateHelpUrl('next-sanity-fetch-strict')}`,\n {cause: options},\n )\n }\n if (typeof options.stega !== 'boolean') {\n throw new Error(\n `sanityFetch() requires an explicit \\`stega\\` option (true or false) when \\`strict: true\\` is set on \\`defineLive\\`.\\n\\nMore information: ${generateHelpUrl('next-sanity-fetch-strict')}`,\n {cause: options},\n )\n }\n}\n","import type {ClientPerspective} from '@sanity/client'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport type {cookies} from 'next/headers'\n\nimport {sanitizePerspective} from '#live/sanitizePerspective'\n\n/**\n *
|
|
1
|
+
{"version":3,"file":"resolvePerspectiveFromCookies.js","names":[],"sources":["../src/live/shared/strictValidation.ts","../src/live/shared/resolvePerspectiveFromCookies.ts"],"sourcesContent":["import {generateHelpUrl} from '@sanity/generate-help-url'\n\nexport function validateStrictSanityLiveProps(props: {includeDrafts?: unknown}): void {\n if (typeof props.includeDrafts !== 'boolean') {\n throw new Error(\n `<SanityLive> requires an explicit \\`includeDrafts\\` prop (true or false) when \\`strict: true\\` is set on \\`defineLive\\`.\\n\\nMore information: ${generateHelpUrl('next-sanity-live-strict')}`,\n {cause: props},\n )\n }\n}\n\nexport function validateStrictFetchOptions(options: {\n perspective?: unknown\n stega?: unknown\n}): void {\n if (typeof options.perspective === 'undefined' || options.perspective === null) {\n throw new Error(\n `sanityFetch() requires an explicit \\`perspective\\` option when \\`strict: true\\` is set on \\`defineLive\\`.\\n\\nMore information: ${generateHelpUrl('next-sanity-fetch-strict')}`,\n {cause: options},\n )\n }\n if (typeof options.stega !== 'boolean') {\n throw new Error(\n `sanityFetch() requires an explicit \\`stega\\` option (true or false) when \\`strict: true\\` is set on \\`defineLive\\`.\\n\\nMore information: ${generateHelpUrl('next-sanity-fetch-strict')}`,\n {cause: options},\n )\n }\n}\n","import type {ClientPerspective} from '@sanity/client'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport type {cookies} from 'next/headers'\n\nimport {sanitizePerspective} from '#live/sanitizePerspective'\n\n/**\n * This helper is intended for use with Next.js Cache Components (`cacheComponents: true`),\n * where `cookies()` and `draftMode()` cannot be called inside `'use cache'` boundaries.\n * Resolve the perspective once outside the cache boundary and pass it in as a prop / cache key.\n *\n * The caller is responsible for awaiting `cookies()` from `next/headers` and passing the\n * resulting cookie store as the `cookies` option — this keeps the helper free of dynamic APIs\n * so it can be invoked from anywhere a `ReadonlyRequestCookies` instance is available.\n *\n * @example\n * ```ts\n * import {cookies} from 'next/headers'\n * import {resolvePerspectiveFromCookies} from 'next-sanity/live'\n *\n * const perspective = await resolvePerspectiveFromCookies({cookies: await cookies()})\n * ```\n *\n * @public\n */\nexport type ResolvePerspectiveFromCookies = (options: {\n cookies: Awaited<ReturnType<typeof cookies>>\n}) => Promise<Exclude<ClientPerspective, 'raw'>>\n\nexport const resolvePerspectiveFromCookies:ResolvePerspectiveFromCookies = async function resolvePerspectiveFromCookies({\n cookies: jar,\n}: {\n cookies: Awaited<ReturnType<typeof cookies>>\n}): Promise<Exclude<ClientPerspective, 'raw'>> {\n return jar.has(perspectiveCookieName)\n ? sanitizePerspective(jar.get(perspectiveCookieName)?.value, 'drafts')\n : 'drafts'\n}\n"],"mappings":";;;AAEA,SAAgB,8BAA8B,OAAwC;AACpF,KAAI,OAAO,MAAM,kBAAkB,UACjC,OAAM,IAAI,MACR,iJAAiJ,gBAAgB,0BAA0B,IAC3L,EAAC,OAAO,OAAM,CACf;;AAIL,SAAgB,2BAA2B,SAGlC;AACP,KAAI,OAAO,QAAQ,gBAAgB,eAAe,QAAQ,gBAAgB,KACxE,OAAM,IAAI,MACR,kIAAkI,gBAAgB,2BAA2B,IAC7K,EAAC,OAAO,SAAQ,CACjB;AAEH,KAAI,OAAO,QAAQ,UAAU,UAC3B,OAAM,IAAI,MACR,4IAA4I,gBAAgB,2BAA2B,IACvL,EAAC,OAAO,SAAQ,CACjB;;ACIL,MAAa,gCAA+D,eAAe,8BAA8B,EACvH,SAAS,OAGoC;AAC7C,QAAO,IAAI,IAAI,sBAAsB,GACjC,oBAAoB,IAAI,IAAI,sBAAsB,EAAE,OAAO,SAAS,GACpE"}
|
package/dist/types.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { ClientPerspective, ClientReturn, ContentSourceMap, LiveEvent, QueryPara
|
|
|
3
3
|
* Perspectives supported by Sanity Live.
|
|
4
4
|
* Using the legacy `'raw'` perspective is not supported and leads to undefined behavior.
|
|
5
5
|
*/
|
|
6
|
-
type
|
|
6
|
+
type LivePerspective = Exclude<ClientPerspective, "raw">;
|
|
7
7
|
/**
|
|
8
8
|
* TODO: docs
|
|
9
9
|
*/
|
|
@@ -13,7 +13,7 @@ type DefinedFetchType = <const QueryString extends string>(options: {
|
|
|
13
13
|
/**
|
|
14
14
|
* @defaultValue 'published'
|
|
15
15
|
*/
|
|
16
|
-
perspective?:
|
|
16
|
+
perspective?: LivePerspective;
|
|
17
17
|
/**
|
|
18
18
|
* Enables stega encoding of the data, this is typically only used in draft mode in conjunction with `perspective: 'drafts'` and with `@sanity/visual-editing` setup.
|
|
19
19
|
* @defaultValue `false`
|
|
@@ -173,7 +173,7 @@ interface StrictDefinedLiveProps extends Omit<DefinedLiveProps, "includeDrafts">
|
|
|
173
173
|
type StrictDefinedFetchType = <const QueryString extends string>(options: {
|
|
174
174
|
query: QueryString;
|
|
175
175
|
params?: QueryParams | Promise<QueryParams>;
|
|
176
|
-
perspective:
|
|
176
|
+
perspective: LivePerspective;
|
|
177
177
|
stega: boolean;
|
|
178
178
|
tags?: string[];
|
|
179
179
|
requestTag?: string;
|
|
@@ -182,5 +182,5 @@ type StrictDefinedFetchType = <const QueryString extends string>(options: {
|
|
|
182
182
|
sourceMap: ContentSourceMap | null;
|
|
183
183
|
tags: string[];
|
|
184
184
|
}>;
|
|
185
|
-
export { SanityLiveAction as a, SanityLiveOnReconnect as c, StrictDefinedFetchType as d, StrictDefinedLiveProps as f,
|
|
185
|
+
export { SanityLiveAction as a, SanityLiveOnReconnect as c, StrictDefinedFetchType as d, StrictDefinedLiveProps as f, LivePerspective as i, SanityLiveOnRestart as l, DefinedFetchType as n, SanityLiveOnError as o, DefinedLiveProps as r, SanityLiveOnGoaway as s, DefineLiveOptions as t, SanityLiveOnWelcome as u };
|
|
186
186
|
//# sourceMappingURL=types.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/visual-editing/client-component/VisualEditing.tsx","../../../src/visual-editing/client-component/index.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/visual-editing/client-component/VisualEditing.tsx","../../../src/visual-editing/client-component/index.ts"],"mappings":";;AAeA;;UAAiB,kBAAA,SAA2B,IAAA,CAAK,oBAAA;EAAL;;;EAI1C,OAAA;;;;;;ACbF;;EDqBE,QAAA;ECrBgC;;;;;;;ED6BhC,aAAA;AAAA;AAAA,cC7BW,aAAA,EAAe,KAAA,CAAM,aAAA,CAAc,kBAAA"}
|
|
@@ -1,12 +1,7 @@
|
|
|
1
|
-
import { HistoryRefresh } from "@sanity/visual-editing/react";
|
|
2
1
|
import { ClientPerspective } from "@sanity/client";
|
|
3
2
|
/**
|
|
4
3
|
* @internal CAUTION: this is an internal action and does not follow semver. Using it directly is at your own risk.
|
|
5
4
|
*/
|
|
6
|
-
declare function actionRefresh(_payload: HistoryRefresh): Promise<void>;
|
|
7
|
-
/**
|
|
8
|
-
* @internal CAUTION: this is an internal action and does not follow semver. Using it directly is at your own risk.
|
|
9
|
-
*/
|
|
10
5
|
declare function actionPerspectiveChange(perspective: ClientPerspective): Promise<void>;
|
|
11
|
-
export { actionPerspectiveChange
|
|
6
|
+
export { actionPerspectiveChange };
|
|
12
7
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/visual-editing/server-actions/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/visual-editing/server-actions/index.ts"],"mappings":";;AAYA;;iBAAsB,uBAAA,CAAwB,WAAA,EAAa,iBAAA,GAAoB,OAAA"}
|
|
@@ -6,12 +6,6 @@ import { refresh } from "next/cache";
|
|
|
6
6
|
/**
|
|
7
7
|
* @internal CAUTION: this is an internal action and does not follow semver. Using it directly is at your own risk.
|
|
8
8
|
*/
|
|
9
|
-
async function actionRefresh(_payload) {
|
|
10
|
-
refresh();
|
|
11
|
-
}
|
|
12
|
-
/**
|
|
13
|
-
* @internal CAUTION: this is an internal action and does not follow semver. Using it directly is at your own risk.
|
|
14
|
-
*/
|
|
15
9
|
async function actionPerspectiveChange(perspective) {
|
|
16
10
|
const sanitizedPerspective = sanitizePerspective(perspective, "drafts");
|
|
17
11
|
if (!sanitizedPerspective || Array.isArray(sanitizedPerspective) && sanitizedPerspective.length === 0) throw new Error(`Invalid perspective`, { cause: perspective });
|
|
@@ -29,6 +23,6 @@ async function actionPerspectiveChange(perspective) {
|
|
|
29
23
|
});
|
|
30
24
|
refresh();
|
|
31
25
|
}
|
|
32
|
-
export { actionPerspectiveChange
|
|
26
|
+
export { actionPerspectiveChange };
|
|
33
27
|
|
|
34
28
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/visual-editing/server-actions/index.ts"],"sourcesContent":["'use server'\n\nimport type {ClientPerspective} from '@sanity/client'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/visual-editing/server-actions/index.ts"],"sourcesContent":["'use server'\n\nimport type {ClientPerspective} from '@sanity/client'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {refresh} from 'next/cache'\nimport {cookies} from 'next/headers'\n\nimport {sanitizePerspective} from '#live/sanitizePerspective'\n\n/**\n * @internal CAUTION: this is an internal action and does not follow semver. Using it directly is at your own risk.\n */\nexport async function actionPerspectiveChange(perspective: ClientPerspective): Promise<void> {\n const sanitizedPerspective = sanitizePerspective(perspective, 'drafts')\n if (\n !sanitizedPerspective ||\n (Array.isArray(sanitizedPerspective) && sanitizedPerspective.length === 0)\n ) {\n throw new Error(`Invalid perspective`, {cause: perspective})\n }\n\n const nextPerspective = Array.isArray(sanitizedPerspective)\n ? sanitizedPerspective.join(',')\n : sanitizedPerspective\n const jar = await cookies()\n if (\n nextPerspective === jar.get(perspectiveCookieName)?.value &&\n process.env.NODE_ENV !== 'production'\n ) {\n // oxlint-disable-next-line no-console\n console.debug('actionPerspectiveChange', 'Perspective is the same, skipping', nextPerspective)\n return\n }\n jar.set(perspectiveCookieName, nextPerspective, {\n httpOnly: true,\n path: '/',\n secure: true,\n sameSite: 'none',\n })\n\n refresh()\n}\n"],"mappings":";;;;;;;;AAYA,eAAsB,wBAAwB,aAA+C;CAC3F,MAAM,uBAAuB,oBAAoB,aAAa,SAAS;AACvE,KACE,CAAC,wBACA,MAAM,QAAQ,qBAAqB,IAAI,qBAAqB,WAAW,EAExE,OAAM,IAAI,MAAM,uBAAuB,EAAC,OAAO,aAAY,CAAC;CAG9D,MAAM,kBAAkB,MAAM,QAAQ,qBAAqB,GACvD,qBAAqB,KAAK,IAAI,GAC9B;CACJ,MAAM,MAAM,MAAM,SAAS;AAC3B,KACE,oBAAoB,IAAI,IAAI,sBAAsB,EAAE,SACpD,QAAQ,IAAI,aAAa,cACzB;AAEA,UAAQ,MAAM,2BAA2B,qCAAqC,gBAAgB;AAC9F;;AAEF,KAAI,IAAI,uBAAuB,iBAAiB;EAC9C,UAAU;EACV,MAAM;EACN,QAAQ;EACR,UAAU;EACX,CAAC;AAEF,UAAS"}
|