@pantheon-systems/p1-next-sdk 0.23.0 → 0.25.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.
Files changed (54) hide show
  1. package/README.md +99 -1
  2. package/bin/lib/cli.js +143 -25
  3. package/bin/lib/detect.js +14 -2
  4. package/bin/lib/fs-ops.js +2 -1
  5. package/bin/lib/localized-pages.js +522 -0
  6. package/bin/lib/messages.js +38 -23
  7. package/bin/templates/localized-pages/app/[[...puckPath]]/layout.tsx.template +29 -0
  8. package/bin/templates/localized-pages/app/[[...puckPath]]/page.tsx.template +24 -0
  9. package/bin/templates/localized-pages/app/p1/layout.tsx.template +11 -0
  10. package/bin/templates/localized-pages/components/html-shell.tsx.template +28 -0
  11. package/bin/templates/localized-pages/components/locale-suggestion.module.css.template +74 -0
  12. package/bin/templates/localized-pages/components/locale-suggestion.tsx.template +94 -0
  13. package/bin/templates/localized-pages/legacy/app/[...puckPath]/page.tsx.template +23 -0
  14. package/bin/templates/localized-pages/legacy/app/layout.tsx.template +37 -0
  15. package/bin/templates/localized-pages/legacy/app/layout.v1.tsx.template +27 -0
  16. package/bin/templates/localized-pages/legacy/app/page.tsx.template +19 -0
  17. package/bin/templates/localized-pages/lib/locale-name.ts.template +9 -0
  18. package/dist/chatbot/chatbot-plugin.js +3 -0
  19. package/dist/create-published-page.d.ts +22 -9
  20. package/dist/create-published-page.js +59 -8
  21. package/dist/editor-client/editor-content.js +3 -0
  22. package/dist/editor-client/use-business-account-id.d.ts +5 -0
  23. package/dist/editor-client/use-business-account-id.js +7 -0
  24. package/dist/experimental-features/features.d.ts +16 -5
  25. package/dist/experimental-features/features.js +6 -5
  26. package/dist/experimental-features/resolve-features.d.ts +5 -2
  27. package/dist/experimental-features/resolve-features.js +7 -4
  28. package/dist/experimental-features/session-cache.d.ts +1 -1
  29. package/dist/experimental-features/session-cache.js +2 -2
  30. package/dist/experimental-features/use-p1-experimental-features.d.ts +10 -3
  31. package/dist/experimental-features/use-p1-experimental-features.js +29 -11
  32. package/dist/handler.d.ts +2 -1
  33. package/dist/index.d.ts +1 -0
  34. package/dist/index.js +1 -0
  35. package/dist/localization/index.d.ts +4 -0
  36. package/dist/localization/index.js +3 -0
  37. package/dist/localization/saved-locale.d.ts +13 -0
  38. package/dist/localization/saved-locale.js +20 -0
  39. package/dist/localization-react.d.ts +40 -0
  40. package/dist/localization-react.js +15 -0
  41. package/dist/page-localization.d.ts +12 -0
  42. package/dist/page-localization.js +9 -0
  43. package/dist/pages-handler.js +2 -2
  44. package/dist/routes/publish.d.ts +0 -2
  45. package/dist/routes/publish.js +2 -3
  46. package/dist/routes/revalidate.d.ts +4 -4
  47. package/dist/routes/revalidate.js +10 -4
  48. package/dist/server.d.ts +2 -0
  49. package/dist/server.js +1 -0
  50. package/docs/migrations/editor-layout.md +213 -0
  51. package/docs/migrations/localized-pages.md +208 -0
  52. package/package.json +9 -3
  53. package/dist/chatbot/flag-context.d.ts +0 -15
  54. package/dist/chatbot/flag-context.js +0 -13
package/README.md CHANGED
@@ -91,6 +91,87 @@ for the chatbot and changes nothing when the rollout ends. `P1ChatbotProvider` i
91
91
  and renders its children unchanged; an existing `wrapEditor` that uses it can be dropped.
