@prismicio/next 0.1.0 → 0.2.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { NextApiRequest, NextApiResponse, PreviewData } from 'next';
2
+ import * as React from 'react';
2
3
  import { Client, HttpRequestLike } from '@prismicio/client';
3
- import React from 'react';
4
4
  import { LinkResolverFunction } from '@prismicio/helpers';
5
5
 
6
6
  /**
@@ -13,60 +13,19 @@ declare type SetPreviewDataConfig = {
13
13
  *
14
14
  * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
15
15
  */
16
- req: {
17
- query: NextApiRequest["query"];
18
- cookies: NextApiRequest["cookies"];
19
- };
16
+ req: Pick<NextApiRequest, "query" | "cookies">;
20
17
  /**
21
18
  * The `res` object from a Next.js API route. This is given as a parameter to
22
19
  * the API route.
23
20
  *
24
21
  * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
25
22
  */
26
- res: {
27
- setPreviewData: NextApiResponse["setPreviewData"];
28
- };
23
+ res: Pick<NextApiResponse, "setPreviewData">;
29
24
  };
30
25
  /**
31
26
  * Set Prismic preview data for Next.js's Preview Mode.
32
27
  */
33
- declare function setPreviewData({ req, res, }: SetPreviewDataConfig): Promise<void>;
34
-
35
- /**
36
- * Configuration for `enableAutoPreviews`.
37
- *
38
- * @typeParam TPreviewData - Next.js preview data object.
39
- */
40
- declare type EnableAutoPreviewsConfig<TPreviewData extends PreviewData = PreviewData> = {
41
- /**
42
- * Prismic client with which automatic previews will be enabled.
43
- */
44
- client: Client;
45
- } & ({
46
- /**
47
- * A Next.js context object (such as the context object from
48
- * `getStaticProps` or `getServerSideProps`).
49
- *
50
- * Pass a `context` object when using `enableAutoPreviews` outside a
51
- * Next.js API endpoint.
52
- */
53
- previewData?: TPreviewData;
54
- } | {
55
- /**
56
- * A Next.js API endpoint request object.
57
- *
58
- * Pass a `req` object when using `enableAutoPreviews` in a Next.js API endpoint.
59
- */
60
- req?: HttpRequestLike;
61
- });
62
- /**
63
- * Configures a Prismic client to automatically query draft content during a
64
- * preview session. It either takes in a Next.js `getStaticProps` context object
65
- * or a Next.js API endpoint request object.
66
- *
67
- * @param config - Configuration for the function.
68
- */
69
- declare const enableAutoPreviews: <TPreviewData extends PreviewData>(config: EnableAutoPreviewsConfig<TPreviewData>) => void;
28
+ declare function setPreviewData({ req, res }: SetPreviewDataConfig): void;
70
29
 
71
30
  /**
72
31
  * Configuration for `exitPreview`.
@@ -78,27 +37,17 @@ declare type ExitPreviewConfig = {
78
37
  *
79
38
  * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
80
39
  */
81
- req: {
82
- headers: {
83
- referer?: NextApiRequest["headers"]["referer"];
84
- };
85
- };
40
+ req: Pick<NextApiRequest, "headers">;
86
41
  /**
87
42
  * The `res` object from a Next.js API route. This is given as a parameter to
88
43
  * the API route.
89
44
  *
90
45
  * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
91
46
  */
92
- res: {
93
- clearPreviewData: NextApiResponse["clearPreviewData"];
94
- redirect: NextApiResponse["redirect"];
95
- };
47
+ res: Pick<NextApiResponse, "clearPreviewData" | "json">;
96
48
  };
97
49
  /**
98
50
  * Exits Next.js's Preview Mode from within a Next.js API route.
99
- *
100
- * If the user was sent to the endpoint from a page, the user will be redirected
101
- * back to that page after exiting Preview Mode.
102
51
  */
103
52
  declare function exitPreview(config: ExitPreviewConfig): void;
104
53
 
