next-sanity 13.0.0-cache-components.13 → 13.0.0-cache-components.15

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 (61) hide show
  1. package/dist/PresentationComlink.js +3 -3
  2. package/dist/PresentationComlink.js.map +1 -1
  3. package/dist/RefreshOnFocus.js.map +1 -1
  4. package/dist/RefreshOnMount.js +2 -2
  5. package/dist/RefreshOnMount.js.map +1 -1
  6. package/dist/RefreshOnReconnect.js.map +1 -1
  7. package/dist/{live/client-components/live/index.js → SanityLive.js} +23 -46
  8. package/dist/SanityLive.js.map +1 -0
  9. package/dist/constants.js.map +1 -1
  10. package/dist/context.js.map +1 -1
  11. package/dist/defineLive.d.ts +5 -50
  12. package/dist/defineLive.d.ts.map +1 -1
  13. package/dist/hooks/index.d.ts +1 -1
  14. package/dist/hooks/index.d.ts.map +1 -1
  15. package/dist/hooks/index.js.map +1 -1
  16. package/dist/isCorsOriginError.d.ts.map +1 -1
  17. package/dist/isCorsOriginError.js.map +1 -1
  18. package/dist/{experimental/client-components/live.d.ts → live/client-components/index.d.ts} +12 -11
  19. package/dist/live/client-components/index.d.ts.map +1 -0
  20. package/dist/live/client-components/index.js +6 -0
  21. package/dist/live/client-components/index.js.map +1 -0
  22. package/dist/{live.d.ts → live/conditions/default/index.d.ts} +3 -3
  23. package/dist/live/conditions/default/index.d.ts.map +1 -0
  24. package/dist/{live.js → live/conditions/default/index.js} +2 -2
  25. package/dist/live/conditions/default/index.js.map +1 -0
  26. package/dist/live/conditions/next-js/index.d.ts +8 -0
  27. package/dist/live/conditions/next-js/index.d.ts.map +1 -0
  28. package/dist/live/conditions/next-js/index.js +78 -0
  29. package/dist/live/conditions/next-js/index.js.map +1 -0
  30. package/dist/live/conditions/react-server/index.d.ts +3 -0
  31. package/dist/live/conditions/react-server/index.js +100 -0
  32. package/dist/live/conditions/react-server/index.js.map +1 -0
  33. package/dist/live/server-actions/index.default.d.ts +15 -0
  34. package/dist/live/server-actions/index.default.d.ts.map +1 -0
  35. package/dist/live/server-actions/{index.js → index.default.js} +26 -13
  36. package/dist/live/server-actions/index.default.js.map +1 -0
  37. package/dist/live/server-actions/index.next-js.d.ts +15 -0
  38. package/dist/live/server-actions/index.next-js.d.ts.map +1 -0
  39. package/dist/live/server-actions/index.next-js.js +52 -0
  40. package/dist/live/server-actions/index.next-js.js.map +1 -0
  41. package/dist/resolvePerspectiveFromCookies.js.map +1 -1
  42. package/dist/sanitizePerspective.js.map +1 -1
  43. package/package.json +18 -17
  44. package/dist/experimental/client-components/live.d.ts.map +0 -1
  45. package/dist/experimental/client-components/live.js +0 -179
  46. package/dist/experimental/client-components/live.js.map +0 -1
  47. package/dist/live/client-components/live/index.d.ts +0 -26
  48. package/dist/live/client-components/live/index.d.ts.map +0 -1
  49. package/dist/live/client-components/live/index.js.map +0 -1
  50. package/dist/live/server-actions/index.d.ts +0 -6
  51. package/dist/live/server-actions/index.d.ts.map +0 -1
  52. package/dist/live/server-actions/index.js.map +0 -1
  53. package/dist/live.d.ts.map +0 -1
  54. package/dist/live.js.map +0 -1
  55. package/dist/live.next-js.d.ts +0 -16
  56. package/dist/live.next-js.d.ts.map +0 -1
  57. package/dist/live.next-js.js +0 -87
  58. package/dist/live.next-js.js.map +0 -1
  59. package/dist/live.react-server.d.ts +0 -3
  60. package/dist/live.react-server.js +0 -94
  61. package/dist/live.react-server.js.map +0 -1
