# @pantheon-systems/p1-next-sdk

Next.js SDK for the P1 editor. Mounts the editor, its API routes, auth, and published-page
rendering into a Next.js App Router application with a handful of factories.

> Part of Pantheon's **P1** platform. It is published publicly so P1 applications can install
> it, but it talks to Pantheon-hosted services and is not a general-purpose Next.js library.
> Pre-1.0: minor versions may carry breaking changes.

## Install

```bash
npm install @pantheon-systems/p1-next-sdk
```

Peer dependencies:

```bash
npm install @puckeditor/core next react react-dom
```

The fastest way to get a working application is to scaffold one:

```bash
npm create @pantheon-systems/p1-starter-kit my-app
```

## Usage

Mount the API routes in `app/p1/api/[...p1]/route.ts`:

```ts
import { createP1Handler } from "@pantheon-systems/p1-next-sdk/server";
import config from "../../../../puck.config";

const handler = createP1Handler({
  config,
  p1BaseUrl: process.env.NEXT_PUBLIC_CSS_BASE_URL,
  p1ApiKey: process.env.CSS_API_KEY,
  p1SiteId: process.env.NEXT_PUBLIC_CSS_SITE_ID,
});

export const { GET, POST } = handler;
```

And the editor and dashboard pages:

```ts
import { createP1Pages } from "@pantheon-systems/p1-next-sdk/server";
import config from "../../../../puck.config";

export const pages = createP1Pages({
  config,
  p1BaseUrl: process.env.NEXT_PUBLIC_CSS_BASE_URL,
  p1ApiKey: process.env.CSS_API_KEY,
  p1SiteId: process.env.NEXT_PUBLIC_CSS_SITE_ID,
});
```

Client components render inside `P1NextRouterProvider`, which bridges P1 navigation to the
Next.js router.

### AI chatbot

The chatbot is in limited release, and whether it is available to a given site is decided by
Pantheon rather than configured by the application. Return `useP1Chatbot`'s result from the
editor's `useExtensions` slot; there is nothing to branch on. The chat plugin is always in the
list and shows itself only when the chatbot is available, so the editor canvas does not reload
when availability resolves. `pluginOptions` follows availability: while the chatbot is
unavailable it carries no handler and hides the panel toggle.

```tsx
function useEditorExtensions({ openDocument }: P1EditorContext): P1EditorExtensions {
  const chatbot = useP1Chatbot({ onPageCreated: openDocument });

  return {
    plugins: chatbot.plugins,
    pluginOptions: chatbot.pluginOptions,
  };
}

export const EditorClientWrapper = createP1EditorClient({
  puckConfig: config,
  useExtensions: useEditorExtensions,
});
```

There is nothing to configure. Availability is resolved alongside the editor's other
experimental features, in the same single check, so a project adds no environment variables
for the chatbot and changes nothing when the rollout ends. `P1ChatbotProvider` is deprecated
and renders its children unchanged; an existing `wrapEditor` that uses it can be dropped.
`editorKeySuffix` is deprecated and always an empty string; remove it from your extensions.

### Localization

On a site with locales, every page rendered by `createPublishedPage` is wrapped in
`P1LocalizationProvider` and its `<head>` gets `hreflang` alternates for its locale variants. The
alternates are absolute URLs built on `NEXT_PUBLIC_SITE_URL`, emitted only when it is set. A site
with no locales renders exactly as before.

`getDocumentLanguage` gives a root layout the page's locale for `<html lang>`, so the static HTML
carries the page's language. It reads the same page the route renders, so it adds no request. The
layout has to sit above the page route, which means rendering pages from an optional catch-all
(`app/[[...puckPath]]/page.tsx`) with the root layout beside it:

