@prismicio/next 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,7 +10,7 @@
10
10
  Helpers to integrate Prismic into Next.js apps.
11
11
 
12
12
  - 👁️  Easily set up Prismic Preview
13
- - _More features coming!_
13
+ - 🖼️  Render optimized images using [`next/image`][next-image] and Prismic's built-in [Imgix][imgix] integration
14
14
 
15
15
  ## Install
16
16
 
@@ -57,6 +57,8 @@ For more clarity on this project and its structure you can also check out the de
57
57
  <!-- Links -->
58
58
 
59
59
  [prismic]: https://prismic.io
60
+ [imgix]: https://imgix.com/
61
+ [next-image]: https://nextjs.org/docs/basic-features/image-optimization
60
62
 
61
63
  <!-- TODO: Replace link with a more useful one if available -->
62
64
 
@@ -0,0 +1,61 @@
1
+ import { jsx } from 'react/jsx-runtime';
2
+ import Image from 'next/image';
3
+ import { buildURL } from 'imgix-url-builder';
4
+ import * as prismicH from '@prismicio/helpers';
5
+ import { __PRODUCTION__ } from './lib/__PRODUCTION__.mjs';
6
+ import { devMsg } from './lib/devMsg.mjs';
7
+
8
+ const imgixLoader = (args) => {
9
+ const url = new URL(args.src);
10
+ const params = {
11
+ fit: url.searchParams.get("fit") || "max",
12
+ w: args.width,
13
+ h: void 0
14
+ };
15
+ if (args.quality) {
16
+ params.q = args.quality;
17
+ }
18
+ return buildURL(args.src, params);
19
+ };
20
+ const PrismicNextImage = ({
21
+ field,
22
+ imgixParams = {},
23
+ alt,
24
+ fallbackAlt,
25
+ layout,
26
+ ...restProps
27
+ }) => {
28
+ if (!__PRODUCTION__) {
29
+ if (typeof alt === "string" && alt !== "") {
30
+ console.warn(
31
+ `[PrismicNextImage] The "alt" prop can only be used to declare an image as decorative by passing an empty string (alt="") but was provided a non-empty string. You can resolve this warning by removing the "alt" prop or changing it to alt="". For more details, see ${devMsg(
32
+ "alt-must-be-an-empty-string"
33
+ )}`
34
+ );
35
+ }
36
+ if (typeof fallbackAlt === "string" && fallbackAlt !== "") {
37
+ console.warn(
38
+ `[PrismicNextImage] The "fallbackAlt" prop can only be used to declare an image as decorative by passing an empty string (fallbackAlt="") but was provided a non-empty string. You can resolve this warning by removing the "fallbackAlt" prop or changing it to fallbackAlt="". For more details, see ${devMsg(
39
+ "alt-must-be-an-empty-string"
40
+ )}`
41
+ );
42
+ }
43
+ }
44
+ if (prismicH.isFilled.imageThumbnail(field)) {
45
+ const src = buildURL(field.url, imgixParams);
46
+ return /* @__PURE__ */ jsx(Image, {
47
+ src,
48
+ width: layout === "fill" ? void 0 : field.dimensions.width,
49
+ height: layout === "fill" ? void 0 : field.dimensions.height,
50
+ alt: alt ?? (field.alt || fallbackAlt),
51
+ loader: imgixLoader,
52
+ layout,
53
+ ...restProps
54
+ });
55
+ } else {
56
+ return null;
57
+ }
58
+ };
59
+
60
+ export { PrismicNextImage };
61
+ //# sourceMappingURL=PrismicNextImage.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PrismicNextImage.mjs","sources":["../src/PrismicNextImage.tsx"],"sourcesContent":["import * as React from \"react\";\nimport Image, { ImageProps, ImageLoaderProps } from \"next/image\";\nimport { buildURL, ImgixURLParams } from \"imgix-url-builder\";\nimport * as prismicH from \"@prismicio/helpers\";\nimport * as prismicT from \"@prismicio/types\";\n\nimport { __PRODUCTION__ } from \"./lib/__PRODUCTION__\";\nimport { devMsg } from \"./lib/devMsg\";\n\n/**\n * Creates a `next/image` loader for Imgix, which Prismic uses, with an optional\n * collection of default Imgix parameters.\n *\n * @see To learn about `next/image` loaders: https://nextjs.org/docs/api-reference/next/image#loader\n * @see To learn about Imgix's URL API: https://docs.imgix.com/apis/rendering\n */\nconst imgixLoader = (args: ImageLoaderProps): string => {\n\tconst url = new URL(args.src);\n\n\tconst params: ImgixURLParams = {\n\t\tfit: (url.searchParams.get(\"fit\") as ImgixURLParams[\"fit\"]) || \"max\",\n\t\tw: args.width,\n\t\th: undefined,\n\t};\n\n\tif (args.quality) {\n\t\tparams.q = args.quality;\n\t}\n\n\treturn buildURL(args.src, params);\n};\n\nexport type PrismicNextImageProps = Omit<\n\tImageProps,\n\t\"src\" | \"alt\" | \"width\" | \"height\"\n> & {\n\t/**\n\t * The Prismic Image field or thumbnail to render.\n\t */\n\tfield: prismicT.ImageFieldImage | null | undefined;\n\n\t/**\n\t * An object of Imgix URL API parameters to transform the image.\n\t *\n\t * @see https://docs.imgix.com/apis/rendering\n\t */\n\timgixParams?: ImgixURLParams;\n\n\t/**\n\t * Declare an image as decorative by providing `alt=\"\"`.\n\t *\n\t * See:\n\t * https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/alt#decorative_images\n\t */\n\talt?: \"\";\n\n\t/**\n\t * Declare an image as decorative only if the Image field does not have\n\t * alternative text by providing `fallbackAlt=\"\"`.\n\t *\n\t * See:\n\t * https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/alt#decorative_images\n\t */\n\tfallbackAlt?: \"\";\n};\n\n/**\n * React component that renders an image from a Prismic Image field or one of\n * its thumbnails using `next/image`. It will automatically set the `alt`\n * attribute using the Image field's `alt` property.\n *\n * It uses an Imgix URL-based loader by default. A custom loader can be provided\n * with the `loader` prop. If you would like to use the Next.js Image\n * Optimization API instead, set `loader={undefined}`.\n *\n * @param props - Props for the component.\n *\n * @returns A responsive image component using `next/image` for the given Image\n * field.\n *\n * @see To learn more about `next/image`, see: https://nextjs.org/docs/api-reference/next/image\n */\nexport const PrismicNextImage = ({\n\tfield,\n\timgixParams = {},\n\talt,\n\tfallbackAlt,\n\tlayout,\n\t...restProps\n}: PrismicNextImageProps) => {\n\tif (!__PRODUCTION__) {\n\t\tif (typeof alt === \"string\" && alt !== \"\") {\n\t\t\tconsole.warn(\n\t\t\t\t`[PrismicNextImage] The \"alt\" prop can only be used to declare an image as decorative by passing an empty string (alt=\"\") but was provided a non-empty string. You can resolve this warning by removing the \"alt\" prop or changing it to alt=\"\". For more details, see ${devMsg(\n\t\t\t\t\t\"alt-must-be-an-empty-string\",\n\t\t\t\t)}`,\n\t\t\t);\n\t\t}\n\n\t\tif (typeof fallbackAlt === \"string\" && fallbackAlt !== \"\") {\n\t\t\tconsole.warn(\n\t\t\t\t`[PrismicNextImage] The \"fallbackAlt\" prop can only be used to declare an image as decorative by passing an empty string (fallbackAlt=\"\") but was provided a non-empty string. You can resolve this warning by removing the \"fallbackAlt\" prop or changing it to fallbackAlt=\"\". For more details, see ${devMsg(\n\t\t\t\t\t\"alt-must-be-an-empty-string\",\n\t\t\t\t)}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tif (prismicH.isFilled.imageThumbnail(field)) {\n\t\tconst src = buildURL(field.url, imgixParams);\n\n\t\treturn (\n\t\t\t<Image\n\t\t\t\tsrc={src}\n\t\t\t\twidth={layout === \"fill\" ? undefined : field.dimensions.width}\n\t\t\t\theight={layout === \"fill\" ? undefined : field.dimensions.height}\n\t\t\t\talt={alt ?? (field.alt || fallbackAlt)}\n\t\t\t\tloader={imgixLoader}\n\t\t\t\tlayout={layout}\n\t\t\t\t{...restProps}\n\t\t\t/>\n\t\t);\n\t} else {\n\t\treturn null;\n\t}\n};\n"],"names":[],"mappings":";;;;;;;AAgBA,MAAM,WAAA,GAAc,CAAC,IAAmC,KAAA;AACvD,EAAA,MAAM,GAAM,GAAA,IAAI,GAAI,CAAA,IAAA,CAAK,GAAG,CAAA,CAAA;AAE5B,EAAA,MAAM,MAAyB,GAAA;AAAA,IAC9B,GAAM,EAAA,GAAA,CAAI,YAAa,CAAA,GAAA,CAAI,KAAK,CAA+B,IAAA,KAAA;AAAA,IAC/D,GAAG,IAAK,CAAA,KAAA;AAAA,IACR,CAAG,EAAA,KAAA,CAAA;AAAA,GACJ,CAAA;AAEA,EAAA,IAAI,KAAK,OAAS,EAAA;AACjB,IAAA,MAAA,CAAO,IAAI,IAAK,CAAA,OAAA,CAAA;AAAA,GACjB;AAEA,EAAO,OAAA,QAAA,CAAS,IAAK,CAAA,GAAA,EAAK,MAAM,CAAA,CAAA;AACjC,CAAA,CAAA;AAoDO,MAAM,mBAAmB,CAAC;AAAA,EAChC,KAAA;AAAA,EACA,cAAc,EAAC;AAAA,EACf,GAAA;AAAA,EACA,WAAA;AAAA,EACA,MAAA;AAAA,EACG,GAAA,SAAA;AACJ,CAA6B,KAAA;AAC5B,EAAA,IAAI,CAAC,cAAgB,EAAA;AACpB,IAAA,IAAI,OAAO,GAAA,KAAQ,QAAY,IAAA,GAAA,KAAQ,EAAI,EAAA;AAC1C,MAAQ,OAAA,CAAA,IAAA;AAAA,QACP,CAAyQ,sQAAA,EAAA,MAAA;AAAA,UACxQ,6BAAA;AAAA,SACD,CAAA,CAAA;AAAA,OACD,CAAA;AAAA,KACD;AAEA,IAAA,IAAI,OAAO,WAAA,KAAgB,QAAY,IAAA,WAAA,KAAgB,EAAI,EAAA;AAC1D,MAAQ,OAAA,CAAA,IAAA;AAAA,QACP,CAAyS,sSAAA,EAAA,MAAA;AAAA,UACxS,6BAAA;AAAA,SACD,CAAA,CAAA;AAAA,OACD,CAAA;AAAA,KACD;AAAA,GACD;AAEA,EAAA,IAAI,QAAS,CAAA,QAAA,CAAS,cAAe,CAAA,KAAK,CAAG,EAAA;AAC5C,IAAA,MAAM,GAAM,GAAA,QAAA,CAAS,KAAM,CAAA,GAAA,EAAK,WAAW,CAAA,CAAA;AAE3C,IAAA,uBACE,GAAA,CAAA,KAAA,EAAA;AAAA,MACA,GAAA;AAAA,MACA,KAAO,EAAA,MAAA,KAAW,MAAS,GAAA,KAAA,CAAA,GAAY,MAAM,UAAW,CAAA,KAAA;AAAA,MACxD,MAAQ,EAAA,MAAA,KAAW,MAAS,GAAA,KAAA,CAAA,GAAY,MAAM,UAAW,CAAA,MAAA;AAAA,MACzD,GAAA,EAAK,GAAQ,KAAA,KAAA,CAAM,GAAO,IAAA,WAAA,CAAA;AAAA,MAC1B,MAAQ,EAAA,WAAA;AAAA,MACR,MAAA;AAAA,MACC,GAAG,SAAA;AAAA,KACL,CAAA,CAAA;AAAA,GAEK,MAAA;AACN,IAAO,OAAA,IAAA,CAAA;AAAA,GACR;AACD;;;;"}
@@ -0,0 +1,88 @@
1
+ import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
2
+ import * as React from 'react';
3
+ import { PrismicToolbar } from '@prismicio/react';
4
+ import { useRouter } from 'next/router';
5
+ import { getPrismicPreviewCookie } from './lib/getPrismicPreviewCookie.mjs';
6
+ import { getPreviewCookieRepositoryName } from './lib/getPreviewCookieRepositoryName.mjs';
7
+
8
+ function PrismicPreview({
9
+ repositoryName,
10
+ children,
11
+ updatePreviewURL = "/api/preview",
12
+ exitPreviewURL = "/api/exit-preview"
13
+ }) {
14
+ const router = useRouter();
15
+ const resolvedUpdatePreviewURL = router.basePath + updatePreviewURL;
16
+ const resolvedExitPreviewURL = router.basePath + exitPreviewURL;
17
+ React.useEffect(() => {
18
+ const startPreviewMode = async () => {
19
+ const res = await globalThis.fetch(resolvedUpdatePreviewURL);
20
+ if (res.ok) {
21
+ globalThis.location.reload();
22
+ } else {
23
+ console.error(
24
+ `[<PrismicPreview>] Failed to start or update Preview Mode using the "${resolvedUpdatePreviewURL}" API endpoint. Does it exist?`
25
+ );
26
+ }
27
+ };
28
+ const handlePrismicPreviewUpdate = async (event) => {
29
+ event.preventDefault();
30
+ await startPreviewMode();
31
+ };
32
+ const handlePrismicPreviewEnd = async (event) => {
33
+ event.preventDefault();
34
+ const res = await globalThis.fetch(resolvedExitPreviewURL);
35
+ if (res.ok) {
36
+ globalThis.location.reload();
37
+ } else {
38
+ console.error(
39
+ `[<PrismicPreview>] Failed to exit Preview Mode using the "${resolvedExitPreviewURL}" API endpoint. Does it exist?`
40
+ );
41
+ }
42
+ };
43
+ if (router.isPreview) {
44
+ window.addEventListener(
45
+ "prismicPreviewUpdate",
46
+ handlePrismicPreviewUpdate
47
+ );
48
+ window.addEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
49
+ } else {
50
+ const prismicPreviewCookie = getPrismicPreviewCookie(
51
+ globalThis.document.cookie
52
+ );
53
+ if (prismicPreviewCookie) {
54
+ const locationIsDescendantOfBasePath = window.location.href.startsWith(
55
+ window.location.origin + router.basePath
56
+ );
57
+ const prismicPreviewCookieRepositoryName = getPreviewCookieRepositoryName(prismicPreviewCookie);
58
+ if (locationIsDescendantOfBasePath && prismicPreviewCookieRepositoryName === repositoryName) {
59
+ startPreviewMode();
60
+ }
61
+ }
62
+ }
63
+ return () => {
64
+ window.removeEventListener(
65
+ "prismicPreviewUpdate",
66
+ handlePrismicPreviewUpdate
67
+ );
68
+ window.removeEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
69
+ };
70
+ }, [
71
+ repositoryName,
72
+ resolvedExitPreviewURL,
73
+ resolvedUpdatePreviewURL,
74
+ router.isPreview,
75
+ router.basePath
76
+ ]);
77
+ return /* @__PURE__ */ jsxs(Fragment, {
78
+ children: [
79
+ children,
80
+ /* @__PURE__ */ jsx(PrismicToolbar, {
81
+ repositoryName
82
+ })
83
+ ]
84
+ });
85
+ }
86
+
87
+ export { PrismicPreview };
88
+ //# sourceMappingURL=PrismicPreview.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PrismicPreview.mjs","sources":["../src/PrismicPreview.tsx"],"sourcesContent":["import * as React from \"react\";\nimport { PrismicToolbar } from \"@prismicio/react\";\nimport { useRouter } from \"next/router\";\n\nimport { getPrismicPreviewCookie } from \"./lib/getPrismicPreviewCookie\";\nimport { getPreviewCookieRepositoryName } from \"./lib/getPreviewCookieRepositoryName\";\n\n/**\n * Props for `<PrismicPreview>`.\n */\nexport type PrismicPreviewProps = {\n\t/**\n\t * The name of your Prismic repository. A Prismic Toolbar will be registered\n\t * using this repository.\n\t */\n\trepositoryName: string;\n\n\t/**\n\t * The URL of your app's Prismic preview endpoint (default: `/api/preview`).\n\t * This URL will be fetched on preview update events.\n\t *\n\t * **Note**: If your `next.config.js` file contains a `basePath`, it is\n\t * automatically included.\n\t */\n\tupdatePreviewURL?: string;\n\n\t/**\n\t * The URL of your app's exit preview endpoint (default: `/api/exit-preview`).\n\t * This URL will be fetched on preview exit events.\n\t *\n\t * **Note**: If your `next.config.js` file contains a `basePath`, it is\n\t * automatically included.\n\t */\n\texitPreviewURL?: string;\n\n\t/**\n\t * Children to render adjacent to the Prismic Toolbar. The Prismic Toolbar\n\t * will be rendered last.\n\t */\n\tchildren?: React.ReactNode;\n};\n\n/**\n * React component that sets up Prismic Previews using the Prismic Toolbar. When\n * the Prismic Toolbar send events to the browser, such as on preview updates\n * and exiting, this component will automatically update the Next.js preview\n * cookie and refresh the page.\n *\n * This component can be wrapped around your app or added anywhere in your app's\n * tree. It must be rendered on every page.\n */\nexport function PrismicPreview({\n\trepositoryName,\n\tchildren,\n\tupdatePreviewURL = \"/api/preview\",\n\texitPreviewURL = \"/api/exit-preview\",\n}: PrismicPreviewProps): JSX.Element {\n\tconst router = useRouter();\n\n\tconst resolvedUpdatePreviewURL = router.basePath + updatePreviewURL;\n\tconst resolvedExitPreviewURL = router.basePath + exitPreviewURL;\n\n\tReact.useEffect(() => {\n\t\t/**\n\t\t * Starts Preview Mode and refreshes the page's props.\n\t\t */\n\t\tconst startPreviewMode = async () => {\n\t\t\t// Start Next.js Preview Mode via the given preview API endpoint.\n\t\t\tconst res = await globalThis.fetch(resolvedUpdatePreviewURL);\n\n\t\t\tif (res.ok) {\n\t\t\t\tglobalThis.location.reload();\n\t\t\t} else {\n\t\t\t\tconsole.error(\n\t\t\t\t\t`[<PrismicPreview>] Failed to start or update Preview Mode using the \"${resolvedUpdatePreviewURL}\" API endpoint. Does it exist?`,\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\n\t\tconst handlePrismicPreviewUpdate = async (event: Event) => {\n\t\t\t// Prevent the toolbar from reloading the page.\n\t\t\tevent.preventDefault();\n\n\t\t\tawait startPreviewMode();\n\t\t};\n\n\t\tconst handlePrismicPreviewEnd = async (event: Event) => {\n\t\t\t// Prevent the toolbar from reloading the page.\n\t\t\tevent.preventDefault();\n\n\t\t\t// Exit Next.js Preview Mode via the given preview API endpoint.\n\t\t\tconst res = await globalThis.fetch(resolvedExitPreviewURL);\n\n\t\t\tif (res.ok) {\n\t\t\t\tglobalThis.location.reload();\n\t\t\t} else {\n\t\t\t\tconsole.error(\n\t\t\t\t\t`[<PrismicPreview>] Failed to exit Preview Mode using the \"${resolvedExitPreviewURL}\" API endpoint. Does it exist?`,\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\n\t\tif (router.isPreview) {\n\t\t\t// Register Prismic Toolbar event handlers.\n\t\t\twindow.addEventListener(\n\t\t\t\t\"prismicPreviewUpdate\",\n\t\t\t\thandlePrismicPreviewUpdate,\n\t\t\t);\n\t\t\twindow.addEventListener(\"prismicPreviewEnd\", handlePrismicPreviewEnd);\n\t\t} else {\n\t\t\tconst prismicPreviewCookie = getPrismicPreviewCookie(\n\t\t\t\tglobalThis.document.cookie,\n\t\t\t);\n\n\t\t\tif (prismicPreviewCookie) {\n\t\t\t\t// If a Prismic preview cookie is present, but Next.js Preview\n\t\t\t\t// Mode is not active, we must activate Preview Mode manually.\n\t\t\t\t//\n\t\t\t\t// This will happen when a visitor accesses the page using a\n\t\t\t\t// Prismic preview share link.\n\n\t\t\t\t/**\n\t\t\t\t * Determines if the current location is a descendant of the app's base\n\t\t\t\t * path.\n\t\t\t\t *\n\t\t\t\t * This is used to prevent infinite refrehes; when\n\t\t\t\t * `isDescendantOfBasePath` is `false`, `router.isPreview` is also\n\t\t\t\t * `false`.\n\t\t\t\t *\n\t\t\t\t * If the app does not have a base path, this should always be `true`.\n\t\t\t\t */\n\t\t\t\tconst locationIsDescendantOfBasePath = window.location.href.startsWith(\n\t\t\t\t\twindow.location.origin + router.basePath,\n\t\t\t\t);\n\n\t\t\t\tconst prismicPreviewCookieRepositoryName =\n\t\t\t\t\tgetPreviewCookieRepositoryName(prismicPreviewCookie);\n\n\t\t\t\tif (\n\t\t\t\t\tlocationIsDescendantOfBasePath &&\n\t\t\t\t\tprismicPreviewCookieRepositoryName === repositoryName\n\t\t\t\t) {\n\t\t\t\t\tstartPreviewMode();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// On cleanup, unregister Prismic Toolbar event handlers.\n\t\treturn () => {\n\t\t\twindow.removeEventListener(\n\t\t\t\t\"prismicPreviewUpdate\",\n\t\t\t\thandlePrismicPreviewUpdate,\n\t\t\t);\n\t\t\twindow.removeEventListener(\"prismicPreviewEnd\", handlePrismicPreviewEnd);\n\t\t};\n\t}, [\n\t\trepositoryName,\n\t\tresolvedExitPreviewURL,\n\t\tresolvedUpdatePreviewURL,\n\t\trouter.isPreview,\n\t\trouter.basePath,\n\t]);\n\n\treturn (\n\t\t<>\n\t\t\t{children}\n\t\t\t<PrismicToolbar repositoryName={repositoryName} />\n\t\t</>\n\t);\n}\n"],"names":[],"mappings":";;;;;;;AAmDO,SAAS,cAAe,CAAA;AAAA,EAC9B,cAAA;AAAA,EACA,QAAA;AAAA,EACA,gBAAmB,GAAA,cAAA;AAAA,EACnB,cAAiB,GAAA,mBAAA;AAClB,CAAqC,EAAA;AACpC,EAAA,MAAM,SAAS,SAAU,EAAA,CAAA;AAEzB,EAAM,MAAA,wBAAA,GAA2B,OAAO,QAAW,GAAA,gBAAA,CAAA;AACnD,EAAM,MAAA,sBAAA,GAAyB,OAAO,QAAW,GAAA,cAAA,CAAA;AAEjD,EAAA,KAAA,CAAM,UAAU,MAAM;AAIrB,IAAA,MAAM,mBAAmB,YAAY;AAEpC,MAAA,MAAM,GAAM,GAAA,MAAM,UAAW,CAAA,KAAA,CAAM,wBAAwB,CAAA,CAAA;AAE3D,MAAA,IAAI,IAAI,EAAI,EAAA;AACX,QAAA,UAAA,CAAW,SAAS,MAAO,EAAA,CAAA;AAAA,OACrB,MAAA;AACN,QAAQ,OAAA,CAAA,KAAA;AAAA,UACP,CAAwE,qEAAA,EAAA,wBAAA,CAAA,8BAAA,CAAA;AAAA,SACzE,CAAA;AAAA,OACD;AAAA,KACD,CAAA;AAEA,IAAM,MAAA,0BAAA,GAA6B,OAAO,KAAiB,KAAA;AAE1D,MAAA,KAAA,CAAM,cAAe,EAAA,CAAA;AAErB,MAAA,MAAM,gBAAiB,EAAA,CAAA;AAAA,KACxB,CAAA;AAEA,IAAM,MAAA,uBAAA,GAA0B,OAAO,KAAiB,KAAA;AAEvD,MAAA,KAAA,CAAM,cAAe,EAAA,CAAA;AAGrB,MAAA,MAAM,GAAM,GAAA,MAAM,UAAW,CAAA,KAAA,CAAM,sBAAsB,CAAA,CAAA;AAEzD,MAAA,IAAI,IAAI,EAAI,EAAA;AACX,QAAA,UAAA,CAAW,SAAS,MAAO,EAAA,CAAA;AAAA,OACrB,MAAA;AACN,QAAQ,OAAA,CAAA,KAAA;AAAA,UACP,CAA6D,0DAAA,EAAA,sBAAA,CAAA,8BAAA,CAAA;AAAA,SAC9D,CAAA;AAAA,OACD;AAAA,KACD,CAAA;AAEA,IAAA,IAAI,OAAO,SAAW,EAAA;AAErB,MAAO,MAAA,CAAA,gBAAA;AAAA,QACN,sBAAA;AAAA,QACA,0BAAA;AAAA,OACD,CAAA;AACA,MAAO,MAAA,CAAA,gBAAA,CAAiB,qBAAqB,uBAAuB,CAAA,CAAA;AAAA,KAC9D,MAAA;AACN,MAAA,MAAM,oBAAuB,GAAA,uBAAA;AAAA,QAC5B,WAAW,QAAS,CAAA,MAAA;AAAA,OACrB,CAAA;AAEA,MAAA,IAAI,oBAAsB,EAAA;AAiBzB,QAAM,MAAA,8BAAA,GAAiC,MAAO,CAAA,QAAA,CAAS,IAAK,CAAA,UAAA;AAAA,UAC3D,MAAA,CAAO,QAAS,CAAA,MAAA,GAAS,MAAO,CAAA,QAAA;AAAA,SACjC,CAAA;AAEA,QAAM,MAAA,kCAAA,GACL,+BAA+B,oBAAoB,CAAA,CAAA;AAEpD,QACC,IAAA,8BAAA,IACA,uCAAuC,cACtC,EAAA;AACD,UAAiB,gBAAA,EAAA,CAAA;AAAA,SAClB;AAAA,OACD;AAAA,KACD;AAGA,IAAA,OAAO,MAAM;AACZ,MAAO,MAAA,CAAA,mBAAA;AAAA,QACN,sBAAA;AAAA,QACA,0BAAA;AAAA,OACD,CAAA;AACA,MAAO,MAAA,CAAA,mBAAA,CAAoB,qBAAqB,uBAAuB,CAAA,CAAA;AAAA,KACxE,CAAA;AAAA,GACE,EAAA;AAAA,IACF,cAAA;AAAA,IACA,sBAAA;AAAA,IACA,wBAAA;AAAA,IACA,MAAO,CAAA,SAAA;AAAA,IACP,MAAO,CAAA,QAAA;AAAA,GACP,CAAA,CAAA;AAED,EACC,uBAAA,IAAA,CAAA,QAAA,EAAA;AAAA,IACE,QAAA,EAAA;AAAA,MAAA,QAAA;AAAA,sBACA,GAAA,CAAA,cAAA,EAAA;AAAA,QAAe,cAAA;AAAA,OAAgC,CAAA;AAAA,KAAA;AAAA,GACjD,CAAA,CAAA;AAEF;;;;"}
@@ -0,0 +1,16 @@
1
+ const isPrismicNextPreviewData = (previewData) => {
2
+ return typeof previewData === "object" && "ref" in previewData;
3
+ };
4
+ const enableAutoPreviews = (config) => {
5
+ if ("previewData" in config && config.previewData) {
6
+ const { previewData } = config;
7
+ if (isPrismicNextPreviewData(previewData) && previewData.ref) {
8
+ config.client.queryContentFromRef(previewData.ref);
9
+ }
10
+ } else if ("req" in config && config.req) {
11
+ config.client.enableAutoPreviewsFromReq(config.req);
12
+ }
13
+ };
14
+
15
+ export { enableAutoPreviews };
16
+ //# sourceMappingURL=enableAutoPreviews.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enableAutoPreviews.mjs","sources":["../src/enableAutoPreviews.ts"],"sourcesContent":["import { PreviewData } from \"next\";\nimport { Client, HttpRequestLike } from \"@prismicio/client\";\n\ninterface PrismicNextPreviewData {\n\tref: string;\n}\n\n/**\n * Determines if a Next.js preview data object contains Prismic preview data.\n *\n * @param previewData - The Next.js preview data object to check.\n *\n * @returns `true` if `previewData` contains Prismic preview data, `false`\n * otherwise.\n */\nconst isPrismicNextPreviewData = (\n\tpreviewData: PreviewData,\n): previewData is PrismicNextPreviewData => {\n\treturn typeof previewData === \"object\" && \"ref\" in previewData;\n};\n\n/**\n * Configuration for `enableAutoPreviews`.\n *\n * @typeParam TPreviewData - Next.js preview data object.\n */\nexport type EnableAutoPreviewsConfig<\n\tTPreviewData extends PreviewData = PreviewData,\n> = {\n\t/**\n\t * Prismic client with which automatic previews will be enabled.\n\t */\n\tclient: Client;\n} & (\n\t| {\n\t\t\t/**\n\t\t\t * A Next.js context object (such as the context object from\n\t\t\t * `getStaticProps` or `getServerSideProps`).\n\t\t\t *\n\t\t\t * Pass a `context` object when using `enableAutoPreviews` outside a\n\t\t\t * Next.js API endpoint.\n\t\t\t */\n\t\t\tpreviewData?: TPreviewData;\n\t }\n\t| {\n\t\t\t/**\n\t\t\t * A Next.js API endpoint request object.\n\t\t\t *\n\t\t\t * Pass a `req` object when using `enableAutoPreviews` in a Next.js API\n\t\t\t * endpoint.\n\t\t\t */\n\t\t\treq?: HttpRequestLike;\n\t }\n);\n/**\n * Configures a Prismic client to automatically query draft content during a\n * preview session. It either takes in a Next.js `getStaticProps` context object\n * or a Next.js API endpoint request object.\n *\n * @param config - Configuration for the function.\n */\nexport const enableAutoPreviews = <TPreviewData extends PreviewData>(\n\tconfig: EnableAutoPreviewsConfig<TPreviewData>,\n): void => {\n\tif (\"previewData\" in config && config.previewData) {\n\t\t// If preview data is being passed from Next Context then use queryContentFromRef\n\n\t\tconst { previewData } = config;\n\n\t\tif (isPrismicNextPreviewData(previewData) && previewData.ref) {\n\t\t\tconfig.client.queryContentFromRef(previewData.ref);\n\t\t}\n\t} else if (\"req\" in config && config.req) {\n\t\t// If the req object is passed then use enableAutoPreviewsFromReq\n\n\t\tconfig.client.enableAutoPreviewsFromReq(config.req);\n\t}\n};\n"],"names":[],"mappings":"AAeA,MAAM,wBAAA,GAA2B,CAChC,WAC2C,KAAA;AAC3C,EAAO,OAAA,OAAO,WAAgB,KAAA,QAAA,IAAY,KAAS,IAAA,WAAA,CAAA;AACpD,CAAA,CAAA;AA0Ca,MAAA,kBAAA,GAAqB,CACjC,MACU,KAAA;AACV,EAAI,IAAA,aAAA,IAAiB,MAAU,IAAA,MAAA,CAAO,WAAa,EAAA;AAGlD,IAAM,MAAA,EAAE,aAAgB,GAAA,MAAA,CAAA;AAExB,IAAA,IAAI,wBAAyB,CAAA,WAAW,CAAK,IAAA,WAAA,CAAY,GAAK,EAAA;AAC7D,MAAO,MAAA,CAAA,MAAA,CAAO,mBAAoB,CAAA,WAAA,CAAY,GAAG,CAAA,CAAA;AAAA,KAClD;AAAA,GACU,MAAA,IAAA,KAAA,IAAS,MAAU,IAAA,MAAA,CAAO,GAAK,EAAA;AAGzC,IAAO,MAAA,CAAA,MAAA,CAAO,yBAA0B,CAAA,MAAA,CAAO,GAAG,CAAA,CAAA;AAAA,GACnD;AACD;;;;"}
@@ -0,0 +1,7 @@
1
+ function exitPreview(config) {
2
+ config.res.clearPreviewData();
3
+ config.res.status(205).json({ success: true });
4
+ }
5
+
6
+ export { exitPreview };
7
+ //# sourceMappingURL=exitPreview.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exitPreview.mjs","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+CO,SAAS,YAAY,MAAiC,EAAA;AAE5D,EAAA,MAAA,CAAO,IAAI,gBAAiB,EAAA,CAAA;AAI5B,EAAO,MAAA,CAAA,GAAA,CAAI,OAAO,GAAG,CAAA,CAAE,KAAK,EAAE,OAAA,EAAS,MAAM,CAAA,CAAA;AAC9C;;;;"}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { NextApiRequest, NextApiResponse, PreviewData } from 'next';
2
2
  import * as React from 'react';