@@ -0,0 +1,78 @@
1
+ import { n as PUBLISHED_SYNC_TAG_PREFIX, r as revalidate, t as DRAFT_SYNC_TAG_PREFIX } from "../../../constants.js";
2
+ import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
3
+ import { t as resolvePerspectiveFromCookies } from "../../../resolvePerspectiveFromCookies.js";
4
+ import { Suspense } from "react";
5
+ import { jsx } from "react/jsx-runtime";
6
+ import { SanityLive } from "next-sanity/live/client-components";
7
+ import { actionLiveEvent, actionLiveEventIncludingDrafts, actionStudioPerspective } from "next-sanity/live/server-actions";
8
+ import { cacheLife, cacheTag } from "next/cache";
9
+ import { preconnect } from "react-dom";
10
+ function defineLive(config) {
11
+ const { client: _client, serverToken, browserToken } = config;
12
+ if (!_client) throw new Error("`client` is required for `defineLive` to function");
13
+ if (process.env.NODE_ENV !== "production" && !serverToken && serverToken !== false) console.warn("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`.");
14
+ if (process.env.NODE_ENV !== "production" && !browserToken && browserToken !== false) console.warn("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`.");
15
+ const client = _client.withConfig({
16
+ allowReconfigure: false,
17
+ useCdn: true
18
+ });
19
+ const { token: originalToken } = client.config();
20
+ const fetch = async function fetch$1({ query, params = {}, perspective = "published", stega = false, tags: customCacheTags = [], requestTag = "next-loader.fetch.cache-components" }) {
21
+ const useCdn = perspective === "published";
22
+ const { result, resultSourceMap, syncTags } = await client.fetch(query, params, {
23
+ filterResponse: false,
24
+ returnQuery: false,
25
+ perspective,
26
+ useCdn,
27
+ stega,
28
+ cacheMode: useCdn ? "noStale" : void 0,
29
+ tag: requestTag,
30
+ token: perspective === "published" ? originalToken : serverToken || originalToken
31
+ });
32
+ const tags = [...customCacheTags, ...(syncTags || []).map((tag) => `${perspective === "published" ? PUBLISHED_SYNC_TAG_PREFIX : DRAFT_SYNC_TAG_PREFIX}${tag}`)];
33
+ cacheTag(...tags);
34
+ cacheLife({ revalidate });
35
+ return {
36
+ data: result,
37
+ sourceMap: resultSourceMap || null,
38
+ tags
39
+ };
40
+ };
41
+ const Live = function Live$1(props) {
42
+ const { perspective = "published", onChange = actionLiveEvent, onChangeIncludingDrafts = actionLiveEventIncludingDrafts, onStudioPerspective = actionStudioPerspective, refreshOnMount = false, refreshOnFocus = false, refreshOnReconnect = false, requestTag = "next-loader.live.cache-components", onError, onGoAway, intervalOnGoAway } = props;
43
+ const includeDrafts = typeof browserToken === "string" && perspective !== "published";
44
+ const { projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix } = client.config();
45
+ const { origin } = new URL(client.getUrl("", false));
46
+ preconnect(origin);
47
+ return /* @__PURE__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(SanityLive, {
48
+ config: {
49
+ projectId,
50
+ dataset,
51
+ apiHost,
52
+ apiVersion,
53
+ useProjectHostname,
54
+ requestTagPrefix,
55
+ token: includeDrafts ? browserToken : void 0
56
+ },
57
+ perspective,
58
+ onLiveEvent: onChange,
59
+ onLiveEventIncludingDrafts: onChangeIncludingDrafts,
60
+ onPresentationPerspective: onStudioPerspective,
61
+ requestTag,
62
+ refreshOnMount,
63
+ refreshOnFocus,
64
+ refreshOnReconnect,
65
+ onError,
66
+ onGoAway,
67
+ intervalOnGoAway
68
+ }) });
69
+ };
70
+ Live.displayName = "DefinedSanityLive";
71
+ return {
72
+ sanityFetch: fetch,
73
+ SanityLive: Live
74
+ };
75
+ }
76
+ export { defineLive, isCorsOriginError, resolvePerspectiveFromCookies };
77
+
78
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["fetch","Live","SanityLiveClientComponent"],"sources":["../../../../src/live/conditions/next-js/defineLive.tsx"],"sourcesContent":["import type {DefinedFetchType, DefinedLiveProps, LiveOptions} from '#live/types'\n\nimport {DRAFT_SYNC_TAG_PREFIX, PUBLISHED_SYNC_TAG_PREFIX, revalidate} from '#live/constants'\nimport {SanityLive as SanityLiveClientComponent} from 'next-sanity/live/client-components'\nimport {\n actionStudioPerspective,\n actionLiveEvent,\n actionLiveEventIncludingDrafts,\n} from 'next-sanity/live/server-actions'\nimport {cacheLife, cacheTag} from 'next/cache'\nimport {Suspense} from 'react'\nimport {preconnect} from 'react-dom'\n\nimport type {DefinedSanityFetchType, DefinedSanityLiveProps} from '../react-server/defineLive'\n\nexport function defineLive(config: LiveOptions): {\n sanityFetch: DefinedSanityFetchType\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 * userland can still set a shorter revalidate time by calling `cacheLife` themselves.\n */\n cacheLife({revalidate})\n\n return {data: result, sourceMap: resultSourceMap || null, tags}\n }\n\n const Live: React.ComponentType<DefinedLiveProps> = function Live(props) {\n const {\n perspective = 'published',\n onChange = actionLiveEvent,\n onChangeIncludingDrafts = actionLiveEventIncludingDrafts,\n onStudioPerspective = actionStudioPerspective,\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 const includeDrafts = typeof browserToken === 'string' && perspective !== 'published'\n\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n\n // Preconnect to the Live Event API origin early, as the Sanity API is almost always on a different origin than the app\n const {origin} = new URL(client.getUrl('', false))\n preconnect(origin)\n\n return (\n <Suspense>\n <SanityLiveClientComponent\n config={{\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n requestTagPrefix,\n token: includeDrafts ? browserToken : undefined,\n }}\n perspective={perspective}\n onLiveEvent={onChange}\n onLiveEventIncludingDrafts={onChangeIncludingDrafts}\n onPresentationPerspective={onStudioPerspective}\n requestTag={requestTag}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n />\n </Suspense>\n )\n }\n Live.displayName = 'DefinedSanityLive'\n\n return {\n sanityFetch: fetch,\n SanityLive: Live,\n }\n}\n"],"mappings":";;;;;;;;;AAeA,SAAgB,WAAW,QAGzB;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;CAE9C,MAAM,QAA0B,eAAeA,QAAM,EACnD,OACA,SAAS,EAAE,EACX,cAAc,aACd,QAAQ,OACR,MAAM,kBAAkB,EAAE,EAC1B,aAAa,wCACZ;EACD,MAAM,SAAS,gBAAgB;EAE/B,MAAM,EAAC,QAAQ,iBAAiB,aAAY,MAAM,OAAO,MAAM,OAAO,QAAQ;GAC5E,gBAAgB;GAChB,aAAa;GACb;GACA;GACA;GACA,WAAW,SAAS,YAAY,KAAA;GAChC,KAAK;GACL,OAAO,gBAAgB,cAAc,gBAAgB,eAAe;GACrE,CAAC;EACF,MAAM,OAAO,CACX,GAAG,iBACH,IAAI,YAAY,EAAE,EAAE,KACjB,QACC,GAAG,gBAAgB,cAAc,4BAA4B,wBAAwB,MACxF,CACF;AAID,WAAS,GAAG,KAAK;AAKjB,YAAU,EAAC,YAAW,CAAC;AAEvB,SAAO;GAAC,MAAM;GAAQ,WAAW,mBAAmB;GAAM;GAAK;;CAGjE,MAAM,OAA8C,SAASC,OAAK,OAAO;EACvE,MAAM,EACJ,cAAc,aACd,WAAW,iBACX,0BAA0B,gCAC1B,sBAAsB,yBACtB,iBAAiB,OACjB,iBAAiB,OACjB,qBAAqB,OACrB,aAAa,qCACb,SACA,UACA,qBACE;EAEJ,MAAM,gBAAgB,OAAO,iBAAiB,YAAY,gBAAgB;EAE1E,MAAM,EAAC,WAAW,SAAS,SAAS,YAAY,oBAAoB,qBAClE,OAAO,QAAQ;EAGjB,MAAM,EAAC,WAAU,IAAI,IAAI,OAAO,OAAO,IAAI,MAAM,CAAC;AAClD,aAAW,OAAO;AAElB,SACE,oBAAC,UAAA,EAAA,UACC,oBAACC,YAAAA;GACC,QAAQ;IACN;IACA;IACA;IACA;IACA;IACA;IACA,OAAO,gBAAgB,eAAe,KAAA;IACvC;GACY;GACb,aAAa;GACb,4BAA4B;GAC5B,2BAA2B;GACf;GACI;GACA;GACI;GACX;GACC;GACQ;IAClB,EAAA,CACO;;AAGf,MAAK,cAAc;AAEnB,QAAO;EACL,aAAa;EACb,YAAY;EACb"}
@@ -0,0 +1,3 @@
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 };
@@ -0,0 +1,100 @@
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
+ import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
5
+ import { cookies, draftMode } from "next/headers";
6
+ import { jsx } from "react/jsx-runtime";
7
+ import { SanityLive } from "next-sanity/live/client-components";
8
+ import { actionLiveEvent, actionLiveEventIncludingDrafts, actionStudioPerspective } from "next-sanity/live/server-actions";
9
+ import { preconnect } from "react-dom";
10
+ function defineLive(config) {
11
+ const { client: _client, serverToken, browserToken, fetchOptions, stega: stegaEnabled = true } = config;
12
+ if (!_client) throw new Error("`client` is required for `defineLive` to function");
13
+ if (process.env.NODE_ENV !== "production" && !serverToken && serverToken !== false) console.warn("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`.");
14
+ if (process.env.NODE_ENV !== "production" && !browserToken && browserToken !== false) console.warn("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`.");
15
+ const client = _client.withConfig({
16
+ allowReconfigure: false,
17
+ useCdn: false
18
+ });
19
+ const { token: originalToken } = client.config();
20
+ const studioUrlDefined = typeof client.config().stega.studioUrl !== "undefined";
21
+ const sanityFetch = async function sanityFetch$1({ query, params = {}, stega: _stega, tags = ["sanity"], perspective: _perspective, tag, requestTag = tag ?? "next-loader.fetch" }) {
22
+ const stega = _stega ?? (stegaEnabled && studioUrlDefined && (await draftMode()).isEnabled);
23
+ const perspective = _perspective ?? await resolveCookiePerspective();
24
+ const useCdn = perspective === "published";
25
+ const revalidate = fetchOptions?.revalidate !== void 0 ? fetchOptions.revalidate : process.env.NODE_ENV === "production" ? false : void 0;
26
+ const { syncTags } = await client.fetch(query, await params, {
27
+ filterResponse: false,
28
+ perspective,
29
+ stega: false,
30
+ returnQuery: false,
31
+ next: {
32
+ revalidate,
33
+ tags: [...tags, "sanity:fetch-sync-tags"]
34
+ },
35
+ useCdn,
36
+ cacheMode: useCdn ? "noStale" : void 0,
37
+ tag: [requestTag, "fetch-sync-tags"].filter(Boolean).join(".")
38
+ });
39
+ const cacheTags = [...tags, ...syncTags?.map((tag$1) => `sanity:${tag$1}`) || []];
40
+ const { result, resultSourceMap } = await client.fetch(query, await params, {
41
+ filterResponse: false,
42
+ perspective,
43
+ stega,
44
+ token: perspective !== "published" && serverToken ? serverToken : originalToken,
45
+ next: {
46
+ revalidate,
47
+ tags: cacheTags
48
+ },
49
+ useCdn,
50
+ cacheMode: useCdn ? "noStale" : void 0,
51
+ tag: requestTag
52
+ });
53
+ return {
54
+ data: result,
55
+ sourceMap: resultSourceMap || null,
56
+ tags: cacheTags
57
+ };
58
+ };
59
+ const SanityLive$1 = async function SanityLive$2(props) {
60
+ const { onChange = actionLiveEvent, onChangeIncludingDrafts = actionLiveEventIncludingDrafts, onStudioPerspective = actionStudioPerspective, refreshOnMount, refreshOnFocus, refreshOnReconnect, requestTag = "next-loader.live", onError, onGoAway, intervalOnGoAway, perspective: _perspective } = props;
61
+ const { projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix } = client.config();
62
+ const perspective = _perspective ?? await resolveCookiePerspective();
63
+ const includeDrafts = typeof browserToken === "string" && perspective !== "published";
64
+ const { origin } = new URL(client.getUrl("", false));
65
+ preconnect(origin);
66
+ return /* @__PURE__ */ jsx(SanityLive, {
67
+ config: {
68
+ projectId,
69
+ dataset,
70
+ apiHost,
71
+ apiVersion,
72
+ useProjectHostname,
73
+ requestTagPrefix,
74
+ token: includeDrafts ? browserToken : void 0
75
+ },
76
+ perspective: await resolveCookiePerspective(),
77
+ onLiveEvent: onChange,
78
+ onLiveEventIncludingDrafts: onChangeIncludingDrafts,
79
+ onPresentationPerspective: onStudioPerspective,
80
+ requestTag,
81
+ refreshOnMount,
82
+ refreshOnFocus,
83
+ refreshOnReconnect,
84
+ onError,
85
+ onGoAway,
86
+ intervalOnGoAway
87
+ });
88
+ };
89
+ SanityLive$1.displayName = "DefinedSanityLive";
90
+ return {
91
+ sanityFetch,
92
+ SanityLive: SanityLive$1
93
+ };
94
+ }
95
+ async function resolveCookiePerspective() {
96
+ return (await draftMode()).isEnabled ? (await cookies()).has(perspectiveCookieName) ? sanitizePerspective((await cookies()).get(perspectiveCookieName)?.value, "drafts") : "drafts" : "published";
97
+ }
98
+ export { defineLive, isCorsOriginError, resolvePerspectiveFromCookies };
99
+
100
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["sanityFetch","tag","SanityLive","SanityLiveClientComponent"],"sources":["../../../../src/live/conditions/react-server/defineLive.tsx"],"sourcesContent":["import type {DefinedLiveProps, PerspectiveType} from '#live/types'\n\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {\n type ClientPerspective,\n type ClientReturn,\n type ContentSourceMap,\n type QueryParams,\n type SanityClient,\n} from '@sanity/client'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {SanityLive as SanityLiveClientComponent} from 'next-sanity/live/client-components'\nimport {\n actionStudioPerspective,\n actionLiveEvent,\n actionLiveEventIncludingDrafts,\n} from 'next-sanity/live/server-actions'\nimport {cookies, draftMode} from 'next/headers'\nimport {preconnect} from 'react-dom'\n\n/**\n * @public\n */\nexport type DefinedSanityFetchType = <const QueryString extends string>(options: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n /**\n * Add custom `next.tags` to the underlying fetch request.\n * @see https://nextjs.org/docs/app/api-reference/functions/fetch#optionsnexttags\n * This can be used in conjunction with custom fallback revalidation strategies, as well as with custom Server Actions that mutate data and want to render with fresh data right away (faster than the Live Event latency).\n * @defaultValue `['sanity']`\n */\n tags?: string[]\n perspective?: Exclude<ClientPerspective, 'raw'>\n stega?: boolean\n /**\n * This request tag is used to identify the request when viewing request logs from your Sanity Content Lake.\n * @see https://www.sanity.io/docs/reference-api-request-tags\n * @defaultValue 'next-loader.fetch'\n */\n requestTag?: string\n}) => Promise<{\n data: ClientReturn<QueryString>\n sourceMap: ContentSourceMap | null\n tags: string[]\n}>\n\n/**\n * @public\n */\nexport interface DefinedSanityLiveProps extends DefinedLiveProps {\n /**\n * @defaultValue `automatically resolved`\n */\n perspective?: PerspectiveType\n}\n\n/**\n * @public\n */\nexport interface DefineSanityLiveOptions {\n /**\n * Required for `sanityFetch` and `SanityLive` to work\n */\n client: SanityClient\n /**\n * Optional. If provided then the token needs to have permissions to query documents with `drafts.` prefixes in order for `perspective: 'drafts'` to work.\n * This token is not shared with the browser.\n */\n serverToken?: string | false\n /**\n * Optional. This token is shared with the browser, and should only have access to query published documents.\n * It is used to setup a `Live Draft Content` EventSource connection, and enables live previewing drafts stand-alone, outside of Presentation Tool.\n */\n browserToken?: string | false\n /**\n * Fetch options used by `sanityFetch`\n */\n fetchOptions?: {\n /**\n * Optional, enables time based revalidation in addition to the EventSource connection.\n * @defaultValue `false`\n */\n revalidate?: number | false\n }\n /**\n * Optional. Include stega encoding when draft mode is enabled.\n * @defaultValue `true`\n */\n stega?: boolean\n}\n\nexport function defineLive(config: DefineSanityLiveOptions): {\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 // fetch: DefinedFetchType\n // Live: React.ComponentType<DefinedLiveProps>\n} {\n const {\n client: _client,\n serverToken,\n browserToken,\n fetchOptions,\n stega: stegaEnabled = true,\n } = config\n\n if (!_client) {\n throw new Error('`client` is required for `defineLive` to function')\n }\n\n if (process.env.NODE_ENV !== 'production' && !serverToken && serverToken !== false) {\n console.warn(\n 'No `serverToken` provided to `defineLive`. This means that only published content will be fetched and respond to live events. You can silence this warning by setting `serverToken: false`.',\n )\n }\n\n if (process.env.NODE_ENV !== 'production' && !browserToken && browserToken !== false) {\n console.warn(\n 'No `browserToken` provided to `defineLive`. This means that live previewing drafts will only work when using the Presentation Tool in your Sanity Studio. To support live previewing drafts stand-alone, provide a `browserToken`. It is shared with the browser so it should only have Viewer rights or lower. You can silence this warning by setting `browserToken: false`.',\n )\n }\n\n const client = _client.withConfig({allowReconfigure: false, useCdn: false})\n const {token: originalToken} = client.config()\n const studioUrlDefined = typeof client.config().stega.studioUrl !== 'undefined'\n\n const sanityFetch: DefinedSanityFetchType = async function sanityFetch<\n const QueryString extends string,\n >({\n query,\n params = {},\n stega: _stega,\n tags = ['sanity'],\n perspective: _perspective,\n tag,\n requestTag = tag ?? 'next-loader.fetch',\n }: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n stega?: boolean\n tags?: string[]\n perspective?: Exclude<ClientPerspective, 'raw'>\n tag?: string\n requestTag?: string\n }) {\n const stega = _stega ?? (stegaEnabled && studioUrlDefined && (await draftMode()).isEnabled)\n const perspective = _perspective ?? (await resolveCookiePerspective())\n const useCdn = perspective === 'published'\n const revalidate =\n fetchOptions?.revalidate !== undefined\n ? fetchOptions.revalidate\n : process.env.NODE_ENV === 'production'\n ? false\n : undefined\n\n // fetch the tags first, with revalidate to 1s to ensure we get the latest tags, eventually\n const {syncTags} = await client.fetch(query, await params, {\n filterResponse: false,\n perspective: perspective as ClientPerspective,\n stega: false,\n returnQuery: false,\n next: {revalidate, tags: [...tags, 'sanity:fetch-sync-tags']},\n useCdn,\n cacheMode: useCdn ? 'noStale' : undefined,\n tag: [requestTag, 'fetch-sync-tags'].filter(Boolean).join('.'),\n })\n\n const cacheTags = [...tags, ...(syncTags?.map((tag) => `sanity:${tag}`) || [])]\n\n const {result, resultSourceMap} = await client.fetch(query, await params, {\n filterResponse: false,\n perspective: perspective as ClientPerspective,\n stega,\n token: perspective !== 'published' && serverToken ? serverToken : originalToken,\n next: {revalidate, tags: cacheTags},\n useCdn,\n cacheMode: useCdn ? 'noStale' : undefined,\n tag: requestTag,\n })\n return {data: result, sourceMap: resultSourceMap || null, tags: cacheTags}\n }\n\n const SanityLive: React.ComponentType<DefinedSanityLiveProps> = async function SanityLive(props) {\n const {\n onChange = actionLiveEvent,\n onChangeIncludingDrafts = actionLiveEventIncludingDrafts,\n onStudioPerspective = actionStudioPerspective,\n refreshOnMount,\n refreshOnFocus,\n refreshOnReconnect,\n requestTag = 'next-loader.live',\n onError,\n onGoAway,\n intervalOnGoAway,\n perspective: _perspective,\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n const perspective = _perspective ?? (await resolveCookiePerspective())\n const includeDrafts = typeof browserToken === 'string' && perspective !== 'published'\n\n // Preconnect to the Live Event API origin early, as the Sanity API is almost always on a different origin than the app\n const {origin} = new URL(client.getUrl('', false))\n preconnect(origin)\n\n return (\n <SanityLiveClientComponent\n config={{\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n requestTagPrefix,\n token: includeDrafts ? browserToken : undefined,\n }}\n perspective={await resolveCookiePerspective()}\n onLiveEvent={onChange}\n onLiveEventIncludingDrafts={onChangeIncludingDrafts}\n onPresentationPerspective={onStudioPerspective}\n requestTag={requestTag}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n />\n )\n }\n SanityLive.displayName = 'DefinedSanityLive'\n\n return {\n sanityFetch,\n SanityLive,\n }\n}\n\nasync function resolveCookiePerspective(): Promise<Exclude<ClientPerspective, 'raw'>> {\n return (await draftMode()).isEnabled\n ? (await cookies()).has(perspectiveCookieName)\n ? sanitizePerspective((await cookies()).get(perspectiveCookieName)?.value, 'drafts')\n : 'drafts'\n : 'published'\n}\n"],"mappings":";;;;;;;;;AA4FA,SAAgB,WAAW,QAWzB;CACA,MAAM,EACJ,QAAQ,SACR,aACA,cACA,cACA,OAAO,eAAe,SACpB;AAEJ,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,oDAAoD;AAGtE,KAAI,QAAQ,IAAI,aAAa,gBAAgB,CAAC,eAAe,gBAAgB,MAC3E,SAAQ,KACN,8LACD;AAGH,KAAI,QAAQ,IAAI,aAAa,gBAAgB,CAAC,gBAAgB,iBAAiB,MAC7E,SAAQ,KACN,iXACD;CAGH,MAAM,SAAS,QAAQ,WAAW;EAAC,kBAAkB;EAAO,QAAQ;EAAM,CAAC;CAC3E,MAAM,EAAC,OAAO,kBAAiB,OAAO,QAAQ;CAC9C,MAAM,mBAAmB,OAAO,OAAO,QAAQ,CAAC,MAAM,cAAc;CAEpE,MAAM,cAAsC,eAAeA,cAEzD,EACA,OACA,SAAS,EAAE,EACX,OAAO,QACP,OAAO,CAAC,SAAS,EACjB,aAAa,cACb,KACA,aAAa,OAAO,uBASnB;EACD,MAAM,QAAQ,WAAW,gBAAgB,qBAAqB,MAAM,WAAW,EAAE;EACjF,MAAM,cAAc,gBAAiB,MAAM,0BAA0B;EACrE,MAAM,SAAS,gBAAgB;EAC/B,MAAM,aACJ,cAAc,eAAe,KAAA,IACzB,aAAa,aACb,QAAQ,IAAI,aAAa,eACvB,QACA,KAAA;EAGR,MAAM,EAAC,aAAY,MAAM,OAAO,MAAM,OAAO,MAAM,QAAQ;GACzD,gBAAgB;GACH;GACb,OAAO;GACP,aAAa;GACb,MAAM;IAAC;IAAY,MAAM,CAAC,GAAG,MAAM,yBAAyB;IAAC;GAC7D;GACA,WAAW,SAAS,YAAY,KAAA;GAChC,KAAK,CAAC,YAAY,kBAAkB,CAAC,OAAO,QAAQ,CAAC,KAAK,IAAI;GAC/D,CAAC;EAEF,MAAM,YAAY,CAAC,GAAG,MAAM,GAAI,UAAU,KAAK,UAAQ,UAAUC,QAAM,IAAI,EAAE,CAAE;EAE/E,MAAM,EAAC,QAAQ,oBAAmB,MAAM,OAAO,MAAM,OAAO,MAAM,QAAQ;GACxE,gBAAgB;GACH;GACb;GACA,OAAO,gBAAgB,eAAe,cAAc,cAAc;GAClE,MAAM;IAAC;IAAY,MAAM;IAAU;GACnC;GACA,WAAW,SAAS,YAAY,KAAA;GAChC,KAAK;GACN,CAAC;AACF,SAAO;GAAC,MAAM;GAAQ,WAAW,mBAAmB;GAAM,MAAM;GAAU;;CAG5E,MAAMC,eAA0D,eAAeA,aAAW,OAAO;EAC/F,MAAM,EACJ,WAAW,iBACX,0BAA0B,gCAC1B,sBAAsB,yBACtB,gBACA,gBACA,oBACA,aAAa,oBACb,SACA,UACA,kBACA,aAAa,iBACX;EACJ,MAAM,EAAC,WAAW,SAAS,SAAS,YAAY,oBAAoB,qBAClE,OAAO,QAAQ;EACjB,MAAM,cAAc,gBAAiB,MAAM,0BAA0B;EACrE,MAAM,gBAAgB,OAAO,iBAAiB,YAAY,gBAAgB;EAG1E,MAAM,EAAC,WAAU,IAAI,IAAI,OAAO,OAAO,IAAI,MAAM,CAAC;AAClD,aAAW,OAAO;AAElB,SACE,oBAACC,YAAAA;GACC,QAAQ;IACN;IACA;IACA;IACA;IACA;IACA;IACA,OAAO,gBAAgB,eAAe,KAAA;IACvC;GACD,aAAa,MAAM,0BAA0B;GAC7C,aAAa;GACb,4BAA4B;GAC5B,2BAA2B;GACf;GACI;GACA;GACI;GACX;GACC;GACQ;IAClB;;AAGN,cAAW,cAAc;AAEzB,QAAO;EACL;EACA,YAAA;EACD;;AAGH,eAAe,2BAAuE;AACpF,SAAQ,MAAM,WAAW,EAAE,aACtB,MAAM,SAAS,EAAE,IAAI,sBAAsB,GAC1C,qBAAqB,MAAM,SAAS,EAAE,IAAI,sBAAsB,EAAE,OAAO,SAAS,GAClF,WACF"}
@@ -0,0 +1,15 @@
1
+ import { ClientPerspective } from "@sanity/client";
2
+ /**
3
+ * Used by `<SanityLive onStudioPerspective={actionStudioPerspective} />`
4
+ */
5
+ declare function actionStudioPerspective(perspective: ClientPerspective): Promise<void>;
6
+ /**
7
+ * Used by `<SanityLive onLiveEvent={actionLiveEvent} />`
8
+ */
9
+ declare function actionLiveEvent(_tags: unknown): Promise<void>;
10
+ /**
11
+ * Used by `<SanityLive onLiveEventIncludingDrafts={actionLiveEventIncludingDrafts} />`
12
+ */
13
+ declare function actionLiveEventIncludingDrafts(_tags: unknown): Promise<void>;
14
+ export { actionLiveEvent, actionLiveEventIncludingDrafts, actionStudioPerspective };
15
+ //# sourceMappingURL=index.default.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.default.d.ts","names":[],"sources":["../../../src/live/server-actions/index.default.ts"],"sourcesContent":[],"mappings":";;AAcA;AAkCA;AAyBsB,iBA3DA,uBAAA,CA2DgD,WAAA,EA3DX,iBA2DW,CAAA,EA3DS,OA2DT,CAAA,IAAA,CAAA;;;;iBAzBhD,eAAA,kBAAiC;;;;iBAyBjC,8BAAA,kBAAgD"}
@@ -1,18 +1,15 @@
1
1
  "use server";
2
- import { n as PUBLISHED_SYNC_TAG_PREFIX } from "../../constants.js";
2
+ import { n as PUBLISHED_SYNC_TAG_PREFIX, t as DRAFT_SYNC_TAG_PREFIX } from "../../constants.js";
3
3
  import { t as sanitizePerspective } from "../../sanitizePerspective.js";
4
4
  import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
5
- import { cookies } from "next/headers";
5
+ import { cookies, draftMode } from "next/headers";
6
6
  import { refresh, revalidateTag, updateTag } from "next/cache";
7
- async function revalidateSyncTags(tags) {
8
- revalidateTag("sanity:fetch-sync-tags", "max");
9
- for (const _tag of tags) {
10
- const tag = `sanity:${_tag}`;
11
- revalidateTag(tag, { expire: 0 });
12
- console.log(`<SanityLive /> revalidated tag: ${tag}`);
7
+ async function actionStudioPerspective(perspective) {
8
+ const { isEnabled } = await draftMode();
9
+ if (!isEnabled) {
10
+ console.warn("Draft mode is not enabled, skipping actionStudioPerspective");
11
+ return;
13
12
  }
14
- }
15
- async function setPerspectiveCookie(perspective) {
16
13
  const jar = await cookies();
17
14
  const sanitizedPerspective = sanitizePerspective(perspective, "drafts");
18
15
  if (!sanitizedPerspective || Array.isArray(sanitizedPerspective) && sanitizedPerspective.length === 0) throw new Error(`Invalid perspective`, { cause: perspective });
@@ -24,7 +21,7 @@ async function setPerspectiveCookie(perspective) {
24
21
  });
25
22
  refresh();
26
23
  }
27
- async function expireTags(_tags) {
24
+ async function actionLiveEvent(_tags) {
28
25
  if (!Array.isArray(_tags)) {
29
26
  console.warn("<SanityLive /> `expireTags` called with non-array tags", _tags);
30
27
  return;
@@ -34,9 +31,25 @@ async function expireTags(_tags) {
34
31
  console.warn("<SanityLive /> `expireTags` called with no valid tags", _tags);
35
32
  return;
36
33
  }
34
+ revalidateTag("sanity:fetch-sync-tags", "max");
35
+ for (const tag of tags) {
36
+ revalidateTag(tag, { expire: 0 });
37
+ console.log(`<SanityLive /> revalidated tag: ${tag}`);
38
+ }
39
+ }
40
+ async function actionLiveEventIncludingDrafts(_tags) {
41
+ if (!Array.isArray(_tags)) {
42
+ console.warn("<SanityLive /> `expireTags` called with non-array tags", _tags);
43
+ return;
44
+ }
45
+ const tags = _tags.filter((tag) => typeof tag === "string" && tag.startsWith(DRAFT_SYNC_TAG_PREFIX));
46
+ if (!tags.length) {
47
+ console.warn("<SanityLive /> `expireTags` called with no valid tags", _tags);
48
+ return;
49
+ }
37
50
  for (const tag of tags) updateTag(tag);
38
51
  console.log(`<SanityLive /> updated tags: ${tags.join(", ")}`);
39
52
  }
40
- export { expireTags, revalidateSyncTags, setPerspectiveCookie };
53
+ export { actionLiveEvent, actionLiveEventIncludingDrafts, actionStudioPerspective };
41
54
 
42
- //# sourceMappingURL=index.js.map
55
+ //# sourceMappingURL=index.default.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.default.js","names":[],"sources":["../../../src/live/server-actions/index.default.ts"],"sourcesContent":["'use server'\n\nimport type {ClientPerspective} from '@sanity/client'\n\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {refresh, revalidateTag, updateTag} from 'next/cache'\nimport {cookies, draftMode} from 'next/headers'\n\nimport {DRAFT_SYNC_TAG_PREFIX, PUBLISHED_SYNC_TAG_PREFIX} from '../shared/constants'\nimport {sanitizePerspective} from '../shared/sanitizePerspective'\n\n/**\n * Used by `<SanityLive onStudioPerspective={actionStudioPerspective} />`\n */\nexport async function actionStudioPerspective(perspective: ClientPerspective): Promise<void> {\n const {isEnabled} = await draftMode()\n if (!isEnabled) {\n console.warn('Draft mode is not enabled, skipping actionStudioPerspective')\n return\n }\n\n const jar = await cookies()\n const sanitizedPerspective = sanitizePerspective(perspective, 'drafts')\n if (\n !sanitizedPerspective ||\n (Array.isArray(sanitizedPerspective) && sanitizedPerspective.length === 0)\n ) {\n throw new Error(`Invalid perspective`, {cause: perspective})\n }\n\n // @TODO check if the cookie is already set, before setting it and then calling refresh()\n jar.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 refresh()\n}\n\n/**\n * Used by `<SanityLive onLiveEvent={actionLiveEvent} />`\n */\nexport async function actionLiveEvent(_tags: unknown): Promise<void> {\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\n revalidateTag('sanity:fetch-sync-tags', 'max')\n\n for (const tag of tags) {\n revalidateTag(tag, {expire: 0})\n // oxlint-disable-next-line no-console\n console.log(`<SanityLive /> revalidated tag: ${tag}`)\n }\n}\n\n/**\n * Used by `<SanityLive onLiveEventIncludingDrafts={actionLiveEventIncludingDrafts} />`\n */\nexport async function actionLiveEventIncludingDrafts(_tags: unknown): Promise<void> {\n // @TODO check draft mode before expiring tags\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(DRAFT_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":";;;;;;AAcA,eAAsB,wBAAwB,aAA+C;CAC3F,MAAM,EAAC,cAAa,MAAM,WAAW;AACrC,KAAI,CAAC,WAAW;AACd,UAAQ,KAAK,8DAA8D;AAC3E;;CAGF,MAAM,MAAM,MAAM,SAAS;CAC3B,MAAM,uBAAuB,oBAAoB,aAAa,SAAS;AACvE,KACE,CAAC,wBACA,MAAM,QAAQ,qBAAqB,IAAI,qBAAqB,WAAW,EAExE,OAAM,IAAI,MAAM,uBAAuB,EAAC,OAAO,aAAY,CAAC;AAI9D,KAAI,IACF,uBACA,MAAM,QAAQ,qBAAqB,GAAG,qBAAqB,KAAK,IAAI,GAAG,sBACvE;EACE,UAAU;EACV,MAAM;EACN,QAAQ;EACR,UAAU;EACX,CACF;AAED,UAAS;;AAMX,eAAsB,gBAAgB,OAA+B;AACnE,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;;AAGF,eAAc,0BAA0B,MAAM;AAE9C,MAAK,MAAM,OAAO,MAAM;AACtB,gBAAc,KAAK,EAAC,QAAQ,GAAE,CAAC;AAE/B,UAAQ,IAAI,mCAAmC,MAAM;;;AAOzD,eAAsB,+BAA+B,OAA+B;AAElF,KAAI,CAAC,MAAM,QAAQ,MAAM,EAAE;AACzB,UAAQ,KAAK,0DAA0D,MAAM;AAC7E;;CAEF,MAAM,OAAO,MAAM,QAChB,QAAQ,OAAO,QAAQ,YAAY,IAAI,WAAW,sBAAsB,CAC1E;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"}
@@ -0,0 +1,15 @@
1
+ import { ClientPerspective } from "@sanity/client";
2
+ /**
3
+ * Used by `<SanityLive onStudioPerspective={actionStudioPerspective} />`
4
+ */
5
+ declare function actionStudioPerspective(perspective: ClientPerspective): Promise<void>;
6
+ /**
7
+ * Used by `<SanityLive onLiveEvent={actionLiveEvent} />`
8
+ */
9
+ declare function actionLiveEvent(_tags: unknown): Promise<void>;
10
+ /**
11
+ * Used by `<SanityLive onLiveEventIncludingDrafts={actionLiveEventIncludingDrafts} />`
12
+ */
13
+ declare function actionLiveEventIncludingDrafts(tags: unknown): Promise<void>;
14
+ export { actionLiveEvent, actionLiveEventIncludingDrafts, actionStudioPerspective };
15
+ //# sourceMappingURL=index.next-js.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.next-js.d.ts","names":[],"sources":["../../../src/live/server-actions/index.next-js.ts"],"sourcesContent":[],"mappings":";;AAaA;AA4BA;AAyBsB,iBArDA,uBAAA,CAqDA,WAA+C,EArDV,iBAqDU,CAAA,EArDU,OAqDV,CAAA,IAAA,CAAA;;;;iBAzB/C,eAAA,kBAAiC;;;;iBAyBjC,8BAAA,iBAA+C"}
@@ -0,0 +1,52 @@
1
+ "use server";
2
+ import { n as PUBLISHED_SYNC_TAG_PREFIX, t as DRAFT_SYNC_TAG_PREFIX } from "../../constants.js";
3
+ import { t as sanitizePerspective } from "../../sanitizePerspective.js";
4
+ import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
5
+ import { cookies, draftMode } from "next/headers";
6
+ import { refresh, updateTag } from "next/cache";
7
+ async function actionStudioPerspective(perspective) {
8
+ const jar = await cookies();
9
+ const sanitizedPerspective = sanitizePerspective(perspective, "drafts");
10
+ if (!sanitizedPerspective || Array.isArray(sanitizedPerspective) && sanitizedPerspective.length === 0) throw new Error(`Invalid perspective`, { cause: perspective });
11
+ jar.set(perspectiveCookieName, Array.isArray(sanitizedPerspective) ? sanitizedPerspective.join(",") : sanitizedPerspective, {
12
+ httpOnly: true,
13
+ path: "/",
14
+ secure: true,
15
+ sameSite: "none"
16
+ });
17
+ refresh();
18
+ }
19
+ async function actionLiveEvent(_tags) {
20
+ if (!Array.isArray(_tags)) {
21
+ console.warn("<SanityLive /> `expireTags` called with non-array tags", _tags);
22
+ return;
23
+ }
24
+ const tags = _tags.filter((tag) => typeof tag === "string" && tag.startsWith(PUBLISHED_SYNC_TAG_PREFIX));
25
+ if (!tags.length) {
26
+ console.warn("<SanityLive /> `expireTags` called with no valid tags", _tags);
27
+ return;
28
+ }
29
+ for (const tag of tags) updateTag(tag);
30
+ console.log(`<SanityLive /> updated tags: ${tags.join(", ")}`);
31
+ }
32
+ async function actionLiveEventIncludingDrafts(tags) {
33
+ const { isEnabled } = await draftMode();
34
+ if (isEnabled) refresh();
35
+ else return expireDraftTags(tags);
36
+ }
37
+ async function expireDraftTags(_tags) {
38
+ if (!Array.isArray(_tags)) {
39
+ console.warn("<SanityLive /> `expireTags` called with non-array tags", _tags);
40
+ return;
41
+ }
42
+ const tags = _tags.filter((tag) => typeof tag === "string" && tag.startsWith(DRAFT_SYNC_TAG_PREFIX));
43
+ if (!tags.length) {
44
+ console.warn("<SanityLive /> `expireTags` called with no valid tags", _tags);
45
+ return;
46
+ }
47
+ for (const tag of tags) updateTag(tag);
48
+ console.log(`<SanityLive /> updated tags: ${tags.join(", ")}`);
49
+ }
50
+ export { actionLiveEvent, actionLiveEventIncludingDrafts, actionStudioPerspective };
51
+
52
+ //# sourceMappingURL=index.next-js.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.next-js.js","names":[],"sources":["../../../src/live/server-actions/index.next-js.ts"],"sourcesContent":["'use server'\n\nimport type {ClientPerspective} from '@sanity/client'\n\nimport {DRAFT_SYNC_TAG_PREFIX, PUBLISHED_SYNC_TAG_PREFIX} from '#live/constants'\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {refresh, updateTag} from 'next/cache'\nimport {cookies, draftMode} from 'next/headers'\n\n/**\n * Used by `<SanityLive onStudioPerspective={actionStudioPerspective} />`\n */\nexport async function actionStudioPerspective(perspective: ClientPerspective): Promise<void> {\n const jar = await cookies()\n const sanitizedPerspective = sanitizePerspective(perspective, 'drafts')\n if (\n !sanitizedPerspective ||\n (Array.isArray(sanitizedPerspective) && sanitizedPerspective.length === 0)\n ) {\n throw new Error(`Invalid perspective`, {cause: perspective})\n }\n\n // @TODO check if the cookie is already set, before setting it and then calling refresh()\n jar.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 refresh()\n}\n\n/**\n * Used by `<SanityLive onLiveEvent={actionLiveEvent} />`\n */\nexport async function actionLiveEvent(_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\n/**\n * Used by `<SanityLive onLiveEventIncludingDrafts={actionLiveEventIncludingDrafts} />`\n */\nexport async function actionLiveEventIncludingDrafts(tags: unknown): Promise<void> {\n const {isEnabled} = await draftMode()\n if (isEnabled) {\n // With cache components just refresh by default when in draft mode and assume bypass\n refresh()\n } else {\n return expireDraftTags(tags)\n }\n}\n\nasync function expireDraftTags(_tags: unknown): Promise<void> {\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(DRAFT_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":";;;;;;AAaA,eAAsB,wBAAwB,aAA+C;CAC3F,MAAM,MAAM,MAAM,SAAS;CAC3B,MAAM,uBAAuB,oBAAoB,aAAa,SAAS;AACvE,KACE,CAAC,wBACA,MAAM,QAAQ,qBAAqB,IAAI,qBAAqB,WAAW,EAExE,OAAM,IAAI,MAAM,uBAAuB,EAAC,OAAO,aAAY,CAAC;AAI9D,KAAI,IACF,uBACA,MAAM,QAAQ,qBAAqB,GAAG,qBAAqB,KAAK,IAAI,GAAG,sBACvE;EACE,UAAU;EACV,MAAM;EACN,QAAQ;EACR,UAAU;EACX,CACF;AAED,UAAS;;AAMX,eAAsB,gBAAgB,OAA+B;AAInE,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;;AAMhE,eAAsB,+BAA+B,MAA8B;CACjF,MAAM,EAAC,cAAa,MAAM,WAAW;AACrC,KAAI,UAEF,UAAS;KAET,QAAO,gBAAgB,KAAK;;AAIhC,eAAe,gBAAgB,OAA+B;AAC5D,KAAI,CAAC,MAAM,QAAQ,MAAM,EAAE;AACzB,UAAQ,KAAK,0DAA0D,MAAM;AAC7E;;CAEF,MAAM,OAAO,MAAM,QAChB,QAAQ,OAAO,QAAQ,YAAY,IAAI,WAAW,sBAAsB,CAC1E;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"}
@@ -1 +1 @@
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
+ {"version":3,"file":"resolvePerspectiveFromCookies.js","names":["resolvePerspectiveFromCookies"],"sources":["../src/live/shared/resolvePerspectiveFromCookies.ts"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\nimport type {cookies} from 'next/headers'\n\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\n\nimport {sanitizePerspective} from './sanitizePerspective'\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":";;AAyBA,MAAa,gCAAgC,eAAeA,gCAA8B,EACxF,SAAS,OAGoC;AAC7C,QAAO,IAAI,IAAI,sBAAsB,GACjC,oBAAoB,IAAI,IAAI,sBAAsB,EAAE,OAAO,SAAS,GACpE"}
@@ -1 +1 @@
1
- {"version":3,"file":"sanitizePerspective.js","names":[],"sources":["../src/shared/live/sanitizePerspective.ts"],"sourcesContent":["import {validateApiPerspective, type ClientPerspective} from '@sanity/client'\n\n// @TODO split into sanitizePerspective and parsePerspective, expose parsePerspective on the /live export\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 : Array.isArray(_perspective) ? _perspective.filter(Boolean) : _perspective\n try {\n validateApiPerspective(perspective)\n return perspective === 'raw' ? fallback : perspective\n } catch (err) {\n console.warn(`Invalid perspective:`, _perspective, perspective, err)\n return fallback\n }\n}\n"],"mappings":";AAGA,SAAgB,oBACd,cACA,UACmC;CACnC,MAAM,cACJ,OAAO,iBAAiB,YAAY,aAAa,SAAS,IAAI,GAC1D,aAAa,MAAM,IAAI,GACvB,MAAM,QAAQ,aAAa,GAAG,aAAa,OAAO,QAAQ,GAAG;AACnE,KAAI;AACF,yBAAuB,YAAY;AACnC,SAAO,gBAAgB,QAAQ,WAAW;UACnC,KAAK;AACZ,UAAQ,KAAK,wBAAwB,cAAc,aAAa,IAAI;AACpE,SAAO"}
1
+ {"version":3,"file":"sanitizePerspective.js","names":[],"sources":["../src/live/shared/sanitizePerspective.ts"],"sourcesContent":["import {validateApiPerspective, type ClientPerspective} from '@sanity/client'\n\n// @TODO split into sanitizePerspective and parsePerspective, expose parsePerspective on the /live export\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 : Array.isArray(_perspective)\n ? _perspective.filter(Boolean)\n : _perspective\n try {\n validateApiPerspective(perspective)\n return perspective === 'raw' ? fallback : perspective\n } catch (err) {\n console.warn(`Invalid perspective:`, _perspective, perspective, err)\n return fallback\n }\n}\n"],"mappings":";AAGA,SAAgB,oBACd,cACA,UACmC;CACnC,MAAM,cACJ,OAAO,iBAAiB,YAAY,aAAa,SAAS,IAAI,GAC1D,aAAa,MAAM,IAAI,GACvB,MAAM,QAAQ,aAAa,GACzB,aAAa,OAAO,QAAQ,GAC5B;AACR,KAAI;AACF,yBAAuB,YAAY;AACnC,SAAO,gBAAgB,QAAQ,WAAW;UACnC,KAAK;AACZ,UAAQ,KAAK,wBAAwB,cAAc,aAAa,IAAI;AACpE,SAAO"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "next-sanity",
3
- "version": "13.0.0-cache-components.13",
3
+ "version": "13.0.0-cache-components.15",
4
4
  "description": "Sanity.io toolkit for Next.js",
5
5
  "keywords": [
6
6
  "live",
@@ -29,23 +29,24 @@
29
29
  "sideEffects": false,
30
30
  "types": "./dist/index.d.ts",
31
31
  "imports": {
32
- "#client-components/*": "./src/shared/client-components/*.tsx",
33
- "#live/*": "./src/shared/live/*.ts"
32
+ "#live/*": "./src/live/shared/*.ts"
34
33
  },
35
34
  "exports": {
36
35
  ".": "./dist/index.js",
37
36
  "./cache-life": "./dist/cache-life.js",
38
37
  "./draft-mode": "./dist/draft-mode/index.js",
39
- "./experimental/client-components/live": "./dist/experimental/client-components/live.js",
40
38
  "./hooks": "./dist/hooks/index.js",
41
39
  "./image": "./dist/image/index.js",
42
40
  "./live": {
43
- "next-js": "./dist/live.next-js.js",
44
- "react-server": "./dist/live.react-server.js",
45
- "default": "./dist/live.js"
41
+ "next-js": "./dist/live/conditions/next-js/index.js",
42
+ "react-server": "./dist/live/conditions/react-server/index.js",
43
+ "default": "./dist/live/conditions/default/index.js"
44
+ },
45
+ "./live/client-components": "./dist/live/client-components/index.js",
46
+ "./live/server-actions": {
47
+ "next-js": "./dist/live/server-actions/index.next-js.js",
48
+ "default": "./dist/live/server-actions/index.default.js"
46
49
  },
47
- "./live/client-components/live": "./dist/live/client-components/live/index.js",
48
- "./live/server-actions": "./dist/live/server-actions/index.js",
49
50
  "./studio": "./dist/studio/index.js",
50
51
  "./studio/client-component": "./dist/studio/client-component/index.js",
51
52
  "./visual-editing": "./dist/visual-editing/index.js",
@@ -62,32 +63,32 @@
62
63
  "@sanity/preview-url-secret": "^4.0.2",
63
64
  "@sanity/visual-editing": "^5.0.4",
64
65
  "dequal": "^2.0.3",
65
- "groq": "^5.1.0",
66
+ "groq": "^5.2.0",
66
67
  "history": "^5.3.0"
67
68
  },
68
69
  "devDependencies": {
69
70
  "@sanity/browserslist-config": "^1.0.5",
70
71
  "@sanity/tsconfig": "^2.1.0",
71
72
  "@sanity/webhook": "4.0.4",
72
- "@types/node": "^24.10.4",
73
- "@types/react": "^19.2.7",
73
+ "@types/node": "^24.10.7",
74
+ "@types/react": "^19.2.8",
74
75
  "@types/react-dom": "^19.2.3",
75
- "@vitest/coverage-v8": "^4.0.16",
76
- "next": "16.1.1-canary.14",
76
+ "@vitest/coverage-v8": "^4.0.17",
77
+ "next": "16.1.1-canary.22",
77
78
  "publint": "^0.3.16",
78
79
  "react": "^19.2.3",
79
80
  "react-dom": "^19.2.3",
80
81
  "styled-components": "^6.2.0",
81
- "tsdown": "0.19.0-beta.1",
82
+ "tsdown": "0.19.0",
82
83
  "typescript": "5.9.3",
83
- "vitest": "^4.0.16"
84
+ "vitest": "^4.0.17"
84
85
  },
85
86
  "peerDependencies": {
86
87
  "@sanity/client": "^7.14.0",
87
88
  "next": "^16.0.0-0",
88
89
  "react": "^19.2.3",
89
90
  "react-dom": "^19.2.3",
90
- "sanity": "^5.1.0",
91
+ "sanity": "^5.2.0",
91
92
  "styled-components": "^6.1"
92
93
  },
93
94
  "browserslist": "extends @sanity/browserslist-config",
@@ -1 +0,0 @@
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;;ACkCA;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"}