@foliwake/next 0.9.0 → 0.10.2

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.
@@ -0,0 +1,24 @@
1
+ import type { StepResult } from './apply.js';
2
+ import type { CheckResult } from './check.js';
3
+ import { type SiteFacts } from './site.js';
4
+ /** The result of an init run, as `--json` prints it. */
5
+ export interface InitReport {
6
+ ok: boolean;
7
+ dryRun: boolean;
8
+ site: string;
9
+ url: string;
10
+ blocks: string | null;
11
+ steps: StepResult[];
12
+ warnings: string[];
13
+ next: string[];
14
+ }
15
+ /** What to do after init. */
16
+ export declare function nextSteps(site: string, opts: {
17
+ preview: boolean;
18
+ hook: boolean;
19
+ mount: string | null;
20
+ }): string[];
21
+ /** The report for people. */
22
+ export declare function humanReport(report: InitReport, facts: SiteFacts): string;
23
+ /** The `--check` report for people. */
24
+ export declare function checkReport(checks: readonly CheckResult[]): string;
@@ -0,0 +1,43 @@
1
+ import { siteLine } from './site.js';
2
+ const MARK = {
3
+ created: '✓',
4
+ updated: '✓',
5
+ exists: '·',
6
+ skipped: '!',
7
+ manual: '!',
8
+ };
9
+ function stepLine(step, dryRun) {
10
+ const changes = step.outcome === 'created' || step.outcome === 'updated';
11
+ const outcome = dryRun && changes ? `would be ${step.outcome}` : step.outcome;
12
+ const note = step.note ? ` (${step.note})` : '';
13
+ return `${MARK[step.outcome]} ${step.path.padEnd(36)} ${outcome}: ${step.what}${note}`;
14
+ }
15
+ /** What to do after init. */
16
+ export function nextSteps(site, opts) {
17
+ const steps = [`Run the app (npm run dev) and open http://localhost:3000${opts.mount ?? ''}/<a page of the site>.`];
18
+ if (opts.preview) {
19
+ steps.push(`Preview: a site admin runs \`foliwake site preview-token --site ${site}\`; ` +
20
+ 'put the token in .env.local as FOLIWAKE_PREVIEW_TOKEN (never commit it). ' +
21
+ 'Replace isAuthor() before you deploy.');
22
+ }
23
+ if (opts.hook) {
24
+ steps.push("Hook: ask the site admin to add https://<your app>/foliwake/hook as the site's app hook, " +
25
+ 'and put the shared secret in FOLIWAKE_HOOK_SECRET.');
26
+ }
27
+ return steps;
28
+ }
29
+ /** The report for people. */
30
+ export function humanReport(report, facts) {
31
+ const lines = [`✓ ${siteLine(facts)}`, ...report.steps.map((step) => stepLine(step, report.dryRun))];
32
+ for (const warning of report.warnings)
33
+ lines.push(`! ${warning}`);
34
+ if (report.dryRun)
35
+ lines.push('Dry run: nothing was written.');
36
+ for (const step of report.next)
37
+ lines.push(`Next: ${step}`);
38
+ return `${lines.join('\n')}\n`;
39
+ }
40
+ /** The `--check` report for people. */
41
+ export function checkReport(checks) {
42
+ return `${checks.map((c) => `${c.ok ? '✓' : '✗'} ${c.name}: ${c.detail}`).join('\n')}\n`;
43
+ }
@@ -0,0 +1,12 @@
1
+ /** What init talks to: streams, the terminal, the environment and (tests) fetch. */
2
+ export interface InitIo {
3
+ stdout: (text: string) => void;
4
+ stderr: (text: string) => void;
5
+ env: NodeJS.ProcessEnv;
6
+ cwd: string;
7
+ /** Asks a question on the terminal; absent when there is none. */
8
+ ask?: (question: string) => Promise<string>;
9
+ fetch?: typeof fetch;
10
+ }
11
+ /** Runs init with `argv` (the words after the program). Returns the exit code. */
12
+ export declare function runInit(argv: string[], io: InitIo): Promise<number>;
@@ -0,0 +1,95 @@
1
+ // `npx @foliwake/next init`: detect the app, check the site, plan, apply (or show the plan), report.
2
+ // Exit codes: 0 done, 1 error, 2 input needed.
3
+ import { checkMount } from '../page-route.js';
4
+ import { applySteps } from './apply.js';
5
+ import { checkSetup } from './check.js';
6
+ import { detectProject, InitError, supportsNext } from './detect.js';
7
+ import { parseOptions, USAGE, UsageError } from './options.js';
8
+ import { planSteps } from './plan.js';
9
+ import { checkReport, humanReport, nextSteps } from './report.js';
10
+ import { verifySite } from './site.js';
11
+ class NeedsInput extends Error {
12
+ }
13
+ const NEEDS_URL = "Give the site's live URL: npx @foliwake/next init --url https://my-site.example.org";
14
+ async function urlOf(opts, io) {
15
+ if (opts.url)
16
+ return opts.url;
17
+ if (opts.yes || !io.ask)
18
+ throw new NeedsInput(NEEDS_URL);
19
+ const answer = (await io.ask("The site's live URL (https://…): ")).trim();
20
+ if (!answer)
21
+ throw new NeedsInput(NEEDS_URL);
22
+ return answer;
23
+ }
24
+ function projectWarnings(project) {
25
+ const warnings = [];
26
+ if (supportsNext(project.nextVersion) === null) {
27
+ warnings.push(`Next ${project.nextVersion ?? '(unknown)'}: cannot tell its version; 16.2 or newer is needed.`);
28
+ }
29
+ if (!project.hasFoliwakeNext)
30
+ warnings.push(`Install the package: ${project.packageManager} add @foliwake/next`);
31
+ if (project.gitClean === null)
32
+ warnings.push('Not a git checkout: review the changes by hand.');
33
+ return warnings;
34
+ }
35
+ function checkProject(project, opts) {
36
+ if (supportsNext(project.nextVersion) === false) {
37
+ throw new InitError(`Next ${project.nextVersion} is too old: @foliwake/next needs Next 16.2 or newer.`);
38
+ }
39
+ if (project.gitClean === false && !opts.ignoreGitChanges && !opts.dryRun) {
40
+ throw new InitError('The git working tree has uncommitted changes: commit them, or pass --ignore-git-changes.');
41
+ }
42
+ }
43
+ async function runCheck(project, opts, io) {
44
+ const checks = await checkSetup(project, io.env, io.fetch);
45
+ io.stdout(opts.json ? `${JSON.stringify({ ok: checks.every((c) => c.ok), checks })}\n` : checkReport(checks));
46
+ return checks.every((c) => c.ok) ? 0 : 1;
47
+ }
48
+ async function runSetup(project, opts, io) {
49
+ const mount = checkMount(opts.mount ?? undefined);
50
+ checkProject(project, opts);
51
+ const facts = await verifySite(await urlOf(opts, io), io.fetch);
52
+ const choices = { url: facts.url, preview: opts.preview, hook: opts.hook, mount };
53
+ const steps = applySteps(planSteps(project, choices), { cwd: project.cwd, dryRun: opts.dryRun, force: opts.force });
54
+ const report = {
55
+ ok: !steps.some((step) => step.outcome === 'manual'),
56
+ dryRun: opts.dryRun,
57
+ site: facts.site,
58
+ url: facts.url,
59
+ blocks: facts.blocks,
60
+ steps,
61
+ warnings: [...projectWarnings(project), ...(facts.note ? [facts.note] : [])],
62
+ next: nextSteps(facts.site, choices),
63
+ };
64
+ io.stdout(opts.json ? `${JSON.stringify(report)}\n` : humanReport(report, facts));
65
+ return 0;
66
+ }
67
+ function failure(error, io, json) {
68
+ const code = error instanceof NeedsInput ? 2 : 1;
69
+ const message = error.message;
70
+ io.stderr(`${json ? JSON.stringify({ ok: false, error: message }) : `✗ ${message}`}\n`);
71
+ return code;
72
+ }
73
+ /** Runs init with `argv` (the words after the program). Returns the exit code. */
74
+ export async function runInit(argv, io) {
75
+ let opts;
76
+ try {
77
+ opts = parseOptions(argv, io.env, io.cwd);
78
+ }
79
+ catch (error) {
80
+ if (error instanceof UsageError)
81
+ return failure(error, io, false);
82
+ throw error;
83
+ }
84
+ if (opts.command === 'help') {
85
+ io.stdout(`${USAGE}\n`);
86
+ return 0;
87
+ }
88
+ try {
89
+ const project = detectProject(opts.cwd);
90
+ return opts.check ? await runCheck(project, opts, io) : await runSetup(project, opts, io);
91
+ }
92
+ catch (error) {
93
+ return failure(error, io, opts.json);
94
+ }
95
+ }
@@ -0,0 +1,15 @@
1
+ import { type FoliwakeDiscovery } from '@foliwake/server/discovery';
2
+ /** What init found on the site. */
3
+ export interface SiteFacts {
4
+ url: string;
5
+ site: string;
6
+ discovery: FoliwakeDiscovery;
7
+ /** `X-Foliwake-Blocks` of the root page, as sent, or null. */
8
+ blocks: string | null;
9
+ /** A note when the root page could not be checked (it may not exist). */
10
+ note: string | null;
11
+ }
12
+ /** Reads the discovery document and checks the root page. Throws (InitError, FoliwakeConfigError). */
13
+ export declare function verifySite(url: string, doFetch?: typeof fetch): Promise<SiteFacts>;
14
+ /** One line about the site, such as `site my-site, plain/2, blocks entry="scripts/blocks.js", …`. */
15
+ export declare function siteLine(facts: SiteFacts): string;
@@ -0,0 +1,35 @@
1
+ // What init checks on the site before writing: its discovery document, and that its pages answer as plain/2
2
+ // (`X-Code-Release` on `/index.plain.html`). Prints what it found; never sends a credential.
3
+ import { fetchDiscovery } from '@foliwake/server/discovery';
4
+ import { InitError } from './detect.js';
5
+ const NO_CODE_RELEASE = 'answered without X-Code-Release: its engine does not serve plain/2 pages. Update the engine, then run init again.';
6
+ async function headIndex(url, doFetch) {
7
+ const signal = AbortSignal.timeout(5000);
8
+ return doFetch(`${url}/index.plain.html`, { method: 'HEAD', redirect: 'manual', signal });
9
+ }
10
+ async function rootPage(url, doFetch) {
11
+ let response;
12
+ try {
13
+ response = await headIndex(url, doFetch);
14
+ }
15
+ catch {
16
+ return { blocks: null, note: `${url}/index.plain.html did not answer; pages were not checked.` };
17
+ }
18
+ if (response.status !== 200) {
19
+ return { blocks: null, note: `${url}/index.plain.html answered HTTP ${response.status}; pages were not checked.` };
20
+ }
21
+ if (!response.headers.get('x-code-release'))
22
+ throw new InitError(`${url}/index.plain.html ${NO_CODE_RELEASE}`);
23
+ return { blocks: response.headers.get('x-foliwake-blocks'), note: null };
24
+ }
25
+ /** Reads the discovery document and checks the root page. Throws (InitError, FoliwakeConfigError). */
26
+ export async function verifySite(url, doFetch = globalThis.fetch) {
27
+ const discovery = await fetchDiscovery(url, { fetch: doFetch });
28
+ const origin = discovery.live.url;
29
+ return { url: origin, site: discovery.site, discovery, ...(await rootPage(origin, doFetch)) };
30
+ }
31
+ /** One line about the site, such as `site my-site, plain/2, blocks entry="scripts/blocks.js", …`. */
32
+ export function siteLine(facts) {
33
+ const blocks = facts.blocks ? `blocks ${facts.blocks}` : 'no blocks module named (pages stay static)';
34
+ return `${facts.url}: site ${facts.site}, plain/${facts.discovery.contracts.plain}, ${blocks}`;
35
+ }
@@ -0,0 +1,14 @@
1
+ /** The first line of every generated file. */
2
+ export declare const GENERATED = "// generated by @foliwake/next init \u2014 edit freely";
3
+ /** The language of the app's files. */
4
+ export type Lang = 'ts' | 'js';
5
+ /** `app/foliwake/[...path]/route.ts`: code, media, hook and health; preview behind isAuthor with --preview. */
6
+ export declare function routeFile(authorImport: string | null): string;
7
+ /** The live page route: one line at the root, a mounted factory otherwise. */
8
+ export declare function livePageFile(mount: string | null): string;
9
+ /** The preview page route under `/preview`, behind isAuthor. */
10
+ export declare function previewPageFile(authorImport: string): string;
11
+ /** The author check stub: everyone while `next dev` runs, nobody in production, until the app replaces it. */
12
+ export declare function isAuthorFile(lang: Lang): string;
13
+ /** A new next.config. */
14
+ export declare function nextConfigFile(): string;
@@ -0,0 +1,29 @@
1
+ // The files `init` writes. Each starts with GENERATED, so `--force` overwrites only files init wrote.
2
+ /** The first line of every generated file. */
3
+ export const GENERATED = '// generated by @foliwake/next init — edit freely';
4
+ const lines = (...rows) => `${rows.join('\n')}\n`;
5
+ /** `app/foliwake/[...path]/route.ts`: code, media, hook and health; preview behind isAuthor with --preview. */
6
+ export function routeFile(authorImport) {
7
+ if (authorImport === null)
8
+ return lines(GENERATED, "export { GET, HEAD, POST } from '@foliwake/next/handler';");
9
+ return lines(GENERATED, "import { createFoliwakeHandler } from '@foliwake/next/handler';", `import { isAuthor } from '${authorImport}';`, '', 'export const { GET, HEAD, POST } = createFoliwakeHandler({ authorizePreview: isAuthor });');
10
+ }
11
+ /** The live page route: one line at the root, a mounted factory otherwise. */
12
+ export function livePageFile(mount) {
13
+ if (mount === null)
14
+ return lines(GENERATED, "export { default, generateMetadata } from '@foliwake/next/page';");
15
+ return lines(GENERATED, "import { createFoliwakePage } from '@foliwake/next/page';", '', `const Page = createFoliwakePage({ mount: '${mount}' });`, '', 'export default Page;', 'export const generateMetadata = Page.generateMetadata;');
16
+ }
17
+ /** The preview page route under `/preview`, behind isAuthor. */
18
+ export function previewPageFile(authorImport) {
19
+ return lines(GENERATED, "import { createFoliwakePage } from '@foliwake/next/page';", `import { isAuthor } from '${authorImport}';`, '', "const Page = createFoliwakePage({ channel: 'preview', authorize: isAuthor, mount: '/preview' });", '', 'export default Page;', 'export const generateMetadata = Page.generateMetadata;');
20
+ }
21
+ /** The author check stub: everyone while `next dev` runs, nobody in production, until the app replaces it. */
22
+ export function isAuthorFile(lang) {
23
+ const signature = lang === 'ts' ? 'export function isAuthor(): boolean {' : 'export function isAuthor() {';
24
+ return lines(GENERATED, '// Replace this with your sign-in: who may see preview (unpublished) pages.', '// Development only: every visitor is an author under `next dev`; in production nobody is.', signature, " return process.env.NODE_ENV === 'development';", '}');
25
+ }
26
+ /** A new next.config. */
27
+ export function nextConfigFile() {
28
+ return lines("import { withFoliwake } from '@foliwake/next/config';", '', 'export default withFoliwake({ cacheComponents: true });');
29
+ }
@@ -0,0 +1,21 @@
1
+ import type { ChannelName, FoliwakePageData } from '@foliwake/blocks-contract/page';
2
+ /** The metadata the route gives Next: the page's title, and `noindex` for preview. */
3
+ export interface PageMetadata {
4
+ title?: string;
5
+ robots?: {
6
+ index: false;
7
+ follow: false;
8
+ };
9
+ }
10
+ /** The site's page path of a catch-all route's segments (`['lessons', 'a']` → `/lessons/a`, none → `/`). */
11
+ export declare function pagePathOf(segments: readonly string[] | undefined): string;
12
+ /** Checks the channel of a page route; preview needs the app's author check. */
13
+ export declare function checkPageChannel(channel: ChannelName | undefined, authorize: unknown): ChannelName;
14
+ /** Checks a mount (`/pages`) and returns it, or null for the app's root. */
15
+ export declare function checkMount(mount: string | undefined): string | null;
16
+ /** How the body's root-relative links become app links: as they are at the root, under the mount otherwise. */
17
+ export declare function mountRewriter(mount: string | null): ((href: string) => string) | undefined;
18
+ /** The metadata of a page (null: not found, nothing to say). */
19
+ export declare function metadataOf(page: FoliwakePageData | null, channel: ChannelName): PageMetadata;
20
+ /** Reads a page; a missing page or one outside `app.pages` is null; any other error is thrown. */
21
+ export declare function readOrNull(read: () => Promise<FoliwakePageData>): Promise<FoliwakePageData | null>;
@@ -0,0 +1,55 @@
1
+ const MOUNT = /^(?:\/[a-z0-9-]+)+$/;
2
+ /** The site's page path of a catch-all route's segments (`['lessons', 'a']` → `/lessons/a`, none → `/`). */
3
+ export function pagePathOf(segments) {
4
+ return `/${(segments ?? []).join('/')}`;
5
+ }
6
+ /** Checks the channel of a page route; preview needs the app's author check. */
7
+ export function checkPageChannel(channel, authorize) {
8
+ const chosen = channel ?? 'live';
9
+ if (chosen !== 'live' && chosen !== 'preview')
10
+ throw new TypeError("channel: 'live' or 'preview'.");
11
+ if (chosen === 'preview' && typeof authorize !== 'function') {
12
+ throw new TypeError("A preview page needs authorize: the app's author check; no default shows preview.");
13
+ }
14
+ return chosen;
15
+ }
16
+ /** Checks a mount (`/pages`) and returns it, or null for the app's root. */
17
+ export function checkMount(mount) {
18
+ if (mount === undefined || mount === '/')
19
+ return null;
20
+ if (!MOUNT.test(mount))
21
+ throw new TypeError(`mount: an app path of [a-z0-9-] segments, such as "/pages".`);
22
+ return mount;
23
+ }
24
+ /** How the body's root-relative links become app links: as they are at the root, under the mount otherwise. */
25
+ export function mountRewriter(mount) {
26
+ if (mount === null)
27
+ return undefined;
28
+ return (href) => `${mount}${href === '/' ? '' : href}`;
29
+ }
30
+ /** The metadata of a page (null: not found, nothing to say). */
31
+ export function metadataOf(page, channel) {
32
+ const metadata = {};
33
+ if (page?.title)
34
+ metadata.title = page.title;
35
+ if (channel === 'preview')
36
+ metadata.robots = { index: false, follow: false };
37
+ return metadata;
38
+ }
39
+ function isMissing(error) {
40
+ if (typeof error !== 'object' || error === null)
41
+ return false;
42
+ const { name, kind } = error;
43
+ return name === 'FoliwakePageError' && (kind === 'not_found' || kind === 'not_allowed');
44
+ }
45
+ /** Reads a page; a missing page or one outside `app.pages` is null; any other error is thrown. */
46
+ export async function readOrNull(read) {
47
+ try {
48
+ return await read();
49
+ }
50
+ catch (error) {
51
+ if (isMissing(error))
52
+ return null;
53
+ throw error;
54
+ }
55
+ }
@@ -0,0 +1,42 @@
1
+ import 'server-only';
2
+ import { type ReactNode } from 'react';
3
+ import type { ChannelName, FoliwakePageData } from '@foliwake/blocks-contract/page';
4
+ import type { PrepareOptions } from '@foliwake/server/page';
5
+ import { type PageMetadata } from './page-route.js';
6
+ /** The route's props: Next's params of a catch-all segment `[...path]` or `[[...path]]`. */
7
+ export interface FoliwakeRouteProps {
8
+ params: Promise<{
9
+ path?: string[];
10
+ }>;
11
+ }
12
+ /** Options of `createFoliwakePage`. */
13
+ export interface FoliwakePageOptions {
14
+ /** Returns the app's component for the page; default `<FoliwakePage page={page} as="article" />`. */
15
+ render?: (page: FoliwakePageData) => ReactNode;
16
+ /** `preparePage` options; `rewriteLink` defaults to the mount's. */
17
+ prepare?: PrepareOptions;
18
+ /** `live` (default, cached) or `preview` (per request; needs `authorize`). */
19
+ channel?: ChannelName;
20
+ /** The app's author check (cookies(), headers(), its session); false → not found. Required for preview. */
21
+ authorize?: () => boolean | Promise<boolean>;
22
+ /** The app path the route is mounted at, such as `/pages`; default the root. */
23
+ mount?: string;
24
+ /** The Suspense fallback while the page is read; default none. */
25
+ fallback?: ReactNode;
26
+ }
27
+ /** A page route component with its `generateMetadata`. */
28
+ export type FoliwakeRoute = ((props: FoliwakeRouteProps) => ReactNode) & {
29
+ generateMetadata: (props: FoliwakeRouteProps) => Promise<PageMetadata>;
30
+ };
31
+ /**
32
+ * A page route of Foliwake pages: reads the page of the route's path (live: cached; preview: per request, behind
33
+ * `authorize`), renders it in a Suspense boundary, emits the blocks' preload hints and the import map. A missing
34
+ * page, one outside `app.pages`, or a refused author check is `notFound()`. `generateMetadata` gives the title
35
+ * (the body's first `<h1>`) and `noindex` for preview.
36
+ */
37
+ export declare function createFoliwakePage(opts?: FoliwakePageOptions): FoliwakeRoute;
38
+ declare const route: FoliwakeRoute;
39
+ /** The default route: live pages at the app's root. */
40
+ export default route;
41
+ /** The default route's metadata. */
42
+ export declare const generateMetadata: (props: FoliwakeRouteProps) => Promise<PageMetadata>;
@@ -0,0 +1,51 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // @foliwake/next/page: a ready page route. At the app's root, `app/[...path]/page.tsx`:
3
+ //
4
+ // export { default, generateMetadata } from '@foliwake/next/page';
5
+ //
6
+ // The app's own routes win over the catch-all; `/` stays the app's. Customise with createFoliwakePage: the render
7
+ // (host members, events), preview with an author check, a mount such as `/pages`.
8
+ import 'server-only';
9
+ import { Suspense, cache } from 'react';
10
+ import { notFound } from 'next/navigation.js';
11
+ import { FoliwakePage } from './client.js';
12
+ import { emitPreloadHints, FoliwakeImportMap, readPage } from './page.js';
13
+ import { checkMount, checkPageChannel, metadataOf, mountRewriter, pagePathOf, readOrNull, } from './page-route.js';
14
+ const defaultRender = (page) => _jsx(FoliwakePage, { page: page, as: "article" });
15
+ /** Reads one page per request and path (React cache: the render and generateMetadata share it). */
16
+ function pageReader(opts, channel) {
17
+ const rewriteLink = mountRewriter(checkMount(opts.mount));
18
+ const prepare = { ...(rewriteLink ? { rewriteLink } : {}), ...(opts.prepare ?? {}) };
19
+ return cache(async (path) => {
20
+ if (opts.authorize && !(await opts.authorize()))
21
+ return null;
22
+ return readOrNull(() => readPage(path, { ...prepare, channel }));
23
+ });
24
+ }
25
+ /**
26
+ * A page route of Foliwake pages: reads the page of the route's path (live: cached; preview: per request, behind
27
+ * `authorize`), renders it in a Suspense boundary, emits the blocks' preload hints and the import map. A missing
28
+ * page, one outside `app.pages`, or a refused author check is `notFound()`. `generateMetadata` gives the title
29
+ * (the body's first `<h1>`) and `noindex` for preview.
30
+ */
31
+ export function createFoliwakePage(opts = {}) {
32
+ const channel = checkPageChannel(opts.channel, opts.authorize);
33
+ checkMount(opts.mount);
34
+ const read = pageReader(opts, channel);
35
+ const render = opts.render ?? defaultRender;
36
+ async function Body({ params }) {
37
+ const page = await read(pagePathOf((await params).path));
38
+ if (page === null)
39
+ notFound();
40
+ emitPreloadHints(page);
41
+ return (_jsxs(_Fragment, { children: [_jsx(FoliwakeImportMap, { page: page }), render(page)] }));
42
+ }
43
+ const Route = (props) => (_jsx(Suspense, { fallback: opts.fallback ?? null, children: _jsx(Body, { params: props.params }) }));
44
+ const generateMetadata = async ({ params }) => metadataOf(await read(pagePathOf((await params).path)), channel);
45
+ return Object.assign(Route, { generateMetadata });
46
+ }
47
+ const route = createFoliwakePage();
48
+ /** The default route: live pages at the app's root. */
49
+ export default route;
50
+ /** The default route's metadata. */
51
+ export const generateMetadata = route.generateMetadata;
@@ -6,8 +6,9 @@ import { revalidateTag } from 'next/cache.js';
6
6
  import { after } from 'next/server.js';
