canopycms-next 0.0.68-int.93 → 0.0.68-int.95

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/client.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { type ReactElement, type ReactNode } from 'react';
2
+ import { useCanopyPreview } from 'canopycms/client';
1
3
  import type { CanopyClientConfig, CustomFieldRenderers } from 'canopycms/client';
2
4
  /**
3
5
  * Next.js-specific wrapper for CanopyEditorPage that automatically reads
@@ -24,3 +26,33 @@ import type { CanopyClientConfig, CustomFieldRenderers } from 'canopycms/client'
24
26
  * ```
25
27
  */
26
28
  export declare const NextCanopyEditorPage: (config: CanopyClientConfig, customRenderers?: CustomFieldRenderers) => () => import("react/jsx-runtime").JSX.Element;
29
+ /** What a preview view renders from: the editor's live draft, plus `useCanopyPreview`'s helpers. */
30
+ export type CanopyPreviewViewProps<T> = ReturnType<typeof useCanopyPreview<T>>;
31
+ /** The props of a view wrapped by `withCanopyPreview`. */
32
+ export interface CanopyPreviewProps<T, X = undefined> {
33
+ /** The saved entry data, rendered until the editor sends a draft. */
34
+ initialData: T;
35
+ /** Editor origin to trust, for an editor on another origin. Defaults to this page's own. */
36
+ editorOrigin?: string;
37
+ /**
38
+ * What the route's `load` returned (see `previewView`), handed to the view untouched as its
39
+ * `extras` prop. Absent on a public page and for a view with no loader.
40
+ */
41
+ extras?: X;
42
+ }
43
+ /**
44
+ * Wraps a view so it renders the editor's live draft of `initialData`, through `useCanopyPreview`;
45
+ * outside an editor frame it renders `initialData` unchanged.
46
+ *
47
+ * Call it in your own `'use client'` module and pass the result to `createPreviewPage`'s `views`,
48
+ * or render it on a public page. The wrapping lives in your module, not in `createPreviewPage`,
49
+ * because Next ships every client module a page's server code imports: one imported by the
50
+ * context would put the editor in every page that reads content.
51
+ *
52
+ * The returned type is a call signature rather than `ComponentType`, whose `propTypes` would make
53
+ * a view for one content type unassignable to a map of views for many. It returns `ReactElement`,
54
+ * which JSX accepts on every supported TypeScript, where `ReactNode` needs `JSX.ElementType`.
55
+ */
56
+ export declare function withCanopyPreview<T, X = undefined>(View: (props: CanopyPreviewViewProps<T> & {
57
+ extras: X | undefined;
58
+ }) => ReactNode): (props: CanopyPreviewProps<T, X>) => ReactElement;
package/dist/client.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { Suspense } from 'react';
4
4
  import { useSearchParams } from 'next/navigation';
5
- import { CanopyEditorPage } from 'canopycms/client';
5
+ import { CanopyEditorPage, useCanopyPreview } from 'canopycms/client';
6
6
  /**
7
7
  * Next.js-specific wrapper for CanopyEditorPage that automatically reads
8
8
  * URL search params (branch, entry) using Next.js's useSearchParams hook.
@@ -44,3 +44,24 @@ export const NextCanopyEditorPage = (config, customRenderers) => {
44
44
  return (_jsx(Suspense, { fallback: null, children: _jsx(EditorWithSearchParams, {}) }));
45
45
  };
46
46
  };
47
+ /**
48
+ * Wraps a view so it renders the editor's live draft of `initialData`, through `useCanopyPreview`;
49
+ * outside an editor frame it renders `initialData` unchanged.
50
+ *
51
+ * Call it in your own `'use client'` module and pass the result to `createPreviewPage`'s `views`,
52
+ * or render it on a public page. The wrapping lives in your module, not in `createPreviewPage`,
53
+ * because Next ships every client module a page's server code imports: one imported by the
54
+ * context would put the editor in every page that reads content.
55
+ *
56
+ * The returned type is a call signature rather than `ComponentType`, whose `propTypes` would make
57
+ * a view for one content type unassignable to a map of views for many. It returns `ReactElement`,
58
+ * which JSX accepts on every supported TypeScript, where `ReactNode` needs `JSX.ElementType`.
59
+ */
60
+ export function withCanopyPreview(View) {
61
+ return function CanopyPreview({ initialData, editorOrigin, extras }) {
62
+ const preview = useCanopyPreview({ initialData, editorOrigin });
63
+ // `extras` is a prop of its own, never spread into the hook's result, so it cannot shadow
64
+ // `data` or `fieldProps`.
65
+ return _jsx(View, { ...preview, extras: extras });
66
+ };
67
+ }
package/dist/config.cjs CHANGED
@@ -399,7 +399,7 @@ function withCanopy(nextConfig = {}, options = {}) {
399
399
  ])
