@prismicio/next 0.1.2 → 0.1.3

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.
@@ -1,9 +1,10 @@
1
- import React, { useEffect } from "react";
1
+ import * as React from "react";
2
+ import * as prismic from "@prismicio/client";
2
3
  import { PrismicToolbar } from "@prismicio/react";
3
4
  import { useRouter } from "next/router";
4
5
 
5
6
  import { getCookie } from "./lib/getCookie";
6
- import { extractPreviewRefRepositoryName } from "./lib/extractPreviewRefRepositoryName";
7
+ import { getPreviewCookieRepositoryName } from "./lib/getPreviewCookieRepositoryName";
7
8
 
8
9
  /**
9
10
  * Props for `<PrismicPreview>`.
@@ -18,33 +19,28 @@ export type PrismicPreviewProps = {
18
19
  /**
19
20
  * The URL of your app's Prismic preview endpoint (default: `/api/preview`).
20
21
  * This URL will be fetched on preview update events.
22
+ *
23
+ * **Note**: If your `next.config.js` file contains a `basePath`, it is
24
+ * automatically included.
21
25
  */
22
26
  updatePreviewURL?: string;
23
27
 
24
28
  /**
25
29
  * The URL of your app's exit preview endpoint (default: `/api/exit-preview`).
26
30
  * This URL will be fetched on preview exit events.
31
+ *
32
+ * **Note**: If your `next.config.js` file contains a `basePath`, it is
33
+ * automatically included.
27
34
  */
28
35
  exitPreviewURL?: string;
29
36
 
37
+ /**
38
+ * Children to render adjacent to the Prismic Toolbar. The Prismic Toolbar
39
+ * will be rendered last.
40
+ */
30
41
  children?: React.ReactNode;
31
42
  };
32
43
 
33
- /**
34
- * Determines if an Event object came from the Prismic Toolbar.
35
- *
36
- * @param event - Event to check.
37
- *
38
- * @returns `true` if `event` came from the Prismic Toolbar, `false` otherwise.
39
- */
40
- const isPrismicUpdateToolbarEvent = (
41
- event: Event,
42
- ): event is CustomEvent<{ ref: string }> => {
43
- return (
44
- "detail" in event && typeof (event as CustomEvent).detail.ref === "string"
45
- );
46
- };
47
-
48
44
  /**
49
45
  * React component that sets up Prismic Previews using the Prismic Toolbar. When
50
46
  * the Prismic Toolbar send events to the browser, such as on preview updates
@@ -62,31 +58,31 @@ export function PrismicPreview({
62
58
  }: PrismicPreviewProps): JSX.Element {
63
59
  const router = useRouter();
64
60
 
65
- useEffect(() => {
66
- const previewRefRepositoryName = extractPreviewRefRepositoryName(
67
- getCookie("io.prismic.preview", globalThis.document.cookie) as string,
68
- );
69
-
70
- const startPreviewIfLoadedFromSharedLink = async () => {
71
- if (previewRefRepositoryName === repositoryName && !router.isPreview) {
72
- await fetch(updatePreviewURL);
73
- window.location.reload();
61
+ const resolvedUpdatePreviewURL = router.basePath + updatePreviewURL;
62
+ const resolvedExitPreviewURL = router.basePath + exitPreviewURL;
63
+
64
+ React.useEffect(() => {
65
+ /**
66
+ * Starts Preview Mode and refreshes the page's props.
67
+ */
68
+ const startPreviewMode = async () => {
69
+ // Start Next.js Preview Mode via the given preview API endpoint.
70
+ const res = await globalThis.fetch(resolvedUpdatePreviewURL);
71
+
72
+ if (res.ok) {
73
+ globalThis.location.reload();
74
+ } else {
75
+ console.error(
76
+ `[<PrismicPreview>] Failed to start or update Preview Mode using the "${resolvedUpdatePreviewURL}" API endpoint. Does it exist?`,
77
+ );
74
78
  }
75
79
  };
76
80
 
77
- startPreviewIfLoadedFromSharedLink();
78
-
79
81
  const handlePrismicPreviewUpdate = async (event: Event) => {
80
- if (isPrismicUpdateToolbarEvent(event)) {
81
- // Prevent the toolbar from reloading the page.
82
- event.preventDefault();
83
-
84
- // Start Next.js Preview Mode via the given preview API endpoint.
85
- await fetch(updatePreviewURL);
82
+ // Prevent the toolbar from reloading the page.
83
+ event.preventDefault();
86
84
 
87
- // Reload the page with an active Preview Mode.
88
- window.location.reload();
89
- }
85
+ await startPreviewMode();
90
86
  };