7
7
  import { checkEnvName } from '@foliwake/server/config';
8
8
  import { readEnvelopeCachedEntry } from './cache.js';
9
- import { createRevalidateHandler } from './revalidate-core.js';
9
+ import { createHookEndpoint, hookSecretsFrom } from '@foliwake/server/hook-endpoint';
10
10
  import { foliwakeConfig, foliwakeTags } from './server.js';
11
+ import { SDK } from './version.js';
11
12
  function checkOptions(opts) {
12
13
  if (!opts || typeof opts.secretEnv !== 'string') {
13
14
  throw new TypeError("Pass { secretEnv: '<the variable holding the hook secret>' }.");
@@ -41,9 +42,10 @@ export function foliwakeRevalidateHandler(opts) {
41
42
  checkOptions(opts);
42
43
  let handler = null;
43
44
  const POST = (request) => {
44
- handler ??= createRevalidateHandler({
45
+ handler ??= createHookEndpoint({
45
46
  site: foliwakeConfig().site,
46
- secrets: () => [process.env[opts.secretEnv], opts.previousSecretEnv && process.env[opts.previousSecretEnv]],
47
+ sdk: SDK,
48
+ secrets: hookSecretsFrom({ names: [opts.secretEnv, opts.previousSecretEnv], log: console }),
47
49
  liveTag,
48
50
  expire: expireWith(opts.mode ?? 'expire'),
49
51
  warm: (path) => readEnvelopeCachedEntry(path),
@@ -1,4 +1,14 @@
1
1
  import { type FoliwakeAppConfig } from '@foliwake/server/config';
2
+ import { type FoliwakeConfigSnapshot } from '@foliwake/server/resolve';
2
3
  /** The Next `env` key withFoliwake() sets. Not NEXT_PUBLIC_: never inlined into client code by name. */
3
4
  export declare const CONFIG_ENV_KEY = "FOLIWAKE_APP_CONFIG";
5
+ /** What withFoliwake inlines: a snapshot (version 3 / discovery), or a version 2 file's name and text. */
6
+ export type InlinedConfig = {
7
+ snapshot: FoliwakeConfigSnapshot;
8
+ } | {
9
+ file: string;
10
+ text: string;
11
+ };
12
+ /** The config of an inlined value. */
13
+ export declare function configOfInlined(inlined: InlinedConfig): FoliwakeAppConfig;
4
14
  export declare function loadConfigSync(): FoliwakeAppConfig;
package/dist/settings.js CHANGED
@@ -1,22 +1,32 @@
1
- // Where the app's Foliwake config comes from at run time: withFoliwake() validates the file at build time and
2
- // inlines it (Next `env`) into server code only (this module is imported from server-only modules). Without
3
- // withFoliwake, the file is read on first use (FOLIWAKE_REMOTE or ./foliwake.remote.json).
1
+ // Where the app's Foliwake config comes from at run time: withFoliwake() reads it at build time (the version 2 file,
2
+ // or FOLIWAKE_URL's discovery document with the optional version 3 file) and inlines a snapshot (Next `env`) into
3
+ // server code only (this module is imported from server-only modules). Without withFoliwake, a version 2 file is
4
+ // read on first use (FOLIWAKE_REMOTE or ./foliwake.remote.json); FOLIWAKE_URL needs withFoliwake.
4
5
  import { readFileSync } from 'node:fs';
5
6
  import path from 'node:path';
6
7
  import { configFilePath, parseFoliwakeConfig } from '@foliwake/server/config';
8
+ import { configFromSnapshot, URL_ENV } from '@foliwake/server/resolve';
7
9
  /** The Next `env` key withFoliwake() sets. Not NEXT_PUBLIC_: never inlined into client code by name. */
8
10
  export const CONFIG_ENV_KEY = 'FOLIWAKE_APP_CONFIG';
9
11
  let cached = null;
12
+ /** The config of an inlined value. */
13
+ export function configOfInlined(inlined) {
14
+ if ('snapshot' in inlined)
15
+ return configFromSnapshot(inlined.snapshot);
16
+ return parseFoliwakeConfig(inlined.text, { file: inlined.file });
17
+ }
18
+ const NOT_WRAPPED = `${URL_ENV} is set, but next.config does not use withFoliwake(): the site's discovery document is read when ` +
19
+ 'Next loads next.config. Wrap the config: export default withFoliwake({ cacheComponents: true }).';
20
+ function readWithoutWrapper() {
21
+ if (process.env[URL_ENV])
22
+ throw new Error(NOT_WRAPPED);
23
+ const file = configFilePath();
24
+ return parseFoliwakeConfig(readFileSync(file, 'utf8'), { file: path.basename(file) });
25
+ }
10
26
  export function loadConfigSync() {
11
27
  if (cached)
12
28
  return cached;
13
29
  const inlined = process.env.FOLIWAKE_APP_CONFIG;
14
- if (inlined) {
15
- const { file, text } = JSON.parse(inlined);
16
- cached = parseFoliwakeConfig(text, { file });
17
- return cached;
18
- }
19
- const file = configFilePath();
20
- cached = parseFoliwakeConfig(readFileSync(file, 'utf8'), { file: path.basename(file) });
30
+ cached = inlined ? configOfInlined(JSON.parse(inlined)) : readWithoutWrapper();
21
31
  return cached;
22
32
  }
@@ -0,0 +1 @@
1
+ export declare const SDK = "@foliwake/next/__FOLIWAKE_NEXT_VERSION__";
@@ -0,0 +1,2 @@
1
+ // What the hook endpoint answers a ping with: this package and its version, stamped in by tools/build.mjs.
2
+ export const SDK = '@foliwake/next/0.10.2';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foliwake/next",
3
- "version": "0.9.0",
3
+ "version": "0.10.2",
4
4
  "description": "Next.js App Router adapter for Foliwake pages: withFoliwake, cached envelope read, <FoliwakeServerPage>, preview pages, code and media route handlers, CSP header.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -10,7 +10,7 @@
10
10
  "url": "git+https://github.com/foliwake/foliwake-js.git",
11
11
  "directory": "packages/next"
12
12
  },
13
- "homepage": "https://sdk.foliwake.dev/reference/packages/next",
13
+ "homepage": "https://sdk.foliwake.org/reference/packages/next",
14
14
  "bugs": {
15
15
  "url": "https://github.com/foliwake/foliwake-js/issues"
16
16
  },
@@ -31,10 +31,14 @@
31
31
  "access": "public",
32
32
  "provenance": true
33
33
  },
34
+ "bin": {
35
+ "foliwake-next": "./dist/init/bin.js"
36
+ },
34
37
  "foliwake": {
35
38
  "plain": 2,
36
39
  "blocksContract": 2,
37
- "remoteConfig": 2
40
+ "remoteConfig": 3,
41
+ "discovery": 1
38
42
  },
39
43
  "exports": {
40
44
  ".": {
@@ -49,6 +53,14 @@
49
53
  "types": "./dist/config.d.ts",
50
54
  "default": "./dist/config.js"
51
55
  },
56
+ "./page": {
57
+ "types": "./dist/ready-page.d.ts",
58
+ "default": "./dist/ready-page.js"
59
+ },
60
+ "./handler": {
61
+ "types": "./dist/handler.d.ts",
62
+ "default": "./dist/handler.js"
63
+ },
52
64
  "./routes": {
53
65
  "types": "./dist/routes.d.ts",
54
66
  "default": "./dist/routes.js"
@@ -61,13 +73,15 @@
61
73
  "types": "./dist/revalidate.d.ts",
62
74
  "default": "./dist/revalidate.js"
63
75
  },
76
+ "./schemas/remote-2.schema.json": "./schemas/remote-2.schema.json",
77
+ "./schemas/remote-3.schema.json": "./schemas/remote-3.schema.json",
64
78
  "./package.json": "./package.json"
65
79
  },
66
80
  "dependencies": {
67
81
  "server-only": "0.0.1",
68
- "@foliwake/blocks-contract": "0.9.0",
69
- "@foliwake/react": "0.9.0",
70
- "@foliwake/server": "0.9.0"
82
+ "@foliwake/blocks-contract": "0.10.2",
83
+ "@foliwake/react": "0.10.2",
84
+ "@foliwake/server": "0.10.2"
71
85
  },
72
86
  "peerDependencies": {
73
87
  "next": ">=16.2.0 <17",
@@ -85,6 +99,7 @@
85
99
  "!dist/**/*.map",
86
100
  "!dist/.build-stamp",
87
101
  "!dist/.build-manifest.json",
102
+ "schemas/",
88
103
  "LICENSE",
89
104
  "README.md",
90
105
  "CHANGELOG.md"