@prismicio/next 1.1.0 → 1.2.1

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 (44) hide show
  1. package/bin/prismic-next.js +3 -0
  2. package/dist/PrismicNextImage.cjs +6 -15
  3. package/dist/PrismicNextImage.cjs.map +1 -1
  4. package/dist/PrismicNextImage.d.ts +1 -1
  5. package/dist/PrismicNextImage.js +6 -15
  6. package/dist/PrismicNextImage.js.map +1 -1
  7. package/dist/PrismicNextLink.d.ts +4 -4
  8. package/dist/PrismicPreview.d.ts +1 -1
  9. package/dist/PrismicPreviewClient.d.ts +1 -1
  10. package/dist/_node_modules/@prismicio/client/dist/helpers/asLink.cjs +12 -3
  11. package/dist/_node_modules/@prismicio/client/dist/helpers/asLink.cjs.map +1 -1
  12. package/dist/_node_modules/@prismicio/client/dist/helpers/asLink.js +12 -3
  13. package/dist/_node_modules/@prismicio/client/dist/helpers/asLink.js.map +1 -1
  14. package/dist/_node_modules/@prismicio/client/dist/helpers/isFilled.cjs.map +1 -1
  15. package/dist/_node_modules/@prismicio/client/dist/helpers/isFilled.js.map +1 -1
  16. package/dist/cli/index.d.ts +1 -0
  17. package/dist/cli.cjs +123 -0
  18. package/dist/cli.cjs.map +1 -0
  19. package/dist/cli.js +104 -0
  20. package/dist/cli.js.map +1 -0
  21. package/dist/enableAutoPreviews.cjs +4 -1
  22. package/dist/enableAutoPreviews.cjs.map +1 -1
  23. package/dist/enableAutoPreviews.d.ts +1 -1
  24. package/dist/enableAutoPreviews.js +4 -1
  25. package/dist/enableAutoPreviews.js.map +1 -1
  26. package/dist/exitPreview.d.ts +1 -1
  27. package/dist/index.d.ts +1 -1
  28. package/dist/package.json.cjs +1 -1
  29. package/dist/package.json.js +1 -1
  30. package/dist/redirectToPreviewURL.d.ts +1 -1
  31. package/dist/setPreviewData.d.ts +1 -1
  32. package/dist/types.d.ts +10 -4
  33. package/package.json +16 -5
  34. package/src/PrismicNextImage.tsx +17 -7
  35. package/src/cli/index.ts +168 -0
  36. package/src/enableAutoPreviews.ts +6 -6
  37. package/src/index.ts +1 -1
  38. package/src/types.ts +7 -0
  39. package/dist/lib/__PRODUCTION__.cjs +0 -5
  40. package/dist/lib/__PRODUCTION__.cjs.map +0 -1
  41. package/dist/lib/__PRODUCTION__.d.ts +0 -7
  42. package/dist/lib/__PRODUCTION__.js +0 -5
  43. package/dist/lib/__PRODUCTION__.js.map +0 -1
  44. package/src/lib/__PRODUCTION__.ts +0 -7
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+
3
+ import("../dist/cli.cjs").then((mod) => mod.run(process.argv));
@@ -5,7 +5,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
5
5
  const jsxRuntime = require("react/jsx-runtime");
6
6
  const Image = require("next/image");
7
7
  const imgixUrlBuilder = require("imgix-url-builder");
8
- const __PRODUCTION__ = require("./lib/__PRODUCTION__.cjs");
9
8
  const devMsg = require("./lib/devMsg.cjs");
10
9
  const imgixLoader = require("./imgixLoader.cjs");
11
10
  const isFilled = require('./_node_modules/@prismicio/client/dist/helpers/isFilled.cjs');
@@ -22,7 +21,7 @@ const castInt = (input) => {
22
21
  }
23
22
  };
24
23
  const PrismicNextImage = ({ field, imgixParams = {}, alt, fallbackAlt, fill, width, height, fallback = null, ...restProps }) => {
25
- if (!__PRODUCTION__.__PRODUCTION__) {
24
+ if (process.env.NODE_ENV !== "production") {
26
25
  if (typeof alt === "string" && alt !== "") {
27
26
  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.devMsg("alt-must-be-an-empty-string")}`);
28
27
  }
@@ -42,19 +41,11 @@ const PrismicNextImage = ({ field, imgixParams = {}, alt, fallbackAlt, fill, wid
42
41
  } else if (castedWidth == null && castedHeight != null) {
43
42
  resolvedWidth = castedHeight * ar;
44
43
  }
45
- return jsxRuntime.jsx(Image, {
46
- src,
47
- width: fill ? void 0 : resolvedWidth,
48
- height: fill ? void 0 : resolvedHeight,
49
- // A non-null assertion is required since we
50
- // can't statically know if an alt attribute is
51
- // available.
52
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
53
- alt: alt ?? (field.alt || fallbackAlt),
54
- fill,
55
- loader: imgixLoader.imgixLoader,
56
- ...restProps
57
- });
44
+ const resolvedAlt = alt ?? (field.alt || fallbackAlt);
45
+ if (process.env.NODE_ENV !== "production" && typeof resolvedAlt !== "string") {
46
+ console.error(`[PrismicNextImage] The following image is missing an "alt" property. Please add Alternative Text to the image in Prismic. To mark the image as decorative instead, add one of \`alt=""\` or \`fallbackAlt=""\`.`, src);
47
+ }
48
+ return jsxRuntime.jsx(Image, { src, width: fill ? void 0 : resolvedWidth, height: fill ? void 0 : resolvedHeight, alt: resolvedAlt, fill, loader: imgixLoader.imgixLoader, ...restProps });
58
49
  } else {
59
50
  return jsxRuntime.jsx(jsxRuntime.Fragment, { children: fallback });
60
51
  }
@@ -1 +1 @@
1
- {"version":3,"file":"PrismicNextImage.cjs","sources":["../../src/PrismicNextImage.tsx"],"sourcesContent":["\"use client\";\n\nimport Image, { ImageProps } from \"next/image\";\nimport { buildURL, ImgixURLParams } from \"imgix-url-builder\";\nimport * as prismic from \"@prismicio/client\";\n\nimport { __PRODUCTION__ } from \"./lib/__PRODUCTION__\";\nimport { devMsg } from \"./lib/devMsg\";\n\nimport { imgixLoader } from \"./imgixLoader\";\n\nconst castInt = (input: string | number | undefined): number | undefined => {\n\tif (typeof input === \"number\" || typeof input === \"undefined\") {\n\t\treturn input;\n\t} else {\n\t\tconst parsed = Number.parseInt(input);\n\n\t\tif (Number.isNaN(parsed)) {\n\t\t\treturn undefined;\n\t\t} else {\n\t\t\treturn parsed;\n\t\t}\n\t}\n};\n\nexport type PrismicNextImageProps = Omit<ImageProps, \"src\" | \"alt\"> & {\n\t/**\n\t * The Prismic Image field or thumbnail to render.\n\t */\n\tfield: prismic.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\t/**\n\t * Rendered when the field is empty. If a fallback is not given, `null` will\n\t * be rendered.\n\t */\n\tfallback?: React.ReactNode;\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 * @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\tfill,\n\twidth,\n\theight,\n\tfallback = null,\n\t...restProps\n}: PrismicNextImageProps): JSX.Element => {\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 (prismic.isFilled.imageThumbnail(field)) {\n\t\tconst src = buildURL(field.url, imgixParams);\n\n\t\tconst ar = field.dimensions.width / field.dimensions.height;\n\n\t\tconst castedWidth = castInt(width);\n\t\tconst castedHeight = castInt(height);\n\n\t\tlet resolvedWidth = castedWidth ?? field.dimensions.width;\n\t\tlet resolvedHeight = castedHeight ?? field.dimensions.height;\n\n\t\tif (castedWidth != null && castedHeight == null) {\n\t\t\tresolvedHeight = castedWidth / ar;\n\t\t} else if (castedWidth == null && castedHeight != null) {\n\t\t\tresolvedWidth = castedHeight * ar;\n\t\t}\n\n\t\treturn (\n\t\t\t<Image\n\t\t\t\tsrc={src}\n\t\t\t\twidth={fill ? undefined : resolvedWidth}\n\t\t\t\theight={fill ? undefined : resolvedHeight}\n\t\t\t\t// A non-null assertion is required since we\n\t\t\t\t// can't statically know if an alt attribute is\n\t\t\t\t// available.\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n\t\t\t\talt={(alt ?? (field.alt || fallbackAlt))!}\n\t\t\t\tfill={fill}\n\t\t\t\tloader={imgixLoader}\n\t\t\t\t{...restProps}\n\t\t\t/>\n\t\t);\n\t} else {\n\t\treturn <>{fallback}</>;\n\t}\n};\n"],"names":[],"mappings":";;;;;;;;;;;AAWA;AACC;AACQ;AAAA;AAED;AAEF;AACI;AAAA;AAEA;AAAA;AACP;AAEH;AAsDO;AAWN;AACC;AACC;AAGI;AAIL;AACC;AAGI;AAEJ;AAGF;AACC;AAEA;AAEM;AACA;AAEF;AACA;AAEA;AACH;AAA+B;AAE/B;AAA+B;AAGhC;AACO;AACL;AAC0B;AACC;AAAA;AAAA;AAAA;AAAA;AAKA;AAC3B;AACQ;AACJ;AACH;AAGH;AAAkB;AAEpB;;"}
1
+ {"version":3,"file":"PrismicNextImage.cjs","sources":["../../src/PrismicNextImage.tsx"],"sourcesContent":["\"use client\";\n\nimport Image, { ImageProps } from \"next/image\";\nimport { buildURL, ImgixURLParams } from \"imgix-url-builder\";\nimport * as prismic from \"@prismicio/client\";\n\nimport { devMsg } from \"./lib/devMsg\";\n\nimport { imgixLoader } from \"./imgixLoader\";\n\nconst castInt = (input: string | number | undefined): number | undefined => {\n\tif (typeof input === \"number\" || typeof input === \"undefined\") {\n\t\treturn input;\n\t} else {\n\t\tconst parsed = Number.parseInt(input);\n\n\t\tif (Number.isNaN(parsed)) {\n\t\t\treturn undefined;\n\t\t} else {\n\t\t\treturn parsed;\n\t\t}\n\t}\n};\n\nexport type PrismicNextImageProps = Omit<ImageProps, \"src\" | \"alt\"> & {\n\t/**\n\t * The Prismic Image field or thumbnail to render.\n\t */\n\tfield: prismic.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\t/**\n\t * Rendered when the field is empty. If a fallback is not given, `null` will\n\t * be rendered.\n\t */\n\tfallback?: React.ReactNode;\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 * @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\tfill,\n\twidth,\n\theight,\n\tfallback = null,\n\t...restProps\n}: PrismicNextImageProps): JSX.Element => {\n\tif (process.env.NODE_ENV !== \"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 (prismic.isFilled.imageThumbnail(field)) {\n\t\tconst src = buildURL(field.url, imgixParams);\n\n\t\tconst ar = field.dimensions.width / field.dimensions.height;\n\n\t\tconst castedWidth = castInt(width);\n\t\tconst castedHeight = castInt(height);\n\n\t\tlet resolvedWidth = castedWidth ?? field.dimensions.width;\n\t\tlet resolvedHeight = castedHeight ?? field.dimensions.height;\n\n\t\tif (castedWidth != null && castedHeight == null) {\n\t\t\tresolvedHeight = castedWidth / ar;\n\t\t} else if (castedWidth == null && castedHeight != null) {\n\t\t\tresolvedWidth = castedHeight * ar;\n\t\t}\n\n\t\t// A non-null assertion is required since we can't statically\n\t\t// know if an alt attribute is available.\n\t\t// eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n\t\tconst resolvedAlt = (alt ?? (field.alt || fallbackAlt))!;\n\n\t\tif (\n\t\t\tprocess.env.NODE_ENV !== \"production\" &&\n\t\t\ttypeof resolvedAlt !== \"string\"\n\t\t) {\n\t\t\tconsole.error(\n\t\t\t\t`[PrismicNextImage] The following image is missing an \"alt\" property. Please add Alternative Text to the image in Prismic. To mark the image as decorative instead, add one of \\`alt=\"\"\\` or \\`fallbackAlt=\"\"\\`.`,\n\t\t\t\tsrc,\n\t\t\t);\n\t\t}\n\n\t\treturn (\n\t\t\t<Image\n\t\t\t\tsrc={src}\n\t\t\t\twidth={fill ? undefined : resolvedWidth}\n\t\t\t\theight={fill ? undefined : resolvedHeight}\n\t\t\t\talt={resolvedAlt}\n\t\t\t\tfill={fill}\n\t\t\t\tloader={imgixLoader}\n\t\t\t\t{...restProps}\n\t\t\t/>\n\t\t);\n\t} else {\n\t\treturn <>{fallback}</>;\n\t}\n};\n"],"names":[],"mappings":";;;;;;;;;;AAUA;AACC;AACQ;AAAA;AAED;AAEF;AACI;AAAA;AAEA;AAAA;AACP;AAEH;AAsDO;AAWF;AACH;AACC;AAGI;AAIL;AACC;AAGI;AAEJ;AAGF;AACC;AAEA;AAEM;AACA;AAEF;AACA;AAEA;AACH;AAA+B;AAE/B;AAA+B;AAM1B;AAEN;AAIS;AAEJ;AAIL;AASG;AAGH;AAAkB;AAEpB;;"}
@@ -2,7 +2,7 @@
2
2
  import { ImageProps } from "next/image";
3
3
  import { ImgixURLParams } from "imgix-url-builder";
4
4
  import * as prismic from "@prismicio/client";
