diff --git a/examples/08-extensions/03-embeds-without-backend/.bnexample.json b/examples/08-extensions/03-embeds-without-backend/.bnexample.json new file mode 100644 index 0000000000..f316363d72 --- /dev/null +++ b/examples/08-extensions/03-embeds-without-backend/.bnexample.json @@ -0,0 +1,9 @@ +{ + "playground": true, + "docs": false, + "author": "", + "tags": ["Extension", "Custom Blocks"], + "dependencies": { + "@blocknote/embeds": "latest" + } +} diff --git a/examples/08-extensions/03-embeds-without-backend/README.md b/examples/08-extensions/03-embeds-without-backend/README.md new file mode 100644 index 0000000000..61727b1f2e --- /dev/null +++ b/examples/08-extensions/03-embeds-without-backend/README.md @@ -0,0 +1,7 @@ +# Embeds without a backend + +Paste a sample URL into an empty paragraph, then choose URL, Bookmark or Embed. Pasting itself only inserts an ordinary link and never fetches a preview. + +YouTube, Bluesky and the small typed custom CodePen React provider work directly after you choose Embed. The optional catch-all accepts other websites and honestly shows a source card without a resolver. No backend endpoint, provider catalog or automatic favicon service is used. Bookmarks save only the source URL unless you supply a metadata callback; saved bookmarks never resolve metadata on mount. + +Run the playground and open `/extensions/embeds-without-backend`. Compare with [the endpoint-backed example](https://playground.blocknotejs.org/extensions/embeds-with-backend). Copy buttons write plain text and focus an empty paragraph; they do not fetch or insert previews. This example does not persist documents across reloads. diff --git a/examples/08-extensions/03-embeds-without-backend/index.html b/examples/08-extensions/03-embeds-without-backend/index.html new file mode 100644 index 0000000000..e6e12ba4e6 --- /dev/null +++ b/examples/08-extensions/03-embeds-without-backend/index.html @@ -0,0 +1,17 @@ + + + + + Embeds without a backend + + + +
+ + + diff --git a/examples/08-extensions/03-embeds-without-backend/main.tsx b/examples/08-extensions/03-embeds-without-backend/main.tsx new file mode 100644 index 0000000000..1260513388 --- /dev/null +++ b/examples/08-extensions/03-embeds-without-backend/main.tsx @@ -0,0 +1,11 @@ +// AUTO-GENERATED FILE, DO NOT EDIT DIRECTLY +import React from "react"; +import { createRoot } from "react-dom/client"; +import App from "./src/App.jsx"; + +const root = createRoot(document.getElementById("root")!); +root.render( + + + , +); diff --git a/examples/08-extensions/03-embeds-without-backend/package.json b/examples/08-extensions/03-embeds-without-backend/package.json new file mode 100644 index 0000000000..fc64194232 --- /dev/null +++ b/examples/08-extensions/03-embeds-without-backend/package.json @@ -0,0 +1,31 @@ +{ + "name": "@blocknote/example-extensions-embeds-without-backend", + "description": "AUTO-GENERATED FILE, DO NOT EDIT DIRECTLY", + "type": "module", + "private": true, + "version": "0.12.4", + "scripts": { + "start": "vite", + "dev": "vite", + "build:prod": "tsc && vite build", + "preview": "vite preview" + }, + "dependencies": { + "@blocknote/ariakit": "latest", + "@blocknote/core": "latest", + "@blocknote/mantine": "latest", + "@blocknote/react": "latest", + "@blocknote/shadcn": "latest", + "@mantine/core": "^9.0.2", + "@mantine/hooks": "^9.0.2", + "react": "^19.2.3", + "react-dom": "^19.2.3", + "@blocknote/embeds": "latest" + }, + "devDependencies": { + "@types/react": "^19.2.3", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^6.0.1", + "vite": "^8.0.0" + } +} diff --git a/examples/08-extensions/03-embeds-without-backend/src/App.tsx b/examples/08-extensions/03-embeds-without-backend/src/App.tsx new file mode 100644 index 0000000000..cc9171abfb --- /dev/null +++ b/examples/08-extensions/03-embeds-without-backend/src/App.tsx @@ -0,0 +1,117 @@ +import { BlockNoteSchema } from "@blocknote/core"; +import "@blocknote/core/fonts/inter.css"; +import { + embedBlockSpecs, + withEmbeds, + PasteChoice, + createProvider, + SafeIframe, + type EmbedViewProps, +} from "@blocknote/embeds"; +import { youtubeProvider } from "@blocknote/embeds/providers/youtube"; +import { blueskyProvider } from "@blocknote/embeds/providers/bluesky"; +import { createOEmbedProvider } from "@blocknote/embeds/providers/oembed"; +import "@blocknote/embeds/style.css"; +import { BlockNoteView } from "@blocknote/mantine"; +import "@blocknote/mantine/style.css"; +import { useCreateBlockNote } from "@blocknote/react"; +import { useState } from "react"; + +const CODEPEN_URL = "https://codepen.io/team/codepen/pen/PNaGbb"; + +function CodePen({ url }: EmbedViewProps) { + const source = new URL(url); + return ( + + ); +} + +/** Custom providers are ordinary typed React components; configuration stays in the app. */ +const codepenProvider = createProvider({ + id: "codepen", + matches(url) { + return ( + url.hostname === "codepen.io" && + /^\/(?:team\/)?[\w-]+\/pen\/[\w-]+\/?$/.test(url.pathname) + ); + }, + component: CodePen, +}); + +const embeds = { + providers: [ + youtubeProvider, + blueskyProvider, + codepenProvider, + createOEmbedProvider(), + ], +}; +const schema = BlockNoteSchema.create().extend({ + blockSpecs: embedBlockSpecs, +}); +const samples = [ + ["YouTube", "https://www.youtube.com/watch?v=jNQXAC9IVRw"], + ["Bluesky", "https://bsky.app/profile/bsky.app/post/3kktuiwidw22d"], + ["CodePen", CODEPEN_URL], + ["Website", "https://www.blocknotejs.org"], +] as const; + +export default function App() { + const [notice, setNotice] = useState( + "No backend: website metadata may be unavailable. Unsupported embeds show a source link.", + ); + const editor = useCreateBlockNote( + withEmbeds({ + schema, + embeds, + }), + ); + async function copy(url: string) { + try { + await navigator.clipboard.writeText(url); + } catch { + setNotice(`Copy manually: ${url}`); + return; + } + const last = editor.document.at(-1); + if (last) { + const target = + last.type === "paragraph" && last.content.length === 0 + ? last + : editor.insertBlocks([{ type: "paragraph" }], last, "after")[0]; + editor.setTextCursorPosition(target, "end"); + } + editor.focus(); + setNotice( + "URL copied. Paste into the empty paragraph to choose URL, Bookmark or Embed.", + ); + } + return ( + <> +
+ {samples.map(([label, url]) => ( + + ))} + {notice} +
+ + + + + ); +} diff --git a/examples/08-extensions/03-embeds-without-backend/tsconfig.json b/examples/08-extensions/03-embeds-without-backend/tsconfig.json new file mode 100644 index 0000000000..2aa62c56e6 --- /dev/null +++ b/examples/08-extensions/03-embeds-without-backend/tsconfig.json @@ -0,0 +1,32 @@ +{ + "__comment": "AUTO-GENERATED FILE, DO NOT EDIT DIRECTLY", + "compilerOptions": { + "target": "ESNext", + "useDefineForClassFields": true, + "lib": ["DOM", "DOM.Iterable", "ESNext"], + "allowJs": false, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "strict": true, + "forceConsistentCasingInFileNames": true, + "module": "ESNext", + "moduleResolution": "bundler", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + "composite": true, + "paths": { + "@shared/*": ["../../../shared/*"] + } + }, + "include": ["."], + "__ADD_FOR_LOCAL_DEV_references": [ + { + "path": "../../../packages/core/" + }, + { + "path": "../../../packages/react/" + } + ] +} diff --git a/examples/08-extensions/03-embeds-without-backend/vite-env.d.ts b/examples/08-extensions/03-embeds-without-backend/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/08-extensions/03-embeds-without-backend/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/08-extensions/03-embeds-without-backend/vite.config.ts b/examples/08-extensions/03-embeds-without-backend/vite.config.ts new file mode 100644 index 0000000000..cbf6ff2ffc --- /dev/null +++ b/examples/08-extensions/03-embeds-without-backend/vite.config.ts @@ -0,0 +1,35 @@ +// AUTO-GENERATED FILE, DO NOT EDIT DIRECTLY +import react from "@vitejs/plugin-react"; +import * as fs from "fs"; +import * as path from "path"; +import { defineConfig } from "vite"; +// https://vitejs.dev/config/ +export default defineConfig(((conf: { command: string }) => ({ + plugins: [react()], + optimizeDeps: {}, + build: { + sourcemap: true, + }, + resolve: { + alias: + conf.command === "build" || + !fs.existsSync(path.resolve(__dirname, "../../../packages/core/src")) + ? {} + : ({ + // The repo-wide alias for the shared test-utils directory (private, + // so it only resolves inside the monorepo). Harmless for examples + // that don't use it. + "@shared": path.resolve(__dirname, "../../../shared/"), + // Comment out the lines below to load a built version of blocknote + // or, keep as is to load live from sources with live reload working + "@blocknote/core": path.resolve( + __dirname, + "../../../packages/core/src/", + ), + "@blocknote/react": path.resolve( + __dirname, + "../../../packages/react/src/", + ), + } as any), + }, +})) as Parameters[0]); diff --git a/examples/08-extensions/04-embeds-with-backend/.bnexample.json b/examples/08-extensions/04-embeds-with-backend/.bnexample.json new file mode 100644 index 0000000000..f316363d72 --- /dev/null +++ b/examples/08-extensions/04-embeds-with-backend/.bnexample.json @@ -0,0 +1,9 @@ +{ + "playground": true, + "docs": false, + "author": "", + "tags": ["Extension", "Custom Blocks"], + "dependencies": { + "@blocknote/embeds": "latest" + } +} diff --git a/examples/08-extensions/04-embeds-with-backend/README.md b/examples/08-extensions/04-embeds-with-backend/README.md new file mode 100644 index 0000000000..f5f16d9c70 --- /dev/null +++ b/examples/08-extensions/04-embeds-with-backend/README.md @@ -0,0 +1,11 @@ +# Embeds with a backend + +The same minimal paste-and-choose flow as [the browser-only example](https://playground.blocknotejs.org/extensions/embeds-without-backend), with a standard oEmbed endpoint for saved bookmark metadata and optional live generic previews. No request starts until Bookmark or Embed is chosen. + +Run the playground and open `/extensions/embeds-with-backend`; its existing local-development resolver is connected automatically. For a standalone app, set `VITE_OEMBED_URL=https://your-app.example/oembed` in the serving Vite application's `.env.local` and restart it. Without an endpoint, direct providers and useful URL-only fallbacks still work. + +The default client accepts raw oEmbed 1.0 JSON, including the existing `@blocknote/xl-embed-server` metadata extensions. Save bookmark metadata once through the small typed callback; mount and reload do not resolve it again. Live providers own their loading and rendering. + +An oEmbed response is untrusted data, not authorization to run HTML. Generic iframe rendering is denied unless its exact HTTPS origin is explicitly approved; same-origin application frames are always denied. Unsupported rich HTML becomes a source/metadata card. No upstream scripts or HTML are inserted. + +The existing reference server requires application-supplied protected outbound fetching: plain global fetch is not an SSRF-safe server transport. Authentication, CORS, rate limits and deployment remain application-owned. Keep secrets on the server. This example does not persist documents across reloads. diff --git a/examples/08-extensions/04-embeds-with-backend/index.html b/examples/08-extensions/04-embeds-with-backend/index.html new file mode 100644 index 0000000000..04df5f5c3c --- /dev/null +++ b/examples/08-extensions/04-embeds-with-backend/index.html @@ -0,0 +1,17 @@ + + + + + Embeds with a backend + + + +
+ + + diff --git a/examples/08-extensions/04-embeds-with-backend/main.tsx b/examples/08-extensions/04-embeds-with-backend/main.tsx new file mode 100644 index 0000000000..1260513388 --- /dev/null +++ b/examples/08-extensions/04-embeds-with-backend/main.tsx @@ -0,0 +1,11 @@ +// AUTO-GENERATED FILE, DO NOT EDIT DIRECTLY +import React from "react"; +import { createRoot } from "react-dom/client"; +import App from "./src/App.jsx"; + +const root = createRoot(document.getElementById("root")!); +root.render( + + + , +); diff --git a/examples/08-extensions/04-embeds-with-backend/package.json b/examples/08-extensions/04-embeds-with-backend/package.json new file mode 100644 index 0000000000..a5a7d082ec --- /dev/null +++ b/examples/08-extensions/04-embeds-with-backend/package.json @@ -0,0 +1,31 @@ +{ + "name": "@blocknote/example-extensions-embeds-with-backend", + "description": "AUTO-GENERATED FILE, DO NOT EDIT DIRECTLY", + "type": "module", + "private": true, + "version": "0.12.4", + "scripts": { + "start": "vite", + "dev": "vite", + "build:prod": "tsc && vite build", + "preview": "vite preview" + }, + "dependencies": { + "@blocknote/ariakit": "latest", + "@blocknote/core": "latest", + "@blocknote/mantine": "latest", + "@blocknote/react": "latest", + "@blocknote/shadcn": "latest", + "@mantine/core": "^9.0.2", + "@mantine/hooks": "^9.0.2", + "react": "^19.2.3", + "react-dom": "^19.2.3", + "@blocknote/embeds": "latest" + }, + "devDependencies": { + "@types/react": "^19.2.3", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^6.0.1", + "vite": "^8.0.0" + } +} diff --git a/examples/08-extensions/04-embeds-with-backend/src/App.tsx b/examples/08-extensions/04-embeds-with-backend/src/App.tsx new file mode 100644 index 0000000000..bd0d0038c3 --- /dev/null +++ b/examples/08-extensions/04-embeds-with-backend/src/App.tsx @@ -0,0 +1,147 @@ +import { BlockNoteSchema } from "@blocknote/core"; +import "@blocknote/core/fonts/inter.css"; +import { + embedBlockSpecs, + withEmbeds, + PasteChoice, + createProvider, + SafeIframe, + type EmbedViewProps, + type ResolveMetadata, +} from "@blocknote/embeds"; +import { + createOEmbedClient, + metadataFromOEmbed, +} from "@blocknote/embeds/oembed"; +import { youtubeProvider } from "@blocknote/embeds/providers/youtube"; +import { blueskyProvider } from "@blocknote/embeds/providers/bluesky"; +import { createOEmbedProvider } from "@blocknote/embeds/providers/oembed"; +import "@blocknote/embeds/style.css"; +import { BlockNoteView } from "@blocknote/mantine"; +import "@blocknote/mantine/style.css"; +import { useCreateBlockNote } from "@blocknote/react"; +import { useState } from "react"; + +const CODEPEN_URL = "https://codepen.io/team/codepen/pen/PNaGbb"; + +function CodePen({ url }: EmbedViewProps) { + const source = new URL(url); + return ( + + ); +} + +const codepenProvider = createProvider({ + id: "codepen", + matches(url) { + return ( + url.hostname === "codepen.io" && + /^\/(?:team\/)?[\w-]+\/pen\/[\w-]+\/?$/.test(url.pathname) + ); + }, + component: CodePen, +}); + +const configuredEndpoint: unknown = import.meta.env.VITE_OEMBED_URL; +const playgroundEndpoint: unknown = import.meta.env + .BLOCKNOTE_EMBED_DEMO_ENDPOINT; +const endpoint = [configuredEndpoint, playgroundEndpoint].find( + (value): value is string => typeof value === "string" && value.length > 0, +); +const resolve = endpoint ? createOEmbedClient({ endpoint }) : undefined; +const resolveMetadata: ResolveMetadata = async (url, options) => { + if (!resolve) { + return { status: "unavailable" }; + } + const result = await resolve(url, options); + return result.status === "success" + ? { status: "success", value: metadataFromOEmbed(result.value) } + : result; +}; +const embeds = { + providers: [ + youtubeProvider, + blueskyProvider, + codepenProvider, + createOEmbedProvider({ + resolve, + // Data from an oEmbed service is not permission to execute arbitrary iframe content. + approvedIframeOrigins: [ + "https://player.vimeo.com", + "https://www.youtube-nocookie.com", + ], + }), + ], + resolveMetadata, +}; +const schema = BlockNoteSchema.create().extend({ + blockSpecs: embedBlockSpecs, +}); +const samples = [ + ["YouTube", "https://www.youtube.com/watch?v=jNQXAC9IVRw"], + ["Bluesky", "https://bsky.app/profile/bsky.app/post/3kktuiwidw22d"], + ["CodePen", CODEPEN_URL], + ["Website", "https://www.blocknotejs.org"], +] as const; + +export default function App() { + const [notice, setNotice] = useState( + endpoint + ? "Backend connected: bookmarks save metadata; supported links show live previews." + : "No backend configured. Set VITE_OEMBED_URL; unsupported embeds show a source link.", + ); + const editor = useCreateBlockNote( + withEmbeds({ + schema, + embeds, + }), + ); + async function copy(url: string) { + try { + await navigator.clipboard.writeText(url); + } catch { + setNotice(`Copy manually: ${url}`); + return; + } + const last = editor.document.at(-1); + if (last) { + const target = + last.type === "paragraph" && last.content.length === 0 + ? last + : editor.insertBlocks([{ type: "paragraph" }], last, "after")[0]; + editor.setTextCursorPosition(target, "end"); + } + editor.focus(); + setNotice( + "URL copied. Paste into the empty paragraph to choose URL, Bookmark or Embed.", + ); + } + return ( + <> +
+ {samples.map(([label, url]) => ( + + ))} + {notice} +
+ + + + + ); +} diff --git a/examples/08-extensions/04-embeds-with-backend/tsconfig.json b/examples/08-extensions/04-embeds-with-backend/tsconfig.json new file mode 100644 index 0000000000..2aa62c56e6 --- /dev/null +++ b/examples/08-extensions/04-embeds-with-backend/tsconfig.json @@ -0,0 +1,32 @@ +{ + "__comment": "AUTO-GENERATED FILE, DO NOT EDIT DIRECTLY", + "compilerOptions": { + "target": "ESNext", + "useDefineForClassFields": true, + "lib": ["DOM", "DOM.Iterable", "ESNext"], + "allowJs": false, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "strict": true, + "forceConsistentCasingInFileNames": true, + "module": "ESNext", + "moduleResolution": "bundler", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + "composite": true, + "paths": { + "@shared/*": ["../../../shared/*"] + } + }, + "include": ["."], + "__ADD_FOR_LOCAL_DEV_references": [ + { + "path": "../../../packages/core/" + }, + { + "path": "../../../packages/react/" + } + ] +} diff --git a/examples/08-extensions/04-embeds-with-backend/vite-env.d.ts b/examples/08-extensions/04-embeds-with-backend/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/08-extensions/04-embeds-with-backend/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/08-extensions/04-embeds-with-backend/vite.config.ts b/examples/08-extensions/04-embeds-with-backend/vite.config.ts new file mode 100644 index 0000000000..cbf6ff2ffc --- /dev/null +++ b/examples/08-extensions/04-embeds-with-backend/vite.config.ts @@ -0,0 +1,35 @@ +// AUTO-GENERATED FILE, DO NOT EDIT DIRECTLY +import react from "@vitejs/plugin-react"; +import * as fs from "fs"; +import * as path from "path"; +import { defineConfig } from "vite"; +// https://vitejs.dev/config/ +export default defineConfig(((conf: { command: string }) => ({ + plugins: [react()], + optimizeDeps: {}, + build: { + sourcemap: true, + }, + resolve: { + alias: + conf.command === "build" || + !fs.existsSync(path.resolve(__dirname, "../../../packages/core/src")) + ? {} + : ({ + // The repo-wide alias for the shared test-utils directory (private, + // so it only resolves inside the monorepo). Harmless for examples + // that don't use it. + "@shared": path.resolve(__dirname, "../../../shared/"), + // Comment out the lines below to load a built version of blocknote + // or, keep as is to load live from sources with live reload working + "@blocknote/core": path.resolve( + __dirname, + "../../../packages/core/src/", + ), + "@blocknote/react": path.resolve( + __dirname, + "../../../packages/react/src/", + ), + } as any), + }, +})) as Parameters[0]); diff --git a/packages/embeds/README.md b/packages/embeds/README.md new file mode 100644 index 0000000000..0c6c8dd525 --- /dev/null +++ b/packages/embeds/README.md @@ -0,0 +1,162 @@ +# React embeds and bookmarks + +```tsx +import { BlockNoteSchema } from "@blocknote/core"; +import { BlockNoteView } from "@blocknote/mantine"; +import "@blocknote/mantine/style.css"; +import { useCreateBlockNote } from "@blocknote/react"; +import { embedBlockSpecs, withEmbeds, PasteChoice } from "@blocknote/embeds"; +import { youtubeProvider } from "@blocknote/embeds/providers/youtube"; +import { createOEmbedProvider } from "@blocknote/embeds/providers/oembed"; +import "@blocknote/embeds/style.css"; + +// Create once, outside render (or memoize for the editor lifetime). +const embeds = { providers: [youtubeProvider, createOEmbedProvider()] }; +const schema = BlockNoteSchema.create().extend({ + blockSpecs: embedBlockSpecs, +}); + +function Editor() { + const editor = useCreateBlockNote(withEmbeds({ schema, embeds })); + return ( + + + + ); +} +``` + +Paste one HTTP(S) URL into an empty paragraph: it remains an ordinary link until the user chooses Bookmark or Embed. Single-entry URI lists and HTML-only single links/URL text are also supported; rich, proprietary, multiple-content and file payloads delegate. No preview request, remote image, iframe or provider component is started by the choice menu itself. + +`withEmbeds` appends the configured extension, preserves other editor options and removes its `embeds` configuration field. Extend your schema explicitly as above; it must contain the ordinary paragraph, text and link types. Supply an application `pasteHandler` alongside `schema`/`embeds` to compose it: noncandidate pastes return that handler's result unchanged, including `false` or `undefined`. The default handler runs only when no application handler exists; a custom handler can call its typed `defaultPasteHandler` itself. + +### Programmatic actions + +```tsx +import { EmbedExtension } from "@blocknote/embeds"; + +const embeds = editor.getExtension(EmbedExtension); +if (embeds) { + embeds.insertEmbed("https://www.youtube.com/watch?v=jNQXAC9IVRw"); + const outcome = await embeds.insertBookmark( + "https://example.org", + targetBlockId, + ); + if (outcome.status === "url-only") { + // Saved a useful bookmark without metadata. + } + embeds.insertUrl("https://example.org", targetBlockId); +} +``` + +Actions replace the specified block (or the cursor block captured at invocation), preserving its ID and children. They do not require `PasteChoice`. Outcomes use `status`: `converted`, `url-only`, `unchanged`, `unavailable` (invalid source, missing target/provider or read-only), or `cancelled` (stale bookmark work). Unexpected callback errors reject rather than becoming document text. **Only one bookmark request is active per editor**: every representation action supersedes it, even when the chosen representation is already visible. Moving the caret or dismissing the chooser alone does not cancel it; editing/deleting the target subtree, history changes to that target, read-only transitions and editor unmount do. + +Bookmarks resolve once through the optional typed `resolveMetadata(url, {signal})` callback, save scalar title/description/image URL props and never resolve on mount. Return `{status: "success", value: metadata}` or `{status: "unavailable"}`; expected failures still create URL-only bookmarks. Unexpected exceptions propagate. Superseded, edited, deleted, unmounted and read-only targets cannot receive a late result. + +Embeds save only `originalUrl` and `providerId`. Providers are opt-in and first-match-wins; place a catch-all last. A custom provider is `{id, matches(url: URL), component: ReactComponent}`. Its component receives `{url: string}` and owns asynchronous work and custom controls. Keep registration stable for the editor lifetime. + +Use `createProvider` for inferred matcher/render props and a preserved literal ID: + +```tsx +import { createProvider } from "@blocknote/embeds"; + +const exampleProvider = createProvider({ + id: "example", + matches(url) { + return url.hostname === "example.com"; + }, + component({ url }) { + return Custom example preview; + }, +}); +``` + +Register it in `withEmbeds({ schema, embeds: { providers: [exampleProvider] } })`. Rendering stays +entirely in your application; the helper adds no fetching or persisted settings. + +Optional entrypoints: + +- `providers/youtube`: `youtubeProvider` +- `providers/bluesky`: `blueskyProvider` +- `providers/oembed`: `createOEmbedProvider({resolve?, approvedIframeOrigins?})` +- `oembed`: `createOEmbedClient({endpoint})`, `metadataFromOEmbed`, and standard oEmbed types + +Without a resolver the catch-all deliberately shows a useful source card. The optional endpoint client accepts raw standard oEmbed JSON, including `xl-embed-server` metadata extensions. An application can adapt its result to bookmark metadata in a few lines; see the endpoint-backed example. + +Live-provider resolvers return `{status: "unavailable"}` for expected failures. Unexpected throws/rejections are rethrown during React rendering so an application error boundary can handle them; they are not turned into unavailable previews or displayed as exception messages. Rejections after cancellation are ignored. + +**oEmbed data does not authorize execution.** Generic iframe rendering is denied by default. Approve exact HTTPS origins explicitly; application-origin iframes and `srcdoc` are denied even then. No upstream HTML/scripts or attributes are inserted. Photos and metadata use validated HTTP(S) resource URLs. Stored remote images can still load when a saved bookmark is displayed. + +`SafeIframe` is available to app-owned providers. It accepts a trusted provider URL (not upstream HTML); resize messages require both exact origin and matching iframe window before a provider-specific decoder runs. All static HTML exports are resource-free original source links. + +## DOCX, PDF, Typst, ODT and email mappings + +Like `@blocknote/math-block`, embeds provides **opt-in mappings**, not automatic exporter registration. Keep the same extended editor schema and add the two mappings to the exporter's `blockMapping`: + +```ts +import { + DOCXExporter, + docxDefaultSchemaMappings, +} from "@blocknote/xl-docx-exporter"; +import { + bookmarkBlockMapping, + embedBlockMapping, +} from "@blocknote/embeds/docx-exporter"; + +const exporter = new DOCXExporter(schema, { + ...docxDefaultSchemaMappings, + blockMapping: { + ...docxDefaultSchemaMappings.blockMapping, + bookmark: bookmarkBlockMapping, + embed: embedBlockMapping, + }, +}); +const document = await exporter.toDocxJsDocument(editor.document); +``` + +Each format entrypoint exports those same two mapping names. Compose with the corresponding defaults, including any other custom block mappings, exactly as for math blocks: + +| Embeds import | Exporter | Defaults | +| ---------------------------------- | -------------------------------------------------------------------- | --------------------------------- | +| `@blocknote/embeds/docx-exporter` | `DOCXExporter` from `@blocknote/xl-docx-exporter` | `docxDefaultSchemaMappings` | +| `@blocknote/embeds/odt-exporter` | `ODTExporter` from `@blocknote/xl-odt-exporter` | `odtDefaultSchemaMappings` | +| `@blocknote/embeds/email-exporter` | `ReactEmailExporter` from `@blocknote/xl-email-exporter` | `reactEmailDefaultSchemaMappings` | +| `@blocknote/embeds/typst-exporter` | `TypstExporter` from `@blocknote/xl-typst-exporter` | `typstDefaultSchemaMappings` | +| `@blocknote/embeds/typst-exporter` | **Current** `PDFExporter` from `@blocknote/xl-pdf-exporter` | `typstDefaultSchemaMappings` | +| `@blocknote/embeds/pdf-exporter` | **Legacy** `PDFExporter` from `@blocknote/xl-pdf-exporter/react-pdf` | `pdfDefaultSchemaMappings` | + +For example, current PDF uses the **same Typst mappings**, not the legacy React-PDF mappings: + +```ts +import { + PDFExporter, + typstDefaultSchemaMappings, +} from "@blocknote/xl-pdf-exporter"; +import { + bookmarkBlockMapping, + embedBlockMapping, +} from "@blocknote/embeds/typst-exporter"; + +const exporter = new PDFExporter(schema, { + ...typstDefaultSchemaMappings, + blockMapping: { + ...typstDefaultSchemaMappings.blockMapping, + bookmark: bookmarkBlockMapping, + embed: embedBlockMapping, + }, +}); +const result = await exporter.toPDF(editor.document, { + title: "My document", + lang: "en", +}); +``` + +Use `@blocknote/embeds/pdf-exporter` **only** for the deprecated `@blocknote/xl-pdf-exporter/react-pdf` consumer. It returns native React-PDF elements and is not compatible with the current Typst-backed PDF mappings. + +Bookmarks export their persisted title and description plus a readable original URL; a title equal to the URL is not repeated. Live embeds export their original URL regardless of whether their provider is still registered. HTTP(S) sources are native clickable links; invalid imported sources remain escaped, inactive text. Empty sources have an inert fallback label. Block children remain the exporter's responsibility and are not duplicated by these mappings. + +These mappings are deliberately **text-only and network-independent**: no provider rendering, iframe screenshots, metadata resolution or stored `imageUrl` thumbnail downloads. They do not bypass the exporter's image policy by reusing remote editor images. The exporter engine's own fonts/WASM/assets remain governed by that engine's options. + +Install only the exporter/runtime dependencies for the format you use (for example `docx` with DOCX, `@react-email/components` with email, `@react-pdf/renderer` with legacy PDF). They are optional peers, isolated behind their format entrypoints; importing the editor, a provider, or another format does not import these mappings or runtimes. Nothing is added to any exporter's default schema. + +Checks: `vp run test`, `vp run lint`, `vp run build`. Browser tests run only through the repository's focused Docker suite with retries disabled. diff --git a/packages/embeds/package.json b/packages/embeds/package.json new file mode 100644 index 0000000000..e63bd4f20f --- /dev/null +++ b/packages/embeds/package.json @@ -0,0 +1,128 @@ +{ + "name": "@blocknote/embeds", + "version": "0.57.0", + "type": "module", + "license": "MPL-2.0", + "description": "Opt-in React bookmarks and live embeds for BlockNote.", + "sideEffects": [ + "*.css" + ], + "files": [ + "dist", + "types", + "src", + "!**/*.test.*" + ], + "source": "src/index.ts", + "main": "./dist/blocknote-embeds.js", + "module": "./dist/blocknote-embeds.js", + "types": "./types/src/index.d.ts", + "exports": { + ".": { + "types": "./types/src/index.d.ts", + "import": "./dist/blocknote-embeds.js" + }, + "./oembed": { + "types": "./types/src/oembed.d.ts", + "import": "./dist/oembed.js" + }, + "./providers/youtube": { + "types": "./types/src/providers/youtube.d.ts", + "import": "./dist/providers/youtube.js" + }, + "./providers/bluesky": { + "types": "./types/src/providers/bluesky.d.ts", + "import": "./dist/providers/bluesky.js" + }, + "./providers/oembed": { + "types": "./types/src/providers/oembed.d.ts", + "import": "./dist/providers/oembed.js" + }, + "./style.css": "./src/style.css", + "./docx-exporter": { + "types": "./types/src/docx-exporter/index.d.ts", + "import": "./dist/docx-exporter.js" + }, + "./typst-exporter": { + "types": "./types/src/typst-exporter/index.d.ts", + "import": "./dist/typst-exporter.js" + }, + "./odt-exporter": { + "types": "./types/src/odt-exporter/index.d.ts", + "import": "./dist/odt-exporter.js" + }, + "./email-exporter": { + "types": "./types/src/email-exporter/index.d.ts", + "import": "./dist/email-exporter.js" + }, + "./pdf-exporter": { + "types": "./types/src/pdf-exporter/index.d.ts", + "import": "./dist/pdf-exporter.js" + } + }, + "scripts": { + "test": "vp test --run", + "lint": "vp lint --type-aware src", + "format": "vp fmt src vite.config.ts package.json tsconfig.json" + }, + "dependencies": { + "@floating-ui/react": "^0.27.18", + "@blocknote/core": "workspace:^", + "@blocknote/react": "workspace:^" + }, + "peerDependencies": { + "react": "^18.0 || ^19.0 || >=19.0.0-rc", + "react-dom": "^18.0 || ^19.0 || >=19.0.0-rc", + "docx": "^9.8.0", + "@blocknote/xl-typst-exporter": "workspace:^", + "@react-pdf/renderer": "^4.5.1", + "@react-email/components": "^1.0.12", + "@blocknote/xl-docx-exporter": "workspace:^", + "@blocknote/xl-odt-exporter": "workspace:^", + "@blocknote/xl-email-exporter": "workspace:^", + "@blocknote/xl-pdf-exporter": "workspace:^" + }, + "peerDependenciesMeta": { + "docx": { + "optional": true + }, + "@blocknote/xl-typst-exporter": { + "optional": true + }, + "@react-pdf/renderer": { + "optional": true + }, + "@react-email/components": { + "optional": true + }, + "@blocknote/xl-docx-exporter": { + "optional": true + }, + "@blocknote/xl-odt-exporter": { + "optional": true + }, + "@blocknote/xl-email-exporter": { + "optional": true + }, + "@blocknote/xl-pdf-exporter": { + "optional": true + } + }, + "devDependencies": { + "@blocknote/mantine": "workspace:^", + "@types/react": "^19.2.3", + "@types/react-dom": "^19.2.3", + "react": "^19.2.5", + "react-dom": "^19.2.5", + "vite-plus": "catalog:", + "docx": "^9.9.0", + "@react-email/components": "^1.0.12", + "@react-pdf/renderer": "^4.5.1", + "@blocknote/xl-docx-exporter": "workspace:^", + "@blocknote/xl-typst-exporter": "workspace:^", + "@blocknote/xl-pdf-exporter": "workspace:^", + "@blocknote/xl-odt-exporter": "workspace:^", + "@blocknote/xl-email-exporter": "workspace:^", + "@zip.js/zip.js": "^2.8.8" + } +} diff --git a/packages/embeds/src/EmbedExtension.ts b/packages/embeds/src/EmbedExtension.ts new file mode 100644 index 0000000000..6f3d53a51c --- /dev/null +++ b/packages/embeds/src/EmbedExtension.ts @@ -0,0 +1,146 @@ +import { + createExtension, + createStore, + type BlockNoteEditor, +} from "@blocknote/core"; +import { clipboardUrl } from "./clipboard.js"; +import { createEmbedActions } from "./embedActions.js"; +import { blockNode, type EmbedState } from "./embedState.js"; +import type { EmbedsBlockSchema, EmbedsOptions } from "./types.js"; + +/** One configured instance coordinates paste state and the conversion owner's lifetime. */ +export const EmbedExtension = createExtension( + ({ + editor, + options, + }: { + editor: BlockNoteEditor; + options: EmbedsOptions & { isValidLink?: (href: string) => boolean }; + }) => { + const ids = new Set(); + for (const provider of options.providers) { + if (!provider.id || ids.has(provider.id)) { + throw new Error("Embed provider IDs must be nonempty and unique"); + } + ids.add(provider.id); + } + const store = createStore({}); + const actions = createEmbedActions(editor, options, store); + function dismissPaste() { + store.setState({ ...store.state, candidate: undefined }); + } + function handlePaste({ event }: { event: ClipboardEvent }): boolean { + dismissPaste(); + const data = event.clipboardData; + const { block } = editor.getTextCursorPosition(); + const eligible = + data !== null && + data.files.length === 0 && + data.types.every( + (type) => + type !== "blocknote/html" && + type !== "vscode-editor-data" && + type !== "Files", + ) && + editor.isEditable && + editor.prosemirrorState.selection.empty && + block.type === "paragraph" && + block.content.length === 0; + if (!eligible) { + return false; + } + const url = clipboardUrl(data); + if (url && (options.isValidLink?.(url) ?? true)) { + const before = editor.getBlock(block.id); + if (!before) { + return false; + } + const content = [ + { + type: "link" as const, + href: url, + content: [{ type: "text" as const, text: url, styles: {} }], + }, + ]; + const expected = JSON.stringify({ ...before, content }); + editor.insertInlineContent(content, { updateSelection: true }); + const node = blockNode(editor.prosemirrorState.doc, block.id); + if ( + node && + editor.isEditable && + JSON.stringify(editor.getBlock(block.id)) === expected && + editor.prosemirrorState.selection.empty && + editor.getTextCursorPosition().block.id === block.id + ) { + store.setState({ + ...store.state, + candidate: { + blockId: block.id, + url, + node, + selection: editor.prosemirrorState.selection.from, + }, + }); + } + return true; + } + return false; + } + return { + key: "embeds", + options, + store, + insertBookmark: actions.insertBookmark, + insertEmbed: actions.insertEmbed, + insertUrl: actions.insertUrl, + handlePaste, + dismissPaste, + mount({ signal }) { + let traversing = false; + const unsubscribe = editor.onBeforeChange(({ tr }) => { + if (signal.aborted) { + return; + } + traversing = true; + try { + const candidate = store.state.candidate; + if ( + candidate && + (!editor.isEditable || + !tr.selection.empty || + tr.selection.from !== candidate.selection || + (tr.docChanged && + !blockNode(tr.doc, candidate.blockId)?.eq(candidate.node))) + ) { + dismissPaste(); + } + const pending = actions.pending; + if ( + pending && + (!editor.isEditable || + (tr.docChanged && + !blockNode(tr.doc, pending.blockId)?.eq(pending.node))) + ) { + pending.controller.abort(); + } + } finally { + traversing = false; + } + }); + signal.addEventListener( + "abort", + () => { + actions.pending?.controller.abort(); + dismissPaste(); + if (traversing) { + queueMicrotask(unsubscribe); + } else { + unsubscribe(); + } + }, + { once: true }, + ); + }, + }; + }, +); diff --git a/packages/embeds/src/SafeIframe.tsx b/packages/embeds/src/SafeIframe.tsx new file mode 100644 index 0000000000..5ee8904ce5 --- /dev/null +++ b/packages/embeds/src/SafeIframe.tsx @@ -0,0 +1,81 @@ +import { useCallback, useRef, useState } from "react"; +import { parseSourceUrl } from "./url.js"; + +export type SafeIframeProps = { + src: string; + title: string; + aspectRatio?: number; + allow?: string; + referrerPolicy?: "no-referrer" | "strict-origin-when-cross-origin"; + /** Provider-specific message format. Origin and window are checked before decoding. */ + decodeHeight?: (data: unknown) => number | undefined; +}; + +/** Fresh iframe only: no upstream HTML, srcDoc, arbitrary attributes or wildcard messaging. */ +export function SafeIframe({ + src, + title, + aspectRatio = 16 / 9, + allow, + referrerPolicy = "no-referrer", + decodeHeight, +}: SafeIframeProps) { + const attachment = useRef(undefined); + const [height, setHeight] = useState(); + const url = parseSourceUrl(src); + const origin = url?.origin; + const attach = useCallback( + (node: HTMLIFrameElement | null): void => { + attachment.current?.abort(); + attachment.current = undefined; + if (!node || !origin || !decodeHeight) { + return; + } + const controller = new AbortController(); + attachment.current = controller; + node.ownerDocument.defaultView?.addEventListener( + "message", + (event: MessageEvent) => { + if ( + event.origin !== origin || + !node.contentWindow || + event.source !== node.contentWindow + ) { + return; + } + const value = decodeHeight(event.data); + if ( + typeof value === "number" && + Number.isFinite(value) && + value > 0 + ) { + setHeight(Math.min(2000, Math.max(100, value))); + } + }, + { signal: controller.signal }, + ); + }, + [origin, decodeHeight], + ); + if ( + !url || + url.protocol !== "https:" || + (typeof window !== "undefined" && url.origin === window.location.origin) + ) { + return null; + } + return ( + `, + }, + }), + }); + const { extension } = await mount({ providers: [provider] }); + extension.insertEmbed(URL); + if (kind === "approved") { + await expect.element(page.getByTitle("Safe title")).toBeInTheDocument(); + const frame = document.querySelector("iframe"); + expect(frame?.getAttribute("src")).toBe(src); + expect(frame?.getAttribute("sandbox")).toBe( + "allow-scripts allow-same-origin allow-presentation allow-popups", + ); + expect(frame?.hasAttribute("onload")).toBe(false); + expect(frame?.hasAttribute("srcdoc")).toBe(false); + } else { + await expect + .element(page.getByRole("link", { name: "Safe title" })) + .toBeVisible(); + expect(document.querySelector("iframe")).toBeNull(); + } + expect("__untrusted" in window).toBe(false); + }); + it("aborts stale live-provider loads and never renders their late result", async () => { + const first = deferred(); + const second = deferred(); + const resolve = vi.fn((url: string, options: { signal: AbortSignal }) => + url === URL ? first.resolve(url, options) : second.resolve(url, options), + ); + const { extension } = await mount({ + providers: [createOEmbedProvider({ resolve })], + }); + extension.insertEmbed(URL); + await vi.waitFor(() => expect(first.resolve).toHaveBeenCalledTimes(1)); + extension.insertEmbed("https://other.example"); + await vi.waitFor(() => expect(second.resolve).toHaveBeenCalledTimes(1)); + expect(first.resolve.mock.calls[0][1].signal.aborted).toBe(true); + second.finish({ + status: "success", + value: { version: "1.0", type: "link", title: "Newest" }, + }); + await expect + .element(page.getByRole("link", { name: "Newest" })) + .toBeVisible(); + first.finish({ + status: "success", + value: { version: "1.0", type: "link", title: "Stale" }, + }); + await expect + .element(page.getByRole("link", { name: "Stale" })) + .not.toBeInTheDocument(); + extension.insertEmbed(URL); + await vi.waitFor(() => expect(first.resolve).toHaveBeenCalledTimes(2)); + root?.unmount(); + root = undefined; + expect(first.resolve.mock.calls[1][1].signal.aborted).toBe(true); + }); + it("authenticates real iframe messages before decoding, clamps heights and detaches replaced nodes", async () => { + host = document.createElement("div"); + document.body.append(host); + root = createRoot(host); + const decodeHeight = vi.fn((data: unknown) => + typeof data === "number" ? data : undefined, + ); + function render(key: string) { + root?.render( + , + ); + } + function send(source: Window | null, origin: string, data: number) { + const event = new MessageEvent("message", { origin, data }); + // Some engines reject detached/navigated WindowProxy values in the + // constructor. Keep the actual DOM window identity, not a fake window. + Object.defineProperty(event, "source", { value: source }); + window.dispatchEvent(event); + } + render("first"); + await expect.element(page.getByTitle("Resize fixture")).toBeInTheDocument(); + const frame = document.querySelector("iframe"); + if (!frame?.contentWindow) { + throw new Error("No frame window"); + } + const source = frame.contentWindow; + send(frame.contentWindow, "https://evil.example", 999); + send(window, "https://player.example", 999); + expect(decodeHeight).not.toHaveBeenCalled(); + send(frame.contentWindow, "https://player.example", 9000); + await vi.waitFor(() => expect(frame.style.height).toBe("2000px")); + send(frame.contentWindow, "https://player.example", NaN); + expect(frame.style.height).toBe("2000px"); + render("replacement"); + await vi.waitFor(() => + expect(document.querySelector("iframe")).not.toBe(frame), + ); + const replacement = document.querySelector("iframe"); + if (!replacement?.contentWindow) { + throw new Error("No replacement window"); + } + decodeHeight.mockClear(); + send(source, "https://player.example", 400); + expect(decodeHeight).not.toHaveBeenCalled(); + send(replacement.contentWindow, "https://player.example", 1); + await vi.waitFor(() => expect(replacement.style.height).toBe("100px")); + root?.unmount(); + root = undefined; + decodeHeight.mockClear(); + send(source, "https://player.example", 500); + expect(decodeHeight).not.toHaveBeenCalled(); + }); + it("keeps Bluesky aligned with runtime editor theme and transparent light canvas without reloading data", async () => { + const fetch = vi.fn(async () => + Response.json({ did: "did:plc:ewvi7nxzyoun6zhxrhs64oiz" }), + ); + vi.stubGlobal("fetch", fetch); + const { editor, extension, render } = await mount( + { providers: [blueskyProvider] }, + { theme: "dark" }, + ); + extension.insertEmbed( + "https://bsky.app/profile/bsky.app/post/3kktuiwidw22d", + ); + for (const theme of ["dark", "light", "dark"] as const) { + render(theme); + await vi.waitFor(() => { + const frame = document.querySelector( + 'iframe[title="Bluesky post"]', + ); + if (!frame) { + throw new Error("Missing Bluesky frame"); + } + expect( + new globalThis.URL(frame.src).searchParams.get("colorMode"), + ).toBe(theme); + expect(getComputedStyle(frame).colorScheme).toBe("light"); + expect(getComputedStyle(frame).backgroundColor).toBe( + "rgba(0, 0, 0, 0)", + ); + }); + } + expect(fetch).toHaveBeenCalledTimes(1); + expect(editor.getBlock("target")?.props).toEqual({ + originalUrl: "https://bsky.app/profile/bsky.app/post/3kktuiwidw22d", + providerId: "bluesky", + }); + }); +}); + +describe("PR3349 client review regressions", () => { + it("delegates HTML URLs separated by a br instead of merging their text", async () => { + const caller = vi.fn>(({ editor }) => { + editor.insertInlineContent("Caller kept both URLs"); + return true; + }); + const { editor } = await mount({ providers: [] }, { pasteHandler: caller }); + paste(editor, { + "text/html": "https://one.example/
https://two.example/", + }); + expect(caller).toHaveBeenCalledTimes(1); + expect(editor.getBlock("target")?.content).toEqual([ + { type: "text", text: "Caller kept both URLs", styles: {} }, + ]); + await expect + .element(page.getByRole("combobox", { name: "Paste as" })) + .not.toBeInTheDocument(); + }); + it("omits unavailable Embed options and keeps rendered and keyboard choices aligned", async () => { + const { editor } = await mount({ providers: [] }); + paste(editor, URL); + await expect.element(choice("Bookmark")).toBeVisible(); + await expect.element(choice("Embed")).not.toBeInTheDocument(); + await userEvent.keyboard("{End}{Enter}"); + await vi.waitFor(() => + expect(editor.getBlock("target")?.type).toBe("bookmark"), + ); + }); + it("honors configured link validation before inserting or offering paste choices", async () => { + const isValidLink = vi.fn(() => false); + const { editor } = await mount( + { providers: [] }, + { links: { isValidLink } }, + ); + paste(editor, URL); + expect(isValidLink).toHaveBeenCalledWith(URL); + expect(editor.getBlock("target")?.content).toEqual([ + { type: "text", text: URL, styles: {} }, + ]); + await expect + .element(page.getByRole("combobox", { name: "Paste as" })) + .not.toBeInTheDocument(); + }); + it.each(["direct", "resolved"] as const)( + "accepts supported did:web identities via the %s path", + async (mode) => { + const did = "did:web:user.example.com"; + const fetch = vi.fn(async () => Response.json({ did })); + vi.stubGlobal("fetch", fetch); + const { extension } = await mount({ providers: [blueskyProvider] }); + extension.insertEmbed( + `https://bsky.app/profile/${mode === "direct" ? did : "user.example.com"}/post/3kktuiwidw22d`, + ); + await vi.waitFor(() => + expect( + document.querySelector('iframe[title="Bluesky post"]'), + ).not.toBeNull(), + ); + expect(document.querySelector("iframe")?.getAttribute("src")).toBe( + `https://embed.bsky.app/embed/${did}/app.bsky.feed.post/3kktuiwidw22d?colorMode=light`, + ); + expect(fetch).toHaveBeenCalledTimes(mode === "direct" ? 0 : 1); + }, + ); + it.each([ + "did:web:-bad.example.com", + "did:web:user.example.com:path", + "did:other:user.example.com", + "did:plc:abc123", + ])("rejects malformed or unsupported resolved identity %s", async (did) => { + vi.stubGlobal( + "fetch", + vi.fn(async () => Response.json({ did })), + ); + const { extension } = await mount({ providers: [blueskyProvider] }); + extension.insertEmbed( + "https://bsky.app/profile/user.example.com/post/3kktuiwidw22d", + ); + await vi.waitFor(() => + expect(host?.textContent).toContain("Preview unavailable"), + ); + expect(document.querySelector("iframe")).toBeNull(); + }); + it("rejects ambiguous sources at both iframe sinks despite base-less approval looking cross-origin", async () => { + const ambiguous = "https:player.example/video"; + expect(new globalThis.URL(ambiguous).origin).toBe("https://player.example"); + const doc = document.implementation.createHTMLDocument(); + const base = doc.createElement("base"); + base.href = "https://app.example/editor/"; + doc.head.append(base); + const nativeFrame = doc.createElement("iframe"); + nativeFrame.setAttribute("src", ambiguous); + expect(nativeFrame.src).toBe( + "https://app.example/editor/player.example/video", + ); + const { extension } = await mount({ + providers: [ + createOEmbedProvider({ + approvedIframeOrigins: ["https://player.example"], + resolve: async () => ({ + status: "success", + value: { + type: "rich", + version: "1.0", + width: 640, + height: 480, + title: "Ambiguous frame", + html: ``, + }, + }), + }), + ], + }); + extension.insertEmbed(URL); + await vi.waitFor(() => + expect(host?.querySelector("a")?.textContent).toBe("Ambiguous frame"), + ); + expect(host?.querySelector("iframe")).toBeNull(); + root?.render(); + await vi.waitFor(() => + expect(host?.querySelector(".bn-editor")).toBeNull(), + ); + expect(host?.querySelector("iframe")).toBeNull(); + }); + it.each(["reject", "throw"] as const)( + "surfaces unexpected resolver %s through the app error boundary, without displaying its message", + async (mode) => { + const error = new Error("Private resolver internals"); + const onError = vi.fn(); + const request = deferred(); + const resolve = + mode === "throw" + ? () => { + throw error; + } + : request.resolve; + const { extension } = await mount( + { providers: [createOEmbedProvider({ resolve })] }, + { onError }, + ); + extension.insertEmbed(URL); + if (mode === "reject") { + await vi.waitFor(() => + expect(request.resolve).toHaveBeenCalledTimes(1), + ); + request.fail(error); + } + await vi.waitFor(() => + expect(host?.querySelector('[role="alert"]')?.textContent).toBe( + "Embed rendering failed.", + ), + ); + expect(onError).toHaveBeenCalledWith(error); + expect(host?.textContent).not.toContain(error.message); + expect(host?.textContent).not.toContain("Preview unavailable"); + }, + ); + it.each(["supersession", "unmount"] as const)( + "ignores resolver rejection after %s without an unhandled rejection", + async (reason) => { + const first = deferred(); + const second = deferred(); + const onError = vi.fn(); + const resolve = (url: string, options: { signal: AbortSignal }) => + url === URL + ? first.resolve(url, options) + : second.resolve(url, options); + const { extension } = await mount( + { providers: [createOEmbedProvider({ resolve })] }, + { onError }, + ); + extension.insertEmbed(URL); + await vi.waitFor(() => expect(first.resolve).toHaveBeenCalledTimes(1)); + if (reason === "unmount") { + root?.unmount(); + root = undefined; + expect(first.resolve.mock.calls[0][1].signal.aborted).toBe(true); + first.fail(new DOMException("Aborted", "AbortError")); + await vi.waitFor(() => + expect(host?.querySelector(".bn-editor")).toBeNull(), + ); + expect(onError).not.toHaveBeenCalled(); + return; + } + extension.insertEmbed("https://other.example"); + await vi.waitFor(() => expect(second.resolve).toHaveBeenCalledTimes(1)); + expect(first.resolve.mock.calls[0][1].signal.aborted).toBe(true); + first.fail(new DOMException("Aborted", "AbortError")); + second.finish({ + status: "success", + value: { version: "1.0", type: "link", title: "Current preview" }, + }); + await expect + .element(page.getByRole("link", { name: "Current preview" })) + .toBeVisible(); + expect(onError).not.toHaveBeenCalled(); + }, + ); +}); diff --git a/packages/embeds/src/exporters/exporters.test.tsx b/packages/embeds/src/exporters/exporters.test.tsx new file mode 100644 index 0000000000..64d4197295 --- /dev/null +++ b/packages/embeds/src/exporters/exporters.test.tsx @@ -0,0 +1,376 @@ +import { BlockNoteSchema, createBlockSpec, type Block } from "@blocknote/core"; +import { + DOCXExporter, + docxDefaultSchemaMappings, +} from "@blocknote/xl-docx-exporter"; +import { + ODTExporter, + odtDefaultSchemaMappings, +} from "@blocknote/xl-odt-exporter"; +import { + ReactEmailExporter, + reactEmailDefaultSchemaMappings, +} from "@blocknote/xl-email-exporter"; +import { + TypstExporter, + typstDefaultSchemaMappings, +} from "@blocknote/xl-typst-exporter"; +import { PDFExporter } from "@blocknote/xl-pdf-exporter"; +import { + PDFExporter as LegacyPDFExporter, + pdfDefaultSchemaMappings, +} from "@blocknote/xl-pdf-exporter/react-pdf"; +import { Document as WordDocument, Packer, Paragraph } from "docx"; +import { Document, Page, Text, renderToBuffer } from "@react-pdf/renderer"; +import { BlobReader, TextWriter, ZipReader } from "@zip.js/zip.js"; +import { createElement } from "react"; +import { readFileSync } from "node:fs"; +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; +import { embedBlockSpecs } from "../embedBlockSpecs.js"; +import * as docx from "../docx-exporter/index.js"; +import * as odt from "../odt-exporter/index.js"; +import * as email from "../email-exporter/index.js"; +import * as typst from "../typst-exporter/index.js"; +import * as legacyPDF from "../pdf-exporter/index.js"; + +// Real custom schema composition: no untyped fixture casts or fake editor ports. +const schema = BlockNoteSchema.create().extend({ + blockSpecs: { + ...embedBlockSpecs, + custom: createBlockSpec( + { type: "custom", propSchema: {}, content: "none" }, + { + render() { + throw new Error("Editor rendering must not run during export"); + }, + }, + )(), + }, +}); +type DocumentBlock = Block< + typeof schema.blockSchema, + typeof schema.inlineContentSchema, + typeof schema.styleSchema +>; +const source = "https://EXAMPLE.org/article?x=1&y=%22quoted%22#part"; +const title = 'Saved & "quotes" [#panic()]'; +const description = 'Description <script> & "literal"'; +const child: DocumentBlock = { + id: "child", + type: "custom", + props: {}, + content: undefined, + children: [], +}; +const blocks: DocumentBlock[] = [ + { + id: "bookmark", + type: "bookmark", + props: { + originalUrl: source, + title, + description, + imageUrl: "https://images.example/thumbnail.png", + }, + content: undefined, + children: [child], + }, + { + id: "embed", + type: "embed", + props: { + originalUrl: "https://video.example/watch?a=1&b=2", + providerId: "not-registered", + }, + content: undefined, + children: [], + }, + { + id: "fallback", + type: "bookmark", + props: { + originalUrl: "https://plain.example", + title: "", + description: "", + imageUrl: "", + }, + content: undefined, + children: [], + }, + { + id: "unsafe-bookmark", + type: "bookmark", + props: { + originalUrl: "javascript:alert(1)", + title: "Unsafe source <saved>", + description: "Still saved", + imageUrl: "https://images.example/other.png", + }, + content: undefined, + children: [], + }, + { + id: "unsafe-embed", + type: "embed", + props: { originalUrl: "https:ambiguous.example", providerId: "anything" }, + content: undefined, + children: [], + }, + { + id: "empty-embed", + type: "embed", + props: { originalUrl: "", providerId: "" }, + content: undefined, + children: [], + }, +]; + +async function zipText(blob: Blob, name: string) { + const zip = new ZipReader(new BlobReader(blob)); + try { + const entry = (await zip.getEntries()).find( + (entry) => entry.filename === name, + ); + if (!entry || entry.directory) { + throw new Error(`Missing ZIP entry ${name}`); + } + return await entry.getData(new TextWriter()); + } finally { + await zip.close(); + } +} + +// ODT font embedding is the engine's separate policy, not a mapping behavior. +// Suppress only that unrelated local-asset step to assert truly fetch-free mappings. +class TextOnlyODTExporter extends ODTExporter< + typeof schema.blockSchema, + typeof schema.styleSchema, + typeof schema.inlineContentSchema +> { + protected override async loadFonts() { + return []; + } +} + +afterEach(() => vi.unstubAllGlobals()); + +describe("opt-in embeds exporter mappings", () => { + function forbidFetching() { + const nativeFetch = globalThis.fetch; + const fetch = vi.fn(() => { + throw new Error("These saved text exports must not fetch resources"); + }); + vi.stubGlobal("fetch", (input: RequestInfo | URL, init?: RequestInit) => { + const url = input instanceof Request ? input.url : String(input); + // Some engines load their shipped WASM through data/file URLs. This is + // not provider/image resolution and is outside the mapping's policy. + if (url.startsWith("data:") || url.startsWith("file:")) { + return nativeFetch(input, init); + } + return fetch(); + }); + return fetch; + } + it("composes DOCX mappings and writes native hyperlinks, escaped metadata, fallbacks and children once", async () => { + const fetch = forbidFetching(); + const exporter = new DOCXExporter(schema, { + ...docxDefaultSchemaMappings, + blockMapping: { + ...docxDefaultSchemaMappings.blockMapping, + bookmark: docx.bookmarkBlockMapping, + embed: docx.embedBlockMapping, + custom: () => new Paragraph("Custom child"), + }, + }); + const document = new WordDocument({ + sections: [{ children: await exporter.transformBlocks(blocks) }], + }); + const blob = await Packer.toBlob(document); + const xml = await zipText(blob, "word/document.xml"); + const relationships = await zipText(blob, "word/_rels/document.xml.rels"); + expect(xml).toContain( + "Saved <title> & "quotes" [#panic()]", + ); + expect(xml).toContain( + "Description <script> & "literal"", + ); + expect(xml).toContain(source.replaceAll("&", "&")); + expect(xml).toContain("https://video.example/watch?a=1&b=2"); + expect(xml).toContain("https://plain.example"); + expect(xml).toContain("javascript:alert(1)"); + expect(xml).toContain("https:ambiguous.example"); + expect(xml).toContain("Invalid source URL"); + expect(xml.match(/Custom child/g)).toHaveLength(1); + expect(relationships).toContain( + source.split("#")[0].replaceAll("&", "&"), + ); + expect(xml).toContain('w:anchor="part"'); + expect(relationships).not.toContain("javascript:"); + expect(relationships).not.toContain("https:ambiguous"); + expect(xml).not.toContain("<w:drawing"); + expect(fetch).not.toHaveBeenCalled(); + }); + it("composes ODT mappings into real ODF text/links, not upstream HTML or images", async () => { + const fetch = forbidFetching(); + const exporter = new TextOnlyODTExporter(schema, { + ...odtDefaultSchemaMappings, + blockMapping: { + ...odtDefaultSchemaMappings.blockMapping, + bookmark: odt.bookmarkBlockMapping, + embed: odt.embedBlockMapping, + custom: (block) => + createElement("text:p", { key: block.id }, "Custom child"), + }, + }); + const xml = await zipText( + await exporter.toODTDocument(blocks), + "content.xml", + ); + expect(xml).toContain( + "Saved <title> & "quotes" [#panic()]", + ); + expect(xml).toContain( + "Description <script> & "literal"", + ); + expect(xml).toContain(`xlink:href="${source.replaceAll("&", "&")}"`); + expect(xml).toContain("https://video.example/watch?a=1&b=2"); + expect(xml).toContain("https://plain.example"); + expect(xml).toContain("javascript:alert(1)"); + expect(xml).not.toContain('xlink:href="javascript:'); + expect(xml).not.toContain('xlink:href="https:ambiguous'); + expect(xml.match(/Custom child/g)).toHaveLength(1); + expect(xml).not.toContain("<draw:image"); + expect(xml).not.toContain("thumbnail.png"); + expect(fetch).not.toHaveBeenCalled(); + }); + it("composes email mappings with escaped saved text and visible source links without fetching thumbnails", async () => { + const fetch = forbidFetching(); + const exporter = new ReactEmailExporter(schema, { + ...reactEmailDefaultSchemaMappings, + blockMapping: { + ...reactEmailDefaultSchemaMappings.blockMapping, + bookmark: email.bookmarkBlockMapping, + embed: email.embedBlockMapping, + custom: () => <p>Custom child</p>, + }, + }); + const html = await exporter.toReactEmailDocument(blocks); + expect(html).toContain( + "Saved <title> & "quotes" [#panic()]", + ); + expect(html).toContain(`href="${source.replaceAll("&", "&")}"`); + expect(html).toContain( + "Description <script> & "literal"", + ); + expect(html).toContain("https://video.example/watch?a=1&b=2"); + expect(html).toContain("https://plain.example"); + expect(html).toContain("javascript:alert(1)"); + expect(html).not.toContain('href="javascript:'); + expect(html).not.toContain('href="https:ambiguous'); + expect(html.match(/Custom child/g)).toHaveLength(1); + expect(html).not.toMatch(/<(img|iframe|script)\b/); + expect(fetch).not.toHaveBeenCalled(); + }); + it("composes Typst mappings with string-literal escaping and inactive unsafe sources", async () => { + const fetch = forbidFetching(); + const exporter = new TypstExporter(schema, { + ...typstDefaultSchemaMappings, + blockMapping: { + ...typstDefaultSchemaMappings.blockMapping, + bookmark: typst.bookmarkBlockMapping, + embed: typst.embedBlockMapping, + custom: () => '#"Custom child"', + }, + }); + const output = await exporter.toTypst(blocks, { title: "Saved embeds" }); + expect(output).toContain( + `#link(${JSON.stringify(source)})[#${JSON.stringify(title)}]`, + ); + expect(output).toContain(`#${JSON.stringify(description)}`); + expect(output).toContain(`[#${JSON.stringify(source)}]`); + expect(output).toContain('#link("https://video.example/watch?a=1&b=2")'); + expect(output).toContain('#link("https://plain.example")'); + expect(output).toContain('#"javascript:alert(1)"'); + expect(output).not.toContain('#link("javascript:'); + expect(output).not.toContain('#link("https:ambiguous'); + expect(output.match(/Custom child/g)).toHaveLength(1); + expect(exporter.assetFiles.size).toBe(1); // Engine's bundled code theme only. + expect(fetch).not.toHaveBeenCalled(); + }); + it( + "uses the same Typst mappings for current PDF and compiles native link annotations offline", + { timeout: 20000 }, + async () => { + const fetch = forbidFetching(); + const exporter = new PDFExporter( + schema, + { + ...typstDefaultSchemaMappings, + blockMapping: { + ...typstDefaultSchemaMappings.blockMapping, + bookmark: typst.bookmarkBlockMapping, + embed: typst.embedBlockMapping, + custom: () => '#"Custom child"', + }, + }, + { + wasm: readFileSync( + new URL( + "../../../xl-typst-compiler/pkg/blocknote_typst_wasm_bg.wasm", + import.meta.url, + ), + ), + fonts: [ + readFileSync( + new URL( + "../../../../shared/assets/fonts/inter/Inter_18pt-Regular.ttf", + import.meta.url, + ), + ), + ], + emojiFont: [], + emojiFontFamily: undefined, + }, + ); + const result = await exporter.toPDF(blocks, { + title: "Saved embeds", + lang: "en", + }); + if (result.error) { + throw new Error(JSON.stringify(result.compileErrors)); + } + const pdf = new TextDecoder("latin1").decode(result.bytes); + expect(pdf).toMatch(/\/Subtype\s*\/Link/); + expect(pdf).toContain(source); + expect(pdf).not.toContain("javascript:alert"); + expect(result.pdfUA.declared).toBe(true); + expect(fetch).not.toHaveBeenCalled(); + }, + ); + it("keeps legacy react-pdf mappings distinct and writes clickable links without provider/image rendering", async () => { + const fetch = forbidFetching(); + const exporter = new LegacyPDFExporter(schema, { + ...pdfDefaultSchemaMappings, + blockMapping: { + ...pdfDefaultSchemaMappings.blockMapping, + bookmark: legacyPDF.bookmarkBlockMapping, + embed: legacyPDF.embedBlockMapping, + custom: () => <Text>Custom child</Text>, + }, + }); + // Engine font registration is separate; built-in Helvetica keeps this test offline. + const pdf = await renderToBuffer( + <Document> + <Page style={{ fontFamily: "Helvetica" }}> + {await exporter.transformBlocks(blocks)} + </Page> + </Document>, + ); + const text = new TextDecoder("latin1").decode(pdf); + expect(text).toMatch(/\/Subtype\s*\/Link/); + expect(text).toContain(source); + expect(text).toContain("https://video.example/watch?a=1&b=2"); + expect(text).not.toContain("javascript:alert"); + expect(fetch).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/embeds/src/exporters/sourceContent.ts b/packages/embeds/src/exporters/sourceContent.ts new file mode 100644 index 0000000000..bc78688b9a --- /dev/null +++ b/packages/embeds/src/exporters/sourceContent.ts @@ -0,0 +1,31 @@ +import type { + BlockFromConfigNoChildren, + InlineContentSchema, + StyleSchema, +} from "@blocknote/core"; +import type { bookmarkConfig, embedConfig } from "../types.js"; +import { parseSourceUrl } from "../url.js"; + +export type SourceBlock = + | BlockFromConfigNoChildren< + typeof bookmarkConfig, + InlineContentSchema, + StyleSchema + > + | BlockFromConfigNoChildren< + typeof embedConfig, + InlineContentSchema, + StyleSchema + >; + +/** Saved text only: no editor, providers, metadata resolution or remote thumbnails. */ +export function sourceContent(block: SourceBlock) { + const source = block.props.originalUrl; + const title = block.type === "bookmark" ? block.props.title : ""; + return { + label: title || source || "Invalid source URL", + description: block.type === "bookmark" ? block.props.description : "", + source, + href: parseSourceUrl(source) ? source : undefined, + }; +} diff --git a/packages/embeds/src/fetchJson.ts b/packages/embeds/src/fetchJson.ts new file mode 100644 index 0000000000..4d8c045eec --- /dev/null +++ b/packages/embeds/src/fetchJson.ts @@ -0,0 +1,40 @@ +import type { ResolveResult } from "./types.js"; + +function transportFailure(error: unknown, signal: AbortSignal) { + return ( + error instanceof TypeError || + (signal.aborted && error === signal.reason) || + (error instanceof DOMException && + (error.name === "AbortError" || error.name === "TimeoutError")) + ); +} + +/** Private transport boundary only. Each caller still validates its own unknown wire data. */ +export async function fetchJson( + request: Request, +): Promise<ResolveResult<unknown>> { + let response: Response; + try { + response = await fetch(request); + } catch (error) { + if (!transportFailure(error, request.signal)) { + throw error; + } + return { status: "unavailable" }; + } + if (!response.ok) { + return { status: "unavailable" }; + } + try { + return { status: "success", value: await response.json() }; + } catch (error) { + // SyntaxError is expected for JSON parsing, not an exception from fetch itself. + if ( + !(error instanceof SyntaxError) && + !transportFailure(error, request.signal) + ) { + throw error; + } + return { status: "unavailable" }; + } +} diff --git a/packages/embeds/src/index.ts b/packages/embeds/src/index.ts new file mode 100644 index 0000000000..b1e0bd1a15 --- /dev/null +++ b/packages/embeds/src/index.ts @@ -0,0 +1,16 @@ +export { embedBlockSpecs } from "./embedBlockSpecs.js"; +export { EmbedExtension } from "./EmbedExtension.js"; +export { withEmbeds } from "./withEmbeds.js"; +export type { EmbedOutcome } from "./embedActions.js"; +export { PasteChoice } from "./components.js"; +export { createProvider } from "./createProvider.js"; +export { SafeIframe } from "./SafeIframe.js"; +export type { SafeIframeProps } from "./SafeIframe.js"; +export type { + BookmarkMetadata, + ResolveResult, + ResolveMetadata, + EmbedProvider, + EmbedViewProps, + EmbedsOptions, +} from "./types.js"; diff --git a/packages/embeds/src/odt-exporter/index.ts b/packages/embeds/src/odt-exporter/index.ts new file mode 100644 index 0000000000..e1da99abcb --- /dev/null +++ b/packages/embeds/src/odt-exporter/index.ts @@ -0,0 +1,31 @@ +import { createElement } from "react"; +import { sourceContent, type SourceBlock } from "../exporters/sourceContent.js"; + +function sourceBlockMapping(block: SourceBlock) { + const { label, description, source, href } = sourceContent(block); + // Native ODF nodes, not raw XML/HTML; React escapes text and attributes. + return createElement( + "text:p", + { key: block.id }, + href + ? createElement("text:a", { xlinkType: "simple", xlinkHref: href }, label) + : label, + description && createElement("text:line-break"), + description, + source && source !== label && createElement("text:line-break"), + source && + source !== label && + (href + ? createElement( + "text:a", + { xlinkType: "simple", xlinkHref: href }, + source, + ) + : source), + ); +} + +export { + sourceBlockMapping as bookmarkBlockMapping, + sourceBlockMapping as embedBlockMapping, +}; diff --git a/packages/embeds/src/oembed.test.ts b/packages/embeds/src/oembed.test.ts new file mode 100644 index 0000000000..59b26dde30 --- /dev/null +++ b/packages/embeds/src/oembed.test.ts @@ -0,0 +1,86 @@ +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; +import { + createOEmbedClient, + metadataFromOEmbed, + parseOEmbed, +} from "./oembed.js"; +import { createEmbedResolver } from "../../xl-embed-server/src/index.js"; + +afterEach(() => vi.unstubAllGlobals()); +describe("standard oEmbed client", () => { + it("interoperates with the existing server's raw metadata response", async () => { + const resolver = createEmbedResolver({ + protectedFetch: async () => + new Response( + '<html><head><title>ExampleArticle', + { headers: { "Content-Type": "text/html" } }, + ), + }); + const transport = vi.fn(async (input: URL | RequestInfo) => + resolver.fetch(new Request(input)), + ); + vi.stubGlobal("fetch", transport); + const resolve = createOEmbedClient({ + endpoint: "https://app.example/oembed?tenant=demo", + }); + const result = await resolve("https://EXAMPLE.org/article", { + signal: new AbortController().signal, + }); + if (result.status !== "success") { + throw new Error("Expected metadata response"); + } + expect(metadataFromOEmbed(result.value)).toEqual({ + title: "Example", + description: "Saved description", + imageUrl: "https://example.org/image.jpg", + }); + const input = transport.mock.calls[0][0]; + const target = new URL(input instanceof Request ? input.url : input); + expect(target.searchParams.get("tenant")).toBe("demo"); + expect(target.searchParams.get("url")).toBe("https://EXAMPLE.org/article"); + }); + it.each([ + {}, + { version: "1.0", type: "video", html: "