```tsx
// app/[[...puckPath]]/layout.tsx
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL;

// Resolves the page's relative canonical link.
export const metadata: Metadata = siteUrl ? { metadataBase: new URL(siteUrl) } : {};

export default async function SiteLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ puckPath?: string[] }>;
}) {
  const lang = (await published.getDocumentLanguage({ params })) ?? "en";
  return (
    <html lang={lang}>
      <body>{children}</body>
    </html>
  );
}
```

Publishing a route template refreshes the page routes `[...puckPath]` and `[[...puckPath]]`. An app
rendering pages from another segment names it with `publicPageSegment` on `createP1Handler`.

Components below the client read the page's locale and its locale variants with
`useP1Localization`. A language switcher links to each variant and saves the visitor's choice
as the link is followed. A variant with no locale, or one outside the site's locales, has
`locale: null` and needs a label of its own:

```tsx
import { useP1Localization } from "@pantheon-systems/p1-next-sdk";
import { saveLocale } from "@pantheon-systems/p1-next-sdk/localization";

function LanguageSwitcher() {
  const { variants } = useP1Localization();
  return variants.map((v) => (
    <a
      key={v.path}
      href={v.path}
      aria-current={v.current}
      onClick={() => v.locale && saveLocale(v.locale)}
    >
      {v.locale ?? v.path}
    </a>
  ));
}
```

`saveLocale` and `getSavedLocale` keep the visitor's choice in a `p1_locale` cookie that only the
browser reads, so pages stay statically rendered. `getSavedLocaleSuggestion` gives the page's
variant in the saved locale, for a prompt such as "This page is available in Français". Read the
cookie once the page has hydrated, so the server and client renders match:

```tsx
const subscribe = () => () => {};

function useSavedLocale() {
  return useSyncExternalStore(subscribe, getSavedLocale, () => null);
}
```

The framework-independent pieces (`isLocalized`, `getMatchingLocale`, `isSameLocale`,
`resolveVisitorLocale`, the saved-locale cookie helpers, `getLocaleVariants`,
`getHreflangAlternates` and `getSavedLocaleSuggestion`) are in `.../localization` for
sites that render pages their own way. All but the cookie helpers are re-exported from
`@pantheon-systems/css-client/localization`, which a site can import directly.

## Entry points

| Import | Contents |
| --- | --- |
| `@pantheon-systems/p1-next-sdk` | `createP1EditorClient`, `P1NextRouterProvider` and client-side helpers |
| `.../server` | `createP1Handler`, `createP1AuthHandler`, `createP1Pages`, `createP1Middleware`, `createCssQueryFetchers` |
| `.../chatbot` | `useP1Chatbot`, and the deprecated `P1ChatbotProvider` |
| `.../localization` | Locale matching, locale variant, saved-locale cookie and `hreflang` helpers, with no framework dependency |

Transpilation is required, since the P1 packages ship untranspiled ESM:

```js
// next.config.mjs
transpilePackages: [
  "@pantheon-systems/css-client",
  "@pantheon-systems/puck-css",
  "@pantheon-systems/p1-next-sdk",
],
```

## CLI

`p1-next-sdk` dispatches on the first argument:

```bash
npx @pantheon-systems/p1-next-sdk migrate <migration>   # was: npx p1-migrate
npx @pantheon-systems/p1-next-sdk@latest enable-registry
```

### migrate

Updates an existing app's files to what newer P1 packages expect, one migration at a time, on a clean git tree. Run it with no migration to list them:

```bash
npx @pantheon-systems/p1-next-sdk migrate                                   # list the migrations
npx @pantheon-systems/p1-next-sdk migrate localized-pages --dry-run         # preview one
npx @pantheon-systems/p1-next-sdk migrate localized-pages                   # apply it
```

- `editor-layout`: moves the editor into the persistent `app/p1/(editor)/` layout. Guide: `docs/migrations/editor-layout.md`.
- `localized-pages`: serves every published page from `app/[[...puckPath]]/` under a root layout that sets `<html lang>`. Guide: `docs/migrations/localized-pages.md`.
- `locale-prompt`: adds the starter's saved-language prompt to the page client, after `localized-pages`.
- `cache-handler`: adds the starter's cache handler, so a page you take live is purged from the CDN on Pantheon hosting. Guide: `docs/migrations/cache-handler.md`.