91
87
 
92
88
  const handlePrismicPreviewEnd = async (event: Event) => {
@@ -94,40 +90,81 @@ export function PrismicPreview({
94
90
  event.preventDefault();
95
91
 
96
92
  // Exit Next.js Preview Mode via the given preview API endpoint.
97
- await fetch(exitPreviewURL);
93
+ const res = await globalThis.fetch(resolvedExitPreviewURL);
98
94
 
99
- // Reload the page with an active Preview Mode.
100
- window.location.reload();
95
+ if (res.ok) {
96
+ globalThis.location.reload();
97
+ } else {
98
+ console.error(
99
+ `[<PrismicPreview>] Failed to exit Preview Mode using the "${resolvedExitPreviewURL}" API endpoint. Does it exist?`,
100
+ );
101
+ }
101
102
  };
102
103
 
103
- // Register Prismic Toolbar event handlers.
104
- if (window) {
104
+ if (router.isPreview) {
105
+ // Register Prismic Toolbar event handlers.
105
106
  window.addEventListener(
106
107
  "prismicPreviewUpdate",
107
108
  handlePrismicPreviewUpdate,
108
109
  );
109
110
  window.addEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
111
+ } else {
112
+ const prismicPreviewCookie = getCookie(
113
+ prismic.cookie.preview,
114
+ globalThis.document.cookie,
115
+ );
116
+
117
+ if (prismicPreviewCookie) {
118
+ // If a Prismic preview cookie is present, but Next.js Preview
119
+ // Mode is not active, we must activate Preview Mode manually.
120
+ //
121
+ // This will happen when a visitor accesses the page using a
122
+ // Prismic preview share link.
123
+
124
+ /**
125
+ * Determines if the current location is a descendant of the app's base path.
126
+ *
127
+ * This is used to prevent infinite refrehes; when
128
+ * `isDescendantOfBasePath` is `false`, `router.isPreview` is also `false`.
129
+ *
130
+ * If the app does not have a base path, this should always be `true`.
131
+ */
132
+ const locationIsDescendantOfBasePath = window.location.href.startsWith(
133
+ window.location.origin + router.basePath,
134
+ );
135
+
136
+ const prismicPreviewCookieRepositoryName =
137
+ getPreviewCookieRepositoryName(prismicPreviewCookie);
138
+
139
+ if (
140
+ locationIsDescendantOfBasePath &&
141
+ prismicPreviewCookieRepositoryName === repositoryName
142
+ ) {
143
+ startPreviewMode();
144
+ }
145
+ }
110
146
  }
111
147
 
112
148
  // On cleanup, unregister Prismic Toolbar event handlers.
113
149
  return () => {
114
- if (window) {
115
- window.removeEventListener(
116
- "prismicPreviewUpdate",
117
- handlePrismicPreviewUpdate,
118
- );
119
- window.removeEventListener(
120
- "prismicPreviewEnd",
121
- handlePrismicPreviewEnd,
122
- );
123
- }
150
+ window.removeEventListener(
151
+ "prismicPreviewUpdate",
152
+ handlePrismicPreviewUpdate,
153
+ );
154
+ window.removeEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
124
155
  };
125
- }, []);
156
+ }, [
157
+ repositoryName,
158
+ resolvedExitPreviewURL,
159
+ resolvedUpdatePreviewURL,
160
+ router.isPreview,
161
+ router.basePath,
162
+ ]);
126
163
 
127
164
  return (
128
165
  <>
129
- <PrismicToolbar repositoryName={repositoryName} />
130
166
  {children}
167
+ <PrismicToolbar repositoryName={repositoryName} />
131
168
  </>
132
169
  );
133
170
  }