92
92
  `editorKeySuffix` is deprecated and always an empty string; remove it from your extensions.
93
93
 
94
+ ### Localization
95
+
96
+ On a site with locales, every page rendered by `createPublishedPage` is wrapped in
97
+ `P1LocalizationProvider` and its `<head>` gets `hreflang` alternates for its locale variants. The
98
+ alternates are absolute URLs built on `NEXT_PUBLIC_SITE_URL`, emitted only when it is set. A site
99
+ with no locales renders exactly as before.
100
+
101
+ `getDocumentLanguage` gives a root layout the page's locale for `<html lang>`, so the static HTML
102
+ carries the page's language. It reads the same page the route renders, so it adds no request. The
103
+ layout has to sit above the page route, which means rendering pages from an optional catch-all
104
+ (`app/[[...puckPath]]/page.tsx`) with the root layout beside it:
105
+
106
+ ```tsx
107
+ // app/[[...puckPath]]/layout.tsx
108
+ const siteUrl = process.env.NEXT_PUBLIC_SITE_URL;
109
+
110
+ // Resolves the page's relative canonical link.
111
+ export const metadata: Metadata = siteUrl ? { metadataBase: new URL(siteUrl) } : {};
112
+
113
+ export default async function SiteLayout({
114
+ children,
115
+ params,
116
+ }: {
117
+ children: React.ReactNode;
118
+ params: Promise<{ puckPath?: string[] }>;
119
+ }) {
120
+ const lang = (await published.getDocumentLanguage({ params })) ?? "en";
121
+ return (
122
+ <html lang={lang}>
123
+ <body>{children}</body>
124
+ </html>
125
+ );
126
+ }
127
+ ```
128
+
129
+ Publishing a route template refreshes the page routes `[...puckPath]` and `[[...puckPath]]`. An app
130
+ rendering pages from another segment names it with `publicPageSegment` on `createP1Handler`.
131
+
132
+ Components below the client read the page's locale and its locale variants with
133
+ `useP1Localization`. A language switcher links to each variant and saves the visitor's choice
134
+ as the link is followed. A variant with no locale, or one outside the site's locales, has
135
+ `locale: null` and needs a label of its own:
136
+
137
+ ```tsx
138
+ import { useP1Localization } from "@pantheon-systems/p1-next-sdk";
139
+ import { saveLocale } from "@pantheon-systems/p1-next-sdk/localization";
140
+
141
+ function LanguageSwitcher() {
142
+ const { variants } = useP1Localization();
143
+ return variants.map((v) => (
144
+ <a
145
+ key={v.path}
146
+ href={v.path}
147
+ aria-current={v.current}
148
+ onClick={() => v.locale && saveLocale(v.locale)}
149
+ >
150
+ {v.locale ?? v.path}
151
+ </a>
152
+ ));
153
+ }
154
+ ```
155
+
156
+ `saveLocale` and `getSavedLocale` keep the visitor's choice in a `p1_locale` cookie that only the
157
+ browser reads, so pages stay statically rendered. `getSavedLocaleSuggestion` gives the page's
158
+ variant in the saved locale, for a prompt such as "This page is available in Français". Read the
159
+ cookie once the page has hydrated, so the server and client renders match:
160
+
161
+ ```tsx
162
+ const subscribe = () => () => {};
163
+
164
+ function useSavedLocale() {
165
+ return useSyncExternalStore(subscribe, getSavedLocale, () => null);
166
+ }
167
+ ```
168
+
169
+ The framework-independent pieces (`isLocalized`, `getMatchingLocale`, `isSameLocale`,
170
+ `resolveVisitorLocale`, the saved-locale cookie helpers, `getLocaleVariants`,
171
+ `getHreflangAlternates` and `getSavedLocaleSuggestion`) are in `.../localization` for
172
+ sites that render pages their own way. All but the cookie helpers are re-exported from
173
+ `@pantheon-systems/css-client/localization`, which a site can import directly.
174
+
94
175
  ## Entry points
95
176
 
96
177
  | Import | Contents |