Each changes a file only when it matches a scaffolded version; otherwise it stops before writing anything and says what to do by hand. The guides ship in this package, under `node_modules/@pantheon-systems/p1-next-sdk/docs/migrations/`.

### enable-registry

Wires an existing app up to the P1 component registry, so `shadcn add @p1/…` works in a project
scaffolded before the registry existed:

```bash
npx @pantheon-systems/p1-next-sdk@latest enable-registry
```

Keep the `@latest`. With a bare package name, `npx` runs the copy already installed in the project
when there is one, which may be too old to have the command. `pnpm dlx` and `yarn dlx` always fetch
the published version.

It writes `components.json`, creates `components/puck/blocks/index.ts`, adds the `@/*` path alias to
`tsconfig.json`, and adds a `blocks:sync` script to `package.json`. Anything already in place is left
alone, so a second run changes nothing, and a `tsconfig.json` or `package.json` it cannot edit safely
is reported rather than rewritten. It also checks the `@pantheon-systems/p1-next-sdk` installed in the
project and says so when it is older than the first version that has `sync-blocks`, since the script
runs the installed copy. It does not change the dependency, so upgrade it yourself first. Under Yarn
Plug'n'Play the installed version cannot be read, and it says so.

It does not touch `puck.config.tsx`. That file is yours and you have changed it, so the two spreads
to add are printed instead:

```tsx
import { p1Blocks, p1Categories } from "./components/puck/blocks";

categories: { ...p1Categories, /* your own categories after */ },
components: { ...p1Blocks,     /* your own blocks after */ },
```

Both spreads must come first — later keys win in an object literal, so one placed last lets a
registry category overwrite yours, and its blocks stay registered while vanishing from the drawer.

### sync-blocks

Registers the blocks installed from the P1 component registry, so one that is on disk is in the
editor drawer without pasting lines into `components/puck/blocks/index.ts`. Run it through the
project's `blocks:sync` script, which `enable-registry` and the starter template both set up:

```bash
npm run blocks:sync    # or: yarn blocks:sync, pnpm blocks:sync
```

The script is `"blocks:sync": "p1-next-sdk sync-blocks"`, which takes `[dir] [--dry-run | --check]`.

Each `*.block.tsx` under `components/puck/blocks/` is read, never run, with the project's own
`typescript`, so a block that touches `window` or imports something that is not installed reads
fine. The `*Block` export gives the Puck key and the categories come from `meta.categories`; the
part of `index.ts` between the `<p1-blocks:begin>` and `<p1-blocks:end>` markers is rewritten and
nothing outside it is touched. A second run changes nothing, and a barrel a formatter has reflowed
(Prettier line breaks, trailing commas, quotes) is the same code and counts as up to date.

A barrel with no markers is taken over when its `p1Blocks` and `p1Categories` exports are empty,
whatever their formatting or comments. One with registrations of your own is refused and left
alone: move your own blocks into `puck.config.tsx`, delete the import lines for registry blocks, and
either wrap what remains in the markers or delete both exports and run it again.

A block is recognised by an exported const whose name ends in `Block` that is typed
`ComponentConfig<…>` or written as an object with a `render` function. `meta.categories` has to be a
literal array of strings, since it cannot be evaluated without running the file. The command stops
with the file and line when a block cannot be read, has no block export, has more than one, or
registers under the same key as another.

- `--dry-run` shows what would be registered and writes nothing.
- `--check` exits 1 if `index.ts` is out of date and writes nothing, for a CI step.
- To keep an installed block out of the editor, list its directory in `package.json`:
  `"p1": { "blocks": { "exclude": ["pricing"] } }`.