3
- import { Client, HttpRequestLike } from '@prismicio/client';
3
+ import { Client, HttpRequestLike, ClientConfig } from '@prismicio/client';
4
4
  import { LinkResolverFunction } from '@prismicio/helpers';
5
5
  import { ImageProps } from 'next/image';
6
6
  import { ImgixURLParams } from 'imgix-url-builder';
@@ -56,6 +56,7 @@ declare type ExitPreviewConfig = {
56
56
  */
57
57
  res: {
58
58
  clearPreviewData: NextApiResponse["clearPreviewData"];
59
+ status: NextApiResponse["status"];
59
60
  json: NextApiResponse["json"];
60
61
  };
61
62
  /**
@@ -133,7 +134,8 @@ declare type EnableAutoPreviewsConfig<TPreviewData extends PreviewData = Preview
133
134
  /**
134
135
  * A Next.js API endpoint request object.
135
136
  *
136
- * Pass a `req` object when using `enableAutoPreviews` in a Next.js API endpoint.
137
+ * Pass a `req` object when using `enableAutoPreviews` in a Next.js API
138
+ * endpoint.
137
139
  */
138
140
  req?: HttpRequestLike;
139
141
  });
@@ -179,7 +181,8 @@ declare type RedirectToPreviewURLConfig<TLinkResolverFunction extends LinkResolv
179
181
  */