400
400
  ];
401
401
  const generateBuildId = nextConfig.generateBuildId ?? (options.staticBuild ? resolveStaticBuildId : void 0);
402
- const env = nextConfig.trailingSlash ? { CANOPY_API_TRAILING_SLASH: "true", ...nextConfig.env } : void 0;
402
+ const env = nextConfig.trailingSlash ? { CANOPY_TRAILING_SLASH: "true", ...nextConfig.env } : void 0;
403
403
  return {
404
404
  ...nextConfig,
405
405
  transpilePackages: allPackages,
package/dist/config.mjs CHANGED
@@ -363,7 +363,7 @@ function withCanopy(nextConfig = {}, options = {}) {
363
363
  ])
364
364
  ];
365
365
  const generateBuildId = nextConfig.generateBuildId ?? (options.staticBuild ? resolveStaticBuildId : void 0);
366
- const env = nextConfig.trailingSlash ? { CANOPY_API_TRAILING_SLASH: "true", ...nextConfig.env } : void 0;
366
+ const env = nextConfig.trailingSlash ? { CANOPY_TRAILING_SLASH: "true", ...nextConfig.env } : void 0;
367
367
  return {
368
368
  ...nextConfig,
369
369
  transpilePackages: allPackages,
@@ -1,7 +1,9 @@
1
1
  import { type CanopyContext, type CanopyBuildContext, type CanopyServices, type SeoFieldLocation } from 'canopycms/server';
2
2
  import type { CanopyConfig, AuthPlugin, FieldConfig } from 'canopycms';
3
3
  import type { Metadata, MetadataRoute } from 'next';
4
+ import type { ReactElement } from 'react';
4
5
  import { createCanopyCatchAllHandler } from './adapter.js';
6
+ import { type CreatePreviewPageOptions, type PreviewPageProps } from './preview-page.js';
5
7
  import { type EntryToMetadataOptions, type GenerateContentSitemapOptions, type GenerateContentStaticParamsOptions } from './static.js';
6
8
  /**
7
9
  * Merge a context-wide default SEO field location (`createNextCanopyContext({ seo })`) with a
@@ -132,6 +134,22 @@ export interface NextCanopyContextResult {
132
134
  * (see that function's doc); pass `fields`/`group` on a given call to override just that call.
133
135
  */
134
136
  entryToMetadata: (entryData: unknown, options?: EntryToMetadataOptions) => Metadata;
137
+ /**
138
+ * The page for the preview route the editor's `previewPrefix` names, for a site whose public
139
+ * pages are a static export. Mount it as `app/<prefix>/[[...path]]/page.server.tsx`, so only the
140
+ * CMS build has it:
141
+ *
142
+ * ```tsx
143
+ * export default createPreviewPage({ views: { post: PostPreview, doc: DocPreview } })
144
+ * ```
145
+ *
146
+ * Each view is made by `withCanopyPreview` (`canopycms-next/client`) in a `'use client'` module.
147
+ * It renders each entry from the `?branch=` the editor names, through `views[entryType]` with
148
+ * the live draft. Reads are request-scoped and ACL-checked, and anything not readable is a 404.
149
+ * A view that needs more server reads is `previewView({ view, load })`: `load` runs after the
150
+ * entry is read and its result arrives as the view's `extras` prop.
151
+ */
152
+ createPreviewPage: (options: CreatePreviewPageOptions) => (props: PreviewPageProps) => Promise<ReactElement>;
135
153
  /** API catch-all route handler */
136
154
  handler: ReturnType<typeof createCanopyCatchAllHandler>;
137
155
  /** Underlying services (rarely needed directly) */
@@ -5,6 +5,7 @@ import { createCanopyContext, isBuildMode, startDevContentWatcher, createCanopyS
5
5
  import { assertAuthPluginAllowedForMode } from 'canopycms/auth';
6
6
  import { CachingAuthPlugin, FileBasedAuthCache } from 'canopycms/auth/cache';
7
7
  import { createCanopyCatchAllHandler } from './adapter.js';
8
+ import { createPreviewPageFor, } from './preview-page.js';
8
9
  import { collectStaticParams, entryToMetadata as entryToMetadataCore, generateContentSitemap, } from './static.js';
9
10
  /**
10
11
  * Merge a context-wide default SEO field location (`createNextCanopyContext({ seo })`) with a
@@ -271,6 +272,7 @@ export async function createNextCanopyContext(options) {
271
272
  generateContentStaticParams,
272
273
  generateContentSitemap: boundGenerateContentSitemap,
273
274
  entryToMetadata: boundEntryToMetadata,
275
+ createPreviewPage: (previewOptions) => createPreviewPageFor(getCanopy, previewOptions, options.config.deployedAs),
274
276
  handler,
275
277
  services,
276
278
  };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { createCanopyCatchAllHandler, wrapNextRequest, type CanopyNextOptions } from './adapter.js';
2
2
  export { createNextCanopyContext, type NextCanopyOptions, type NextCanopyContextResult, } from './context-wrapper.js';
3
+ export { previewView, type CreatePreviewPageOptions, type PreviewEntry, type PreviewLoadContext, type PreviewPageProps, type PreviewViewWithLoader, } from './preview-page.js';
3
4
  export { collectStaticParams, generateContentSitemap, entryToMetadata, type GenerateContentStaticParamsOptions, type GenerateContentSitemapOptions, type EntryToMetadataOptions, type SitemapExtraUrl, } from './static.js';
4
5
  export { createMockAuthPlugin, createRejectingAuthPlugin } from './test-utils.js';
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export { createCanopyCatchAllHandler, wrapNextRequest } from './adapter.js';
2
2
  export { createNextCanopyContext, } from './context-wrapper.js';
3
+ export { previewView, } from './preview-page.js';
3
4
  export { collectStaticParams, generateContentSitemap, entryToMetadata, } from './static.js';
4
5
  export { createMockAuthPlugin, createRejectingAuthPlugin } from './test-utils.js';
@@ -0,0 +1,90 @@
1
+ import type { ReactElement, ReactNode } from 'react';
2
+ import type { CanopyConfig } from 'canopycms';
3
+ import type { CanopyContext } from 'canopycms/server';
4
+ import type { CanopyPreviewProps } from './client.js';
5
+ type ReadEntry = NonNullable<Awaited<ReturnType<CanopyContext['readByUrlPath']>>>;
6
+ /**
7
+ * The entry a `load` receives. It carries no `meta.physicalPath`, so a loader that returns its
8
+ * whole `entry` cannot send the server's filesystem layout to the browser.
9
+ */
10
+ export interface PreviewEntry {
11
+ data: unknown;
12
+ path: string;
13
+ entryType: string;
14
+ entryId?: ReadEntry['meta']['entryId'];
15
+ }
16
+ /** What a `load` receives. */
17
+ export interface PreviewLoadContext {
18
+ /** The entry the route is rendering, as read from the requested branch. */
19
+ entry: PreviewEntry;
20
+ /** The request-scoped context the entry was read through: authenticated and ACL-checked. */
21
+ canopy: CanopyContext;
22
+ /** The `?branch=` the editor named, to pass on to further reads. */
23
+ branch: string | undefined;
24
+ }
25
+ /**
26
+ * A view and the server loader that feeds its `extras` prop. Make one with `previewView`.
27
+ *
28
+ * `load` runs on the server, once per request, after the entry is read and its view found, so an
29
+ * entry type with no view is a 404 without running it. It may throw, or call `notFound()`: either
30
+ * rejects the page rather than rendering.
31
+ *
32
+ * Its result reaches the browser like any RSC prop, so it must be RSC-serializable: plain data
33
+ * or React elements. A server-rendered element such as `<RelatedPosts />` is fine, which lets a
34
+ * view reuse a server component for a section that need not update live. The result is a
35
+ * snapshot of the request and does not follow the editor's live draft; only `data` does.
36
+ */
37
+ export interface PreviewViewWithLoader<X> {
38
+ view: (props: CanopyPreviewProps<never, X>) => ReactNode;
39
+ load: (ctx: PreviewLoadContext) => X | Promise<X>;
40
+ }
41
+ /**
42
+ * The form `views` holds, with `X` erased. `view` takes `extras?: never`, so a view of any `X`
43
+ * is assignable (its parameter is only wider), and `load` returns `unknown`, so any loader is
44
+ * too. That drops the check that `load`'s result is what `view` expects, which `previewView`
45
+ * restores where each pair is written.
46
+ */
47
+ interface ErasedPreviewViewWithLoader {
48
+ view: (props: CanopyPreviewProps<never, never>) => ReactNode;
49
+ load: (ctx: PreviewLoadContext) => unknown;
50
+ }
51
+ type PreviewView = (props: CanopyPreviewProps<never>) => ReactNode;
52
+ /**
53
+ * Pairs a view with its loader, so TypeScript checks that `load`'s result is what the view's
54
+ * `extras` prop expects. A record of views cannot infer a distinct `X` per key, so this identity
55
+ * function infers it for each entry on its own.
56
+ */
57
+ export declare function previewView<X>(entry: PreviewViewWithLoader<X>): PreviewViewWithLoader<X>;
58
+ export interface CreatePreviewPageOptions {
59
+ /**
60
+ * The view for each entry type the preview route serves, keyed by entry type name, each made by
61
+ * `withCanopyPreview` (`canopycms-next/client`) in a `'use client'` module, or a
62
+ * `previewView({ view, load })` pair when the view needs more than the entry. An entry whose
63
+ * type has no view is a 404.
64
+ */
65
+ views: Record<string, PreviewView | ErasedPreviewViewWithLoader>;
66
+ /** Editor origin to trust, for an editor on another origin. Defaults to the page's own. */
67
+ editorOrigin?: string;
68
+ }
69
+ /** The props Next passes a `[[...path]]` page. */
70
+ export interface PreviewPageProps {
71
+ params: Promise<{
72
+ path?: string[];
73
+ }>;
74
+ searchParams: Promise<Record<string, string | string[] | undefined>>;
75
+ }
76
+ /**
77
+ * The page for a `[[...path]]` route mounted at `editor.previewPrefix`: it reads the entry at
78
+ * the route's path from the `?branch=` the editor names and renders its view.
79
+ *
80
+ * The read goes through the request-scoped `getCanopy()`, never the build context: it is
81
+ * authenticated and ACL-checked, and a branch other than the active one is only loaded, never
82
+ * created. A missing, unreadable or malformed branch, and a path no entry publishes, are all a
83
+ * 404, so a hidden branch looks the same as a missing one.
84
+ *
85
+ * On a `deployedAs: 'static'` deployment every request is a 404: reads there skip access checks,
86
+ * so the route would show any branch to anyone.
87
+ * @internal Exported for tests.
88
+ */
89
+ export declare function createPreviewPageFor(getCanopy: () => Promise<CanopyContext>, options: CreatePreviewPageOptions, deployedAs?: CanopyConfig['deployedAs']): (props: PreviewPageProps) => Promise<ReactElement>;
90
+ export {};
@@ -0,0 +1,64 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { notFound } from 'next/navigation';
3
+ /**
4
+ * Pairs a view with its loader, so TypeScript checks that `load`'s result is what the view's
5
+ * `extras` prop expects. A record of views cannot infer a distinct `X` per key, so this identity
6
+ * function infers it for each entry on its own.
7
+ */
8
+ export function previewView(entry) {
9
+ return entry;
10
+ }
11
+ function hasLoader(entry) {
12
+ return (typeof entry === 'object' &&
13
+ entry !== null &&
14
+ Object.prototype.hasOwnProperty.call(entry, 'load'));
15
+ }
16
+ /**
17
+ * The page for a `[[...path]]` route mounted at `editor.previewPrefix`: it reads the entry at
18
+ * the route's path from the `?branch=` the editor names and renders its view.
19
+ *
20
+ * The read goes through the request-scoped `getCanopy()`, never the build context: it is
21
+ * authenticated and ACL-checked, and a branch other than the active one is only loaded, never
22
+ * created. A missing, unreadable or malformed branch, and a path no entry publishes, are all a
23
+ * 404, so a hidden branch looks the same as a missing one.
24
+ *
25
+ * On a `deployedAs: 'static'` deployment every request is a 404: reads there skip access checks,
26
+ * so the route would show any branch to anyone.
27
+ * @internal Exported for tests.
28
+ */
29
+ export function createPreviewPageFor(getCanopy, options, deployedAs = 'server') {
30
+ return async function CanopyPreviewPage({ params, searchParams }) {
31
+ if (deployedAs === 'static')
32
+ notFound();
33
+ const [{ path = [] }, query] = await Promise.all([params, searchParams]);
34
+ const branch = query.branch;
35
+ if (Array.isArray(branch))
36
+ notFound();
37
+ const canopy = await getCanopy();
38
+ const result = await canopy.readByUrlPath(`/${path.join('/')}`, { branch });
39
+ if (!result)
40
+ notFound();
41
+ const { entryType } = result.meta;
42
+ const viewEntry = Object.prototype.hasOwnProperty.call(options.views, entryType)
43
+ ? options.views[entryType]
44
+ : undefined;
45
+ if (!viewEntry)
46
+ notFound();
47
+ if (!hasLoader(viewEntry)) {
48
+ const View = viewEntry;
49
+ return _jsx(View, { initialData: result.data, editorOrigin: options.editorOrigin });
50
+ }
51
+ const { meta } = result;
52
+ const entry = {
53
+ data: result.data,
54
+ path: result.path,
55
+ entryType: meta.entryType,
56
+ entryId: meta.entryId,
57
+ };
58
+ const extras = await viewEntry.load({ entry, canopy, branch });
59
+ // The record erases `view` to `extras?: never`, so it cannot check `load`'s result against the
60
+ // view; `previewView` does, where a pair is written.
61
+ const View = viewEntry.view;
62
+ return _jsx(View, { initialData: result.data, editorOrigin: options.editorOrigin, extras: extras });
63
+ };
64
+ }
@@ -40,7 +40,7 @@ export interface WithCanopyOptions {
40
40
  * (kept under `experimental` on Next 13/14 or legacy spellings; your own includes stay), so a
41
41
  * Turbopack `output: 'standalone'` server can load sharp — Next's tracing misses that library
42
42
  * for sharp 0.35 (doesn't fix webpack builds); warns if the directory or version can't be found.
43
- * - `trailingSlash: true` sets `env.CANOPY_API_TRAILING_SLASH`, so editor API calls skip Next's 308.
43
+ * - `trailingSlash: true` sets `env.CANOPY_TRAILING_SLASH`, so the editor's requests skip Next's 308.
44
44
  * - On Next 16+, sets `turbopack: {}` when your config has neither `turbopack` nor `webpack` and
45
45
  * the Next version can be read — Next 16 defaults to Turbopack and exits when a config exports
46
46
  * `webpack` (the React aliases above add one) with no `turbopack` key; a `turbopack` you set is
@@ -337,7 +337,7 @@ function sharpTracingConfig(nextConfig, options) {
337
337
  * (kept under `experimental` on Next 13/14 or legacy spellings; your own includes stay), so a
338
338
  * Turbopack `output: 'standalone'` server can load sharp — Next's tracing misses that library
339
339
  * for sharp 0.35 (doesn't fix webpack builds); warns if the directory or version can't be found.
340
- * - `trailingSlash: true` sets `env.CANOPY_API_TRAILING_SLASH`, so editor API calls skip Next's 308.
340
+ * - `trailingSlash: true` sets `env.CANOPY_TRAILING_SLASH`, so the editor's requests skip Next's 308.
341
341
  * - On Next 16+, sets `turbopack: {}` when your config has neither `turbopack` nor `webpack` and
342
342
  * the Next version can be read — Next 16 defaults to Turbopack and exits when a config exports
343
343
  * `webpack` (the React aliases above add one) with no `turbopack` key; a `turbopack` you set is
@@ -449,10 +449,10 @@ export function withCanopy(nextConfig = {}, options = {}) {
449
449
  // verbatim (`next/dist/build/generate-build-id.js`) — which is what makes a hex tree hash usable
450
450
  // as a build id at all. Do not "helpfully" route this through the fallback.
451
451
  const generateBuildId = nextConfig.generateBuildId ?? (options.staticBuild ? resolveStaticBuildId : undefined);
452
- // Next substitutes `env` into every bundle at build time, where the API client reads it
453
- // (`readApiTrailingSlashEnv` in canopycms's `api/request-url.ts`).
452
+ // Next substitutes `env` into every bundle at build time, where the API client and the editor's
453
+ // preview URLs read it (`readTrailingSlashEnv` in canopycms's `utils/url-prefix.ts`).
454
454
  const env = nextConfig.trailingSlash
455
- ? { CANOPY_API_TRAILING_SLASH: 'true', ...nextConfig.env }
455
+ ? { CANOPY_TRAILING_SLASH: 'true', ...nextConfig.env }
456
456
  : undefined;
457
457
  return {
458
458
  ...nextConfig,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "canopycms-next",
3
- "version": "0.0.68-int.93",
3
+ "version": "0.0.68-int.95",
4
4
  "description": "Next.js adapter for CanopyCMS",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -38,7 +38,7 @@
38
38
  "peerDependencies": {
39
39
  "next": "^13.5.7 || ^14.2.25 || ^15.5.21 || >=16.0.0 <16.2.0 || >=16.3.0 <17.0.0",
40
40
  "react": "^18.0.0 || ^19.0.0",
41
- "canopycms": "0.0.68-int.93"
41
+ "canopycms": "0.0.68-int.95"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@types/node": "^22.9.0",
@@ -48,7 +48,7 @@
48
48
  "react": "^18.3.1",
49
49
  "typescript": "^5.6.3",
50
50
  "vitest": "^4.1.0",
51
- "canopycms": "0.0.68-int.93"
51
+ "canopycms": "0.0.68-int.95"
52
52
  },
53
53
  "scripts": {
54
54
  "build": "rm -rf dist && tsc -p tsconfig.build.json && node ../../scripts/add-js-extensions.mjs dist && esbuild src/config.ts --bundle --platform=node --packages=external --external:next --format=cjs --outfile=dist/config.cjs && esbuild src/config.ts --bundle --platform=node --packages=external --external:next --format=esm --outfile=dist/config.mjs",