@@ -114,13 +63,23 @@ declare type PrismicPreviewProps = {
114
63
  /**
115
64
  * The URL of your app's Prismic preview endpoint (default: `/api/preview`).
116
65
  * This URL will be fetched on preview update events.
66
+ *
67
+ * **Note**: If your `next.config.js` file contains a `basePath`, it is
68
+ * automatically included.
117
69
  */
118
70
  updatePreviewURL?: string;
119
71
  /**
120
72
  * The URL of your app's exit preview endpoint (default: `/api/exit-preview`).
121
73
  * This URL will be fetched on preview exit events.
74
+ *
75
+ * **Note**: If your `next.config.js` file contains a `basePath`, it is
76
+ * automatically included.
122
77
  */
123
78
  exitPreviewURL?: string;
79
+ /**
80
+ * Children to render adjacent to the Prismic Toolbar. The Prismic Toolbar
81
+ * will be rendered last.
82
+ */
124
83
  children?: React.ReactNode;
125
84
  };
126
85
  /**
@@ -132,55 +91,62 @@ declare type PrismicPreviewProps = {
132
91
  * This component can be wrapped around your app or added anywhere in your app's
133
92
  * tree. It must be rendered on every page.
134
93
  */
135
- declare function PrismicPreview({ repositoryName, children, updatePreviewURL, exitPreviewURL, }: PrismicPreviewProps): JSX.Element;
136
-
137
- /**
138
- * Redirects a user to the URL of a previewed Prismic document from within a
139
- * Next.js API route.
140
- */
141
- declare function redirectToPreviewURL({ req, res, client, linkResolver, defaultURL, }: PreviewConfig): Promise<void>;
94
+ declare function PrismicPreview({ repositoryName, updatePreviewURL, exitPreviewURL, children, }: PrismicPreviewProps): JSX.Element;
142
95
 
143
96
  /**
144
- * Configuration for creating a Prismic client with automatic preview support in
145
- * Next.js apps.
97
+ * Configuration for `enableAutoPreviews`.
98
+ *
99
+ * @typeParam TPreviewData - Next.js preview data object.
146
100
  */
147
- declare type CreateClientConfig = {
101
+ declare type EnableAutoPreviewsConfig<TPreviewData extends PreviewData = PreviewData> = {
148
102
  /**
149
- * Preview data coming from Next.js context object. This context object comes
150
- * from `getStaticProps` or `getServerSideProps`.
103
+ * Prismic client with which automatic previews will be enabled.
104
+ */
105
+ client: Client;
106
+ } & ({
107
+ /**
108
+ * A Next.js context object (such as the context object from
109
+ * `getStaticProps` or `getServerSideProps`).
151
110
  *
152
- * Pass `previewData` when using outside a Next.js API endpoint.
111
+ * Pass a `context` object when using `enableAutoPreviews` outside a
112
+ * Next.js API endpoint.
153
113
  */
154
- previewData?: PreviewData;
114
+ previewData?: TPreviewData;
115
+ } | {
155
116
  /**
156
117
  * A Next.js API endpoint request object.
157
118
  *
158
- * Pass a `req` object when using in a Next.js API endpoint.
119
+ * Pass a `req` object when using `enableAutoPreviews` in a Next.js API endpoint.
159
120
  */
160
- req?: NextApiRequest;
161
- };
121
+ req?: HttpRequestLike;
122
+ });
123
+ /**
124
+ * Configures a Prismic client to automatically query draft content during a
125
+ * preview session. It either takes in a Next.js `getStaticProps` context object
126
+ * or a Next.js API endpoint request object.
127
+ *
128
+ * @param config - Configuration for the function.
129
+ */
130
+ declare const enableAutoPreviews: <TPreviewData extends PreviewData>(config: EnableAutoPreviewsConfig<TPreviewData>) => void;
131
+
162
132
  /**
163
133
  * Preview config for enabling previews with redirectToPreviewURL
164
134
  */
