next-sanity 13.0.0-cache-components.7 → 13.0.0-cache-components.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/LICENSE +1 -1
  2. package/dist/PresentationComlink.js +6 -6
  3. package/dist/PresentationComlink.js.map +1 -1
  4. package/dist/PresentationComlink2.js +7 -7
  5. package/dist/PresentationComlink2.js.map +1 -1
  6. package/dist/defineLive.d.ts +1 -142
  7. package/dist/defineLive.d.ts.map +1 -1
  8. package/dist/experimental/client-components/live.d.ts +2 -4
  9. package/dist/experimental/client-components/live.d.ts.map +1 -1
  10. package/dist/experimental/client-components/live.js +8 -7
  11. package/dist/experimental/client-components/live.js.map +1 -1
  12. package/dist/hooks/index.d.ts +1 -4
  13. package/dist/hooks/index.d.ts.map +1 -1
  14. package/dist/hooks/index.js +1 -1
  15. package/dist/index.d.ts +1 -1
  16. package/dist/index.js +1 -1
  17. package/dist/live/client-components/live/index.js +3 -3
  18. package/dist/live/server-actions/index.d.ts +2 -1
  19. package/dist/live/server-actions/index.d.ts.map +1 -1
  20. package/dist/live/server-actions/index.js +17 -3
  21. package/dist/live/server-actions/index.js.map +1 -1
  22. package/dist/live.d.ts +5 -3
  23. package/dist/live.d.ts.map +1 -1
  24. package/dist/live.js +1 -1
  25. package/dist/live.next-js.d.ts +5 -3
  26. package/dist/live.next-js.d.ts.map +1 -1
  27. package/dist/live.next-js.js +5 -20
  28. package/dist/live.next-js.js.map +1 -1
  29. package/dist/live.react-server.d.ts +5 -3
  30. package/dist/live.react-server.js +3 -3
  31. package/package.json +6 -8
  32. package/dist/context.js +0 -29
  33. package/dist/context.js.map +0 -1
  34. package/dist/isCorsOriginError.d.ts +0 -5
  35. package/dist/isCorsOriginError.d.ts.map +0 -1
  36. package/dist/isCorsOriginError.js +0 -6
  37. package/dist/isCorsOriginError.js.map +0 -1
  38. package/dist/resolvePerspectiveFromCookies.js +0 -8
  39. package/dist/resolvePerspectiveFromCookies.js.map +0 -1
  40. package/dist/sanitizePerspective.js +0 -14
  41. package/dist/sanitizePerspective.js.map +0 -1
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2025 Sanity.io
3
+ Copyright (c) 2026 Sanity.io
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -1,7 +1,7 @@
1
- import { f as setPerspective, l as setComlink, s as perspective, u as setComlinkClientConfig } from "./context.js";
2
- import { t as sanitizePerspective } from "./sanitizePerspective.js";
3
1
  import { useRouter } from "next/navigation";
2
+ import { perspective, setComlink, setComlinkClientConfig, setPerspective } from "#client-components/context";
4
3
  import { startTransition, useEffect, useEffectEvent } from "react";
4
+ import { sanitizePerspective } from "#live/sanitizePerspective";
5
5
  import { createCompatibilityActors } from "@sanity/presentation-comlink";
6
6
  import { setPerspectiveCookie } from "next-sanity/live/server-actions";
7
7
  import { createNode, createNodeMachine } from "@sanity/comlink";
@@ -22,18 +22,18 @@ function PresentationComlink(props) {
22
22
  }
23
23
  });