@@ -60,19 +60,17 @@ export type EnableAutoPreviewsConfig<
60
60
  export const enableAutoPreviews = <TPreviewData extends PreviewData>(
61
61
  config: EnableAutoPreviewsConfig<TPreviewData>,
62
62
  ): void => {
63
- /**
64
- * If preview data is being passed from Next Context then use queryContentFromRef
65
- */
66
63
  if ("previewData" in config && config.previewData) {
64
+ // If preview data is being passed from Next Context then use queryContentFromRef
65
+
67
66
  const { previewData } = config;
68
67
 
69
68
  if (isPrismicNextPreviewData(previewData) && previewData.ref) {
70
69
  config.client.queryContentFromRef(previewData.ref);
71
70
  }
72
- /**
73
- * If the req object is passed then use enableAutoPreviewsFromReq
74
- */
75
71
  } else if ("req" in config && config.req) {
72
+ // If the req object is passed then use enableAutoPreviewsFromReq
73
+
76
74
  config.client.enableAutoPreviewsFromReq(config.req);
77
75
  }
78
76
  };
@@ -1,4 +1,4 @@
1
- import { NextApiResponse, NextApiRequest } from "next";
1
+ import type { NextApiResponse, NextApiRequest } from "next";
2
2
 
3
3
  /**
4
4
  * Configuration for `exitPreview`.
@@ -10,10 +10,18 @@ export type ExitPreviewConfig = {
10
10
  *
11
11
  * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
12
12
  */
13
+ // `req` is no longer used in `exitPreview()`. It previously would
14
+ // redirect the user to the referring URL, but it no longer has that
15
+ // behavior.
16
+ //
17
+ // `req` is retained as a parameter to make setting up an exit preview
18
+ // API route easier (this eliminates the awkward need to handle an
19
+ // unused `req` param).
20
+ //
21
+ // It is also retained in case it is needed in the future, such as
22
+ // reading headers or metadata about the request.
13
23
  req: {
14
- headers: {
15
- referer?: NextApiRequest["headers"]["referer"];
16
- };
24
+ headers: NextApiRequest["headers"];
17
25
  };
18
26
 
19
27
  /**
@@ -24,31 +32,21 @@ export type ExitPreviewConfig = {
24
32
  */
25
33
  res: {
26
34
  clearPreviewData: NextApiResponse["clearPreviewData"];
27
- redirect: NextApiResponse["redirect"];
35
+ json: NextApiResponse["json"];
28
36
  };
37
+
38
+ /**
39
+ * @deprecated - This property is no longer used. It can be deleted safely.
40
+ */
41
+ exitPreviewURL?: string;
29
42
  };
30
43
 
31
44
  /**
32
45
  * Exits Next.js's Preview Mode from within a Next.js API route.
33
- *
34
- * If the user was sent to the endpoint from a page, the user will be redirected
35
- * back to that page after exiting Preview Mode.
36
46
  */
37
47
  export function exitPreview(config: ExitPreviewConfig): void {
38
- const { req } = config;
39
- // Exit the current user from "Preview Mode". This function accepts no args.
48
+ // Exit the current user from Preview Mode.
40
49
  config.res.clearPreviewData();
41
50
 
42
- if (req.headers.referer) {
43
- const url = new URL(req.headers.referer);
44
-
45
- if (url.pathname !== "/api/exit-preview") {
46
- // Redirect the user to the referrer page.
47
- config.res.redirect(req.headers.referer);
48
-
49
- return;
50
- }
51
- }
52
-
53
- config.res.redirect("/");
51
+ config.res.json({ success: true });
54
52
  }
package/src/index.ts CHANGED
@@ -1,10 +1,19 @@
1
- export type { SetPreviewDataConfig } from "./setPreviewData";
2
- export type { EnableAutoPreviewsConfig } from "./enableAutoPreviews";
3
- export type { ExitPreviewConfig as ExitPreviewParams } from "./exitPreview";
4
- export type { PrismicPreviewProps } from "./PrismicPreview";
5
1
  export { setPreviewData } from "./setPreviewData";
2
+ export type { SetPreviewDataConfig } from "./setPreviewData";
3
+
6
4
  export { exitPreview } from "./exitPreview";
5
+ export type { ExitPreviewConfig } from "./exitPreview";
6
+
7
7
  export { PrismicPreview } from "./PrismicPreview";
8
+ export type { PrismicPreviewProps } from "./PrismicPreview";
9
+
8
10
  export { enableAutoPreviews } from "./enableAutoPreviews";
11
+ export type { EnableAutoPreviewsConfig } from "./enableAutoPreviews";
12
+
9
13
  export { redirectToPreviewURL } from "./redirectToPreviewURL";