165
- declare type PreviewConfig = {
135
+ declare type RedirectToPreviewURLConfig<TLinkResolverFunction extends LinkResolverFunction<any> = LinkResolverFunction> = {
166
136
  /**
167
137
  * The `req` object from a Next.js API route. This is given as a parameter to
168
138
  * the API route.
169
139
  *
170
140
  * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
171
141
  */
172
- req: {
173
- query: NextApiRequest["query"];
174
- };
142
+ req: Pick<NextApiRequest, "query">;
175
143
  /**
176
144
  * The `res` object from a Next.js API route. This is given as a parameter to
177
145
  * the API route.
178
146
  *
179
147
  * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
180
148
  */
181
- res: {
182
- redirect: NextApiResponse["redirect"];
183
- };
149
+ res: Pick<NextApiResponse, "redirect">;
184
150
  /**
185
151
  * The Prismic client configured for the preview session's repository.
186
152
  */
@@ -190,11 +156,49 @@ declare type PreviewConfig = {
190
156
  *
191
157
  * @see To learn more about Link Resolver: {@link https://prismic.io/docs/core-concepts/link-resolver-route-resolver}
192
158
  */
193
- linkResolver?: LinkResolverFunction;
159
+ linkResolver?: TLinkResolverFunction;
194
160
  /**
195
161
  * The default redirect URL if a URL cannot be determined for the previewed document.
162
+ *
163
+ * **Note**: If your `next.config.js` file contains a `basePath`, you must
164
+ * include the `basePath` as part of this option. `redirectToPreviewURL()`
165
+ * cannot read your global `basePath`.
196
166
  */
197
167
  defaultURL?: string;
168
+ /**
169
+ * The `basePath` for the Next.js app as it is defined in `next.config.js`.
170
+ * This option can be omitted if the app does not have a `basePath`.
171
+ *
172
+ * @remarks
173
+ * The API route is unable to detect the app's `basePath` automatically. It
174
+ * must be provided to `redirectToPreviewURL()` manually.
175
+ */
176
+ basePath?: string;
177
+ };
178
+ /**
179
+ * Redirects a user to the URL of a previewed Prismic document from within a
180
+ * Next.js API route.
181
+ */
182
+ declare function redirectToPreviewURL<TLinkResolverFunction extends LinkResolverFunction<any>>(config: RedirectToPreviewURLConfig<TLinkResolverFunction>): Promise<void>;
183
+
184
+ /**
185
+ * Configuration for creating a Prismic client with automatic preview support in
186
+ * Next.js apps.
187
+ */
188
+ declare type CreateClientConfig = {
189
+ /**
190
+ * Preview data coming from Next.js context object. This context object comes
191
+ * from `getStaticProps` or `getServerSideProps`.
192
+ *
193
+ * Pass `previewData` when using outside a Next.js API endpoint.
194
+ */
195
+ previewData?: PreviewData;
196
+ /**
197
+ * A Next.js API endpoint request object.
198
+ *
199
+ * Pass a `req` object when using in a Next.js API endpoint.
200
+ */
201
+ req?: NextApiRequest;
198
202
  };
199
203
 
200
- export { CreateClientConfig, EnableAutoPreviewsConfig, ExitPreviewConfig as ExitPreviewParams, PreviewConfig, PrismicPreview, SetPreviewDataConfig, enableAutoPreviews, exitPreview, redirectToPreviewURL, setPreviewData };
204
+ export { CreateClientConfig, EnableAutoPreviewsConfig, ExitPreviewConfig, PrismicPreview, PrismicPreviewProps, RedirectToPreviewURLConfig, SetPreviewDataConfig, enableAutoPreviews, exitPreview, redirectToPreviewURL, setPreviewData };
package/dist/index.js ADDED
@@ -0,0 +1,153 @@
1
+ import * as prismic from '@prismicio/client';
2
+ import * as React from 'react';
3
+ import { PrismicToolbar } from '@prismicio/react';
4
+ import { useRouter } from 'next/router';
5
+
6
+ function setPreviewData({ req, res }) {
7
+ const ref = req.query.token || req.cookies[prismic.cookie.preview];
8
+ if (ref) {
9
+ res.setPreviewData({ ref });
10
+ }
11
+ }
12
+
13
+ function exitPreview(config) {
14
+ config.res.clearPreviewData();
15
+ config.res.json({ success: true });
16
+ }
17
+
18
+ const readValue = (value) => {
19
+ return value.replace(/%3B/g, ";");
20
+ };
21
+ const getCookie = (name) => {
22
+ const cookies = document.cookie.split("; ");
23
+ for (const cookie of cookies) {
24
+ const parts = cookie.split("=");
25
+ const value = parts.slice(1).join("=");
26
+ const thisName = readValue(parts[0]).replace(/%3D/g, "=");
27
+ if (thisName === name) {
28
+ return readValue(value);
29
+ }
30
+ }
31
+ };
32
+
33
+ const extractFirstSubdomain = (host) => host.split(".")[0];
34
+ const extractRepositoryNameFromObjectRef = (previewRef) => {
35
+ try {
36
+ const parsed = JSON.parse(decodeURIComponent(previewRef));
37
+ const keys = Object.keys(parsed);
38
+ const domainKey = keys.find((key) => /\.prismic\.io$/.test(key));
39
+ if (domainKey) {
40
+ return extractFirstSubdomain(domainKey);
41
+ } else {
42
+ return void 0;
43
+ }
44
+ } catch (e) {
45
+ return void 0;
46
+ }
47
+ };
48
+ const extractRepositoryNameFromURLRef = (previewRef) => {
49
+ try {
50
+ const url = new URL(previewRef);
51
+ return extractFirstSubdomain(url.host);
52
+ } catch (e) {
53
+ return void 0;
54
+ }
55
+ };
56
+ const extractPreviewRefRepositoryName = (previewRef) => {
57
+ return extractRepositoryNameFromObjectRef(previewRef) || extractRepositoryNameFromURLRef(previewRef);
58
+ };
59
+
60
+ const updatePreviewMode = async (updatePreviewURL) => {
61
+ const res = await globalThis.fetch(updatePreviewURL);
62
+ if (res.ok) {
63
+ window.location.reload();
64
+ } else {
65
+ console.error(`[<PrismicPreview>] Failed to start or update Preview Mode using the "${updatePreviewURL}" API endpoint. Does it exist?`);
66
+ }
67
+ };
68
+ const exitPreviewMode = async (exitPreviewURL) => {
69
+ const res = await globalThis.fetch(exitPreviewURL);
70
+ if (res.ok) {
71
+ window.location.reload();
72
+ } else {
73
+ console.error(`[<PrismicPreview>] Failed to exit Preview Mode using the "${exitPreviewURL}" API endpoint. Does it exist?`);
74
+ }
75
+ };
76
+ function PrismicPreview({
77
+ repositoryName,
78
+ updatePreviewURL = "/api/preview",
79
+ exitPreviewURL = "/api/exit-preview",
80
+ children
81
+ }) {
82
+ const router = useRouter();
83
+ const resolvedUpdatePreviewURL = router.basePath + updatePreviewURL;
84
+ const resolvedExitPreviewURL = router.basePath + exitPreviewURL;
85
+ React.useEffect(() => {
86
+ const previewCookie = getCookie(prismic.cookie.preview);
87
+ const prismicPreviewSessionIsForThisRepo = Boolean(previewCookie && extractPreviewRefRepositoryName(previewCookie) === repositoryName);
88
+ const locationIsDescendantOfBasePath = window.location.href.startsWith(window.location.origin + router.basePath);
89
+ const loadedFromShareLink = !router.isPreview && previewCookie;
90
+ if (prismicPreviewSessionIsForThisRepo && locationIsDescendantOfBasePath && loadedFromShareLink) {
91
+ updatePreviewMode(resolvedUpdatePreviewURL);
92
+ return;
93
+ }
94
+ const handlePrismicPreviewUpdate = async (event) => {
95
+ event.preventDefault();
96
+ await updatePreviewMode(resolvedUpdatePreviewURL);
97
+ };
98
+ const handlePrismicPreviewEnd = async (event) => {
99
+ event.preventDefault();
100
+ await exitPreviewMode(resolvedExitPreviewURL);
101
+ };
102
+ window.addEventListener("prismicPreviewUpdate", handlePrismicPreviewUpdate);
103
+ window.addEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
104
+ return () => {
105
+ window.removeEventListener("prismicPreviewUpdate", handlePrismicPreviewUpdate);
106
+ window.removeEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
107
+ };
108
+ }, [
109
+ repositoryName,
110
+ resolvedUpdatePreviewURL,
111
+ resolvedExitPreviewURL,
112
+ router.isPreview,
113
+ router.basePath
114
+ ]);
115
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, children, /* @__PURE__ */ React.createElement(PrismicToolbar, {
116
+ repositoryName
117
+ }));
118
+ }
119
+
120
+ const isPrismicNextPreviewData = (previewData) => {
121
+ return typeof previewData === "object" && "ref" in previewData;
122
+ };
123
+ const enableAutoPreviews = (config) => {
124
+ if ("previewData" in config && config.previewData) {
125
+ const { previewData } = config;
126
+ if (isPrismicNextPreviewData(previewData) && previewData.ref) {
127
+ config.client.queryContentFromRef(previewData.ref);
128
+ }
129
+ } else if ("req" in config && config.req) {
130
+ config.client.enableAutoPreviewsFromReq(config.req);
131
+ }
132
+ };
133
+
134
+ const isPrismicNextQuery = (query) => {
135
+ return typeof query.documentId === "string" && typeof query.token === "string";
136
+ };
137
+ async function redirectToPreviewURL(config) {
138
+ const defaultURL = config.defaultURL || "/";
139
+ const basePath = config.basePath || "";
140
+ if (isPrismicNextQuery(config.req.query)) {
141
+ const previewUrl = await config.client.resolvePreviewURL({
142
+ linkResolver: config.linkResolver,
143
+ defaultURL,
144
+ documentID: config.req.query.documentId,
145
+ previewToken: config.req.query.token
146
+ });
147
+ config.res.redirect(basePath + previewUrl);
148
+ return;
149
+ }
150
+ config.res.redirect(basePath + defaultURL);
151
+ }
152
+
153
+ export { PrismicPreview, enableAutoPreviews, exitPreview, redirectToPreviewURL, setPreviewData };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@prismicio/next",
3
- "version": "0.1.0",
4
- "description": "Integrate Prismic into a Next.js app",
3
+ "version": "0.2.0-alpha.0",
4
+ "description": "Helpers to integrate Prismic into Next.js apps",
5
5
  "keywords": [
6
6
  "typescript",
7
7
  "prismic",
@@ -15,16 +15,15 @@
15
15
  },
16
16
  "license": "Apache-2.0",
17
17
  "author": "Prismic <contact@prismic.io> (https://prismic.io)",
18
- "type": "module",
19
18
  "exports": {
20
19
  ".": {
21
20
  "require": "./dist/index.cjs",
22
- "import": "./dist/index.mjs"
21
+ "import": "./dist/index.js"
23
22
  },
24
23
  "./package.json": "./package.json"
25
24
  },
26
25
  "main": "./dist/index.cjs",
27
- "module": "dist/index.mjs",
26
+ "module": "dist/index.js",
28
27
  "types": "dist/index.d.ts",
29
28
  "files": [
30
29
  "dist",
@@ -36,50 +35,49 @@
36
35
  "format": "prettier --write .",
37
36
  "lint": "eslint --ext .js,.ts .",
38
37
  "prepare": "npm run build",
39
- "release": "npm run build && npm run test && standard-version && git push --follow-tags && npm run build && npm publish",
40
- "release:alpha": "npm run build && npm run test && standard-version --release-as major --prerelease alpha && git push --follow-tags && npm run build && npm publish --tag alpha",
38
+ "release": "npm run test && standard-version && git push --follow-tags && npm run build && npm publish",
39
+ "release:alpha": "npm run test && standard-version --release-as major --prerelease alpha && git push --follow-tags && npm run build && npm publish --tag alpha",
41
40
  "release:alpha:dry": "standard-version --release-as major --prerelease alpha --dry-run",
42
41
  "release:dry": "standard-version --dry-run",
43
- "test": "npm run lint && npm run unit",
44
- "unit": "nyc --reporter=lcovonly --reporter=text --exclude-after-remap=false ava"
42
+ "size": "size-limit",
43
+ "test": "npm run lint && npm run unit && npm run build && npm run size",
44
+ "unit": "vitest run --coverage",
45
+ "unit:watch": "vitest watch"
45
46
  },
46
47
  "dependencies": {
47
- "@prismicio/react": "^2.0.2"
48
+ "@prismicio/client": "^6.0.0",
49
+ "@prismicio/react": "^2.2.0",
50
+ "@prismicio/types": "^0.1.27"
48
51
  },
49
52
  "devDependencies": {
50
- "@prismicio/client": "^6.0.0-beta.0",
51
- "@prismicio/mock": "^0.0.6",
52
- "@prismicio/types": "^0.1.13",
53
- "@testing-library/react": "^12.1.2",
54
- "@types/jsdom": "^16.2.13",
55
- "@types/jsdom-global": "^3.0.2",
56
- "@types/node-fetch": "^3.0.3",
57
- "@types/sinon": "^10.0.6",
58
- "@typescript-eslint/eslint-plugin": "^4.29.1",
59
- "@typescript-eslint/parser": "^4.29.1",
60
- "ava": "^3.15.0",
61
- "eslint": "^7.32.0",
62
- "eslint-config-prettier": "^8.3.0",
63
- "eslint-plugin-prettier": "^3.4.0",
53
+ "@size-limit/preset-small-lib": "^7.0.8",
54
+ "@types/react-test-renderer": "^17.0.1",
55
+ "@typescript-eslint/eslint-plugin": "^5.17.0",
56
+ "@typescript-eslint/parser": "^5.17.0",
57
+ "c8": "^7.11.0",
58
+ "eslint": "^8.12.0",
59
+ "eslint-config-prettier": "^8.5.0",
60
+ "eslint-plugin-prettier": "^4.0.0",
61
+ "eslint-plugin-react": "^7.29.4",
62
+ "eslint-plugin-react-hooks": "^4.4.0",
64
63
  "eslint-plugin-tsdoc": "^0.2.14",
65
- "jsdom": "^18.1.1",
66
- "jsdom-global": "^3.0.2",
67
- "msw": "^0.35.0",
68
- "node-fetch": "^2.6.6",
64
+ "happy-dom": "^2.55.0",
65
+ "next": "^12.1.4",
69
66
  "nyc": "^15.1.0",
70
- "prettier": "^2.3.2",
71
- "prettier-plugin-jsdoc": "^0.3.30",
72
- "react-test-renderer": "^17.0.2",
73
- "sinon": "^12.0.1",
74
- "siroc": "^0.15.0",
75
- "standard-version": "^9.3.1",
76
- "ts-eager": "^2.0.2",
77
- "typescript": "^4.3.5"
67
+ "prettier": "^2.6.1",
68
+ "prettier-plugin-jsdoc": "^0.3.35",
69
+ "react": "^18.0.0",
70
+ "react-test-renderer": "^18.0.0",
71
+ "siroc": "^0.16.0",
72
+ "size-limit": "^7.0.8",
73
+ "standard-version": "^9.3.2",
74
+ "typescript": "^4.6.3",
75
+ "vitest": "^0.8.1"
78
76
  },
79
77
  "peerDependencies": {
80
- "@prismicio/client": "^6.0.0-beta.0",
78
+ "@prismicio/client": "^6.0.0",
81
79
  "next": "^11 || ^12",
82
- "react": "^17"
80
+ "react": "^17 || ^18"
83
81
  },
84
82
  "engines": {
85
83
  "node": ">=12.7.0"