180
182
  linkResolver?: TLinkResolverFunction;
181
183
  /**
182
- * The default redirect URL if a URL cannot be determined for the previewed document.
184
+ * The default redirect URL if a URL cannot be determined for the previewed
185
+ * document.
183
186
  *
184
187
  * **Note**: If you `next.config.js` file contains a `basePath`, the
185
188
  * `defaultURL` option must _not_ include it. Instead, provide the `basePath`
@@ -240,7 +243,8 @@ declare type PrismicNextImageProps = Omit<ImageProps, "src" | "alt" | "width" |
240
243
  *
241
244
  * @param props - Props for the component.
242
245
  *
243
- * @returns A responsive image component using `next/image` for the given Image field.
246
+ * @returns A responsive image component using `next/image` for the given Image
247
+ * field.
244
248
  *
245
249
  * @see To learn more about `next/image`, see: https://nextjs.org/docs/api-reference/next/image
246
250
  */
@@ -264,6 +268,6 @@ declare type CreateClientConfig = {
264
268
  * Pass a `req` object when using in a Next.js API endpoint.
265
269
  */
266
270
  req?: NextApiRequest;
267
- };
271
+ } & ClientConfig;
268
272
 
269
273
  export { CreateClientConfig, EnableAutoPreviewsConfig, ExitPreviewConfig, PrismicNextImage, PrismicNextImageProps, PrismicPreview, PrismicPreviewProps, RedirectToPreviewURLConfig, SetPreviewDataConfig, enableAutoPreviews, exitPreview, redirectToPreviewURL, setPreviewData };