24
24
  useEffect(() => {
25
- const comlink = createNode({
25
+ const comlink$1 = createNode({
26
26
  name: "loaders",
27
27
  connectTo: "presentation"
28
28
  }, createNodeMachine().provide({ actors: createCompatibilityActors() }));
29
29
  let controller;
30
- comlink.on("loader/perspective", (data) => {
30
+ comlink$1.on("loader/perspective", (data) => {
31
31
  controller?.abort();
32
32
  controller = new AbortController();
33
33
  handlePerspectiveChange(data.perspective, controller.signal);
34
34
  });
35
- const stop = comlink.start();
36
- setComlink(comlink);
35
+ const stop = comlink$1.start();
36
+ setComlink(comlink$1);
37
37
  return () => {
38
38
  stop();
39
39
  };
@@ -1 +1 @@
1
- {"version":3,"file":"PresentationComlink.js","names":["controller: AbortController | undefined"],"sources":["../src/experimental/client-components/PresentationComlink.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\n\nimport {\n setComlink,\n setComlinkClientConfig,\n setPerspective,\n perspective,\n} from '#client-components/context'\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {createNode, createNodeMachine} from '@sanity/comlink'\nimport {\n createCompatibilityActors,\n type LoaderControllerMsg,\n type LoaderNodeMsg,\n} from '@sanity/presentation-comlink'\nimport {setPerspectiveCookie} from 'next-sanity/live/server-actions'\nimport {useRouter} from 'next/navigation'\nimport {startTransition, useEffect, useEffectEvent} from 'react'\n\nexport default function PresentationComlink(props: {\n projectId: string\n dataset: string\n draftModeEnabled: boolean\n}): React.JSX.Element | null {\n const {projectId, dataset, draftModeEnabled} = props\n const router = useRouter()\n\n useEffect(() => {\n setComlinkClientConfig(projectId, dataset)\n }, [dataset, projectId])\n\n const handlePerspectiveChange = useEffectEvent(\n (_perspective: ClientPerspective, signal: AbortSignal) => {\n const nextPerspective = sanitizePerspective(_perspective, 'drafts')\n if (draftModeEnabled && perspective.toString() !== nextPerspective.toString()) {\n setPerspective(nextPerspective)\n startTransition(() =>\n setPerspectiveCookie(nextPerspective)\n .then(() => {\n if (signal.aborted) return\n router.refresh()\n })\n .catch((reason) =>\n console.error('Failed to set the preview perspective cookie', reason),\n ),\n )\n }\n },\n )\n\n useEffect(() => {\n const comlink = createNode<LoaderNodeMsg, LoaderControllerMsg>(\n {name: 'loaders', connectTo: 'presentation'},\n createNodeMachine<LoaderNodeMsg, LoaderControllerMsg>().provide({\n actors: createCompatibilityActors<LoaderNodeMsg>(),\n }),\n )\n\n let controller: AbortController | undefined\n comlink.on('loader/perspective', (data) => {\n controller?.abort()\n controller = new AbortController()\n handlePerspectiveChange(data.perspective, controller.signal)\n })\n\n const stop = comlink.start()\n setComlink(comlink)\n return () => {\n stop()\n }\n }, [])\n\n return null\n}\n"],"mappings":";;;;;;;AAmBA,SAAwB,oBAAoB,OAIf;CAC3B,MAAM,EAAC,WAAW,SAAS,qBAAoB;CAC/C,MAAM,SAAS,WAAW;AAE1B,iBAAgB;AACd,yBAAuB,WAAW,QAAQ;IACzC,CAAC,SAAS,UAAU,CAAC;CAExB,MAAM,0BAA0B,gBAC7B,cAAiC,WAAwB;EACxD,MAAM,kBAAkB,oBAAoB,cAAc,SAAS;AACnE,MAAI,oBAAoB,YAAY,UAAU,KAAK,gBAAgB,UAAU,EAAE;AAC7E,kBAAe,gBAAgB;AAC/B,yBACE,qBAAqB,gBAAgB,CAClC,WAAW;AACV,QAAI,OAAO,QAAS;AACpB,WAAO,SAAS;KAChB,CACD,OAAO,WACN,QAAQ,MAAM,gDAAgD,OAAO,CACtE,CACJ;;GAGN;AAED,iBAAgB;EACd,MAAM,UAAU,WACd;GAAC,MAAM;GAAW,WAAW;GAAe,EAC5C,mBAAuD,CAAC,QAAQ,EAC9D,QAAQ,2BAA0C,EACnD,CAAC,CACH;EAED,IAAIA;AACJ,UAAQ,GAAG,uBAAuB,SAAS;AACzC,eAAY,OAAO;AACnB,gBAAa,IAAI,iBAAiB;AAClC,2BAAwB,KAAK,aAAa,WAAW,OAAO;IAC5D;EAEF,MAAM,OAAO,QAAQ,OAAO;AAC5B,aAAW,QAAQ;AACnB,eAAa;AACX,SAAM;;IAEP,EAAE,CAAC;AAEN,QAAO"}
1
+ {"version":3,"file":"PresentationComlink.js","names":["comlink","controller: AbortController | undefined"],"sources":["../src/experimental/client-components/PresentationComlink.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\n\nimport {\n setComlink,\n setComlinkClientConfig,\n setPerspective,\n perspective,\n} from '#client-components/context'\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {createNode, createNodeMachine} from '@sanity/comlink'\nimport {\n createCompatibilityActors,\n type LoaderControllerMsg,\n type LoaderNodeMsg,\n} from '@sanity/presentation-comlink'\nimport {setPerspectiveCookie} from 'next-sanity/live/server-actions'\nimport {useRouter} from 'next/navigation'\nimport {startTransition, useEffect, useEffectEvent} from 'react'\n\nexport default function PresentationComlink(props: {\n projectId: string\n dataset: string\n draftModeEnabled: boolean\n}): React.JSX.Element | null {\n const {projectId, dataset, draftModeEnabled} = props\n const router = useRouter()\n\n useEffect(() => {\n setComlinkClientConfig(projectId, dataset)\n }, [dataset, projectId])\n\n const handlePerspectiveChange = useEffectEvent(\n (_perspective: ClientPerspective, signal: AbortSignal) => {\n const nextPerspective = sanitizePerspective(_perspective, 'drafts')\n if (draftModeEnabled && perspective.toString() !== nextPerspective.toString()) {\n setPerspective(nextPerspective)\n startTransition(() =>\n setPerspectiveCookie(nextPerspective)\n .then(() => {\n if (signal.aborted) return\n router.refresh()\n })\n .catch((reason) =>\n console.error('Failed to set the preview perspective cookie', reason),\n ),\n )\n }\n },\n )\n\n useEffect(() => {\n const comlink = createNode<LoaderNodeMsg, LoaderControllerMsg>(\n {name: 'loaders', connectTo: 'presentation'},\n createNodeMachine<LoaderNodeMsg, LoaderControllerMsg>().provide({\n actors: createCompatibilityActors<LoaderNodeMsg>(),\n }),\n )\n\n let controller: AbortController | undefined\n comlink.on('loader/perspective', (data) => {\n controller?.abort()\n controller = new AbortController()\n handlePerspectiveChange(data.perspective, controller.signal)\n })\n\n const stop = comlink.start()\n setComlink(comlink)\n return () => {\n stop()\n }\n }, [])\n\n return null\n}\n"],"mappings":";;;;;;;AAmBA,SAAwB,oBAAoB,OAIf;CAC3B,MAAM,EAAC,WAAW,SAAS,qBAAoB;CAC/C,MAAM,SAAS,WAAW;AAE1B,iBAAgB;AACd,yBAAuB,WAAW,QAAQ;IACzC,CAAC,SAAS,UAAU,CAAC;CAExB,MAAM,0BAA0B,gBAC7B,cAAiC,WAAwB;EACxD,MAAM,kBAAkB,oBAAoB,cAAc,SAAS;AACnE,MAAI,oBAAoB,YAAY,UAAU,KAAK,gBAAgB,UAAU,EAAE;AAC7E,kBAAe,gBAAgB;AAC/B,yBACE,qBAAqB,gBAAgB,CAClC,WAAW;AACV,QAAI,OAAO,QAAS;AACpB,WAAO,SAAS;KAChB,CACD,OAAO,WACN,QAAQ,MAAM,gDAAgD,OAAO,CACtE,CACJ;;GAGN;AAED,iBAAgB;EACd,MAAMA,YAAU,WACd;GAAC,MAAM;GAAW,WAAW;GAAe,EAC5C,mBAAuD,CAAC,QAAQ,EAC9D,QAAQ,2BAA0C,EACnD,CAAC,CACH;EAED,IAAIC;AACJ,YAAQ,GAAG,uBAAuB,SAAS;AACzC,eAAY,OAAO;AACnB,gBAAa,IAAI,iBAAiB;AAClC,2BAAwB,KAAK,aAAa,WAAW,OAAO;IAC5D;EAEF,MAAM,OAAOD,UAAQ,OAAO;AAC5B,aAAWA,UAAQ;AACnB,eAAa;AACX,SAAM;;IAEP,EAAE,CAAC;AAEN,QAAO"}
@@ -1,5 +1,5 @@
1
- import { l as setComlink, u as setComlinkClientConfig } from "./context.js";
2
1
  import { useRouter } from "next/navigation";
2
+ import { setComlink, setComlinkClientConfig } from "#client-components/context";
3
3
  import { useEffect, useEffectEvent } from "react";
4
4
  import { createCompatibilityActors } from "@sanity/presentation-comlink";
5
5
  import { setPerspectiveCookie } from "next-sanity/live/server-actions";
@@ -10,25 +10,25 @@ function PresentationComlink(props) {
10
10
  useEffect(() => {
11
11
  setComlinkClientConfig(projectId, dataset);
12
12
  }, [dataset, projectId]);
13
- const handlePerspectiveChange = useEffectEvent((perspective, signal) => {
14
- if (draftModeEnabled && perspective !== draftModePerspective) setPerspectiveCookie(perspective).then(() => {
13
+ const handlePerspectiveChange = useEffectEvent((perspective$1, signal) => {
14
+ if (draftModeEnabled && perspective$1 !== draftModePerspective) setPerspectiveCookie(perspective$1).then(() => {
15
15
  if (signal.aborted) return;
16
16
  router.refresh();
17
17
  }).catch((reason) => console.error("Failed to set the preview perspective cookie", reason));
18
18
  });
19
19
  useEffect(() => {
20
- const comlink = createNode({
20
+ const comlink$1 = createNode({
21
21
  name: "loaders",
22
22
  connectTo: "presentation"
23
23
  }, createNodeMachine().provide({ actors: createCompatibilityActors() }));
24
24
  let controller;
25
- comlink.on("loader/perspective", (data) => {
25
+ comlink$1.on("loader/perspective", (data) => {
26
26
  controller?.abort();
27
27
  controller = new AbortController();
28
28
  handlePerspectiveChange(data.perspective, controller.signal);
29
29
  });
30
- const stop = comlink.start();
31
- setComlink(comlink);
30
+ const stop = comlink$1.start();
31
+ setComlink(comlink$1);
32
32
  return () => {
33
33
  stop();
34
34
  };
@@ -1 +1 @@
1
- {"version":3,"file":"PresentationComlink2.js","names":["controller: AbortController | undefined"],"sources":["../src/live/client-components/live/PresentationComlink.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\n\nimport {\n createNode,\n createNodeMachine,\n // type Node,\n} from '@sanity/comlink'\nimport {setComlink, setComlinkClientConfig} from '#client-components/context'\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\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,IAAIA;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;AAElC,IAAA,8BAAe"}
1
+ {"version":3,"file":"PresentationComlink2.js","names":["perspective","comlink","controller: AbortController | undefined"],"sources":["../src/live/client-components/live/PresentationComlink.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\n\nimport {\n createNode,\n createNodeMachine,\n // type Node,\n} from '@sanity/comlink'\nimport {setComlink, setComlinkClientConfig} from '#client-components/context'\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\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,eAAgC,WAAwB;AACvD,MAAI,oBAAoBA,kBAAgB,qBACtC,sBAAqBA,cAAY,CAC9B,WAAW;AACV,OAAI,OAAO,QAAS;AACpB,UAAO,SAAS;IAChB,CACD,OAAO,WAAW,QAAQ,MAAM,gDAAgD,OAAO,CAAC;GAGhG;AAGD,iBAAgB;EACd,MAAMC,YAAU,WACd;GACE,MAAM;GACN,WAAW;GACZ,EACD,mBAAuD,CAAC,QAAQ,EAC9D,QAAQ,2BAA0C,EACnD,CAAC,CACH;EAMD,IAAIC;AACJ,YAAQ,GAAG,uBAAuB,SAAS;AACzC,eAAY,OAAO;AACnB,gBAAa,IAAI,iBAAiB;AAClC,2BAAwB,KAAK,aAAa,WAAW,OAAO;IAC5D;EAEF,MAAM,OAAOD,UAAQ,OAAO;AAE5B,aAAWA,UAAQ;AAEnB,eAAa;AAEX,SAAM;;IAEP,EAAE,CAAC;AA0CN,QAAO;;AAET,oBAAoB,cAAc;AAElC,IAAA,8BAAe"}
@@ -1,145 +1,4 @@
1
- import { cookies } from "next/headers";
2
1
  import { ClientPerspective, ClientReturn, ContentSourceMap, LiveEventGoAway, QueryParams, SanityClient, SyncTag } from "@sanity/client";
3
- import { ClientPerspective as ClientPerspective$1, ClientReturn as ClientReturn$1, ContentSourceMap as ContentSourceMap$1, LiveEventGoAway as LiveEventGoAway$1, QueryParams as QueryParams$1, SanityClient as SanityClient$1 } from "next-sanity";
4
- type ResolvePerspectiveFromCookies = (options: {
5
- /**
6
- * You must await the cookies() function from next/headers
7
- * and pass it here.
8
- * Example:
9
- * ```ts
10
- * import { cookies } from 'next/headers'
11
- *
12
- * const perspective = await resolvePerspectiveFromCookies({cookies: await cookies()})
13
- * ```
14
- */
15
- cookies: Awaited<ReturnType<typeof cookies>>;
16
- }) => Promise<Exclude<ClientPerspective, "raw">>;
17
- /**
18
- * Resolves the perspective from the cookie that is set by `import { defineEnableDraftMode } from "next-sanity/draft-mode"`
19
- * @public
20
- */
21
- declare const resolvePerspectiveFromCookies: ({
22
- cookies: jar
23
- }: {
24
- cookies: Awaited<ReturnType<typeof cookies>>;
25
- }) => Promise<Exclude<ClientPerspective, "raw">>;
26
- /**
27
- * Perspectives supported by Sanity Live.
28
- * Using the legacy `'raw'` perspective is not supported and leads to undefined behavior.
29
- */
30
- type PerspectiveType = Exclude<ClientPerspective$1, "raw">;
31
- /**
32
- * TODO: docs
33
- */
34
- type DefinedFetchType = <const QueryString extends string>(options: {
35
- query: QueryString;
36
- params?: QueryParams$1;
37
- /**
38
- * @defaultValue 'published'
39
- */
40
- perspective?: PerspectiveType;
41
- /**
42
- * 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.
43
- * @defaultValue `false`
44
- */
45
- stega?: boolean;
46
- /**
47
- * Custom cache tags that can be used with next's `updateTag` functions for custom `read-your-write` server actions,
48
- * for example a like button that uses client.mutate to update a document and then immediately shows the result.
49
- */
50
- tags?: string[];
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.fetch'
55
- */
56
- requestTag?: string;
57
- }) => Promise<{
58
- data: ClientReturn$1<QueryString, unknown>;
59
- sourceMap: ContentSourceMap$1 | null;
60
- tags: string[];
61
- }>;
62
- interface DefinedLiveProps {
63
- /**
64
- * TODO: should match the `perspective` you give `defineLive().fetch()`, setting it to a value other than `"published"`
65
- * and with `browserToken` set will cause it to subscribe to draft content changes as well as published content.
66
- */
67
- perspective?: PerspectiveType;
68
- /**
69
- * TODO: If Presentation Tool is present this event will fire with the current `perspective` stack used in the
70
- * Sanity Studio global perspective menu. The default event handler will store this state in a cookie,
71
- * which can be read with `resolvePerspectiveFromCookies` and used to ensure data fetching in the preview
72
- * matches the perspective and content viewed in the Studio, allowing you to quickly switch and preview different perspectives.
73
- */
74
- onStudioPerspective?: (perspective: PerspectiveType) => void;
75
- /**
76
- * Automatic refresh of RSC when the component <SanityLive /> is mounted.
77
- * @defaultValue `false`
78
- */
79
- refreshOnMount?: boolean;
80
- /**
81
- * Automatically refresh when window gets focused
82
- * @defaultValue `false`
83
- */
84
- refreshOnFocus?: boolean;
85
- /**
86
- * Automatically refresh when the browser regains a network connection (via navigator.onLine)
87
- * @defaultValue `false`
88
- */
89
- refreshOnReconnect?: boolean;
90
- /**
91
- * Automatically refresh on an interval when the Live Event API emits a `goaway` event, which indicates that the connection is rejected or closed.
92
- * This typically happens if the connection limit is reached, or if the connection is idle for too long.
93
- * To disable this long polling fallback behavior set `intervalOnGoAway` to `false` or `0`.
94
- * You can also use `onGoAway` to handle the `goaway` event in your own way, and read the reason why the event was emitted.
95
- * @defaultValue `30_000` 30 seconds interval
96
- */
97
- intervalOnGoAway?: number | false;
98
- /**
99
- * This request tag is used to identify the request when viewing request logs from your Sanity Content Lake.
100
- * @see https://www.sanity.io/docs/reference-api-request-tags
101
- * @defaultValue 'next-loader.live'
102
- */
103
- requestTag?: string;
104
- /**
105
- * Handle errors from the Live Events subscription.
106
- * By default it's reported using `console.error`, you can override this prop to handle it in your own way.
107
- */
108
- onError?: (error: unknown) => void;
109
- /**
110
- * Handle the `goaway` event if the connection is rejected/closed.
111
- * `event.reason` will be a string of why the event was emitted, for example `'connection limit reached'`.
112
- * 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.
113
- * If you want to disable long polling set `intervalOnGoAway` to `false` or `0`.
114
- */
115
- onGoAway?: (event: LiveEventGoAway$1, intervalOnGoAway: number | false) => void;
116
- /**
117
- * TODO: docs, this handles events for published content only, and can be used to revalidate content for all your users when in presentation tool
118
- */
119
- onChange?: (tags: string[]) => Promise<void | "refresh">;
120
- /**
121
- * TODO: docs, this handles events for all changes, published, drafts and even version documents in content releases.
122
- * It's only used when `browserToken` is provided, and the `perspective` prop is other than `"published"`.
123
- * Wether you should just `refresh()` or use `updateTag` to expire tags depends on how you fetch draft content and wether it's cached or not.
124
- */
125
- onChangeIncludingDrafts?: (tags: string[]) => Promise<void | "refresh">;
126
- }
127
- interface LiveOptions {
128
- /**
129
- * Required for `fetch()` and `<Live>` to work
130
- */
131
- client: SanityClient$1;
132
- /**
133
- * Optional. If provided then the token needs to have permissions to query documents with `drafts.` prefixes in order for `perspective: 'drafts'` to work.
134
- * This token is never shared with the browser, unless you reuse it in `browserToken`..
135
- */
136
- serverToken?: string | false;
137
- /**
138
- * Optional. This token is shared with the browser when `<Live>` is given a `perspective` prop other than `"published"`, and should only have access to query published documents.
139
- * It is used to setup a `Live Draft Content` EventSource connection, and enables live previewing drafts stand-alone, outside of Presentation Tool.
140
- */
141
- browserToken?: string | false;
142
- }
143
2
  /**
144
3
  * @public
145
4
  */
@@ -264,5 +123,5 @@ declare function defineLive(config: DefineSanityLiveOptions): {
264
123
  */
265
124
  SanityLive: React.ComponentType<DefinedSanityLiveProps>;
266
125
  };
267
- export { DefinedFetchType as a, PerspectiveType as c, defineLive as i, ResolvePerspectiveFromCookies as l, DefinedSanityFetchType as n, DefinedLiveProps as o, DefinedSanityLiveProps as r, LiveOptions as s, DefineSanityLiveOptions as t, resolvePerspectiveFromCookies as u };
126
+ export { defineLive as i, DefinedSanityFetchType as n, DefinedSanityLiveProps as r, DefineSanityLiveOptions as t };
268
127
  //# sourceMappingURL=defineLive.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"defineLive.d.ts","names":[],"sources":["../src/shared/live/resolvePerspectiveFromCookies.ts","../src/shared/live/types.ts","../src/live/defineLive.tsx"],"sourcesContent":[],"mappings":";;;KAMY,6BAAA;;AAAZ;;;;;;;;AAkBA;EACW,OAAA,EARA,OAQA,CARQ,UAQR,CAAA,OAR0B,OAQ1B,CAAA,CAAA;CAE0B,EAAA,GAT/B,OAS+B,CATvB,OASuB,CATf,iBASe,EAAA,KAAA,CAAA,CAAA;;;;;AACjC,cAJS,6BAIT,EAAA,CAAA;EAAA,OAAA,EAHO;CAGP,EAAA;EAAA,OAAA,EADO,OACP,CADe,UACf,CAAA,OADiC,OACjC,CAAA,CAAA;MAAA,QAAQ,QAAQ;;;;AAtBpB;AAWqC,KCJzB,eAAA,GAAkB,ODIO,CCJC,mBDID,EAAA,KAAA,CAAA;;;;AACvB,KCAF,gBAAA,GDAE,CAAA,0BAAA,MAAA,CAAA,CAAA,OAAA,EAAA;EAAR,KAAA,ECCG,WDDH;EAAA,MAAA,CAAA,ECEK,aDFL;EAMN;;;EAGmB,WAAA,CAAA,ECHH,eDGG;EAAR;;;;EACP,KAAA,CAAA,EAAA,OAAA;;ACfJ;AAKA;;EAEW,IAAA,CAAA,EAAA,MAAA,EAAA;EAIK;;;;;EAiBV,UAAA,CAAA,EAAA,MAAA;AAMN,CAAA,EAAA,GANM,OAMW,CAAA;EAKD,IAAA,EAVR,cAUQ,CAVK,WAUL,EAAA,OAAA,CAAA;EAQsB,SAAA,EAjBzB,kBAiByB,GAAA,IAAA;EA6CjB,IAAA,EAAA,MAAA,EAAA;CAKY,CAAA;AAOe,UAtE/B,gBAAA,CAsE+B;EAAA;AAGhD;;ACpGA;EACS,WAAA,CAAA,ED+BO,eC/BP;EACE;;;;;;EAiBH,mBAAA,CAAA,EAAA,CAAA,WAAA,EDqB8B,eCrB9B,EAAA,GAAA,IAAA;EACK;;;AAOb;EA+CqB,cAA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ings":";;AAoBA;;AAEW,KAFC,sBAAA,GAED,CAAA,0BAAA,MAAA,CAAA,CAAA,OAAA,EAAA;EAAsB,KAAA,EADxB,WACwB;EAAR,MAAA,CAAA,EAAd,WAAc,GAAA,OAAA,CAAQ,WAAR,CAAA;EAQD;;;;;;EAQlB,IAAA,CAAA,EAAA,MAAA,EAAA;EASN,WAAiB,CAAA,EAjBD,OAiBC,CAjBO,iBAiBP,EAAA,KAAA,CAAA;EA+CI,KAAA,CAAA,EAAA,OAAA;EAMS;;;AAM9B;AAgCA;EAAmC,UAAA,CAAA,EAAA,MAAA;CAIpB,EAAA,GAxGT,OAwGS,CAAA;EAImB,IAAA,EA3G1B,YA2G0B,CA3Gb,WA2Ga,CAAA;EAApB,SAAM,EA1GP,gBA0GO,GAAA,IAAA;EAAA,IAAA,EAAA,MAAA,EAAA;;;;;UAnGH,sBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA+CI;;;;;8BAMS,cAAc;;;;;UAM3B,uBAAA;;;;UAIP;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA4BM,UAAA,SAAmB;;;;eAIpB;;;;cAID,KAAA,CAAM,cAAc"}
@@ -1,7 +1,5 @@
1
- import { ClientPerspective, InitializedClientConfig, LiveEventGoAway, SyncTag } from "@sanity/client";
1
+ import { ClientPerspective, InitializedClientConfig, LiveEventGoAway } from "@sanity/client";
2
2
  interface SanityClientConfig extends Pick<InitializedClientConfig, "projectId" | "dataset" | "apiHost" | "apiVersion" | "useProjectHostname" | "token" | "requestTagPrefix"> {}
3
- declare const PUBLISHED_SYNC_TAG_PREFIX = "sp:";
4
- declare const DRAFT_SYNC_TAG_PREFIX = "sd:";
5
3
  /**
6
4
  * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.
7
5
  */
@@ -19,7 +17,7 @@ interface SanityLiveProps {
19
17
  onError?: (error: unknown) => void;
20
18
  intervalOnGoAway?: number | false;
21
19
  onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void;
22
- revalidateSyncTags: (tags: `${typeof PUBLISHED_SYNC_TAG_PREFIX | typeof DRAFT_SYNC_TAG_PREFIX}${SyncTag}`[]) => Promise<void | "refresh">;
20
+ revalidateSyncTags?: (tags: string[]) => Promise<void | "refresh">;
23
21
  resolveDraftModePerspective: () => Promise<ClientPerspective>;
24
22
  }
25
23
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"live.d.ts","names":[],"sources":["../../../src/experimental/types.ts","../../../src/experimental/constants.ts","../../../src/experimental/client-components/live.tsx"],"sourcesContent":[],"mappings":";UAEiB,kBAAA,SAA2B,KAC1C;cCHW,yBAAA;cACA,qBAAA;;AADb;AACA;UCmCiB,eAAA;EAAjB,MAAiB,EACP,kBADO;EACP,gBAAA,EAAA,OAAA;EAYW,cAAA,CAAA,EAAA,OAAA;EAED,cAAA,CAAA,EAAA,OAAA;EAAmC,kBAAA,CAAA,EAAA,OAAA;EAAwB,UAAA,EAAA,MAAA,GAAA,SAAA;EACxE;;;;SAmCiB,CAAA,EAAA,CAAA,KAAA,EAAA,OAAA,EAAkB,GAAA,IAAA;;qBAtCrB;uCAED,mCAAmC,wBAAwB,gBACxE;qCAC8B,QAAQ;;;;;iBAkCrB,UAAA,QAAkB,kBAAkB,KAAA,CAAM,GAAA,CAAI"}
1
+ {"version":3,"file":"live.d.ts","names":[],"sources":["../../../src/experimental/types.ts","../../../src/experimental/client-components/live.tsx"],"sourcesContent":[],"mappings":";UAEiB,kBAAA,SAA2B,KAC1C;AADF;;ACmCA;AACU,UADO,eAAA,CACP;EAYW,MAAA,EAZX,kBAYW;EACsB,gBAAA,EAAA,OAAA;EACE,cAAA,CAAA,EAAA,OAAA;EAAR,cAAA,CAAA,EAAA,OAAA;EAAA,kBAAA,CAAA,EAAA,OAAA;YAkCb,EAAA,MAAA,GAAA,SAAkB;;;;;;;qBApCrB;2CACsB;qCACN,QAAQ;;;;;iBAkCrB,UAAA,QAAkB,kBAAkB,KAAA,CAAM,GAAA,CAAI"}
@@ -1,13 +1,14 @@
1
1
  "use client";
2
- import { d as setEnvironment, f as setPerspective } from "../../context.js";
3
- import { t as isCorsOriginError } from "../../isCorsOriginError.js";
4
- import { t as sanitizePerspective } from "../../sanitizePerspective.js";
5
2
  import { n as PUBLISHED_SYNC_TAG_PREFIX } from "../../constants.js";
6
3
  import { useRouter } from "next/navigation";
4
+ import { setEnvironment, setPerspective } from "#client-components/context";
7
5
  import { useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
8
6
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
7
+ import { isCorsOriginError } from "#live/isCorsOriginError";
8
+ import { sanitizePerspective } from "#live/sanitizePerspective";
9
9
  import { createClient } from "@sanity/client";
10
10
  import { isMaybePresentation, isMaybePreviewWindow } from "@sanity/presentation-comlink";
11
+ import { expireTags } from "next-sanity/live/server-actions";
11
12
  import dynamic from "next/dynamic";
12
13
  const PresentationComlink = dynamic(() => import("../../PresentationComlink.js"), { ssr: false });
13
14
  const RefreshOnMount = dynamic(() => import("../../RefreshOnMount.js"), { ssr: false });
@@ -22,7 +23,7 @@ function handleOnGoAway(event, intervalOnGoAway) {
22
23
  else console.error("Sanity Live connection closed, automatic revalidation is disabled, the server gave this reason:", event.reason);
23
24
  }
24
25
  function SanityLive(props) {
25
- const { config, draftModeEnabled, refreshOnMount = false, refreshOnFocus = draftModeEnabled ? false : typeof window === "undefined" ? true : window.self === window.top, refreshOnReconnect = true, intervalOnGoAway = 3e4, requestTag = "next-loader.live", onError = handleError, onGoAway = handleOnGoAway, revalidateSyncTags, resolveDraftModePerspective } = props;
26
+ const { config, draftModeEnabled, refreshOnMount = false, refreshOnFocus = draftModeEnabled ? false : typeof window === "undefined" ? true : window.self === window.top, refreshOnReconnect = true, intervalOnGoAway = 3e4, requestTag = "next-loader.live", onError = handleError, onGoAway = handleOnGoAway, revalidateSyncTags: revalidateSyncTags$1 = expireTags, resolveDraftModePerspective } = props;
26
27
  const { projectId, dataset, apiHost, apiVersion, useProjectHostname, token, requestTagPrefix } = config;
27
28
  const client = useMemo(() => createClient({
28
29
  projectId,
@@ -50,7 +51,7 @@ function SanityLive(props) {
50
51
  if (process.env.NODE_ENV !== "production" && event.type === "welcome") {
51
52
  console.info("Sanity is live with", token ? "automatic revalidation for draft content changes as well as published content" : draftModeEnabled ? "automatic revalidation for only published content. Provide a `browserToken` to `defineLive` to support draft content outside of Presentation Tool." : "automatic revalidation of published content");
52
53
  setLongPollingInterval(false);
53
- } else if (event.type === "message") revalidateSyncTags(event.tags.map((tag) => `${PUBLISHED_SYNC_TAG_PREFIX}${tag}`)).then((result) => {
54
+ } else if (event.type === "message") revalidateSyncTags$1(event.tags.map((tag) => `${PUBLISHED_SYNC_TAG_PREFIX}${tag}`)).then((result) => {
54
55
  if (result === "refresh") router.refresh();
55
56
  });
56
57
  else if (event.type === "restart" || event.type === "reconnect") router.refresh();
@@ -102,10 +103,10 @@ function SanityLive(props) {
102
103
  return;
103
104
  }
104
105
  const controller = new AbortController();
105
- resolveDraftModePerspective().then((perspective) => {
106
+ resolveDraftModePerspective().then((perspective$1) => {
106
107
  if (controller.signal.aborted) return;
107
108
  setResolvedInitialPerspective(true);
108
- setPerspective(sanitizePerspective(perspective, "drafts"));
109
+ setPerspective(sanitizePerspective(perspective$1, "drafts"));
109
110
  }).catch((err) => {
110
111
  if (controller.signal.aborted) return;
111
112
  console.error("Failed to resolve draft mode perspective", err);
@@ -1 +1 @@
1
- {"version":3,"file":"live.js","names":[],"sources":["../../../src/experimental/client-components/live.tsx"],"sourcesContent":["'use client'\n\nimport {setEnvironment, setPerspective} from '#client-components/context'\nimport {isCorsOriginError} from '#live/isCorsOriginError'\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {\n createClient,\n type ClientPerspective,\n type LiveEvent,\n type LiveEventGoAway,\n type SyncTag,\n} from '@sanity/client'\nimport {isMaybePresentation, isMaybePreviewWindow} from '@sanity/presentation-comlink'\nimport dynamic from 'next/dynamic'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useMemo, useRef, useState, useEffectEvent} from 'react'\n\nimport type {SanityClientConfig} from '../types'\n\nimport {PUBLISHED_SYNC_TAG_PREFIX, type DRAFT_SYNC_TAG_PREFIX} from '../constants'\n\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'), {ssr: false})\nconst RefreshOnMount = dynamic(() => import('../../live/client-components/live/RefreshOnMount'), {\n ssr: false,\n})\nconst RefreshOnFocus = dynamic(() => import('../../live/client-components/live/RefreshOnFocus'), {\n ssr: false,\n})\nconst RefreshOnReconnect = dynamic(\n () => import('../../live/client-components/live/RefreshOnReconnect'),\n {ssr: false},\n)\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport interface SanityLiveProps {\n config: SanityClientConfig\n draftModeEnabled: boolean\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: (\n tags: `${typeof PUBLISHED_SYNC_TAG_PREFIX | typeof DRAFT_SYNC_TAG_PREFIX}${SyncTag}`[],\n ) => Promise<void | 'refresh'>\n resolveDraftModePerspective: () => Promise<ClientPerspective>\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 * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport default function SanityLive(props: SanityLiveProps): React.JSX.Element | null {\n const {\n config,\n draftModeEnabled,\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,\n resolveDraftModePerspective,\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, token, requestTagPrefix} =\n config\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 const [resolvedInitialPerspective, setResolvedInitialPerspective] = useState(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 void revalidateSyncTags(\n event.tags.map((tag: SyncTag) => `${PUBLISHED_SYNC_TAG_PREFIX}${tag}` as const),\n ).then((result) => {\n if (result === 'refresh') router.refresh()\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 // @TODO previous version that handle both published and draft events\n // useEffect(() => {\n // const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).subscribe({\n // next: handleLiveEvent,\n // error: (err: unknown) => {\n // onError(err)\n // },\n // })\n // return () => subscription.unsubscribe()\n // }, [client.live, onError, requestTag, token])\n useEffect(() => {\n const subscription = client.live.events({tag: requestTag}).subscribe({\n next: handleLiveEvent,\n error: (err: unknown) => {\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token])\n\n /**\n * Handle live events for drafts differently, only use it to trigger refreshes, don't expire the cache\n */\n const handleLiveDraftEvent = useEffectEvent((event: LiveEvent) => {\n if (event.type === 'message') {\n // Just refresh, due to cache bypass in draft mode it'll fetch fresh content (though we wish cache worked as in production)\n // @TODO if draft content is published, then this extra refresh is unnecessary, it's tricky to check since `event.id` are different on the two EventSource connections\n router.refresh()\n }\n })\n useEffect(() => {\n if (!token) return\n const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).subscribe({\n next: handleLiveDraftEvent,\n error: (err: unknown) => {\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token])\n\n /**\n * 2. Notify what perspective we're in, when in Draft Mode\n */\n useEffect(() => {\n if (resolvedInitialPerspective) return undefined\n\n if (!draftModeEnabled) {\n setResolvedInitialPerspective(true)\n setPerspective('unknown')\n return undefined\n }\n\n const controller = new AbortController()\n resolveDraftModePerspective()\n .then((perspective) => {\n if (controller.signal.aborted) return\n setResolvedInitialPerspective(true)\n setPerspective(sanitizePerspective(perspective, 'drafts'))\n })\n .catch((err) => {\n if (controller.signal.aborted) return\n console.error('Failed to resolve draft mode perspective', err)\n setResolvedInitialPerspective(true)\n setPerspective('unknown')\n })\n return () => controller.abort()\n }, [draftModeEnabled, resolveDraftModePerspective, resolvedInitialPerspective])\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 && resolvedInitialPerspective && (\n <PresentationComlink\n projectId={projectId!}\n dataset={dataset!}\n draftModeEnabled={draftModeEnabled}\n />\n )}\n {!draftModeEnabled && refreshOnMount && <RefreshOnMount />}\n {!draftModeEnabled && refreshOnFocus && <RefreshOnFocus />}\n {!draftModeEnabled && refreshOnReconnect && <RefreshOnReconnect />}\n </>\n )\n}\n"],"mappings":";;;;;;;;;;;AAqBA,MAAM,sBAAsB,cAAc,OAAO,iCAA0B,EAAC,KAAK,OAAM,CAAC;AACxF,MAAM,iBAAiB,cAAc,OAAO,4BAAqD,EAC/F,KAAK,OACN,CAAC;AACF,MAAM,iBAAiB,cAAc,OAAO,4BAAqD,EAC/F,KAAK,OACN,CAAC;AACF,MAAM,qBAAqB,cACnB,OAAO,gCACb,EAAC,KAAK,OAAM,CACb;AAyBD,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,SAAwB,WAAW,OAAkD;CACnF,MAAM,EACJ,QACA,kBACA,iBAAiB,OACjB,iBAAiB,mBACb,QACA,OAAO,WAAW,cAChB,OACA,OAAO,SAAS,OAAO,KAC7B,qBAAqB,MACrB,mBAAmB,KACnB,aAAa,oBACb,UAAU,aACV,WAAW,gBACX,oBACA,gCACE;CACJ,MAAM,EAAC,WAAW,SAAS,SAAS,YAAY,oBAAoB,OAAO,qBACzE;CAEF,MAA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,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,eAAe,8BAClC,oBAAC,qBAAA;GACY;GACF;GACS;IAClB;EAEH,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAA,EAAA,CAAiB;EACzD,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAA,EAAA,CAAiB;EACzD,CAAC,oBAAoB,sBAAsB,oBAAC,oBAAA,EAAA,CAAqB;KACjE"}
1
+ {"version":3,"file":"live.js","names":["revalidateSyncTags","perspective"],"sources":["../../../src/experimental/client-components/live.tsx"],"sourcesContent":["'use client'\n\nimport {setEnvironment, setPerspective} from '#client-components/context'\nimport {isCorsOriginError} from '#live/isCorsOriginError'\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {\n createClient,\n type ClientPerspective,\n type LiveEvent,\n type LiveEventGoAway,\n type SyncTag,\n} from '@sanity/client'\nimport {isMaybePresentation, isMaybePreviewWindow} from '@sanity/presentation-comlink'\nimport {expireTags} 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 type {SanityClientConfig} from '../types'\n\nimport {PUBLISHED_SYNC_TAG_PREFIX} from '../constants'\n\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'), {ssr: false})\nconst RefreshOnMount = dynamic(() => import('../../live/client-components/live/RefreshOnMount'), {\n ssr: false,\n})\nconst RefreshOnFocus = dynamic(() => import('../../live/client-components/live/RefreshOnFocus'), {\n ssr: false,\n})\nconst RefreshOnReconnect = dynamic(\n () => import('../../live/client-components/live/RefreshOnReconnect'),\n {ssr: false},\n)\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport interface SanityLiveProps {\n config: SanityClientConfig\n draftModeEnabled: boolean\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: string[]) => Promise<void | 'refresh'>\n resolveDraftModePerspective: () => Promise<ClientPerspective>\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 * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport default function SanityLive(props: SanityLiveProps): React.JSX.Element | null {\n const {\n config,\n draftModeEnabled,\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 = expireTags,\n resolveDraftModePerspective,\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, token, requestTagPrefix} =\n config\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 const [resolvedInitialPerspective, setResolvedInitialPerspective] = useState(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 void revalidateSyncTags(\n event.tags.map((tag: SyncTag) => `${PUBLISHED_SYNC_TAG_PREFIX}${tag}` as const),\n ).then((result) => {\n if (result === 'refresh') router.refresh()\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 // @TODO previous version that handle both published and draft events\n // useEffect(() => {\n // const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).subscribe({\n // next: handleLiveEvent,\n // error: (err: unknown) => {\n // onError(err)\n // },\n // })\n // return () => subscription.unsubscribe()\n // }, [client.live, onError, requestTag, token])\n useEffect(() => {\n const subscription = client.live.events({tag: requestTag}).subscribe({\n next: handleLiveEvent,\n error: (err: unknown) => {\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token])\n\n /**\n * Handle live events for drafts differently, only use it to trigger refreshes, don't expire the cache\n */\n const handleLiveDraftEvent = useEffectEvent((event: LiveEvent) => {\n if (event.type === 'message') {\n // Just refresh, due to cache bypass in draft mode it'll fetch fresh content (though we wish cache worked as in production)\n // @TODO if draft content is published, then this extra refresh is unnecessary, it's tricky to check since `event.id` are different on the two EventSource connections\n router.refresh()\n }\n })\n useEffect(() => {\n if (!token) return\n const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).subscribe({\n next: handleLiveDraftEvent,\n error: (err: unknown) => {\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token])\n\n /**\n * 2. Notify what perspective we're in, when in Draft Mode\n */\n useEffect(() => {\n if (resolvedInitialPerspective) return undefined\n\n if (!draftModeEnabled) {\n setResolvedInitialPerspective(true)\n setPerspective('unknown')\n return undefined\n }\n\n const controller = new AbortController()\n resolveDraftModePerspective()\n .then((perspective) => {\n if (controller.signal.aborted) return\n setResolvedInitialPerspective(true)\n setPerspective(sanitizePerspective(perspective, 'drafts'))\n })\n .catch((err) => {\n if (controller.signal.aborted) return\n console.error('Failed to resolve draft mode perspective', err)\n setResolvedInitialPerspective(true)\n setPerspective('unknown')\n })\n return () => controller.abort()\n }, [draftModeEnabled, resolveDraftModePerspective, resolvedInitialPerspective])\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 && resolvedInitialPerspective && (\n <PresentationComlink\n projectId={projectId!}\n dataset={dataset!}\n draftModeEnabled={draftModeEnabled}\n />\n )}\n {!draftModeEnabled && refreshOnMount && <RefreshOnMount />}\n {!draftModeEnabled && refreshOnFocus && <RefreshOnFocus />}\n {!draftModeEnabled && refreshOnReconnect && <RefreshOnReconnect />}\n </>\n )\n}\n"],"mappings":";;;;;;;;;;;;AAsBA,MAAM,sBAAsB,cAAc,OAAO,iCAA0B,EAAC,KAAK,OAAM,CAAC;AACxF,MAAM,iBAAiB,cAAc,OAAO,4BAAqD,EAC/F,KAAK,OACN,CAAC;AACF,MAAM,iBAAiB,cAAc,OAAO,4BAAqD,EAC/F,KAAK,OACN,CAAC;AACF,MAAM,qBAAqB,cACnB,OAAO,gCACb,EAAC,KAAK,OAAM,CACb;AAuBD,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,SAAwB,WAAW,OAAkD;CACnF,MAAM,EACJ,QACA,kBACA,iBAAiB,OACjB,iBAAiB,mBACb,QACA,OAAO,WAAW,cAChB,OACA,OAAO,SAAS,OAAO,KAC7B,qBAAqB,MACrB,mBAAmB,KACnB,aAAa,oBACb,UAAU,aACV,WAAW,gBACX,oBAAA,uBAAqB,YACrB,gCACE;CACJ,MAAM,EAAC,WAAW,SAAS,SAAS,YAAY,oBAAoB,OAAO,qBACzE;CAEF,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;CACD,MAAM,CAAC,qBAAqB,0BAA0B,SAAyB,MAAM;CACrF,MAAM,CAAC,4BAA4B,iCAAiC,SAAS,MAAM;CAKnF,MAAM,SA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AI,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,eAAe,8BAClC,oBAAC,qBAAA;GACY;GACF;GACS;IAClB;EAEH,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAA,EAAA,CAAiB;EACzD,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAA,EAAA,CAAiB;EACzD,CAAC,oBAAoB,sBAAsB,oBAAC,oBAAA,EAAA,CAAqB;KACjE"}
@@ -1,9 +1,6 @@
1
+ import { LiveEnvironment, LivePerspective } from "#client-components/context";
1
2
  import { useOptimistic } from "@sanity/visual-editing/react";
2
3
  import { ClientPerspective, ClientReturn, ContentSourceMap, QueryParams } from "@sanity/client";
3
- import "@sanity/presentation-comlink";
4
- import "@sanity/comlink";
5
- type LivePerspective = "checking" | "unknown" | ClientPerspective;
6
- type LiveEnvironment = "checking" | "presentation-iframe" | "presentation-window" | "live" | "static" | "unknown";
7
4
  /**
8
5
  * Reports the current draft mode environment.
9
6
  * Use it to determine how to adapt the UI based on wether:
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":["perspectiveListeners: Set<() => void>","perspective: LivePerspective","environmentListeners: Set<() => void>","environment: LiveEnvironment","comlinkListeners: Set<() => void>","comlink: Node<LoaderNodeMsg, LoaderControllerMsg> | null","comlinkProjectId: string | null","comlinkDataset: string | null"],"sources":["../../src/shared/client-components/context.tsx","../../src/live/hooks/useDraftMode.ts","../../src/live/hooks/useIsPresentationTool.ts","../../src/live/hooks/useIsLivePreview.ts","../../src/live/hooks/usePresentationQuery.ts"],"sourcesContent":[],"mappings":";;;;KAIY,eAAA,4BAA2C;KAY3C,eAAA;;;;;AAZZ;AAYA;;ACIA;AAmBA;;AC3BgB,iBDQA,uBAAA,CAAA,CCRA,EDQ2B,eCR3B;;ACKhB;;ACDA;AAOA;;AACQ,iBHeQ,uBAAA,CAAA,CGfR,EHemC,eGfnC;;;;;;AJpBR;AAYA;;ACIA;AAmBA;iBC3BgB,qBAAA,CAAA;;;;;;AFRhB;AAYA;;ACIA;AAmBA;;AC3BA;;ACKA;;ACDY,iBDCI,gBAAA,CAAA,CCDJ,EAAA,OAAA,GAAA,IAAA;;KAAA,mCAAA;;;EJZZ,WAAY,EAAA,IAAA;AAYZ,CAAA;;ACIgB,KGGJ,iCHH+B,CAAA,oBAAA,MAAA,CAAA,GAAA;EAmB3C,IAAgB,EGfR,YHeQ,CGfK,WHeL,CAAA;aGdH;EFbb,WAAgB,EEcD,iBFdC;;ACKA,KCYJ,2BDZI,CAAA,oBAAA,MAAA,CAAA,GCaZ,mCDbY,GCcZ,iCDdY,CCcsB,WDdtB,CAAA;;ACDhB;AAOA;;;;;;AAMY,iBAyDI,oBAzDJ,CAAA,0BAAA,MAAA,CAAA,CAAA,KAAA,EAAA;EACR,KAAA,EAyDK,WAzDL;EACkC,MAAA,CAAA,EAyD3B,WAzD2B,GAyDb,OAzDa,CAyDL,WAzDK,CAAA;EAAlC,KAAA,CAAA,EAAA,OAAA;CAAA,CAAA,EA2DA,2BA3DA,CA2D4B,WA3D5B,CAAA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/live/hooks/useDraftMode.ts","../../src/live/hooks/useIsPresentationTool.ts","../../src/live/hooks/useIsLivePreview.ts","../../src/live/hooks/usePresentationQuery.ts"],"sourcesContent":[],"mappings":";;;;;;AAoBA;AAmBA;;AC3BA;;ACKA;;ACDY,iBHII,uBAAA,CAAA,CGJJ,EHI+B,eGJ/B;AAOZ;;;;;;AAMY,iBHUI,uBAAA,CAAA,CGVJ,EHU+B,eGV/B;;;;;AHTZ;AAmBA;;AC3BA;;ACKA;iBDLgB,qBAAA,CAAA;;;;;ADQhB;AAmBA;;AC3BA;;ACKA;;ACDA;AAOA;;;AAEa,iBDRG,gBAAA,CAAA,CCQH,EAAA,OAAA,GAAA,IAAA;;KATD,mCAAA;;EHIZ,SAAgB,EAAA,IAAA;EAmBhB,WAAgB,EAAA,IAAA;;AC3BhB;KEWY;EDNZ,IAAgB,ECOR,YDPQ,CCOK,WDPL,CAAA;aCQH;EATb,WAAY,EAUG,iBAVH;AAOZ,CAAA;AACqB,KAKT,2BALS,CAAA,oBAAA,MAAA,CAAA,GAMjB,mCANiB,GAOjB,iCAPiB,CAOiB,WAPjB,CAAA;;;;;AAKrB;;;;AAEI,iBAuDY,oBAvDZ,CAAA,0BAAA,MAAA,CAAA,CAAA,KAAA,EAAA;EAuDJ,KAAgB,EACP,WADO;EACP,MAAA,CAAA,EACE,WADF,GACgB,OADhB,CACwB,WADxB,CAAA;EACE,KAAA,CAAA,EAAA,OAAA;CAAsB,CAAA,EAE7B,2BAF6B,CAED,WAFC,CAAA"}
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { a as environment, c as perspectiveListeners, i as comlinkProjectId, n as comlinkDataset, o as environmentListeners, r as comlinkListeners, s as perspective, t as comlink } from "../context.js";
2
+ import { comlink, comlinkDataset, comlinkListeners, comlinkProjectId, environment, environmentListeners, perspective, perspectiveListeners } from "#client-components/context";
3
3
  import { useCallback, useEffect, useEffectEvent, useMemo, useReducer, useSyncExternalStore } from "react";
4
4
  import { stegaEncodeSourceMap } from "@sanity/client/stega";
5
5
  import { dequal } from "dequal/lite";
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { t as isCorsOriginError } from "./isCorsOriginError.js";
2
1
  import { stegaClean } from "@sanity/client/stega";
2
+ import { isCorsOriginError } from "#live/isCorsOriginError";
3
3
  import { createClient, unstable__adapter, unstable__environment } from "@sanity/client";
4
4
  import { CreateDataAttribute, CreateDataAttributeProps, createDataAttribute } from "@sanity/visual-editing/create-data-attribute";
5
5
  import groq, { defineQuery } from "groq";
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { t as isCorsOriginError } from "./isCorsOriginError.js";
2
1
  import { stegaClean } from "@sanity/client/stega";
2
+ import { isCorsOriginError } from "#live/isCorsOriginError";
3
3
  import { createClient, unstable__adapter, unstable__environment } from "@sanity/client";
4
4
  import { createDataAttribute } from "@sanity/visual-editing/create-data-attribute";
5
5
  import groq, { defineQuery } from "groq";
@@ -1,13 +1,13 @@
1
1
  "use client";
2
- import { d as setEnvironment, f as setPerspective } from "../../../context.js";
3
- import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
4
2
  import { useRouter } from "next/navigation";
3
+ import { setEnvironment, setPerspective } from "#client-components/context";
5
4
  import { useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
6
5
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
6
+ import { isCorsOriginError } from "#live/isCorsOriginError";
7
7
  import { createClient } from "@sanity/client";
8
8
  import { isMaybePresentation, isMaybePreviewWindow } from "@sanity/presentation-comlink";
9
- import dynamic from "next/dynamic";
10
9
  import { revalidateSyncTags } from "next-sanity/live/server-actions";
10
+ import dynamic from "next/dynamic";
11
11
  const PresentationComlink = dynamic(() => import("../../../PresentationComlink2.js"), { ssr: false });
12
12
  const RefreshOnMount = dynamic(() => import("../../../RefreshOnMount.js"), { ssr: false });
13
13
  const RefreshOnFocus = dynamic(() => import("../../../RefreshOnFocus.js"), { ssr: false });
@@ -1,5 +1,6 @@
1
1
  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
- export { revalidateSyncTags, setPerspectiveCookie };
4
+ declare function expireTags(_tags: unknown): Promise<void>;
5
+ export { expireTags, revalidateSyncTags, setPerspectiveCookie };
5
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/live/server-actions/index.ts"],"sourcesContent":[],"mappings":";iBASsB,kBAAA,OAAyB,YAAY;AAArC,iBAWA,oBAAA,CAXqC,WAAA,EAWH,iBAXG,CAAA,EAWiB,OAXjB,CAAA,IAAA,CAAA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/live/server-actions/index.ts"],"sourcesContent":[],"mappings":";iBAWsB,kBAAA,OAAyB,YAAY;AAArC,iBAWA,oBAAA,CAXqC,WAAA,EAWH,iBAXG,CAAA,EAWiB,OAXjB,CAAA,IAAA,CAAA;AAWrC,iBAyBA,UAAA,CAzBA,KAAkC,EAAA,OAAA,CAAA,EAyBN,OAzB0B,CAAA,IAAA,CAAA"}
@@ -1,8 +1,9 @@
1
1
  "use server";
2
- import { t as sanitizePerspective } from "../../sanitizePerspective.js";
2
+ import { n as PUBLISHED_SYNC_TAG_PREFIX } from "../../constants.js";
3
3
  import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
4
4
  import { cookies, draftMode } from "next/headers";
5
- import { revalidateTag } from "next/cache";
5
+ import { sanitizePerspective } from "#live/sanitizePerspective";
6
+ import { revalidateTag, updateTag } from "next/cache";
6
7
  async function revalidateSyncTags(tags) {
7
8
  revalidateTag("sanity:fetch-sync-tags", "max");
8
9
  for (const _tag of tags) {
@@ -22,6 +23,19 @@ async function setPerspectiveCookie(perspective) {
22
23
  sameSite: "none"
23
24
  });
24
25
  }
25
- export { revalidateSyncTags, setPerspectiveCookie };
26
+ async function expireTags(_tags) {
27
+ if (!Array.isArray(_tags)) {
28
+ console.warn("<SanityLive /> `expireTags` called with non-array tags", _tags);
29
+ return;
30
+ }
31
+ const tags = _tags.filter((tag) => typeof tag === "string" && tag.startsWith(PUBLISHED_SYNC_TAG_PREFIX));
32
+ if (!tags.length) {
33
+ console.warn("<SanityLive /> `expireTags` called with no valid tags", _tags);
34
+ return;
35
+ }
36
+ for (const tag of tags) updateTag(tag);
37
+ console.log(`<SanityLive /> updated tags: ${tags.join(", ")}`);
38
+ }
39
+ export { expireTags, revalidateSyncTags, setPerspectiveCookie };
26
40
 
27
41
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
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'\n\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {revalidateTag} from 'next/cache'\nimport {cookies, draftMode} from 'next/headers'\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
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/live/server-actions/index.ts"],"sourcesContent":["'use server'\n\nimport type {ClientPerspective, SyncTag} from '@sanity/client'\n\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {revalidateTag, updateTag} from 'next/cache'\nimport {cookies, draftMode} from 'next/headers'\n\nimport {PUBLISHED_SYNC_TAG_PREFIX} from '../../experimental/constants'\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\n// @TODO expose parseTags function that returns the correct array of tags\n// we already have s1: prefixes, but they could change\n// use sp: for prod, sd: for draft, keep em short\nexport async function expireTags(_tags: unknown): Promise<void> {\n // @TODO Draft Mode bypasses cache anyway so we don't bother with expiring tags for draft content\n // const isDraftMode = (await draftMode()).isEnabled\n // const tags = _tags.map((tag) => `${isDraftMode ? 'drafts' : 'sanity'}:${tag}`)\n if (!Array.isArray(_tags)) {\n console.warn('<SanityLive /> `expireTags` called with non-array tags', _tags)\n return undefined\n }\n const tags = _tags.filter(\n (tag) => typeof tag === 'string' && tag.startsWith(PUBLISHED_SYNC_TAG_PREFIX),\n )\n if (!tags.length) {\n console.warn('<SanityLive /> `expireTags` called with no valid tags', _tags)\n return undefined\n }\n for (const tag of tags) {\n updateTag(tag)\n }\n // oxlint-disable-next-line no-console\n console.log(`<SanityLive /> updated tags: ${tags.join(', ')}`)\n}\n"],"mappings":";;;;;;AAWA,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;;AAMH,eAAsB,WAAW,OAA+B;AAI9D,KAAI,CAAC,MAAM,QAAQ,MAAM,EAAE;AACzB,UAAQ,KAAK,0DAA0D,MAAM;AAC7E;;CAEF,MAAM,OAAO,MAAM,QAChB,QAAQ,OAAO,QAAQ,YAAY,IAAI,WAAW,0BAA0B,CAC9E;AACD,KAAI,CAAC,KAAK,QAAQ;AAChB,UAAQ,KAAK,yDAAyD,MAAM;AAC5E;;AAEF,MAAK,MAAM,OAAO,KAChB,WAAU,IAAI;AAGhB,SAAQ,IAAI,gCAAgC,KAAK,KAAK,KAAK,GAAG"}
package/dist/live.d.ts CHANGED
@@ -1,5 +1,7 @@
1
- import { t as isCorsOriginError } from "./isCorsOriginError.js";
2
- import { a as DefinedFetchType, c as PerspectiveType, l as ResolvePerspectiveFromCookies, n as DefinedSanityFetchType, o as DefinedLiveProps, r as DefinedSanityLiveProps, t as DefineSanityLiveOptions } from "./defineLive.js";
1
+ import { n as DefinedSanityFetchType, r as DefinedSanityLiveProps, t as DefineSanityLiveOptions } from "./defineLive.js";
2
+ import { isCorsOriginError } from "#live/isCorsOriginError";
3
+ import { ResolvePerspectiveFromCookies } from "#live/resolvePerspectiveFromCookies";
4
+ import { DefinedFetchType, DefinedLiveProps, PerspectiveType as LivePerspective } from "#live/types";
3
5
  /**
4
6
  * @public
5
7
  */
@@ -20,5 +22,5 @@ declare function defineLive(_config: DefineSanityLiveOptions): {
20
22
  * @public
21
23
  */
22
24
  declare const resolvePerspectiveFromCookies: ResolvePerspectiveFromCookies;
23
- export { type PerspectiveType as LivePerspective, defineLive, isCorsOriginError, resolvePerspectiveFromCookies };
25
+ export { type LivePerspective, defineLive, isCorsOriginError, resolvePerspectiveFromCookies };
24
26
  //# sourceMappingURL=live.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"live.d.ts","names":["resolvePerspectiveFromCookies: ResolvePerspectiveFromCookies"],"sources":["../src/live.tsx"],"sourcesContent":[],"mappings":";;;;;AAsBc,iBAFE,UAAA,CAEF,OAAA,EAFsB,uBAEtB,CAAA,EAAA;EAIC,KAAA,EALN,gBAKM;EAImB,IAAA,EAR1B,KAAA,CAAM,aAQoB,CARN,gBAQM,CAAA;EAApB;;AASd;eAbe;;;;cAID,KAAA,CAAM,cAAc;;;;;;cASrBA,+BAA+B"}
1
+ {"version":3,"file":"live.d.ts","names":["resolvePerspectiveFromCookies: ResolvePerspectiveFromCookies"],"sources":["../src/live.tsx"],"sourcesContent":[],"mappings":";;;;;AAoBA;;AACS,iBADO,UAAA,CACP,OAAA,EAD2B,uBAC3B,CAAA,EAAA;EACmB,KAAA,EADnB,gBACmB;EAApB,IAAA,EAAA,KAAA,CAAM,aAAA,CAAc,gBAAd,CAAA;EAIC;;;EAIK,WAAA,EAJL,sBAIK;EASpB;;;cATc,KAAA,CAAM,cAAc;;;;;;cASrBA,+BAA+B"}
package/dist/live.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as isCorsOriginError } from "./isCorsOriginError.js";
1
+ import { isCorsOriginError } from "#live/isCorsOriginError";
2
2
  function defineLive(_config) {
3
3
  throw new Error(`defineLive can't be imported by a client component`);
4
4
  }
@@ -1,5 +1,7 @@
1
- import { t as isCorsOriginError } from "./isCorsOriginError.js";
2
- import { a as DefinedFetchType, c as PerspectiveType, n as DefinedSanityFetchType, o as DefinedLiveProps, r as DefinedSanityLiveProps, s as LiveOptions, u as resolvePerspectiveFromCookies } from "./defineLive.js";
1
+ import { n as DefinedSanityFetchType, r as DefinedSanityLiveProps } from "./defineLive.js";
2
+ import { isCorsOriginError } from "#live/isCorsOriginError";
3
+ import { resolvePerspectiveFromCookies } from "#live/resolvePerspectiveFromCookies";
4
+ import { DefinedFetchType, DefinedLiveProps, LiveOptions, PerspectiveType as LivePerspective } from "#live/types";
3
5
  declare function defineLive(config: LiveOptions): {
4
6
  fetch: DefinedFetchType;
5
7
  Live: React.ComponentType<DefinedLiveProps>;
@@ -12,5 +14,5 @@ declare function defineLive(config: LiveOptions): {
12
14
  */
13
15
  SanityLive: React.ComponentType<DefinedSanityLiveProps>;
14
16
  };
15
- export { type PerspectiveType as LivePerspective, defineLive, isCorsOriginError, resolvePerspectiveFromCookies };
17
+ export { type LivePerspective, defineLive, isCorsOriginError, resolvePerspectiveFromCookies };
16
18
  //# sourceMappingURL=live.next-js.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"live.next-js.d.ts","names":[],"sources":["../src/experimental/live.tsx"],"sourcesContent":[],"mappings":";;iBAagB,UAAA,SAAmB;EAAnC,KAAgB,EACP,gBADO;EAAmB,IAAA,EAE3B,KAAA,CAAM,aAFqB,CAEP,gBAFO,CAAA;EAC1B;;;EAKM,WAAA,EAAA,sBAAA;EAImB;;;cAApB,KAAA,CAAM,cAAc"}
1
+ {"version":3,"file":"live.next-js.d.ts","names":[],"sources":["../src/experimental/live.tsx"],"sourcesContent":[],"mappings":";;;;iBAagB,UAAA,SAAmB;SAC1B;QACD,KAAA,CAAM,cAAc;EAF5B;;;EAE4B,WAAA,EAIb,sBAJa;EAApB;;;EAQM,UAAM,EAAN,KAAA,CAAM,aAAA,CAAc,sBAAd,CAAA;CAAA"}
@@ -1,11 +1,11 @@
1
- import { t as isCorsOriginError } from "./isCorsOriginError.js";
2
1
  import { n as PUBLISHED_SYNC_TAG_PREFIX, t as DRAFT_SYNC_TAG_PREFIX } from "./constants.js";
3
- import { t as resolvePerspectiveFromCookies } from "./resolvePerspectiveFromCookies.js";
4
2
  import { cookies, draftMode } from "next/headers";
5
3
  import { Suspense } from "react";
6
4
  import { jsx } from "react/jsx-runtime";
5
+ import { isCorsOriginError } from "#live/isCorsOriginError";
6
+ import { resolvePerspectiveFromCookies, resolvePerspectiveFromCookies as resolvePerspectiveFromCookies$1 } from "#live/resolvePerspectiveFromCookies";
7
7
  import SanityLiveClientComponent from "next-sanity/experimental/client-components/live";
8
- import { cacheTag, updateTag } from "next/cache";
8
+ import { cacheTag } from "next/cache";
9
9
  import { preconnect } from "react-dom";
10
10
  function defineLive(config) {
11
11
  const { client: _client, serverToken, browserToken } = config;
@@ -40,7 +40,6 @@ function defineLive(config) {
40
40
  },
41
41
  Live: function Live(props) {
42
42
  const { perspective = "published", onChange, onChangeIncludingDrafts, onStudioPerspective, refreshOnMount = false, refreshOnFocus = false, refreshOnReconnect = false, requestTag = "next-loader.live.cache-components", onError, onGoAway, intervalOnGoAway } = props;
43
- if (onChange) console.warn("`onChange` is not implemented yet");
44
43
  if (onChangeIncludingDrafts) console.warn("`onChangeIncludingDrafts` is not implemented yet");
45
44
  if (onStudioPerspective) console.warn("`onStudioPerspective` is not implemented yet");
46
45
  const includeDrafts = typeof browserToken === "string" && perspective !== "published";
@@ -65,7 +64,7 @@ function defineLive(config) {
65
64
  onError,
66
65
  onGoAway,
67
66
  intervalOnGoAway,
68
- revalidateSyncTags: expireTags,
67
+ revalidateSyncTags: onChange,
69
68
  resolveDraftModePerspective
70
69
  }) });
71
70
  },
@@ -77,23 +76,9 @@ function defineLive(config) {
77
76
  }
78
77
  };
79
78
  }
80
- async function expireTags(_tags) {
81
- "use server";
82
- if (!Array.isArray(_tags)) {
83
- console.warn("<SanityLive /> `expireTags` called with non-array tags", _tags);
84
- return;
85
- }
86
- const tags = _tags.filter((tag) => typeof tag === "string" && tag.startsWith(PUBLISHED_SYNC_TAG_PREFIX));
87
- if (!tags.length) {
88
- console.warn("<SanityLive /> `expireTags` called with no valid tags", _tags);
89
- return;
90
- }
91
- for (const tag of tags) updateTag(tag);
92
- console.log(`<SanityLive /> updated tags: ${tags.join(", ")}`);
93
- }
94
79
  async function resolveDraftModePerspective() {
95
80
  "use server";
96
- if ((await draftMode()).isEnabled) return resolvePerspectiveFromCookies({ cookies: await cookies() });
81
+ if ((await draftMode()).isEnabled) return resolvePerspectiveFromCookies$1({ cookies: await cookies() });
97
82
  return "published";
98
83
  }
99
84
  export { defineLive, isCorsOriginError, resolvePerspectiveFromCookies };
@@ -1 +1 @@
1
- {"version":3,"file":"live.next-js.js","names":[],"sources":["../src/experimental/live.tsx"],"sourcesContent":["import type {DefinedFetchType, DefinedLiveProps, LiveOptions, PerspectiveType} from '#live/types'\n\nimport {resolvePerspectiveFromCookies} from '#live/resolvePerspectiveFromCookies'\nimport SanityLiveClientComponent from 'next-sanity/experimental/client-components/live'\nimport {cacheTag, updateTag} from 'next/cache'\nimport {draftMode, cookies} from 'next/headers'\nimport {Suspense} from 'react'\nimport {preconnect} from 'react-dom'\n\nimport type {DefinedSanityFetchType, DefinedSanityLiveProps} from '../live/defineLive'\n\nimport {DRAFT_SYNC_TAG_PREFIX, PUBLISHED_SYNC_TAG_PREFIX} from './constants'\n\nexport function defineLive(config: LiveOptions): {\n fetch: DefinedFetchType\n Live: React.ComponentType<DefinedLiveProps>\n /**\n * @deprecated use `fetch` instead, and define your own `sanityFetch` function with logic for when to toggle `stega` and `perspective`\n */\n sanityFetch: DefinedSanityFetchType\n /**\n * @deprecated use `Live` instead, and define your own `SanityLive` component with logic for when to toggle `perspective`\n */\n SanityLive: React.ComponentType<DefinedSanityLiveProps>\n} {\n const {client: _client, serverToken, browserToken} = 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} = client.config()\n\n const fetch: DefinedFetchType = async function fetch({\n query,\n params = {},\n perspective = 'published',\n stega = false,\n tags: customCacheTags = [],\n requestTag = 'next-loader.fetch.cache-components',\n }) {\n const useCdn = perspective === 'published'\n\n const {result, resultSourceMap, syncTags} = await client.fetch(query, params, {\n filterResponse: false,\n returnQuery: false,\n perspective,\n useCdn,\n stega,\n cacheMode: useCdn ? 'noStale' : undefined,\n tag: requestTag,\n token: perspective === 'published' ? originalToken : serverToken || originalToken, // @TODO can pass undefined instead of config.token here?\n })\n const tags = [\n ...customCacheTags,\n ...(syncTags || []).map(\n (tag) =>\n `${perspective === 'published' ? PUBLISHED_SYNC_TAG_PREFIX : DRAFT_SYNC_TAG_PREFIX}${tag}`,\n ),\n ]\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 */\n // cacheLife({revalidate: 60 * 60 * 24 * 90})\n\n return {data: result, sourceMap: resultSourceMap || null, tags}\n\n // return sanityCachedFetch(\n // {\n // apiHost,\n // apiVersion,\n // useProjectHostname,\n // dataset,\n // projectId,\n // requestTagPrefix,\n // token: originalToken,\n // },\n // {\n // query,\n // params,\n // perspective,\n // stega,\n // requestTag,\n // draftToken: serverToken,\n // customCacheTags,\n // },\n // ).then(({data, sourceMap, tags}) => ({\n // data:\n // stega && sourceMap\n // ? stegaEncodeSourceMap(data, sourceMap, {...stegaConfig, enabled: true})\n // : data,\n // sourceMap,\n // tags,\n // }))\n }\n\n const Live: React.ComponentType<DefinedLiveProps> = function Live(props) {\n const {\n perspective = 'published',\n onChange,\n onChangeIncludingDrafts,\n onStudioPerspective,\n refreshOnMount = false,\n refreshOnFocus = false,\n refreshOnReconnect = false,\n requestTag = 'next-loader.live.cache-components',\n onError,\n onGoAway,\n intervalOnGoAway,\n } = props\n\n if (onChange) {\n console.warn('`onChange` is not implemented yet')\n }\n if (onChangeIncludingDrafts) {\n console.warn('`onChangeIncludingDrafts` is not implemented yet')\n }\n if (onStudioPerspective) {\n console.warn('`onStudioPerspective` is not implemented yet')\n }\n\n const includeDrafts = typeof browserToken === 'string' && perspective !== 'published'\n\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n const {origin} = new URL(client.getUrl('', false))\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 preconnect(origin)\n\n return (\n <Suspense>\n <SanityLiveClientComponent\n config={{\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n requestTagPrefix,\n token: includeDrafts ? browserToken : undefined,\n }}\n requestTag={requestTag}\n // origin={origin}\n draftModeEnabled={includeDrafts}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n revalidateSyncTags={expireTags}\n resolveDraftModePerspective={resolveDraftModePerspective}\n />\n </Suspense>\n )\n }\n\n return {\n fetch,\n Live,\n sanityFetch: () => {\n throw new Error(\n '`defineLive().sanityFetch` is not available when `cacheComponents: true`, use `defineLive().fetch` instead',\n )\n },\n SanityLive: () => {\n throw new Error(\n '`defineLive().SanityLive` is not available when `cacheComponents: true`, use `defineLive().Live` instead',\n )\n },\n }\n}\n\n// @TODO expose parseTags function that returns the correct array of tags\n// we already have s1: prefixes, but they could change\n// use sp: for prod, sd: for draft, keep em short\nasync function expireTags(_tags: unknown): Promise<void> {\n 'use server'\n // @TODO Draft Mode bypasses cache anyway so we don't bother with expiring tags for draft content\n // const isDraftMode = (await draftMode()).isEnabled\n // const tags = _tags.map((tag) => `${isDraftMode ? 'drafts' : 'sanity'}:${tag}`)\n if (!Array.isArray(_tags)) {\n console.warn('<SanityLive /> `expireTags` called with non-array tags', _tags)\n return undefined\n }\n const tags = _tags.filter(\n (tag) => typeof tag === 'string' && tag.startsWith(PUBLISHED_SYNC_TAG_PREFIX),\n )\n if (!tags.length) {\n console.warn('<SanityLive /> `expireTags` called with no valid tags', _tags)\n return undefined\n }\n for (const tag of tags) {\n updateTag(tag)\n }\n // oxlint-disable-next-line no-console\n console.log(`<SanityLive /> updated tags: ${tags.join(', ')}`)\n}\n\nasync function resolveDraftModePerspective(): Promise<PerspectiveType> {\n 'use server'\n if ((await draftMode()).isEnabled) {\n const jar = await cookies()\n return resolvePerspectiveFromCookies({cookies: jar})\n }\n return 'published'\n}\n\n// revalidateSyncTags => actionUpdateTags\n// router.refresh() => actionRefresh\n"],"mappings":";;;;;;;;;AAaA,SAAgB,WAAW,QAWzB;CACA,MAAM,EAAC,QAAQ,SAAS,aAAa,iBAAgB;AAErD,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,oDAAoD;AAGtE,KAAI,QAAQ,IAA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MAAM,EAAC,WAAU,IAAI,IAAI,OAAO,OAAO,IAAI,MAAM,CAAC;AAGlD,cAAW,OAAO;AAElB,UACE,oBAAC,UAAA,EAAA,UACC,oBAAC,2BAAA;IACC,QAAQ;KACN;KACA;KACA;KACA;KACA;KACA;KACA,OAAO,gBAAgB,eAAe,KAAA;KACvC;IACW;IAEZ,kBAAkB;IACF;IACA;IACI;IACX;IACC;IACQ;IAClB,oBAAoB;IACS;KAC7B,EAAA,CACO;;EAOb,mBAAmB;AACjB,SAAM,IAAI,MACR,6GACD;;EAEH,kBAAkB;AAChB,SAAM,IAAI,MACR,2GACD;;EAEJ;;AAMH,eAAe,WAAW,OAA+B;AACvD;AAIA,KAAI,CAAC,MAAM,QAAQ,MAAM,EAAE;AACzB,UAAQ,KAAK,0DAA0D,MAAM;AAC7E;;CAEF,MAAM,OAAO,MAAM,QAChB,QAAQ,OAAO,QAAQ,YAAY,IAAI,WAAW,0BAA0B,CAC9E;AACD,KAAI,CAAC,KAAK,QAAQ;AAChB,UAAQ,KAAK,yDAAyD,MAAM;AAC5E;;AAEF,MAAK,MAAM,OAAO,KAChB,WAAU,IAAI;AAGhB,SAAQ,IAAI,gCAAgC,KAAK,KAAK,KAAK,GAAG;;AAGhE,eAAe,8BAAwD;AACrE;AACA,MAAK,MAAM,WAAW,EAAE,UAEtB,QAAO,8BAA8B,EAAC,SAD1B,MAAM,SAAS,EACwB,CAAC;AAEtD,QAAO"}
1
+ {"version":3,"file":"live.next-js.js","names":["resolvePerspectiveFromCookies"],"sources":["../src/experimental/live.tsx"],"sourcesContent":["import type {DefinedFetchType, DefinedLiveProps, LiveOptions, PerspectiveType} from '#live/types'\n\nimport {resolvePerspectiveFromCookies} from '#live/resolvePerspectiveFromCookies'\nimport SanityLiveClientComponent from 'next-sanity/experimental/client-components/live'\nimport {cacheTag} from 'next/cache'\nimport {draftMode, cookies} from 'next/headers'\nimport {Suspense} from 'react'\nimport {preconnect} from 'react-dom'\n\nimport type {DefinedSanityFetchType, DefinedSanityLiveProps} from '../live/defineLive'\n\nimport {DRAFT_SYNC_TAG_PREFIX, PUBLISHED_SYNC_TAG_PREFIX} from './constants'\n\nexport function defineLive(config: LiveOptions): {\n fetch: DefinedFetchType\n Live: React.ComponentType<DefinedLiveProps>\n /**\n * @deprecated use `fetch` instead, and define your own `sanityFetch` function with logic for when to toggle `stega` and `perspective`\n */\n sanityFetch: DefinedSanityFetchType\n /**\n * @deprecated use `Live` instead, and define your own `SanityLive` component with logic for when to toggle `perspective`\n */\n SanityLive: React.ComponentType<DefinedSanityLiveProps>\n} {\n const {client: _client, serverToken, browserToken} = 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} = client.config()\n\n const fetch: DefinedFetchType = async function fetch({\n query,\n params = {},\n perspective = 'published',\n stega = false,\n tags: customCacheTags = [],\n requestTag = 'next-loader.fetch.cache-components',\n }) {\n const useCdn = perspective === 'published'\n\n const {result, resultSourceMap, syncTags} = await client.fetch(query, params, {\n filterResponse: false,\n returnQuery: false,\n perspective,\n useCdn,\n stega,\n cacheMode: useCdn ? 'noStale' : undefined,\n tag: requestTag,\n token: perspective === 'published' ? originalToken : serverToken || originalToken, // @TODO can pass undefined instead of config.token here?\n })\n const tags = [\n ...customCacheTags,\n ...(syncTags || []).map(\n (tag) =>\n `${perspective === 'published' ? PUBLISHED_SYNC_TAG_PREFIX : DRAFT_SYNC_TAG_PREFIX}${tag}`,\n ),\n ]\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 */\n // cacheLife({revalidate: 60 * 60 * 24 * 90})\n\n return {data: result, sourceMap: resultSourceMap || null, tags}\n\n // return sanityCachedFetch(\n // {\n // apiHost,\n // apiVersion,\n // useProjectHostname,\n // dataset,\n // projectId,\n // requestTagPrefix,\n // token: originalToken,\n // },\n // {\n // query,\n // params,\n // perspective,\n // stega,\n // requestTag,\n // draftToken: serverToken,\n // customCacheTags,\n // },\n // ).then(({data, sourceMap, tags}) => ({\n // data:\n // stega && sourceMap\n // ? stegaEncodeSourceMap(data, sourceMap, {...stegaConfig, enabled: true})\n // : data,\n // sourceMap,\n // tags,\n // }))\n }\n\n const Live: React.ComponentType<DefinedLiveProps> = function Live(props) {\n const {\n perspective = 'published',\n onChange,\n onChangeIncludingDrafts,\n onStudioPerspective,\n refreshOnMount = false,\n refreshOnFocus = false,\n refreshOnReconnect = false,\n requestTag = 'next-loader.live.cache-components',\n onError,\n onGoAway,\n intervalOnGoAway,\n } = props\n\n if (onChangeIncludingDrafts) {\n console.warn('`onChangeIncludingDrafts` is not implemented yet')\n }\n if (onStudioPerspective) {\n console.warn('`onStudioPerspective` is not implemented yet')\n }\n\n const includeDrafts = typeof browserToken === 'string' && perspective !== 'published'\n\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n const {origin} = new URL(client.getUrl('', false))\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 preconnect(origin)\n\n return (\n <Suspense>\n <SanityLiveClientComponent\n config={{\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n requestTagPrefix,\n token: includeDrafts ? browserToken : undefined,\n }}\n requestTag={requestTag}\n // origin={origin}\n draftModeEnabled={includeDrafts}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n revalidateSyncTags={onChange}\n resolveDraftModePerspective={resolveDraftModePerspective}\n />\n </Suspense>\n )\n }\n\n return {\n fetch,\n Live,\n sanityFetch: () => {\n throw new Error(\n '`defineLive().sanityFetch` is not available when `cacheComponents: true`, use `defineLive().fetch` instead',\n )\n },\n SanityLive: () => {\n throw new Error(\n '`defineLive().SanityLive` is not available when `cacheComponents: true`, use `defineLive().Live` instead',\n )\n },\n }\n}\n\nasync function resolveDraftModePerspective(): Promise<PerspectiveType> {\n 'use server'\n if ((await draftMode()).isEnabled) {\n const jar = await cookies()\n return resolvePerspectiveFromCookies({cookies: jar})\n }\n return 'published'\n}\n\n// revalidateSyncTags => actionUpdateTags\n// router.refresh() => actionRefresh\n"],"mappings":";;;;;;;;;AAaA,SAAgB,WAAW,QAWzB;CACA,MAAM,EAAC,QAAQ,SAAS,aAAa,iBAAgB;AAErD,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,kBAAiB,OAAO,QAAQ;AAgI9C,QAAO;EACL,OA/H8B,eAAe,MAAM,EACnD,OACA,SAAS,EAAE,EACX,cAAc,aACd,QAAQ,OACR,MAAM,kBAAkB,EAAE,EAC1B,aAAa,wCACZ;GACD,MAAM,SAAS,gBAAgB;GAE/B,MAAM,EAAC,QAAQ,iBAAiB,aAAY,MAAM,OAAO,MAAM,OAAO,QAA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 +1,5 @@
1
- import { t as isCorsOriginError } from "./isCorsOriginError.js";
2
- import { c as PerspectiveType, i as defineLive, u as resolvePerspectiveFromCookies } from "./defineLive.js";
3
- export { type PerspectiveType as LivePerspective, defineLive, isCorsOriginError, resolvePerspectiveFromCookies };
1
+ import { i as defineLive } from "./defineLive.js";
2
+ import { isCorsOriginError } from "#live/isCorsOriginError";
3
+ import { resolvePerspectiveFromCookies } from "#live/resolvePerspectiveFromCookies";
4
+ import { PerspectiveType as LivePerspective } from "#live/types";
5
+ export { type LivePerspective, defineLive, isCorsOriginError, resolvePerspectiveFromCookies };
@@ -1,10 +1,10 @@
1
- import { t as isCorsOriginError } from "./isCorsOriginError.js";
2
- import { t as sanitizePerspective } from "./sanitizePerspective.js";
3
- import { t as resolvePerspectiveFromCookies } from "./resolvePerspectiveFromCookies.js";
4
1
  import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
5
2
  import { cookies, draftMode } from "next/headers";
6
3
  import { jsx } from "react/jsx-runtime";
4
+ import { isCorsOriginError } from "#live/isCorsOriginError";
5
+ import { sanitizePerspective } from "#live/sanitizePerspective";
7
6
  import "@sanity/client";
7
+ import { resolvePerspectiveFromCookies } from "#live/resolvePerspectiveFromCookies";
8
8
  import { preconnect, prefetchDNS } from "react-dom";
9
9
  import SanityLiveClientComponent from "next-sanity/live/client-components/live";
10
10
  async function resolveCookiePerspective() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "next-sanity",
3
- "version": "13.0.0-cache-components.7",
3
+ "version": "13.0.0-cache-components.9",
4
4
  "description": "Sanity.io toolkit for Next.js",
5
5
  "keywords": [
6
6
  "live",
@@ -27,8 +27,6 @@
27
27
  ],
28
28
  "type": "module",
29
29
  "sideEffects": false,
30
- "main": "./dist/index.js",
31
- "module": "./dist/index.js",
32
30
  "types": "./dist/index.d.ts",
33
31
  "imports": {
34
32
  "#client-components/*": "./src/shared/client-components/*.tsx",
@@ -57,14 +55,14 @@
57
55
  "./package.json": "./package.json"
58
56
  },
59
57
  "dependencies": {
60
- "@portabletext/react": "^6.0.0",
58
+ "@portabletext/react": "^6.0.1",
61
59
  "@sanity/client": "^7.13.2",
62
60
  "@sanity/comlink": "^4.0.1",
63
61
  "@sanity/presentation-comlink": "^2.0.1",
64
62
  "@sanity/preview-url-secret": "^4.0.1",
65
63
  "@sanity/visual-editing": "^5.0.3",
66
64
  "dequal": "^2.0.3",
67
- "groq": "^5.0.1",
65
+ "groq": "^5.1.0",
68
66
  "history": "^5.3.0"
69
67
  },
70
68
  "devDependencies": {
@@ -75,12 +73,12 @@
75
73
  "@types/react": "^19.2.7",
76
74
  "@types/react-dom": "^19.2.3",
77
75
  "@vitest/coverage-v8": "^4.0.16",
78
- "next": "16.1.1-canary.0",
76
+ "next": "16.1.1-canary.10",
79
77
  "publint": "^0.3.16",
80
78
  "react": "^19.2.3",
81
79
  "react-dom": "^19.2.3",
82
80
  "styled-components": "^6.1.19",
83
- "tsdown": "0.18.1",
81
+ "tsdown": "0.18.4",
84
82
  "typescript": "5.9.3",
85
83
  "vitest": "^4.0.16"
86
84
  },
@@ -89,7 +87,7 @@
89
87
  "next": "^16.0.0-0",
90
88
  "react": "^19.2.3",
91
89
  "react-dom": "^19.2.3",
92
- "sanity": "^5.0.1",
90
+ "sanity": "^5.1.0",
93
91
  "styled-components": "^6.1"
94
92
  },
95
93
  "browserslist": "extends @sanity/browserslist-config",
package/dist/context.js DELETED
@@ -1,29 +0,0 @@
1
- const perspectiveListeners = /* @__PURE__ */ new Set();
2
- let perspective = "checking";
3
- function setPerspective(nextPerspective) {
4
- if (perspective.toString() === nextPerspective.toString()) return;
5
- perspective = nextPerspective;
6
- for (const onPerspectiveChange of perspectiveListeners) onPerspectiveChange();
7
- }
8
- const environmentListeners = /* @__PURE__ */ new Set();
9
- let environment = "checking";
10
- function setEnvironment(nextEnvironment) {
11
- environment = nextEnvironment;
12
- for (const onEnvironmentChange of environmentListeners) onEnvironmentChange();
13
- }
14
- const comlinkListeners = /* @__PURE__ */ new Set();
15
- let comlink = null;
16
- let comlinkProjectId = null;
17
- let comlinkDataset = null;
18
- function setComlink(nextComlink) {
19
- comlink = nextComlink;
20
- for (const onComlinkChange of comlinkListeners) onComlinkChange();
21
- }
22
- function setComlinkClientConfig(nextComlinkProjectId, nextComlinkDataset) {
23
- comlinkProjectId = nextComlinkProjectId;
24
- comlinkDataset = nextComlinkDataset;
25
- for (const onComlinkChange of comlinkListeners) onComlinkChange();
26
- }
27
- export { environment as a, perspectiveListeners as c, setEnvironment as d, setPerspective as f, comlinkProjectId as i, setComlink as l, comlinkDataset as n, environmentListeners as o, comlinkListeners as r, perspective as s, comlink as t, setComlinkClientConfig as u };
28
-
29
- //# sourceMappingURL=context.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"context.js","names":["perspectiveListeners: Set<() => void>","perspective: LivePerspective","environmentListeners: Set<() => void>","environment: LiveEnvironment","comlinkListeners: Set<() => void>","comlink: Node<LoaderNodeMsg, LoaderControllerMsg> | null","comlinkProjectId: string | null","comlinkDataset: string | null"],"sources":["../src/shared/client-components/context.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\nimport type {Node} from '@sanity/comlink'\nimport type {LoaderControllerMsg, LoaderNodeMsg} from '@sanity/presentation-comlink'\n\nexport type LivePerspective = 'checking' | 'unknown' | ClientPerspective\n\nexport const perspectiveListeners: Set<() => void> = new Set()\nexport let perspective: LivePerspective = 'checking'\nexport function setPerspective(nextPerspective: LivePerspective): void {\n if (perspective.toString() === nextPerspective.toString()) return\n perspective = nextPerspective\n for (const onPerspectiveChange of perspectiveListeners) {\n onPerspectiveChange()\n }\n}\n\nexport type LiveEnvironment =\n | 'checking'\n | 'presentation-iframe'\n | 'presentation-window'\n | 'live'\n | 'static'\n | 'unknown'\n\nexport const environmentListeners: Set<() => void> = new Set()\nexport let environment: LiveEnvironment = 'checking'\nexport function setEnvironment(nextEnvironment: LiveEnvironment): void {\n environment = nextEnvironment\n for (const onEnvironmentChange of environmentListeners) {\n onEnvironmentChange()\n }\n}\n\nexport const comlinkListeners: Set<() => void> = new Set()\nexport let comlink: Node<LoaderNodeMsg, LoaderControllerMsg> | null = null\nexport let comlinkProjectId: string | null = null\nexport let comlinkDataset: string | null = null\nexport function setComlink(nextComlink: Node<LoaderNodeMsg, LoaderControllerMsg> | null): void {\n comlink = nextComlink\n for (const onComlinkChange of comlinkListeners) {\n onComlinkChange()\n }\n}\nexport function setComlinkClientConfig(\n nextComlinkProjectId: string | null,\n nextComlinkDataset: string | null,\n): void {\n comlinkProjectId = nextComlinkProjectId\n comlinkDataset = nextComlinkDataset\n for (const onComlinkChange of comlinkListeners) {\n onComlinkChange()\n }\n}\n"],"mappings":"AAMA,MAAaA,uCAAwC,IAAI,KAAK;AAC9D,IAAWC,cAA+B;AAC1C,SAAgB,eAAe,iBAAwC;AACrE,KAAI,YAAY,UAAU,KAAK,gBAAgB,UAAU,CAAE;AAC3D,eAAc;AACd,MAAK,MAAM,uBAAuB,qBAChC,sBAAqB;;AAYzB,MAAaC,uCAAwC,IAAI,KAAK;AAC9D,IAAWC,cAA+B;AAC1C,SAAgB,eAAe,iBAAwC;AACrE,eAAc;AACd,MAAK,MAAM,uBAAuB,qBAChC,sBAAqB;;AAIzB,MAAaC,mCAAoC,IAAI,KAAK;AAC1D,IAAWC,UAA2D;AACtE,IAAWC,mBAAkC;AAC7C,IAAWC,iBAAgC;AAC3C,SAAgB,WAAW,aAAoE;AAC7F,WAAU;AACV,MAAK,MAAM,mBAAmB,iBAC5B,kBAAiB;;AAGrB,SAAgB,uBACd,sBACA,oBACM;AACN,oBAAmB;AACnB,kBAAiB;AACjB,MAAK,MAAM,mBAAmB,iBAC5B,kBAAiB"}
@@ -1,5 +0,0 @@
1
- import { CorsOriginError } from "@sanity/client";
2
- /** @public */
3
- declare function isCorsOriginError(error: unknown): error is CorsOriginError;
4
- export { isCorsOriginError as t };
5
- //# sourceMappingURL=isCorsOriginError.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"isCorsOriginError.d.ts","names":[],"sources":["../src/shared/live/isCorsOriginError.ts"],"sourcesContent":[],"mappings":";;AAGgB,iBAAA,iBAAA,CAA4C,KAAA,EAAA,OAAA,CAAA,EAAA,KAAA,IAAA,eAAA"}
@@ -1,6 +0,0 @@
1
- function isCorsOriginError(error) {
2
- return error instanceof Error && error.name === "CorsOriginError";
3
- }
4
- export { isCorsOriginError as t };
5
-
6
- //# sourceMappingURL=isCorsOriginError.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"isCorsOriginError.js","names":[],"sources":["../src/shared/live/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,8 +0,0 @@
1
- import { t as sanitizePerspective } from "./sanitizePerspective.js";
2
- import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
3
- const resolvePerspectiveFromCookies = async function resolvePerspectiveFromCookies$1({ cookies: jar }) {
4
- return jar.has(perspectiveCookieName) ? sanitizePerspective(jar.get(perspectiveCookieName)?.value, "drafts") : "drafts";
5
- };
6
- export { resolvePerspectiveFromCookies as t };
7
-
8
- //# sourceMappingURL=resolvePerspectiveFromCookies.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"resolvePerspectiveFromCookies.js","names":["resolvePerspectiveFromCookies"],"sources":["../src/shared/live/resolvePerspectiveFromCookies.ts"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\nimport type {cookies} from 'next/headers'\n\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\n\nexport type ResolvePerspectiveFromCookies = (options: {\n /**\n * You must await the cookies() function from next/headers\n * and pass it here.\n * Example:\n * ```ts\n * import { cookies } from 'next/headers'\n *\n * const perspective = await resolvePerspectiveFromCookies({cookies: await cookies()})\n * ```\n */\n cookies: Awaited<ReturnType<typeof cookies>>\n}) => Promise<Exclude<ClientPerspective, 'raw'>>\n\n/**\n * Resolves the perspective from the cookie that is set by `import { defineEnableDraftMode } from \"next-sanity/draft-mode\"`\n * @public\n */\nexport const 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":";;AAwBA,MAAa,gCAAgC,eAAeA,gCAA8B,EACxF,SAAS,OAGoC;AAC7C,QAAO,IAAI,IAAI,sBAAsB,GACjC,oBAAoB,IAAI,IAAI,sBAAsB,EAAE,OAAO,SAAS,GACpE"}
@@ -1,14 +0,0 @@
1
- import { validateApiPerspective } from "@sanity/client";
2
- function sanitizePerspective(_perspective, fallback) {
3
- const perspective = typeof _perspective === "string" && _perspective.includes(",") ? _perspective.split(",") : _perspective;
4
- try {
5
- validateApiPerspective(perspective);
6
- return perspective === "raw" ? fallback : perspective;
7
- } catch (err) {
8
- console.warn(`Invalid perspective:`, _perspective, perspective, err);
9
- return fallback;
10
- }
11
- }
12
- export { sanitizePerspective as t };
13
-
14
- //# sourceMappingURL=sanitizePerspective.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sanitizePerspective.js","names":[],"sources":["../src/shared/live/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"}