5
- export type PrismicNextImageProps = Omit<ImageProps, "src" | "alt"> & {
5
+ export declare type PrismicNextImageProps = Omit<ImageProps, "src" | "alt"> & {
6
6
  /**
7
7
  * The Prismic Image field or thumbnail to render.
8
8
  */
@@ -3,7 +3,6 @@
3
3
  import { jsx, Fragment } from "react/jsx-runtime";
4
4
  import Image from "next/image";
5
5
  import { buildURL } from "imgix-url-builder";
6
- import { __PRODUCTION__ } from "./lib/__PRODUCTION__.js";
7
6
  import { devMsg } from "./lib/devMsg.js";
8
7
  import { imgixLoader } from "./imgixLoader.js";
9
8
  import { imageThumbnail } from './_node_modules/@prismicio/client/dist/helpers/isFilled.js';
@@ -20,7 +19,7 @@ const castInt = (input) => {
20
19
  }
21
20
  };
22
21
  const PrismicNextImage = ({ field, imgixParams = {}, alt, fallbackAlt, fill, width, height, fallback = null, ...restProps }) => {
23
- if (!__PRODUCTION__) {
22
+ if (process.env.NODE_ENV !== "production") {
24
23
  if (typeof alt === "string" && alt !== "") {
25
24
  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")}`);
26
25
  }
@@ -40,19 +39,11 @@ const PrismicNextImage = ({ field, imgixParams = {}, alt, fallbackAlt, fill, wid
40
39
  } else if (castedWidth == null && castedHeight != null) {
41
40
  resolvedWidth = castedHeight * ar;
42
41
  }
43
- return jsx(Image, {
44
- src,
45
- width: fill ? void 0 : resolvedWidth,
46
- height: fill ? void 0 : resolvedHeight,
47
- // A non-null assertion is required since we
48
- // can't statically know if an alt attribute is
49
- // available.
50
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
51
- alt: alt ?? (field.alt || fallbackAlt),
52
- fill,
53
- loader: imgixLoader,
54
- ...restProps
55
- });
42
+ const resolvedAlt = alt ?? (field.alt || fallbackAlt);
43
+ if (process.env.NODE_ENV !== "production" && typeof resolvedAlt !== "string") {
44
+ console.error(`[PrismicNextImage] The following image is missing an "alt" property. Please add Alternative Text to the image in Prismic. To mark the image as decorative instead, add one of \`alt=""\` or \`fallbackAlt=""\`.`, src);
45
+ }
46
+ return jsx(Image, { src, width: fill ? void 0 : resolvedWidth, height: fill ? void 0 : resolvedHeight, alt: resolvedAlt, fill, loader: imgixLoader, ...restProps });
56
47
  } else {
57
48
  return jsx(Fragment, { children: fallback });
58
49
  }
@@ -1 +1 @@
1
- {"version":3,"file":"PrismicNextImage.js","sources":["../../src/PrismicNextImage.tsx"],"sourcesContent":["\"use client\";\n\nimport Image, { ImageProps } from \"next/image\";\nimport { buildURL, ImgixURLParams } from \"imgix-url-builder\";\nimport * as prismic from \"@prismicio/client\";\n\nimport { __PRODUCTION__ } from \"./lib/__PRODUCTION__\";\nimport { devMsg } from \"./lib/devMsg\";\n\nimport { imgixLoader } from \"./imgixLoader\";\n\nconst castInt = (input: string | number | undefined): number | undefined => {\n\tif (typeof input === \"number\" || typeof input === \"undefined\") {\n\t\treturn input;\n\t} else {\n\t\tconst parsed = Number.parseInt(input);\n\n\t\tif (Number.isNaN(parsed)) {\n\t\t\treturn undefined;\n\t\t} else {\n\t\t\treturn parsed;\n\t\t}\n\t}\n};\n\nexport type PrismicNextImageProps = Omit<ImageProps, \"src\" | \"alt\"> & {\n\t/**\n\t * The Prismic Image field or thumbnail to render.\n\t */\n\tfield: prismic.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\t/**\n\t * Rendered when the field is empty. If a fallback is not given, `null` will\n\t * be rendered.\n\t */\n\tfallback?: React.ReactNode;\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 * @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\tfill,\n\twidth,\n\theight,\n\tfallback = null,\n\t...restProps\n}: PrismicNextImageProps): JSX.Element => {\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 (prismic.isFilled.imageThumbnail(field)) {\n\t\tconst src = buildURL(field.url, imgixParams);\n\n\t\tconst ar = field.dimensions.width / field.dimensions.height;\n\n\t\tconst castedWidth = castInt(width);\n\t\tconst castedHeight = castInt(height);\n\n\t\tlet resolvedWidth = castedWidth ?? field.dimensions.width;\n\t\tlet resolvedHeight = castedHeight ?? field.dimensions.height;\n\n\t\tif (castedWidth != null && castedHeight == null) {\n\t\t\tresolvedHeight = castedWidth / ar;\n\t\t} else if (castedWidth == null && castedHeight != null) {\n\t\t\tresolvedWidth = castedHeight * ar;\n\t\t}\n\n\t\treturn (\n\t\t\t<Image\n\t\t\t\tsrc={src}\n\t\t\t\twidth={fill ? undefined : resolvedWidth}\n\t\t\t\theight={fill ? undefined : resolvedHeight}\n\t\t\t\t// A non-null assertion is required since we\n\t\t\t\t// can't statically know if an alt attribute is\n\t\t\t\t// available.\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n\t\t\t\talt={(alt ?? (field.alt || fallbackAlt))!}\n\t\t\t\tfill={fill}\n\t\t\t\tloader={imgixLoader}\n\t\t\t\t{...restProps}\n\t\t\t/>\n\t\t);\n\t} else {\n\t\treturn <>{fallback}</>;\n\t}\n};\n"],"names":[],"mappings":";;;;;;;;;AAWA;AACC;AACQ;AAAA;AAED;AAEF;AACI;AAAA;AAEA;AAAA;AACP;AAEH;AAsDO;AAWN;AACC;AACC;AAGI;AAIL;AACC;AAGI;AAEJ;AAGF;AACC;AAEA;AAEM;AACA;AAEF;AACA;AAEA;AACH;AAA+B;AAE/B;AAA+B;AAGhC;AACO;AACL;AAC0B;AACC;AAAA;AAAA;AAAA;AAAA;AAKA;AAC3B;AACQ;AACJ;AACH;AAGH;AAAkB;AAEpB;;;;"}
1
+ {"version":3,"file":"PrismicNextImage.js","sources":["../../src/PrismicNextImage.tsx"],"sourcesContent":["\"use client\";\n\nimport Image, { ImageProps } from \"next/image\";\nimport { buildURL, ImgixURLParams } from \"imgix-url-builder\";\nimport * as prismic from \"@prismicio/client\";\n\nimport { devMsg } from \"./lib/devMsg\";\n\nimport { imgixLoader } from \"./imgixLoader\";\n\nconst castInt = (input: string | number | undefined): number | undefined => {\n\tif (typeof input === \"number\" || typeof input === \"undefined\") {\n\t\treturn input;\n\t} else {\n\t\tconst parsed = Number.parseInt(input);\n\n\t\tif (Number.isNaN(parsed)) {\n\t\t\treturn undefined;\n\t\t} else {\n\t\t\treturn parsed;\n\t\t}\n\t}\n};\n\nexport type PrismicNextImageProps = Omit<ImageProps, \"src\" | \"alt\"> & {\n\t/**\n\t * The Prismic Image field or thumbnail to render.\n\t */\n\tfield: prismic.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\t/**\n\t * Rendered when the field is empty. If a fallback is not given, `null` will\n\t * be rendered.\n\t */\n\tfallback?: React.ReactNode;\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 * @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\tfill,\n\twidth,\n\theight,\n\tfallback = null,\n\t...restProps\n}: PrismicNextImageProps): JSX.Element => {\n\tif (process.env.NODE_ENV !== \"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 (prismic.isFilled.imageThumbnail(field)) {\n\t\tconst src = buildURL(field.url, imgixParams);\n\n\t\tconst ar = field.dimensions.width / field.dimensions.height;\n\n\t\tconst castedWidth = castInt(width);\n\t\tconst castedHeight = castInt(height);\n\n\t\tlet resolvedWidth = castedWidth ?? field.dimensions.width;\n\t\tlet resolvedHeight = castedHeight ?? field.dimensions.height;\n\n\t\tif (castedWidth != null && castedHeight == null) {\n\t\t\tresolvedHeight = castedWidth / ar;\n\t\t} else if (castedWidth == null && castedHeight != null) {\n\t\t\tresolvedWidth = castedHeight * ar;\n\t\t}\n\n\t\t// A non-null assertion is required since we can't statically\n\t\t// know if an alt attribute is available.\n\t\t// eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n\t\tconst resolvedAlt = (alt ?? (field.alt || fallbackAlt))!;\n\n\t\tif (\n\t\t\tprocess.env.NODE_ENV !== \"production\" &&\n\t\t\ttypeof resolvedAlt !== \"string\"\n\t\t) {\n\t\t\tconsole.error(\n\t\t\t\t`[PrismicNextImage] The following image is missing an \"alt\" property. Please add Alternative Text to the image in Prismic. To mark the image as decorative instead, add one of \\`alt=\"\"\\` or \\`fallbackAlt=\"\"\\`.`,\n\t\t\t\tsrc,\n\t\t\t);\n\t\t}\n\n\t\treturn (\n\t\t\t<Image\n\t\t\t\tsrc={src}\n\t\t\t\twidth={fill ? undefined : resolvedWidth}\n\t\t\t\theight={fill ? undefined : resolvedHeight}\n\t\t\t\talt={resolvedAlt}\n\t\t\t\tfill={fill}\n\t\t\t\tloader={imgixLoader}\n\t\t\t\t{...restProps}\n\t\t\t/>\n\t\t);\n\t} else {\n\t\treturn <>{fallback}</>;\n\t}\n};\n"],"names":[],"mappings":";;;;;;;;AAUA;AACC;AACQ;AAAA;AAED;AAEF;AACI;AAAA;AAEA;AAAA;AACP;AAEH;AAsDO;AAWF;AACH;AACC;AAGI;AAIL;AACC;AAGI;AAEJ;AAGF;AACC;AAEA;AAEM;AACA;AAEF;AACA;AAEA;AACH;AAA+B;AAE/B;AAA+B;AAM1B;AAEN;AAIS;AAEJ;AAIL;AASG;AAGH;AAAkB;AAEpB;;;;"}
@@ -2,7 +2,7 @@
2
2
  import * as React from "react";
3
3
  import * as prismic from "@prismicio/client";
4
4
  import Link from "next/link";
5
- export type PrismicNextLinkProps = Omit<React.ComponentProps<typeof Link>, "field" | "document" | "href" | "rel"> & {
5
+ export declare type PrismicNextLinkProps = Omit<React.ComponentProps<typeof Link>, "field" | "document" | "href" | "rel"> & {
6
6
  linkResolver?: prismic.LinkResolverFunction;
7
7
  rel?: string | prismic.AsLinkAttrsConfig["rel"];
8
8
  } & ({
@@ -47,7 +47,7 @@ export declare const PrismicNextLink: React.ForwardRefExoticComponent<(Pick<Omit
47
47
  } & {
48
48
  children?: React.ReactNode;
49
49
  } & React.RefAttributes<HTMLAnchorElement>, "field" | "document" | "href" | "rel"> & {
50
- linkResolver?: prismic.LinkResolverFunction | undefined;
50
+ linkResolver?: prismic.LinkResolverFunction<string | null | undefined> | undefined;
51
51
  rel?: string | prismic.AsLinkAttrsConfig["rel"];
52
52
  } & {
53
53
  field: prismic.LinkField | null | undefined;
@@ -82,7 +82,7 @@ export declare const PrismicNextLink: React.ForwardRefExoticComponent<(Pick<Omit
82
82
  } & {
83
83
  children?: React.ReactNode;
84
84
  } & React.RefAttributes<HTMLAnchorElement>, "field" | "document" | "href" | "rel"> & {
85
- linkResolver?: prismic.LinkResolverFunction | undefined;
85
+ linkResolver?: prismic.LinkResolverFunction<string | null | undefined> | undefined;
86
86
  rel?: string | prismic.AsLinkAttrsConfig["rel"];
87
87
  } & {
88
88
  field?: undefined;
@@ -117,7 +117,7 @@ export declare const PrismicNextLink: React.ForwardRefExoticComponent<(Pick<Omit
117
117
  } & {
118
118
  children?: React.ReactNode;
119
119
  } & React.RefAttributes<HTMLAnchorElement>, "field" | "document" | "href" | "rel"> & {
120
- linkResolver?: prismic.LinkResolverFunction | undefined;
120
+ linkResolver?: prismic.LinkResolverFunction<string | null | undefined> | undefined;
121
121
  rel?: string | prismic.AsLinkAttrsConfig["rel"];
122
122
  } & {
123
123
  field?: undefined;
@@ -2,7 +2,7 @@ import * as React from "react";
2
2
  /**
3
3
  * Props for `<PrismicPreview>`.
4
4
  */
5
- export type PrismicPreviewProps = {
5
+ export declare type PrismicPreviewProps = {
6
6
  /**
7
7
  * The name of your Prismic repository. A Prismic Toolbar will be registered
8
8
  * using this repository.
@@ -1,4 +1,4 @@
1
1
  import { PrismicPreviewProps } from "./PrismicPreview";
2
- type PrismicPreviewClientProps = Omit<PrismicPreviewProps, "children">;
2
+ declare type PrismicPreviewClientProps = Omit<PrismicPreviewProps, "children">;
3
3
  export declare function PrismicPreviewClient({ repositoryName, updatePreviewURL, exitPreviewURL, }: PrismicPreviewClientProps): null;
4
4
  export {};
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const link = require("../types/value/link.cjs");
4
4
  const documentToLinkField = require("./documentToLinkField.cjs");
5
- const asLink = (linkFieldOrDocument, linkResolver) => {
5
+ const asLink = (linkFieldOrDocument, ...configObjectOrTuple) => {
6
6
  if (!linkFieldOrDocument) {
7
7
  return null;
8
8
  }
@@ -13,13 +13,22 @@ const asLink = (linkFieldOrDocument, linkResolver) => {
13
13
  // TODO: Remove the `prettier-ignore` comment when this bug is fixed.
14
14
  "link_type" in linkFieldOrDocument ? linkFieldOrDocument : documentToLinkField.documentToLinkField(linkFieldOrDocument)
15
15
  );
16
+ const [configObjectOrLinkResolver] = configObjectOrTuple;
17
+ let config;
18
+ if (typeof configObjectOrLinkResolver === "function" || configObjectOrLinkResolver == null) {
19
+ config = {
20
+ linkResolver: configObjectOrLinkResolver
21
+ };
22
+ } else {
23
+ config = { ...configObjectOrLinkResolver };
24
+ }
16
25
  switch (linkField.link_type) {
17
26
  case link.LinkType.Media:
18
27
  case link.LinkType.Web:
19
28
  return "url" in linkField ? linkField.url : null;
20
29
  case link.LinkType.Document: {
21
- if ("id" in linkField && linkResolver) {
22
- const resolvedURL = linkResolver(linkField);
30
+ if ("id" in linkField && config.linkResolver) {
31
+ const resolvedURL = config.linkResolver(linkField);
23
32
  if (resolvedURL != null) {
24
33
  return resolvedURL;
25
34
  }
@@ -1 +1 @@
1
- {"version":3,"file":"asLink.cjs","sources":["../../../../../../node_modules/@prismicio/client/dist/helpers/asLink.js"],"sourcesContent":["import { LinkType } from \"../types/value/link.js\";\nimport { documentToLinkField } from \"./documentToLinkField.js\";\nconst asLink = (linkFieldOrDocument, linkResolver) => {\n if (!linkFieldOrDocument) {\n return null;\n }\n const linkField = (\n // prettier-ignore\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Bug in TypeScript 4.9: https://github.com/microsoft/TypeScript/issues/51501\n // TODO: Remove the `prettier-ignore` comment when this bug is fixed.\n \"link_type\" in linkFieldOrDocument ? linkFieldOrDocument : documentToLinkField(linkFieldOrDocument)\n );\n switch (linkField.link_type) {\n case LinkType.Media:\n case LinkType.Web:\n return \"url\" in linkField ? linkField.url : null;\n case LinkType.Document: {\n if (\"id\" in linkField && linkResolver) {\n const resolvedURL = linkResolver(linkField);\n if (resolvedURL != null) {\n return resolvedURL;\n }\n }\n if (\"url\" in linkField && linkField.url) {\n return linkField.url;\n }\n return null;\n }\n case LinkType.Any:\n default:\n return null;\n }\n};\nexport {\n asLink\n};\n//# sourceMappingURL=asLink.js.map\n"],"names":["documentToLinkField","LinkType"],"mappings":";;;;AAEK,MAAC,SAAS,CAAC,qBAAqB,iBAAiB;AACpD,MAAI,CAAC,qBAAqB;AACxB,WAAO;AAAA,EACR;AACD,QAAM;AAAA;AAAA;AAAA;AAAA;AAAA,IAKJ,eAAe,sBAAsB,sBAAsBA,oBAAAA,oBAAoB,mBAAmB;AAAA;AAEpG,UAAQ,UAAU,WAAS;AAAA,IACzB,KAAKC,KAAAA,SAAS;AAAA,IACd,KAAKA,KAAQ,SAAC;AACZ,aAAO,SAAS,YAAY,UAAU,MAAM;AAAA,IAC9C,KAAKA,KAAAA,SAAS,UAAU;AACtB,UAAI,QAAQ,aAAa,cAAc;AACrC,cAAM,cAAc,aAAa,SAAS;AAC1C,YAAI,eAAe,MAAM;AACvB,iBAAO;AAAA,QACR;AAAA,MACF;AACD,UAAI,SAAS,aAAa,UAAU,KAAK;AACvC,eAAO,UAAU;AAAA,MAClB;AACD,aAAO;AAAA,IACR;AAAA,IACD,KAAKA,KAAAA,SAAS;AAAA,IACd;AACE,aAAO;AAAA,EACV;AACH;;","x_google_ignoreList":[0]}
1
+ {"version":3,"file":"asLink.cjs","sources":["../../../../../../node_modules/@prismicio/client/dist/helpers/asLink.js"],"sourcesContent":["import { LinkType } from \"../types/value/link.js\";\nimport { documentToLinkField } from \"./documentToLinkField.js\";\nconst asLink = (linkFieldOrDocument, ...configObjectOrTuple) => {\n if (!linkFieldOrDocument) {\n return null;\n }\n const linkField = (\n // prettier-ignore\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Bug in TypeScript 4.9: https://github.com/microsoft/TypeScript/issues/51501\n // TODO: Remove the `prettier-ignore` comment when this bug is fixed.\n \"link_type\" in linkFieldOrDocument ? linkFieldOrDocument : documentToLinkField(linkFieldOrDocument)\n );\n const [configObjectOrLinkResolver] = configObjectOrTuple;\n let config;\n if (typeof configObjectOrLinkResolver === \"function\" || configObjectOrLinkResolver == null) {\n config = {\n linkResolver: configObjectOrLinkResolver\n };\n } else {\n config = { ...configObjectOrLinkResolver };\n }\n switch (linkField.link_type) {\n case LinkType.Media:\n case LinkType.Web:\n return \"url\" in linkField ? linkField.url : null;\n case LinkType.Document: {\n if (\"id\" in linkField && config.linkResolver) {\n const resolvedURL = config.linkResolver(linkField);\n if (resolvedURL != null) {\n return resolvedURL;\n }\n }\n if (\"url\" in linkField && linkField.url) {\n return linkField.url;\n }\n return null;\n }\n case LinkType.Any:\n default:\n return null;\n }\n};\nexport {\n asLink\n};\n//# sourceMappingURL=asLink.js.map\n"],"names":["documentToLinkField","LinkType"],"mappings":";;;;AAEK,MAAC,SAAS,CAAC,wBAAwB,wBAAwB;AAC9D,MAAI,CAAC,qBAAqB;AACxB,WAAO;AAAA,EACR;AACD,QAAM;AAAA;AAAA;AAAA;AAAA;AAAA,IAKJ,eAAe,sBAAsB,sBAAsBA,oBAAAA,oBAAoB,mBAAmB;AAAA;AAEpG,QAAM,CAAC,0BAA0B,IAAI;AACrC,MAAI;AACJ,MAAI,OAAO,+BAA+B,cAAc,8BAA8B,MAAM;AAC1F,aAAS;AAAA,MACP,cAAc;AAAA,IACpB;AAAA,EACA,OAAS;AACL,aAAS,EAAE,GAAG;EACf;AACD,UAAQ,UAAU,WAAS;AAAA,IACzB,KAAKC,KAAAA,SAAS;AAAA,IACd,KAAKA,KAAQ,SAAC;AACZ,aAAO,SAAS,YAAY,UAAU,MAAM;AAAA,IAC9C,KAAKA,KAAAA,SAAS,UAAU;AACtB,UAAI,QAAQ,aAAa,OAAO,cAAc;AAC5C,cAAM,cAAc,OAAO,aAAa,SAAS;AACjD,YAAI,eAAe,MAAM;AACvB,iBAAO;AAAA,QACR;AAAA,MACF;AACD,UAAI,SAAS,aAAa,UAAU,KAAK;AACvC,eAAO,UAAU;AAAA,MAClB;AACD,aAAO;AAAA,IACR;AAAA,IACD,KAAKA,KAAAA,SAAS;AAAA,IACd;AACE,aAAO;AAAA,EACV;AACH;;","x_google_ignoreList":[0]}
@@ -1,6 +1,6 @@
1
1
  import { LinkType } from "../types/value/link.js";
2
2
  import { documentToLinkField } from "./documentToLinkField.js";
3
- const asLink = (linkFieldOrDocument, linkResolver) => {
3
+ const asLink = (linkFieldOrDocument, ...configObjectOrTuple) => {
4
4
  if (!linkFieldOrDocument) {
5
5
  return null;
6
6
  }
@@ -11,13 +11,22 @@ const asLink = (linkFieldOrDocument, linkResolver) => {
11
11
  // TODO: Remove the `prettier-ignore` comment when this bug is fixed.
12
12
  "link_type" in linkFieldOrDocument ? linkFieldOrDocument : documentToLinkField(linkFieldOrDocument)
13
13
  );
14
+ const [configObjectOrLinkResolver] = configObjectOrTuple;
15
+ let config;
16
+ if (typeof configObjectOrLinkResolver === "function" || configObjectOrLinkResolver == null) {
17
+ config = {
18
+ linkResolver: configObjectOrLinkResolver
19
+ };
20
+ } else {
21
+ config = { ...configObjectOrLinkResolver };
22
+ }
14
23
  switch (linkField.link_type) {
15
24
  case LinkType.Media:
16
25
  case LinkType.Web:
17
26
  return "url" in linkField ? linkField.url : null;
18
27
  case LinkType.Document: {
19
- if ("id" in linkField && linkResolver) {
20
- const resolvedURL = linkResolver(linkField);
28
+ if ("id" in linkField && config.linkResolver) {
29
+ const resolvedURL = config.linkResolver(linkField);
21
30
  if (resolvedURL != null) {
22
31
  return resolvedURL;
23
32
  }
@@ -1 +1 @@
1
- {"version":3,"file":"asLink.js","sources":["../../../../../../node_modules/@prismicio/client/dist/helpers/asLink.js"],"sourcesContent":["import { LinkType } from \"../types/value/link.js\";\nimport { documentToLinkField } from \"./documentToLinkField.js\";\nconst asLink = (linkFieldOrDocument, linkResolver) => {\n if (!linkFieldOrDocument) {\n return null;\n }\n const linkField = (\n // prettier-ignore\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Bug in TypeScript 4.9: https://github.com/microsoft/TypeScript/issues/51501\n // TODO: Remove the `prettier-ignore` comment when this bug is fixed.\n \"link_type\" in linkFieldOrDocument ? linkFieldOrDocument : documentToLinkField(linkFieldOrDocument)\n );\n switch (linkField.link_type) {\n case LinkType.Media:\n case LinkType.Web:\n return \"url\" in linkField ? linkField.url : null;\n case LinkType.Document: {\n if (\"id\" in linkField && linkResolver) {\n const resolvedURL = linkResolver(linkField);\n if (resolvedURL != null) {\n return resolvedURL;\n }\n }\n if (\"url\" in linkField && linkField.url) {\n return linkField.url;\n }\n return null;\n }\n case LinkType.Any:\n default:\n return null;\n }\n};\nexport {\n asLink\n};\n//# sourceMappingURL=asLink.js.map\n"],"names":[],"mappings":";;AAEK,MAAC,SAAS,CAAC,qBAAqB,iBAAiB;AACpD,MAAI,CAAC,qBAAqB;AACxB,WAAO;AAAA,EACR;AACD,QAAM;AAAA;AAAA;AAAA;AAAA;AAAA,IAKJ,eAAe,sBAAsB,sBAAsB,oBAAoB,mBAAmB;AAAA;AAEpG,UAAQ,UAAU,WAAS;AAAA,IACzB,KAAK,SAAS;AAAA,IACd,KAAK,SAAS;AACZ,aAAO,SAAS,YAAY,UAAU,MAAM;AAAA,IAC9C,KAAK,SAAS,UAAU;AACtB,UAAI,QAAQ,aAAa,cAAc;AACrC,cAAM,cAAc,aAAa,SAAS;AAC1C,YAAI,eAAe,MAAM;AACvB,iBAAO;AAAA,QACR;AAAA,MACF;AACD,UAAI,SAAS,aAAa,UAAU,KAAK;AACvC,eAAO,UAAU;AAAA,MAClB;AACD,aAAO;AAAA,IACR;AAAA,IACD,KAAK,SAAS;AAAA,IACd;AACE,aAAO;AAAA,EACV;AACH;","x_google_ignoreList":[0]}
1
+ {"version":3,"file":"asLink.js","sources":["../../../../../../node_modules/@prismicio/client/dist/helpers/asLink.js"],"sourcesContent":["import { LinkType } from \"../types/value/link.js\";\nimport { documentToLinkField } from \"./documentToLinkField.js\";\nconst asLink = (linkFieldOrDocument, ...configObjectOrTuple) => {\n if (!linkFieldOrDocument) {\n return null;\n }\n const linkField = (\n // prettier-ignore\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Bug in TypeScript 4.9: https://github.com/microsoft/TypeScript/issues/51501\n // TODO: Remove the `prettier-ignore` comment when this bug is fixed.\n \"link_type\" in linkFieldOrDocument ? linkFieldOrDocument : documentToLinkField(linkFieldOrDocument)\n );\n const [configObjectOrLinkResolver] = configObjectOrTuple;\n let config;\n if (typeof configObjectOrLinkResolver === \"function\" || configObjectOrLinkResolver == null) {\n config = {\n linkResolver: configObjectOrLinkResolver\n };\n } else {\n config = { ...configObjectOrLinkResolver };\n }\n switch (linkField.link_type) {\n case LinkType.Media:\n case LinkType.Web:\n return \"url\" in linkField ? linkField.url : null;\n case LinkType.Document: {\n if (\"id\" in linkField && config.linkResolver) {\n const resolvedURL = config.linkResolver(linkField);\n if (resolvedURL != null) {\n return resolvedURL;\n }\n }\n if (\"url\" in linkField && linkField.url) {\n return linkField.url;\n }\n return null;\n }\n case LinkType.Any:\n default:\n return null;\n }\n};\nexport {\n asLink\n};\n//# sourceMappingURL=asLink.js.map\n"],"names":[],"mappings":";;AAEK,MAAC,SAAS,CAAC,wBAAwB,wBAAwB;AAC9D,MAAI,CAAC,qBAAqB;AACxB,WAAO;AAAA,EACR;AACD,QAAM;AAAA;AAAA;AAAA;AAAA;AAAA,IAKJ,eAAe,sBAAsB,sBAAsB,oBAAoB,mBAAmB;AAAA;AAEpG,QAAM,CAAC,0BAA0B,IAAI;AACrC,MAAI;AACJ,MAAI,OAAO,+BAA+B,cAAc,8BAA8B,MAAM;AAC1F,aAAS;AAAA,MACP,cAAc;AAAA,IACpB;AAAA,EACA,OAAS;AACL,aAAS,EAAE,GAAG;EACf;AACD,UAAQ,UAAU,WAAS;AAAA,IACzB,KAAK,SAAS;AAAA,IACd,KAAK,SAAS;AACZ,aAAO,SAAS,YAAY,UAAU,MAAM;AAAA,IAC9C,KAAK,SAAS,UAAU;AACtB,UAAI,QAAQ,aAAa,OAAO,cAAc;AAC5C,cAAM,cAAc,OAAO,aAAa,SAAS;AACjD,YAAI,eAAe,MAAM;AACvB,iBAAO;AAAA,QACR;AAAA,MACF;AACD,UAAI,SAAS,aAAa,UAAU,KAAK;AACvC,eAAO,UAAU;AAAA,MAClB;AACD,aAAO;AAAA,IACR;AAAA,IACD,KAAK,SAAS;AAAA,IACd;AACE,aAAO;AAAA,EACV;AACH;","x_google_ignoreList":[0]}
@@ -1 +1 @@
1
- {"version":3,"file":"isFilled.cjs","sources":["../../../../../../node_modules/@prismicio/client/dist/helpers/isFilled.js"],"sourcesContent":["const isNonNullish = (input) => {\n return input != null;\n};\nconst isNonEmptyArray = (input) => {\n return !!input.length;\n};\nconst richText = (field) => {\n if (!isNonNullish(field)) {\n return false;\n } else if (field.length === 1 && \"text\" in field[0]) {\n return !!field[0].text;\n } else {\n return !!field.length;\n }\n};\nconst title = richText;\nconst imageThumbnail = (thumbnail) => {\n return isNonNullish(thumbnail) && !!thumbnail.url;\n};\nconst image = imageThumbnail;\nconst link = (field) => {\n return isNonNullish(field) && (\"id\" in field || \"url\" in field);\n};\nconst linkToMedia = link;\nconst contentRelationship = link;\nconst date = isNonNullish;\nconst timestamp = isNonNullish;\nconst color = isNonNullish;\nconst number = isNonNullish;\nconst keyText = (field) => {\n return isNonNullish(keyText) && !!field;\n};\nconst select = isNonNullish;\nconst embed = (field) => {\n return isNonNullish(field) && !!field.embed_url;\n};\nconst geoPoint = (field) => {\n return isNonNullish(field) && \"longitude\" in field;\n};\nconst integrationFields = isNonNullish;\nconst group = (group2) => {\n return isNonNullish(group2) && isNonEmptyArray(group2);\n};\nconst sliceZone = (slices) => {\n return isNonNullish(slices) && isNonEmptyArray(slices);\n};\nexport {\n color,\n contentRelationship,\n date,\n embed,\n geoPoint,\n group,\n image,\n imageThumbnail,\n integrationFields,\n keyText,\n link,\n linkToMedia,\n number,\n richText,\n select,\n sliceZone,\n timestamp,\n title\n};\n//# sourceMappingURL=isFilled.js.map\n"],"names":[],"mappings":";;AAAA,MAAM,eAAe,CAAC,UAAU;AAC9B,SAAO,SAAS;AAClB;AAcK,MAAC,iBAAiB,CAAC,cAAc;AACpC,SAAO,aAAa,SAAS,KAAK,CAAC,CAAC,UAAU;AAChD;AAEK,MAAC,OAAO,CAAC,UAAU;AACtB,SAAO,aAAa,KAAK,MAAM,QAAQ,SAAS,SAAS;AAC3D;;;","x_google_ignoreList":[0]}
1
+ {"version":3,"file":"isFilled.cjs","sources":["../../../../../../node_modules/@prismicio/client/dist/helpers/isFilled.js"],"sourcesContent":["const isNonNullish = (input) => {\n return input != null;\n};\nconst isNonEmptyArray = (input) => {\n return !!input.length;\n};\nconst richText = (field) => {\n if (!isNonNullish(field)) {\n return false;\n } else if (field.length === 1 && \"text\" in field[0]) {\n return !!field[0].text;\n } else {\n return !!field.length;\n }\n};\nconst title = richText;\nconst imageThumbnail = (thumbnail) => {\n return isNonNullish(thumbnail) && !!thumbnail.url;\n};\nconst image = imageThumbnail;\nconst link = (field) => {\n return isNonNullish(field) && (\"id\" in field || \"url\" in field);\n};\nconst linkToMedia = link;\nconst contentRelationship = link;\nconst date = isNonNullish;\nconst timestamp = isNonNullish;\nconst color = isNonNullish;\nconst number = isNonNullish;\nconst keyText = (field) => {\n return isNonNullish(keyText) && !!field;\n};\nconst select = isNonNullish;\nconst embed = (field) => {\n return isNonNullish(field) && !!field.embed_url;\n};\nconst geoPoint = (field) => {\n return isNonNullish(field) && \"longitude\" in field;\n};\nconst integrationField = isNonNullish;\nconst integrationFields = integrationField;\nconst group = (group2) => {\n return isNonNullish(group2) && isNonEmptyArray(group2);\n};\nconst sliceZone = (slices) => {\n return isNonNullish(slices) && isNonEmptyArray(slices);\n};\nexport {\n color,\n contentRelationship,\n date,\n embed,\n geoPoint,\n group,\n image,\n imageThumbnail,\n integrationField,\n integrationFields,\n keyText,\n link,\n linkToMedia,\n number,\n richText,\n select,\n sliceZone,\n timestamp,\n title\n};\n//# sourceMappingURL=isFilled.js.map\n"],"names":[],"mappings":";;AAAA,MAAM,eAAe,CAAC,UAAU;AAC9B,SAAO,SAAS;AAClB;AAcK,MAAC,iBAAiB,CAAC,cAAc;AACpC,SAAO,aAAa,SAAS,KAAK,CAAC,CAAC,UAAU;AAChD;AAEK,MAAC,OAAO,CAAC,UAAU;AACtB,SAAO,aAAa,KAAK,MAAM,QAAQ,SAAS,SAAS;AAC3D;;;","x_google_ignoreList":[0]}
@@ -1 +1 @@
1
- {"version":3,"file":"isFilled.js","sources":["../../../../../../node_modules/@prismicio/client/dist/helpers/isFilled.js"],"sourcesContent":["const isNonNullish = (input) => {\n return input != null;\n};\nconst isNonEmptyArray = (input) => {\n return !!input.length;\n};\nconst richText = (field) => {\n if (!isNonNullish(field)) {\n return false;\n } else if (field.length === 1 && \"text\" in field[0]) {\n return !!field[0].text;\n } else {\n return !!field.length;\n }\n};\nconst title = richText;\nconst imageThumbnail = (thumbnail) => {\n return isNonNullish(thumbnail) && !!thumbnail.url;\n};\nconst image = imageThumbnail;\nconst link = (field) => {\n return isNonNullish(field) && (\"id\" in field || \"url\" in field);\n};\nconst linkToMedia = link;\nconst contentRelationship = link;\nconst date = isNonNullish;\nconst timestamp = isNonNullish;\nconst color = isNonNullish;\nconst number = isNonNullish;\nconst keyText = (field) => {\n return isNonNullish(keyText) && !!field;\n};\nconst select = isNonNullish;\nconst embed = (field) => {\n return isNonNullish(field) && !!field.embed_url;\n};\nconst geoPoint = (field) => {\n return isNonNullish(field) && \"longitude\" in field;\n};\nconst integrationFields = isNonNullish;\nconst group = (group2) => {\n return isNonNullish(group2) && isNonEmptyArray(group2);\n};\nconst sliceZone = (slices) => {\n return isNonNullish(slices) && isNonEmptyArray(slices);\n};\nexport {\n color,\n contentRelationship,\n date,\n embed,\n geoPoint,\n group,\n image,\n imageThumbnail,\n integrationFields,\n keyText,\n link,\n linkToMedia,\n number,\n richText,\n select,\n sliceZone,\n timestamp,\n title\n};\n//# sourceMappingURL=isFilled.js.map\n"],"names":[],"mappings":"AAAA,MAAM,eAAe,CAAC,UAAU;AAC9B,SAAO,SAAS;AAClB;AAcK,MAAC,iBAAiB,CAAC,cAAc;AACpC,SAAO,aAAa,SAAS,KAAK,CAAC,CAAC,UAAU;AAChD;AAEK,MAAC,OAAO,CAAC,UAAU;AACtB,SAAO,aAAa,KAAK,MAAM,QAAQ,SAAS,SAAS;AAC3D;","x_google_ignoreList":[0]}
1
+ {"version":3,"file":"isFilled.js","sources":["../../../../../../node_modules/@prismicio/client/dist/helpers/isFilled.js"],"sourcesContent":["const isNonNullish = (input) => {\n return input != null;\n};\nconst isNonEmptyArray = (input) => {\n return !!input.length;\n};\nconst richText = (field) => {\n if (!isNonNullish(field)) {\n return false;\n } else if (field.length === 1 && \"text\" in field[0]) {\n return !!field[0].text;\n } else {\n return !!field.length;\n }\n};\nconst title = richText;\nconst imageThumbnail = (thumbnail) => {\n return isNonNullish(thumbnail) && !!thumbnail.url;\n};\nconst image = imageThumbnail;\nconst link = (field) => {\n return isNonNullish(field) && (\"id\" in field || \"url\" in field);\n};\nconst linkToMedia = link;\nconst contentRelationship = link;\nconst date = isNonNullish;\nconst timestamp = isNonNullish;\nconst color = isNonNullish;\nconst number = isNonNullish;\nconst keyText = (field) => {\n return isNonNullish(keyText) && !!field;\n};\nconst select = isNonNullish;\nconst embed = (field) => {\n return isNonNullish(field) && !!field.embed_url;\n};\nconst geoPoint = (field) => {\n return isNonNullish(field) && \"longitude\" in field;\n};\nconst integrationField = isNonNullish;\nconst integrationFields = integrationField;\nconst group = (group2) => {\n return isNonNullish(group2) && isNonEmptyArray(group2);\n};\nconst sliceZone = (slices) => {\n return isNonNullish(slices) && isNonEmptyArray(slices);\n};\nexport {\n color,\n contentRelationship,\n date,\n embed,\n geoPoint,\n group,\n image,\n imageThumbnail,\n integrationField,\n integrationFields,\n keyText,\n link,\n linkToMedia,\n number,\n richText,\n select,\n sliceZone,\n timestamp,\n title\n};\n//# sourceMappingURL=isFilled.js.map\n"],"names":[],"mappings":"AAAA,MAAM,eAAe,CAAC,UAAU;AAC9B,SAAO,SAAS;AAClB;AAcK,MAAC,iBAAiB,CAAC,cAAc;AACpC,SAAO,aAAa,SAAS,KAAK,CAAC,CAAC,UAAU;AAChD;AAEK,MAAC,OAAO,CAAC,UAAU;AACtB,SAAO,aAAa,KAAK,MAAM,QAAQ,SAAS,SAAS;AAC3D;","x_google_ignoreList":[0]}
@@ -0,0 +1 @@
1
+ export declare function run(argv: string[]): Promise<void>;
package/dist/cli.cjs ADDED
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const mri = require("mri");
4
+ const path = require("node:path");
5
+ const fs = require("node:fs/promises");
6
+ const tty = require("node:tty");
7
+ const node_buffer = require("node:buffer");
8
+ const _package = require("./package.json.cjs");
9
+ function _interopNamespaceDefault(e) {
10
+ const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
11
+ if (e) {
12
+ for (const k in e) {
13
+ if (k !== "default") {
14
+ const d = Object.getOwnPropertyDescriptor(e, k);
15
+ Object.defineProperty(n, k, d.get ? d : {
16
+ enumerable: true,
17
+ get: () => e[k]
18
+ });
19
+ }
20
+ }
21
+ }
22
+ n.default = e;
23
+ return Object.freeze(n);
24
+ }
25
+ const path__namespace = /* @__PURE__ */ _interopNamespaceDefault(path);
26
+ const fs__namespace = /* @__PURE__ */ _interopNamespaceDefault(fs);
27
+ const tty__namespace = /* @__PURE__ */ _interopNamespaceDefault(tty);
28
+ async function pathExists(filePath) {
29
+ try {
30
+ await fs__namespace.access(filePath);
31
+ return true;
32
+ } catch {
33
+ return false;
34
+ }
35
+ }
36
+ function color(colorCode, string) {
37
+ return tty__namespace.WriteStream.prototype.hasColors() ? "\x1B[" + colorCode + "m" + string + "\x1B[39m" : string;
38
+ }
39
+ function warn(string) {
40
+ return console.warn(`- ${color(33, "warn")} ${string}`);
41
+ }
42
+ function info(string) {
43
+ return console.info(`- ${color(35, "info")} ${string}`);
44
+ }
45
+ async function run(argv) {
46
+ const args = mri(argv.slice(2), {
47
+ boolean: ["help", "version"],
48
+ alias: {
49
+ help: "h",
50
+ version: "v"
51
+ },
52
+ default: {
53
+ help: false,
54
+ version: false
55
+ }
56
+ });
57
+ const command = args._[0];
58
+ switch (command) {
59
+ case "clear-cache": {
60
+ warn("`prismic-next clear-cache` is an experimental utility. It may be replaced with a different solution in the future.");
61
+ async function getAppRootDir() {
62
+ let currentDir = process.cwd();
63
+ while (!await pathExists(path__namespace.join(currentDir, ".next")) && !await pathExists(path__namespace.join(currentDir, "package.json"))) {
64
+ if (currentDir === path__namespace.resolve("/")) {
65
+ break;
66
+ }
67
+ currentDir = path__namespace.join(currentDir, "..");
68
+ }
69
+ if (await pathExists(path__namespace.join(currentDir, ".next")) || await pathExists(path__namespace.join(currentDir, "package.json"))) {
70
+ return currentDir;
71
+ }
72
+ }
73
+ const appRootDir = await getAppRootDir();
74
+ if (!appRootDir) {
75
+ warn("Could not find the Next.js app root. Run `prismic-next clear-cache` in a Next.js project with a `.next` directory or `package.json` file.");
76
+ return;
77
+ }
78
+ const fetchCacheDir = path__namespace.join(appRootDir, ".next", "cache", "fetch-cache");
79
+ if (!await pathExists(fetchCacheDir)) {
80
+ info("No Next.js fetch cache directory found. You are good to go!");
81
+ return;
82
+ }
83
+ const cacheEntries = await fs__namespace.readdir(fetchCacheDir);
84
+ await Promise.all(cacheEntries.map(async (entry) => {
85
+ try {
86
+ const contents = await fs__namespace.readFile(path__namespace.join(fetchCacheDir, entry), "utf8");
87
+ const payload = JSON.parse(contents);
88
+ if (payload.kind !== "FETCH") {
89
+ return;
90
+ }
91
+ const bodyPayload = JSON.parse(node_buffer.Buffer.from(payload.data.body, "base64").toString());
92
+ if (/\.prismic\.io\/auth$/.test(bodyPayload.oauth_initiate)) {
93
+ await fs__namespace.unlink(path__namespace.join(fetchCacheDir, entry));
94
+ info(`Prismic /api/v2 request cache cleared: ${entry}`);
95
+ }
96
+ } catch (e) {
97
+ }
98
+ }));
99
+ info("The Prismic request cache has been cleared. Uncached requests will begin on the next Next.js server start-up.");
100
+ return;
101
+ }
102
+ default: {
103
+ if (command && (!args.version || !args.help)) {
104
+ warn("Invalid command.\n");
105
+ }
106
+ if (args.version) {
107
+ console.info(_package.version);
108
+ return;
109
+ }
110
+ console.info(`
111
+ Usage:
112
+ prismic-next <command> [options...]
113
+ Available commands:
114
+ clear-cache
115
+ Options:
116
+ --help, -h Show help text
117
+ --version, -v Show version
118
+ `.trim());
119
+ }
120
+ }
121
+ }
122
+ exports.run = run;
123
+ //# sourceMappingURL=cli.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.cjs","sources":["../../src/cli/index.ts"],"sourcesContent":["import mri from \"mri\";\nimport * as path from \"node:path\";\nimport * as fs from \"node:fs/promises\";\nimport * as tty from \"node:tty\";\nimport { Buffer } from \"node:buffer\";\n\nimport * as pkg from \"../../package.json\";\n\nasync function pathExists(filePath: string) {\n\ttry {\n\t\tawait fs.access(filePath);\n\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction color(colorCode: number, string: string) {\n\treturn tty.WriteStream.prototype.hasColors()\n\t\t? \"\\u001B[\" + colorCode + \"m\" + string + \"\\u001B[39m\"\n\t\t: string;\n}\n\nfunction warn(string: string) {\n\t// Yellow\n\treturn console.warn(`- ${color(33, \"warn\")} ${string}`);\n}\n\nfunction info(string: string) {\n\t// Magenta\n\treturn console.info(`- ${color(35, \"info\")} ${string}`);\n}\n\ntype Args = {\n\thelp: boolean;\n\tversion: boolean;\n};\n\nexport async function run(argv: string[]) {\n\tconst args = mri<Args>(argv.slice(2), {\n\t\tboolean: [\"help\", \"version\"],\n\t\talias: {\n\t\t\thelp: \"h\",\n\t\t\tversion: \"v\",\n\t\t},\n\t\tdefault: {\n\t\t\thelp: false,\n\t\t\tversion: false,\n\t\t},\n\t});\n\n\tconst command = args._[0];\n\n\tswitch (command) {\n\t\tcase \"clear-cache\": {\n\t\t\twarn(\n\t\t\t\t\"`prismic-next clear-cache` is an experimental utility. It may be replaced with a different solution in the future.\",\n\t\t\t);\n\n\t\t\tasync function getAppRootDir() {\n\t\t\t\tlet currentDir = process.cwd();\n\n\t\t\t\twhile (\n\t\t\t\t\t!(await pathExists(path.join(currentDir, \".next\"))) &&\n\t\t\t\t\t!(await pathExists(path.join(currentDir, \"package.json\")))\n\t\t\t\t) {\n\t\t\t\t\tif (currentDir === path.resolve(\"/\")) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrentDir = path.join(currentDir, \"..\");\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\t(await pathExists(path.join(currentDir, \".next\"))) ||\n\t\t\t\t\t(await pathExists(path.join(currentDir, \"package.json\")))\n\t\t\t\t) {\n\t\t\t\t\treturn currentDir;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst appRootDir = await getAppRootDir();\n\n\t\t\tif (!appRootDir) {\n\t\t\t\twarn(\n\t\t\t\t\t\"Could not find the Next.js app root. Run `prismic-next clear-cache` in a Next.js project with a `.next` directory or `package.json` file.\",\n\t\t\t\t);\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst fetchCacheDir = path.join(\n\t\t\t\tappRootDir,\n\t\t\t\t\".next\",\n\t\t\t\t\"cache\",\n\t\t\t\t\"fetch-cache\",\n\t\t\t);\n\n\t\t\tif (!(await pathExists(fetchCacheDir))) {\n\t\t\t\tinfo(\"No Next.js fetch cache directory found. You are good to go!\");\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst cacheEntries = await fs.readdir(fetchCacheDir);\n\n\t\t\tawait Promise.all(\n\t\t\t\tcacheEntries.map(async (entry) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst contents = await fs.readFile(\n\t\t\t\t\t\t\tpath.join(fetchCacheDir, entry),\n\t\t\t\t\t\t\t\"utf8\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst payload = JSON.parse(contents);\n\n\t\t\t\t\t\tif (payload.kind !== \"FETCH\") {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst bodyPayload = JSON.parse(\n\t\t\t\t\t\t\tBuffer.from(payload.data.body, \"base64\").toString(),\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\t// Delete `/api/v2` requests.\n\t\t\t\t\t\tif (/\\.prismic\\.io\\/auth$/.test(bodyPayload.oauth_initiate)) {\n\t\t\t\t\t\t\tawait fs.unlink(path.join(fetchCacheDir, entry));\n\n\t\t\t\t\t\t\tinfo(`Prismic /api/v2 request cache cleared: ${entry}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t// noop\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t);\n\n\t\t\tinfo(\n\t\t\t\t\"The Prismic request cache has been cleared. Uncached requests will begin on the next Next.js server start-up.\",\n\t\t\t);\n\n\t\t\treturn;\n\t\t}\n\n\t\tdefault: {\n\t\t\tif (command && (!args.version || !args.help)) {\n\t\t\t\twarn(\"Invalid command.\\n\");\n\t\t\t}\n\n\t\t\tif (args.version) {\n\t\t\t\tconsole.info(pkg.version);\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconsole.info(\n\t\t\t\t`\nUsage:\n prismic-next <command> [options...]\nAvailable commands:\n clear-cache\nOptions:\n --help, -h Show help text\n --version, -v Show version\n`.trim(),\n\t\t\t);\n\t\t}\n\t}\n}\n"],"names":["fs","tty","path","Buffer","pkg.version"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAQA,eAAe,WAAW,UAAgB;AACrC,MAAA;AACG,UAAAA,cAAG,OAAO,QAAQ;AAEjB,WAAA;AAAA,EAAA,QACN;AACM,WAAA;AAAA,EACP;AACF;AAEA,SAAS,MAAM,WAAmB,QAAc;AACxC,SAAAC,eAAI,YAAY,UAAU,cAC9B,UAAY,YAAY,MAAM,SAAS,aACvC;AACJ;AAEA,SAAS,KAAK,QAAc;AAE3B,SAAO,QAAQ,KAAK,KAAK,MAAM,IAAI,MAAM,KAAK,QAAQ;AACvD;AAEA,SAAS,KAAK,QAAc;AAE3B,SAAO,QAAQ,KAAK,KAAK,MAAM,IAAI,MAAM,KAAK,QAAQ;AACvD;AAOA,eAAsB,IAAI,MAAc;AACvC,QAAM,OAAO,IAAU,KAAK,MAAM,CAAC,GAAG;AAAA,IACrC,SAAS,CAAC,QAAQ,SAAS;AAAA,IAC3B,OAAO;AAAA,MACN,MAAM;AAAA,MACN,SAAS;AAAA,IACT;AAAA,IACD,SAAS;AAAA,MACR,MAAM;AAAA,MACN,SAAS;AAAA,IACT;AAAA,EAAA,CACD;AAEK,QAAA,UAAU,KAAK,EAAE,CAAC;AAExB,UAAQ,SAAS;AAAA,IAChB,KAAK,eAAe;AACnB,WACC,oHAAoH;AAGrH,qBAAe,gBAAa;AACvB,YAAA,aAAa,QAAQ;AAEzB,eACC,CAAE,MAAM,WAAWC,gBAAK,KAAK,YAAY,OAAO,CAAC,KACjD,CAAE,MAAM,WAAWA,gBAAK,KAAK,YAAY,cAAc,CAAC,GACvD;AACD,cAAI,eAAeA,gBAAK,QAAQ,GAAG,GAAG;AACrC;AAAA,UACA;AAEY,uBAAAA,gBAAK,KAAK,YAAY,IAAI;AAAA,QACvC;AAED,YACE,MAAM,WAAWA,gBAAK,KAAK,YAAY,OAAO,CAAC,KAC/C,MAAM,WAAWA,gBAAK,KAAK,YAAY,cAAc,CAAC,GACtD;AACM,iBAAA;AAAA,QACP;AAAA,MACF;AAEM,YAAA,aAAa,MAAM;AAEzB,UAAI,CAAC,YAAY;AAChB,aACC,2IAA2I;AAG5I;AAAA,MACA;AAED,YAAM,gBAAgBA,gBAAK,KAC1B,YACA,SACA,SACA,aAAa;AAGd,UAAI,CAAE,MAAM,WAAW,aAAa,GAAI;AACvC,aAAK,6DAA6D;AAElE;AAAA,MACA;AAED,YAAM,eAAe,MAAMF,cAAG,QAAQ,aAAa;AAEnD,YAAM,QAAQ,IACb,aAAa,IAAI,OAAO,UAAS;AAC5B,YAAA;AACG,gBAAA,WAAW,MAAMA,cAAG,SACzBE,gBAAK,KAAK,eAAe,KAAK,GAC9B,MAAM;AAED,gBAAA,UAAU,KAAK,MAAM,QAAQ;AAE/B,cAAA,QAAQ,SAAS,SAAS;AAC7B;AAAA,UACA;AAEK,gBAAA,cAAc,KAAK,MACxBC,YAAO,OAAA,KAAK,QAAQ,KAAK,MAAM,QAAQ,EAAE,SAAU,CAAA;AAIpD,cAAI,uBAAuB,KAAK,YAAY,cAAc,GAAG;AAC5D,kBAAMH,cAAG,OAAOE,gBAAK,KAAK,eAAe,KAAK,CAAC;AAE/C,iBAAK,0CAA0C,OAAO;AAAA,UACtD;AAAA,iBACO;QAER;AAAA,MACD,CAAA,CAAC;AAGH,WACC,+GAA+G;AAGhH;AAAA,IACA;AAAA,IAED,SAAS;AACR,UAAI,YAAY,CAAC,KAAK,WAAW,CAAC,KAAK,OAAO;AAC7C,aAAK,oBAAoB;AAAA,MACzB;AAED,UAAI,KAAK,SAAS;AACT,gBAAA,KAAKE,SAAAA,OAAW;AAExB;AAAA,MACA;AAED,cAAQ,KACP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQF,KAAM,CAAA;AAAA,IAEL;AAAA,EACD;AACF;;"}
package/dist/cli.js ADDED
@@ -0,0 +1,104 @@
1
+ import mri from "mri";
2
+ import * as path from "node:path";
3
+ import * as fs from "node:fs/promises";
4
+ import * as tty from "node:tty";
5
+ import { Buffer } from "node:buffer";
6
+ import { version } from "./package.json.js";
7
+ async function pathExists(filePath) {
8
+ try {
9
+ await fs.access(filePath);
10
+ return true;
11
+ } catch {
12
+ return false;
13
+ }
14
+ }
15
+ function color(colorCode, string) {
16
+ return tty.WriteStream.prototype.hasColors() ? "\x1B[" + colorCode + "m" + string + "\x1B[39m" : string;
17
+ }
18
+ function warn(string) {
19
+ return console.warn(`- ${color(33, "warn")} ${string}`);
20
+ }
21
+ function info(string) {
22
+ return console.info(`- ${color(35, "info")} ${string}`);
23
+ }
24
+ async function run(argv) {
25
+ const args = mri(argv.slice(2), {
26
+ boolean: ["help", "version"],
27
+ alias: {
28
+ help: "h",
29
+ version: "v"
30
+ },
31
+ default: {
32
+ help: false,
33
+ version: false
34
+ }
35
+ });
36
+ const command = args._[0];
37
+ switch (command) {
38
+ case "clear-cache": {
39
+ warn("`prismic-next clear-cache` is an experimental utility. It may be replaced with a different solution in the future.");
40
+ async function getAppRootDir() {
41
+ let currentDir = process.cwd();
42
+ while (!await pathExists(path.join(currentDir, ".next")) && !await pathExists(path.join(currentDir, "package.json"))) {
43
+ if (currentDir === path.resolve("/")) {
44
+ break;
45
+ }
46
+ currentDir = path.join(currentDir, "..");
47
+ }
48
+ if (await pathExists(path.join(currentDir, ".next")) || await pathExists(path.join(currentDir, "package.json"))) {
49
+ return currentDir;
50
+ }
51
+ }
52
+ const appRootDir = await getAppRootDir();
53
+ if (!appRootDir) {
54
+ warn("Could not find the Next.js app root. Run `prismic-next clear-cache` in a Next.js project with a `.next` directory or `package.json` file.");
55
+ return;
56
+ }
57
+ const fetchCacheDir = path.join(appRootDir, ".next", "cache", "fetch-cache");
58
+ if (!await pathExists(fetchCacheDir)) {
59
+ info("No Next.js fetch cache directory found. You are good to go!");
60
+ return;
61
+ }
62
+ const cacheEntries = await fs.readdir(fetchCacheDir);
63
+ await Promise.all(cacheEntries.map(async (entry) => {
64
+ try {
65
+ const contents = await fs.readFile(path.join(fetchCacheDir, entry), "utf8");
66
+ const payload = JSON.parse(contents);
67
+ if (payload.kind !== "FETCH") {
68
+ return;
69
+ }
70
+ const bodyPayload = JSON.parse(Buffer.from(payload.data.body, "base64").toString());
71
+ if (/\.prismic\.io\/auth$/.test(bodyPayload.oauth_initiate)) {
72
+ await fs.unlink(path.join(fetchCacheDir, entry));
73
+ info(`Prismic /api/v2 request cache cleared: ${entry}`);
74
+ }
75
+ } catch (e) {
76
+ }
77
+ }));
78
+ info("The Prismic request cache has been cleared. Uncached requests will begin on the next Next.js server start-up.");
79
+ return;
80
+ }
81
+ default: {
82
+ if (command && (!args.version || !args.help)) {
83
+ warn("Invalid command.\n");
84
+ }
85
+ if (args.version) {
86
+ console.info(version);
87
+ return;
88
+ }
89
+ console.info(`
90
+ Usage:
91
+ prismic-next <command> [options...]
92
+ Available commands:
93
+ clear-cache
94
+ Options:
95
+ --help, -h Show help text
96
+ --version, -v Show version
97
+ `.trim());
98
+ }
99
+ }
100
+ }
101
+ export {
102
+ run
103
+ };
104
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sources":["../../src/cli/index.ts"],"sourcesContent":["import mri from \"mri\";\nimport * as path from \"node:path\";\nimport * as fs from \"node:fs/promises\";\nimport * as tty from \"node:tty\";\nimport { Buffer } from \"node:buffer\";\n\nimport * as pkg from \"../../package.json\";\n\nasync function pathExists(filePath: string) {\n\ttry {\n\t\tawait fs.access(filePath);\n\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction color(colorCode: number, string: string) {\n\treturn tty.WriteStream.prototype.hasColors()\n\t\t? \"\\u001B[\" + colorCode + \"m\" + string + \"\\u001B[39m\"\n\t\t: string;\n}\n\nfunction warn(string: string) {\n\t// Yellow\n\treturn console.warn(`- ${color(33, \"warn\")} ${string}`);\n}\n\nfunction info(string: string) {\n\t// Magenta\n\treturn console.info(`- ${color(35, \"info\")} ${string}`);\n}\n\ntype Args = {\n\thelp: boolean;\n\tversion: boolean;\n};\n\nexport async function run(argv: string[]) {\n\tconst args = mri<Args>(argv.slice(2), {\n\t\tboolean: [\"help\", \"version\"],\n\t\talias: {\n\t\t\thelp: \"h\",\n\t\t\tversion: \"v\",\n\t\t},\n\t\tdefault: {\n\t\t\thelp: false,\n\t\t\tversion: false,\n\t\t},\n\t});\n\n\tconst command = args._[0];\n\n\tswitch (command) {\n\t\tcase \"clear-cache\": {\n\t\t\twarn(\n\t\t\t\t\"`prismic-next clear-cache` is an experimental utility. It may be replaced with a different solution in the future.\",\n\t\t\t);\n\n\t\t\tasync function getAppRootDir() {\n\t\t\t\tlet currentDir = process.cwd();\n\n\t\t\t\twhile (\n\t\t\t\t\t!(await pathExists(path.join(currentDir, \".next\"))) &&\n\t\t\t\t\t!(await pathExists(path.join(currentDir, \"package.json\")))\n\t\t\t\t) {\n\t\t\t\t\tif (currentDir === path.resolve(\"/\")) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrentDir = path.join(currentDir, \"..\");\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\t(await pathExists(path.join(currentDir, \".next\"))) ||\n\t\t\t\t\t(await pathExists(path.join(currentDir, \"package.json\")))\n\t\t\t\t) {\n\t\t\t\t\treturn currentDir;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst appRootDir = await getAppRootDir();\n\n\t\t\tif (!appRootDir) {\n\t\t\t\twarn(\n\t\t\t\t\t\"Could not find the Next.js app root. Run `prismic-next clear-cache` in a Next.js project with a `.next` directory or `package.json` file.\",\n\t\t\t\t);\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst fetchCacheDir = path.join(\n\t\t\t\tappRootDir,\n\t\t\t\t\".next\",\n\t\t\t\t\"cache\",\n\t\t\t\t\"fetch-cache\",\n\t\t\t);\n\n\t\t\tif (!(await pathExists(fetchCacheDir))) {\n\t\t\t\tinfo(\"No Next.js fetch cache directory found. You are good to go!\");\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst cacheEntries = await fs.readdir(fetchCacheDir);\n\n\t\t\tawait Promise.all(\n\t\t\t\tcacheEntries.map(async (entry) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst contents = await fs.readFile(\n\t\t\t\t\t\t\tpath.join(fetchCacheDir, entry),\n\t\t\t\t\t\t\t\"utf8\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst payload = JSON.parse(contents);\n\n\t\t\t\t\t\tif (payload.kind !== \"FETCH\") {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst bodyPayload = JSON.parse(\n\t\t\t\t\t\t\tBuffer.from(payload.data.body, \"base64\").toString(),\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\t// Delete `/api/v2` requests.\n\t\t\t\t\t\tif (/\\.prismic\\.io\\/auth$/.test(bodyPayload.oauth_initiate)) {\n\t\t\t\t\t\t\tawait fs.unlink(path.join(fetchCacheDir, entry));\n\n\t\t\t\t\t\t\tinfo(`Prismic /api/v2 request cache cleared: ${entry}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t// noop\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t);\n\n\t\t\tinfo(\n\t\t\t\t\"The Prismic request cache has been cleared. Uncached requests will begin on the next Next.js server start-up.\",\n\t\t\t);\n\n\t\t\treturn;\n\t\t}\n\n\t\tdefault: {\n\t\t\tif (command && (!args.version || !args.help)) {\n\t\t\t\twarn(\"Invalid command.\\n\");\n\t\t\t}\n\n\t\t\tif (args.version) {\n\t\t\t\tconsole.info(pkg.version);\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconsole.info(\n\t\t\t\t`\nUsage:\n prismic-next <command> [options...]\nAvailable commands:\n clear-cache\nOptions:\n --help, -h Show help text\n --version, -v Show version\n`.trim(),\n\t\t\t);\n\t\t}\n\t}\n}\n"],"names":["pkg.version"],"mappings":";;;;;;AAQA,eAAe,WAAW,UAAgB;AACrC,MAAA;AACG,UAAA,GAAG,OAAO,QAAQ;AAEjB,WAAA;AAAA,EAAA,QACN;AACM,WAAA;AAAA,EACP;AACF;AAEA,SAAS,MAAM,WAAmB,QAAc;AACxC,SAAA,IAAI,YAAY,UAAU,cAC9B,UAAY,YAAY,MAAM,SAAS,aACvC;AACJ;AAEA,SAAS,KAAK,QAAc;AAE3B,SAAO,QAAQ,KAAK,KAAK,MAAM,IAAI,MAAM,KAAK,QAAQ;AACvD;AAEA,SAAS,KAAK,QAAc;AAE3B,SAAO,QAAQ,KAAK,KAAK,MAAM,IAAI,MAAM,KAAK,QAAQ;AACvD;AAOA,eAAsB,IAAI,MAAc;AACvC,QAAM,OAAO,IAAU,KAAK,MAAM,CAAC,GAAG;AAAA,IACrC,SAAS,CAAC,QAAQ,SAAS;AAAA,IAC3B,OAAO;AAAA,MACN,MAAM;AAAA,MACN,SAAS;AAAA,IACT;AAAA,IACD,SAAS;AAAA,MACR,MAAM;AAAA,MACN,SAAS;AAAA,IACT;AAAA,EAAA,CACD;AAEK,QAAA,UAAU,KAAK,EAAE,CAAC;AAExB,UAAQ,SAAS;AAAA,IAChB,KAAK,eAAe;AACnB,WACC,oHAAoH;AAGrH,qBAAe,gBAAa;AACvB,YAAA,aAAa,QAAQ;AAEzB,eACC,CAAE,MAAM,WAAW,KAAK,KAAK,YAAY,OAAO,CAAC,KACjD,CAAE,MAAM,WAAW,KAAK,KAAK,YAAY,cAAc,CAAC,GACvD;AACD,cAAI,eAAe,KAAK,QAAQ,GAAG,GAAG;AACrC;AAAA,UACA;AAEY,uBAAA,KAAK,KAAK,YAAY,IAAI;AAAA,QACvC;AAED,YACE,MAAM,WAAW,KAAK,KAAK,YAAY,OAAO,CAAC,KAC/C,MAAM,WAAW,KAAK,KAAK,YAAY,cAAc,CAAC,GACtD;AACM,iBAAA;AAAA,QACP;AAAA,MACF;AAEM,YAAA,aAAa,MAAM;AAEzB,UAAI,CAAC,YAAY;AAChB,aACC,2IAA2I;AAG5I;AAAA,MACA;AAED,YAAM,gBAAgB,KAAK,KAC1B,YACA,SACA,SACA,aAAa;AAGd,UAAI,CAAE,MAAM,WAAW,aAAa,GAAI;AACvC,aAAK,6DAA6D;AAElE;AAAA,MACA;AAED,YAAM,eAAe,MAAM,GAAG,QAAQ,aAAa;AAEnD,YAAM,QAAQ,IACb,aAAa,IAAI,OAAO,UAAS;AAC5B,YAAA;AACG,gBAAA,WAAW,MAAM,GAAG,SACzB,KAAK,KAAK,eAAe,KAAK,GAC9B,MAAM;AAED,gBAAA,UAAU,KAAK,MAAM,QAAQ;AAE/B,cAAA,QAAQ,SAAS,SAAS;AAC7B;AAAA,UACA;AAEK,gBAAA,cAAc,KAAK,MACxB,OAAO,KAAK,QAAQ,KAAK,MAAM,QAAQ,EAAE,SAAU,CAAA;AAIpD,cAAI,uBAAuB,KAAK,YAAY,cAAc,GAAG;AAC5D,kBAAM,GAAG,OAAO,KAAK,KAAK,eAAe,KAAK,CAAC;AAE/C,iBAAK,0CAA0C,OAAO;AAAA,UACtD;AAAA,iBACO;QAER;AAAA,MACD,CAAA,CAAC;AAGH,WACC,+GAA+G;AAGhH;AAAA,IACA;AAAA,IAED,SAAS;AACR,UAAI,YAAY,CAAC,KAAK,WAAW,CAAC,KAAK,OAAO;AAC7C,aAAK,oBAAoB;AAAA,MACzB;AAED,UAAI,KAAK,SAAS;AACT,gBAAA,KAAKA,OAAW;AAExB;AAAA,MACA;AAED,cAAQ,KACP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQF,KAAM,CAAA;AAAA,IAEL;AAAA,EACD;AACF;"}
@@ -2,9 +2,12 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const headers = require("next/headers");
4
4
  const cookie = require('./_node_modules/@prismicio/client/dist/cookie.cjs');
5
+ const isPrismicPreviewData = (input) => {
6
+ return typeof input === "object" && input !== null && "ref" in input;
7
+ };
5
8
  const enableAutoPreviews = (config) => {
6
9
  if ("previewData" in config && config.previewData) {
7
- if (typeof config.previewData === "object" && "ref" in config.previewData && typeof config.previewData.ref === "string") {
10
+ if (isPrismicPreviewData(config.previewData)) {
8
11
  config.client.queryContentFromRef(config.previewData.ref);
9
12
  }
10
13
  } else if ("req" in config && config.req) {
@@ -1 +1 @@
1
- {"version":3,"file":"enableAutoPreviews.cjs","sources":["../../src/enableAutoPreviews.ts"],"sourcesContent":["import { PreviewData } from \"next\";\nimport { cookies } from \"next/headers\";\nimport * as prismic from \"@prismicio/client\";\n\nimport { NextApiRequestLike } from \"./types\";\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\t// `Pick` is used to use the smallest possible subset of\n\t// `prismic.Client`. Doing this reduces the surface area for breaking\n\t// type changes.\n\tclient: Pick<\n\t\tprismic.Client,\n\t\t\"queryContentFromRef\" | \"enableAutoPreviewsFromReq\"\n\t>;\n\n\t/**\n\t * **Only used in the Pages Directory (/pages).**\n\t *\n\t * The `previewData` object provided in the `getStaticProps()` or\n\t * `getServerSideProps()` context object.\n\t */\n\tpreviewData?: TPreviewData;\n\n\t/**\n\t * **Only used in the Pages Directory (/pages).**\n\t *\n\t * The `req` object from a Next.js API route.\n\t *\n\t * @see Next.js API route docs: \\<https://nextjs.org/docs/api-routes/introduction\\>\n\t */\n\treq?: NextApiRequestLike;\n};\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// Assume we are in `getStaticProps()` or\n\t\t// `getServerSideProps()` with active Preview Mode (`pages`\n\t\t// directory).\n\n\t\tif (\n\t\t\ttypeof config.previewData === \"object\" &&\n\t\t\t\"ref\" in config.previewData &&\n\t\t\ttypeof config.previewData.ref === \"string\"\n\t\t) {\n\t\t\tconfig.client.queryContentFromRef(config.previewData.ref);\n\t\t}\n\t} else if (\"req\" in config && config.req) {\n\t\t// Assume we are in an API Route (`pages` directory).\n\n\t\tconfig.client.enableAutoPreviewsFromReq(config.req);\n\t} else {\n\t\t// Assume we are in App Router (`app` directory) OR\n\t\t// `getStaticProps()`/`getServerSideProps()` with an inactive\n\t\t// Preview Mode (`pages` directory).\n\n\t\t// We use a function value so the cookie is checked on every\n\t\t// request. We don't have a static value to read from.\n\t\tconfig.client.queryContentFromRef(() => {\n\t\t\tlet cookie: string | undefined;\n\t\t\ttry {\n\t\t\t\tcookie = cookies().get(prismic.cookie.preview)?.value;\n\t\t\t} catch {\n\t\t\t\t// noop - We are probably in\n\t\t\t\t// `getStaticProps()` or `getServerSideProps()`\n\t\t\t\t// with inactive Preview Mode where `cookies()`\n\t\t\t\t// does not work. We don't need to do any\n\t\t\t\t// preview handling.\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// We are probably in App Router (`app` directory).\n\n\t\t\t// We only return the cookie if a Prismic Preview session is active.\n\t\t\t//\n\t\t\t// An inactive cookie looks like this (URL encoded):\n\t\t\t// \t{\n\t\t\t// \t\t\"_tracker\": \"abc123\"\n\t\t\t// \t}\n\t\t\t//\n\t\t\t// An active cookie looks like this (URL encoded):\n\t\t\t// \t{\n\t\t\t// \t\t\"_tracker\": \"abc123\",\n\t\t\t// \t\t\"example-prismic-repo.prismic.io\": {\n\t\t\t// \t\t\tpreview: \"https://example-prismic-repo.prismic.io/previews/abc:123?websitePreviewId=xyz\"\n\t\t\t// \t\t}\n\t\t\t// \t}\n\t\t\tif (cookie && /\\.prismic\\.io/.test(cookie)) {\n\t\t\t\treturn cookie;\n\t\t\t}\n\t\t});\n\t}\n};\n"],"names":["cookie","cookies","prismic.cookie.preview"],"mappings":";;;;AAkDa,MAAA,qBAAqB,CACjC,WACS;AACL,MAAA,iBAAiB,UAAU,OAAO,aAAa;AAMjD,QAAA,OAAO,OAAO,gBAAgB,YAC9B,SAAS,OAAO,eAChB,OAAO,OAAO,YAAY,QAAQ,UACjC;AACD,aAAO,OAAO,oBAAoB,OAAO,YAAY,GAAG;AAAA,IACxD;AAAA,EACS,WAAA,SAAS,UAAU,OAAO,KAAK;AAGlC,WAAA,OAAO,0BAA0B,OAAO,GAAG;AAAA,EAAA,OAC5C;AAOC,WAAA,OAAO,oBAAoB,MAAK;;AAClC,UAAAA;AACA,UAAA;AACHA,oBAASC,aAAAA,QAAU,EAAA,IAAIC,OAAsB,OAAA,MAApCD,mBAAuC;AAAA,MAAA,QAC/C;AAOD;AAAA,MACA;AAkBD,UAAID,YAAU,gBAAgB,KAAKA,QAAM,GAAG;AACpC,eAAAA;AAAAA,MACP;AAAA,IAAA,CACD;AAAA,EACD;AACF;;"}
1
+ {"version":3,"file":"enableAutoPreviews.cjs","sources":["../../src/enableAutoPreviews.ts"],"sourcesContent":["import { PreviewData } from \"next\";\nimport { cookies } from \"next/headers\";\nimport * as prismic from \"@prismicio/client\";\n\nimport { NextApiRequestLike, PrismicPreviewData } from \"./types\";\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\t// `Pick` is used to use the smallest possible subset of\n\t// `prismic.Client`. Doing this reduces the surface area for breaking\n\t// type changes.\n\tclient: Pick<\n\t\tprismic.Client,\n\t\t\"queryContentFromRef\" | \"enableAutoPreviewsFromReq\"\n\t>;\n\n\t/**\n\t * **Only used in the Pages Directory (/pages).**\n\t *\n\t * The `previewData` object provided in the `getStaticProps()` or\n\t * `getServerSideProps()` context object.\n\t */\n\tpreviewData?: TPreviewData;\n\n\t/**\n\t * **Only used in the Pages Directory (/pages).**\n\t *\n\t * The `req` object from a Next.js API route.\n\t *\n\t * @see Next.js API route docs: \\<https://nextjs.org/docs/api-routes/introduction\\>\n\t */\n\treq?: NextApiRequestLike;\n};\n\nconst isPrismicPreviewData = (input: unknown): input is PrismicPreviewData => {\n\treturn typeof input === \"object\" && input !== null && \"ref\" in input;\n};\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// Assume we are in `getStaticProps()` or\n\t\t// `getServerSideProps()` with active Preview Mode (`pages`\n\t\t// directory).\n\n\t\tif (isPrismicPreviewData(config.previewData)) {\n\t\t\tconfig.client.queryContentFromRef(config.previewData.ref);\n\t\t}\n\t} else if (\"req\" in config && config.req) {\n\t\t// Assume we are in an API Route (`pages` directory).\n\n\t\tconfig.client.enableAutoPreviewsFromReq(config.req);\n\t} else {\n\t\t// Assume we are in App Router (`app` directory) OR\n\t\t// `getStaticProps()`/`getServerSideProps()` with an inactive\n\t\t// Preview Mode (`pages` directory).\n\n\t\t// We use a function value so the cookie is checked on every\n\t\t// request. We don't have a static value to read from.\n\t\tconfig.client.queryContentFromRef(() => {\n\t\t\tlet cookie: string | undefined;\n\t\t\ttry {\n\t\t\t\tcookie = cookies().get(prismic.cookie.preview)?.value;\n\t\t\t} catch {\n\t\t\t\t// noop - We are probably in\n\t\t\t\t// `getStaticProps()` or `getServerSideProps()`\n\t\t\t\t// with inactive Preview Mode where `cookies()`\n\t\t\t\t// does not work. We don't need to do any\n\t\t\t\t// preview handling.\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// We are probably in App Router (`app` directory).\n\n\t\t\t// We only return the cookie if a Prismic Preview session is active.\n\t\t\t//\n\t\t\t// An inactive cookie looks like this (URL encoded):\n\t\t\t// \t{\n\t\t\t// \t\t\"_tracker\": \"abc123\"\n\t\t\t// \t}\n\t\t\t//\n\t\t\t// An active cookie looks like this (URL encoded):\n\t\t\t// \t{\n\t\t\t// \t\t\"_tracker\": \"abc123\",\n\t\t\t// \t\t\"example-prismic-repo.prismic.io\": {\n\t\t\t// \t\t\tpreview: \"https://example-prismic-repo.prismic.io/previews/abc:123?websitePreviewId=xyz\"\n\t\t\t// \t\t}\n\t\t\t// \t}\n\t\t\tif (cookie && /\\.prismic\\.io/.test(cookie)) {\n\t\t\t\treturn cookie;\n\t\t\t}\n\t\t});\n\t}\n};\n"],"names":["cookie","cookies","prismic.cookie.preview"],"mappings":";;;;AA2CA,MAAM,uBAAuB,CAAC,UAA+C;AAC5E,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,SAAS;AAChE;AASa,MAAA,qBAAqB,CACjC,WACS;AACL,MAAA,iBAAiB,UAAU,OAAO,aAAa;AAK9C,QAAA,qBAAqB,OAAO,WAAW,GAAG;AAC7C,aAAO,OAAO,oBAAoB,OAAO,YAAY,GAAG;AAAA,IACxD;AAAA,EACS,WAAA,SAAS,UAAU,OAAO,KAAK;AAGlC,WAAA,OAAO,0BAA0B,OAAO,GAAG;AAAA,EAAA,OAC5C;AAOC,WAAA,OAAO,oBAAoB,MAAK;;AAClC,UAAAA;AACA,UAAA;AACHA,oBAASC,aAAAA,QAAU,EAAA,IAAIC,OAAsB,OAAA,MAApCD,mBAAuC;AAAA,MAAA,QAC/C;AAOD;AAAA,MACA;AAkBD,UAAID,YAAU,gBAAgB,KAAKA,QAAM,GAAG;AACpC,eAAAA;AAAAA,MACP;AAAA,IAAA,CACD;AAAA,EACD;AACF;;"}
@@ -6,7 +6,7 @@ import { NextApiRequestLike } from "./types";
6
6
  *
7
7
  * @typeParam TPreviewData - Next.js preview data object.
8
8
  */
9
- export type EnableAutoPreviewsConfig<TPreviewData extends PreviewData = PreviewData> = {
9
+ export declare type EnableAutoPreviewsConfig<TPreviewData extends PreviewData = PreviewData> = {
10
10
  /**
11
11
  * Prismic client with which automatic previews will be enabled.
12
12
  */
@@ -1,8 +1,11 @@
1
1
  import { cookies } from "next/headers";
2
2
  import { preview } from './_node_modules/@prismicio/client/dist/cookie.js';
3
+ const isPrismicPreviewData = (input) => {
4
+ return typeof input === "object" && input !== null && "ref" in input;
5
+ };
3
6
  const enableAutoPreviews = (config) => {
4
7
  if ("previewData" in config && config.previewData) {
5
- if (typeof config.previewData === "object" && "ref" in config.previewData && typeof config.previewData.ref === "string") {
8
+ if (isPrismicPreviewData(config.previewData)) {
6
9
  config.client.queryContentFromRef(config.previewData.ref);
7
10
  }
8
11
  } else if ("req" in config && config.req) {
@@ -1 +1 @@
1
- {"version":3,"file":"enableAutoPreviews.js","sources":["../../src/enableAutoPreviews.ts"],"sourcesContent":["import { PreviewData } from \"next\";\nimport { cookies } from \"next/headers\";\nimport * as prismic from \"@prismicio/client\";\n\nimport { NextApiRequestLike } from \"./types\";\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\t// `Pick` is used to use the smallest possible subset of\n\t// `prismic.Client`. Doing this reduces the surface area for breaking\n\t// type changes.\n\tclient: Pick<\n\t\tprismic.Client,\n\t\t\"queryContentFromRef\" | \"enableAutoPreviewsFromReq\"\n\t>;\n\n\t/**\n\t * **Only used in the Pages Directory (/pages).**\n\t *\n\t * The `previewData` object provided in the `getStaticProps()` or\n\t * `getServerSideProps()` context object.\n\t */\n\tpreviewData?: TPreviewData;\n\n\t/**\n\t * **Only used in the Pages Directory (/pages).**\n\t *\n\t * The `req` object from a Next.js API route.\n\t *\n\t * @see Next.js API route docs: \\<https://nextjs.org/docs/api-routes/introduction\\>\n\t */\n\treq?: NextApiRequestLike;\n};\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// Assume we are in `getStaticProps()` or\n\t\t// `getServerSideProps()` with active Preview Mode (`pages`\n\t\t// directory).\n\n\t\tif (\n\t\t\ttypeof config.previewData === \"object\" &&\n\t\t\t\"ref\" in config.previewData &&\n\t\t\ttypeof config.previewData.ref === \"string\"\n\t\t) {\n\t\t\tconfig.client.queryContentFromRef(config.previewData.ref);\n\t\t}\n\t} else if (\"req\" in config && config.req) {\n\t\t// Assume we are in an API Route (`pages` directory).\n\n\t\tconfig.client.enableAutoPreviewsFromReq(config.req);\n\t} else {\n\t\t// Assume we are in App Router (`app` directory) OR\n\t\t// `getStaticProps()`/`getServerSideProps()` with an inactive\n\t\t// Preview Mode (`pages` directory).\n\n\t\t// We use a function value so the cookie is checked on every\n\t\t// request. We don't have a static value to read from.\n\t\tconfig.client.queryContentFromRef(() => {\n\t\t\tlet cookie: string | undefined;\n\t\t\ttry {\n\t\t\t\tcookie = cookies().get(prismic.cookie.preview)?.value;\n\t\t\t} catch {\n\t\t\t\t// noop - We are probably in\n\t\t\t\t// `getStaticProps()` or `getServerSideProps()`\n\t\t\t\t// with inactive Preview Mode where `cookies()`\n\t\t\t\t// does not work. We don't need to do any\n\t\t\t\t// preview handling.\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// We are probably in App Router (`app` directory).\n\n\t\t\t// We only return the cookie if a Prismic Preview session is active.\n\t\t\t//\n\t\t\t// An inactive cookie looks like this (URL encoded):\n\t\t\t// \t{\n\t\t\t// \t\t\"_tracker\": \"abc123\"\n\t\t\t// \t}\n\t\t\t//\n\t\t\t// An active cookie looks like this (URL encoded):\n\t\t\t// \t{\n\t\t\t// \t\t\"_tracker\": \"abc123\",\n\t\t\t// \t\t\"example-prismic-repo.prismic.io\": {\n\t\t\t// \t\t\tpreview: \"https://example-prismic-repo.prismic.io/previews/abc:123?websitePreviewId=xyz\"\n\t\t\t// \t\t}\n\t\t\t// \t}\n\t\t\tif (cookie && /\\.prismic\\.io/.test(cookie)) {\n\t\t\t\treturn cookie;\n\t\t\t}\n\t\t});\n\t}\n};\n"],"names":["prismic.cookie.preview"],"mappings":";;AAkDa,MAAA,qBAAqB,CACjC,WACS;AACL,MAAA,iBAAiB,UAAU,OAAO,aAAa;AAMjD,QAAA,OAAO,OAAO,gBAAgB,YAC9B,SAAS,OAAO,eAChB,OAAO,OAAO,YAAY,QAAQ,UACjC;AACD,aAAO,OAAO,oBAAoB,OAAO,YAAY,GAAG;AAAA,IACxD;AAAA,EACS,WAAA,SAAS,UAAU,OAAO,KAAK;AAGlC,WAAA,OAAO,0BAA0B,OAAO,GAAG;AAAA,EAAA,OAC5C;AAOC,WAAA,OAAO,oBAAoB,MAAK;;AAClC,UAAA;AACA,UAAA;AACH,kBAAS,aAAU,EAAA,IAAIA,OAAsB,MAApC,mBAAuC;AAAA,MAAA,QAC/C;AAOD;AAAA,MACA;AAkBD,UAAI,UAAU,gBAAgB,KAAK,MAAM,GAAG;AACpC,eAAA;AAAA,MACP;AAAA,IAAA,CACD;AAAA,EACD;AACF;"}
1
+ {"version":3,"file":"enableAutoPreviews.js","sources":["../../src/enableAutoPreviews.ts"],"sourcesContent":["import { PreviewData } from \"next\";\nimport { cookies } from \"next/headers\";\nimport * as prismic from \"@prismicio/client\";\n\nimport { NextApiRequestLike, PrismicPreviewData } from \"./types\";\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\t// `Pick` is used to use the smallest possible subset of\n\t// `prismic.Client`. Doing this reduces the surface area for breaking\n\t// type changes.\n\tclient: Pick<\n\t\tprismic.Client,\n\t\t\"queryContentFromRef\" | \"enableAutoPreviewsFromReq\"\n\t>;\n\n\t/**\n\t * **Only used in the Pages Directory (/pages).**\n\t *\n\t * The `previewData` object provided in the `getStaticProps()` or\n\t * `getServerSideProps()` context object.\n\t */\n\tpreviewData?: TPreviewData;\n\n\t/**\n\t * **Only used in the Pages Directory (/pages).**\n\t *\n\t * The `req` object from a Next.js API route.\n\t *\n\t * @see Next.js API route docs: \\<https://nextjs.org/docs/api-routes/introduction\\>\n\t */\n\treq?: NextApiRequestLike;\n};\n\nconst isPrismicPreviewData = (input: unknown): input is PrismicPreviewData => {\n\treturn typeof input === \"object\" && input !== null && \"ref\" in input;\n};\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// Assume we are in `getStaticProps()` or\n\t\t// `getServerSideProps()` with active Preview Mode (`pages`\n\t\t// directory).\n\n\t\tif (isPrismicPreviewData(config.previewData)) {\n\t\t\tconfig.client.queryContentFromRef(config.previewData.ref);\n\t\t}\n\t} else if (\"req\" in config && config.req) {\n\t\t// Assume we are in an API Route (`pages` directory).\n\n\t\tconfig.client.enableAutoPreviewsFromReq(config.req);\n\t} else {\n\t\t// Assume we are in App Router (`app` directory) OR\n\t\t// `getStaticProps()`/`getServerSideProps()` with an inactive\n\t\t// Preview Mode (`pages` directory).\n\n\t\t// We use a function value so the cookie is checked on every\n\t\t// request. We don't have a static value to read from.\n\t\tconfig.client.queryContentFromRef(() => {\n\t\t\tlet cookie: string | undefined;\n\t\t\ttry {\n\t\t\t\tcookie = cookies().get(prismic.cookie.preview)?.value;\n\t\t\t} catch {\n\t\t\t\t// noop - We are probably in\n\t\t\t\t// `getStaticProps()` or `getServerSideProps()`\n\t\t\t\t// with inactive Preview Mode where `cookies()`\n\t\t\t\t// does not work. We don't need to do any\n\t\t\t\t// preview handling.\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// We are probably in App Router (`app` directory).\n\n\t\t\t// We only return the cookie if a Prismic Preview session is active.\n\t\t\t//\n\t\t\t// An inactive cookie looks like this (URL encoded):\n\t\t\t// \t{\n\t\t\t// \t\t\"_tracker\": \"abc123\"\n\t\t\t// \t}\n\t\t\t//\n\t\t\t// An active cookie looks like this (URL encoded):\n\t\t\t// \t{\n\t\t\t// \t\t\"_tracker\": \"abc123\",\n\t\t\t// \t\t\"example-prismic-repo.prismic.io\": {\n\t\t\t// \t\t\tpreview: \"https://example-prismic-repo.prismic.io/previews/abc:123?websitePreviewId=xyz\"\n\t\t\t// \t\t}\n\t\t\t// \t}\n\t\t\tif (cookie && /\\.prismic\\.io/.test(cookie)) {\n\t\t\t\treturn cookie;\n\t\t\t}\n\t\t});\n\t}\n};\n"],"names":["prismic.cookie.preview"],"mappings":";;AA2CA,MAAM,uBAAuB,CAAC,UAA+C;AAC5E,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,SAAS;AAChE;AASa,MAAA,qBAAqB,CACjC,WACS;AACL,MAAA,iBAAiB,UAAU,OAAO,aAAa;AAK9C,QAAA,qBAAqB,OAAO,WAAW,GAAG;AAC7C,aAAO,OAAO,oBAAoB,OAAO,YAAY,GAAG;AAAA,IACxD;AAAA,EACS,WAAA,SAAS,UAAU,OAAO,KAAK;AAGlC,WAAA,OAAO,0BAA0B,OAAO,GAAG;AAAA,EAAA,OAC5C;AAOC,WAAA,OAAO,oBAAoB,MAAK;;AAClC,UAAA;AACA,UAAA;AACH,kBAAS,aAAU,EAAA,IAAIA,OAAsB,MAApC,mBAAuC;AAAA,MAAA,QAC/C;AAOD;AAAA,MACA;AAkBD,UAAI,UAAU,gBAAgB,KAAK,MAAM,GAAG;AACpC,eAAA;AAAA,MACP;AAAA,IAAA,CACD;AAAA,EACD;AACF;"}
@@ -3,7 +3,7 @@ import { NextApiRequestLike, NextApiResponseLike } from "./types";
3
3
  /**
4
4
  * Configuration for `exitPreview`.
5
5
  */
6
- export type ExitPreviewConfig = {
6
+ export declare type ExitPreviewConfig = {
7
7
  /**
8
8
  * The `req` object from a Next.js API route.
9
9
  *
package/dist/index.d.ts CHANGED
@@ -13,4 +13,4 @@ export type { RedirectToPreviewURLConfig } from "./redirectToPreviewURL";
13
13
  export { PrismicNextImage } from "./PrismicNextImage";
14
14
  export type { PrismicNextImageProps } from "./PrismicNextImage";
15
15
  export { imgixLoader } from "./imgixLoader";
16
- export type { CreateClientConfig } from "./types";
16
+ export type { CreateClientConfig, PrismicPreviewData } from "./types";
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const version = "1.1.0";
3
+ const version = "1.2.1";
4
4
  exports.version = version;
5
5
  //# sourceMappingURL=package.json.cjs.map
@@ -1,4 +1,4 @@
1
- const version = "1.1.0";
1
+ const version = "1.2.1";
2
2
  export {
3
3
  version
4
4
  };
@@ -3,7 +3,7 @@ import { NextApiRequestLike, NextApiResponseLike, NextRequestLike } from "./type
3
3
  /**
4
4
  * Preview config for enabling previews with redirectToPreviewURL
5
5
  */
6
- export type RedirectToPreviewURLConfig = ({
6
+ export declare type RedirectToPreviewURLConfig = ({
7
7
  /**
8
8
  * The `request` object from a Next.js Route Handler.
9
9
  *
@@ -2,7 +2,7 @@ import { NextApiRequestLike, NextApiResponseLike } from "./types";
2
2
  /**
3
3
  * Configuration for `setPreviewData`.
4
4
  */
5
- export type SetPreviewDataConfig = {
5
+ export declare type SetPreviewDataConfig = {
6
6
  /**
7
7
  * The `req` object from a Next.js API route.
8
8
  *
package/dist/types.d.ts CHANGED
@@ -5,11 +5,17 @@ declare module "@prismicio/client" {
5
5
  next?: RequestInit["next"];
6
6
  }
7
7
  }
8
+ /**
9
+ * Prismic data saved in Next.js Preview Mode's object.
10
+ */
11
+ export declare type PrismicPreviewData = {
12
+ ref: string;
13
+ };
8
14
  /**
9
15
  * Configuration for creating a Prismic client with automatic preview support in
10
16
  * Next.js apps.
11
17
  */
12
- export type CreateClientConfig = ClientConfig & {
18
+ export declare type CreateClientConfig = ClientConfig & {
13
19
  /**
14
20
  * **Only used in the Pages Directory (/pages).**
15
21
  *
@@ -32,7 +38,7 @@ export type CreateClientConfig = ClientConfig & {
32
38
  * This request type is only compatible with Route Handlers defined in the `app`
33
39
  * directory.
34
40
  */
35
- export type NextRequestLike = {
41
+ export declare type NextRequestLike = {
36
42
  headers: {
37
43
  get(name: string): string | null;
38
44
  };
@@ -45,7 +51,7 @@ export type NextRequestLike = {
45
51
  * This request type is only compatible with API routes defined in the `pages`
46
52
  * directory.
47
53
  */
48
- export type NextApiRequestLike = {
54
+ export declare type NextApiRequestLike = {
49
55
  query: Partial<Record<string, string | string[]>>;
50
56
  cookies: Partial<Record<string, string>>;
51
57
  };
@@ -55,7 +61,7 @@ export type NextApiRequestLike = {
55
61
  * This request type is only compatible with API routes defined in the `pages`
56
62
  * directory.
57
63
  */
58
- export type NextApiResponseLike = {
64
+ export declare type NextApiResponseLike = {
59
65
  redirect(url: string): NextApiResponseLike;
60
66
  clearPreviewData(): NextApiResponseLike;
61
67
  status(statusCode: number): NextApiResponseLike;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prismicio/next",
3
- "version": "1.1.0",
3
+ "version": "1.2.1",
4
4
  "description": "Helpers to integrate Prismic into Next.js apps",
5
5
  "keywords": [
6
6
  "typescript",
@@ -18,8 +18,14 @@
18
18
  "sideEffects": false,
19
19
  "exports": {
20
20
  ".": {
21
- "import": "./dist/index.js",
22
- "require": "./dist/index.cjs"
21
+ "require": {
22
+ "types": "./dist/index.d.ts",
23
+ "default": "./dist/index.cjs"
24
+ },
25
+ "import": {
26
+ "types": "./dist/index.d.ts",
27
+ "default": "./dist/index.js"
28
+ }
23
29
  },
24
30
  "./package.json": "./package.json"
25
31
  },
@@ -45,11 +51,15 @@
45
51
  "size": "size-limit",
46
52
  "test": "npm run lint && npm run types && npm run unit && npm run build && npm run size"
47
53
  },
54
+ "bin": {
55
+ "prismic-next": "./bin/prismic-next.js"
56
+ },
48
57
  "dependencies": {
49
- "imgix-url-builder": "^0.0.3"
58
+ "imgix-url-builder": "^0.0.3",
59
+ "mri": "^1.2.0"
50
60
  },
51
61
  "devDependencies": {
52
- "@prismicio/client": "^7.0.0-alpha.3",
62
+ "@prismicio/client": "^7.0.1",
53
63
  "@prismicio/mock": "^0.2.0",
54
64
  "@size-limit/preset-small-lib": "^8.2.4",
55
65
  "@types/react-test-renderer": "^18.0.0",
@@ -64,6 +74,7 @@
64
74
  "eslint-plugin-react-hooks": "^4.6.0",
65
75
  "eslint-plugin-tsdoc": "^0.2.17",
66
76
  "happy-dom": "^9.9.2",
77
+ "memfs": "^3.5.1",
67
78
  "next": "^13.4.0",
68
79
  "node-fetch": "^3.3.1",
69
80
  "prettier": "^2.8.8",
@@ -4,7 +4,6 @@ import Image, { ImageProps } from "next/image";
4
4
  import { buildURL, ImgixURLParams } from "imgix-url-builder";
5
5
  import * as prismic from "@prismicio/client";
6
6
 
7
- import { __PRODUCTION__ } from "./lib/__PRODUCTION__";
8
7
  import { devMsg } from "./lib/devMsg";
9
8
 
10
9
  import { imgixLoader } from "./imgixLoader";
@@ -86,7 +85,7 @@ export const PrismicNextImage = ({
86
85
  fallback = null,
87
86
  ...restProps
88
87
  }: PrismicNextImageProps): JSX.Element => {
89
- if (!__PRODUCTION__) {
88
+ if (process.env.NODE_ENV !== "production") {
90
89
  if (typeof alt === "string" && alt !== "") {
91
90
  console.warn(
92
91
  `[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(
@@ -121,16 +120,27 @@ export const PrismicNextImage = ({
121
120
  resolvedWidth = castedHeight * ar;
122
121
  }
123
122
 
123
+ // A non-null assertion is required since we can't statically
124
+ // know if an alt attribute is available.
125
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
126
+ const resolvedAlt = (alt ?? (field.alt || fallbackAlt))!;
127
+
128
+ if (
129
+ process.env.NODE_ENV !== "production" &&
130
+ typeof resolvedAlt !== "string"
131
+ ) {
132
+ console.error(
133
+ `[PrismicNextImage] The following image is missing an "alt" property. Please add Alternative Text to the image in Prismic. To mark the image as decorative instead, add one of \`alt=""\` or \`fallbackAlt=""\`.`,
134
+ src,
135
+ );
136
+ }
137
+
124
138
  return (
125
139
  <Image
126
140
  src={src}
127
141
  width={fill ? undefined : resolvedWidth}
128
142
  height={fill ? undefined : resolvedHeight}
129
- // A non-null assertion is required since we
130
- // can't statically know if an alt attribute is
131
- // available.
132
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
133
- alt={(alt ?? (field.alt || fallbackAlt))!}
143
+ alt={resolvedAlt}
134
144
  fill={fill}
135
145
  loader={imgixLoader}
136
146
  {...restProps}
@@ -0,0 +1,168 @@
1
+ import mri from "mri";
2
+ import * as path from "node:path";
3
+ import * as fs from "node:fs/promises";
4
+ import * as tty from "node:tty";
5
+ import { Buffer } from "node:buffer";
6
+
7
+ import * as pkg from "../../package.json";
8
+
9
+ async function pathExists(filePath: string) {
10
+ try {
11
+ await fs.access(filePath);
12
+
13
+ return true;
14
+ } catch {
15
+ return false;
16
+ }
17
+ }
18
+
19
+ function color(colorCode: number, string: string) {
20
+ return tty.WriteStream.prototype.hasColors()
21
+ ? "\u001B[" + colorCode + "m" + string + "\u001B[39m"
22
+ : string;
23
+ }
24
+
25
+ function warn(string: string) {
26
+ // Yellow
27
+ return console.warn(`- ${color(33, "warn")} ${string}`);
28
+ }
29
+
30
+ function info(string: string) {
31
+ // Magenta
32
+ return console.info(`- ${color(35, "info")} ${string}`);
33
+ }
34
+
35
+ type Args = {
36
+ help: boolean;
37
+ version: boolean;
38
+ };
39
+
40
+ export async function run(argv: string[]) {
41
+ const args = mri<Args>(argv.slice(2), {
42
+ boolean: ["help", "version"],
43
+ alias: {
44
+ help: "h",
45
+ version: "v",
46
+ },
47
+ default: {
48
+ help: false,
49
+ version: false,
50
+ },
51
+ });
52
+
53
+ const command = args._[0];
54
+
55
+ switch (command) {
56
+ case "clear-cache": {
57
+ warn(
58
+ "`prismic-next clear-cache` is an experimental utility. It may be replaced with a different solution in the future.",
59
+ );
60
+
61
+ async function getAppRootDir() {
62
+ let currentDir = process.cwd();
63
+
64
+ while (
65
+ !(await pathExists(path.join(currentDir, ".next"))) &&
66
+ !(await pathExists(path.join(currentDir, "package.json")))
67
+ ) {
68
+ if (currentDir === path.resolve("/")) {
69
+ break;
70
+ }
71
+
72
+ currentDir = path.join(currentDir, "..");
73
+ }
74
+
75
+ if (
76
+ (await pathExists(path.join(currentDir, ".next"))) ||
77
+ (await pathExists(path.join(currentDir, "package.json")))
78
+ ) {
79
+ return currentDir;
80
+ }
81
+ }
82
+
83
+ const appRootDir = await getAppRootDir();
84
+
85
+ if (!appRootDir) {
86
+ warn(
87
+ "Could not find the Next.js app root. Run `prismic-next clear-cache` in a Next.js project with a `.next` directory or `package.json` file.",
88
+ );
89
+
90
+ return;
91
+ }
92
+
93
+ const fetchCacheDir = path.join(
94
+ appRootDir,
95
+ ".next",
96
+ "cache",
97
+ "fetch-cache",
98
+ );
99
+
100
+ if (!(await pathExists(fetchCacheDir))) {
101
+ info("No Next.js fetch cache directory found. You are good to go!");
102
+
103
+ return;
104
+ }
105
+
106
+ const cacheEntries = await fs.readdir(fetchCacheDir);
107
+
108
+ await Promise.all(
109
+ cacheEntries.map(async (entry) => {
110
+ try {
111
+ const contents = await fs.readFile(
112
+ path.join(fetchCacheDir, entry),
113
+ "utf8",
114
+ );
115
+ const payload = JSON.parse(contents);
116
+
117
+ if (payload.kind !== "FETCH") {
118
+ return;
119
+ }
120
+
121
+ const bodyPayload = JSON.parse(
122
+ Buffer.from(payload.data.body, "base64").toString(),
123
+ );
124
+
125
+ // Delete `/api/v2` requests.
126
+ if (/\.prismic\.io\/auth$/.test(bodyPayload.oauth_initiate)) {
127
+ await fs.unlink(path.join(fetchCacheDir, entry));
128
+
129
+ info(`Prismic /api/v2 request cache cleared: ${entry}`);
130
+ }
131
+ } catch (e) {
132
+ // noop
133
+ }
134
+ }),
135
+ );
136
+
137
+ info(
138
+ "The Prismic request cache has been cleared. Uncached requests will begin on the next Next.js server start-up.",
139
+ );
140
+
141
+ return;
142
+ }
143
+
144
+ default: {
145
+ if (command && (!args.version || !args.help)) {
146
+ warn("Invalid command.\n");
147
+ }
148
+
149
+ if (args.version) {
150
+ console.info(pkg.version);
151
+
152
+ return;
153
+ }
154
+
155
+ console.info(
156
+ `
157
+ Usage:
158
+ prismic-next <command> [options...]
159
+ Available commands:
160
+ clear-cache
161
+ Options:
162
+ --help, -h Show help text
163
+ --version, -v Show version
164
+ `.trim(),
165
+ );
166
+ }
167
+ }
168
+ }
@@ -2,7 +2,7 @@ import { PreviewData } from "next";
2
2
  import { cookies } from "next/headers";
3
3
  import * as prismic from "@prismicio/client";
4
4
 
5
- import { NextApiRequestLike } from "./types";
5
+ import { NextApiRequestLike, PrismicPreviewData } from "./types";
6
6
 
7
7
  /**
8
8
  * Configuration for `enableAutoPreviews`.
@@ -41,6 +41,10 @@ export type EnableAutoPreviewsConfig<
41
41
  req?: NextApiRequestLike;
42
42
  };
43
43
 
44
+ const isPrismicPreviewData = (input: unknown): input is PrismicPreviewData => {
45
+ return typeof input === "object" && input !== null && "ref" in input;
46
+ };
47
+
44
48
  /**
45
49
  * Configures a Prismic client to automatically query draft content during a
46
50
  * preview session. It either takes in a Next.js `getStaticProps` context object
@@ -56,11 +60,7 @@ export const enableAutoPreviews = <TPreviewData extends PreviewData>(
56
60
  // `getServerSideProps()` with active Preview Mode (`pages`
57
61
  // directory).
58
62
 
59
- if (
60
- typeof config.previewData === "object" &&
61
- "ref" in config.previewData &&
62
- typeof config.previewData.ref === "string"
63
- ) {
63
+ if (isPrismicPreviewData(config.previewData)) {
64
64
  config.client.queryContentFromRef(config.previewData.ref);
65
65
  }
66
66
  } else if ("req" in config && config.req) {
package/src/index.ts CHANGED
@@ -21,4 +21,4 @@ export type { PrismicNextImageProps } from "./PrismicNextImage";
21
21
 
22
22
  export { imgixLoader } from "./imgixLoader";
23
23
 
24
- export type { CreateClientConfig } from "./types";
24
+ export type { CreateClientConfig, PrismicPreviewData } from "./types";
package/src/types.ts CHANGED
@@ -8,6 +8,13 @@ declare module "@prismicio/client" {
8
8
  }
9
9
  }
10
10
 
11
+ /**
12
+ * Prismic data saved in Next.js Preview Mode's object.
13
+ */
14
+ export type PrismicPreviewData = {
15
+ ref: string;
16
+ };
17
+
11
18
  /**
12
19
  * Configuration for creating a Prismic client with automatic preview support in
13
20
  * Next.js apps.
@@ -1,5 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const __PRODUCTION__ = process.env.NODE_ENV === "production";
4
- exports.__PRODUCTION__ = __PRODUCTION__;
5
- //# sourceMappingURL=__PRODUCTION__.cjs.map
@@ -1 +0,0 @@
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;;"}
@@ -1,7 +0,0 @@
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;
@@ -1,5 +0,0 @@
1
- const __PRODUCTION__ = process.env.NODE_ENV === "production";
2
- export {
3
- __PRODUCTION__
4
- };
5
- //# sourceMappingURL=__PRODUCTION__.js.map
@@ -1 +0,0 @@
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;"}
@@ -1,7 +0,0 @@
1
- /**
2
- * `true` if in the production environment, `false` otherwise.
3
- *
4
- * This boolean can be used to perform actions only in development environments,
5
- * such as logging.
6
- */
7
- export const __PRODUCTION__ = process.env.NODE_ENV === "production";