create-nextblock 0.15.9 → 0.16.1
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/package.json +1 -1
- package/templates/nextblock-template/app/api/ai/seo/alt-text/route.ts +221 -0
- package/templates/nextblock-template/app/api/ai/seo/metadata/route.ts +186 -0
- package/templates/nextblock-template/app/api/cron/reset-sandbox/sandboxResetSql.ts +193 -1
- package/templates/nextblock-template/app/cms/CmsClientLayout.tsx +7 -1
- package/templates/nextblock-template/app/cms/blocks/components/BlockEditorArea.tsx +27 -0
- package/templates/nextblock-template/app/cms/blocks/editors/ImageBlockEditor.tsx +406 -229
- package/templates/nextblock-template/app/cms/blocks/editors/TextBlockEditor.tsx +171 -6
- package/templates/nextblock-template/app/cms/components/FeatureImageField.tsx +254 -245
- package/templates/nextblock-template/app/cms/media/components/MediaEditForm.tsx +177 -2
- package/templates/nextblock-template/app/cms/pages/[id]/edit/EditPageClient.tsx +28 -0
- package/templates/nextblock-template/app/cms/pages/components/PageForm.tsx +649 -406
- package/templates/nextblock-template/app/cms/posts/[id]/edit/page.tsx +33 -0
- package/templates/nextblock-template/app/cms/posts/components/PostForm.tsx +618 -383
- package/templates/nextblock-template/app/cms/settings/seo/RedirectsCard.tsx +514 -0
- package/templates/nextblock-template/app/cms/settings/seo/RobotsCard.tsx +529 -0
- package/templates/nextblock-template/app/cms/settings/seo/SeoSettingsClient.tsx +57 -0
- package/templates/nextblock-template/app/cms/settings/seo/actions.ts +448 -0
- package/templates/nextblock-template/app/cms/settings/seo/mappers.ts +93 -0
- package/templates/nextblock-template/app/cms/settings/seo/page.tsx +46 -0
- package/templates/nextblock-template/app/cms/settings/seo/require-admin.ts +47 -0
- package/templates/nextblock-template/app/layout.tsx +1 -1
- package/templates/nextblock-template/app/robots.ts +123 -0
- package/templates/nextblock-template/app/sitemap.ts +1 -1
- package/templates/nextblock-template/components/seo/GenerateMetaButton.tsx +137 -0
- package/templates/nextblock-template/components/seo/PageSeoAuditSection.tsx +244 -0
- package/templates/nextblock-template/components/seo/SeoAuditPanel.tsx +749 -0
- package/templates/nextblock-template/components/seo/SeoIssueList.tsx +195 -0
- package/templates/nextblock-template/components/seo/SeoScoreDial.tsx +144 -0
- package/templates/nextblock-template/components/seo/SocialPreview.tsx +243 -0
- package/templates/nextblock-template/components/seo/SocialPreviewDialog.tsx +110 -0
- package/templates/nextblock-template/lib/cortex-ai/alt-text-request.ts +86 -0
- package/templates/nextblock-template/lib/cortex-ai/sandbox-headers.ts +60 -0
- package/templates/nextblock-template/lib/seo/alt-text-write-back.test.ts +154 -0
- package/templates/nextblock-template/lib/seo/alt-text-write-back.ts +109 -0
- package/templates/nextblock-template/lib/seo/block-content.ts +123 -0
- package/templates/nextblock-template/lib/seo/fix-prompts.test.ts +242 -0
- package/templates/nextblock-template/lib/seo/fix-prompts.ts +204 -0
- package/templates/nextblock-template/lib/seo/page-audit-context.tsx +140 -0
- package/templates/nextblock-template/lib/seo/page-document.test.ts +350 -0
- package/templates/nextblock-template/lib/seo/page-document.ts +412 -0
- package/templates/nextblock-template/lib/seo/redirect-store.test.ts +479 -0
- package/templates/nextblock-template/lib/seo/redirect-store.ts +466 -0
- package/templates/nextblock-template/lib/seo/robots-settings-signature.test.ts +102 -0
- package/templates/nextblock-template/lib/seo/robots-settings-signature.ts +41 -0
- package/templates/nextblock-template/lib/seo/robots-txt.test.ts +370 -0
- package/templates/nextblock-template/lib/seo/robots-txt.ts +510 -0
- package/templates/nextblock-template/lib/setup/migrations-bundle.ts +10 -0
- package/templates/nextblock-template/next-env.d.ts +2 -2
- package/templates/nextblock-template/package.json +1 -1
- package/templates/nextblock-template/proxy.ts +240 -20
- package/templates/nextblock-template/app/robots.txt/route.ts +0 -32
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import { useState } from 'react';
|
|
4
|
+
import { Share2 } from 'lucide-react';
|
|
5
|
+
import {
|
|
6
|
+
Button,
|
|
7
|
+
Dialog,
|
|
8
|
+
DialogContent,
|
|
9
|
+
DialogDescription,
|
|
10
|
+
DialogHeader,
|
|
11
|
+
DialogTitle,
|
|
12
|
+
DialogTrigger,
|
|
13
|
+
} from '@nextblock-cms/ui';
|
|
14
|
+
import SocialPreview from './SocialPreview';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The share-card rehearsal, moved behind a button.
|
|
18
|
+
*
|
|
19
|
+
* WHY A MODAL. `SocialPreview` renders three platform tabs above a 1.91:1 card that is up
|
|
20
|
+
* to 520px wide, so inline it costs roughly four hundred vertical pixels in the middle of
|
|
21
|
+
* a page/post settings form that is already long enough to scroll. That is a poor trade for
|
|
22
|
+
* something an author consults once while wording a description and then never looks at
|
|
23
|
+
* again for the rest of the session. Behind a trigger it costs one line, and the moment it
|
|
24
|
+
* IS wanted it gets the whole viewport instead of a squeezed column.
|
|
25
|
+
*
|
|
26
|
+
* WHY THE PRESENTATIONAL COMPONENT STAYS UNTOUCHED. `SocialPreview` knows how three feeds
|
|
27
|
+
* clip a headline and nothing else — no open state, no trigger, no dialog. Keeping that
|
|
28
|
+
* split means the same preview can still be dropped inline anywhere it earns the space
|
|
29
|
+
* (a future site-wide SEO screen, a publish-confirmation step) without having to be
|
|
30
|
+
* unwrapped from a modal first. This component owns the disclosure; that one owns the
|
|
31
|
+
* drawing.
|
|
32
|
+
*
|
|
33
|
+
* WHY IT STAYS LIVE WHILE OPEN. The props below are the caller's live form state, so every
|
|
34
|
+
* keystroke in the meta fields behind the dialog repaints the card — the same behaviour the
|
|
35
|
+
* inline version had. The dialog is a React portal, not a snapshot, so nothing is frozen at
|
|
36
|
+
* open time and there is no "reopen to refresh" trap.
|
|
37
|
+
*
|
|
38
|
+
* NOTHING HERE PERSISTS. This component holds exactly one piece of state — whether the
|
|
39
|
+
* modal is open — and it is read by nobody but Radix. It contributes no form field, no
|
|
40
|
+
* FormData entry, and no input to the caller's autosave diff.
|
|
41
|
+
*/
|
|
42
|
+
interface SocialPreviewDialogProps {
|
|
43
|
+
description: string;
|
|
44
|
+
imageUrl?: string | null;
|
|
45
|
+
siteName?: string | null;
|
|
46
|
+
title: string;
|
|
47
|
+
/** Optional override for the trigger label, for surfaces that word it differently. */
|
|
48
|
+
triggerLabel?: string;
|
|
49
|
+
url: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export default function SocialPreviewDialog({
|
|
53
|
+
description,
|
|
54
|
+
imageUrl,
|
|
55
|
+
siteName,
|
|
56
|
+
title,
|
|
57
|
+
triggerLabel = 'Preview share card',
|
|
58
|
+
url,
|
|
59
|
+
}: SocialPreviewDialogProps) {
|
|
60
|
+
const [isOpen, setIsOpen] = useState(false);
|
|
61
|
+
|
|
62
|
+
return (
|
|
63
|
+
<Dialog onOpenChange={setIsOpen} open={isOpen}>
|
|
64
|
+
{/* `asChild` so the trigger is the house `Button` rather than a bare Radix button, and
|
|
65
|
+
`type="button"` explicitly: this renders inside the page/post `<form>`, where a
|
|
66
|
+
button that inherits the default `submit` type would save the record instead of
|
|
67
|
+
opening a preview. The visible text is the accessible name, and Radix leaves the
|
|
68
|
+
element a real focusable button, so keyboard and pointer reach it identically. */}
|
|
69
|
+
<DialogTrigger asChild>
|
|
70
|
+
<Button className="h-7 px-2 text-[11px]" size="sm" type="button" variant="outline">
|
|
71
|
+
<Share2 aria-hidden="true" className="mr-1.5 h-3.5 w-3.5" />
|
|
72
|
+
{triggerLabel}
|
|
73
|
+
</Button>
|
|
74
|
+
</DialogTrigger>
|
|
75
|
+
|
|
76
|
+
{/* The card is tall and the platform switcher sits above it, so the panel is capped at
|
|
77
|
+
85% of the viewport and the BODY scrolls rather than the dialog growing past the
|
|
78
|
+
screen edge — on a laptop in a browser with devtools open, an uncapped panel would
|
|
79
|
+
push its own close button out of reach. `overflow-hidden` on the shell keeps the
|
|
80
|
+
rounded corners from being cut by the scrolling child. */}
|
|
81
|
+
<DialogContent className="flex max-h-[85vh] flex-col gap-0 overflow-hidden sm:max-w-[600px]">
|
|
82
|
+
{/* `pr-8` reserves room for the close affordance the dialog draws at top-right. */}
|
|
83
|
+
<DialogHeader className="flex-shrink-0 pb-4 pr-8">
|
|
84
|
+
<DialogTitle>Share preview</DialogTitle>
|
|
85
|
+
<DialogDescription>
|
|
86
|
+
How this link is likely to appear when it is shared. Edit the meta title and
|
|
87
|
+
description behind this dialog and the card updates as you type.
|
|
88
|
+
</DialogDescription>
|
|
89
|
+
</DialogHeader>
|
|
90
|
+
|
|
91
|
+
<div className="flex-grow overflow-y-auto py-1">
|
|
92
|
+
<SocialPreview
|
|
93
|
+
description={description}
|
|
94
|
+
imageUrl={imageUrl}
|
|
95
|
+
siteName={siteName}
|
|
96
|
+
title={title}
|
|
97
|
+
url={url}
|
|
98
|
+
/>
|
|
99
|
+
</div>
|
|
100
|
+
|
|
101
|
+
{/* Stated once here rather than repeated on each tab: the numbers in the preview are
|
|
102
|
+
tuned to observed rendering, and every platform reserves the right to reflow. */}
|
|
103
|
+
<p className="flex-shrink-0 pt-3 text-[11px] leading-snug text-muted-foreground">
|
|
104
|
+
Truncation is approximate — each platform reflows link previews on its own terms —
|
|
105
|
+
so treat a card that clips here as a prompt to shorten the copy, not a guarantee.
|
|
106
|
+
</p>
|
|
107
|
+
</DialogContent>
|
|
108
|
+
</Dialog>
|
|
109
|
+
);
|
|
110
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers for assembling a valid `POST /api/ai/seo/alt-text` body from what the CMS has
|
|
3
|
+
* on hand. Both call sites — the image block editor and the media library edit form —
|
|
4
|
+
* face the same two problems, so they are solved once here.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Turn whatever the CMS has for an image into a URL the AI vision call can actually fetch.
|
|
9
|
+
*
|
|
10
|
+
* Why this is not just "pass the src along": `/api/ai/seo/alt-text` does not receive the
|
|
11
|
+
* image bytes, it receives a URL, and the AI SDK downloads that URL *server-side* before
|
|
12
|
+
* handing the image to the model. A relative path is meaningless in that context — there
|
|
13
|
+
* is no document base to resolve it against — so the route rejects anything that is not
|
|
14
|
+
* absolute http(s).
|
|
15
|
+
*
|
|
16
|
+
* And relative is the common case, not the exotic one. `resolveMediaUrl()` returns
|
|
17
|
+
* `/${objectKey}` whenever `NEXT_PUBLIC_R2_BASE_URL` is unset, which is exactly how the
|
|
18
|
+
* native Supabase-storage backend runs. So on a default install every single image in
|
|
19
|
+
* the library would otherwise fail the alt-text call. Resolving against
|
|
20
|
+
* `window.location.origin` fixes that for any deployment the browser can reach, which is
|
|
21
|
+
* the same origin the server is serving from.
|
|
22
|
+
*
|
|
23
|
+
* The remaining failure the caller must surface rather than swallow is a `blob:` or
|
|
24
|
+
* `data:` src (an un-uploaded local preview): the server cannot fetch either, so we
|
|
25
|
+
* return null and let the UI say so instead of firing a request that is certain to 400.
|
|
26
|
+
*/
|
|
27
|
+
export function toAbsoluteImageUrl(url: string | null | undefined): string | null {
|
|
28
|
+
const candidate = (url ?? '').trim();
|
|
29
|
+
if (!candidate) {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (/^https?:\/\//i.test(candidate)) {
|
|
34
|
+
return candidate;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Only the browser knows the origin this CMS is being served from; on the server we
|
|
38
|
+
// have no basis to invent one, so a relative path stays unusable and the caller warns.
|
|
39
|
+
if (typeof window === 'undefined') {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
try {
|
|
44
|
+
const absolute = new URL(candidate, window.location.origin);
|
|
45
|
+
return absolute.protocol === 'http:' || absolute.protocol === 'https:'
|
|
46
|
+
? absolute.toString()
|
|
47
|
+
: null;
|
|
48
|
+
} catch {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Shared copy for the inline warning shown when {@link toAbsoluteImageUrl} returns null. */
|
|
54
|
+
export const UNRESOLVABLE_IMAGE_URL_MESSAGE =
|
|
55
|
+
'This image has no public http(s) address yet, so Cortex AI cannot look at it. Save it to the media library first.';
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The route validates `context` with `z.string().max(2000)` inside a `z.strictObject`, so
|
|
59
|
+
* an over-long value does not get trimmed server-side — it fails the whole request with a
|
|
60
|
+
* 400. Captions are free-text inputs with no length limit of their own, which makes that
|
|
61
|
+
* reachable: a long caption would break the alt-text button for reasons the operator could
|
|
62
|
+
* never guess from the error. Trimming client-side keeps the request valid, and losing the
|
|
63
|
+
* tail of a 2,000-character caption costs nothing, since context is a hint and the model
|
|
64
|
+
* has the image itself.
|
|
65
|
+
*/
|
|
66
|
+
const ALT_TEXT_CONTEXT_MAX_LENGTH = 2000;
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Join the context fragments a caller has into one string the route will accept, or return
|
|
70
|
+
* `undefined` when there is nothing worth sending — the field is optional, and an empty
|
|
71
|
+
* string is a different (and less honest) thing to send than no field at all.
|
|
72
|
+
*/
|
|
73
|
+
export function buildAltTextContext(...fragments: Array<string | null | undefined>): string | undefined {
|
|
74
|
+
const joined = fragments
|
|
75
|
+
.map((fragment) => (fragment ?? '').trim())
|
|
76
|
+
.filter(Boolean)
|
|
77
|
+
.join(' ');
|
|
78
|
+
|
|
79
|
+
if (!joined) {
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return joined.length > ALT_TEXT_CONTEXT_MAX_LENGTH
|
|
84
|
+
? joined.slice(0, ALT_TEXT_CONTEXT_MAX_LENGTH)
|
|
85
|
+
: joined;
|
|
86
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sandbox credential passthrough for browser-initiated Cortex AI requests.
|
|
3
|
+
*
|
|
4
|
+
* On the hosted sandbox there is no server-side OpenRouter key, because every visitor
|
|
5
|
+
* shares one deployment and we will not spend the project's credits on strangers.
|
|
6
|
+
* Instead each visitor pastes their own key into the Cortex AI settings screen, which
|
|
7
|
+
* stores it in `localStorage`, and every AI call made from the browser forwards it on
|
|
8
|
+
* the request as a header. The route only reads those headers when
|
|
9
|
+
* `NEXT_PUBLIC_IS_SANDBOX === 'true'`, so on a real install the headers are ignored
|
|
10
|
+
* even if something were to send them.
|
|
11
|
+
*
|
|
12
|
+
* This lived inline in `NotionEditor.handleAiGenerate` and was about to be copied into
|
|
13
|
+
* three more call sites (image alt text, media alt text, page/post metadata). Copies
|
|
14
|
+
* drift: the day a storage key or header name changes, the forgotten copy silently
|
|
15
|
+
* stops authenticating and the sandbox user sees "no credentials" from one button and
|
|
16
|
+
* not another. One exported builder keeps that impossible.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** localStorage key holding the visitor's own OpenRouter API key on the sandbox. */
|
|
20
|
+
export const CORTEX_AI_SANDBOX_API_KEY_STORAGE_KEY = 'cortex_ai_sandbox_openrouter_api_key';
|
|
21
|
+
|
|
22
|
+
/** localStorage key holding the visitor's serialized model selection on the sandbox. */
|
|
23
|
+
export const CORTEX_AI_SANDBOX_MODEL_STORAGE_KEY = 'cortex_ai_sandbox_openrouter_model_selection';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Builds the headers for a JSON POST to a Cortex AI route, adding the sandbox
|
|
27
|
+
* credential headers when — and only when — this build is the sandbox and the visitor
|
|
28
|
+
* has actually stored a key.
|
|
29
|
+
*
|
|
30
|
+
* `localStorage` access is wrapped in try/catch on purpose: a browser configured to
|
|
31
|
+
* block site data throws on the *accessor itself*, not just on read, and an AI button
|
|
32
|
+
* that explodes before it can send a request is a far worse failure than one that sends
|
|
33
|
+
* an unauthenticated request and gets a clean 403 back.
|
|
34
|
+
*/
|
|
35
|
+
export function buildCortexAiRequestHeaders(): Record<string, string> {
|
|
36
|
+
const headers: Record<string, string> = {
|
|
37
|
+
'content-type': 'application/json',
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
if (process.env.NEXT_PUBLIC_IS_SANDBOX !== 'true' || typeof window === 'undefined') {
|
|
41
|
+
return headers;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
try {
|
|
45
|
+
const sandboxKey = window.localStorage.getItem(CORTEX_AI_SANDBOX_API_KEY_STORAGE_KEY);
|
|
46
|
+
const sandboxModel = window.localStorage.getItem(CORTEX_AI_SANDBOX_MODEL_STORAGE_KEY);
|
|
47
|
+
|
|
48
|
+
if (sandboxKey) {
|
|
49
|
+
headers['x-sandbox-openrouter-key'] = sandboxKey;
|
|
50
|
+
}
|
|
51
|
+
if (sandboxModel) {
|
|
52
|
+
headers['x-sandbox-openrouter-model'] = sandboxModel;
|
|
53
|
+
}
|
|
54
|
+
} catch {
|
|
55
|
+
// Storage is unavailable (private window, blocked site data). Fall through with the
|
|
56
|
+
// plain content-type header; the route will answer 403 and the caller will toast it.
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return headers;
|
|
60
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
altTextImageIdentity,
|
|
5
|
+
resolveAltTextWriteBack,
|
|
6
|
+
STALE_ALT_TEXT_MESSAGE,
|
|
7
|
+
} from './alt-text-write-back';
|
|
8
|
+
|
|
9
|
+
type ImageContent = {
|
|
10
|
+
alt_text: string | null;
|
|
11
|
+
caption: string | null;
|
|
12
|
+
external_url?: string | null;
|
|
13
|
+
media_id: string | null;
|
|
14
|
+
object_key: string | null;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
function content(overrides: Partial<ImageContent> = {}): ImageContent {
|
|
18
|
+
return {
|
|
19
|
+
alt_text: '',
|
|
20
|
+
caption: '',
|
|
21
|
+
external_url: null,
|
|
22
|
+
media_id: 'media-1',
|
|
23
|
+
object_key: 'uploads/harvest.jpg',
|
|
24
|
+
...overrides,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
describe('altTextImageIdentity', () => {
|
|
29
|
+
it('identifies a stored image by its object key', () => {
|
|
30
|
+
expect(altTextImageIdentity(content())).toBe('stored:uploads/harvest.jpg');
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('falls back to the editor selection while content has not echoed it back yet', () => {
|
|
34
|
+
expect(altTextImageIdentity(content({ object_key: null }), 'uploads/just-picked.jpg')).toBe(
|
|
35
|
+
'stored:uploads/just-picked.jpg'
|
|
36
|
+
);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('prefers the external URL, because that is the image the editor renders and sends', () => {
|
|
40
|
+
expect(
|
|
41
|
+
altTextImageIdentity(
|
|
42
|
+
content({ external_url: 'https://images.example.com/a.jpg', object_key: 'uploads/old.jpg' }),
|
|
43
|
+
'uploads/older.jpg'
|
|
44
|
+
)
|
|
45
|
+
).toBe('external:https://images.example.com/a.jpg');
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('returns an empty identity when there is no image at all', () => {
|
|
49
|
+
expect(altTextImageIdentity(content({ media_id: null, object_key: null }))).toBe('');
|
|
50
|
+
expect(altTextImageIdentity(content({ object_key: ' ' }))).toBe('');
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('never confuses an external URL with an object key of the same text', () => {
|
|
54
|
+
expect(altTextImageIdentity({ external_url: 'x', object_key: null })).not.toBe(
|
|
55
|
+
altTextImageIdentity({ external_url: null, object_key: 'x' })
|
|
56
|
+
);
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
describe('resolveAltTextWriteBack', () => {
|
|
61
|
+
it('writes the description into the CURRENT content, not the copy captured at click time', () => {
|
|
62
|
+
// The caption was typed while the vision call was in flight. Merging into the captured
|
|
63
|
+
// copy would silently revert it.
|
|
64
|
+
const current = content({ caption: 'Typed while generating' });
|
|
65
|
+
|
|
66
|
+
expect(
|
|
67
|
+
resolveAltTextWriteBack({
|
|
68
|
+
capturedIdentity: 'stored:uploads/harvest.jpg',
|
|
69
|
+
currentContent: current,
|
|
70
|
+
currentIdentity: 'stored:uploads/harvest.jpg',
|
|
71
|
+
generatedAltText: 'A field of chamomile at dawn.',
|
|
72
|
+
objectKey: 'uploads/harvest.jpg',
|
|
73
|
+
})
|
|
74
|
+
).toEqual({
|
|
75
|
+
alt_text: 'A field of chamomile at dawn.',
|
|
76
|
+
caption: 'Typed while generating',
|
|
77
|
+
external_url: null,
|
|
78
|
+
media_id: 'media-1',
|
|
79
|
+
object_key: 'uploads/harvest.jpg',
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it('writes object_key from the editor selection, matching the typed-alt-text shape exactly', () => {
|
|
84
|
+
const result = resolveAltTextWriteBack({
|
|
85
|
+
capturedIdentity: 'stored:uploads/just-picked.jpg',
|
|
86
|
+
currentContent: content({ object_key: null }),
|
|
87
|
+
currentIdentity: 'stored:uploads/just-picked.jpg',
|
|
88
|
+
generatedAltText: 'Chamomile.',
|
|
89
|
+
objectKey: 'uploads/just-picked.jpg',
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
expect(result?.object_key).toBe('uploads/just-picked.jpg');
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('drops the response when the image was replaced mid-flight', () => {
|
|
96
|
+
// The regression this whole module exists for: alt text describing image A must never
|
|
97
|
+
// be attached to image B.
|
|
98
|
+
expect(
|
|
99
|
+
resolveAltTextWriteBack({
|
|
100
|
+
capturedIdentity: 'stored:uploads/harvest.jpg',
|
|
101
|
+
currentContent: content({ object_key: 'uploads/packaging.jpg' }),
|
|
102
|
+
currentIdentity: 'stored:uploads/packaging.jpg',
|
|
103
|
+
generatedAltText: 'A field of chamomile at dawn.',
|
|
104
|
+
objectKey: 'uploads/packaging.jpg',
|
|
105
|
+
})
|
|
106
|
+
).toBeNull();
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it('drops the response when the image was removed mid-flight, so nothing is resurrected', () => {
|
|
110
|
+
expect(
|
|
111
|
+
resolveAltTextWriteBack({
|
|
112
|
+
capturedIdentity: 'stored:uploads/harvest.jpg',
|
|
113
|
+
currentContent: content({ media_id: null, object_key: null }),
|
|
114
|
+
currentIdentity: '',
|
|
115
|
+
generatedAltText: 'A field of chamomile at dawn.',
|
|
116
|
+
objectKey: null,
|
|
117
|
+
})
|
|
118
|
+
).toBeNull();
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it('drops the response when a stored image was swapped for an external URL', () => {
|
|
122
|
+
const current = content({
|
|
123
|
+
external_url: 'https://images.example.com/new.jpg',
|
|
124
|
+
media_id: null,
|
|
125
|
+
object_key: null,
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
expect(
|
|
129
|
+
resolveAltTextWriteBack({
|
|
130
|
+
capturedIdentity: 'stored:uploads/harvest.jpg',
|
|
131
|
+
currentContent: current,
|
|
132
|
+
currentIdentity: altTextImageIdentity(current),
|
|
133
|
+
generatedAltText: 'A field of chamomile at dawn.',
|
|
134
|
+
objectKey: null,
|
|
135
|
+
})
|
|
136
|
+
).toBeNull();
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it('refuses to treat two empty identities as a match', () => {
|
|
140
|
+
expect(
|
|
141
|
+
resolveAltTextWriteBack({
|
|
142
|
+
capturedIdentity: '',
|
|
143
|
+
currentContent: content({ media_id: null, object_key: null }),
|
|
144
|
+
currentIdentity: '',
|
|
145
|
+
generatedAltText: 'A field of chamomile at dawn.',
|
|
146
|
+
objectKey: null,
|
|
147
|
+
})
|
|
148
|
+
).toBeNull();
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it('offers an explanation that tells the operator the description was discarded', () => {
|
|
152
|
+
expect(STALE_ALT_TEXT_MESSAGE).toContain('discarded');
|
|
153
|
+
});
|
|
154
|
+
});
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pure core of the "Generate with AI" alt-text write-back in `ImageBlockEditor`.
|
|
3
|
+
*
|
|
4
|
+
* A vision call takes seconds, and the block editor stays fully interactive while one is
|
|
5
|
+
* in flight: the author can remove the image, pick a different one from the library, or
|
|
6
|
+
* paste an external URL before the description ever arrives. The original handler assumed
|
|
7
|
+
* the block it started on would still be the block it finished on — it captured `content`
|
|
8
|
+
* at click time and wrote `{ ...capturedContent, alt_text: generated }` back on completion
|
|
9
|
+
* — and that assumption is wrong in exactly the cases that matter. Writing the captured
|
|
10
|
+
* copy back resurrects an image the author had deleted, or pairs a freshly chosen image
|
|
11
|
+
* with a description of the previous one. The second failure is worse than having no alt
|
|
12
|
+
* text at all: it is confidently wrong, and the screen-reader user it exists for has no
|
|
13
|
+
* way to detect that it describes a different picture.
|
|
14
|
+
*
|
|
15
|
+
* The fix is to capture the image's IDENTITY rather than a snapshot of the content, and to
|
|
16
|
+
* discard the response when the block no longer holds that image. This decision lives here
|
|
17
|
+
* rather than inline in the component because the component cannot be unit-tested in this
|
|
18
|
+
* workspace — there is no DOM environment — and a rule about what may overwrite an
|
|
19
|
+
* accessibility field deserves a test.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The part of an image block's content that says which image is loaded.
|
|
24
|
+
*
|
|
25
|
+
* Deliberately structural and snake_case: these are the JSONB attribute names the block
|
|
26
|
+
* actually stores, so a caller passes its content object straight in without translating.
|
|
27
|
+
*/
|
|
28
|
+
export interface AltTextImageSource {
|
|
29
|
+
external_url?: string | null;
|
|
30
|
+
object_key?: string | null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Shown when a generated description is thrown away because the image moved on. It is
|
|
35
|
+
* phrased as a fact plus the next step rather than as a failure, because nothing failed —
|
|
36
|
+
* the model answered, the answer is simply about an image that is no longer here.
|
|
37
|
+
*/
|
|
38
|
+
export const STALE_ALT_TEXT_MESSAGE =
|
|
39
|
+
'The image changed while Cortex AI was describing it, so that description was discarded. Generate again for the current image.';
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* A stable string naming the image a block is currently showing, or `''` for no image.
|
|
43
|
+
*
|
|
44
|
+
* The external URL wins over the stored object key because that is the order the editor
|
|
45
|
+
* itself renders and sends in: a block with an `external_url` shows the external image
|
|
46
|
+
* regardless of any stale `object_key` left beside it. `fallbackObjectKey` mirrors the
|
|
47
|
+
* editor's `content.object_key || selectedMediaObjectKey` display rule, which exists
|
|
48
|
+
* because a just-picked image lives in component state for a beat before the parent
|
|
49
|
+
* echoes it back through `content`.
|
|
50
|
+
*
|
|
51
|
+
* The `external:` / `stored:` prefixes keep the two namespaces from ever colliding, so a
|
|
52
|
+
* URL that happens to equal an object key cannot be mistaken for the same image.
|
|
53
|
+
*/
|
|
54
|
+
export function altTextImageIdentity(
|
|
55
|
+
source: AltTextImageSource,
|
|
56
|
+
fallbackObjectKey?: string | null
|
|
57
|
+
): string {
|
|
58
|
+
const externalUrl = source.external_url?.trim();
|
|
59
|
+
if (externalUrl) {
|
|
60
|
+
return `external:${externalUrl}`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const objectKey = (source.object_key || fallbackObjectKey || '').trim();
|
|
64
|
+
if (objectKey) {
|
|
65
|
+
return `stored:${objectKey}`;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return '';
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface AltTextWriteBackParams<TContent extends AltTextImageSource> {
|
|
72
|
+
/** The identity taken at click time, i.e. the image that was actually sent to the model. */
|
|
73
|
+
capturedIdentity: string;
|
|
74
|
+
/** The block's content as of right now — never the copy captured at click time. */
|
|
75
|
+
currentContent: TContent;
|
|
76
|
+
/** The identity of the image the block holds right now. */
|
|
77
|
+
currentIdentity: string;
|
|
78
|
+
generatedAltText: string;
|
|
79
|
+
/** The editor's `selectedMediaObjectKey`, written through unchanged (see below). */
|
|
80
|
+
objectKey: string | null | undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Decide what — if anything — the generated description should write back.
|
|
85
|
+
*
|
|
86
|
+
* Returns `null` when the response must be dropped: either the image has been replaced or
|
|
87
|
+
* removed since the request went out, or there was no identifiable image to begin with (an
|
|
88
|
+
* empty captured identity, which the disabled button should already prevent, is treated as
|
|
89
|
+
* a mismatch rather than as a match against another empty).
|
|
90
|
+
*
|
|
91
|
+
* When it does write, it merges into the CURRENT content and reproduces the exact shape
|
|
92
|
+
* `handleAltTextChange` uses — the same key set, including `object_key` taken from the
|
|
93
|
+
* editor's selection state. Making the AI path indistinguishable from typing is what
|
|
94
|
+
* guarantees the value lands in the block's JSONB attributes through the one save path,
|
|
95
|
+
* instead of creating a second write shape to keep in sync forever.
|
|
96
|
+
*/
|
|
97
|
+
export function resolveAltTextWriteBack<TContent extends AltTextImageSource>(
|
|
98
|
+
params: AltTextWriteBackParams<TContent>
|
|
99
|
+
): (TContent & { alt_text: string; object_key: string | null | undefined }) | null {
|
|
100
|
+
if (!params.capturedIdentity || params.capturedIdentity !== params.currentIdentity) {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return {
|
|
105
|
+
...params.currentContent,
|
|
106
|
+
alt_text: params.generatedAltText,
|
|
107
|
+
object_key: params.objectKey,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { extractIntroExcerptFromBlocks, stripHtmlToText } from '../../app/lib/seo';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Flatten a page's or post's block rows into plain prose for the metadata generator.
|
|
5
|
+
*
|
|
6
|
+
* `POST /api/ai/seo/metadata` wants the *body copy* — it has to read the page to write a
|
|
7
|
+
* title and description about it. What the CMS holds instead is a tree of block rows
|
|
8
|
+
* whose text is scattered across differently-named fields and nested one or two levels
|
|
9
|
+
* deep inside layout containers. This walks that tree once and returns the readable text.
|
|
10
|
+
*
|
|
11
|
+
* It deliberately reuses `stripHtmlToText` from `app/lib/seo.ts` rather than growing a
|
|
12
|
+
* fourth HTML stripper in this repo. That module was checked before importing it here:
|
|
13
|
+
* its only import is `import type { Metadata } from 'next'`, a type-only import that is
|
|
14
|
+
* erased at compile time, so nothing server-only is pulled into the client bundle even
|
|
15
|
+
* though `app/lib/site-settings.ts` — a different module — imports it under 'server-only'.
|
|
16
|
+
*
|
|
17
|
+
* The walk covers the containers that actually nest content today:
|
|
18
|
+
* - `section` blocks hold their children in `content.column_blocks`,
|
|
19
|
+
* - `hero` blocks hold theirs in `content.slides`,
|
|
20
|
+
* matching how `collectIntroTextCandidates` in `app/lib/seo.ts` traverses the same shapes.
|
|
21
|
+
* Anything unrecognized is skipped rather than guessed at, because feeding the model
|
|
22
|
+
* stray JSON keys produces worse metadata than feeding it less prose.
|
|
23
|
+
*/
|
|
24
|
+
function collectBlockText(value: unknown, collected: string[]): void {
|
|
25
|
+
if (!value) {
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
if (Array.isArray(value)) {
|
|
30
|
+
value.forEach((item) => collectBlockText(item, collected));
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (typeof value !== 'object') {
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const block = value as {
|
|
39
|
+
block_type?: string;
|
|
40
|
+
content?: Record<string, unknown>;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
if (block.block_type === 'section' || block.block_type === 'hero') {
|
|
44
|
+
collectBlockText(block.content?.column_blocks, collected);
|
|
45
|
+
collectBlockText(block.content?.slides, collected);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (block.block_type === 'heading') {
|
|
50
|
+
const headingText = block.content?.text_content;
|
|
51
|
+
if (typeof headingText === 'string' && headingText.trim()) {
|
|
52
|
+
collected.push(stripHtmlToText(headingText));
|
|
53
|
+
}
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (block.block_type === 'text') {
|
|
58
|
+
const htmlContent = block.content?.html_content;
|
|
59
|
+
const textContent = block.content?.text_content;
|
|
60
|
+
const candidate =
|
|
61
|
+
typeof htmlContent === 'string'
|
|
62
|
+
? stripHtmlToText(htmlContent)
|
|
63
|
+
: typeof textContent === 'string'
|
|
64
|
+
? stripHtmlToText(textContent)
|
|
65
|
+
: '';
|
|
66
|
+
|
|
67
|
+
if (candidate) {
|
|
68
|
+
collected.push(candidate);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Maximum prose we send to the metadata route.
|
|
75
|
+
*
|
|
76
|
+
* A meta title and description summarize the *top* of a page; the model does not need
|
|
77
|
+
* the whole of a 5,000-word article to write 160 characters, and shipping the whole of
|
|
78
|
+
* it costs tokens and latency on every click of the button. Cutting at a sentence-ish
|
|
79
|
+
* boundary keeps the tail from ending mid-word, which reads to the model as a typo.
|
|
80
|
+
*/
|
|
81
|
+
const MAX_CONTENT_CHARACTERS = 6000;
|
|
82
|
+
|
|
83
|
+
export function extractPlainTextFromBlocks(blocks: unknown): string {
|
|
84
|
+
const collected: string[] = [];
|
|
85
|
+
collectBlockText(blocks, collected);
|
|
86
|
+
|
|
87
|
+
const joined = collected.join('\n\n').trim();
|
|
88
|
+
if (joined.length <= MAX_CONTENT_CHARACTERS) {
|
|
89
|
+
return joined;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const truncated = joined.slice(0, MAX_CONTENT_CHARACTERS);
|
|
93
|
+
const lastBoundary = Math.max(truncated.lastIndexOf('. '), truncated.lastIndexOf('\n'));
|
|
94
|
+
return (lastBoundary > MAX_CONTENT_CHARACTERS / 2
|
|
95
|
+
? truncated.slice(0, lastBoundary + 1)
|
|
96
|
+
: truncated
|
|
97
|
+
).trim();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Best available prose for the metadata call, in descending order of usefulness.
|
|
102
|
+
*
|
|
103
|
+
* A brand-new page has no blocks yet, and an operator clicking "Generate" on an empty
|
|
104
|
+
* page should still get something better than a disabled button — the title plus any
|
|
105
|
+
* editorial summary they have typed is a thin but genuine brief. `fallbacks` is where
|
|
106
|
+
* the caller passes those: a post's excerpt and subtitle, or a page's title.
|
|
107
|
+
*/
|
|
108
|
+
export function buildSeoContentForGeneration(
|
|
109
|
+
blocks: unknown,
|
|
110
|
+
...fallbacks: Array<string | null | undefined>
|
|
111
|
+
): string {
|
|
112
|
+
const fromBlocks = extractPlainTextFromBlocks(blocks);
|
|
113
|
+
if (fromBlocks) {
|
|
114
|
+
return fromBlocks;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const intro = extractIntroExcerptFromBlocks(blocks);
|
|
118
|
+
const parts = [intro, ...fallbacks]
|
|
119
|
+
.map((part) => (typeof part === 'string' ? stripHtmlToText(part) : ''))
|
|
120
|
+
.filter(Boolean);
|
|
121
|
+
|
|
122
|
+
return parts.join('\n\n').trim();
|
|
123
|
+
}
|