@prismicio/next 0.2.0-alpha.0 → 1.0.0-alpha.0

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 (76) hide show
  1. package/README.md +3 -1
  2. package/dist/PrismicNextImage.cjs +100 -0
  3. package/dist/PrismicNextImage.cjs.map +1 -0
  4. package/dist/PrismicNextImage.d.ts +47 -0
  5. package/dist/PrismicNextImage.js +79 -0
  6. package/dist/PrismicNextImage.js.map +1 -0
  7. package/dist/PrismicPreview.cjs +87 -0
  8. package/dist/PrismicPreview.cjs.map +1 -0
  9. package/dist/PrismicPreview.d.ts +42 -0
  10. package/dist/PrismicPreview.js +66 -0
  11. package/dist/PrismicPreview.js.map +1 -0
  12. package/dist/enableAutoPreviews.cjs +17 -0
  13. package/dist/enableAutoPreviews.cjs.map +1 -0
  14. package/dist/enableAutoPreviews.d.ts +38 -0
  15. package/dist/enableAutoPreviews.js +17 -0
  16. package/dist/enableAutoPreviews.js.map +1 -0
  17. package/dist/exitPreview.cjs +8 -0
  18. package/dist/exitPreview.cjs.map +1 -0
  19. package/dist/exitPreview.d.ts +34 -0
  20. package/dist/exitPreview.js +8 -0
  21. package/dist/exitPreview.js.map +1 -0
  22. package/dist/index.cjs +15 -182
  23. package/dist/index.cjs.map +1 -0
  24. package/dist/index.d.ts +13 -204
  25. package/dist/index.js +15 -153
  26. package/dist/index.js.map +1 -0
  27. package/dist/lib/__PRODUCTION__.cjs +5 -0
  28. package/dist/lib/__PRODUCTION__.cjs.map +1 -0
  29. package/dist/lib/__PRODUCTION__.d.ts +7 -0
  30. package/dist/lib/__PRODUCTION__.js +5 -0
  31. package/dist/lib/__PRODUCTION__.js.map +1 -0
  32. package/dist/lib/devMsg.cjs +8 -0
  33. package/dist/lib/devMsg.cjs.map +1 -0
  34. package/dist/lib/devMsg.d.ts +16 -0
  35. package/dist/lib/devMsg.js +8 -0
  36. package/dist/lib/devMsg.js.map +1 -0
  37. package/dist/lib/getPreviewCookieRepositoryName.cjs +7 -0
  38. package/dist/lib/getPreviewCookieRepositoryName.cjs.map +1 -0
  39. package/dist/lib/getPreviewCookieRepositoryName.d.ts +9 -0
  40. package/dist/lib/getPreviewCookieRepositoryName.js +7 -0
  41. package/dist/lib/getPreviewCookieRepositoryName.js.map +1 -0
  42. package/dist/lib/getPrismicPreviewCookie.cjs +40 -0
  43. package/dist/lib/getPrismicPreviewCookie.cjs.map +1 -0
  44. package/dist/lib/getPrismicPreviewCookie.d.ts +9 -0
  45. package/dist/lib/getPrismicPreviewCookie.js +21 -0
  46. package/dist/lib/getPrismicPreviewCookie.js.map +1 -0
  47. package/dist/package.cjs +5 -0
  48. package/dist/package.cjs.map +1 -0
  49. package/dist/package.js +5 -0
  50. package/dist/package.js.map +1 -0
  51. package/dist/redirectToPreviewURL.cjs +22 -0
  52. package/dist/redirectToPreviewURL.cjs.map +1 -0
  53. package/dist/redirectToPreviewURL.d.ts +59 -0
  54. package/dist/redirectToPreviewURL.js +22 -0
  55. package/dist/redirectToPreviewURL.js.map +1 -0
  56. package/dist/setPreviewData.cjs +30 -0
  57. package/dist/setPreviewData.cjs.map +1 -0
  58. package/dist/setPreviewData.d.ts +29 -0
  59. package/dist/setPreviewData.js +11 -0
  60. package/dist/setPreviewData.js.map +1 -0
  61. package/dist/types.d.ts +21 -0
  62. package/package.json +37 -32
  63. package/src/PrismicNextImage.tsx +173 -0
  64. package/src/PrismicPreview.tsx +79 -92
  65. package/src/enableAutoPreviews.ts +4 -2
  66. package/src/exitPreview.ts +20 -7
  67. package/src/index.ts +3 -0
  68. package/src/lib/__PRODUCTION__.ts +7 -0
  69. package/src/lib/devMsg.ts +20 -0
  70. package/src/lib/getPreviewCookieRepositoryName.ts +14 -0
  71. package/src/lib/getPrismicPreviewCookie.ts +33 -0
  72. package/src/redirectToPreviewURL.ts +11 -6
  73. package/src/setPreviewData.ts +7 -2
  74. package/src/types.ts +3 -2
  75. package/src/lib/extractPreviewRefRepositoryName.ts +0 -60
  76. package/src/lib/getCookie.ts +0 -51
