@pantheon-systems/p1-next-sdk 0.22.0 → 0.24.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 (35) hide show
  1. package/README.md +82 -0
  2. package/dist/chatbot/chatbot-plugin.js +3 -0
  3. package/dist/create-published-page.d.ts +22 -9
  4. package/dist/create-published-page.js +59 -8
  5. package/dist/editor-client/editor-content.js +4 -0
  6. package/dist/editor-client/use-business-account-id.d.ts +5 -0
  7. package/dist/editor-client/use-business-account-id.js +7 -0
  8. package/dist/experimental-features/features.d.ts +18 -5
  9. package/dist/experimental-features/features.js +7 -5
  10. package/dist/experimental-features/resolve-features.d.ts +5 -2
  11. package/dist/experimental-features/resolve-features.js +7 -4
  12. package/dist/experimental-features/session-cache.d.ts +1 -1
  13. package/dist/experimental-features/session-cache.js +2 -2
  14. package/dist/experimental-features/use-p1-experimental-features.d.ts +10 -3
  15. package/dist/experimental-features/use-p1-experimental-features.js +29 -11
  16. package/dist/handler.d.ts +2 -1
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.js +1 -0
  19. package/dist/localization/index.d.ts +4 -0
  20. package/dist/localization/index.js +3 -0
  21. package/dist/localization/saved-locale.d.ts +13 -0
  22. package/dist/localization/saved-locale.js +20 -0
  23. package/dist/localization-react.d.ts +40 -0
  24. package/dist/localization-react.js +15 -0
  25. package/dist/page-localization.d.ts +12 -0
  26. package/dist/page-localization.js +9 -0
  27. package/dist/routes/publish.d.ts +0 -2
  28. package/dist/routes/publish.js +2 -3
  29. package/dist/routes/revalidate.d.ts +4 -4
  30. package/dist/routes/revalidate.js +10 -4
  31. package/dist/server.d.ts +2 -0
  32. package/dist/server.js +1 -0
  33. package/package.json +8 -3
  34. package/dist/chatbot/flag-context.d.ts +0 -15
  35. 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
 
@@ -3,12 +3,15 @@ import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
3
3
  import { useP1Auth } from "@pantheon-systems/puck-css";
4
4
  import { createAIChatPlugin } from "@pantheon-systems/p1-ai-chat";
5
5
  import { useP1ExperimentalFeatures } from "../experimental-features";
6
+ import { useBusinessAccountId } from "../editor-client/use-business-account-id";
6
7
  import { p1UserFlagKey } from "../launchdarkly/user-key";
7
8
  export function useChatbotEnabled() {
8
9
  const { user } = useP1Auth();
10
+ const businessAccountId = useBusinessAccountId();
9
11
  const features = useP1ExperimentalFeatures({
10
12
  userId: p1UserFlagKey(user),
11
13
  siteId: process.env.NEXT_PUBLIC_CSS_SITE_ID || undefined,
14
+ businessAccountId,
12
15
  });
13
16
  return features.isEnabled("chatbot");
14
17
  }
@@ -18,16 +18,17 @@
18
18
  * import { createPublishedPage } from "@pantheon-systems/p1-next-sdk/server";
19
19
  * export const published = createPublishedPage({ ... });
20
20
  *
21
- * // app/[...puckPath]/page.tsx
21
+ * // app/[[...puckPath]]/page.tsx — "/" and every other page
22
22
  * export const revalidate = 300;
23
23
  * export default published.Page;
24
24
  * export const generateMetadata = published.generateMetadata;
25
25
  * export const generateStaticParams = published.generateStaticParams;
26
26
  *
27
- * // app/page.tsx
28
- * export const revalidate = 300;
29
- * export default published.HomePage;
30
- * export const generateMetadata = published.generateHomeMetadata;
27
+ * // app/[[...puckPath]]/layout.tsx — the root layout
28
+ * const lang = (await published.getDocumentLanguage({ params })) ?? "en";
29
+ *
30
+ * `HomePage` and `generateHomeMetadata` serve a separate `app/page.tsx` for an
31
+ * app whose catch-all is `[...puckPath]` rather than optional.
31
32
  *
32
33
  * `revalidate` must stay a literal in the route file. Next.js statically
33
34
  * analyzes segment-config exports, so re-exporting one through the factory
@@ -37,6 +38,7 @@
37
38
  import type { Metadata } from "next";
38
39
  import { type RemoteDatasourceFetcher } from "@pantheon-systems/puck-css/server";
39
40
  import type { Data } from "@puckeditor/core";
41
+ import { type PublishedPageLocalization } from "./localization-react";
40
42
  /**
41
43
  * Describes the rendered document to the render client, which uses it for the
42
44
  * edit affordances that only make sense once a real document is on screen.
@@ -49,6 +51,12 @@ export type PublishedPageMetadata = {
49
51
  export type PublishedPageClientProps = {
50
52
  data: Data;
51
53
  pageMetadata: PublishedPageMetadata;
54
+ /**
55
+ * The page's locale and its locale variants. Present only on a site with
56
+ * locales. The same value is available to any component below the client
57
+ * through `useP1Localization`.
58
+ */
59
+ localization?: PublishedPageLocalization;
52
60
  };
