UNPKG

@prismicio/next

Version:

Helpers to integrate Prismic into Next.js apps

1 lines 2.46 kB
{"version":3,"file":"enableAutoPreviews.cjs","sources":["../src/enableAutoPreviews.ts"],"sourcesContent":["import { type Client, cookie as prismicCookie } from \"@prismicio/client\";\n\n/** Configuration for `enableAutoPreviews`. */\nexport type EnableAutoPreviewsConfig = {\n\t/** Prismic client with which automatic previews will be enabled. */\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<Client, \"queryContentFromRef\" | \"enableAutoPreviewsFromReq\">;\n};\n\n/**\n * Configures a Prismic client to automatically query draft content during a\n * preview session.\n *\n * @param config - Configuration for the function.\n */\nexport function enableAutoPreviews(config: EnableAutoPreviewsConfig): void {\n\t// We use a function value so the cookie is checked on every\n\t// request. We don't have a static value to read from.\n\tconfig.client.queryContentFromRef(async () => {\n\t\t// Need this to avoid the following Next.js build-time error:\n\t\t// You're importing a component that needs next/headers. That only works\n\t\t// in a Server Component which is not supported in the pages/ directory.\n\t\tconst { cookies, draftMode } = await import(\"next/headers\");\n\n\t\tlet isDraftModeEnabled = false;\n\t\ttry {\n\t\t\tisDraftModeEnabled = (await draftMode()).isEnabled;\n\t\t} catch {\n\t\t\t// `draftMode()` may have been called in a palce that\n\t\t\t// does not have access to its async storage. This\n\t\t\t// occurs in places like `generateStaticParams()`. We\n\t\t\t// can ignore this case.\n\t\t\treturn;\n\t\t}\n\t\tif (!isDraftModeEnabled) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst cookie = (await cookies()).get(prismicCookie.preview)?.value;\n\t\tif (!cookie) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst isActiveCookie = cookie.includes(\"websitePreviewId=\");\n\t\tif (!isActiveCookie) {\n\t\t\treturn;\n\t\t}\n\n\t\treturn cookie;\n\t});\n}\n"],"names":["prismicCookie"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAiBM,SAAU,mBAAmB,QAAgC;AAG3D,SAAA,OAAO,oBAAoB,YAAW;;AAI5C,UAAM,EAAE,SAAS,cAAc,MAAM,OAAO,cAAc;AAE1D,QAAI,qBAAqB;AACrB,QAAA;AACmB,4BAAA,MAAM,aAAa;AAAA,IAAA,QAClC;AAKP;AAAA,IAAA;AAED,QAAI,CAAC,oBAAoB;AACxB;AAAA,IAAA;AAGD,UAAM,UAAU,YAAM,QAAA,GAAW,IAAIA,OAAA,OAAc,OAAO,MAA1C,mBAA6C;AAC7D,QAAI,CAAC,QAAQ;AACZ;AAAA,IAAA;AAGK,UAAA,iBAAiB,OAAO,SAAS,mBAAmB;AAC1D,QAAI,CAAC,gBAAgB;AACpB;AAAA,IAAA;AAGM,WAAA;AAAA,EAAA,CACP;AACF;;"}