10
- export type { CreateClientConfig, PreviewConfig } from "./types";
14
+ export type { RedirectToPreviewURLConfig } from "./redirectToPreviewURL";
15
+
16
+ export { PrismicNextImage } from "./PrismicNextImage";
17
+ export type { PrismicNextImageProps } from "./PrismicNextImage";
18
+
19
+ export type { CreateClientConfig } from "./types";
@@ -0,0 +1,7 @@
1
+ /**
2
+ * `true` if in the production environment, `false` otherwise.
3
+ *
4
+ * This boolean can be used to perform actions only in development environments,
5
+ * such as logging.
6
+ */
7
+ export const __PRODUCTION__ = process.env.NODE_ENV === "production";
@@ -0,0 +1,20 @@
1
+ import { version } from "../../package.json";
2
+
3
+ /**
4
+ * Returns a `prismic.dev/msg` URL for a given message slug.
5
+ *
6
+ * @example
7
+ *
8
+ * ```ts
9
+ * devMsg("missing-param");
10
+ * // => "https://prismic.dev/msg/next/v1.2.3/missing-param.md"
11
+ * ```
12
+ *
13
+ * @param slug - Slug for the message. This corresponds to a Markdown file in
14
+ * the Git repository's `/messages` directory.
15
+ *
16
+ * @returns The `prismic.dev/msg` URL for the given slug.
17
+ */
18
+ export const devMsg = (slug: string) => {
19
+ return `https://prismic.dev/msg/next/v${version}/${slug}`;
20
+ };
@@ -1,58 +1,29 @@
1
- /**
2
- * The following code is a modifed version of `es-cookie` taken from
3
- * https://github.com/theodorejb/es-cookie
4
- *
5
- * Copyright 2017 Theodore Brown
6
- *
7
- * Permission is hereby granted, free of charge, to any person obtaining a copy
8
- * of this software and associated documentation files (the "Software"), to deal
9
- * in the Software without restriction, including without limitation the rights
10
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
- * copies of the Software, and to permit persons to whom the Software is
12
- * furnished to do so, subject to the following conditions:
13
- *
14
- * The above copyright notice and this permission notice shall be included in
15
- * all copies or substantial portions of the Software.
16
- *
17
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
- * SOFTWARE.*
24
- */
25
-
26
1
  const readValue = (value: string): string => {
27
2
  return value.replace(/%3B/g, ";");
28
3
  };
29
4
 
30
- export const parse = (cookieString: string): { [name: string]: string } => {
31
- const result: { [name: string]: string } = {};
32
- const cookies = cookieString.split("; ");
33
-
34
- for (const cookie of cookies) {
35
- const parts = cookie.split("=");
36
- const value = parts.slice(1).join("=");
37
- const name = readValue(parts[0]).replace(/%3D/g, "=");
38
- result[name] = readValue(value);
39
- }
40
-
41
- return result;
42
- };
43
-
44
- const getAll = (cookieStore: string): { [name: string]: string } =>
45
- parse(cookieStore);
46
-
47
5
  /**
48
6
  * Returns the value of a cookie from a given cookie store.
49
7
  *
50
- * @param name - Of the cookie.
51
- * @param cookieStore - The stringified cookie store from which to read the cookie.
8
+ * @param name - Name of the cookie.
9
+ * @param cookieJar - The stringified cookie store from which to read the cookie.
52
10
  *
53
11
  * @returns The value of the cookie, if it exists.
54
12
  */
55
13
  export const getCookie = (
56
14
  name: string,
57
- cookieStore: string,
58
- ): string | undefined => getAll(cookieStore)[name];
15
+ cookieJar: string,
16
+ ): string | undefined => {
17
+ const cookies = cookieJar.split("; ");
18
+
19
+ for (const cookie of cookies) {
20
+ const parts = cookie.split("=");
21
+ const thisName = readValue(parts[0]).replace(/%3D/g, "=");
22
+
23
+ if (thisName === name) {
24
+ const value = parts.slice(1).join("=");
25
+
26
+ return readValue(value);
27
+ }
28
+ }
29
+ };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Extracts preview reference repo name from stringified Prismic preview cookie
3
+ *
4
+ * @param previewCookie - The Prismic preview cookie.
5
+ *
6
+ * @returns The repository name for the Prismic preview cookie. If the cookie
7
+ * represents an inactive preview session, `undefined` will be returned.
8
+ */
9
+ export const getPreviewCookieRepositoryName = (
10
+ previewCookie: string,
11
+ ): string | undefined => {
12
+ return (decodeURIComponent(previewCookie).match(/"(.+).prismic.io"/) ||
13
+ [])[1];
14
+ };
@@ -1,7 +1,6 @@
1
- import { NextApiRequest } from "next";
2
- import { LinkResolverFunction } from "@prismicio/helpers";
3
-
4
- import { PreviewConfig } from "./";
1
+ import type { Client } from "@prismicio/client";
2
+ import type { NextApiRequest, NextApiResponse } from "next";
3
+ import type { LinkResolverFunction } from "@prismicio/helpers";
5
4
 