package/dist/index.mjs ADDED
@@ -0,0 +1,7 @@
1
+ export { setPreviewData } from './setPreviewData.mjs';
2
+ export { exitPreview } from './exitPreview.mjs';
3
+ export { PrismicPreview } from './PrismicPreview.mjs';
4
+ export { enableAutoPreviews } from './enableAutoPreviews.mjs';
5
+ export { redirectToPreviewURL } from './redirectToPreviewURL.mjs';
6
+ export { PrismicNextImage } from './PrismicNextImage.mjs';
7
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;"}
@@ -0,0 +1,4 @@
1
+ const __PRODUCTION__ = process.env.NODE_ENV === "production";
2
+
3
+ export { __PRODUCTION__ };
4
+ //# sourceMappingURL=__PRODUCTION__.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"__PRODUCTION__.mjs","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,cAAA,GAAiB,OAAQ,CAAA,GAAA,CAAI,QAAa,KAAA;;;;"}
@@ -0,0 +1,8 @@
1
+ import { version } from '../package.mjs';
2
+
3
+ const devMsg = (slug) => {
4
+ return `https://prismic.dev/msg/next/v${version}/${slug}`;
5
+ };
6
+
7
+ export { devMsg };
8
+ //# sourceMappingURL=devMsg.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"devMsg.mjs","sources":["../../src/lib/devMsg.ts"],"sourcesContent":["import { version } from \"../../package.json\";\n\n/**\n * Returns a `prismic.dev/msg` URL for a given message slug.\n *\n * @example\n *\n * ```ts\n * devMsg(\"missing-param\");\n * // => \"https://prismic.dev/msg/next/v1.2.3/missing-param.md\"\n * ```\n *\n * @param slug - Slug for the message. This corresponds to a Markdown file in\n * the Git repository's `/messages` directory.\n *\n * @returns The `prismic.dev/msg` URL for the given slug.\n */\nexport const devMsg = (slug: string) => {\n\treturn `https://prismic.dev/msg/next/v${version}/${slug}`;\n};\n"],"names":[],"mappings":";;AAiBa,MAAA,MAAA,GAAS,CAAC,IAAiB,KAAA;AACvC,EAAA,OAAO,iCAAiC,OAAW,CAAA,CAAA,EAAA,IAAA,CAAA,CAAA,CAAA;AACpD;;;;"}
@@ -0,0 +1,6 @@
1
+ const getPreviewCookieRepositoryName = (previewCookie) => {
2
+ return (decodeURIComponent(previewCookie).match(/"(.+).prismic.io"/) || [])[1];
3
+ };
4
+
5
+ export { getPreviewCookieRepositoryName };
6
+ //# sourceMappingURL=getPreviewCookieRepositoryName.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getPreviewCookieRepositoryName.mjs","sources":["../../src/lib/getPreviewCookieRepositoryName.ts"],"sourcesContent":["/**\n * Extracts preview reference repo name from stringified Prismic preview cookie\n *\n * @param previewCookie - The Prismic preview cookie.\n *\n * @returns The repository name for the Prismic preview cookie. If the cookie\n * represents an inactive preview session, `undefined` will be returned.\n */\nexport const getPreviewCookieRepositoryName = (\n\tpreviewCookie: string,\n): string | undefined => {\n\treturn (decodeURIComponent(previewCookie).match(/\"(.+).prismic.io\"/) ||\n\t\t[])[1];\n};\n"],"names":[],"mappings":"AAQa,MAAA,8BAAA,GAAiC,CAC7C,aACwB,KAAA;AACxB,EAAA,OAAA,CAAQ,mBAAmB,aAAa,CAAA,CAAE,MAAM,mBAAmB,CAAA,IAClE,EAAI,EAAA,CAAA,CAAA,CAAA;AACN;;;;"}
@@ -0,0 +1,21 @@
1
+ import * as prismic from '@prismicio/client';
2
+
3
+ const readValue = (value) => {
4
+ return value.replace(/%3B/g, ";");
5
+ };
6
+ const getPrismicPreviewCookie = (cookieJar) => {
7
+ const cookies = cookieJar.split("; ");
8
+ let value;
9
+ for (const cookie of cookies) {
10
+ const parts = cookie.split("=");
11
+ const name = readValue(parts[0]).replace(/%3D/g, "=");
12
+ if (name === prismic.cookie.preview) {
13
+ value = readValue(parts.slice(1).join("="));
14
+ continue;
15
+ }
16
+ }
17
+ return value;
18
+ };
19
+
20
+ export { getPrismicPreviewCookie };
21
+ //# sourceMappingURL=getPrismicPreviewCookie.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getPrismicPreviewCookie.mjs","sources":["../../src/lib/getPrismicPreviewCookie.ts"],"sourcesContent":["import * as prismic from \"@prismicio/client\";\n\nconst readValue = (value: string): string => {\n\treturn value.replace(/%3B/g, \";\");\n};\n\n/**\n * Returns the value of a cookie from a given cookie store.\n *\n * @param cookieJar - The stringified cookie store from which to read the\n * cookie.\n *\n * @returns The value of the cookie, if it exists.\n */\nexport const getPrismicPreviewCookie = (\n\tcookieJar: string,\n): string | undefined => {\n\tconst cookies = cookieJar.split(\"; \");\n\n\tlet value: string | undefined;\n\n\tfor (const cookie of cookies) {\n\t\tconst parts = cookie.split(\"=\");\n\t\tconst name = readValue(parts[0]).replace(/%3D/g, \"=\");\n\n\t\tif (name === prismic.cookie.preview) {\n\t\t\tvalue = readValue(parts.slice(1).join(\"=\"));\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\treturn value;\n};\n"],"names":[],"mappings":";;AAEA,MAAM,SAAA,GAAY,CAAC,KAA0B,KAAA;AAC5C,EAAO,OAAA,KAAA,CAAM,OAAQ,CAAA,MAAA,EAAQ,GAAG,CAAA,CAAA;AACjC,CAAA,CAAA;AAUa,MAAA,uBAAA,GAA0B,CACtC,SACwB,KAAA;AACxB,EAAM,MAAA,OAAA,GAAU,SAAU,CAAA,KAAA,CAAM,IAAI,CAAA,CAAA;AAEpC,EAAI,IAAA,KAAA,CAAA;AAEJ,EAAA,KAAA,MAAW,UAAU,OAAS,EAAA;AAC7B,IAAM,MAAA,KAAA,GAAQ,MAAO,CAAA,KAAA,CAAM,GAAG,CAAA,CAAA;AAC9B,IAAA,MAAM,OAAO,SAAU,CAAA,KAAA,CAAM,EAAE,CAAE,CAAA,OAAA,CAAQ,QAAQ,GAAG,CAAA,CAAA;AAEpD,IAAI,IAAA,IAAA,KAAS,OAAQ,CAAA,MAAA,CAAO,OAAS,EAAA;AACpC,MAAA,KAAA,GAAQ,UAAU,KAAM,CAAA,KAAA,CAAM,CAAC,CAAE,CAAA,IAAA,CAAK,GAAG,CAAC,CAAA,CAAA;AAC1C,MAAA,SAAA;AAAA,KACD;AAAA,GACD;AAEA,EAAO,OAAA,KAAA,CAAA;AACR;;;;"}
@@ -0,0 +1,4 @@
1
+ const version = "0.1.5";
2
+
3
+ export { version };
4
+ //# sourceMappingURL=package.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"package.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;"}
@@ -0,0 +1,21 @@
1
+ const isPrismicNextQuery = (query) => {
2
+ return typeof query.documentId === "string" && typeof query.token === "string";
3
+ };
4
+ async function redirectToPreviewURL(config) {
5
+ const defaultURL = config.defaultURL || "/";
6
+ const basePath = config.basePath || "";
7
+ if (isPrismicNextQuery(config.req.query)) {
8
+ const previewUrl = await config.client.resolvePreviewURL({
9
+ linkResolver: config.linkResolver,
10
+ defaultURL,
11
+ documentID: config.req.query.documentId,
12
+ previewToken: config.req.query.token
13
+ });
14
+ config.res.redirect(basePath + previewUrl);
15
+ return;
16
+ }
17
+ config.res.redirect(basePath + defaultURL);
18
+ }
19
+
20
+ export { redirectToPreviewURL };
21
+ //# sourceMappingURL=redirectToPreviewURL.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redirectToPreviewURL.mjs","sources":["../src/redirectToPreviewURL.ts"],"sourcesContent":["import type { Client } from \"@prismicio/client\";\nimport type { NextApiRequest, NextApiResponse } from \"next\";\nimport type { LinkResolverFunction } from \"@prismicio/helpers\";\n\ntype PrismicNextQuery = {\n\tdocumentId: string;\n\ttoken: string;\n};\n\n/**\n * Determines if a query object from a Next.js API route request contains\n * Prismic preview data.\n *\n * @param query - Query object to check.\n *\n * @returns `true` if `query` contains Prismic preview data, `false` otherwise.\n */\nconst isPrismicNextQuery = (\n\tquery: NextApiRequest[\"query\"],\n): query is PrismicNextQuery => {\n\treturn (\n\t\ttypeof query.documentId === \"string\" && typeof query.token === \"string\"\n\t);\n};\n\n/**\n * Preview config for enabling previews with redirectToPreviewURL\n */\nexport type RedirectToPreviewURLConfig<\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tTLinkResolverFunction extends LinkResolverFunction<any> = LinkResolverFunction,\n> = {\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\treq: {\n\t\tquery: NextApiRequest[\"query\"];\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\tredirect: NextApiResponse[\"redirect\"];\n\t};\n\n\t/**\n\t * The Prismic client configured for the preview session's repository.\n\t */\n\tclient: Client;\n\n\t/**\n\t * A Link Resolver used to resolve the previewed document's URL.\n\t *\n\t * @see To learn more about Link Resolver: {@link https://prismic.io/docs/core-concepts/link-resolver-route-resolver}\n\t */\n\tlinkResolver?: TLinkResolverFunction;\n\n\t/**\n\t * The default redirect URL if a URL cannot be determined for the previewed\n\t * document.\n\t *\n\t * **Note**: If you `next.config.js` file contains a `basePath`, the\n\t * `defaultURL` option must _not_ include it. Instead, provide the `basePath`\n\t * property using the `basePath` option.\n\t */\n\tdefaultURL?: string;\n\n\t/**\n\t * The `basePath` for the Next.js app as it is defined in `next.config.js`.\n\t * This option can be omitted if the app does not have a `basePath`.\n\t *\n\t * @remarks\n\t * The API route is unable to detect the app's `basePath` automatically. It\n\t * must be provided to `redirectToPreviewURL()` manually.\n\t */\n\tbasePath?: string;\n};\n\n/**\n * Redirects a user to the URL of a previewed Prismic document from within a\n * Next.js API route.\n */\nexport async function redirectToPreviewURL<\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tTLinkResolverFunction extends LinkResolverFunction<any>,\n>(config: RedirectToPreviewURLConfig<TLinkResolverFunction>): Promise<void> {\n\tconst defaultURL = config.defaultURL || \"/\";\n\tconst basePath = config.basePath || \"\";\n\n\tif (isPrismicNextQuery(config.req.query)) {\n\t\tconst previewUrl = await config.client.resolvePreviewURL({\n\t\t\tlinkResolver: config.linkResolver,\n\t\t\tdefaultURL,\n\t\t\tdocumentID: config.req.query.documentId,\n\t\t\tpreviewToken: config.req.query.token,\n\t\t});\n\n\t\tconfig.res.redirect(basePath + previewUrl);\n\n\t\treturn;\n\t}\n\n\tconfig.res.redirect(basePath + defaultURL);\n}\n"],"names":[],"mappings":"AAiBA,MAAM,kBAAA,GAAqB,CAC1B,KAC+B,KAAA;AAC/B,EAAA,OACC,OAAO,KAAM,CAAA,UAAA,KAAe,QAAY,IAAA,OAAO,MAAM,KAAU,KAAA,QAAA,CAAA;AAEjE,CAAA,CAAA;AAkEA,eAAsB,qBAGpB,MAA0E,EAAA;AAC3E,EAAM,MAAA,UAAA,GAAa,OAAO,UAAc,IAAA,GAAA,CAAA;AACxC,EAAM,MAAA,QAAA,GAAW,OAAO,QAAY,IAAA,EAAA,CAAA;AAEpC,EAAA,IAAI,kBAAmB,CAAA,MAAA,CAAO,GAAI,CAAA,KAAK,CAAG,EAAA;AACzC,IAAA,MAAM,UAAa,GAAA,MAAM,MAAO,CAAA,MAAA,CAAO,iBAAkB,CAAA;AAAA,MACxD,cAAc,MAAO,CAAA,YAAA;AAAA,MACrB,UAAA;AAAA,MACA,UAAA,EAAY,MAAO,CAAA,GAAA,CAAI,KAAM,CAAA,UAAA;AAAA,MAC7B,YAAA,EAAc,MAAO,CAAA,GAAA,CAAI,KAAM,CAAA,KAAA;AAAA,KAC/B,CAAA,CAAA;AAED,IAAO,MAAA,CAAA,GAAA,CAAI,QAAS,CAAA,QAAA,GAAW,UAAU,CAAA,CAAA;AAEzC,IAAA,OAAA;AAAA,GACD;AAEA,EAAO,MAAA,CAAA,GAAA,CAAI,QAAS,CAAA,QAAA,GAAW,UAAU,CAAA,CAAA;AAC1C;;;;"}
@@ -0,0 +1,11 @@
1
+ import * as prismic from '@prismicio/client';
2
+
3
+ function setPreviewData({ req, res }) {
4
+ const ref = req.query.token || req.cookies[prismic.cookie.preview];
5
+ if (ref) {
6
+ res.setPreviewData({ ref });
7
+ }
8
+ }
9
+
10
+ export { setPreviewData };
11
+ //# sourceMappingURL=setPreviewData.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setPreviewData.mjs","sources":["../src/setPreviewData.ts"],"sourcesContent":["import { NextApiResponse, NextApiRequest } from \"next\";\nimport * as prismic from \"@prismicio/client\";\n\n/**\n * Configuration for `setPreviewData`.\n */\nexport type SetPreviewDataConfig = {\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\treq: {\n\t\tquery: NextApiRequest[\"query\"];\n\t\tcookies: NextApiRequest[\"cookies\"];\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\tsetPreviewData: NextApiResponse[\"setPreviewData\"];\n\t};\n};\n\n/**\n * Set Prismic preview data for Next.js's Preview Mode.\n */\nexport function setPreviewData({ req, res }: SetPreviewDataConfig): void {\n\tconst ref = req.query.token || req.cookies[prismic.cookie.preview];\n\n\tif (ref) {\n\t\tres.setPreviewData({ ref });\n\t}\n}\n"],"names":[],"mappings":";;AAgCO,SAAS,cAAe,CAAA,EAAE,GAAK,EAAA,GAAA,EAAmC,EAAA;AACxE,EAAA,MAAM,MAAM,GAAI,CAAA,KAAA,CAAM,SAAS,GAAI,CAAA,OAAA,CAAQ,QAAQ,MAAO,CAAA,OAAA,CAAA,CAAA;AAE1D,EAAA,IAAI,GAAK,EAAA;AACR,IAAI,GAAA,CAAA,cAAA,CAAe,EAAE,GAAA,EAAK,CAAA,CAAA;AAAA,GAC3B;AACD;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prismicio/next",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "description": "Helpers to integrate Prismic into Next.js apps",
5
5
  "keywords": [
6
6
  "typescript",
@@ -15,23 +15,22 @@
15
15
  },