@@ -0,0 +1,34 @@
1
+ import type { NextApiResponse, NextApiRequest } from "next";
2
+ /**
3
+ * Configuration for `exitPreview`.
4
+ */
5
+ export declare type ExitPreviewConfig = {
6
+ /**
7
+ * The `req` object from a Next.js API route. This is given as a parameter to
8
+ * the API route.
9
+ *
10
+ * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
11
+ */
12
+ req: {
13
+ headers: NextApiRequest["headers"];
14
+ };
15
+ /**
16
+ * The `res` object from a Next.js API route. This is given as a parameter to
17
+ * the API route.
18
+ *
19
+ * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
20
+ */
21
+ res: {
22
+ clearPreviewData: NextApiResponse["clearPreviewData"];
23
+ status: NextApiResponse["status"];
24
+ json: NextApiResponse["json"];
25
+ };
26
+ /**
27
+ * @deprecated - This property is no longer used. It can be deleted safely.
28
+ */
29
+ exitPreviewURL?: string;
30
+ };
31
+ /**
32
+ * Exits Next.js's Preview Mode from within a Next.js API route.
33
+ */
34
+ export declare function exitPreview(config: ExitPreviewConfig): void;
@@ -0,0 +1,8 @@
1
+ function exitPreview(config) {
2
+ config.res.clearPreviewData();
3
+ config.res.status(205).json({ success: true });
4
+ }
5
+ export {
6
+ exitPreview
7
+ };
8
+ //# sourceMappingURL=exitPreview.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exitPreview.js","sources":["../src/exitPreview.ts"],"sourcesContent":["import type { NextApiResponse, NextApiRequest } from \"next\";\n\n/**\n * Configuration for `exitPreview`.\n */\nexport type ExitPreviewConfig = {\n\t/**\n\t * The `req` object from a Next.js API route. This is given as a parameter to\n\t * the API route.\n\t *\n\t * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}\n\t */\n\t// `req` is no longer used in `exitPreview()`. It previously would\n\t// redirect the user to the referring URL, but it no longer has that\n\t// behavior.\n\t//\n\t// `req` is retained as a parameter to make setting up an exit preview\n\t// API route easier (this eliminates the awkward need to handle an\n\t// unused `req` param).\n\t//\n\t// It is also retained in case it is needed in the future, such as\n\t// reading headers or metadata about the request.\n\treq: {\n\t\theaders: NextApiRequest[\"headers\"];\n\t};\n\n\t/**\n\t * The `res` object from a Next.js API route. This is given as a parameter to\n\t * the API route.\n\t *\n\t * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}\n\t */\n\tres: {\n\t\tclearPreviewData: NextApiResponse[\"clearPreviewData\"];\n\t\tstatus: NextApiResponse[\"status\"];\n\t\tjson: NextApiResponse[\"json\"];\n\t};\n\n\t/**\n\t * @deprecated - This property is no longer used. It can be deleted safely.\n\t */\n\texitPreviewURL?: string;\n};\n\n/**\n * Exits Next.js's Preview Mode from within a Next.js API route.\n */\nexport function exitPreview(config: ExitPreviewConfig): void {\n\t// Exit the current user from Preview Mode.\n\tconfig.res.clearPreviewData();\n\n\t// 205 status is used to prevent CDN-level caching. The default 200\n\t// status code is typically treated as non-changing and cacheable.\n\tconfig.res.status(205).json({ success: true });\n}\n"],"names":[],"mappings":"AA+CM,SAAU,YAAY,QAAyB;AAEpD,SAAO,IAAI;AAIJ,SAAA,IAAI,OAAO,GAAG,EAAE,KAAK,EAAE,SAAS,MAAM;AAC9C;"}
package/dist/index.cjs CHANGED
@@ -1,182 +1,15 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- const prismic = require('@prismicio/client');
6
- const React = require('react');
7
- const react = require('@prismicio/react');
8
- const router = require('next/router');
9
-
10
- function _interopNamespace(e) {
11
- if (e && e.__esModule) return e;
12
- const n = Object.create(null);
13
- if (e) {
14
- for (const k in e) {
15
- if (k !== 'default') {
16
- const d = Object.getOwnPropertyDescriptor(e, k);
17
- Object.defineProperty(n, k, d.get ? d : {
18
- enumerable: true,
19
- get: function () { return e[k]; }
20
- });
21
- }
22
- }
23
- }
24
- n["default"] = e;
25
- return Object.freeze(n);
26
- }
27
-
28
- const prismic__namespace = /*#__PURE__*/_interopNamespace(prismic);
29
- const React__namespace = /*#__PURE__*/_interopNamespace(React);
30
-
31
- function setPreviewData({ req, res }) {
32
- const ref = req.query.token || req.cookies[prismic__namespace.cookie.preview];
33
- if (ref) {
34
- res.setPreviewData({ ref });
35
- }
36
- }
37
-
38
- function exitPreview(config) {
39
- config.res.clearPreviewData();
40
- config.res.json({ success: true });
41
- }
42
-
43
- const readValue = (value) => {
44
- return value.replace(/%3B/g, ";");
45
- };
46
- const getCookie = (name) => {
47
- const cookies = document.cookie.split("; ");
48
- for (const cookie of cookies) {
49
- const parts = cookie.split("=");
50
- const value = parts.slice(1).join("=");
51
- const thisName = readValue(parts[0]).replace(/%3D/g, "=");
52
- if (thisName === name) {
53
- return readValue(value);
54
- }
55
- }
56
- };
57
-
58
- const extractFirstSubdomain = (host) => host.split(".")[0];
59
- const extractRepositoryNameFromObjectRef = (previewRef) => {
60
- try {
61
- const parsed = JSON.parse(decodeURIComponent(previewRef));
62
- const keys = Object.keys(parsed);
63
- const domainKey = keys.find((key) => /\.prismic\.io$/.test(key));
64
- if (domainKey) {
65
- return extractFirstSubdomain(domainKey);
66
- } else {
67
- return void 0;
68
- }
69
- } catch (e) {
70
- return void 0;
71
- }
72
- };
73
- const extractRepositoryNameFromURLRef = (previewRef) => {
74
- try {
75
- const url = new URL(previewRef);
76
- return extractFirstSubdomain(url.host);
77
- } catch (e) {
78
- return void 0;
79
- }
80
- };
81
- const extractPreviewRefRepositoryName = (previewRef) => {
82
- return extractRepositoryNameFromObjectRef(previewRef) || extractRepositoryNameFromURLRef(previewRef);
83
- };
84
-
85
- const updatePreviewMode = async (updatePreviewURL) => {
86
- const res = await globalThis.fetch(updatePreviewURL);
87
- if (res.ok) {
88
- window.location.reload();
89
- } else {
90
- console.error(`[<PrismicPreview>] Failed to start or update Preview Mode using the "${updatePreviewURL}" API endpoint. Does it exist?`);
91
- }
92
- };
93
- const exitPreviewMode = async (exitPreviewURL) => {
94
- const res = await globalThis.fetch(exitPreviewURL);
95
- if (res.ok) {
96
- window.location.reload();
97
- } else {
98
- console.error(`[<PrismicPreview>] Failed to exit Preview Mode using the "${exitPreviewURL}" API endpoint. Does it exist?`);
99
- }
100
- };
101
- function PrismicPreview({
102
- repositoryName,
103
- updatePreviewURL = "/api/preview",
104
- exitPreviewURL = "/api/exit-preview",
105
- children
106
- }) {
107
- const router$1 = router.useRouter();
108
- const resolvedUpdatePreviewURL = router$1.basePath + updatePreviewURL;
109
- const resolvedExitPreviewURL = router$1.basePath + exitPreviewURL;
110
- React__namespace.useEffect(() => {
111
- const previewCookie = getCookie(prismic__namespace.cookie.preview);
112
- const prismicPreviewSessionIsForThisRepo = Boolean(previewCookie && extractPreviewRefRepositoryName(previewCookie) === repositoryName);
113
- const locationIsDescendantOfBasePath = window.location.href.startsWith(window.location.origin + router$1.basePath);
114
- const loadedFromShareLink = !router$1.isPreview && previewCookie;
115
- if (prismicPreviewSessionIsForThisRepo && locationIsDescendantOfBasePath && loadedFromShareLink) {
116
- updatePreviewMode(resolvedUpdatePreviewURL);
117
- return;
118
- }
119
- const handlePrismicPreviewUpdate = async (event) => {
120
- event.preventDefault();
121
- await updatePreviewMode(resolvedUpdatePreviewURL);
122
- };
123
- const handlePrismicPreviewEnd = async (event) => {
124
- event.preventDefault();
125
- await exitPreviewMode(resolvedExitPreviewURL);
126
- };
127
- window.addEventListener("prismicPreviewUpdate", handlePrismicPreviewUpdate);
128
- window.addEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
129
- return () => {
130
- window.removeEventListener("prismicPreviewUpdate", handlePrismicPreviewUpdate);
131
- window.removeEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
132
- };
133
- }, [
134
- repositoryName,
135
- resolvedUpdatePreviewURL,
136
- resolvedExitPreviewURL,
137
- router$1.isPreview,
138
- router$1.basePath
139
- ]);
140
- return /* @__PURE__ */ React__namespace.createElement(React__namespace.Fragment, null, children, /* @__PURE__ */ React__namespace.createElement(react.PrismicToolbar, {
141
- repositoryName
142
- }));
143
- }
144
-
145
- const isPrismicNextPreviewData = (previewData) => {
146
- return typeof previewData === "object" && "ref" in previewData;
147
- };
148
- const enableAutoPreviews = (config) => {
149
- if ("previewData" in config && config.previewData) {
150
- const { previewData } = config;
151
- if (isPrismicNextPreviewData(previewData) && previewData.ref) {
152
- config.client.queryContentFromRef(previewData.ref);
153
- }
154
- } else if ("req" in config && config.req) {
155
- config.client.enableAutoPreviewsFromReq(config.req);
156
- }
157
- };
158
-
159
- const isPrismicNextQuery = (query) => {
160
- return typeof query.documentId === "string" && typeof query.token === "string";
161
- };
162
- async function redirectToPreviewURL(config) {
163
- const defaultURL = config.defaultURL || "/";
164
- const basePath = config.basePath || "";
165
- if (isPrismicNextQuery(config.req.query)) {
166
- const previewUrl = await config.client.resolvePreviewURL({
167
- linkResolver: config.linkResolver,
168
- defaultURL,
169
- documentID: config.req.query.documentId,
170
- previewToken: config.req.query.token
171
- });
172
- config.res.redirect(basePath + previewUrl);
173
- return;
174
- }
175
- config.res.redirect(basePath + defaultURL);
176
- }
177
-
178
- exports.PrismicPreview = PrismicPreview;
179
- exports.enableAutoPreviews = enableAutoPreviews;
180
- exports.exitPreview = exitPreview;
181
- exports.redirectToPreviewURL = redirectToPreviewURL;
182
- exports.setPreviewData = setPreviewData;
1
+ "use strict";
2
+ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
3
+ const setPreviewData = require("./setPreviewData.cjs");
4
+ const exitPreview = require("./exitPreview.cjs");
5
+ const PrismicPreview = require("./PrismicPreview.cjs");
6
+ const enableAutoPreviews = require("./enableAutoPreviews.cjs");
7
+ const redirectToPreviewURL = require("./redirectToPreviewURL.cjs");
8
+ const PrismicNextImage = require("./PrismicNextImage.cjs");
9
+ exports.setPreviewData = setPreviewData.setPreviewData;
10
+ exports.exitPreview = exitPreview.exitPreview;
11
+ exports.PrismicPreview = PrismicPreview.PrismicPreview;
12
+ exports.enableAutoPreviews = enableAutoPreviews.enableAutoPreviews;
13
+ exports.redirectToPreviewURL = redirectToPreviewURL.redirectToPreviewURL;
14
+ exports.PrismicNextImage = PrismicNextImage.PrismicNextImage;
15
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;"}
package/dist/index.d.ts CHANGED
@@ -1,204 +1,13 @@
1
- import { NextApiRequest, NextApiResponse, PreviewData } from 'next';
2
- import * as React from 'react';
3
- import { Client, HttpRequestLike } from '@prismicio/client';
4
- import { LinkResolverFunction } from '@prismicio/helpers';
5
-
6
- /**
7
- * Configuration for `setPreviewData`.
8
- */
9
- declare type SetPreviewDataConfig = {
10
- /**
11
- * The `req` object from a Next.js API route. This is given as a parameter to
12
- * the API route.
13
- *
14
- * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
15
- */
16
- req: Pick<NextApiRequest, "query" | "cookies">;
17
- /**
18
- * The `res` object from a Next.js API route. This is given as a parameter to
19
- * the API route.
20
- *
21
- * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
22
- */
23
- res: Pick<NextApiResponse, "setPreviewData">;
24
- };
25
- /**
26
- * Set Prismic preview data for Next.js's Preview Mode.
27
- */
28
- declare function setPreviewData({ req, res }: SetPreviewDataConfig): void;
29
-
30
- /**
31
- * Configuration for `exitPreview`.
32
- */
33
- declare type ExitPreviewConfig = {
34
- /**
35
- * The `req` object from a Next.js API route. This is given as a parameter to
36
- * the API route.
37
- *
38
- * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
39
- */
40
- req: Pick<NextApiRequest, "headers">;
41
- /**
42
- * The `res` object from a Next.js API route. This is given as a parameter to
43
- * the API route.
44
- *
45
- * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
46
- */
47
- res: Pick<NextApiResponse, "clearPreviewData" | "json">;
48
- };
49
- /**
50
- * Exits Next.js's Preview Mode from within a Next.js API route.
51
- */
52
- declare function exitPreview(config: ExitPreviewConfig): void;
53
-
54
- /**
55
- * Props for `<PrismicPreview>`.
56
- */
57
- declare type PrismicPreviewProps = {
58
- /**
59
- * The name of your Prismic repository. A Prismic Toolbar will be registered
60
- * using this repository.
61
- */
62
- repositoryName: string;
63
- /**
64
- * The URL of your app's Prismic preview endpoint (default: `/api/preview`).
65
- * This URL will be fetched on preview update events.
66
- *
67
- * **Note**: If your `next.config.js` file contains a `basePath`, it is
68
- * automatically included.
69
- */
70
- updatePreviewURL?: string;
71
- /**
72
- * The URL of your app's exit preview endpoint (default: `/api/exit-preview`).
73
- * This URL will be fetched on preview exit events.
74
- *
75
- * **Note**: If your `next.config.js` file contains a `basePath`, it is
76
- * automatically included.
77
- */
78
- exitPreviewURL?: string;
79
- /**
80
- * Children to render adjacent to the Prismic Toolbar. The Prismic Toolbar
81
- * will be rendered last.
82
- */
83
- children?: React.ReactNode;
84
- };
85
- /**
86
- * React component that sets up Prismic Previews using the Prismic Toolbar. When
87
- * the Prismic Toolbar send events to the browser, such as on preview updates
88
- * and exiting, this component will automatically update the Next.js preview
89
- * cookie and refresh the page.
90
- *
91
- * This component can be wrapped around your app or added anywhere in your app's
92
- * tree. It must be rendered on every page.
93
- */
94
- declare function PrismicPreview({ repositoryName, updatePreviewURL, exitPreviewURL, children, }: PrismicPreviewProps): JSX.Element;
95
-
96
- /**
97
- * Configuration for `enableAutoPreviews`.
98
- *
99
- * @typeParam TPreviewData - Next.js preview data object.
100
- */
101
- declare type EnableAutoPreviewsConfig<TPreviewData extends PreviewData = PreviewData> = {
102
- /**
103
- * Prismic client with which automatic previews will be enabled.
104
- */
105
- client: Client;
106
- } & ({
107
- /**
108
- * A Next.js context object (such as the context object from
109
- * `getStaticProps` or `getServerSideProps`).
110
- *
111
- * Pass a `context` object when using `enableAutoPreviews` outside a
112
- * Next.js API endpoint.
113
- */
114
- previewData?: TPreviewData;
115
- } | {
116
- /**
117
- * A Next.js API endpoint request object.
118
- *
119
- * Pass a `req` object when using `enableAutoPreviews` in a Next.js API endpoint.
120
- */
121
- req?: HttpRequestLike;
122
- });
123
- /**
124
- * Configures a Prismic client to automatically query draft content during a
125
- * preview session. It either takes in a Next.js `getStaticProps` context object
126
- * or a Next.js API endpoint request object.
127
- *
128
- * @param config - Configuration for the function.
129
- */
130
- declare const enableAutoPreviews: <TPreviewData extends PreviewData>(config: EnableAutoPreviewsConfig<TPreviewData>) => void;
131
-
132
- /**
133
- * Preview config for enabling previews with redirectToPreviewURL
134
- */
135
- declare type RedirectToPreviewURLConfig<TLinkResolverFunction extends LinkResolverFunction<any> = LinkResolverFunction> = {
136
- /**
137
- * The `req` object from a Next.js API route. This is given as a parameter to
138
- * the API route.
139
- *
140
- * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
141
- */
142
- req: Pick<NextApiRequest, "query">;
143
- /**
144
- * The `res` object from a Next.js API route. This is given as a parameter to
145
- * the API route.
146
- *
147
- * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
148
- */
149
- res: Pick<NextApiResponse, "redirect">;
150
- /**
151
- * The Prismic client configured for the preview session's repository.
152
- */
153
- client: Client;
154
- /**
155
- * A Link Resolver used to resolve the previewed document's URL.
156
- *
157
- * @see To learn more about Link Resolver: {@link https://prismic.io/docs/core-concepts/link-resolver-route-resolver}
158
- */
159
- linkResolver?: TLinkResolverFunction;
160
- /**
161
- * The default redirect URL if a URL cannot be determined for the previewed document.
162
- *
163
- * **Note**: If your `next.config.js` file contains a `basePath`, you must
164
- * include the `basePath` as part of this option. `redirectToPreviewURL()`
165
- * cannot read your global `basePath`.
166
- */
167
- defaultURL?: string;
168
- /**
169
- * The `basePath` for the Next.js app as it is defined in `next.config.js`.
170
- * This option can be omitted if the app does not have a `basePath`.
171
- *
172
- * @remarks
173
- * The API route is unable to detect the app's `basePath` automatically. It
174
- * must be provided to `redirectToPreviewURL()` manually.
175
- */
176
- basePath?: string;
177
- };
178
- /**
179
- * Redirects a user to the URL of a previewed Prismic document from within a
180
- * Next.js API route.
181
- */
182
- declare function redirectToPreviewURL<TLinkResolverFunction extends LinkResolverFunction<any>>(config: RedirectToPreviewURLConfig<TLinkResolverFunction>): Promise<void>;
183
-
184
- /**
185
- * Configuration for creating a Prismic client with automatic preview support in
186
- * Next.js apps.
187
- */
188
- declare type CreateClientConfig = {
189
- /**
190
- * Preview data coming from Next.js context object. This context object comes
191
- * from `getStaticProps` or `getServerSideProps`.
192
- *
193
- * Pass `previewData` when using outside a Next.js API endpoint.
194
- */
195
- previewData?: PreviewData;
196
- /**
197
- * A Next.js API endpoint request object.
198
- *
199
- * Pass a `req` object when using in a Next.js API endpoint.
200
- */
201
- req?: NextApiRequest;
202
- };
203
-
204
- export { CreateClientConfig, EnableAutoPreviewsConfig, ExitPreviewConfig, PrismicPreview, PrismicPreviewProps, RedirectToPreviewURLConfig, SetPreviewDataConfig, enableAutoPreviews, exitPreview, redirectToPreviewURL, setPreviewData };
1
+ export { setPreviewData } from "./setPreviewData";
2
+ export type { SetPreviewDataConfig } from "./setPreviewData";
3
+ export { exitPreview } from "./exitPreview";
4
+ export type { ExitPreviewConfig } from "./exitPreview";
5
+ export { PrismicPreview } from "./PrismicPreview";
6
+ export type { PrismicPreviewProps } from "./PrismicPreview";
7
+ export { enableAutoPreviews } from "./enableAutoPreviews";
8
+ export type { EnableAutoPreviewsConfig } from "./enableAutoPreviews";
9
+ export { redirectToPreviewURL } from "./redirectToPreviewURL";
10
+ export type { RedirectToPreviewURLConfig } from "./redirectToPreviewURL";
11
+ export { PrismicNextImage } from "./PrismicNextImage";
12
+ export type { PrismicNextImageProps } from "./PrismicNextImage";
13
+ export type { CreateClientConfig } from "./types";
package/dist/index.js CHANGED
@@ -1,153 +1,15 @@
1
- import * as prismic from '@prismicio/client';
2
- import * as React from 'react';
3
- import { PrismicToolbar } from '@prismicio/react';
4
- import { useRouter } from 'next/router';
5
-
6
- function setPreviewData({ req, res }) {
7
- const ref = req.query.token || req.cookies[prismic.cookie.preview];
8
- if (ref) {
9
- res.setPreviewData({ ref });
10
- }
11
- }
12
-
13
- function exitPreview(config) {
14
- config.res.clearPreviewData();
15
- config.res.json({ success: true });
16
- }
17
-
18
- const readValue = (value) => {
19
- return value.replace(/%3B/g, ";");
20
- };
21
- const getCookie = (name) => {
22
- const cookies = document.cookie.split("; ");
23
- for (const cookie of cookies) {
24
- const parts = cookie.split("=");
25
- const value = parts.slice(1).join("=");
26
- const thisName = readValue(parts[0]).replace(/%3D/g, "=");
27
- if (thisName === name) {
28
- return readValue(value);
29
- }
30
- }
31
- };
32
-
33
- const extractFirstSubdomain = (host) => host.split(".")[0];
34
- const extractRepositoryNameFromObjectRef = (previewRef) => {
35
- try {
36
- const parsed = JSON.parse(decodeURIComponent(previewRef));
37
- const keys = Object.keys(parsed);
38
- const domainKey = keys.find((key) => /\.prismic\.io$/.test(key));
39
- if (domainKey) {
40
- return extractFirstSubdomain(domainKey);
41
- } else {
42
- return void 0;
43
- }
44
- } catch (e) {
45
- return void 0;
46
- }
47
- };
48
- const extractRepositoryNameFromURLRef = (previewRef) => {
49
- try {
50
- const url = new URL(previewRef);
51
- return extractFirstSubdomain(url.host);
52
- } catch (e) {
53
- return void 0;
54
- }
55
- };
56
- const extractPreviewRefRepositoryName = (previewRef) => {
57
- return extractRepositoryNameFromObjectRef(previewRef) || extractRepositoryNameFromURLRef(previewRef);
58
- };
59
-
60
- const updatePreviewMode = async (updatePreviewURL) => {
61
- const res = await globalThis.fetch(updatePreviewURL);
62
- if (res.ok) {
63
- window.location.reload();
64
- } else {
65
- console.error(`[<PrismicPreview>] Failed to start or update Preview Mode using the "${updatePreviewURL}" API endpoint. Does it exist?`);
66
- }
67
- };
68
- const exitPreviewMode = async (exitPreviewURL) => {
69
- const res = await globalThis.fetch(exitPreviewURL);
70
- if (res.ok) {
71
- window.location.reload();
72
- } else {
73
- console.error(`[<PrismicPreview>] Failed to exit Preview Mode using the "${exitPreviewURL}" API endpoint. Does it exist?`);
74
- }
75
- };
76
- function PrismicPreview({
77
- repositoryName,
78
- updatePreviewURL = "/api/preview",
79
- exitPreviewURL = "/api/exit-preview",
80
- children
81
- }) {
82
- const router = useRouter();
83
- const resolvedUpdatePreviewURL = router.basePath + updatePreviewURL;
84
- const resolvedExitPreviewURL = router.basePath + exitPreviewURL;
85
- React.useEffect(() => {
86
- const previewCookie = getCookie(prismic.cookie.preview);
87
- const prismicPreviewSessionIsForThisRepo = Boolean(previewCookie && extractPreviewRefRepositoryName(previewCookie) === repositoryName);
88
- const locationIsDescendantOfBasePath = window.location.href.startsWith(window.location.origin + router.basePath);
89
- const loadedFromShareLink = !router.isPreview && previewCookie;
90
- if (prismicPreviewSessionIsForThisRepo && locationIsDescendantOfBasePath && loadedFromShareLink) {
91
- updatePreviewMode(resolvedUpdatePreviewURL);
92
- return;
93
- }
94
- const handlePrismicPreviewUpdate = async (event) => {
95
- event.preventDefault();
96
- await updatePreviewMode(resolvedUpdatePreviewURL);
97
- };
98
- const handlePrismicPreviewEnd = async (event) => {
99
- event.preventDefault();
100
- await exitPreviewMode(resolvedExitPreviewURL);
101
- };
102
- window.addEventListener("prismicPreviewUpdate", handlePrismicPreviewUpdate);
103
- window.addEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
104
- return () => {
105
- window.removeEventListener("prismicPreviewUpdate", handlePrismicPreviewUpdate);
106
- window.removeEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
107
- };
108
- }, [
109
- repositoryName,
110
- resolvedUpdatePreviewURL,
111
- resolvedExitPreviewURL,
112
- router.isPreview,
113
- router.basePath
114
- ]);
115
- return /* @__PURE__ */ React.createElement(React.Fragment, null, children, /* @__PURE__ */ React.createElement(PrismicToolbar, {
116
- repositoryName
117
- }));
118
- }
119
-
120
- const isPrismicNextPreviewData = (previewData) => {
121
- return typeof previewData === "object" && "ref" in previewData;
122
- };
123
- const enableAutoPreviews = (config) => {
124
- if ("previewData" in config && config.previewData) {
125
- const { previewData } = config;
126
- if (isPrismicNextPreviewData(previewData) && previewData.ref) {
127
- config.client.queryContentFromRef(previewData.ref);
128
- }
129
- } else if ("req" in config && config.req) {
130
- config.client.enableAutoPreviewsFromReq(config.req);
131
- }
132
- };
133
-
134
- const isPrismicNextQuery = (query) => {
135
- return typeof query.documentId === "string" && typeof query.token === "string";
136
- };
137
- async function redirectToPreviewURL(config) {
138
- const defaultURL = config.defaultURL || "/";
139
- const basePath = config.basePath || "";
140
- if (isPrismicNextQuery(config.req.query)) {
141
- const previewUrl = await config.client.resolvePreviewURL({
142
- linkResolver: config.linkResolver,
143
- defaultURL,
144
- documentID: config.req.query.documentId,
145
- previewToken: config.req.query.token
146
- });
147
- config.res.redirect(basePath + previewUrl);
148
- return;
149
- }
150
- config.res.redirect(basePath + defaultURL);
151
- }
152
-
153
- export { PrismicPreview, enableAutoPreviews, exitPreview, redirectToPreviewURL, setPreviewData };
1
+ import { setPreviewData } from "./setPreviewData.js";
2
+ import { exitPreview } from "./exitPreview.js";
3
+ import { PrismicPreview } from "./PrismicPreview.js";
4
+ import { enableAutoPreviews } from "./enableAutoPreviews.js";
5
+ import { redirectToPreviewURL } from "./redirectToPreviewURL.js";
6
+ import { PrismicNextImage } from "./PrismicNextImage.js";
7
+ export {
8
+ PrismicNextImage,
9
+ PrismicPreview,
10
+ enableAutoPreviews,
11
+ exitPreview,
12
+ redirectToPreviewURL,
13
+ setPreviewData
14
+ };
15
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;"}
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
3
+ const __PRODUCTION__ = process.env.NODE_ENV === "production";
4
+ exports.__PRODUCTION__ = __PRODUCTION__;
5
+ //# sourceMappingURL=__PRODUCTION__.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"__PRODUCTION__.cjs","sources":["../../src/lib/__PRODUCTION__.ts"],"sourcesContent":["/**\n * `true` if in the production environment, `false` otherwise.\n *\n * This boolean can be used to perform actions only in development environments,\n * such as logging.\n */\nexport const __PRODUCTION__ = process.env.NODE_ENV === \"production\";\n"],"names":[],"mappings":";;AAMa,MAAA,iBAAiB,QAAQ,IAAI,aAAa;;"}
@@ -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 declare const __PRODUCTION__: boolean;
@@ -0,0 +1,5 @@
1
+ const __PRODUCTION__ = process.env.NODE_ENV === "production";
2
+ export {
3
+ __PRODUCTION__
4
+ };
5
+ //# sourceMappingURL=__PRODUCTION__.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"__PRODUCTION__.js","sources":["../../src/lib/__PRODUCTION__.ts"],"sourcesContent":["/**\n * `true` if in the production environment, `false` otherwise.\n *\n * This boolean can be used to perform actions only in development environments,\n * such as logging.\n */\nexport const __PRODUCTION__ = process.env.NODE_ENV === \"production\";\n"],"names":[],"mappings":"AAMa,MAAA,iBAAiB,QAAQ,IAAI,aAAa;"}