6
5
  type PrismicNextQuery = {
7
6
  documentId: string;
@@ -18,8 +17,70 @@ type PrismicNextQuery = {
18
17
  */
19
18
  const isPrismicNextQuery = (
20
19
  query: NextApiRequest["query"],
21
- ): query is PrismicNextQuery =>
22
- typeof query.documentId === "string" && typeof query.token === "string";
20
+ ): query is PrismicNextQuery => {
21
+ return (
22
+ typeof query.documentId === "string" && typeof query.token === "string"
23
+ );
24
+ };
25
+
26
+ /**
27
+ * Preview config for enabling previews with redirectToPreviewURL
28
+ */
29
+ export type RedirectToPreviewURLConfig<
30
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
31
+ TLinkResolverFunction extends LinkResolverFunction<any> = LinkResolverFunction,
32
+ > = {
33
+ /**
34
+ * The `req` object from a Next.js API route. This is given as a parameter to
35
+ * the API route.
36
+ *
37
+ * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
38
+ */
39
+ req: {
40
+ query: NextApiRequest["query"];
41
+ };
42
+
43
+ /**
44
+ * The `res` object from a Next.js API route. This is given as a parameter to
45
+ * the API route.
46
+ *
47
+ * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
48
+ */
49
+ res: {
50
+ redirect: NextApiResponse["redirect"];
51
+ };
52
+
53
+ /**
54
+ * The Prismic client configured for the preview session's repository.
55
+ */
56
+ client: Client;
57
+
58
+ /**
59
+ * A Link Resolver used to resolve the previewed document's URL.
60
+ *
61
+ * @see To learn more about Link Resolver: {@link https://prismic.io/docs/core-concepts/link-resolver-route-resolver}
62
+ */
63
+ linkResolver?: TLinkResolverFunction;
64
+
65
+ /**
66
+ * The default redirect URL if a URL cannot be determined for the previewed document.
67
+ *
68
+ * **Note**: If you `next.config.js` file contains a `basePath`, the
69
+ * `defaultURL` option must _not_ include it. Instead, provide the `basePath`
70
+ * property using the `basePath` option.
71
+ */
72
+ defaultURL?: string;
73
+
74
+ /**
75
+ * The `basePath` for the Next.js app as it is defined in `next.config.js`.
76
+ * This option can be omitted if the app does not have a `basePath`.
77
+ *
78
+ * @remarks
79
+ * The API route is unable to detect the app's `basePath` automatically. It
80
+ * must be provided to `redirectToPreviewURL()` manually.
81
+ */
82
+ basePath?: string;
83
+ };
23
84
 
24
85
  /**
25
86
  * Redirects a user to the URL of a previewed Prismic document from within a
@@ -28,26 +89,22 @@ const isPrismicNextQuery = (
28
89
  export async function redirectToPreviewURL<
29
90
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
91
  TLinkResolverFunction extends LinkResolverFunction<any>,
31
- >({
32
- req,
33
- res,
34
- client,
35
- linkResolver,
36
- defaultURL = "/",
37
- }: PreviewConfig<TLinkResolverFunction>): Promise<void> {
38
- if (isPrismicNextQuery(req.query)) {
39
- const { documentId, token } = req.query;
40
- const previewUrl = await client.resolvePreviewURL({
41
- linkResolver,
92
+ >(config: RedirectToPreviewURLConfig<TLinkResolverFunction>): Promise<void> {
93
+ const defaultURL = config.defaultURL || "/";
94
+ const basePath = config.basePath || "";
95
+
96
+ if (isPrismicNextQuery(config.req.query)) {
97
+ const previewUrl = await config.client.resolvePreviewURL({
98
+ linkResolver: config.linkResolver,
42
99
  defaultURL,
43
- documentID: documentId,
44
- previewToken: token,
100
+ documentID: config.req.query.documentId,
101
+ previewToken: config.req.query.token,
45
102
  });
46
103
 
47
- res.redirect(previewUrl);
104
+ config.res.redirect(basePath + previewUrl);
48
105
 
49
106
  return;
50
107
  }
51
108
 
52
- res.redirect(defaultURL);
109
+ config.res.redirect(basePath + defaultURL);
53
110
  }
package/src/types.ts CHANGED
@@ -1,6 +1,4 @@
1
- import { PreviewData, NextApiRequest, NextApiResponse } from "next";
2
- import { LinkResolverFunction } from "@prismicio/helpers";
3
- import { Client } from "@prismicio/client";
1
+ import { PreviewData, NextApiRequest } from "next";
4
2
 
5
3
  /**
6
4
  * Configuration for creating a Prismic client with automatic preview support in
@@ -22,48 +20,3 @@ export type CreateClientConfig = {
22
20
  */
23
21
  req?: NextApiRequest;
24
22
  };