16
16
  "license": "Apache-2.0",
17
17
  "author": "Prismic <contact@prismic.io> (https://prismic.io)",
18
+ "sideEffects": false,
19
+ "type": "module",
18
20
  "exports": {
19
- ".": {
20
- "require": "./dist/index.cjs",
21
- "import": "./dist/index.js"
22
- },
21
+ ".": "./dist/index.mjs",
23
22
  "./package.json": "./package.json"
24
23
  },
25
- "main": "./dist/index.cjs",
26
- "module": "dist/index.js",
24
+ "main": "./dist/index.mjs",
25
+ "module": "./dist/index.mjs",
27
26
  "types": "dist/index.d.ts",
28
27
  "files": [
29
28
  "dist",
30
29
  "src"
31
30
  ],
32
31
  "scripts": {
33
- "build": "siroc build",
34
- "dev": "siroc build --watch",
32
+ "build": "unbuild",
33
+ "dev": "chokidar src --initial --command unbuild",
35
34
  "format": "prettier --write .",
36
35
  "lint": "eslint --ext .js,.ts .",
37
36
  "prepare": "npm run build",
@@ -45,36 +44,38 @@
45
44
  "unit:watch": "vitest watch"
46
45
  },
47
46
  "dependencies": {
48
- "@prismicio/client": "^6.4.3",
49
- "@prismicio/helpers": "^2.3.0",
50
- "@prismicio/react": "^2.4.0",
51
- "@prismicio/types": "^0.1.27",
52
- "eslint-plugin-react": "^7.30.0",
53
- "eslint-plugin-react-hooks": "^4.5.0"
47
+ "@prismicio/client": "^6.7.1",
48
+ "@prismicio/helpers": "^2.3.3",
49
+ "@prismicio/react": "^2.5.0",
50
+ "@prismicio/types": "^0.2.3",
51
+ "eslint-plugin-react": "^7.31.7",
52
+ "eslint-plugin-react-hooks": "^4.6.0",
53
+ "imgix-url-builder": "^0.0.3"
54
54
  },