@@ -98,6 +179,7 @@ and renders its children unchanged; an existing `wrapEditor` that uses it can be
98
179
  | `@pantheon-systems/p1-next-sdk` | `createP1EditorClient`, `P1NextRouterProvider` and client-side helpers |
99
180
  | `.../server` | `createP1Handler`, `createP1AuthHandler`, `createP1Pages`, `createP1Middleware`, `createCssQueryFetchers` |
100
181
  | `.../chatbot` | `useP1Chatbot`, and the deprecated `P1ChatbotProvider` |
182
+ | `.../localization` | Locale matching, locale variant, saved-locale cookie and `hreflang` helpers, with no framework dependency |
101
183
 
102
184
  Transpilation is required, since the P1 packages ship untranspiled ESM:
103
185
 
@@ -115,10 +197,26 @@ transpilePackages: [
115
197
  `p1-next-sdk` dispatches on the first argument:
116
198
 
117
199
  ```bash
118
- npx @pantheon-systems/p1-next-sdk migrate # was: npx p1-migrate
200
+ npx @pantheon-systems/p1-next-sdk migrate <migration> # was: npx p1-migrate
119
201
  npx @pantheon-systems/p1-next-sdk@latest enable-registry
120
202
  ```
121
203
 
204
+ ### migrate
205
+
206
+ 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:
207
+
208
+ ```bash
209
+ npx @pantheon-systems/p1-next-sdk migrate # list the migrations
210
+ npx @pantheon-systems/p1-next-sdk migrate localized-pages --dry-run # preview one
211
+ npx @pantheon-systems/p1-next-sdk migrate localized-pages # apply it
212
+ ```
213
+
214
+ - `editor-layout`: moves the editor into the persistent `app/p1/(editor)/` layout. Guide: `docs/migrations/editor-layout.md`.
215
+ - `localized-pages`: serves every published page from `app/[[...puckPath]]/` under a root layout that sets `<html lang>`. Guide: `docs/migrations/localized-pages.md`.
216
+ - `locale-prompt`: adds the starter's saved-language prompt to the page client, after `localized-pages`.
217
+
218
+ 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/`.
219
+
122
220
  ### enable-registry
123
221
 
124
222
  Wires an existing app up to the P1 component registry, so `shadcn add @p1/…` works in a project
package/bin/lib/cli.js CHANGED
@@ -1,5 +1,6 @@
1
1
  /**
2
- * Codemod orchestration.
2
+ * Codemod orchestration. Each migration is a subcommand that detects its own
3
+ * state, so a re-run changes nothing.
3
4
  *
4
5
  * `migrate()` is pure-ish and testable (takes a dir, returns a result, throws
5
6
  * BailError on unrecognized input). `runCLI()` wraps it with argv parsing and
@@ -9,8 +10,16 @@
9
10
  * the app is never left half-migrated.
10
11
  */
11
12
 
12
- import { join, relative } from "node:path";
13
- import { detectApp, assertSuiteVersions, isRouteSpecial } from "./detect.js";
13
+ import { existsSync } from "node:fs";
14
+ import { dirname, join, relative } from "node:path";
15
+ import {
16
+ detectApp,
17
+ assertSuiteVersions,
18
+ isAtLeast,
19
+ isRouteSpecial,
20
+ LOCALIZATION_MIN_VERSION,
21
+ } from "./detect.js";
22
+ import { planLocalePrompt, planLocalizedPages } from "./localized-pages.js";
14
23
  import { assertCleanTree } from "./git.js";
15
24
  import * as fsops from "./fs-ops.js";
16
25
  import * as msg from "./messages.js";
@@ -66,14 +75,11 @@ function partialMessage({ catchAll, p1Dir }, dir) {
66
75
  );
67
76
  }
68
77
 
69
- export async function migrate(opts = {}) {
70
- const dir = opts.dir ?? process.cwd();
71
- const force = opts.force ?? false;
72
- const dryRun = opts.dryRun ?? false;
73
-
78
+ /** Move the editor into the persistent `(editor)` layout. */
79
+ async function migrateEditorLayout(dir, { force, dryRun }) {
74
80
  const app = detectApp(dir);
75
81
  if (app.status === "already-migrated") {
76
- msg.alreadyMigrated();
82
+ msg.alreadyMigrated(MIGRATIONS["editor-layout"].title);
77
83
  return { changed: false };
78
84
  }
79
85
  if (app.status === "not-found") {
@@ -91,7 +97,7 @@ export async function migrate(opts = {}) {
91
97
  // Runs on --dry-run too: a plan the installed suite cannot render is not a
92
98
  // plan worth previewing.
93
99
  const suite = assertSuiteVersions(dir);
94
- if (suite.status === "unverified") msg.versionsUnverified();
100
+ if (suite.status === "unverified") msg.versionsUnverified("editor-layout");
95
101
  // Unverifiable means unverifiable, not old — attempt the step, matching the
96
102
  // clean-tree check's bias toward proceeding.
97
103
  const chatbot = suite.status !== "ok" || suite.chatbot;
@@ -111,45 +117,152 @@ export async function migrate(opts = {}) {
111
117
  const { p1Pages, page } = splitPageFile(fsops.read(join(catchAll, "page.tsx")));
112
118
  const layout = buildLayoutFile();
113
119
 
114
- const writes = [
115
- [join(newCatchAll, "editor-client.tsx"), newEditorClient],
116
- [join(newCatchAll, "p1-pages.tsx"), p1Pages],
117
- [join(newCatchAll, "page.tsx"), page],
118
- [join(editorGroup, "layout.tsx"), layout],
119
- ];
120
+ return apply(dir, "editor-layout", {
121
+ writes: [
122
+ [join(newCatchAll, "editor-client.tsx"), newEditorClient],
123
+ [join(newCatchAll, "p1-pages.tsx"), p1Pages],
124
+ [join(newCatchAll, "page.tsx"), page],
125
+ [join(editorGroup, "layout.tsx"), layout],
126
+ ],
127
+ removes: [catchAll],
128
+ warnings: [],
129
+ }, { dryRun });
130
+ }
131
+
132
+ function findAppDir(dir) {
133
+ const appDir = [join(dir, "app"), join(dir, "src", "app")].find((p) => existsSync(p));
134
+ if (!appDir) {
135
+ throw new BailError(`Could not find an app/ directory under ${dir}. Run this from your project root.`);
136
+ }
137
+ return appDir;
138
+ }
139
+
140
+ /**
141
+ * The localized-pages and locale-prompt migrations. A project with nothing
142
+ * left to do never needs a verifiable install; anything else checks the
143
+ * installed suite before reporting why the plan cannot proceed, since the
144
+ * guide a bail points to ships with the version that check asks for.
145
+ */
146
+ function localizationMigration(planner) {
147
+ return async (dir, { command, force, dryRun }) => {
148
+ const appDir = findAppDir(dir);
149
+ let plan;
150
+ let bail;
151
+ try {
152
+ plan = planner(dir, appDir);
153
+ } catch (err) {
154
+ if (!(err instanceof BailError)) throw err;
155
+ bail = err;
156
+ }
157
+ if (plan && plan.writes.length === 0 && plan.removes.length === 0) {
158
+ for (const warning of plan.warnings) msg.warning(warning);
159
+ msg.alreadyMigrated(MIGRATIONS[command].title);
160
+ return { changed: false };
161
+ }
162
+
163
+ const title = MIGRATIONS[command].title;
164
+ const suite = assertSuiteVersions(dir, { migration: title });
165
+ if (suite.status === "unverified") msg.versionsUnverified(command);
166
+ else if (!isAtLeast(suite.version, LOCALIZATION_MIN_VERSION)) {
167
+ throw new BailError(
168
+ `Installed P1 packages are at ${suite.version}, but ${title} needs ` +
169
+ `${LOCALIZATION_MIN_VERSION} or newer. Upgrade every @pantheon-systems/* dependency ` +
170
+ "together, reinstall, then re-run.",
171
+ );
172
+ }
173
+ if (bail) throw bail;
174
+
175
+ if (!force && !dryRun && assertCleanTree(dir).status === "no-repo") msg.noGitRepo();
176
+ return apply(dir, command, plan, { dryRun });
177
+ };
178
+ }
120
179
 
180
+ /** Write a computed plan, or describe it on --dry-run. */
181
+ function apply(dir, command, { writes, removes, warnings }, { dryRun }) {
121
182
  for (const [path] of writes) fsops.assertWithin(dir, path);
122
- fsops.assertWithin(dir, catchAll);
183
+ for (const path of removes) fsops.assertWithin(dir, path);
184
+ for (const warning of warnings) msg.warning(warning);
185
+
186
+ const shown = {
187
+ command,
188
+ writes: writes.map(([path]) => show(dir, path)),
189
+ removes: removes.map((path) => show(dir, path)),
190
+ };
123
191
 
124
192
  if (dryRun) {
125
- msg.dryRunPlan(writes.map(([path]) => path), catchAll);
193
+ msg.dryRunPlan(shown);
126
194
  return { changed: false, dryRun: true };
127
195
  }
128
196
 
129
- fsops.ensureDir(newCatchAll);
130
- for (const [path, content] of writes) fsops.write(path, content);
131
- fsops.removeDir(catchAll);
197
+ for (const [path, content] of writes) {
198
+ fsops.ensureDir(dirname(path));
199
+ fsops.write(path, content);
200
+ }
201
+ for (const path of removes) fsops.remove(path);
132
202
 
133
- msg.success(writes.map(([path]) => path), catchAll);
203
+ msg.success(shown);
134
204
  return { changed: true };
135
205
  }
136
206
 
207
+ /** The subcommands, in the order a project that needs all of them runs them. */
208
+ export const MIGRATIONS = {
209
+ "editor-layout": {
210
+ title: "the persistent (editor) layout",
211
+ summary: "Move the editor into the persistent app/p1/(editor) layout",
212
+ run: migrateEditorLayout,
213
+ },
214
+ "localized-pages": {
215
+ title: "localized published pages",
216
+ summary: "Serve every published page from app/[[...puckPath]], with <html lang> per page",
217
+ run: localizationMigration(planLocalizedPages),
218
+ },
219
+ "locale-prompt": {
220
+ title: "the saved-language prompt",
221
+ summary: "Add the starter's saved-language prompt to the page client (after localized-pages)",
222
+ run: localizationMigration(planLocalePrompt),
223
+ },
224
+ };
225
+
226
+ function unknownMigration(name) {
227
+ return new BailError(
228
+ `Unknown migration: ${name}. Choose one of: ${Object.keys(MIGRATIONS).join(", ")}.`,
229
+ );
230
+ }
231
+
232
+ export async function migrate(opts = {}) {
233
+ const command = opts.command;
234
+ if (!Object.hasOwn(MIGRATIONS, command ?? "")) {
235
+ throw command ? unknownMigration(command) : new BailError("Name a migration to run.");
236
+ }
237
+ return MIGRATIONS[command].run(opts.dir ?? process.cwd(), {
238
+ command,
239
+ force: opts.force ?? false,
240
+ dryRun: opts.dryRun ?? false,
241
+ });
242
+ }
243
+
137
244
  /**
138
245
  * Strict on purpose: a silently-ignored `--dryrun` would run the real migration,
139
246
  * and a `--dir` given with a space would migrate the current directory instead
140
247
  * of the one the user named.
141
248
  */
142
249
  export function parseArgs(argv) {
143
- const opts = { dir: process.cwd(), force: false, dryRun: false, help: false };
250
+ const opts = { command: null, dir: process.cwd(), force: false, dryRun: false, help: false };
144
251
  for (const arg of argv) {
145
252
  if (arg === "--force" || arg === "-f") opts.force = true;
146
253
  else if (arg === "--dry-run") opts.dryRun = true;
147
254
  else if (arg === "--help" || arg === "-h") opts.help = true;
148
255
  else if (arg.startsWith("--dir=")) opts.dir = arg.slice("--dir=".length);
149
- else {
256
+ else if (arg.startsWith("-")) {
150
257
  throw new BailError(
151
258
  `Unrecognized argument: ${arg}. Run with --help to see the supported options.`,
152
259
  );
260
+ } else if (!Object.hasOwn(MIGRATIONS, arg)) {
261
+ throw unknownMigration(arg);
262
+ } else if (opts.command !== null) {
263
+ throw new BailError(`Run one migration at a time: got ${opts.command} and ${arg}.`);
264
+ } else {
265
+ opts.command = arg;
153
266
  }
154
267
  }
155
268
  return opts;
@@ -166,7 +279,12 @@ export async function runCLI(argv = process.argv.slice(2)) {
166
279
  return;
167
280
  }
168
281
  if (opts.help) {
169
- msg.help();
282
+ msg.help(MIGRATIONS);
283
+ return;
284
+ }
285
+ if (opts.command === null) {
286
+ msg.help(MIGRATIONS);
287
+ process.exitCode = 1;
170
288
  return;
171
289
  }
172
290
  try {
package/bin/lib/detect.js CHANGED
@@ -80,6 +80,13 @@ export const MIN_SUITE_VERSION = "0.8.0";
80
80
  */
81
81
  export const CHATBOT_MIN_VERSION = "0.16.0";
82
82
 
83
+ /**
84
+ * The oldest release the localized-pages and locale-prompt migrations' output
85
+ * runs against: the root layout calls `getDocumentLanguage` and the language
86
+ * prompt imports `@pantheon-systems/p1-next-sdk/localization`.
87
+ */
88
+ export const LOCALIZATION_MIN_VERSION = "0.24.0";
89
+
83
90
  /**
84
91
  * The lockstep-versioned packages a consumer app actually installs.
85
92
  * `create-p1-starter-kit` is in the same `fixed` group but only ever scaffolds,
@@ -110,6 +117,11 @@ function parseVersion(version) {
110
117
  return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
111
118
  }
112
119
 
120
+ /** Whether a verified suite `version` is at or above `floor`. */
121
+ export function isAtLeast(version, floor) {
122
+ return !isOlderThan(parseVersion(version), parseVersion(floor));
123
+ }
124
+
113
125
  function isOlderThan(version, floor) {
114
126
  for (let i = 0; i < 3; i++) {
115
127
  if (version[i] !== floor[i]) return version[i] < floor[i];
@@ -134,7 +146,7 @@ function isOlderThan(version, floor) {
134
146
  * `chatbot` in the result says whether the chatbot rewrite's output would
135
147
  * resolve against what is installed; the caller skips that step when it is false.
136
148
  */
137
- export function assertSuiteVersions(dir) {
149
+ export function assertSuiteVersions(dir, { migration = "the persistent (editor) layout" } = {}) {
138
150
  const modules = join(dir, "node_modules");
139
151
  const resolved = SUITE.map((pkg) => ({
140
152
  pkg,
@@ -177,7 +189,7 @@ export function assertSuiteVersions(dir) {
177
189
 
178
190
  if (isOlderThan(parsed, parseVersion(MIN_SUITE_VERSION))) {
179
191
  throw new BailError(
180
- `Installed P1 packages are at ${version}, but the persistent (editor) layout ` +
192
+ `Installed P1 packages are at ${version}, but ${migration} ` +
181
193
  `needs ${MIN_SUITE_VERSION} or newer. This codemod runs at the latest published ` +
182
194
  "version because npx fetches it from the registry, so it can restructure routes " +
183
195
  `your installed version cannot render. Note a "^${version}" range will not resolve ` +
package/bin/lib/fs-ops.js CHANGED
@@ -27,6 +27,7 @@ export function write(path, content) {
27
27
  writeFileSync(path, content);
28
28
  }
29
29
 
30
- export function removeDir(path) {
30
+ /** Remove a file, or a directory and everything in it. */
31
+ export function remove(path) {
31
32
  rmSync(path, { recursive: true, force: true });
32
33
  }