53
61
  export type CreatePublishedPageConfig = {
54
62
  /**
@@ -96,15 +104,20 @@ export type CreatePublishedPageConfig = {
96
104
  internalPathPrefixes?: readonly string[];
97
105
  };
98
106
  export declare function createPublishedPage(config: CreatePublishedPageConfig): {
99
- Page: ({ params, }: {
107
+ Page: ({ params }: {
100
108
  params: Promise<{
101
- puckPath: string[];
109
+ puckPath?: string[];
102
110
  }>;
103
111
  }) => Promise<import("react").JSX.Element>;
112
+ getDocumentLanguage: ({ params, }: {
113
+ params: Promise<{
114
+ puckPath?: string[];
115
+ }>;
116
+ }) => Promise<string | null>;
104
117
  HomePage: () => Promise<import("react").JSX.Element>;
105
- generateMetadata: ({ params, }: {
118
+ generateMetadata: ({ params }: {
106
119
  params: Promise<{
107
- puckPath: string[];
120
+ puckPath?: string[];
108
121
  }>;
109
122
  }) => Promise<Metadata>;
110
123
  generateHomeMetadata: () => Promise<Metadata>;
@@ -1,10 +1,13 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { cache } from "react";
3
3
  import { notFound } from "next/navigation";
4
+ import { getHreflangAlternates, getLocaleVariants, } from "@pantheon-systems/css-client/localization";
4
5
  import { loadRemoteDatasourceContext, extractReferencedDatasourceIds, resolveDataTemplates, pagePathFromCatchAllSegments, } from "@pantheon-systems/puck-css/server";
5
6
  import { createCssQueryFetchers } from "./css-query-fetchers";
6
7
  import { loadPublishedPage, loadRouteTemplateKeys, } from "./published-page";
7
8
  import { resolvePageMetadata } from "./resolve-page-metadata";
9
+ import { P1LocalizationProvider, } from "./localization-react";
10
+ import { getPageLocalization } from "./page-localization";
8
11
  export function createPublishedPage(config) {
9
12
  const { Client, Unavailable, Fallback, fetchers = [], resolveMetadata = ({ pageData, path }) => resolvePageMetadata({ pageData, path, fetchers }), titles, internalPathPrefixes, } = config;
10
13
  const loadOptions = internalPathPrefixes ? { internalPathPrefixes } : undefined;
@@ -23,13 +26,48 @@ export function createPublishedPage(config) {
23
26
  });
24
27
  return resolveDataTemplates(data, context);
25
28
  }
29
+ function localize(path, data) {
30
+ const found = getPageLocalization(data);
31
+ if (!found)
32
+ return null;
33
+ const { localization, siteLocales } = found;
34
+ return {
35
+ locale: localization.locale,
36
+ path,
37
+ siteLocales,
38
+ localization,
39
+ variants: getLocaleVariants(localization),
40
+ };
41
+ }
26
42
  async function render(path, data) {
27
43
  const resolvedData = await resolve(path, data);
28
- return (_jsx(Client, { data: resolvedData, pageMetadata: {
29
- route: path,
30
- documentName: data.root.props?.title,
31
- pageType: "page",
32
- } }));
44
+ const localization = localize(path, data);
45
+ const pageMetadata = {
46
+ route: path,
47
+ documentName: data.root.props?.title,
48
+ pageType: "page",
49
+ };
50
+ if (!localization) {
51
+ return _jsx(Client, { data: resolvedData, pageMetadata: pageMetadata });
52
+ }
53
+ return (_jsx(P1LocalizationProvider, { value: localization, children: _jsx(Client, { data: resolvedData, pageMetadata: pageMetadata, localization: localization }) }));
54
+ }
55
+ function withAlternates(metadata, data) {
56
+ const siteUrl = process.env.NEXT_PUBLIC_SITE_URL?.trim();
57
+ if (!siteUrl)
58
+ return metadata;
59
+ const found = getPageLocalization(data);
60
+ const alternates = found && getHreflangAlternates(found.localization);
61
+ if (!alternates)
62
+ return metadata;
63
+ const languages = Object.fromEntries(Object.entries(alternates).map(([locale, path]) => [locale, new URL(path, siteUrl).href]));
64
+ return {
65
+ ...metadata,
66
+ alternates: {
67
+ ...metadata.alternates,
68
+ languages: { ...languages, ...metadata.alternates?.languages },
69
+ },
70
+ };
33
71
  }
34
72
  async function metadataFor(result, path) {
35
73
  if (result.status === "missing") {
@@ -38,18 +76,23 @@ export function createPublishedPage(config) {
38
76
  if (result.status === "unavailable") {
39
77
  return { title: titles?.unavailable ?? "Temporarily unavailable" };
40
78
  }
41
- return resolveMetadata({ pageData: result.data, path });
79
+ const metadata = await resolveMetadata({ pageData: result.data, path });
80
+ return withAlternates(metadata, result.data);
42
81
  }
43
82
  function generateStaticParams() {
44
83
  return [];
45
84
  }
46
- async function generateMetadata({ params, }) {
85
+ async function generateMetadata({ params }) {
47
86
  const { puckPath = [] } = await params;
87
+ if (puckPath.length === 0)
88
+ return generateHomeMetadata();
48
89
  const path = pagePathFromCatchAllSegments(puckPath);
49
90
  return metadataFor(await loadPublishedPage(path, loadOptions), path);
50
91
  }
51
- async function Page({ params, }) {
92
+ async function Page({ params }) {
52
93
  const { puckPath = [] } = await params;
94
+ if (puckPath.length === 0)
95
+ return HomePage();
53
96
  const path = pagePathFromCatchAllSegments(puckPath);
54
97
  const result = await loadPublishedPage(path, loadOptions);
55
98
  if (result.status === "missing") {
@@ -74,8 +117,16 @@ export function createPublishedPage(config) {
74
117
  }
75
118
  return render("/", result.data);
76
119
  }
120
+ async function getDocumentLanguage({ params, }) {
121
+ const { puckPath = [] } = await params;
122
+ const result = await loadPublishedPage(pagePathFromCatchAllSegments(puckPath), loadOptions);
123
+ if (result.status !== "ok")
124
+ return null;
125
+ return getPageLocalization(result.data)?.localization.locale ?? null;
126
+ }
77
127
  return {
78
128
  Page,
129
+ getDocumentLanguage,
79
130
  HomePage,
80
131
  generateMetadata,
81
132
  generateHomeMetadata,
@@ -7,6 +7,7 @@ import { useP1ExperimentalFeatures } from "../experimental-features";
7
7
  import { p1UserFlagKey } from "../launchdarkly/user-key";
8
8
  import { EditorCanvas } from "./editor-canvas";
9
9
  import { useReturnToRedirect } from "./return-to";
10
+ import { useBusinessAccountId } from "./use-business-account-id";
10
11
  export function EditorContent({ runtime, path, }) {
11
12
  const router = useRouter();
12
13
  const { data: editorCtx } = useEditorContext(path);
@@ -14,9 +15,11 @@ export function EditorContent({ runtime, path, }) {
14
15
  const { context: datasourceContext } = useRemoteDatasourceContext(path, datasourceRegistry);
15
16
  const p1Plugins = useP1Plugins(path, runtime.puckConfig);
16
17
  const { user } = useP1Auth();
18
+ const businessAccountId = useBusinessAccountId();
17
19
  const features = useP1ExperimentalFeatures({
18
20
  userId: p1UserFlagKey(user),
19
21
  siteId: runtime.config?.siteId,
22
+ businessAccountId,
20
23
  });
21
24
  const openDocument = useCallback((documentPath) => {
22
25
  router.push(`${editorPathHref(documentPath)}${window.location.search}`);
@@ -37,6 +40,7 @@ export function EditorContent({ runtime, path, }) {
37
40
  ...runtime.pluginOptions,
38
41
  ...extensions.pluginOptions,
39
42
  goLiveStub: features.isEnabled("goLiveStub"),
43
+ sectionNesting: features.isEnabled("sectionNesting"),
40
44
  },
41
45
  overrideOptions: {
42
46
  showDefaultPublish: false,
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The Business account of the current site: undefined while it is still loading, null
3
+ * once it is settled as unknown (or there is no provider, or the provider does not carry it), otherwise its id.
4
+ */
5
+ export declare function useBusinessAccountId(): string | null | undefined;
@@ -0,0 +1,7 @@
1
+ "use client";
2
+ import { useContext } from "react";
3
+ import { P1PuckContext } from "@pantheon-systems/puck-css";
4
+ export function useBusinessAccountId() {
5
+ const puck = useContext(P1PuckContext);
6
+ return puck && "businessAccountId" in puck ? puck.businessAccountId : null;
7
+ }
@@ -12,17 +12,30 @@ export declare const P1_EXPERIMENTAL_FEATURE_FLAGS: {
12
12
  readonly chatbot: "p1-chatbot";
13
13
  /** Demo-only go-live screens with mocked data. Throwaway; remove with the demo folder. */
14
14
  readonly goLiveStub: "p-1-go-live-stub";
15
+ /** Offering to put a new page in its section when its slug is a path. */
16
+ readonly sectionNesting: "p1-section-nesting";
15
17
  };
16
18
  export type P1ExperimentalFeature = keyof typeof P1_EXPERIMENTAL_FEATURE_FLAGS;
17
19
  export declare const P1_EXPERIMENTAL_FEATURES: P1ExperimentalFeature[];
20
+ /**
21
+ * The features whose flag has a rule on the Business account. Only these wait for the
22
+ * Business account and re-evaluate once it arrives; every other feature is answered
23
+ * from the user and site alone and is never changed afterwards. A feature belongs here
24
+ * before a rule on `business-account` is added to its flag.
25
+ */
26
+ export declare const BUSINESS_ACCOUNT_TARGETED_FEATURES: readonly P1ExperimentalFeature[];
18
27
  /** Every experimental feature off. What an unanswered LaunchDarkly resolves to. */
19
28
  export type P1ExperimentalFeatureSet = Record<P1ExperimentalFeature, boolean>;
20
29
  export declare const ALL_OFF: P1ExperimentalFeatureSet;
21
30
  /**
22
- * Read the features out of a raw LaunchDarkly flag set.
31
+ * Whether one experimental feature is on, reading its flag through `valueOf`.
23
32
  *
24
- * Anything that is not literally `true` is off, so a missing flag, a null from an
25
- * unsynced environment, and a non-boolean value all land on the safe side rather than
26
- * exposing an unfinished feature.
33
+ * Only a literal `true` turns a feature on, so a missing flag, a null and a non-boolean
34
+ * all read as off.
35
+ */
36
+ export declare function readFeature(feature: P1ExperimentalFeature, valueOf: (flagKey: string) => unknown): boolean;
37
+ /**
38
+ * Every experimental feature's state. Reads only the flags that gate a feature, one
39
+ * `readFeature` per feature.
27
40
  */
28
- export declare function readFeatures(flags: Record<string, unknown>): P1ExperimentalFeatureSet;
41
+ export declare function readFeatures(valueOf: (flagKey: string) => unknown): P1ExperimentalFeatureSet;
@@ -2,12 +2,14 @@ export const P1_EXPERIMENTAL_FEATURE_FLAGS = {
2
2
  threads: "p1-collaboration",
3
3
  chatbot: "p1-chatbot",
4
4
  goLiveStub: "p-1-go-live-stub",
5
+ sectionNesting: "p1-section-nesting",
5
6
  };
6
7
  export const P1_EXPERIMENTAL_FEATURES = Object.keys(P1_EXPERIMENTAL_FEATURE_FLAGS);
8
+ export const BUSINESS_ACCOUNT_TARGETED_FEATURES = [];
7
9
  export const ALL_OFF = Object.freeze(Object.fromEntries(P1_EXPERIMENTAL_FEATURES.map((feature) => [feature, false])));
8
- export function readFeatures(flags) {
9
- return Object.fromEntries(P1_EXPERIMENTAL_FEATURES.map((feature) => [
10
- feature,
11
- flags[P1_EXPERIMENTAL_FEATURE_FLAGS[feature]] === true,
12
- ]));
10
+ export function readFeature(feature, valueOf) {
11
+ return valueOf(P1_EXPERIMENTAL_FEATURE_FLAGS[feature]) === true;
12
+ }
13
+ export function readFeatures(valueOf) {
14
+ return Object.fromEntries(P1_EXPERIMENTAL_FEATURES.map((feature) => [feature, readFeature(feature, valueOf)]));
13
15
  }
@@ -1,7 +1,10 @@
1
1
  import { type LDContext } from "launchdarkly-js-client-sdk";
2
2
  import { type P1ExperimentalFeatureSet } from "./features";
3
- /** The LaunchDarkly evaluation context: who is editing, and which site they are in. */
4
- export declare function buildFeatureContext(userId: string, siteId: string | undefined): LDContext;
3
+ /**
4
+ * The LaunchDarkly evaluation context: who is editing, which site they are in, and which
5
+ * Business account owns it. Each is identified by key alone.
6
+ */
7
+ export declare function buildFeatureContext(userId: string, siteId: string | undefined, businessAccountId?: string | null): LDContext;
5
8
  /**
6
9
  * Evaluate every experimental feature once for one context.
7
10
  *
@@ -2,14 +2,15 @@ import { initialize } from "launchdarkly-js-client-sdk";
2
2
  import { ALL_OFF, readFeatures } from "./features";
3
3
  import { localFlagOverrides, overridesEveryFeature } from "./local-overrides";
4
4
  const INITIALIZATION_TIMEOUT_SECONDS = 5;
5
- export function buildFeatureContext(userId, siteId) {
6
- if (!siteId) {
5
+ export function buildFeatureContext(userId, siteId, businessAccountId) {
6
+ if (!siteId && !businessAccountId) {
7
7
  return { kind: "user", key: userId };
8
8
  }
9
9
  return {
10
10
  kind: "multi",
11
11
  user: { key: userId },
12
- site: { key: siteId },
12
+ ...(siteId ? { site: { key: siteId } } : {}),
13
+ ...(businessAccountId ? { "business-account": { key: businessAccountId } } : {}),
13
14
  };
14
15
  }
15
16
  export async function resolveFeatures(clientSideId, context) {
@@ -22,9 +23,11 @@ export async function resolveFeatures(clientSideId, context) {
22
23
  client = initialize(clientSideId, context, {
23
24
  streaming: false,
24
25
  diagnosticOptOut: true,
26
+ sendEventsOnlyForVariation: true,
25
27
  });
26
28
  await client.waitForInitialization(INITIALIZATION_TIMEOUT_SECONDS);
27
- return { ...readFeatures(client.allFlags()), ...overrides };
29
+ const ldClient = client;
30
+ return { ...readFeatures((key) => ldClient.variation(key, false)), ...overrides };
28
31
  }
29
32
  catch {
30
33
  return { ...ALL_OFF, ...overrides };
@@ -1,5 +1,5 @@
1
1
  import type { P1ExperimentalFeatureSet } from "./features";
2
- export declare function sessionKey(clientSideId: string, userId: string, siteId: string | undefined): string;
2
+ export declare function sessionKey(clientSideId: string, userId: string, siteId: string | undefined, businessAccountId?: string | null): string;
3
3
  /** The answer already resolved for this key, or null if none has been yet. */
4
4
  export declare function peekFeatures(key: string): P1ExperimentalFeatureSet | null;
5
5
  export declare function featuresFor(key: string, resolve: () => Promise<P1ExperimentalFeatureSet>): Promise<P1ExperimentalFeatureSet>;
@@ -1,7 +1,7 @@
1
1
  const pending = new Map();
2
2
  const settled = new Map();
3
- export function sessionKey(clientSideId, userId, siteId) {
4
- return `${clientSideId}|${userId}|${siteId ?? ""}`;
3
+ export function sessionKey(clientSideId, userId, siteId, businessAccountId) {
4
+ return `${clientSideId}|${userId}|${siteId ?? ""}|${businessAccountId ?? ""}`;
5
5
  }
6
6
  export function peekFeatures(key) {
7
7
  return settled.get(key) ?? null;
@@ -8,6 +8,13 @@ export interface UseP1ExperimentalFeaturesOptions {
8
8
  userId: string | null | undefined;
9
9
  /** The site being edited. Absent narrows evaluation to the user alone. */
10
10
  siteId?: string | null;
11
+ /**
12
+ * The id of the current site's Business account, so a feature can be targeted by
13
+ * Business account. `undefined` means still loading and `null` means there is none.
14
+ * Evaluation never waits for it: only a feature targeted by Business account is held
15
+ * off until it settles, and is then answered for it.
16
+ */
17
+ businessAccountId?: string | null;
11
18
  }
12
19
  export interface P1ExperimentalFeatures {
13
20
  /**
@@ -22,14 +29,14 @@ export interface P1ExperimentalFeatures {
22
29
  resolved: boolean;
23
30
  }
24
31
  /**
25
- * Which experimental features are turned on for this person, on this site.
32
+ * Which experimental features are turned on for this person, on this site, in this Business account.
26
33
  *
27
34
  * Availability is Pantheon's to decide, so a caller asks and wires the answer through
28
35
  * rather than configuring anything: an unset flag, an unreachable LaunchDarkly and a
29
36
  * signed-out reader all report off.
30
37
  *
31
- * Resolved once per user and site for the life of the page and shared between every
32
- * caller, so this can be called from as many components as need it. A flag changed
38
+ * Resolved once per user and site for the life of the page, plus once more per Business
39
+ * account for features targeted by it, and shared between every caller, so this can be called from as many components as need it. A flag changed
33
40
  * mid-session takes effect on the next load.
34
41
  */
35
42
  export declare function useP1ExperimentalFeatures(options: UseP1ExperimentalFeaturesOptions): P1ExperimentalFeatures;
@@ -1,20 +1,41 @@
1
1
  "use client";
2
2
  import { useEffect, useMemo, useState } from "react";
3
3
  import { resolveClientSideId } from "../launchdarkly/client-side-id";
4
- import { ALL_OFF } from "./features";
4
+ import { ALL_OFF, BUSINESS_ACCOUNT_TARGETED_FEATURES, } from "./features";
5
5
  import { buildFeatureContext, resolveFeatures } from "./resolve-features";
6
6
  import { featuresFor, peekFeatures, sessionKey } from "./session-cache";
7
7
  function peek(key) {
8
8
  return key ? peekFeatures(key) : null;
9
9
  }
10
10
  export function useP1ExperimentalFeatures(options) {
11
- const { userId, siteId } = options;
11
+ const { userId, siteId, businessAccountId } = options;
12
12
  const clientSideId = resolveClientSideId();
13
- const key = clientSideId && userId
14
- ? sessionKey(clientSideId, userId, siteId ?? undefined)
13
+ const targetsBusinessAccount = BUSINESS_ACCOUNT_TARGETED_FEATURES.length > 0;
14
+ const key = clientSideId && userId ? sessionKey(clientSideId, userId, siteId ?? undefined) : null;
15
+ const businessAccountKey = clientSideId && userId && targetsBusinessAccount && businessAccountId
16
+ ? sessionKey(clientSideId, userId, siteId ?? undefined, businessAccountId)
15
17
  : null;
18
+ const base = useAnswer(key, clientSideId, userId, siteId, undefined);
19
+ const withBusinessAccount = useAnswer(businessAccountKey, clientSideId, userId, siteId, businessAccountId);
20
+ const waitingForBusinessAccount = targetsBusinessAccount &&
21
+ (businessAccountId === undefined || (businessAccountKey !== null && !withBusinessAccount));
22
+ const features = useMemo(() => {
23
+ if (!base) {
24
+ return null;
25
+ }
26
+ const merged = { ...base };
27
+ for (const feature of BUSINESS_ACCOUNT_TARGETED_FEATURES) {
28
+ merged[feature] = waitingForBusinessAccount ? false : (withBusinessAccount ?? base)[feature];
29
+ }
30
+ return merged;
31
+ }, [base, withBusinessAccount, waitingForBusinessAccount]);
32
+ return useMemo(() => ({
33
+ isEnabled: (feature) => (features ?? ALL_OFF)[feature],
34
+ resolved: features !== null && !waitingForBusinessAccount,
35
+ }), [features, waitingForBusinessAccount]);
36
+ }
37
+ function useAnswer(key, clientSideId, userId, siteId, businessAccountId) {
16
38
  const [answer, setAnswer] = useState(() => ({ key, features: peek(key) }));
17
- const features = answer.key === key ? answer.features : peek(key);
18
39
  useEffect(() => {
19
40
  if (!key || !userId) {
20
41
  return;
@@ -25,7 +46,7 @@ export function useP1ExperimentalFeatures(options) {
25
46
  return;
26
47
  }
27
48
  let active = true;
28
- void featuresFor(key, () => resolveFeatures(clientSideId, buildFeatureContext(userId, siteId ?? undefined))).then((resolved) => {
49
+ void featuresFor(key, () => resolveFeatures(clientSideId, buildFeatureContext(userId, siteId ?? undefined, businessAccountId))).then((resolved) => {
29
50
  if (active) {
30
51
  setAnswer({ key, features: resolved });
31
52
  }
@@ -33,9 +54,6 @@ export function useP1ExperimentalFeatures(options) {
33
54
  return () => {
34
55
  active = false;
35
56
  };
36
- }, [key, clientSideId, userId, siteId]);
37
- return useMemo(() => ({
38
- isEnabled: (feature) => (features ?? ALL_OFF)[feature],
39
- resolved: features !== null,
40
- }), [features]);
57
+ }, [key, clientSideId, userId, siteId, businessAccountId]);
58
+ return answer.key === key ? answer.features : peek(key);
41
59
  }
package/dist/handler.d.ts CHANGED
@@ -21,7 +21,8 @@ export type P1HandlerConfig = P1DataConfig & {
21
21
  * Dynamic segment this app renders public pages from, as Next.js names it for
22
22
  * revalidatePath. Publishing a route template invalidates it so instance URLs
23
23
  * that resolve by template fall-through alone are refreshed too. Defaults to
24
- * the scaffolded app's `/[...puckPath]`.
24
+ * both `/[...puckPath]` and `/[[...puckPath]]`; an app rendering pages from
25
+ * another segment names it here.
25
26
  */
26
27
  publicPageSegment?: string;
27
28
  };
package/dist/index.d.ts CHANGED
@@ -4,3 +4,4 @@ export { createP1EditorClient } from "./editor-client";
4
4
  export type { CreateP1EditorClientOptions, P1EditorContext, P1EditorExtensions, } from "./editor-client";
5
5
  export { useP1ExperimentalFeatures } from "./experimental-features";
6
6
  export type { P1ExperimentalFeature, P1ExperimentalFeatures, UseP1ExperimentalFeaturesOptions, } from "./experimental-features";
7
+ export { P1LocalizationProvider, useP1Localization, type P1Localization, type PublishedPageLocalization, } from "./localization-react";
package/dist/index.js CHANGED
@@ -2,3 +2,4 @@ export { P1NextRouterProvider } from "./P1NextRouterProvider";
2
2
  export { parseEditorSegments, editorPagePathFromUrlPath, } from "./editor-paths";
3
3
  export { createP1EditorClient } from "./editor-client";
4
4
  export { useP1ExperimentalFeatures } from "./experimental-features";
5
+ export { P1LocalizationProvider, useP1Localization, } from "./localization-react";
@@ -0,0 +1,4 @@
1
+ export type { LocalePolicy, PageListEntry, PageListResult, PageLocalization, PageLocaleVariant, SiteLocales, } from "@pantheon-systems/css-client";
2
+ export { getMatchingLocale, isLocalized, isSameLocale, resolveVisitorLocale, type ResolveVisitorLocaleOptions, } from "@pantheon-systems/css-client/localization";
3
+ export { SAVED_LOCALE_COOKIE, getSavedLocale, saveLocale, } from "./saved-locale";
4
+ export { getHreflangAlternates, getLocaleVariants, getSavedLocaleSuggestion, type LocaleVariant, type SavedLocaleSuggestionOptions, } from "@pantheon-systems/css-client/localization";
@@ -0,0 +1,3 @@
1
+ export { getMatchingLocale, isLocalized, isSameLocale, resolveVisitorLocale, } from "@pantheon-systems/css-client/localization";
2
+ export { SAVED_LOCALE_COOKIE, getSavedLocale, saveLocale, } from "./saved-locale";
3
+ export { getHreflangAlternates, getLocaleVariants, getSavedLocaleSuggestion, } from "@pantheon-systems/css-client/localization";
@@ -0,0 +1,13 @@
1
+ /** Name of the cookie that remembers the visitor's chosen locale. */
2
+ export declare const SAVED_LOCALE_COOKIE = "p1_locale";
3
+ /**
4
+ * The visitor's saved locale, read in the browser.
5
+ *
6
+ * @returns The saved locale, or `null` when none is saved, the value is not a locale tag, or there is no `document`.
7
+ */
8
+ export declare function getSavedLocale(): string | null;
9
+ /**
10
+ * Remembers `locale` as the visitor's choice for later visits, in a site-wide
11
+ * cookie that lasts a year. Does nothing outside a browser.
12
+ */
13
+ export declare function saveLocale(locale: string): void;
@@ -0,0 +1,20 @@
1
+ import { parseCookie, stringifySetCookie } from "cookie";
2
+ export const SAVED_LOCALE_COOKIE = "p1_locale";
3
+ const ONE_YEAR_SECONDS = 60 * 60 * 24 * 365;
4
+ const LOCALE_TAG = /^[A-Za-z]{2,8}([-_][A-Za-z0-9]{1,8})*$/;
5
+ export function getSavedLocale() {
6
+ if (typeof document === "undefined")
7
+ return null;
8
+ const value = parseCookie(document.cookie)[SAVED_LOCALE_COOKIE];
9
+ return value !== undefined && LOCALE_TAG.test(value) ? value : null;
10
+ }
11
+ export function saveLocale(locale) {
12
+ if (typeof document === "undefined")
13
+ return;
14
+ document.cookie = stringifySetCookie(SAVED_LOCALE_COOKIE, locale, {
15
+ path: "/",
16
+ maxAge: ONE_YEAR_SECONDS,
17
+ sameSite: "lax",
18
+ secure: location.protocol === "https:",
19
+ });
20
+ }
@@ -0,0 +1,40 @@
1
+ import { type ReactNode } from "react";
2
+ import type { PageLocalization, SiteLocales } from "@pantheon-systems/css-client";
3
+ import type { LocaleVariant } from "@pantheon-systems/css-client/localization";
4
+ /**
5
+ * A localized page as the render pipeline describes it to the app. Plain JSON,
6
+ * so it crosses from server to client components.
7
+ */
8
+ export type PublishedPageLocalization = {
9
+ /** The page's locale, or `null` when it has none set. */
10
+ locale: string | null;
11
+ /** The path of the page. */
12
+ path: string;
13
+ siteLocales: SiteLocales;
14
+ localization: PageLocalization;
15
+ /**
16
+ * The page itself and its other locale variants: those in the site's locales
17
+ * first, in the site's order, then those with `locale: null`.
18
+ */
19
+ variants: LocaleVariant[];
20
+ };
21
+ /** What `useP1Localization` returns. */
22
+ export type P1Localization = {
23
+ /** The page's locale, or `null` outside a localized page. */
24
+ locale: string | null;
25
+ /** The site's locales, or `null` outside a localized page. */
26
+ siteLocales: SiteLocales | null;
27
+ /** Every locale variant of the page, for a language switcher. Empty outside a localized page. */
28
+ variants: LocaleVariant[];
29
+ };
30
+ /**
31
+ * Makes a localized page's details available to `useP1Localization` below it.
32
+ * `createPublishedPage` renders it around the app's client for every page on a
33
+ * site with locales.
34
+ */
35
+ export declare function P1LocalizationProvider({ value, children, }: {
36
+ value: P1Localization;
37
+ children?: ReactNode;
38
+ }): import("react").JSX.Element;
39
+ /** The current page's locale and its locale variants. */
40
+ export declare function useP1Localization(): P1Localization;
@@ -0,0 +1,15 @@
1
+ "use client";
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { createContext, useContext } from "react";
4
+ const LocalizationContext = createContext(null);
5
+ export function P1LocalizationProvider({ value, children, }) {
6
+ return _jsx(LocalizationContext.Provider, { value: value, children: children });
7
+ }
8
+ export function useP1Localization() {
9
+ const page = useContext(LocalizationContext);
10
+ return {
11
+ locale: page?.locale ?? null,
12
+ siteLocales: page?.siteLocales ?? null,
13
+ variants: page?.variants ?? [],
14
+ };
15
+ }
@@ -0,0 +1,12 @@
1
+ import type { Data } from "@puckeditor/core";
2
+ import type { PageLocalization, SiteLocales } from "@pantheon-systems/css-client";
3
+ /**
4
+ * A published page's localization and the site's locales, as carried on the
5
+ * page data returned by `loadPublishedPage`.
6
+ *
7
+ * @returns Both, or `null` when the site has no locales or the page carries no locale variants.
8
+ */
9
+ export declare function getPageLocalization(data: Data): {
10
+ localization: PageLocalization;
11
+ siteLocales: SiteLocales;
12
+ } | null;
@@ -0,0 +1,9 @@
1
+ import { isLocalized } from "@pantheon-systems/css-client/localization";
2
+ export function getPageLocalization(data) {
3
+ const props = data.root?.props;
4
+ const localization = props?._localization;
5
+ const siteLocales = props?._siteLocales;
6
+ if (!Array.isArray(localization?.variants) || !isLocalized(siteLocales))
7
+ return null;
8
+ return { localization, siteLocales };
9
+ }
@@ -1,7 +1,5 @@
1
1
  import { NextResponse } from "next/server";
2
- import { DEFAULT_PUBLIC_PAGE_SEGMENT } from "./revalidate";
3
2
  export { postPublish as POST };
4
- export { DEFAULT_PUBLIC_PAGE_SEGMENT };
5
3
  export declare function postPublish(request: Request, { publicPageSegment }?: {
6
4
  publicPageSegment?: string;
7
5
  }): Promise<NextResponse<{
@@ -1,9 +1,8 @@
1
1
  import { NextResponse } from "next/server";
2
2
  import { normalizePath, persistPublishedPage } from "@pantheon-systems/puck-css/server";
3
- import { DEFAULT_PUBLIC_PAGE_SEGMENT, revalidatePublishedPath } from "./revalidate";
3
+ import { revalidatePublishedPath } from "./revalidate";
4
4
  export { postPublish as POST };
5
- export { DEFAULT_PUBLIC_PAGE_SEGMENT };
6
- export async function postPublish(request, { publicPageSegment = DEFAULT_PUBLIC_PAGE_SEGMENT } = {}) {
5
+ export async function postPublish(request, { publicPageSegment } = {}) {
7
6
  const payload = (await request.json());
8
7
  const path = payload.path === "/" ? "/" : normalizePath(payload.path);
9
8
  if (path === null) {
@@ -16,11 +16,11 @@
16
16
  import { NextResponse } from "next/server";
17
17
  export { postRevalidate as POST };
18
18
  /**
19
- * Dynamic segment rendering public pages, as Next.js names it for
20
- * revalidatePath. Overridable for an app whose catch-all directory is not
21
- * `[...puckPath]`.
19
+ * Dynamic segments that may render public pages, as Next.js names them for
20
+ * revalidatePath: the required and the optional catch-all. An app whose
21
+ * catch-all directory is neither names its own.
22
22
  */
23
- export declare const DEFAULT_PUBLIC_PAGE_SEGMENT = "/[...puckPath]";
23
+ export declare const DEFAULT_PUBLIC_PAGE_SEGMENTS: readonly string[];
24
24
  /**
25
25
  * Invalidate every cached route the content at `path` can be served through.
26
26
  *
@@ -2,17 +2,23 @@ import { revalidatePath } from "next/cache";
2
2
  import { NextResponse } from "next/server";
3
3
  import { isRouteTemplatePath, normalizePath, listOverridePathsForBase, } from "@pantheon-systems/puck-css/server";
4
4
  export { postRevalidate as POST };
5
- export const DEFAULT_PUBLIC_PAGE_SEGMENT = "/[...puckPath]";
6
- export async function revalidatePublishedPath(path, publicPageSegment = DEFAULT_PUBLIC_PAGE_SEGMENT) {
5
+ export const DEFAULT_PUBLIC_PAGE_SEGMENTS = [
6
+ "/[...puckPath]",
7
+ "/[[...puckPath]]",
8
+ ];
9
+ export async function revalidatePublishedPath(path, publicPageSegment) {
7
10
  revalidatePath(path);
8
11
  if (!isRouteTemplatePath(path))
9
12
  return;
10
13
  for (const p of await listOverridePathsForBase(path)) {
11
14
  revalidatePath(p);
12
15
  }
13
- revalidatePath(publicPageSegment, "page");
16
+ const segments = publicPageSegment === undefined ? DEFAULT_PUBLIC_PAGE_SEGMENTS : [publicPageSegment];
17
+ for (const segment of segments) {
18
+ revalidatePath(segment, "page");
19
+ }
14
20
  }
15
- export async function postRevalidate(request, { publicPageSegment = DEFAULT_PUBLIC_PAGE_SEGMENT } = {}) {
21
+ export async function postRevalidate(request, { publicPageSegment } = {}) {
16
22
  const payload = (await request.json().catch(() => null));
17
23
  const raw = typeof payload?.path === "string" ? payload.path : null;
18
24
  if (raw === null) {
package/dist/server.d.ts CHANGED
@@ -5,5 +5,7 @@ export { createCssQueryFetchers, type CreateCssQueryFetchersOptions } from "./cs
5
5
  export { createP1Middleware, type P1MiddlewareConfig } from "./middleware";
6
6
  export { createPublishedPage, type CreatePublishedPageConfig, type PublishedPageClientProps, type PublishedPageMetadata, } from "./create-published-page";
7
7
  export { loadPublishedPage, loadRouteTemplateKeys, type LoadPublishedPageOptions, type PublishedPageResult, } from "./published-page";
8
+ export { getPageLocalization } from "./page-localization";
9
+ export type { PublishedPageLocalization } from "./localization-react";
8
10
  export { buildPageMetadata, type PageHeadMetadata, type PageMetaFields, type SiteMetaDefaults, } from "./page-metadata";
9
11
  export { resolvePageMetadata, type ResolvePageMetadataOptions, type PageMetadataContext, type AuthoredPageMeta, } from "./resolve-page-metadata";
package/dist/server.js CHANGED
@@ -5,5 +5,6 @@ export { createCssQueryFetchers } from "./css-query-fetchers";
5
5
  export { createP1Middleware } from "./middleware";
6
6
  export { createPublishedPage, } from "./create-published-page";
7
7
  export { loadPublishedPage, loadRouteTemplateKeys, } from "./published-page";
8
+ export { getPageLocalization } from "./page-localization";
8
9
  export { buildPageMetadata, } from "./page-metadata";
9
10
  export { resolvePageMetadata, } from "./resolve-page-metadata";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pantheon-systems/p1-next-sdk",
3
- "version": "0.22.0",
3
+ "version": "0.24.0",
4
4
  "license": "UNLICENSED",
5
5
  "description": "Next.js SDK for P1 editor integration",
6
6
  "publishConfig": {
@@ -32,6 +32,10 @@
32
32
  "types": "./dist/chatbot/index.d.ts",
33
33
  "import": "./dist/chatbot/index.js"
34
34
  },
35
+ "./localization": {
36
+ "types": "./dist/localization/index.d.ts",
37
+ "import": "./dist/localization/index.js"
38
+ },
35
39
  "./editor.css": "./src/editor-client/editor.css"
36
40
  },
37
41
  "files": [
@@ -42,9 +46,10 @@
42
46
  "!dist/**/*.map"
43
47
  ],
44
48
  "dependencies": {
45
- "@pantheon-systems/css-client": "0.22.0",
49
+ "@pantheon-systems/css-client": "0.24.0",
46
50
  "@pantheon-systems/p1-ai-chat": "0.10.0",
47
- "@pantheon-systems/puck-css": "0.22.0",
51
+ "@pantheon-systems/puck-css": "0.24.0",
52
+ "cookie": "^1.1.1",
48
53
  "launchdarkly-js-client-sdk": "^3.9.3",
49
54
  "server-only": "^0.0.1"
50
55
  },
@@ -1,15 +0,0 @@
1
- import type { AuthUser } from "@pantheon-systems/puck-css";
2
- export interface FlagContext {
3
- kind: "user";
4
- key: string;
5
- email?: string;
6
- anonymous?: boolean;
7
- }
8
- /**
9
- * Build the LaunchDarkly evaluation context for the signed-in user.
10
- *
11
- * Keyed by {@link p1UserFlagKey}, so the chatbot's targeting agrees with every other
12
- * rollout check. A user with no key at all is pre-auth, and shares the anonymous
13
- * context rather than being targetable.
14
- */
15
- export declare function buildFlagContext(user: AuthUser | null): FlagContext;
@@ -1,13 +0,0 @@
1
- import { p1UserFlagKey } from "../launchdarkly/user-key";
2
- export function buildFlagContext(user) {
3
- const key = p1UserFlagKey(user);
4
- if (!key) {
5
- return { kind: "user", key: "anonymous", anonymous: true };
6
- }
7
- const email = user?.email?.trim();
8
- return {
9
- kind: "user",
10
- key,
11
- ...(email && { email }),
12
- };
13
- }