55
55
  "devDependencies": {
56
- "@prismicio/mock": "^0.0.10",
57
- "@size-limit/preset-small-lib": "^7.0.8",
56
+ "@prismicio/mock": "^0.1.1",
57
+ "@size-limit/preset-small-lib": "^8.1.0",
58
58
  "@types/react-test-renderer": "^18.0.0",
59
- "@typescript-eslint/eslint-plugin": "^5.26.0",
60
- "@typescript-eslint/parser": "^5.26.0",
61
- "c8": "^7.11.3",
62
- "eslint": "^8.16.0",
59
+ "@typescript-eslint/eslint-plugin": "^5.36.2",
60
+ "@typescript-eslint/parser": "^5.36.2",
61
+ "@vitest/coverage-c8": "^0.23.1",
62
+ "chokidar-cli": "^3.0.0",
63
+ "eslint": "^8.23.0",
63
64
  "eslint-config-prettier": "^8.5.0",
64
- "eslint-plugin-prettier": "^4.0.0",
65
+ "eslint-plugin-prettier": "^4.2.1",
65
66
  "eslint-plugin-tsdoc": "^0.2.16",
66
- "happy-dom": "^4.0.1",
67
+ "happy-dom": "^6.0.4",
67
68
  "next": "^12.1.4",
68
69
  "nyc": "^15.1.0",
69
- "prettier": "^2.6.2",
70
- "prettier-plugin-jsdoc": "^0.3.38",
70
+ "prettier": "^2.7.1",
71
+ "prettier-plugin-jsdoc": "^0.4.2",
71
72
  "react": "^18.1.0",
72
- "react-test-renderer": "^18.1.0",
73
- "siroc": "^0.16.0",
74
- "size-limit": "^7.0.8",
73
+ "react-test-renderer": "^18.2.0",
74
+ "size-limit": "^8.1.0",
75
75
  "standard-version": "^9.5.0",
76
- "typescript": "^4.7.2",
77
- "vitest": "^0.12.9"
76
+ "typescript": "^4.8.3",
77
+ "unbuild": "^0.8.10",
78
+ "vitest": "^0.23.1"
78
79
  },
