Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
be2b332e7c | ||
|
|
14558e4677 | ||
|
|
47de196516 | ||
|
|
76132722b0 | ||
|
|
babd3a95b9 | ||
|
|
4c3f9b4568 | ||
|
|
2dcd4436a0 |
70
README.md
70
README.md
@@ -3,7 +3,7 @@
|
||||
A Nuxt 4 layer that renders a Journal blog (post list, post, category, tag and author pages, RSS link) from the Journal API of a SummerCMS application, with its SEO output from the CMS through vue-seo-layer.
|
||||
|
||||
```bash
|
||||
pnpm add git+https://git.golem15.com/golem15/vue-seo-layer.git#v0.2.0 git+https://git.golem15.com/golem15/vue-journal-layer.git#v0.8.1
|
||||
pnpm add git+https://git.golem15.com/golem15/vue-seo-layer.git#v0.2.0 git+https://git.golem15.com/golem15/vue-journal-layer.git#v0.8.2
|
||||
```
|
||||
|
||||
vue-seo-layer is a peer dependency (`^0.2.0`): the app lists it next to the layer, pinned to a tag as above, and needs no `extends` entry for it (the layer extends it). The layer cannot bring it itself: pnpm refuses a git dependency inside another package (`blockExoticSubdeps`, on by default).
|
||||
@@ -32,29 +32,77 @@ Route paths are configuration, not files. The layer's page components live in `a
|
||||
- **Post cards**: one link per card, the title; the whole card is clickable through a CSS stretched link, with the focus ring on the card.
|
||||
- **Body links and images**: the CMS's phrase auto-links, the outbound link rules (nofollow or sponsored from the domain lists; new tab, `noopener` and a visually hidden hint while the CMS's links_new_tab is on) and lazy, async body images, applied at SSR on the sanitized body.
|
||||
- **Breadcrumbs and pagination**: `<SeoBreadcrumbs>` at the top of every journal page (`journal.breadcrumbs`), and `JournalPagination` as `<SeoPagination>` with the journal's class names.
|
||||
- **HTML sanitizer**: post bodies and category content go through `sanitizeJournalHtml` before `v-html` and before they reach the SSR payload. It is [sanitize-html](https://github.com/apostrophecms/sanitize-html) with the Journal API's own allow-list: the usual content elements, `footer`, `class`, schema.org microdata, the `color`, `font-size`, `font-weight` and `text-align` inline styles, and `http`, `https`, `mailto` or relative URLs. Five rules keep the Journal Blog Editor's own markup, mirroring the API's policy: `data-embed` (`youtube`) and `data-id` (an 11-character video id) on `figure`, `alt` with any text on `img` (`alt=""` of a decorative image included), an integer `start` on `ol`, and a `rel` of only `nofollow`, `sponsored` and `ugc` on `a`. `target` is never kept; the outbound link rules add it. With `{ demoteH1: true }`, `h1` headings come out as `h2`. Anything else (`script`, `style`, `iframe`, `svg`, forms, event-handler attributes, `javascript:` URLs in any spelling) is removed and the rest of the value is kept, so a post never renders blank because of one stray tag. Server and browser produce the same string, so hydration matches. See `docs/decisions/0001-sanitize-html.md`.
|
||||
- **Embeds**: YouTube videos added in the Journal Blog Editor render as privacy-enhanced iframes (see [Embeds](#embeds)).
|
||||
- **HTML sanitizer**: post bodies and category content go through `sanitizeJournalHtml` before `v-html` and before they reach the SSR payload. It is [sanitize-html](https://github.com/apostrophecms/sanitize-html) with the Journal API's own allow-list: the usual content elements, `footer`, `class`, schema.org microdata, the `color`, `font-size`, `font-weight` and `text-align` inline styles, and `http`, `https`, `mailto` or relative URLs. Rules keep the Journal Blog Editor's own markup, mirroring the API's policy: pair-aware `data-embed` and `data-id` on `figure` against the active embed provider registry (`youtube` by default, plus app-registered providers) alongside validated `data-aspect` and `data-height` CLS hints, `alt` with any text on `img` (`alt=""` of a decorative image included), an integer `start` on `ol`, and a `rel` of only `nofollow`, `sponsored` and `ugc` on `a`. `target` is never kept; the outbound link rules add it. With `{ demoteH1: true }`, `h1` headings come out as `h2`. Anything else (`script`, `style`, `iframe`, `svg`, forms, event-handler attributes, `javascript:` URLs in any spelling) is removed and the rest of the value is kept, so a post never renders blank because of one stray tag. Server and browser produce the same string, so hydration matches. See `docs/decisions/0001-sanitize-html.md`.
|
||||
- **Embeds**: built-in YouTube privacy-enhanced iframes plus an app-extensible embed provider registry (`app.config.ts` and Nuxt plugin helpers) with SSR static fallback preservation, CLS height reservation, `IntersectionObserver` lazy hydration, and `prefers-reduced-motion` support (see [Embeds](#embeds)).
|
||||
- **i18n**: English and Polish UI strings, registered only for the locales the app enables.
|
||||
|
||||
## Embeds
|
||||
|
||||
The Journal Blog Editor never stores an iframe. It stores a placeholder:
|
||||
The Journal Blog Editor never stores an iframe or inline `<script>`. It stores a `<figure>` placeholder with optional static fallback markup:
|
||||
|
||||
```html
|
||||
<!-- Built-in YouTube -->
|
||||
<figure data-embed="youtube" data-id="dQw4w9WgXcQ"></figure>
|
||||
|
||||
<!-- Custom interactive embed with static SSR fallback -->
|
||||
<figure data-embed="viz" data-id="acme-chart-1" data-aspect="16/9">
|
||||
<img src="/media/abc123/chart.webp" alt="Chart overview" width="800" height="450">
|
||||
<figcaption>Figure 1</figcaption>
|
||||
</figure>
|
||||
```
|
||||
|
||||
`expandEmbeds(html)` in `app/utils/embeds.ts` turns it into:
|
||||
### Default YouTube behavior
|
||||
|
||||
`youtube` (`idPattern: /^[A-Za-z0-9_-]{11}$/`) is registered by default in `app/utils/embedRegistry.ts`. `expandEmbeds(html)` in `app/utils/embeds.ts` turns an empty `<figure data-embed="youtube" data-id="..."></figure>` into the same privacy-enhanced iframe:
|
||||
|
||||
```html
|
||||
<figure class="journal-embed journal-embed--youtube"><iframe src="https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ" title="YouTube video" loading="lazy" referrerpolicy="strict-origin-when-cross-origin" allow="encrypted-media; picture-in-picture; fullscreen" allowfullscreen></iframe></figure>
|
||||
```
|
||||
|
||||
- **Allowlist:** `EMBED_PROVIDERS` holds one provider, `youtube`, whose id must match `^[A-Za-z0-9_-]{11}$`. The iframe `src` is always `https://www.youtube-nocookie.com/embed/` plus that id. `EMBED_PLACEHOLDER` matches the placeholder exactly as the editor writes it (`data-embed` then `data-id`, double quotes, empty figure). Any other figure, provider or id is left unchanged and renders as an empty figure.
|
||||
- **Order:** sanitize first, expand last. `JournalPostBody` renders `expandEmbeds(sanitizeJournalHtml(html))` and `JournalCategoryHeader` does the same with the category content. The payload transforms (`toPostView`, the category page) only sanitize, so the payload carries the placeholder. The expansion's output is never sanitized again, because the sanitizer removes every iframe, including this one. A raw `<iframe>` in stored HTML is removed by the sanitizer before the expansion runs, so the only iframe on a page is one built from a validated placeholder.
|
||||
- **Styles:** `.journal-embed` is a full-width block with a 16 / 9 aspect ratio; its iframe fills it without a border. `.journal-embed--youtube` marks the provider for app styles.
|
||||
- **Overrides:** an app that replaces `JournalPostBody` or `JournalCategoryHeader` and wants embeds calls `expandEmbeds` on the sanitized string, never before sanitizing.
|
||||
- **Content-Security-Policy:** a site that sends a CSP needs `frame-src https://www.youtube-nocookie.com`.
|
||||
Apps may optionally override `youtube` in the registry (for example to render a click-to-play facade instead of an eager SSR iframe).
|
||||
|
||||
### Registering custom embed providers
|
||||
|
||||
Consuming Nuxt apps can register custom embed providers via **`app.config.ts`** (`journal.embeds`, synced on both SSR and client by `app/plugins/journal-embeds.ts`) and/or a **Nuxt plugin** calling `registerJournalEmbedProvider` / `defineJournalEmbedProviders` from `app/utils/embedRegistry.ts`:
|
||||
|
||||
```ts
|
||||
// app/app.config.ts
|
||||
export default defineAppConfig({
|
||||
journal: {
|
||||
embeds: {
|
||||
viz: {
|
||||
idPattern: /^[a-z0-9][a-z0-9-]{0,63}$/,
|
||||
component: () => import('~/components/EmbedViz.vue'),
|
||||
aspectRatio: '16/9',
|
||||
rootMargin: '200px',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
```ts
|
||||
// app/plugins/custom-embeds.ts (runs on both SSR and client)
|
||||
export default defineNuxtPlugin(() => {
|
||||
registerJournalEmbedProvider('acme', {
|
||||
idPattern: /^acme-[0-9]{1,6}$/,
|
||||
mount(el, ctx) {
|
||||
// Plain DOM mount callback with reactive ctx.reducedMotion & ctx.fallbackHtml
|
||||
el.textContent = `Widget ${ctx.id}`
|
||||
return () => {
|
||||
el.replaceChildren()
|
||||
}
|
||||
},
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
- **Sanitizer parity:** Registered providers automatically feed `sanitizeJournalHtml`, `gateJournalHtml`, `isSafeJournalHtml`, and `renderJournalBody` with pair-aware `(data-embed, data-id)` validation (so an ID valid for `viz` is never accepted on `data-embed="youtube"`). Validated `data-aspect` (`16/9`, `4/3`, `1.5`) and `data-height` (`420`, `420px`) attributes are allowed only on valid embed figures; fallback `<img>` (including `srcset`/`sizes`/`width`/`height`) and `<figcaption>` children pass the UGC allow-list while `<script>`, `<style>`, `<iframe>`, `<svg>`, and event handlers are stripped. Prototype keys (`__proto__`, `constructor`, `toString`) are rejected by `Map`-based lookups.
|
||||
- **Order:** sanitize first, expand/hydrate last. `JournalPostBody` and `JournalCategoryHeader` call `expandEmbeds(renderJournalBody(...))` / `expandEmbeds(sanitizeJournalHtml(...))` and wire `useJournalEmbedHydration`. The payload transforms (`toPostView`, `CategoryPage.vue`) only sanitize, so the SSR payload carries the clean `<figure>` markup.
|
||||
- **SSR static fallback & CLS reservation:** For client-hydrated providers (`component` or `mount`, without `renderSsr`), `expandEmbeds` preserves the SSR fallback `<img>` + `<figcaption>` intact, adds `journal-embed journal-embed--<provider>`, and applies validated `aspect-ratio` / `min-height` inline styles. Before swapping in the hydrated widget on the client, `hydrateEmbedFigure` measures the fallback box height and sets `min-height` to prevent cumulative layout shift (CLS).
|
||||
- **Lazy hydration, `prefers-reduced-motion`, and resilience:** `useJournalEmbedHydration` observes each validated `<figure data-embed>` with `IntersectionObserver` (default `rootMargin: '200px'`), passes a reactive `reducedMotion` ref synced with `window.matchMedia('(prefers-reduced-motion: reduce)')`, mounts Vue async components via `createVNode` + `render` inheriting `nuxtApp.vueApp._context` (so i18n, router, and Pinia work inside hydrated embeds) or invokes `mount(el, ctx)`, and cleans up on unmount or HTML updates. If dynamic import or mount throws, the error is caught and the SSR static fallback DOM remains intact.
|
||||
- **Styles:** `.journal-embed--youtube` and iframe embeds default to a `16 / 9` full-width frame; custom embeds render their fallback image, `<figcaption>`, and `.journal-embed__stage` naturally, adding `.journal-embed--hydrated` once mounted. Inside `.journal-post-body`, `<figure>` / `<figcaption>`, `<details>` / `<summary>`, table `<th>` / `<caption>`, and `<blockquote><footer>` receive neutral `--journal-*` defaults, and `figure.journal-wide` breaks out up to `--journal-wide-width` on wide viewports.
|
||||
- **Content-Security-Policy:** The hydration runtime is strictly `script-src 'self'` compliant (no `eval`, no `new Function`, no inline `<script>`). Sites using the built-in YouTube iframe still need `frame-src https://www.youtube-nocookie.com`.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -260,7 +308,7 @@ The feed's item links come from the Journal API, which links posts under `/blog/
|
||||
|
||||
## Upgrading from 0.7
|
||||
|
||||
- **List vue-seo-layer in the app** (from 0.8.1): `"vue-seo-layer": "git+https://git.golem15.com/golem15/vue-seo-layer.git#v0.2.0"` next to `vue-journal-layer#v0.8.1`. It is a peer dependency of the layer (`^0.2.0`). 0.8.0 listed it as its own git dependency, which pnpm refuses by default (`ERR_PNPM_EXOTIC_SUBDEP`), so use 0.8.1.
|
||||
- **List vue-seo-layer in the app** (from 0.8.1): `"vue-seo-layer": "git+https://git.golem15.com/golem15/vue-seo-layer.git#v0.2.0"` next to `vue-journal-layer#v0.8.2`. It is a peer dependency of the layer (`^0.2.0`). 0.8.0 listed it as its own git dependency, which pnpm refuses by default (`ERR_PNPM_EXOTIC_SUBDEP`), so use 0.8.1.
|
||||
- **`@nuxtjs/seo` is gone.** The layer extends vue-seo-layer instead. Remove `site: { url, name }` and the `ogImage`, `seo.canonicalQueryWhitelist`, `sitemap`, `robots` and `schemaOrg` keys that only `@nuxtjs/seo` read; set `NUXT_SEO_API_BASE` (the SEO plugin, default `http://127.0.0.1:8096/_seo/api/v1`) or `seo: { cms: false }` for a site without the SEO plugin. `useSiteConfig()`, `useSchemaOrg()` and the other `@nuxtjs/seo` composables are no longer available to the app through this layer; an app that uses them adds `@nuxtjs/seo` itself (then it emits its own canonical and graph next to the CMS's) or moves to the CMS answer.
|
||||
- **The journal sitemap source is gone** (`/api/__sitemap__/journal`, `buildJournalSitemapEntries`): the sitemap plugin builds the sitemaps, served through vue-seo-layer.
|
||||
- **The shared purge route moved** to vue-seo-layer, with the same path, contract and variables; `server/lib/siteCachePurge.ts`, `server/api/__site__/cache/purge.post.ts` and `server/plugins/site-cache-purge.ts` are no longer in this layer. The deprecated `POST /api/__journal__/cache/purge` keeps working.
|
||||
|
||||
@@ -148,6 +148,65 @@
|
||||
background: var(--journal-color-surface);
|
||||
}
|
||||
|
||||
.journal-post-body blockquote footer {
|
||||
margin-top: var(--journal-space-2);
|
||||
color: var(--journal-color-muted);
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
.journal-post-body figure {
|
||||
margin: var(--journal-space-4) 0;
|
||||
}
|
||||
|
||||
.journal-post-body figure img {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.journal-post-body figcaption {
|
||||
margin-top: var(--journal-space-2);
|
||||
color: var(--journal-color-muted);
|
||||
font-size: 0.9em;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.journal-post-body figure.journal-wide {
|
||||
--journal-breakout-width: min(var(--journal-wide-width), calc(100vw - 2 * var(--journal-space-4)));
|
||||
width: var(--journal-breakout-width);
|
||||
max-width: none;
|
||||
margin-inline: calc((100% - var(--journal-breakout-width)) / 2);
|
||||
}
|
||||
|
||||
.journal-post-body figure.journal-wide img {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.journal-post-body details {
|
||||
margin: var(--journal-space-4) 0;
|
||||
padding: var(--journal-space-3) var(--journal-space-4);
|
||||
border: 1px solid var(--journal-color-border);
|
||||
border-radius: var(--journal-radius-md);
|
||||
background: var(--journal-color-surface);
|
||||
}
|
||||
|
||||
.journal-post-body summary {
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.journal-post-body summary:focus-visible {
|
||||
outline: 2px solid var(--journal-color-accent);
|
||||
outline-offset: 2px;
|
||||
border-radius: var(--journal-radius-sm);
|
||||
}
|
||||
|
||||
.journal-post-body details[open] > summary {
|
||||
margin-bottom: var(--journal-space-3);
|
||||
}
|
||||
|
||||
.journal-post-body details > :last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.journal-post-body code {
|
||||
padding: 0 var(--journal-space-1);
|
||||
border-radius: var(--journal-radius-sm);
|
||||
@@ -180,14 +239,30 @@
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
/* Embeds expanded from the Blog Editor's placeholders (app/utils/embeds.ts) */
|
||||
.journal-post-body th {
|
||||
background: var(--journal-color-surface);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.journal-post-body caption {
|
||||
margin-bottom: var(--journal-space-2);
|
||||
color: var(--journal-color-muted);
|
||||
font-size: 0.9em;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
/* Embeds expanded or hydrated from the Blog Editor's placeholders (app/utils/embeds.ts) */
|
||||
.journal-embed {
|
||||
display: block;
|
||||
width: 100%;
|
||||
aspect-ratio: 16 / 9;
|
||||
margin: var(--journal-space-4) 0;
|
||||
}
|
||||
|
||||
.journal-embed--youtube,
|
||||
.journal-embed:has(> iframe) {
|
||||
aspect-ratio: 16 / 9;
|
||||
}
|
||||
|
||||
.journal-embed iframe {
|
||||
display: block;
|
||||
width: 100%;
|
||||
@@ -195,6 +270,23 @@
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.journal-embed img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.journal-embed figcaption {
|
||||
margin-top: var(--journal-space-2);
|
||||
color: var(--journal-color-muted);
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
.journal-embed__stage {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* Listings */
|
||||
.journal-post-list {
|
||||
display: grid;
|
||||
|
||||
@@ -11,9 +11,12 @@ import { expandEmbeds } from '../../utils/embeds.ts'
|
||||
import { sanitizeJournalHtml } from '../../utils/htmlGate.ts'
|
||||
|
||||
const props = defineProps<{ category: JournalCategory; page?: number }>()
|
||||
const contentRef = ref<HTMLElement | null>(null)
|
||||
const content = computed(() =>
|
||||
props.page && props.page > 1 ? '' : expandEmbeds(sanitizeJournalHtml(props.category.content, { demoteH1: props.category.content_h1_to_h2 !== false })),
|
||||
)
|
||||
|
||||
useJournalEmbedHydration(contentRef, content)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -22,6 +25,6 @@ const content = computed(() =>
|
||||
{{ category.name }}<template v-if="page && page > 1"> · {{ $t('journal.pagination.pageTitle', { page }) }}</template>
|
||||
</h1>
|
||||
<p v-if="category.description" class="journal-category-header__description">{{ category.description }}</p>
|
||||
<div v-if="content" class="journal-category-header__content journal-post-body" v-html="content" />
|
||||
<div v-if="content" ref="contentRef" class="journal-category-header__content journal-post-body" v-html="content" />
|
||||
</header>
|
||||
</template>
|
||||
|
||||
@@ -20,6 +20,7 @@ import { expandEmbeds } from '../../utils/embeds.ts'
|
||||
import { renderJournalBody, type JournalBodyLinkSteps } from '../../utils/htmlGate.ts'
|
||||
|
||||
const props = defineProps<{ html: string | null | undefined; demoteH1?: boolean }>()
|
||||
const bodyRef = ref<HTMLElement | null>(null)
|
||||
|
||||
const answer = useSeoAnswer()
|
||||
const route = useRoute()
|
||||
@@ -71,8 +72,10 @@ const html = computed(() => {
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
useJournalEmbedHydration(bodyRef, html)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="journal-post-body" v-html="html" />
|
||||
<div ref="bodyRef" class="journal-post-body" v-html="html" />
|
||||
</template>
|
||||
|
||||
306
app/composables/useJournalEmbedHydration.ts
Normal file
306
app/composables/useJournalEmbedHydration.ts
Normal file
@@ -0,0 +1,306 @@
|
||||
// Client-side progressive-enhancement hydration runtime for Journal embeds.
|
||||
//
|
||||
// Observes validated `<figure data-embed="..." data-id="...">` elements inside
|
||||
// a rendered HTML container via `IntersectionObserver`, reserves layout height
|
||||
// before swapping (zero CLS), tracks `prefers-reduced-motion`, supports both
|
||||
// Vue async components (inheriting `nuxtApp.vueApp._context`) and plain DOM
|
||||
// `mount(el, ctx)` callbacks, cleans up on unmount or HTML changes, and catches
|
||||
// errors leaving the SSR static fallback DOM untouched.
|
||||
//
|
||||
// Strictly `script-src 'self'` CSP compliant: zero `eval`, `new Function`, or
|
||||
// inline `<script>` injection.
|
||||
import {
|
||||
createVNode,
|
||||
getCurrentInstance,
|
||||
onBeforeUnmount,
|
||||
onMounted,
|
||||
ref,
|
||||
render,
|
||||
watch,
|
||||
type AppContext,
|
||||
type Component,
|
||||
type Ref,
|
||||
type WatchSource,
|
||||
} from 'vue'
|
||||
import {
|
||||
EMBED_ASPECT,
|
||||
EMBED_HEIGHT,
|
||||
getJournalEmbedRegistry,
|
||||
type JournalEmbedMountContext,
|
||||
type JournalEmbedRegistry,
|
||||
type NormalizedJournalEmbedProvider,
|
||||
} from '../utils/embedRegistry.ts'
|
||||
|
||||
/** Options for hydrating a single `<figure data-embed>` element. */
|
||||
export interface HydrateEmbedFigureOptions {
|
||||
id: string
|
||||
providerName: string
|
||||
reducedMotion: Readonly<{ value: boolean }>
|
||||
appContext?: AppContext | null
|
||||
signal?: { aborted: boolean }
|
||||
onError?: (err: unknown, figure: HTMLElement) => void
|
||||
}
|
||||
|
||||
/** Options for `useJournalEmbedHydration`. */
|
||||
export interface JournalEmbedHydrationOptions {
|
||||
registry?: JournalEmbedRegistry
|
||||
rootMargin?: string
|
||||
}
|
||||
|
||||
function replaceChildrenSafe(parent: HTMLElement, ...children: Node[]): void {
|
||||
if (typeof parent.replaceChildren === 'function') {
|
||||
parent.replaceChildren(...children)
|
||||
return
|
||||
}
|
||||
while (parent.firstChild) parent.removeChild(parent.firstChild)
|
||||
for (const child of children) parent.appendChild(child)
|
||||
}
|
||||
|
||||
function restoreFallback(figure: HTMLElement, savedChildren: Node[], fallbackHtml: string): void {
|
||||
if (savedChildren.length > 0) {
|
||||
replaceChildrenSafe(figure, ...savedChildren)
|
||||
} else {
|
||||
figure.innerHTML = fallbackHtml
|
||||
}
|
||||
}
|
||||
|
||||
function warnDev(providerName: string, id: string, err: unknown): void {
|
||||
const isDev = typeof import.meta !== 'undefined' && (import.meta as { dev?: boolean }).dev === true
|
||||
if (isDev && typeof console !== 'undefined' && typeof console.warn === 'function') {
|
||||
console.warn(`[vue-journal-layer] Failed to hydrate embed "${providerName}:${id}":`, err)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hydrates a single validated `<figure data-embed>` element using a registered
|
||||
* provider (`component` or `mount`). Returns a cleanup callback on success, or
|
||||
* `null` if hydration failed or was aborted (leaving SSR fallback DOM intact).
|
||||
*/
|
||||
export async function hydrateEmbedFigure(
|
||||
figure: HTMLElement,
|
||||
provider: NormalizedJournalEmbedProvider,
|
||||
options: HydrateEmbedFigureOptions,
|
||||
): Promise<(() => void) | null> {
|
||||
if (!provider.component && !provider.mount) return null
|
||||
if (options.signal?.aborted) return null
|
||||
|
||||
const fallbackHtml = figure.innerHTML
|
||||
const rawAspect = figure.getAttribute('data-aspect') ?? undefined
|
||||
const rawHeight = figure.getAttribute('data-height') ?? undefined
|
||||
const aspect = rawAspect && EMBED_ASPECT.test(rawAspect) ? rawAspect : undefined
|
||||
const height = rawHeight && EMBED_HEIGHT.test(rawHeight) ? rawHeight : undefined
|
||||
|
||||
// Reserve measured height before swapping to prevent layout shift (CLS).
|
||||
const rectHeight = typeof figure.getBoundingClientRect === 'function' ? figure.getBoundingClientRect().height : 0
|
||||
if (rectHeight > 0 && !figure.style.minHeight) {
|
||||
figure.style.minHeight = `${Math.ceil(rectHeight)}px`
|
||||
}
|
||||
|
||||
const doc = figure.ownerDocument
|
||||
const host = doc.createElement('div')
|
||||
host.className = 'journal-embed__stage'
|
||||
const savedChildren = Array.from(figure.childNodes)
|
||||
let attached = false
|
||||
|
||||
try {
|
||||
if (provider.component) {
|
||||
const mod = await provider.component()
|
||||
if (options.signal?.aborted) return null
|
||||
const comp = (mod && typeof mod === 'object' && 'default' in mod ? (mod as { default: unknown }).default : mod) as Component | undefined
|
||||
if (!comp) throw new Error(`Embed provider "${options.providerName}" component loader returned an empty module`)
|
||||
|
||||
const vnode = createVNode(comp, {
|
||||
id: options.id,
|
||||
provider: options.providerName,
|
||||
aspect,
|
||||
height,
|
||||
fallbackHtml,
|
||||
reducedMotion: options.reducedMotion,
|
||||
})
|
||||
if (options.appContext) vnode.appContext = options.appContext
|
||||
|
||||
// Attach host before render so onMounted sees real layout dimensions (WR-02).
|
||||
replaceChildrenSafe(figure, host)
|
||||
attached = true
|
||||
render(vnode, host)
|
||||
if (options.signal?.aborted) {
|
||||
render(null, host)
|
||||
restoreFallback(figure, savedChildren, fallbackHtml)
|
||||
return null
|
||||
}
|
||||
|
||||
figure.classList.add('journal-embed--hydrated')
|
||||
|
||||
return () => {
|
||||
render(null, host)
|
||||
figure.classList.remove('journal-embed--hydrated')
|
||||
}
|
||||
}
|
||||
|
||||
if (provider.mount) {
|
||||
const ctx: JournalEmbedMountContext = {
|
||||
id: options.id,
|
||||
provider: options.providerName,
|
||||
figure,
|
||||
aspect,
|
||||
height,
|
||||
fallbackHtml,
|
||||
reducedMotion: options.reducedMotion,
|
||||
isReducedMotion: options.reducedMotion.value,
|
||||
}
|
||||
// Attach host before mount so layout-measuring widgets see real dimensions (WR-02).
|
||||
replaceChildrenSafe(figure, host)
|
||||
attached = true
|
||||
const unmount = await provider.mount(host, ctx)
|
||||
if (options.signal?.aborted) {
|
||||
if (typeof unmount === 'function') unmount()
|
||||
restoreFallback(figure, savedChildren, fallbackHtml)
|
||||
return null
|
||||
}
|
||||
|
||||
figure.classList.add('journal-embed--hydrated')
|
||||
|
||||
return () => {
|
||||
if (typeof unmount === 'function') unmount()
|
||||
figure.classList.remove('journal-embed--hydrated')
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if (attached) {
|
||||
try {
|
||||
render(null, host)
|
||||
} catch {
|
||||
// Ignore cleanup errors on failed mount.
|
||||
}
|
||||
restoreFallback(figure, savedChildren, fallbackHtml)
|
||||
}
|
||||
if (options.onError) options.onError(err, figure)
|
||||
else warnDev(options.providerName, options.id, err)
|
||||
return null
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Observes validated `<figure data-embed>` elements inside `containerRef` and
|
||||
* lazily hydrates them on the client when they near the viewport. No-op on SSR.
|
||||
*/
|
||||
export function useJournalEmbedHydration(
|
||||
containerRef: Ref<HTMLElement | null>,
|
||||
htmlSource: WatchSource<string | null | undefined>,
|
||||
options: JournalEmbedHydrationOptions = {},
|
||||
): void {
|
||||
const isServer = (typeof import.meta !== 'undefined' && (import.meta as { server?: boolean }).server === true) || typeof window === 'undefined'
|
||||
if (isServer) return
|
||||
|
||||
// Capture appContext synchronously in setup() rather than inside onMounted/watch (WR-01).
|
||||
const instance = getCurrentInstance()
|
||||
const appContext: AppContext | null =
|
||||
instance?.appContext ??
|
||||
(typeof useNuxtApp === 'function' ? ((useNuxtApp()?.vueApp?._context as AppContext | undefined) ?? null) : null)
|
||||
|
||||
const reducedMotion = ref(false)
|
||||
let mediaQuery: MediaQueryList | null = null
|
||||
const onMotionChange = (event: MediaQueryListEvent) => {
|
||||
reducedMotion.value = event.matches
|
||||
}
|
||||
|
||||
const observers: IntersectionObserver[] = []
|
||||
const cleanups: Array<() => void> = []
|
||||
let activeSignal = { aborted: false }
|
||||
|
||||
const teardown = () => {
|
||||
activeSignal.aborted = true
|
||||
for (const observer of observers.splice(0)) {
|
||||
observer.disconnect()
|
||||
}
|
||||
for (const cleanup of cleanups.splice(0)) {
|
||||
try {
|
||||
cleanup()
|
||||
} catch {
|
||||
// Ignore teardown errors so every mounted embed gets cleaned up.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const scan = () => {
|
||||
teardown()
|
||||
const signal = { aborted: false }
|
||||
activeSignal = signal
|
||||
|
||||
const root = containerRef.value
|
||||
if (!root) return
|
||||
|
||||
const registry = options.registry ?? getJournalEmbedRegistry()
|
||||
const figures = root.querySelectorAll<HTMLElement>('figure[data-embed][data-id]')
|
||||
|
||||
for (const figure of figures) {
|
||||
const providerName = figure.getAttribute('data-embed') ?? ''
|
||||
const id = figure.getAttribute('data-id') ?? ''
|
||||
const provider = registry.get(providerName)
|
||||
if (!provider || !provider.idPattern.test(id)) continue
|
||||
if (!provider.component && !provider.mount) continue
|
||||
|
||||
const trigger = () => {
|
||||
void hydrateEmbedFigure(figure, provider, {
|
||||
id,
|
||||
providerName,
|
||||
reducedMotion,
|
||||
appContext,
|
||||
signal,
|
||||
}).then((cleanup) => {
|
||||
if (!cleanup) return
|
||||
if (signal.aborted) {
|
||||
try {
|
||||
cleanup()
|
||||
} catch {
|
||||
// Already torn down.
|
||||
}
|
||||
return
|
||||
}
|
||||
cleanups.push(cleanup)
|
||||
})
|
||||
}
|
||||
|
||||
if (typeof IntersectionObserver === 'function') {
|
||||
const observer = new IntersectionObserver(
|
||||
(entries, obs) => {
|
||||
if (entries.some((entry) => entry.isIntersecting)) {
|
||||
obs.disconnect()
|
||||
trigger()
|
||||
}
|
||||
},
|
||||
{ rootMargin: provider.rootMargin ?? options.rootMargin ?? '200px' },
|
||||
)
|
||||
observer.observe(figure)
|
||||
observers.push(observer)
|
||||
} else {
|
||||
trigger()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (typeof window.matchMedia === 'function') {
|
||||
mediaQuery = window.matchMedia('(prefers-reduced-motion: reduce)')
|
||||
reducedMotion.value = mediaQuery.matches
|
||||
if (typeof mediaQuery.addEventListener === 'function') {
|
||||
mediaQuery.addEventListener('change', onMotionChange)
|
||||
}
|
||||
}
|
||||
scan()
|
||||
})
|
||||
|
||||
watch(htmlSource, () => {
|
||||
scan()
|
||||
}, { flush: 'post' })
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
teardown()
|
||||
if (mediaQuery && typeof mediaQuery.removeEventListener === 'function') {
|
||||
mediaQuery.removeEventListener('change', onMotionChange)
|
||||
}
|
||||
mediaQuery = null
|
||||
})
|
||||
}
|
||||
20
app/plugins/journal-embeds.ts
Normal file
20
app/plugins/journal-embeds.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
// Universal Nuxt plugin syncing `app.config.ts` (`journal.embeds`) into the
|
||||
// active Journal embed registry on both SSR and client before page components
|
||||
// render, so `htmlGate.ts`, `embeds.ts`, and `useJournalEmbedHydration.ts`
|
||||
// agree on the exact same provider set.
|
||||
import { defineJournalEmbedProviders, type JournalEmbedProvider } from '../utils/embedRegistry.ts'
|
||||
|
||||
const syncedEmbedMaps = new WeakSet<object>()
|
||||
|
||||
export default defineNuxtPlugin({
|
||||
name: 'journal-embeds',
|
||||
enforce: 'pre',
|
||||
setup() {
|
||||
const appConfig = useAppConfig() as { journal?: { embeds?: Record<string, JournalEmbedProvider> } }
|
||||
const embeds = appConfig?.journal?.embeds
|
||||
if (embeds && typeof embeds === 'object' && !syncedEmbedMaps.has(embeds)) {
|
||||
defineJournalEmbedProviders(embeds)
|
||||
syncedEmbedMaps.add(embeds)
|
||||
}
|
||||
},
|
||||
})
|
||||
246
app/utils/embedRegistry.ts
Normal file
246
app/utils/embedRegistry.ts
Normal file
@@ -0,0 +1,246 @@
|
||||
// Extensible embed provider registry for vue-journal-layer.
|
||||
//
|
||||
// Pure TypeScript with zero Nuxt imports so unit tests run directly under
|
||||
// `node --test`. Consuming Nuxt apps register custom providers via
|
||||
// `app.config.ts` (`journal.embeds`, synced by `app/plugins/journal-embeds.ts`)
|
||||
// and/or a Nuxt plugin calling `registerJournalEmbedProvider` /
|
||||
// `defineJournalEmbedProviders`.
|
||||
//
|
||||
// Both `htmlGate.ts` (pair-aware sanitization) and `embeds.ts` /
|
||||
// `useJournalEmbedHydration.ts` (SSR expansion + client lazy hydration) read
|
||||
// from the same registry. Lookups use `Map` exclusively so prototype keys
|
||||
// (`__proto__`, `constructor`, `toString`) are never matched.
|
||||
|
||||
/** Allowed embed provider key format (mirrors sm-journal-plugin). */
|
||||
export const EMBED_PROVIDER_KEY = /^[a-z][a-z0-9_-]{0,31}$/
|
||||
|
||||
const RESERVED_PROVIDER_KEYS = new Set(['constructor', 'prototype'])
|
||||
|
||||
/** Allowed `data-aspect` token (e.g. `16/9`, `4 / 3`, `1.5`), zero CSS injection vectors. */
|
||||
export const EMBED_ASPECT = /^[1-9][0-9]{0,3}(?:\s*\/\s*[1-9][0-9]{0,3}|\.[0-9]{1,4})?$/
|
||||
|
||||
/** Allowed `data-height` token (e.g. `420`, `420px`), zero CSS injection vectors. */
|
||||
export const EMBED_HEIGHT = /^[1-9][0-9]{0,3}(?:px)?$/
|
||||
|
||||
/** Context passed to a provider's optional SSR renderer. */
|
||||
export interface JournalEmbedSsrContext {
|
||||
provider: string
|
||||
innerHtml: string
|
||||
aspect?: string
|
||||
height?: string
|
||||
}
|
||||
|
||||
/** Context passed to a provider's client-side `mount` callback. */
|
||||
export interface JournalEmbedMountContext {
|
||||
id: string
|
||||
provider: string
|
||||
figure: HTMLElement
|
||||
aspect?: string
|
||||
height?: string
|
||||
fallbackHtml: string
|
||||
reducedMotion: Readonly<{ value: boolean }>
|
||||
isReducedMotion: boolean
|
||||
}
|
||||
|
||||
/** Provider registration shape accepted by `app.config.ts` and plugin helpers. */
|
||||
export interface JournalEmbedProvider {
|
||||
/** Pattern a `data-id` value must match (anchored automatically). */
|
||||
idPattern: RegExp | string
|
||||
/**
|
||||
* Optional SSR expansion hook. Returning a string replaces the `<figure>`
|
||||
* element during `expandEmbeds`; returning `undefined` or `null` leaves it
|
||||
* for client hydration or untouched.
|
||||
*/
|
||||
renderSsr?: (id: string, ctx: JournalEmbedSsrContext) => string | undefined | null
|
||||
/** Optional Vue async component loader for client-side lazy hydration. */
|
||||
component?: () => Promise<unknown>
|
||||
/** Optional plain DOM mount callback for client-side lazy hydration. */
|
||||
mount?: (el: HTMLElement, ctx: JournalEmbedMountContext) => void | (() => void) | Promise<void | (() => void)>
|
||||
/** Default CLS aspect-ratio token (validated against `EMBED_ASPECT`). */
|
||||
aspectRatio?: string
|
||||
/** Default CLS min-height token (validated against `EMBED_HEIGHT`). */
|
||||
minHeight?: string
|
||||
/** `IntersectionObserver` rootMargin override (default `'200px'`). */
|
||||
rootMargin?: string
|
||||
}
|
||||
|
||||
/** Normalized provider stored inside `JournalEmbedRegistry`. */
|
||||
export interface NormalizedJournalEmbedProvider {
|
||||
readonly key: string
|
||||
readonly idPattern: RegExp
|
||||
readonly renderSsr?: JournalEmbedProvider['renderSsr']
|
||||
readonly component?: JournalEmbedProvider['component']
|
||||
readonly mount?: JournalEmbedProvider['mount']
|
||||
readonly aspectRatio?: string
|
||||
readonly minHeight?: string
|
||||
readonly rootMargin?: string
|
||||
/** Internal flag distinguishing the built-in default YouTube provider. */
|
||||
readonly _builtinYoutube?: boolean
|
||||
}
|
||||
|
||||
function normalizeCssHeight(value: string): string {
|
||||
return value.endsWith('px') ? value : `${value}px`
|
||||
}
|
||||
|
||||
function buildClsStyle(aspect?: string, height?: string): string {
|
||||
const parts: string[] = []
|
||||
if (aspect && EMBED_ASPECT.test(aspect)) parts.push(`aspect-ratio:${aspect.replace(/\s+/g, '')}`)
|
||||
if (height && EMBED_HEIGHT.test(height)) parts.push(`min-height:${normalizeCssHeight(height)}`)
|
||||
return parts.join(';')
|
||||
}
|
||||
|
||||
/** Built-in privacy-enhanced YouTube provider (100% SSR byte-compatible default). */
|
||||
export const YOUTUBE_EMBED_PROVIDER: JournalEmbedProvider = Object.freeze({
|
||||
idPattern: /^[A-Za-z0-9_-]{11}$/,
|
||||
renderSsr(id: string, ctx: JournalEmbedSsrContext): string | undefined {
|
||||
if (ctx.innerHtml !== '') return undefined
|
||||
const style = buildClsStyle(ctx.aspect, ctx.height)
|
||||
const styleAttr = style ? ` style="${style}"` : ''
|
||||
return (
|
||||
`<figure class="journal-embed journal-embed--youtube"${styleAttr}>` +
|
||||
`<iframe src="https://www.youtube-nocookie.com/embed/${id}" title="YouTube video" loading="lazy" ` +
|
||||
'referrerpolicy="strict-origin-when-cross-origin" ' +
|
||||
'allow="encrypted-media; picture-in-picture; fullscreen" allowfullscreen></iframe>' +
|
||||
'</figure>'
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
function normalizeIdPattern(name: string, pattern: RegExp | string): RegExp {
|
||||
let raw: RegExp
|
||||
if (pattern instanceof RegExp) {
|
||||
raw = pattern
|
||||
} else if (typeof pattern === 'string' && pattern.length > 0) {
|
||||
try {
|
||||
raw = new RegExp(pattern)
|
||||
} catch (err) {
|
||||
throw new Error(`Invalid idPattern for journal embed provider "${name}": ${String(err)}`)
|
||||
}
|
||||
} else {
|
||||
throw new Error(`Journal embed provider "${name}" must provide a RegExp or non-empty string idPattern`)
|
||||
}
|
||||
const flags = raw.flags.replace(/[gy]/g, '')
|
||||
return new RegExp(`^(?:${raw.source})$`, flags)
|
||||
}
|
||||
|
||||
function normalizeProvider(name: string, provider: JournalEmbedProvider): NormalizedJournalEmbedProvider {
|
||||
if (!EMBED_PROVIDER_KEY.test(name) || RESERVED_PROVIDER_KEYS.has(name)) {
|
||||
throw new Error(`Invalid journal embed provider key "${name}": must match ${EMBED_PROVIDER_KEY.source}`)
|
||||
}
|
||||
if (!provider || typeof provider !== 'object') {
|
||||
throw new Error(`Journal embed provider "${name}" must be an object`)
|
||||
}
|
||||
const idPattern = normalizeIdPattern(name, provider.idPattern)
|
||||
let aspectRatio: string | undefined
|
||||
if (provider.aspectRatio !== undefined) {
|
||||
const trimmed = provider.aspectRatio.trim()
|
||||
if (!EMBED_ASPECT.test(trimmed)) {
|
||||
throw new Error(`Invalid aspectRatio "${provider.aspectRatio}" for journal embed provider "${name}"`)
|
||||
}
|
||||
aspectRatio = trimmed
|
||||
}
|
||||
let minHeight: string | undefined
|
||||
if (provider.minHeight !== undefined) {
|
||||
const trimmed = provider.minHeight.trim()
|
||||
if (!EMBED_HEIGHT.test(trimmed)) {
|
||||
throw new Error(`Invalid minHeight "${provider.minHeight}" for journal embed provider "${name}"`)
|
||||
}
|
||||
minHeight = trimmed
|
||||
}
|
||||
return Object.freeze({
|
||||
key: name,
|
||||
idPattern,
|
||||
renderSsr: provider.renderSsr,
|
||||
component: provider.component,
|
||||
mount: provider.mount,
|
||||
aspectRatio,
|
||||
minHeight,
|
||||
rootMargin: typeof provider.rootMargin === 'string' && provider.rootMargin.trim() ? provider.rootMargin.trim() : undefined,
|
||||
_builtinYoutube: provider === YOUTUBE_EMBED_PROVIDER,
|
||||
})
|
||||
}
|
||||
|
||||
/** Prototype-safe registry of allowed Journal embed providers. */
|
||||
export class JournalEmbedRegistry {
|
||||
private readonly providers = new Map<string, NormalizedJournalEmbedProvider>()
|
||||
|
||||
register(name: string, provider: JournalEmbedProvider): this {
|
||||
this.providers.set(name, normalizeProvider(name, provider))
|
||||
return this
|
||||
}
|
||||
|
||||
define(map: Record<string, JournalEmbedProvider> | null | undefined): this {
|
||||
if (!map || typeof map !== 'object') return this
|
||||
for (const key of Object.keys(map)) {
|
||||
const provider = map[key]
|
||||
if (provider !== undefined) this.register(key, provider)
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
get(name: string): NormalizedJournalEmbedProvider | undefined {
|
||||
if (!EMBED_PROVIDER_KEY.test(name)) return undefined
|
||||
return this.providers.get(name)
|
||||
}
|
||||
|
||||
has(name: string): boolean {
|
||||
if (!EMBED_PROVIDER_KEY.test(name)) return false
|
||||
return this.providers.has(name)
|
||||
}
|
||||
|
||||
match(name: string, id: string): boolean {
|
||||
const provider = this.get(name)
|
||||
if (!provider || typeof id !== 'string') return false
|
||||
return provider.idPattern.test(id)
|
||||
}
|
||||
|
||||
keys(): string[] {
|
||||
return [...this.providers.keys()]
|
||||
}
|
||||
|
||||
entries(): Array<[string, NormalizedJournalEmbedProvider]> {
|
||||
return [...this.providers.entries()]
|
||||
}
|
||||
|
||||
clone(): JournalEmbedRegistry {
|
||||
const copy = new JournalEmbedRegistry()
|
||||
for (const [k, v] of this.providers.entries()) copy.providers.set(k, v)
|
||||
return copy
|
||||
}
|
||||
}
|
||||
|
||||
/** Creates a new embed registry, pre-populated with built-in `youtube` by default. */
|
||||
export function createJournalEmbedRegistry(
|
||||
initial?: Record<string, JournalEmbedProvider> | null,
|
||||
includeDefaults = true,
|
||||
): JournalEmbedRegistry {
|
||||
const registry = new JournalEmbedRegistry()
|
||||
if (includeDefaults) registry.register('youtube', YOUTUBE_EMBED_PROVIDER)
|
||||
if (initial) registry.define(initial)
|
||||
return registry
|
||||
}
|
||||
|
||||
let activeRegistry = createJournalEmbedRegistry()
|
||||
|
||||
/** Returns the active module-level Journal embed registry. */
|
||||
export function getJournalEmbedRegistry(): JournalEmbedRegistry {
|
||||
return activeRegistry
|
||||
}
|
||||
|
||||
/** Registers or overrides a single embed provider on the active registry. */
|
||||
export function registerJournalEmbedProvider(name: string, provider: JournalEmbedProvider): JournalEmbedRegistry {
|
||||
return activeRegistry.register(name, provider)
|
||||
}
|
||||
|
||||
/** Registers or overrides a map of embed providers on the active registry. */
|
||||
export function defineJournalEmbedProviders(
|
||||
map: Record<string, JournalEmbedProvider> | null | undefined,
|
||||
): JournalEmbedRegistry {
|
||||
return activeRegistry.define(map)
|
||||
}
|
||||
|
||||
/** Resets the active registry back to the default built-in `youtube` provider (for tests). */
|
||||
export function resetJournalEmbedRegistry(): JournalEmbedRegistry {
|
||||
activeRegistry = createJournalEmbedRegistry()
|
||||
return activeRegistry
|
||||
}
|
||||
@@ -1,20 +1,27 @@
|
||||
// Embed expansion for Journal HTML. The Blog Editor (Journal plugin,
|
||||
// assets/src/blogeditor/embed.ts) never stores an iframe: it writes the
|
||||
// placeholder <figure data-embed="youtube" data-id="ID"></figure>, and the
|
||||
// plugin's bluemonday policy (classes/format_html.go) keeps exactly that, with
|
||||
// data-embed matching ^youtube$ and data-id matching ^[A-Za-z0-9_-]{11}$.
|
||||
// htmlGate.ts mirrors those two rules, so the placeholder survives the layer's
|
||||
// sanitizer too.
|
||||
// assets/src/blogeditor/embed.ts) never stores an iframe: it writes a
|
||||
// `<figure data-embed="<provider>" data-id="<id>">` placeholder (optionally
|
||||
// with `data-aspect`, `data-height`, and sanitized static fallback children
|
||||
// such as `<img>` and `<figcaption>`). Both `sm-journal-plugin` and
|
||||
// `htmlGate.ts` validate `(data-embed, data-id)` pair-aware against the
|
||||
// registered embed providers.
|
||||
//
|
||||
// expandEmbeds is the very last step before v-html, after sanitizeJournalHtml:
|
||||
// its input is always sanitizer output, and its output is never sanitized
|
||||
// again (the sanitizer strips every iframe, including the one built here). The
|
||||
// regex matches the serialization sanitize-html gives the placeholder:
|
||||
// attribute order kept, double quotes, empty figure. Only a known provider
|
||||
// with a valid id becomes an iframe, whose src is a fixed host plus that id;
|
||||
// anything else is returned unchanged and stays an inert empty figure.
|
||||
// again (the sanitizer strips every iframe, including the one built here).
|
||||
// Built-in `youtube` expands empty placeholders to a privacy-enhanced iframe
|
||||
// on youtube-nocookie.com; client-hydrated providers (`component` or `mount`)
|
||||
// keep their SSR fallback DOM intact with `journal-embed` classes and optional
|
||||
// CLS layout reservation (`aspect-ratio` / `min-height`).
|
||||
|
||||
/** One allowlisted embed provider. */
|
||||
import {
|
||||
EMBED_ASPECT,
|
||||
EMBED_HEIGHT,
|
||||
getJournalEmbedRegistry,
|
||||
type JournalEmbedRegistry,
|
||||
} from './embedRegistry.ts'
|
||||
|
||||
/** One allowlisted embed provider (legacy shape kept for backward compatibility). */
|
||||
export type EmbedProvider = {
|
||||
/** The id a placeholder must match to expand. */
|
||||
id: RegExp
|
||||
@@ -40,24 +47,123 @@ export const EMBED_PROVIDERS: Readonly<Record<string, EmbedProvider>> = Object.f
|
||||
*/
|
||||
export const EMBED_PLACEHOLDER = /<figure data-embed="([^"<>]*)" data-id="([^"<>]*)"><\/figure>/g
|
||||
|
||||
// Matches a sanitize-html serialized `<figure ...>...</figure>` (lowercase tag,
|
||||
// single-space-separated double-quoted attributes, no nested `<figure>`).
|
||||
const EMBED_FIGURE_RE = /<figure((?: [a-z][a-z0-9-]*="[^"<>]*")+)>((?:(?!<\/?figure\b)[\s\S])*?)<\/figure>/g
|
||||
const ATTR_PAIR_RE = / ([a-z][a-z0-9-]*)="([^"<>]*)"/g
|
||||
|
||||
function normalizeCssHeight(value: string): string {
|
||||
return value.endsWith('px') ? value : `${value}px`
|
||||
}
|
||||
|
||||
function mergeClasses(existing: string | undefined, required: readonly string[]): string {
|
||||
const tokens = existing ? existing.split(/\s+/).filter(Boolean) : []
|
||||
for (const cls of required) {
|
||||
if (!tokens.includes(cls)) tokens.push(cls)
|
||||
}
|
||||
return tokens.join(' ')
|
||||
}
|
||||
|
||||
function mergeClsStyle(existing: string | undefined, aspect?: string, height?: string): string | undefined {
|
||||
const decls = existing
|
||||
? existing
|
||||
.split(';')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
: []
|
||||
const hasProp = (prop: string) => decls.some((d) => d.toLowerCase().startsWith(`${prop}:`))
|
||||
if (aspect && EMBED_ASPECT.test(aspect) && !hasProp('aspect-ratio')) {
|
||||
decls.push(`aspect-ratio:${aspect.replace(/\s+/g, '')}`)
|
||||
}
|
||||
if (height && EMBED_HEIGHT.test(height) && !hasProp('min-height')) {
|
||||
decls.push(`min-height:${normalizeCssHeight(height)}`)
|
||||
}
|
||||
return decls.length > 0 ? decls.join(';') : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces every placeholder whose provider is in EMBED_PROVIDERS and whose
|
||||
* id passes the provider's pattern with a figure holding the provider's
|
||||
* iframe. Every other match is returned unchanged. Empty input gives "".
|
||||
* Call it on sanitizeJournalHtml output only, and never sanitize its result.
|
||||
* Expands validated embed placeholders using the active (or supplied)
|
||||
* `JournalEmbedRegistry`:
|
||||
* - Providers with `renderSsr` (e.g. built-in `youtube` on an empty figure)
|
||||
* emit their SSR HTML directly.
|
||||
* - Client-hydrated providers (`component` or `mount`) preserve the `<figure>`
|
||||
* and its static SSR fallback children while adding `journal-embed` /
|
||||
* `journal-embed--<provider>` classes and safe CLS `aspect-ratio` /
|
||||
* `min-height` reservation styles.
|
||||
* - Unknown providers or mismatched IDs remain untouched and inert.
|
||||
*
|
||||
* Call on `sanitizeJournalHtml` output only, and never sanitize its result.
|
||||
*/
|
||||
export function expandEmbeds(html: string | null | undefined): string {
|
||||
export function expandEmbeds(
|
||||
html: string | null | undefined,
|
||||
registry: JournalEmbedRegistry = getJournalEmbedRegistry(),
|
||||
): string {
|
||||
if (!html) return ''
|
||||
return html.replace(EMBED_PLACEHOLDER, (match: string, provider: string, id: string) => {
|
||||
if (!Object.hasOwn(EMBED_PROVIDERS, provider)) return match
|
||||
const p = EMBED_PROVIDERS[provider]!
|
||||
if (!p.id.test(id)) return match
|
||||
return (
|
||||
`<figure class="journal-embed journal-embed--${provider}">` +
|
||||
`<iframe src="${p.src(id)}" title="${p.title}" loading="lazy" ` +
|
||||
'referrerpolicy="strict-origin-when-cross-origin" ' +
|
||||
'allow="encrypted-media; picture-in-picture; fullscreen" allowfullscreen></iframe>' +
|
||||
'</figure>'
|
||||
)
|
||||
return html.replace(EMBED_FIGURE_RE, (match: string, attrText: string, innerHtml: string) => {
|
||||
const attrs: Array<[string, string]> = []
|
||||
const byName = new Map<string, string>()
|
||||
for (const m of attrText.matchAll(ATTR_PAIR_RE)) {
|
||||
const name = m[1]!
|
||||
const value = m[2]!
|
||||
attrs.push([name, value])
|
||||
if (!byName.has(name)) byName.set(name, value)
|
||||
}
|
||||
|
||||
const providerName = byName.get('data-embed')
|
||||
const id = byName.get('data-id')
|
||||
if (!providerName || !id) return match
|
||||
|
||||
const provider = registry.get(providerName)
|
||||
if (!provider || !provider.idPattern.test(id)) return match
|
||||
|
||||
const rawAspect = byName.get('data-aspect')
|
||||
const rawHeight = byName.get('data-height')
|
||||
const aspect = rawAspect && EMBED_ASPECT.test(rawAspect) ? rawAspect : undefined
|
||||
const height = rawHeight && EMBED_HEIGHT.test(rawHeight) ? rawHeight : undefined
|
||||
|
||||
if (provider.renderSsr) {
|
||||
if (provider._builtinYoutube) {
|
||||
// Built-in YouTube keeps strict placeholder shape: data-embed before
|
||||
// data-id, no extra attributes beyond data-aspect/data-height, empty body.
|
||||
const allowedKeys = new Set(['data-embed', 'data-id', 'data-aspect', 'data-height'])
|
||||
const embedIdx = attrs.findIndex(([k]) => k === 'data-embed')
|
||||
const idIdx = attrs.findIndex(([k]) => k === 'data-id')
|
||||
const allAllowed = attrs.every(([k]) => allowedKeys.has(k))
|
||||
if (innerHtml !== '' || !allAllowed || embedIdx < 0 || idIdx < 0 || embedIdx > idIdx) {
|
||||
return match
|
||||
}
|
||||
}
|
||||
const rendered = provider.renderSsr(id, { provider: providerName, innerHtml, aspect, height })
|
||||
if (typeof rendered === 'string') return rendered
|
||||
}
|
||||
|
||||
if (provider.component || provider.mount) {
|
||||
const nextClass = mergeClasses(byName.get('class'), ['journal-embed', `journal-embed--${providerName}`])
|
||||
const nextStyle = mergeClsStyle(byName.get('style'), aspect ?? provider.aspectRatio, height ?? provider.minHeight)
|
||||
const outAttrs: Array<[string, string]> = []
|
||||
let wroteClass = false
|
||||
let wroteStyle = false
|
||||
for (const [k, v] of attrs) {
|
||||
if (k === 'class') {
|
||||
if (!wroteClass) {
|
||||
outAttrs.push(['class', nextClass])
|
||||
wroteClass = true
|
||||
}
|
||||
} else if (k === 'style') {
|
||||
if (!wroteStyle && nextStyle) {
|
||||
outAttrs.push(['style', nextStyle])
|
||||
wroteStyle = true
|
||||
}
|
||||
} else {
|
||||
outAttrs.push([k, v])
|
||||
}
|
||||
}
|
||||
if (!wroteClass) outAttrs.unshift(['class', nextClass])
|
||||
if (!wroteStyle && nextStyle) outAttrs.push(['style', nextStyle])
|
||||
const serialized = outAttrs.map(([k, v]) => ` ${k}="${v}"`).join('')
|
||||
return `<figure${serialized}>${innerHtml}</figure>`
|
||||
}
|
||||
|
||||
return match
|
||||
})
|
||||
}
|
||||
|
||||
@@ -5,12 +5,13 @@
|
||||
// inline styles, goldmark's footnote roles, dir="auto" and two chat
|
||||
// transcript data attributes. URLs must be http, https, mailto or relative.
|
||||
//
|
||||
// The Blog Editor's own output adds exactly five rules, the same five the Go
|
||||
// policy has: figure data-embed (youtube only) and data-id (an 11-character
|
||||
// video id), which carry the embed placeholder that embeds.ts expands after
|
||||
// sanitizing; img alt with any text (the editor's free-text alt field, ""
|
||||
// for a decorative image); ol start (an integer); and a rel holding only the
|
||||
// tokens nofollow, sponsored and ugc (the editor's link form, Phase 33).
|
||||
// The Blog Editor's own output adds rules matching the Go policy: figure
|
||||
// data-embed/data-id (pair-aware against the active embed registry) plus
|
||||
// optional data-aspect/data-height for CLS reservation, which carry the embed
|
||||
// placeholder that embeds.ts expands or hydrates after sanitizing; img alt with
|
||||
// any text (the editor's free-text alt field, "" for a decorative image); ol
|
||||
// start (an integer); and a rel holding only the tokens nofollow, sponsored
|
||||
// and ugc (the editor's link form, Phase 33).
|
||||
// tests/fixtures/editor-corpus.json, a byte copy of the editor's corpus,
|
||||
// pins them. target is never kept: the outbound rules add it after
|
||||
// sanitizing (renderJournalBody).
|
||||
@@ -27,6 +28,7 @@
|
||||
// See docs/decisions/0001-sanitize-html.md.
|
||||
|
||||
import sanitizeHtml from 'sanitize-html'
|
||||
import { EMBED_ASPECT, EMBED_HEIGHT, getJournalEmbedRegistry, type JournalEmbedRegistry } from './embedRegistry.ts'
|
||||
|
||||
/** Elements of bluemonday's UGC policy, plus footer. */
|
||||
export const JOURNAL_ALLOWED_TAGS: readonly string[] = [
|
||||
@@ -71,9 +73,13 @@ const LINK_REL = /^(nofollow|sponsored|ugc)( (nofollow|sponsored|ugc))*$/
|
||||
// '?', '"' and more. Any value is accepted, as bluemonday's p.AllowAttrs("alt")
|
||||
// does; sanitize-html escapes attribute values on output and alt carries no URL.
|
||||
const FREE_TEXT = /^[\s\S]*$/
|
||||
// The embed placeholder written by the Blog Editor (see embeds.ts).
|
||||
const EMBED_PROVIDER = /^youtube$/
|
||||
const EMBED_ID = /^[A-Za-z0-9_-]{11}$/
|
||||
// Responsive image attributes injected by sm-journal-plugin for /media/<short-id>/... items (Phase 37, D-14).
|
||||
const IMG_LOADING = /^(lazy|eager)$/i
|
||||
const IMG_DECODING = /^(async|sync|auto)$/i
|
||||
const IMG_SIZES_SAFE = /^[a-zA-Z0-9\s(),.%:-]+$/
|
||||
const IMG_SIZES_FORBIDDEN = /\b(?:url|expression)\s*\(/i
|
||||
const SRCSET_DESCRIPTOR = /^(?:[1-9][0-9]*w|(?:[0-9]+\.?[0-9]*|\.[0-9]+)x)$/
|
||||
const IMG_ALLOWED_SCHEMES: readonly string[] = ['http', 'https']
|
||||
|
||||
// A value pattern; null marks a URL attribute (checked by allowedUrl) or
|
||||
// style (filtered per property by allowedStyles).
|
||||
@@ -124,8 +130,23 @@ const ELEMENT_ATTRS: Record<string, Record<string, ValueRule>> = {
|
||||
rel: SPACE_SEPARATED_TOKENS,
|
||||
shape: /^(default|circle|rect|poly)$/i,
|
||||
},
|
||||
figure: { 'data-embed': EMBED_PROVIDER, 'data-id': EMBED_ID },
|
||||
img: { src: null, alt: FREE_TEXT, align: IMAGE_ALIGN, ...SIZE, usemap: /^#[\p{L}\p{N}_-]+$/iu },
|
||||
figure: {
|
||||
'data-embed': null,
|
||||
'data-id': null,
|
||||
'data-aspect': EMBED_ASPECT,
|
||||
'data-height': EMBED_HEIGHT,
|
||||
},
|
||||
img: {
|
||||
src: null,
|
||||
srcset: null,
|
||||
sizes: null,
|
||||
alt: FREE_TEXT,
|
||||
align: IMAGE_ALIGN,
|
||||
...SIZE,
|
||||
loading: IMG_LOADING,
|
||||
decoding: IMG_DECODING,
|
||||
usemap: /^#[\p{L}\p{N}_-]+$/iu,
|
||||
},
|
||||
time: { datetime: ISO8601 },
|
||||
del: { cite: PARAGRAPH, datetime: ISO8601 },
|
||||
ins: { cite: PARAGRAPH, datetime: ISO8601 },
|
||||
@@ -186,21 +207,88 @@ function allowedUrl(url: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True when `srcset` consists exclusively of valid comma-separated image
|
||||
* candidates (`<url> [<width>w | <density>x]`) whose URLs are relative
|
||||
* (e.g. `/media/...`) or use `http:`/`https:`, never `javascript:`, `data:`,
|
||||
* `vbscript:`, or `mailto:`.
|
||||
*/
|
||||
function allowedSrcset(value: string): boolean {
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) return false
|
||||
const parts = trimmed.split(',')
|
||||
for (const part of parts) {
|
||||
const tokens = part.trim().split(/\s+/).filter(Boolean)
|
||||
if (tokens.length < 1 || tokens.length > 2) return false
|
||||
const candidateUrl = tokens[0]!
|
||||
const scheme = URL_SCHEME.exec(candidateUrl.replace(URL_IGNORED, ''))
|
||||
if (scheme && !IMG_ALLOWED_SCHEMES.includes(scheme[1]!.toLowerCase())) return false
|
||||
try {
|
||||
new URL(candidateUrl, 'https://journal.invalid/')
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
if (tokens.length === 2 && !SRCSET_DESCRIPTOR.test(tokens[1]!)) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function allowedSizes(value: string): boolean {
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) return false
|
||||
return IMG_SIZES_SAFE.test(trimmed) && !IMG_SIZES_FORBIDDEN.test(trimmed)
|
||||
}
|
||||
|
||||
// Runs before sanitize-html's own attribute filter: drops every attribute
|
||||
// whose value fails its pattern. sanitize-html then drops attributes that
|
||||
// are not allowed on the element at all. Lookups are own-property only, so
|
||||
// a tag or attribute named "constructor" or "toString" finds no rule.
|
||||
function filterAttributeValues(tagName: string, attribs: sanitizeHtml.Attributes): sanitizeHtml.Tag {
|
||||
const own = Object.hasOwn(ELEMENT_ATTRS, tagName) ? ELEMENT_ATTRS[tagName] : undefined
|
||||
const kept: sanitizeHtml.Attributes = {}
|
||||
for (const [name, value] of Object.entries(attribs)) {
|
||||
let rule: ValueRule | undefined
|
||||
if (own && Object.hasOwn(own, name)) rule = own[name]
|
||||
else if (Object.hasOwn(GLOBAL_ATTRS, name)) rule = GLOBAL_ATTRS[name]
|
||||
if (rule === undefined) continue
|
||||
if (rule === null ? name === 'style' || allowedUrl(value) : rule.test(value)) kept[name] = value
|
||||
// On `<figure>`, `(data-embed, data-id)` are validated pair-aware against the
|
||||
// active embed registry; `data-aspect` and `data-height` are kept only on a
|
||||
// validated embed figure.
|
||||
function makeFilterAttributeValues(registry: JournalEmbedRegistry) {
|
||||
return function filterAttributeValues(tagName: string, attribs: sanitizeHtml.Attributes): sanitizeHtml.Tag {
|
||||
const own = Object.hasOwn(ELEMENT_ATTRS, tagName) ? ELEMENT_ATTRS[tagName] : undefined
|
||||
const kept: sanitizeHtml.Attributes = {}
|
||||
const isFigure = tagName === 'figure'
|
||||
let validEmbedPair = false
|
||||
if (isFigure) {
|
||||
const rawEmbed = Object.hasOwn(attribs, 'data-embed') ? attribs['data-embed'] : undefined
|
||||
const rawId = Object.hasOwn(attribs, 'data-id') ? attribs['data-id'] : undefined
|
||||
validEmbedPair = typeof rawEmbed === 'string' && typeof rawId === 'string' && registry.match(rawEmbed, rawId)
|
||||
}
|
||||
for (const [name, value] of Object.entries(attribs)) {
|
||||
if (isFigure && (name === 'data-embed' || name === 'data-id')) {
|
||||
if (validEmbedPair) kept[name] = value
|
||||
continue
|
||||
}
|
||||
if (isFigure && name === 'data-aspect') {
|
||||
if (validEmbedPair && EMBED_ASPECT.test(value)) kept[name] = value
|
||||
continue
|
||||
}
|
||||
if (isFigure && name === 'data-height') {
|
||||
if (validEmbedPair && EMBED_HEIGHT.test(value)) kept[name] = value
|
||||
continue
|
||||
}
|
||||
let rule: ValueRule | undefined
|
||||
if (own && Object.hasOwn(own, name)) rule = own[name]
|
||||
else if (Object.hasOwn(GLOBAL_ATTRS, name)) rule = GLOBAL_ATTRS[name]
|
||||
if (rule === undefined) continue
|
||||
if (rule === null) {
|
||||
if (name === 'style') kept[name] = value
|
||||
else if (name === 'srcset') {
|
||||
if (allowedSrcset(value)) kept[name] = value
|
||||
} else if (name === 'sizes') {
|
||||
if (allowedSizes(value)) kept[name] = value
|
||||
} else if (allowedUrl(value)) {
|
||||
kept[name] = value
|
||||
}
|
||||
} else if (rule.test(value)) {
|
||||
kept[name] = value
|
||||
}
|
||||
}
|
||||
return { tagName, attribs: kept }
|
||||
}
|
||||
return { tagName, attribs: kept }
|
||||
}
|
||||
|
||||
const allowedAttributes: Record<string, string[]> = { '*': Object.keys(GLOBAL_ATTRS) }
|
||||
@@ -214,7 +302,7 @@ type Options = sanitizeHtml.IOptions & { allowedEmptyAttributes: string[] }
|
||||
// them as name="", so an empty value compares equal.
|
||||
const EMPTY_ATTRS = ['alt', 'title', 'summary', 'abbr', 'itemscope', 'open', 'nowrap']
|
||||
|
||||
const POLICY: Options = {
|
||||
const BASE_POLICY: Omit<Options, 'transformTags'> = {
|
||||
allowedTags: [...JOURNAL_ALLOWED_TAGS],
|
||||
allowedAttributes,
|
||||
allowedStyles: { '*': ALLOWED_STYLES },
|
||||
@@ -227,7 +315,18 @@ const POLICY: Options = {
|
||||
// content is never shown as text (bluemonday skips the same content).
|
||||
disallowedTagsMode: 'discard',
|
||||
nonTextTags: ['script', 'style', 'textarea', 'option', 'noscript', 'title', 'iframe', 'noembed', 'noframes', 'object', 'xmp', 'template'],
|
||||
transformTags: { '*': filterAttributeValues },
|
||||
}
|
||||
|
||||
// Preserve raw srcset values verbatim in KEEP_ALL so sanitize-html's built-in
|
||||
// srcset filter does not strip them before gateJournalHtml compares POLICY vs KEEP_ALL.
|
||||
const KEEP_ALL_SRCSET_ATTR = 'data-__keep-srcset__'
|
||||
function preserveRawSrcset(tagName: string, attribs: sanitizeHtml.Attributes): sanitizeHtml.Tag {
|
||||
if (!Object.hasOwn(attribs, 'srcset')) return { tagName, attribs }
|
||||
const next: sanitizeHtml.Attributes = {}
|
||||
for (const [k, v] of Object.entries(attribs)) {
|
||||
next[k === 'srcset' ? KEEP_ALL_SRCSET_ATTR : k] = v
|
||||
}
|
||||
return { tagName, attribs: next }
|
||||
}
|
||||
|
||||
// The same parser and serializer with nothing refused: the reference that
|
||||
@@ -241,14 +340,22 @@ const KEEP_ALL: Options = {
|
||||
nonTextTags: [],
|
||||
allowedEmptyAttributes: EMPTY_ATTRS,
|
||||
nonBooleanAttributes: [],
|
||||
transformTags: { '*': preserveRawSrcset },
|
||||
}
|
||||
|
||||
// H1 demotion (the Journal H1 setting, UI-SPEC L7 step 1): every h1 becomes
|
||||
// an h2 with the same attributes. A tag's own transform replaces the '*'
|
||||
// one in sanitize-html, so the policy's demotion still filters the values.
|
||||
const demoted = (filter: (tag: string, attribs: sanitizeHtml.Attributes) => sanitizeHtml.Tag) => (_tag: string, attribs: sanitizeHtml.Attributes): sanitizeHtml.Tag => ({ tagName: 'h2', attribs: filter('h1', attribs).attribs })
|
||||
const POLICY_DEMOTE_H1: Options = { ...POLICY, transformTags: { ...POLICY.transformTags, h1: demoted(filterAttributeValues) } }
|
||||
const KEEP_ALL_DEMOTE_H1: Options = { ...KEEP_ALL, transformTags: { h1: demoted((tagName, attribs) => ({ tagName, attribs })) } }
|
||||
const KEEP_ALL_DEMOTE_H1: Options = { ...KEEP_ALL, transformTags: { ...KEEP_ALL.transformTags, h1: demoted(preserveRawSrcset) } }
|
||||
|
||||
function buildPolicy(demoteH1: boolean, registry: JournalEmbedRegistry): Options {
|
||||
const filter = makeFilterAttributeValues(registry)
|
||||
return {
|
||||
...BASE_POLICY,
|
||||
transformTags: demoteH1 ? { '*': filter, h1: demoted(filter) } : { '*': filter },
|
||||
}
|
||||
}
|
||||
|
||||
/** Options of the gate. */
|
||||
export interface JournalHtmlGateOptions {
|
||||
@@ -258,6 +365,11 @@ export interface JournalHtmlGateOptions {
|
||||
* H1. Default false, the HTML as written.
|
||||
*/
|
||||
demoteH1?: boolean
|
||||
/**
|
||||
* Optional embed provider registry override. Defaults to the active global
|
||||
* registry (`getJournalEmbedRegistry()`).
|
||||
*/
|
||||
embedRegistry?: JournalEmbedRegistry
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -270,7 +382,8 @@ export interface JournalHtmlGateOptions {
|
||||
*/
|
||||
export function sanitizeJournalHtml(html: string | null | undefined, options: JournalHtmlGateOptions = {}): string {
|
||||
if (!html) return ''
|
||||
return sanitizeHtml(html, options.demoteH1 ? POLICY_DEMOTE_H1 : POLICY)
|
||||
const registry = options.embedRegistry ?? getJournalEmbedRegistry()
|
||||
return sanitizeHtml(html, buildPolicy(options.demoteH1 === true, registry))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -278,8 +391,8 @@ export function sanitizeJournalHtml(html: string | null | undefined, options: Jo
|
||||
* attribute or text and only normalizes how the markup is written. The
|
||||
* counterpart of the plugin's CheckHTML. Null or empty input is safe.
|
||||
*/
|
||||
export function isSafeJournalHtml(html: string | null | undefined): boolean {
|
||||
return gateJournalHtml(html).safe
|
||||
export function isSafeJournalHtml(html: string | null | undefined, options: JournalHtmlGateOptions = {}): boolean {
|
||||
return gateJournalHtml(html, options).safe
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -292,8 +405,10 @@ export function isSafeJournalHtml(html: string | null | undefined): boolean {
|
||||
export function gateJournalHtml(html: string | null | undefined, options: JournalHtmlGateOptions = {}): { safe: boolean; html: string } {
|
||||
if (!html) return { safe: true, html: '' }
|
||||
const demote = options.demoteH1 === true
|
||||
const clean = sanitizeHtml(html, demote ? POLICY_DEMOTE_H1 : POLICY)
|
||||
return { safe: clean === sanitizeHtml(html, demote ? KEEP_ALL_DEMOTE_H1 : KEEP_ALL), html: clean }
|
||||
const registry = options.embedRegistry ?? getJournalEmbedRegistry()
|
||||
const clean = sanitizeHtml(html, buildPolicy(demote, registry))
|
||||
const reference = sanitizeHtml(html, demote ? KEEP_ALL_DEMOTE_H1 : KEEP_ALL).replaceAll(`${KEEP_ALL_SRCSET_ATTR}=`, 'srcset=')
|
||||
return { safe: clean === reference, html: clean }
|
||||
}
|
||||
|
||||
/** The body link steps of vue-seo-layer (app/utils/bodyLinks.ts), passed in by the component. */
|
||||
@@ -334,7 +449,7 @@ export interface JournalBodyOptions extends JournalHtmlGateOptions {
|
||||
* escaped markup to sanitized output, never re-reads the raw input.
|
||||
*/
|
||||
export function renderJournalBody(html: string | null | undefined, options: JournalBodyOptions = {}, steps?: JournalBodyLinkSteps | null): string {
|
||||
let out = sanitizeJournalHtml(html, { demoteH1: options.demoteH1 === true })
|
||||
let out = sanitizeJournalHtml(html, { demoteH1: options.demoteH1 === true, embedRegistry: options.embedRegistry })
|
||||
if (!out || !steps) return out
|
||||
const links = Array.isArray(options.autolinks) ? options.autolinks : []
|
||||
const max = Number(options.autolinkMax) || 0
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "vue-journal-layer",
|
||||
"version": "0.8.1",
|
||||
"version": "0.8.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./nuxt.config.ts",
|
||||
|
||||
525
tests/embedHydration.test.ts
Normal file
525
tests/embedHydration.test.ts
Normal file
@@ -0,0 +1,525 @@
|
||||
// Client-side lazy embed hydration tests (Phase 38, D-08).
|
||||
// Runs directly under `node --test` using lightweight DOM, IntersectionObserver,
|
||||
// and matchMedia doubles (zero browser/DOM test-runner dependency).
|
||||
import { afterEach, test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import type { AppContext } from 'vue'
|
||||
import { createJournalEmbedRegistry, resetJournalEmbedRegistry } from '../app/utils/embedRegistry.ts'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Minimal DOM double sufficient for Vue 3 `render(vnode, host)` and
|
||||
// `useJournalEmbedHydration` / `hydrateEmbedFigure`.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class FakeNode {
|
||||
nodeType: number
|
||||
parentNode: FakeElement | null = null
|
||||
childNodes: FakeNode[] = []
|
||||
ownerDocument: FakeDocument
|
||||
|
||||
constructor(nodeType: number, ownerDocument: FakeDocument) {
|
||||
this.nodeType = nodeType
|
||||
this.ownerDocument = ownerDocument
|
||||
}
|
||||
|
||||
get firstChild(): FakeNode | null {
|
||||
return this.childNodes[0] ?? null
|
||||
}
|
||||
|
||||
get nextSibling(): FakeNode | null {
|
||||
if (!this.parentNode) return null
|
||||
const idx = this.parentNode.childNodes.indexOf(this)
|
||||
return idx >= 0 ? (this.parentNode.childNodes[idx + 1] ?? null) : null
|
||||
}
|
||||
}
|
||||
|
||||
class FakeText extends FakeNode {
|
||||
nodeValue: string
|
||||
constructor(text: string, ownerDocument: FakeDocument) {
|
||||
super(3, ownerDocument)
|
||||
this.nodeValue = String(text)
|
||||
}
|
||||
get textContent(): string {
|
||||
return this.nodeValue
|
||||
}
|
||||
set textContent(v: string) {
|
||||
this.nodeValue = String(v ?? '')
|
||||
}
|
||||
}
|
||||
|
||||
class FakeComment extends FakeNode {
|
||||
nodeValue: string
|
||||
constructor(text: string, ownerDocument: FakeDocument) {
|
||||
super(8, ownerDocument)
|
||||
this.nodeValue = String(text)
|
||||
}
|
||||
}
|
||||
|
||||
class FakeClassList {
|
||||
private readonly set = new Set<string>()
|
||||
add(...tokens: string[]): void {
|
||||
for (const t of tokens) if (t) this.set.add(t)
|
||||
}
|
||||
remove(...tokens: string[]): void {
|
||||
for (const t of tokens) this.set.delete(t)
|
||||
}
|
||||
contains(token: string): boolean {
|
||||
return this.set.has(token)
|
||||
}
|
||||
toString(): string {
|
||||
return [...this.set].join(' ')
|
||||
}
|
||||
}
|
||||
|
||||
class FakeElement extends FakeNode {
|
||||
readonly tagName: string
|
||||
readonly attrs = new Map<string, string>()
|
||||
readonly classList = new FakeClassList()
|
||||
readonly style: Record<string, string> = {}
|
||||
measuredHeight = 0
|
||||
private _rawInnerHtml = ''
|
||||
|
||||
constructor(tagName: string, ownerDocument: FakeDocument) {
|
||||
super(1, ownerDocument)
|
||||
this.tagName = tagName.toUpperCase()
|
||||
}
|
||||
|
||||
get className(): string {
|
||||
return this.classList.toString()
|
||||
}
|
||||
set className(val: string) {
|
||||
for (const t of val.split(/\s+/).filter(Boolean)) this.classList.add(t)
|
||||
}
|
||||
|
||||
get innerHTML(): string {
|
||||
if (this.childNodes.length === 0) return this._rawInnerHtml
|
||||
return this.childNodes
|
||||
.map((c) => {
|
||||
if (c instanceof FakeText) return c.nodeValue
|
||||
if (c instanceof FakeComment) return `<!--${c.nodeValue}-->`
|
||||
if (c instanceof FakeElement) {
|
||||
const tag = c.tagName.toLowerCase()
|
||||
const attrStr = [...c.attrs.entries()].map(([k, v]) => ` ${k}="${v}"`).join('')
|
||||
const cls = c.className ? ` class="${c.className}"` : ''
|
||||
return `<${tag}${cls}${attrStr}>${c.innerHTML}</${tag}>`
|
||||
}
|
||||
return ''
|
||||
})
|
||||
.join('')
|
||||
}
|
||||
|
||||
set innerHTML(val: string) {
|
||||
this.childNodes = []
|
||||
this._rawInnerHtml = val
|
||||
}
|
||||
|
||||
get textContent(): string {
|
||||
if (this.childNodes.length === 0) return this._rawInnerHtml
|
||||
return this.childNodes.map((c) => (c instanceof FakeText || c instanceof FakeElement ? c.textContent : '')).join('')
|
||||
}
|
||||
|
||||
set textContent(val: string) {
|
||||
this.childNodes = []
|
||||
this._rawInnerHtml = ''
|
||||
if (val !== '') this.appendChild(new FakeText(String(val), this.ownerDocument))
|
||||
}
|
||||
|
||||
getAttribute(name: string): string | null {
|
||||
return this.attrs.get(name) ?? null
|
||||
}
|
||||
setAttribute(name: string, value: string): void {
|
||||
if (name === 'class') this.className = value
|
||||
else this.attrs.set(name, String(value))
|
||||
}
|
||||
removeAttribute(name: string): void {
|
||||
this.attrs.delete(name)
|
||||
}
|
||||
|
||||
getBoundingClientRect(): { height: number; width: number } {
|
||||
return { height: this.measuredHeight, width: 800 }
|
||||
}
|
||||
|
||||
appendChild(child: FakeNode): FakeNode {
|
||||
if (child.parentNode) child.parentNode.removeChild(child)
|
||||
child.parentNode = this
|
||||
this.childNodes.push(child)
|
||||
return child
|
||||
}
|
||||
|
||||
insertBefore(child: FakeNode, anchor: FakeNode | null): FakeNode {
|
||||
if (child.parentNode) child.parentNode.removeChild(child)
|
||||
child.parentNode = this
|
||||
if (!anchor) {
|
||||
this.childNodes.push(child)
|
||||
return child
|
||||
}
|
||||
const idx = this.childNodes.indexOf(anchor)
|
||||
if (idx < 0) this.childNodes.push(child)
|
||||
else this.childNodes.splice(idx, 0, child)
|
||||
return child
|
||||
}
|
||||
|
||||
removeChild(child: FakeNode): FakeNode {
|
||||
const idx = this.childNodes.indexOf(child)
|
||||
if (idx >= 0) {
|
||||
this.childNodes.splice(idx, 1)
|
||||
child.parentNode = null
|
||||
}
|
||||
return child
|
||||
}
|
||||
|
||||
replaceChildren(...nodes: FakeNode[]): void {
|
||||
for (const c of this.childNodes) c.parentNode = null
|
||||
this.childNodes = []
|
||||
this._rawInnerHtml = ''
|
||||
for (const n of nodes) this.appendChild(n)
|
||||
}
|
||||
|
||||
querySelectorAll(selector: string): FakeElement[] {
|
||||
if (selector !== 'figure[data-embed][data-id]') return []
|
||||
const out: FakeElement[] = []
|
||||
const walk = (el: FakeElement) => {
|
||||
for (const c of el.childNodes) {
|
||||
if (c instanceof FakeElement) {
|
||||
if (c.tagName === 'FIGURE' && c.attrs.has('data-embed') && c.attrs.has('data-id')) out.push(c)
|
||||
walk(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(this)
|
||||
return out
|
||||
}
|
||||
}
|
||||
|
||||
class FakeDocument {
|
||||
createElement(tag: string): FakeElement {
|
||||
return new FakeElement(tag, this)
|
||||
}
|
||||
createElementNS(_ns: string, tag: string): FakeElement {
|
||||
return new FakeElement(tag, this)
|
||||
}
|
||||
createTextNode(text: string): FakeText {
|
||||
return new FakeText(text, this)
|
||||
}
|
||||
createComment(text: string): FakeComment {
|
||||
return new FakeComment(text, this)
|
||||
}
|
||||
}
|
||||
|
||||
function makeFigure(
|
||||
doc: FakeDocument,
|
||||
attrs: Record<string, string>,
|
||||
fallbackHtml: string,
|
||||
measuredHeight = 360,
|
||||
): FakeElement {
|
||||
const fig = doc.createElement('figure')
|
||||
for (const [k, v] of Object.entries(attrs)) fig.setAttribute(k, v)
|
||||
fig.innerHTML = fallbackHtml
|
||||
fig.measuredHeight = measuredHeight
|
||||
return fig
|
||||
}
|
||||
|
||||
const origWindow = globalThis.window
|
||||
const origIO = globalThis.IntersectionObserver
|
||||
|
||||
// Install FakeDocument BEFORE importing `vue` so `@vue/runtime-dom` binds its
|
||||
// module-level `doc` reference to our lightweight DOM double.
|
||||
const sharedDoc = new FakeDocument()
|
||||
;(globalThis as Record<string, unknown>).document = sharedDoc
|
||||
const { createApp, createVNode, defineComponent, h, inject, onUnmounted, ref, render } = await import('vue')
|
||||
const { hydrateEmbedFigure, useJournalEmbedHydration } = await import('../app/composables/useJournalEmbedHydration.ts')
|
||||
|
||||
afterEach(() => {
|
||||
resetJournalEmbedRegistry()
|
||||
if (origWindow === undefined) delete (globalThis as Record<string, unknown>).window
|
||||
else (globalThis as Record<string, unknown>).window = origWindow
|
||||
if (origIO === undefined) delete (globalThis as Record<string, unknown>).IntersectionObserver
|
||||
else (globalThis as Record<string, unknown>).IntersectionObserver = origIO
|
||||
})
|
||||
|
||||
test('hydrateEmbedFigure mounts a plain DOM provider, reserves CLS minHeight, passes reducedMotion, and runs cleanup', async () => {
|
||||
const doc = new FakeDocument()
|
||||
const fallback = '<img src="/media/abc/chart.webp" alt="Chart"><figcaption>Fig 1</figcaption>'
|
||||
const fig = makeFigure(doc, { 'data-embed': 'viz', 'data-id': 'chart-1', 'data-aspect': '16/9' }, fallback, 342.4)
|
||||
|
||||
let cleanedUp = false
|
||||
let receivedCtx: Record<string, unknown> | null = null
|
||||
let attachedDuringMount = false
|
||||
const registry = createJournalEmbedRegistry({
|
||||
viz: {
|
||||
idPattern: /^[a-z0-9-]+$/,
|
||||
mount(el, ctx) {
|
||||
attachedDuringMount = (el as unknown as FakeElement).parentNode === fig
|
||||
receivedCtx = {
|
||||
id: ctx.id,
|
||||
provider: ctx.provider,
|
||||
aspect: ctx.aspect,
|
||||
fallbackHtml: ctx.fallbackHtml,
|
||||
isReducedMotion: ctx.isReducedMotion,
|
||||
reducedMotionValue: ctx.reducedMotion.value,
|
||||
}
|
||||
el.textContent = `mounted:${ctx.id}`
|
||||
return () => {
|
||||
cleanedUp = true
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const reducedMotion = ref(true)
|
||||
const cleanup = await hydrateEmbedFigure(fig as unknown as HTMLElement, registry.get('viz')!, {
|
||||
id: 'chart-1',
|
||||
providerName: 'viz',
|
||||
reducedMotion,
|
||||
})
|
||||
|
||||
assert.ok(cleanup, 'expected cleanup function')
|
||||
assert.equal(attachedDuringMount, true, 'host element must be attached to figure before mount() runs')
|
||||
// CLS height reservation from measured fallback box (Math.ceil(342.4) = 343px).
|
||||
assert.equal(fig.style.minHeight, '343px')
|
||||
assert.equal(fig.classList.contains('journal-embed--hydrated'), true)
|
||||
assert.deepEqual(receivedCtx, {
|
||||
id: 'chart-1',
|
||||
provider: 'viz',
|
||||
aspect: '16/9',
|
||||
fallbackHtml: fallback,
|
||||
isReducedMotion: true,
|
||||
reducedMotionValue: true,
|
||||
})
|
||||
assert.match(fig.innerHTML, /class="journal-embed__stage"/)
|
||||
assert.match(fig.innerHTML, /mounted:chart-1/)
|
||||
|
||||
cleanup()
|
||||
assert.equal(cleanedUp, true)
|
||||
assert.equal(fig.classList.contains('journal-embed--hydrated'), false)
|
||||
})
|
||||
|
||||
test('hydrateEmbedFigure mounts a Vue async component inheriting appContext and unmounts cleanly', async () => {
|
||||
const doc = new FakeDocument()
|
||||
;(globalThis as Record<string, unknown>).document = doc
|
||||
|
||||
const fallback = '<img src="/media/abc/chart.webp" alt="Chart">'
|
||||
const fig = makeFigure(doc, { 'data-embed': 'viz', 'data-id': 'vue-chart', 'data-height': '420px' }, fallback, 420)
|
||||
|
||||
let unmounted = false
|
||||
const injectedKey = Symbol('app-i18n')
|
||||
const FakeChart = defineComponent({
|
||||
props: {
|
||||
id: { type: String, required: true },
|
||||
provider: { type: String, required: true },
|
||||
height: { type: String, default: undefined },
|
||||
fallbackHtml: { type: String, default: '' },
|
||||
reducedMotion: { type: Object, required: true },
|
||||
},
|
||||
setup(props) {
|
||||
const injected = inject<string>(injectedKey, 'missing')
|
||||
onUnmounted(() => {
|
||||
unmounted = true
|
||||
})
|
||||
return () =>
|
||||
h(
|
||||
'div',
|
||||
{ class: 'vue-chart-root' },
|
||||
`${props.provider}:${props.id}:${props.height}:${injected}:rm=${(props.reducedMotion as { value: boolean }).value}`,
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
const registry = createJournalEmbedRegistry({
|
||||
viz: {
|
||||
idPattern: /^[a-z0-9-]+$/,
|
||||
component: async () => ({ default: FakeChart }),
|
||||
},
|
||||
})
|
||||
|
||||
const fakeApp = createApp({ render: () => null })
|
||||
fakeApp.provide(injectedKey, 'from-nuxt-app')
|
||||
const appContext = fakeApp._context as AppContext
|
||||
|
||||
const reducedMotion = ref(false)
|
||||
const cleanup = await hydrateEmbedFigure(fig as unknown as HTMLElement, registry.get('viz')!, {
|
||||
id: 'vue-chart',
|
||||
providerName: 'viz',
|
||||
reducedMotion,
|
||||
appContext,
|
||||
onError: (err) => {
|
||||
throw err
|
||||
},
|
||||
})
|
||||
|
||||
assert.ok(cleanup)
|
||||
assert.equal(fig.classList.contains('journal-embed--hydrated'), true)
|
||||
assert.match(fig.innerHTML, /viz:vue-chart:420px:from-nuxt-app:rm=false/)
|
||||
|
||||
// Reactive reducedMotion update propagates into the mounted Vue component.
|
||||
reducedMotion.value = true
|
||||
await Promise.resolve()
|
||||
assert.match(fig.innerHTML, /rm=true/)
|
||||
|
||||
cleanup()
|
||||
assert.equal(unmounted, true)
|
||||
assert.equal(fig.classList.contains('journal-embed--hydrated'), false)
|
||||
})
|
||||
|
||||
test('hydrateEmbedFigure catches rejected import or mount throw and leaves SSR fallback DOM intact', async () => {
|
||||
const doc = new FakeDocument()
|
||||
const fallback = '<img src="/media/abc/fallback.webp" alt="Fallback"><figcaption>Still here</figcaption>'
|
||||
|
||||
// 1. Rejected dynamic component import
|
||||
const fig1 = makeFigure(doc, { 'data-embed': 'viz', 'data-id': 'broken-import' }, fallback, 300)
|
||||
const reg1 = createJournalEmbedRegistry({
|
||||
viz: {
|
||||
idPattern: /^[a-z0-9-]+$/,
|
||||
component: async () => {
|
||||
throw new Error('chunk load failed')
|
||||
},
|
||||
},
|
||||
})
|
||||
const errors: unknown[] = []
|
||||
const cleanup1 = await hydrateEmbedFigure(fig1 as unknown as HTMLElement, reg1.get('viz')!, {
|
||||
id: 'broken-import',
|
||||
providerName: 'viz',
|
||||
reducedMotion: ref(false),
|
||||
onError: (err) => errors.push(err),
|
||||
})
|
||||
assert.equal(cleanup1, null)
|
||||
assert.equal(errors.length, 1)
|
||||
assert.equal(fig1.innerHTML, fallback)
|
||||
assert.equal(fig1.classList.contains('journal-embed--hydrated'), false)
|
||||
|
||||
// 2. Thrown error inside plain DOM mount
|
||||
const fig2 = makeFigure(doc, { 'data-embed': 'viz', 'data-id': 'broken-mount' }, fallback, 300)
|
||||
const reg2 = createJournalEmbedRegistry({
|
||||
viz: {
|
||||
idPattern: /^[a-z0-9-]+$/,
|
||||
mount() {
|
||||
throw new Error('mount exploded')
|
||||
},
|
||||
},
|
||||
})
|
||||
const cleanup2 = await hydrateEmbedFigure(fig2 as unknown as HTMLElement, reg2.get('viz')!, {
|
||||
id: 'broken-mount',
|
||||
providerName: 'viz',
|
||||
reducedMotion: ref(false),
|
||||
onError: (err) => errors.push(err),
|
||||
})
|
||||
assert.equal(cleanup2, null)
|
||||
assert.equal(errors.length, 2)
|
||||
assert.equal(fig2.innerHTML, fallback)
|
||||
assert.equal(fig2.classList.contains('journal-embed--hydrated'), false)
|
||||
})
|
||||
|
||||
test('useJournalEmbedHydration defers hydration until IntersectionObserver fires and reacts to matchMedia changes', async () => {
|
||||
const doc = new FakeDocument()
|
||||
;(globalThis as Record<string, unknown>).document = doc
|
||||
|
||||
const motionListeners: Array<(e: { matches: boolean }) => void> = []
|
||||
const fakeWindow = {
|
||||
matchMedia: (query: string) => ({
|
||||
media: query,
|
||||
matches: false,
|
||||
addEventListener: (_type: string, fn: (e: { matches: boolean }) => void) => motionListeners.push(fn),
|
||||
removeEventListener: (_type: string, fn: (e: { matches: boolean }) => void) => {
|
||||
const idx = motionListeners.indexOf(fn)
|
||||
if (idx >= 0) motionListeners.splice(idx, 1)
|
||||
},
|
||||
}),
|
||||
}
|
||||
;(globalThis as Record<string, unknown>).window = fakeWindow
|
||||
|
||||
const observed: Array<{
|
||||
target: unknown
|
||||
options: { rootMargin?: string } | undefined
|
||||
trigger: (isIntersecting: boolean) => void
|
||||
disconnected: boolean
|
||||
}> = []
|
||||
|
||||
class FakeIntersectionObserver {
|
||||
private readonly cb: (entries: Array<{ isIntersecting: boolean }>, obs: FakeIntersectionObserver) => void
|
||||
private readonly opts: { rootMargin?: string } | undefined
|
||||
private record: (typeof observed)[number] | null = null
|
||||
|
||||
constructor(cb: (entries: Array<{ isIntersecting: boolean }>, obs: FakeIntersectionObserver) => void, opts?: { rootMargin?: string }) {
|
||||
this.cb = cb
|
||||
this.opts = opts
|
||||
}
|
||||
observe(target: unknown): void {
|
||||
this.record = {
|
||||
target,
|
||||
options: this.opts,
|
||||
disconnected: false,
|
||||
trigger: (isIntersecting: boolean) => this.cb([{ isIntersecting }], this),
|
||||
}
|
||||
observed.push(this.record)
|
||||
}
|
||||
disconnect(): void {
|
||||
if (this.record) this.record.disconnected = true
|
||||
}
|
||||
}
|
||||
;(globalThis as Record<string, unknown>).IntersectionObserver = FakeIntersectionObserver
|
||||
|
||||
const container = doc.createElement('div')
|
||||
const fallback = '<img src="/media/abc/chart.webp" alt="Chart">'
|
||||
const fig = makeFigure(doc, { 'data-embed': 'viz', 'data-id': 'lazy-chart' }, fallback, 320)
|
||||
container.appendChild(fig)
|
||||
|
||||
let mountCalls = 0
|
||||
let unmountCalls = 0
|
||||
let seenMotionRef: Readonly<{ value: boolean }> | null = null
|
||||
const registry = createJournalEmbedRegistry({
|
||||
viz: {
|
||||
idPattern: /^[a-z0-9-]+$/,
|
||||
rootMargin: '250px',
|
||||
mount(el, ctx) {
|
||||
mountCalls += 1
|
||||
seenMotionRef = ctx.reducedMotion
|
||||
el.textContent = `hydrated:${ctx.id}`
|
||||
return () => {
|
||||
unmountCalls += 1
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Mount a minimal host Vue component using `useJournalEmbedHydration`.
|
||||
const html = ref('<figure data-embed="viz" data-id="lazy-chart"></figure>')
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
const elRef = ref<HTMLElement | null>(container as unknown as HTMLElement)
|
||||
useJournalEmbedHydration(elRef, html, { registry })
|
||||
return () => h('div')
|
||||
},
|
||||
})
|
||||
|
||||
const appRoot = doc.createElement('div')
|
||||
render(createVNode(Host), appRoot as unknown as Element)
|
||||
|
||||
// Before intersection: observer registered with provider rootMargin, not yet hydrated.
|
||||
assert.equal(observed.length, 1)
|
||||
assert.equal(observed[0]!.options?.rootMargin, '250px')
|
||||
assert.equal(mountCalls, 0)
|
||||
assert.equal(fig.innerHTML, fallback)
|
||||
|
||||
// Non-intersecting event does not trigger hydration.
|
||||
observed[0]!.trigger(false)
|
||||
await Promise.resolve()
|
||||
assert.equal(mountCalls, 0)
|
||||
|
||||
// Intersecting event disconnects observer and hydrates the figure.
|
||||
observed[0]!.trigger(true)
|
||||
await new Promise((r) => setTimeout(r, 0))
|
||||
assert.equal(observed[0]!.disconnected, true)
|
||||
assert.equal(mountCalls, 1)
|
||||
assert.equal(fig.classList.contains('journal-embed--hydrated'), true)
|
||||
assert.equal(seenMotionRef!.value, false)
|
||||
|
||||
// matchMedia change updates the reactive reducedMotion ref.
|
||||
assert.equal(motionListeners.length, 1)
|
||||
motionListeners[0]!({ matches: true })
|
||||
assert.equal(seenMotionRef!.value, true)
|
||||
|
||||
// Unmounting the host component runs embed cleanup and removes matchMedia listener.
|
||||
render(null, appRoot as unknown as Element)
|
||||
assert.equal(unmountCalls, 1)
|
||||
assert.equal(motionListeners.length, 0)
|
||||
})
|
||||
@@ -2,11 +2,22 @@
|
||||
// <figure data-embed="youtube" data-id="ID"></figure>; the sinks render
|
||||
// expandEmbeds(sanitizeJournalHtml(html)), so the sanitizer runs first and the
|
||||
// only iframe in the output is the one built from a validated placeholder.
|
||||
import { test } from 'node:test'
|
||||
import { afterEach, test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { EMBED_PLACEHOLDER, EMBED_PROVIDERS, expandEmbeds } from '../app/utils/embeds.ts'
|
||||
import { sanitizeJournalHtml } from '../app/utils/htmlGate.ts'
|
||||
import {
|
||||
createJournalEmbedRegistry,
|
||||
defineJournalEmbedProviders,
|
||||
getJournalEmbedRegistry,
|
||||
registerJournalEmbedProvider,
|
||||
resetJournalEmbedRegistry,
|
||||
} from '../app/utils/embedRegistry.ts'
|
||||
import { gateJournalHtml, isSafeJournalHtml, sanitizeJournalHtml } from '../app/utils/htmlGate.ts'
|
||||
|
||||
afterEach(() => {
|
||||
resetJournalEmbedRegistry()
|
||||
})
|
||||
|
||||
const ID = 'dQw4w9WgXcQ'
|
||||
const PLACEHOLDER = `<figure data-embed="youtube" data-id="${ID}"></figure>`
|
||||
@@ -82,8 +93,8 @@ test('a placeholder smuggling an iframe or extra attributes expands only its val
|
||||
})
|
||||
|
||||
test('a malformed placeholder stays an empty figure after the sink', () => {
|
||||
assert.equal(sink(`<figure data-embed="youtube" data-id="short"></figure>`), '<figure data-embed="youtube"></figure>')
|
||||
assert.equal(sink(`<figure data-embed="vimeo" data-id="${ID}"></figure>`), `<figure data-id="${ID}"></figure>`)
|
||||
assert.equal(sink(`<figure data-embed="youtube" data-id="short"></figure>`), '<figure></figure>')
|
||||
assert.equal(sink(`<figure data-embed="vimeo" data-id="${ID}"></figure>`), '<figure></figure>')
|
||||
assert.equal(iframeCount(sink(`<figure data-embed="vimeo" data-id="${ID}"></figure>`)), 0)
|
||||
})
|
||||
|
||||
@@ -175,3 +186,121 @@ test('the iframe src is a fixed host plus the validated id, never stored text',
|
||||
assert.match(out, /loading="lazy"/)
|
||||
assert.doesNotMatch(out, /allow="[^"]*(autoplay|camera|microphone|geolocation)/)
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Phase 38: Extensible embed provider registry, pair-aware sanitizer & SSR
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test('registry supports dual registration helpers and rejects prototype-pollution keys', () => {
|
||||
const scoped = createJournalEmbedRegistry({
|
||||
viz: { idPattern: /^[a-z0-9][a-z0-9-]{0,63}$/ },
|
||||
})
|
||||
assert.equal(scoped.has('youtube'), true)
|
||||
assert.equal(scoped.has('viz'), true)
|
||||
assert.equal(scoped.match('viz', 'chart-2026'), true)
|
||||
assert.equal(scoped.match('viz', 'Chart-2026'), false)
|
||||
assert.equal(scoped.match('youtube', 'chart-2026'), false)
|
||||
|
||||
// Prototype keys never match and cannot be registered.
|
||||
for (const bad of ['__proto__', 'constructor', 'toString', 'valueOf', '../x', 'YouTube', '']) {
|
||||
assert.equal(scoped.has(bad), false, bad)
|
||||
assert.equal(scoped.get(bad), undefined, bad)
|
||||
assert.equal(scoped.match(bad, 'abc'), false, bad)
|
||||
assert.throws(() => scoped.register(bad, { idPattern: /^[a-z]+$/ }), /Invalid journal embed provider key/)
|
||||
}
|
||||
|
||||
// Global singleton helpers + reset.
|
||||
registerJournalEmbedProvider('viz', { idPattern: '^[a-z0-9-]+$' })
|
||||
defineJournalEmbedProviders({ acme: { idPattern: /^acme-[0-9]+$/ } })
|
||||
assert.equal(getJournalEmbedRegistry().has('viz'), true)
|
||||
assert.equal(getJournalEmbedRegistry().has('acme'), true)
|
||||
resetJournalEmbedRegistry()
|
||||
assert.equal(getJournalEmbedRegistry().has('viz'), false)
|
||||
assert.equal(getJournalEmbedRegistry().has('acme'), false)
|
||||
assert.equal(getJournalEmbedRegistry().has('youtube'), true)
|
||||
})
|
||||
|
||||
test('pair-aware htmlGate allows custom embed with responsive fallback img and strips mismatches/XSS', () => {
|
||||
registerJournalEmbedProvider('viz', {
|
||||
idPattern: /^[a-z0-9][a-z0-9-]{0,63}$/,
|
||||
mount: () => {},
|
||||
})
|
||||
|
||||
const valid =
|
||||
'<figure data-embed="viz" data-id="lions-mane-studies" data-aspect="16/9" data-height="420px">' +
|
||||
'<img src="/media/abc123/chart.webp" srcset="/media/abc123/chart-480w.webp 480w, /media/abc123/chart-960w.webp 960w" sizes="(max-width: 768px) 100vw, 800px" alt="Chart" width="800" height="450" />' +
|
||||
'<figcaption>Figure 1</figcaption>' +
|
||||
'</figure>'
|
||||
assert.equal(sanitizeJournalHtml(valid), valid)
|
||||
assert.equal(isSafeJournalHtml(valid), true)
|
||||
assert.equal(gateJournalHtml(valid).html, valid)
|
||||
|
||||
// Cross-provider ID mismatches strip all embed attributes.
|
||||
assert.equal(
|
||||
sanitizeJournalHtml('<figure data-embed="youtube" data-id="lions-mane-studies" data-aspect="16/9"></figure>'),
|
||||
'<figure></figure>',
|
||||
)
|
||||
assert.equal(
|
||||
sanitizeJournalHtml(`<figure data-embed="viz" data-id="${ID}" data-height="420px"></figure>`),
|
||||
'<figure></figure>',
|
||||
)
|
||||
assert.equal(isSafeJournalHtml('<figure data-embed="youtube" data-id="lions-mane-studies"></figure>'), false)
|
||||
|
||||
// Invalid data-aspect / data-height (CSS injection vectors) are stripped.
|
||||
assert.equal(
|
||||
sanitizeJournalHtml('<figure data-embed="viz" data-id="ok-id" data-aspect="16/9; background:url(javascript:alert(1))"></figure>'),
|
||||
'<figure data-embed="viz" data-id="ok-id"></figure>',
|
||||
)
|
||||
assert.equal(
|
||||
sanitizeJournalHtml('<figure data-embed="viz" data-id="ok-id" data-height="-100px"></figure>'),
|
||||
'<figure data-embed="viz" data-id="ok-id"></figure>',
|
||||
)
|
||||
|
||||
// XSS inside custom embed is stripped while safe fallback survives.
|
||||
const xss =
|
||||
'<figure data-embed="viz" data-id="ok-id" data-aspect="4/3">' +
|
||||
'<script>alert(1)</script>' +
|
||||
'<iframe src="https://evil.test"></iframe>' +
|
||||
'<svg onload="alert(1)"><circle r="1"/></svg>' +
|
||||
'<img src="/media/abc/ok.webp" alt="Safe" onerror="alert(1)">' +
|
||||
'<figcaption>Caption</figcaption>' +
|
||||
'</figure>'
|
||||
const cleaned = sanitizeJournalHtml(xss)
|
||||
assert.doesNotMatch(cleaned, /<script|<iframe|<svg|onerror|alert/i)
|
||||
assert.equal(
|
||||
cleaned,
|
||||
'<figure data-embed="viz" data-id="ok-id" data-aspect="4/3"><img src="/media/abc/ok.webp" alt="Safe" /><figcaption>Caption</figcaption></figure>',
|
||||
)
|
||||
})
|
||||
|
||||
test('expandEmbeds preserves SSR fallback + adds classes/CLS styles for client-hydrated providers and allows youtube override', () => {
|
||||
registerJournalEmbedProvider('viz', {
|
||||
idPattern: /^[a-z0-9-]+$/,
|
||||
mount: () => {},
|
||||
aspectRatio: '16/9',
|
||||
minHeight: '360px',
|
||||
})
|
||||
|
||||
const raw =
|
||||
'<figure data-embed="viz" data-id="chart-1" data-aspect="4/3">' +
|
||||
'<img src="/media/abc/chart.webp" alt="Chart" width="800" height="600">' +
|
||||
'<figcaption>Figure 1</figcaption>' +
|
||||
'</figure>'
|
||||
const expanded = expandEmbeds(sanitizeJournalHtml(raw))
|
||||
assert.match(expanded, /class="journal-embed journal-embed--viz"/)
|
||||
assert.match(expanded, /data-embed="viz"/)
|
||||
assert.match(expanded, /data-id="chart-1"/)
|
||||
assert.match(expanded, /style="aspect-ratio:4\/3;min-height:360px"/)
|
||||
assert.match(expanded, /<img src="\/media\/abc\/chart\.webp" alt="Chart" width="800" height="600" \/>/)
|
||||
assert.match(expanded, /<figcaption>Figure 1<\/figcaption>/)
|
||||
|
||||
// Built-in YouTube remains byte-identical.
|
||||
assert.equal(expandEmbeds(PLACEHOLDER), IFRAME)
|
||||
|
||||
// Overriding youtube replaces SSR rendering.
|
||||
registerJournalEmbedProvider('youtube', {
|
||||
idPattern: /^[A-Za-z0-9_-]{11}$/,
|
||||
renderSsr: (id) => `<figure class="custom-yt" data-id="${id}"></figure>`,
|
||||
})
|
||||
assert.equal(expandEmbeds(PLACEHOLDER), `<figure class="custom-yt" data-id="${ID}"></figure>`)
|
||||
})
|
||||
|
||||
@@ -247,10 +247,10 @@ test('the embed placeholder survives two sanitizer passes (payload, then sink)',
|
||||
|
||||
test('embed attributes outside the four editor rules are still stripped', () => {
|
||||
const cases: Array<[string, string, string]> = [
|
||||
['other provider', '<figure data-embed="vimeo" data-id="dQw4w9WgXcQ"></figure>', '<figure data-id="dQw4w9WgXcQ"></figure>'],
|
||||
['10-character id', '<figure data-embed="youtube" data-id="dQw4w9WgXc"></figure>', '<figure data-embed="youtube"></figure>'],
|
||||
['12-character id', '<figure data-embed="youtube" data-id="dQw4w9WgXcQQ"></figure>', '<figure data-embed="youtube"></figure>'],
|
||||
['id with a quote', '<figure data-embed="youtube" data-id="dQw4w9WgX"Q"></figure>', '<figure data-embed="youtube"></figure>'],
|
||||
['other provider', '<figure data-embed="vimeo" data-id="dQw4w9WgXcQ"></figure>', '<figure></figure>'],
|
||||
['10-character id', '<figure data-embed="youtube" data-id="dQw4w9WgXc"></figure>', '<figure></figure>'],
|
||||
['12-character id', '<figure data-embed="youtube" data-id="dQw4w9WgXcQQ"></figure>', '<figure></figure>'],
|
||||
['id with a quote', '<figure data-embed="youtube" data-id="dQw4w9WgX"Q"></figure>', '<figure></figure>'],
|
||||
['data-id on div', '<div data-embed="youtube" data-id="dQw4w9WgXcQ">x</div>', '<div>x</div>'],
|
||||
['data-id on img', '<img src="/a.jpg" data-id="dQw4w9WgXcQ" />', '<img src="/a.jpg" />'],
|
||||
['other data attribute on figure', '<figure data-embed="youtube" data-id="dQw4w9WgXcQ" data-src="https://evil.test/"></figure>', PLACEHOLDER],
|
||||
@@ -308,11 +308,11 @@ test('the four editor rules accept exactly the editor values (D-05 amended mirro
|
||||
|
||||
test('the Go policy negatives are stripped the same way here', () => {
|
||||
const cases: Array<[string, string, string]> = [
|
||||
['upper-case provider', '<figure data-embed="YouTube" data-id="dQw4w9WgXcQ"></figure>', '<figure data-id="dQw4w9WgXcQ"></figure>'],
|
||||
['provider with a suffix', '<figure data-embed="youtube2" data-id="dQw4w9WgXcQ"></figure>', '<figure data-id="dQw4w9WgXcQ"></figure>'],
|
||||
['empty id', '<figure data-embed="youtube" data-id=""></figure>', '<figure data-embed="youtube"></figure>'],
|
||||
['id with a URL', '<figure data-embed="youtube" data-id="javascript:1"></figure>', '<figure data-embed="youtube"></figure>'],
|
||||
['id with a space', '<figure data-embed="youtube" data-id="dQw4w9 gXcQ"></figure>', '<figure data-embed="youtube"></figure>'],
|
||||
['upper-case provider', '<figure data-embed="YouTube" data-id="dQw4w9WgXcQ"></figure>', '<figure></figure>'],
|
||||
['provider with a suffix', '<figure data-embed="youtube2" data-id="dQw4w9WgXcQ"></figure>', '<figure></figure>'],
|
||||
['empty id', '<figure data-embed="youtube" data-id=""></figure>', '<figure></figure>'],
|
||||
['id with a URL', '<figure data-embed="youtube" data-id="javascript:1"></figure>', '<figure></figure>'],
|
||||
['id with a space', '<figure data-embed="youtube" data-id="dQw4w9 gXcQ"></figure>', '<figure></figure>'],
|
||||
['embed attributes on p', '<p data-embed="youtube" data-id="dQw4w9WgXcQ">x</p>', '<p>x</p>'],
|
||||
['embed attributes on a', '<a href="/x" data-embed="youtube" data-id="dQw4w9WgXcQ">x</a>', '<a href="/x">x</a>'],
|
||||
['data attribute alone on figure', '<figure data-url="https://evil.test/"></figure>', '<figure></figure>'],
|
||||
@@ -374,6 +374,32 @@ test('a decorative image keeps alt=""', () => {
|
||||
assert.deepEqual(gateJournalHtml('<p><img src="/a.png" alt=""></p>'), { safe: true, html: '<p><img src="/a.png" alt="" /></p>' })
|
||||
})
|
||||
|
||||
test('inline /media/ responsive srcset, sizes, width, height, loading, and decoding survive sanitization', () => {
|
||||
const html =
|
||||
'<p><img src="/media/abc123456789/hero.jpg" srcset="/media/abc123456789/hero-480w.webp 480w, /media/abc123456789/hero-960w.webp 960w, https://cdn.acme.test/media/abc123456789/hero-1600w.webp 1600w" sizes="(max-width: 768px) 100vw, 800px" width="1600" height="900" loading="lazy" decoding="async" alt="Hero" /></p>'
|
||||
assert.equal(sanitizeJournalHtml(html), html)
|
||||
assert.deepEqual(gateJournalHtml(html), { safe: true, html })
|
||||
assert.equal(sanitizeJournalHtml(sanitizeJournalHtml(html)), html)
|
||||
})
|
||||
|
||||
test('unsafe srcset schemes and invalid img attributes are stripped', () => {
|
||||
const cases: Array<[string, string, string]> = [
|
||||
['javascript srcset', '<img src="/media/abc123456789/a.jpg" srcset="javascript:alert(1) 480w" />', '<img src="/media/abc123456789/a.jpg" />'],
|
||||
['data srcset', '<img src="/media/abc123456789/a.jpg" srcset="data:image/svg+xml;base64,PHN2Zz4= 480w" />', '<img src="/media/abc123456789/a.jpg" />'],
|
||||
['mixed safe and javascript srcset', '<img src="/media/abc123456789/a.jpg" srcset="/media/abc123456789/a-480w.webp 480w, javascript:alert(1) 960w" />', '<img src="/media/abc123456789/a.jpg" />'],
|
||||
['vbscript srcset', '<img src="/media/abc123456789/a.jpg" srcset="vbscript:msgbox(1) 480w" />', '<img src="/media/abc123456789/a.jpg" />'],
|
||||
['mailto srcset', '<img src="/media/abc123456789/a.jpg" srcset="mailto:a@b.test 480w" />', '<img src="/media/abc123456789/a.jpg" />'],
|
||||
['invalid descriptor', '<img src="/media/abc123456789/a.jpg" srcset="/media/abc123456789/a-480w.webp onload=1" />', '<img src="/media/abc123456789/a.jpg" />'],
|
||||
['unsafe sizes url()', '<img src="/media/abc123456789/a.jpg" sizes="url(https://evil.test/x)" />', '<img src="/media/abc123456789/a.jpg" />'],
|
||||
['invalid loading', '<img src="/media/abc123456789/a.jpg" loading="auto" />', '<img src="/media/abc123456789/a.jpg" />'],
|
||||
['invalid decoding', '<img src="/media/abc123456789/a.jpg" decoding="fast" />', '<img src="/media/abc123456789/a.jpg" />'],
|
||||
]
|
||||
for (const [name, html, want] of cases) {
|
||||
assert.equal(sanitizeJournalHtml(html), want, name)
|
||||
assert.equal(isSafeJournalHtml(html), false, `${name} reported safe`)
|
||||
}
|
||||
})
|
||||
|
||||
// renderJournalBody runs the UI-SPEC L7 order on the sanitized HTML.
|
||||
function recordingSteps(calls: string[]): JournalBodyLinkSteps {
|
||||
return {
|
||||
|
||||
Reference in New Issue
Block a user