25
-
26
- /**
27
- * Preview config for enabling previews with redirectToPreviewURL
28
- */
29
- export type PreviewConfig<
30
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
31
- TLinkResolverFunction extends LinkResolverFunction<any> = LinkResolverFunction,
32
- > = {
33
- /**
34
- * The `req` object from a Next.js API route. This is given as a parameter to
35
- * the API route.
36
- *
37
- * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
38
- */
39
- req: {
40
- query: NextApiRequest["query"];
41
- };
42
-
43
- /**
44
- * The `res` object from a Next.js API route. This is given as a parameter to
45
- * the API route.
46
- *
47
- * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
48
- */
49
- res: {
50
- redirect: NextApiResponse["redirect"];
51
- };
52
-
53
- /**
54
- * The Prismic client configured for the preview session's repository.
55
- */
56
- client: Client;
57
-
58
- /**
59
- * A Link Resolver used to resolve the previewed document's URL.
60
- *
61
- * @see To learn more about Link Resolver: {@link https://prismic.io/docs/core-concepts/link-resolver-route-resolver}
62
- */
63
- linkResolver?: TLinkResolverFunction;
64
-
65
- /**
66
- * The default redirect URL if a URL cannot be determined for the previewed document.
67
- */
68
- defaultURL?: string;
69
- };
@@ -1,60 +0,0 @@
1
- /**
2
- * Returns the repository name from an object-style Prismic ref.
3
- *
4
- * @param host - Host string
5
- */
6
- const extractFirstSubdomain = (host: string): string => host.split(".")[0];
7
-
8
- /**
9
- * Parses ref object from cookie and returns proper preview link
10
- *
11
- * @param previewRef - Prismic Preview reference
12
- */
13
- const extractRepositoryNameFromObjectRef = (
14
- previewRef: string,
15
- ): string | undefined => {
16
- try {
17
- const parsed = JSON.parse(decodeURIComponent(previewRef));
18
- const keys = Object.keys(parsed);
19
- const domainKey = keys.find((key) => /\.prismic\.io$/.test(key));
20
-
21
- if (domainKey) {
22
- return extractFirstSubdomain(domainKey);
23
- } else {
24
- return undefined;
25
- }
26
- } catch {
27
- return undefined;
28
- }
29
- };
30
-
31
- /**
32
- * Returns the repository name from a URL-style Prismic ref.
33
- *
34
- * @param previewRef - Preview ref from getCookie()
35
- */
36
- const extractRepositoryNameFromURLRef = (
37
- previewRef: string,
38
- ): string | undefined => {
39
- try {
40
- const url = new URL(previewRef);
41
-
42
- return extractFirstSubdomain(url.host);
43
- } catch {
44
- return undefined;
45
- }
46
- };
47
-
48
- /**
49
- * Extracts preview reference repo name from stringified Prismic preview cookie
50
- *
51
- * @param previewRef - Preview Reference
52
- */
53
- export const extractPreviewRefRepositoryName = (
54
- previewRef: string,
55
- ): string | undefined => {
56
- return (
57
- extractRepositoryNameFromObjectRef(previewRef) ||
58
- extractRepositoryNameFromURLRef(previewRef)
59
- );
60
- };