79
80
  "peerDependencies": {
80
81
  "@prismicio/client": "^6.0.0",
@@ -75,7 +75,8 @@ export type PrismicNextImageProps = Omit<
75
75
  *
76
76
  * @param props - Props for the component.
77
77
  *
78
- * @returns A responsive image component using `next/image` for the given Image field.
78
+ * @returns A responsive image component using `next/image` for the given Image
79
+ * field.
79
80
  *
80
81
  * @see To learn more about `next/image`, see: https://nextjs.org/docs/api-reference/next/image
81
82
  */
@@ -1,9 +1,8 @@
1
1
  import * as React from "react";
2
- import * as prismic from "@prismicio/client";
3
2
  import { PrismicToolbar } from "@prismicio/react";
4
3
  import { useRouter } from "next/router";
5
4
 
6
- import { getCookie } from "./lib/getCookie";
5
+ import { getPrismicPreviewCookie } from "./lib/getPrismicPreviewCookie";
7
6
  import { getPreviewCookieRepositoryName } from "./lib/getPreviewCookieRepositoryName";
8
7
 
9
8
  /**
@@ -109,8 +108,7 @@ export function PrismicPreview({
109
108
  );
110
109
  window.addEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
111
110
  } else {
112
- const prismicPreviewCookie = getCookie(
113
- prismic.cookie.preview,
111
+ const prismicPreviewCookie = getPrismicPreviewCookie(
114
112
  globalThis.document.cookie,
115
113
  );
116
114
 
@@ -122,10 +120,12 @@ export function PrismicPreview({
122
120
  // Prismic preview share link.
123
121
 
124
122
  /**
125
- * Determines if the current location is a descendant of the app's base path.
123
+ * Determines if the current location is a descendant of the app's base
124
+ * path.
126
125
  *
127
126
  * This is used to prevent infinite refrehes; when
128
- * `isDescendantOfBasePath` is `false`, `router.isPreview` is also `false`.
127
+ * `isDescendantOfBasePath` is `false`, `router.isPreview` is also
128
+ * `false`.
129
129
  *
130
130
  * If the app does not have a base path, this should always be `true`.
131
131
  */
@@ -10,7 +10,8 @@ interface PrismicNextPreviewData {
10
10
  *
11
11
  * @param previewData - The Next.js preview data object to check.
12
12
  *
13
- * @returns `true` if `previewData` contains Prismic preview data, `false` otherwise.
13
+ * @returns `true` if `previewData` contains Prismic preview data, `false`
14
+ * otherwise.
14
15
  */
15
16
  const isPrismicNextPreviewData = (
16
17
  previewData: PreviewData,
@@ -45,7 +46,8 @@ export type EnableAutoPreviewsConfig<
45
46
  /**
46
47
  * A Next.js API endpoint request object.
47
48
  *
48
- * Pass a `req` object when using `enableAutoPreviews` in a Next.js API endpoint.
49
+ * Pass a `req` object when using `enableAutoPreviews` in a Next.js API
50
+ * endpoint.
49
51
  */
50
52
  req?: HttpRequestLike;
51
53
  }
@@ -32,6 +32,7 @@ export type ExitPreviewConfig = {
32
32
  */
33
33
  res: {
34
34
  clearPreviewData: NextApiResponse["clearPreviewData"];
35
+ status: NextApiResponse["status"];
35
36
  json: NextApiResponse["json"];
36
37
  };
37
38
 
@@ -48,5 +49,7 @@ export function exitPreview(config: ExitPreviewConfig): void {
48
49
  // Exit the current user from Preview Mode.
49
50
  config.res.clearPreviewData();
50
51
 
51
- config.res.json({ success: true });
52
+ // 205 status is used to prevent CDN-level caching. The default 200
53
+ // status code is typically treated as non-changing and cacheable.
54
+ config.res.status(205).json({ success: true });
52
55
  }
@@ -1,3 +1,5 @@
1
+ import * as prismic from "@prismicio/client";
2
+
1
3
  const readValue = (value: string): string => {
2
4
  return value.replace(/%3B/g, ";");
3
5
  };
@@ -5,25 +7,27 @@ const readValue = (value: string): string => {
5
7
  /**
6
8
  * Returns the value of a cookie from a given cookie store.
7
9
  *
8
- * @param name - Name of the cookie.
9
- * @param cookieJar - The stringified cookie store from which to read the cookie.
10
+ * @param cookieJar - The stringified cookie store from which to read the
11
+ * cookie.
10
12
  *
11
13
  * @returns The value of the cookie, if it exists.
12
14
  */
13
- export const getCookie = (
14
- name: string,
15
+ export const getPrismicPreviewCookie = (
15
16
  cookieJar: string,
16
17
  ): string | undefined => {
17
18
  const cookies = cookieJar.split("; ");
18
19
 
20
+ let value: string | undefined;
21
+
19
22
  for (const cookie of cookies) {
20
23
  const parts = cookie.split("=");
21
- const thisName = readValue(parts[0]).replace(/%3D/g, "=");
24
+ const name = readValue(parts[0]).replace(/%3D/g, "=");
22
25
 
23
- if (thisName === name) {
24
- const value = parts.slice(1).join("=");
25
-
26
- return readValue(value);
26
+ if (name === prismic.cookie.preview) {
27
+ value = readValue(parts.slice(1).join("="));
28
+ continue;
27
29
  }
28
30
  }
31
+
32
+ return value;
29
33
  };
@@ -63,7 +63,8 @@ export type RedirectToPreviewURLConfig<
63
63
  linkResolver?: TLinkResolverFunction;
64
64
 
65
65
  /**
66
- * The default redirect URL if a URL cannot be determined for the previewed document.
66
+ * The default redirect URL if a URL cannot be determined for the previewed
67
+ * document.
67
68
  *
68
69
  * **Note**: If you `next.config.js` file contains a `basePath`, the
69
70
  * `defaultURL` option must _not_ include it. Instead, provide the `basePath`
package/src/types.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { PreviewData, NextApiRequest } from "next";
1
+ import type { PreviewData, NextApiRequest } from "next";
2
+ import type { ClientConfig } from "@prismicio/client";
2
3
 
3
4
  /**
4
5
  * Configuration for creating a Prismic client with automatic preview support in
@@ -19,4 +20,4 @@ export type CreateClientConfig = {
19
20
  * Pass a `req` object when using in a Next.js API endpoint.
20
21
  */
21
22
  req?: NextApiRequest;
22
- };
23
+ } & ClientConfig;
package/dist/index.cjs DELETED
@@ -1,244 +0,0 @@
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
- const Image = require('next/image');
10
- const prismicH = require('@prismicio/helpers');
11
-
12
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
13
-
14
- function _interopNamespace(e) {
15
- if (e && e.__esModule) return e;
16
- const n = Object.create(null);
17
- if (e) {
18
- for (const k in e) {
19
- if (k !== 'default') {
20
- const d = Object.getOwnPropertyDescriptor(e, k);
21
- Object.defineProperty(n, k, d.get ? d : {
22
- enumerable: true,
23
- get: function () { return e[k]; }
24
- });
25
- }
26
- }
27
- }
28
- n["default"] = e;
29
- return Object.freeze(n);
30
- }
31
-
32
- const prismic__namespace = /*#__PURE__*/_interopNamespace(prismic);
33
- const React__namespace = /*#__PURE__*/_interopNamespace(React);
34
- const Image__default = /*#__PURE__*/_interopDefaultLegacy(Image);
35
- const prismicH__namespace = /*#__PURE__*/_interopNamespace(prismicH);
36
-
37
- function setPreviewData({ req, res }) {
38
- const ref = req.query.token || req.cookies[prismic__namespace.cookie.preview];
39
- if (ref) {
40
- res.setPreviewData({ ref });
41
- }
42
- }
43
-
44
- function exitPreview(config) {
45
- config.res.clearPreviewData();
46
- config.res.json({ success: true });
47
- }
48
-
49
- const readValue = (value) => {
50
- return value.replace(/%3B/g, ";");
51
- };
52
- const getCookie = (name, cookieJar) => {
53
- const cookies = cookieJar.split("; ");
54
- for (const cookie of cookies) {
55
- const parts = cookie.split("=");
56
- const thisName = readValue(parts[0]).replace(/%3D/g, "=");
57
- if (thisName === name) {
58
- const value = parts.slice(1).join("=");
59
- return readValue(value);
60
- }
61
- }
62
- };
63
-
64
- const getPreviewCookieRepositoryName = (previewCookie) => {
65
- return (decodeURIComponent(previewCookie).match(/"(.+).prismic.io"/) || [])[1];
66
- };
67
-
68
- function PrismicPreview({
69
- repositoryName,
70
- children,
71
- updatePreviewURL = "/api/preview",
72
- exitPreviewURL = "/api/exit-preview"
73
- }) {
74
- const router$1 = router.useRouter();
75
- const resolvedUpdatePreviewURL = router$1.basePath + updatePreviewURL;
76
- const resolvedExitPreviewURL = router$1.basePath + exitPreviewURL;
77
- React__namespace.useEffect(() => {
78
- const startPreviewMode = async () => {
79
- const res = await globalThis.fetch(resolvedUpdatePreviewURL);
80
- if (res.ok) {
81
- globalThis.location.reload();
82
- } else {
83
- console.error(`[<PrismicPreview>] Failed to start or update Preview Mode using the "${resolvedUpdatePreviewURL}" API endpoint. Does it exist?`);
84
- }
85
- };
86
- const handlePrismicPreviewUpdate = async (event) => {
87
- event.preventDefault();
88
- await startPreviewMode();
89
- };
90
- const handlePrismicPreviewEnd = async (event) => {
91
- event.preventDefault();
92
- const res = await globalThis.fetch(resolvedExitPreviewURL);
93
- if (res.ok) {
94
- globalThis.location.reload();
95
- } else {
96
- console.error(`[<PrismicPreview>] Failed to exit Preview Mode using the "${resolvedExitPreviewURL}" API endpoint. Does it exist?`);
97
- }
98
- };
99
- if (router$1.isPreview) {
100
- window.addEventListener("prismicPreviewUpdate", handlePrismicPreviewUpdate);
101
- window.addEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
102
- } else {
103
- const prismicPreviewCookie = getCookie(prismic__namespace.cookie.preview, globalThis.document.cookie);
104
- if (prismicPreviewCookie) {
105
- const locationIsDescendantOfBasePath = window.location.href.startsWith(window.location.origin + router$1.basePath);
106
- const prismicPreviewCookieRepositoryName = getPreviewCookieRepositoryName(prismicPreviewCookie);
107
- if (locationIsDescendantOfBasePath && prismicPreviewCookieRepositoryName === repositoryName) {
108
- startPreviewMode();
109
- }
110
- }
111
- }
112
- return () => {
113
- window.removeEventListener("prismicPreviewUpdate", handlePrismicPreviewUpdate);
114
- window.removeEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
115
- };
116
- }, [
117
- repositoryName,
118
- resolvedExitPreviewURL,
119
- resolvedUpdatePreviewURL,
120
- router$1.isPreview,
121
- router$1.basePath
122
- ]);
123
- return /* @__PURE__ */ React__namespace.createElement(React__namespace.Fragment, null, children, /* @__PURE__ */ React__namespace.createElement(react.PrismicToolbar, {
124
- repositoryName
125
- }));
126
- }
127
-
128
- const isPrismicNextPreviewData = (previewData) => {
129
- return typeof previewData === "object" && "ref" in previewData;
130
- };
131
- const enableAutoPreviews = (config) => {
132
- if ("previewData" in config && config.previewData) {
133
- const { previewData } = config;
134
- if (isPrismicNextPreviewData(previewData) && previewData.ref) {
135
- config.client.queryContentFromRef(previewData.ref);
136
- }
137
- } else if ("req" in config && config.req) {
138
- config.client.enableAutoPreviewsFromReq(config.req);
139
- }
140
- };
141
-
142
- const isPrismicNextQuery = (query) => {
143
- return typeof query.documentId === "string" && typeof query.token === "string";
144
- };
145
- async function redirectToPreviewURL(config) {
146
- const defaultURL = config.defaultURL || "/";
147
- const basePath = config.basePath || "";
148
- if (isPrismicNextQuery(config.req.query)) {
149
- const previewUrl = await config.client.resolvePreviewURL({
150
- linkResolver: config.linkResolver,
151
- defaultURL,
152
- documentID: config.req.query.documentId,
153
- previewToken: config.req.query.token
154
- });
155
- config.res.redirect(basePath + previewUrl);
156
- return;
157
- }
158
- config.res.redirect(basePath + defaultURL);
159
- }
160
-
161
- const camelCaseToParamCase = (input) => {
162
- return input.replace(/[A-Z]/g, (match) => {
163
- return `-${match.toLowerCase()}`;
164
- });
165
- };
166
- const buildURL = (url, params) => {
167
- const instance = new URL(url);
168
- for (const camelCasedParamKey in params) {
169
- const paramKey = camelCaseToParamCase(camelCasedParamKey);
170
- const paramValue = params[camelCasedParamKey];
171
- if (paramValue === void 0) {
172
- instance.searchParams.delete(paramKey);
173
- } else if (Array.isArray(paramValue)) {
174
- instance.searchParams.set(paramKey, paramValue.join(","));
175
- } else {
176
- instance.searchParams.set(paramKey, `${paramValue}`);
177
- }
178
- }
179
- const s = instance.searchParams.get("s");
180
- if (s) {
181
- instance.searchParams.delete("s");
182
- instance.searchParams.append("s", s);
183
- }
184
- return instance.toString();
185
- };
186
-
187
- const __PRODUCTION__ = process.env.NODE_ENV === "production";
188
-
189
- var version = "0.1.3";
190
-
191
- const devMsg = (slug) => {
192
- return `https://prismic.dev/msg/next/v${version}/${slug}`;
193
- };
194
-
195
- const imgixLoader = (args) => {
196
- const url = new URL(args.src);
197
- const params = {
198
- fit: url.searchParams.get("fit") || "max",
199
- w: args.width,
200
- h: void 0
201
- };
202
- if (args.quality) {
203
- params.q = args.quality;
204
- }
205
- return buildURL(args.src, params);
206
- };
207
- const PrismicNextImage = ({
208
- field,
209
- imgixParams = {},
210
- alt,
211
- fallbackAlt,
212
- layout,
213
- ...restProps
214
- }) => {
215
- if (!__PRODUCTION__) {
216
- if (typeof alt === "string" && alt !== "") {
217
- console.warn(`[PrismicNextImage] The "alt" prop can only be used to declare an image as decorative by passing an empty string (alt="") but was provided a non-empty string. You can resolve this warning by removing the "alt" prop or changing it to alt="". For more details, see ${devMsg("alt-must-be-an-empty-string")}`);
218
- }
219
- if (typeof fallbackAlt === "string" && fallbackAlt !== "") {
220
- console.warn(`[PrismicNextImage] The "fallbackAlt" prop can only be used to declare an image as decorative by passing an empty string (fallbackAlt="") but was provided a non-empty string. You can resolve this warning by removing the "fallbackAlt" prop or changing it to fallbackAlt="". For more details, see ${devMsg("alt-must-be-an-empty-string")}`);
221
- }
222
- }
223
- if (prismicH__namespace.isFilled.imageThumbnail(field)) {
224
- const src = buildURL(field.url, imgixParams);
225
- return /* @__PURE__ */ React__namespace.createElement(Image__default["default"], {
226
- src,
227
- width: layout === "fill" ? void 0 : field.dimensions.width,
228
- height: layout === "fill" ? void 0 : field.dimensions.height,
229
- alt: alt != null ? alt : field.alt || fallbackAlt,
230
- loader: imgixLoader,
231
- layout,
232
- ...restProps
233
- });
234
- } else {
235
- return null;
236
- }
237
- };
238
-
239
- exports.PrismicNextImage = PrismicNextImage;
240
- exports.PrismicPreview = PrismicPreview;
241
- exports.enableAutoPreviews = enableAutoPreviews;
242
- exports.exitPreview = exitPreview;
243
- exports.redirectToPreviewURL = redirectToPreviewURL;
244
- exports.setPreviewData = setPreviewData;
package/dist/index.js DELETED
@@ -1,210 +0,0 @@
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
- import Image from 'next/image';
6
- import * as prismicH from '@prismicio/helpers';
7
-
8
- function setPreviewData({ req, res }) {
9
- const ref = req.query.token || req.cookies[prismic.cookie.preview];
10
- if (ref) {
11
- res.setPreviewData({ ref });
12
- }
13
- }
14
-
15
- function exitPreview(config) {
16
- config.res.clearPreviewData();
17
- config.res.json({ success: true });
18
- }
19
-
20
- const readValue = (value) => {
21
- return value.replace(/%3B/g, ";");
22
- };
23
- const getCookie = (name, cookieJar) => {
24
- const cookies = cookieJar.split("; ");
25
- for (const cookie of cookies) {
26
- const parts = cookie.split("=");
27
- const thisName = readValue(parts[0]).replace(/%3D/g, "=");
28
- if (thisName === name) {
29
- const value = parts.slice(1).join("=");
30
- return readValue(value);
31
- }
32
- }
33
- };
34
-
35
- const getPreviewCookieRepositoryName = (previewCookie) => {
36
- return (decodeURIComponent(previewCookie).match(/"(.+).prismic.io"/) || [])[1];
37
- };
38
-
39
- function PrismicPreview({
40
- repositoryName,
41
- children,
42
- updatePreviewURL = "/api/preview",
43
- exitPreviewURL = "/api/exit-preview"
44
- }) {
45
- const router = useRouter();
46
- const resolvedUpdatePreviewURL = router.basePath + updatePreviewURL;
47
- const resolvedExitPreviewURL = router.basePath + exitPreviewURL;
48
- React.useEffect(() => {
49
- const startPreviewMode = async () => {
50
- const res = await globalThis.fetch(resolvedUpdatePreviewURL);
51
- if (res.ok) {
52
- globalThis.location.reload();
53
- } else {
54
- console.error(`[<PrismicPreview>] Failed to start or update Preview Mode using the "${resolvedUpdatePreviewURL}" API endpoint. Does it exist?`);
55
- }
56
- };
57
- const handlePrismicPreviewUpdate = async (event) => {
58
- event.preventDefault();
59
- await startPreviewMode();
60
- };
61
- const handlePrismicPreviewEnd = async (event) => {
62
- event.preventDefault();
63
- const res = await globalThis.fetch(resolvedExitPreviewURL);
64
- if (res.ok) {
65
- globalThis.location.reload();
66
- } else {
67
- console.error(`[<PrismicPreview>] Failed to exit Preview Mode using the "${resolvedExitPreviewURL}" API endpoint. Does it exist?`);
68
- }
69
- };
70
- if (router.isPreview) {
71
- window.addEventListener("prismicPreviewUpdate", handlePrismicPreviewUpdate);
72
- window.addEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
73
- } else {
74
- const prismicPreviewCookie = getCookie(prismic.cookie.preview, globalThis.document.cookie);
75
- if (prismicPreviewCookie) {
76
- const locationIsDescendantOfBasePath = window.location.href.startsWith(window.location.origin + router.basePath);
77
- const prismicPreviewCookieRepositoryName = getPreviewCookieRepositoryName(prismicPreviewCookie);
78
- if (locationIsDescendantOfBasePath && prismicPreviewCookieRepositoryName === repositoryName) {
79
- startPreviewMode();
80
- }
81
- }
82
- }
83
- return () => {
84
- window.removeEventListener("prismicPreviewUpdate", handlePrismicPreviewUpdate);
85
- window.removeEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
86
- };
87
- }, [
88
- repositoryName,
89
- resolvedExitPreviewURL,
90
- resolvedUpdatePreviewURL,
91
- router.isPreview,
92
- router.basePath
93
- ]);
94
- return /* @__PURE__ */ React.createElement(React.Fragment, null, children, /* @__PURE__ */ React.createElement(PrismicToolbar, {
95
- repositoryName
96
- }));
97
- }
98
-
99
- const isPrismicNextPreviewData = (previewData) => {
100
- return typeof previewData === "object" && "ref" in previewData;
101
- };
102
- const enableAutoPreviews = (config) => {
103
- if ("previewData" in config && config.previewData) {
104
- const { previewData } = config;
105
- if (isPrismicNextPreviewData(previewData) && previewData.ref) {
106
- config.client.queryContentFromRef(previewData.ref);
107
- }
108
- } else if ("req" in config && config.req) {
109
- config.client.enableAutoPreviewsFromReq(config.req);
110
- }
111
- };
112
-
113
- const isPrismicNextQuery = (query) => {
114
- return typeof query.documentId === "string" && typeof query.token === "string";
115
- };
116
- async function redirectToPreviewURL(config) {
117
- const defaultURL = config.defaultURL || "/";
118
- const basePath = config.basePath || "";
119
- if (isPrismicNextQuery(config.req.query)) {
120
- const previewUrl = await config.client.resolvePreviewURL({
121
- linkResolver: config.linkResolver,
122
- defaultURL,
123
- documentID: config.req.query.documentId,
124
- previewToken: config.req.query.token
125
- });
126
- config.res.redirect(basePath + previewUrl);
127
- return;
128
- }
129
- config.res.redirect(basePath + defaultURL);
130
- }
131
-
132
- const camelCaseToParamCase = (input) => {
133
- return input.replace(/[A-Z]/g, (match) => {
134
- return `-${match.toLowerCase()}`;
135
- });
136
- };
137
- const buildURL = (url, params) => {
138
- const instance = new URL(url);
139
- for (const camelCasedParamKey in params) {
140
- const paramKey = camelCaseToParamCase(camelCasedParamKey);
141
- const paramValue = params[camelCasedParamKey];
142
- if (paramValue === void 0) {
143
- instance.searchParams.delete(paramKey);
144
- } else if (Array.isArray(paramValue)) {
145
- instance.searchParams.set(paramKey, paramValue.join(","));
146
- } else {
147
- instance.searchParams.set(paramKey, `${paramValue}`);
148
- }
149
- }
150
- const s = instance.searchParams.get("s");
151
- if (s) {
152
- instance.searchParams.delete("s");
153
- instance.searchParams.append("s", s);
154
- }
155
- return instance.toString();
156
- };
157
-
158
- const __PRODUCTION__ = process.env.NODE_ENV === "production";
159
-
160
- var version = "0.1.3";
161
-
162
- const devMsg = (slug) => {
163
- return `https://prismic.dev/msg/next/v${version}/${slug}`;
164
- };
165
-
166
- const imgixLoader = (args) => {
167
- const url = new URL(args.src);
168
- const params = {
169
- fit: url.searchParams.get("fit") || "max",
170
- w: args.width,
171
- h: void 0
172
- };
173
- if (args.quality) {
174
- params.q = args.quality;
175
- }
176
- return buildURL(args.src, params);
177
- };
178
- const PrismicNextImage = ({
179
- field,
180
- imgixParams = {},
181
- alt,
182
- fallbackAlt,
183
- layout,
184
- ...restProps
185
- }) => {
186
- if (!__PRODUCTION__) {
187
- if (typeof alt === "string" && alt !== "") {
188
- console.warn(`[PrismicNextImage] The "alt" prop can only be used to declare an image as decorative by passing an empty string (alt="") but was provided a non-empty string. You can resolve this warning by removing the "alt" prop or changing it to alt="". For more details, see ${devMsg("alt-must-be-an-empty-string")}`);
189
- }
190
- if (typeof fallbackAlt === "string" && fallbackAlt !== "") {
191
- console.warn(`[PrismicNextImage] The "fallbackAlt" prop can only be used to declare an image as decorative by passing an empty string (fallbackAlt="") but was provided a non-empty string. You can resolve this warning by removing the "fallbackAlt" prop or changing it to fallbackAlt="". For more details, see ${devMsg("alt-must-be-an-empty-string")}`);
192
- }
193
- }
194
- if (prismicH.isFilled.imageThumbnail(field)) {
195
- const src = buildURL(field.url, imgixParams);
196
- return /* @__PURE__ */ React.createElement(Image, {
197
- src,
198
- width: layout === "fill" ? void 0 : field.dimensions.width,
199
- height: layout === "fill" ? void 0 : field.dimensions.height,
200
- alt: alt != null ? alt : field.alt || fallbackAlt,
201
- loader: imgixLoader,
202
- layout,
203
- ...restProps
204
- });
205
- } else {
206
- return null;
207
- }
208
- };
209
-
210
- export { PrismicNextImage, PrismicPreview, enableAutoPreviews, exitPreview, redirectToPreviewURL, setPreviewData };