@blogmcp/render-embed 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/anchor.d.ts +44 -0
- package/dist/anchor.js +62 -0
- package/dist/anchor.js.map +1 -0
- package/dist/host.d.ts +109 -0
- package/dist/host.js +239 -0
- package/dist/host.js.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +17 -0
- package/dist/index.js.map +1 -0
- package/dist/media.d.ts +10 -0
- package/dist/media.js +17 -0
- package/dist/media.js.map +1 -0
- package/dist/parse.d.ts +50 -0
- package/dist/parse.js +185 -0
- package/dist/parse.js.map +1 -0
- package/dist/protocol.d.ts +145 -0
- package/dist/protocol.js +55 -0
- package/dist/protocol.js.map +1 -0
- package/dist/renderer.d.ts +65 -0
- package/dist/renderer.js +166 -0
- package/dist/renderer.js.map +1 -0
- package/dist/schema.d.ts +1635 -0
- package/dist/schema.js +103 -0
- package/dist/schema.js.map +1 -0
- package/dist/types.d.ts +77 -0
- package/dist/types.js +12 -0
- package/dist/types.js.map +1 -0
- package/package.json +77 -0
- package/src/anchor.ts +83 -0
- package/src/host.ts +302 -0
- package/src/index.ts +25 -0
- package/src/media.ts +17 -0
- package/src/parse.ts +198 -0
- package/src/protocol.ts +154 -0
- package/src/renderer.ts +197 -0
- package/src/schema.ts +139 -0
- package/src/types.ts +76 -0
package/dist/schema.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime (Zod) validators for every protocol message — the security boundary. Layered on top of
|
|
3
|
+
* the DOM-free `acceptEnvelope` gate (protocol.ts): channel/nonce/seq/source first, then full
|
|
4
|
+
* payload validation here, BEFORE any field is used.
|
|
5
|
+
*
|
|
6
|
+
* Flat discriminated unions on `type` (NO top-level `.refine`, which would collapse the shape). The
|
|
7
|
+
* hand-written TS unions in protocol.ts are the readable source; `test/schema.spec.ts` cross-checks
|
|
8
|
+
* that a valid message of each TS type passes the matching Zod schema, so the two can't drift.
|
|
9
|
+
*/
|
|
10
|
+
import { z } from 'zod';
|
|
11
|
+
import { RENDER_EMBED_PROTOCOL } from './protocol.js';
|
|
12
|
+
const channel = z.literal(RENDER_EMBED_PROTOCOL);
|
|
13
|
+
// Reject NaN/Infinity at the boundary — geometry/offsets are clamped downstream, but unguarded
|
|
14
|
+
// numbers (e.g. embed.height.px) would otherwise propagate a non-finite value to consumers.
|
|
15
|
+
const num = z.number().finite();
|
|
16
|
+
const rect = z.object({ x: num, y: num, width: num, height: num });
|
|
17
|
+
const scroll = z.object({ top: num, left: num });
|
|
18
|
+
const theme = z.object({ mode: z.enum(['light', 'dark']), tokens: z.record(z.string()).optional() });
|
|
19
|
+
function envelope(type, payload) {
|
|
20
|
+
return z.object({
|
|
21
|
+
channel,
|
|
22
|
+
seq: z.number(),
|
|
23
|
+
v: z.number(),
|
|
24
|
+
nonce: z.string(),
|
|
25
|
+
type: z.literal(type),
|
|
26
|
+
payload,
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
const renderUnit = z.object({
|
|
30
|
+
type: z.enum(['html', 'component']),
|
|
31
|
+
nodeId: z.string(),
|
|
32
|
+
sourceRange: z.object({ start: num, end: num }),
|
|
33
|
+
html: z.string().optional(),
|
|
34
|
+
name: z.string().optional(),
|
|
35
|
+
props: z.record(z.unknown()).optional(),
|
|
36
|
+
children: z.string().optional(),
|
|
37
|
+
});
|
|
38
|
+
// ---- Host → renderer ----------------------------------------------------------------------------
|
|
39
|
+
export const hostInitSchema = envelope('embed.init', z.object({
|
|
40
|
+
maxVersion: num,
|
|
41
|
+
theme,
|
|
42
|
+
hostOrigin: z.string(),
|
|
43
|
+
capabilities: z.object({
|
|
44
|
+
wantNodeEvents: z.boolean(),
|
|
45
|
+
wantSelection: z.boolean(),
|
|
46
|
+
wantHeight: z.boolean(),
|
|
47
|
+
}),
|
|
48
|
+
safeAreaInsets: z
|
|
49
|
+
.object({ top: z.number(), right: z.number(), bottom: z.number(), left: z.number() })
|
|
50
|
+
.optional(),
|
|
51
|
+
}));
|
|
52
|
+
export const hostRenderSchema = envelope('embed.render', z.object({ blocks: z.array(renderUnit).optional(), content: z.string().optional(), language: z.string() }));
|
|
53
|
+
export const hostScrollSchema = envelope('embed.scrollToNode', z.object({ nodeId: z.string(), behavior: z.enum(['smooth', 'auto']).optional() }));
|
|
54
|
+
export const hostHighlightSchema = envelope('embed.highlight', z.object({ nodeIds: z.array(z.string()), kind: z.enum(['comment', 'selection', 'clear']) }));
|
|
55
|
+
export const hostSetThemeSchema = envelope('embed.setTheme', theme);
|
|
56
|
+
export const hostMessageSchema = z.discriminatedUnion('type', [
|
|
57
|
+
hostInitSchema,
|
|
58
|
+
hostRenderSchema,
|
|
59
|
+
hostScrollSchema,
|
|
60
|
+
hostHighlightSchema,
|
|
61
|
+
hostSetThemeSchema,
|
|
62
|
+
]);
|
|
63
|
+
// ---- Renderer → host ----------------------------------------------------------------------------
|
|
64
|
+
const capabilities = z.object({
|
|
65
|
+
canParse: z.boolean(),
|
|
66
|
+
honorsNodeIds: z.boolean(),
|
|
67
|
+
nodeEvents: z.boolean(),
|
|
68
|
+
selection: z.boolean(),
|
|
69
|
+
height: z.boolean(),
|
|
70
|
+
screenshotFallback: z.boolean(),
|
|
71
|
+
});
|
|
72
|
+
export const rendererReadySchema = envelope('embed.ready', z.object({ version: num, capabilities }));
|
|
73
|
+
export const rendererHeightSchema = envelope('embed.height', z.object({ px: num }));
|
|
74
|
+
export const rendererNodeClickedSchema = envelope('embed.nodeClicked', z.object({
|
|
75
|
+
nodeId: z.string(),
|
|
76
|
+
rect,
|
|
77
|
+
scroll,
|
|
78
|
+
modifiers: z.object({ meta: z.boolean(), shift: z.boolean() }).optional(),
|
|
79
|
+
}));
|
|
80
|
+
export const rendererSelectionSchema = envelope('embed.selection', z.object({ nodeId: z.string(), startOffset: num, endOffset: num, text: z.string(), rect, scroll }));
|
|
81
|
+
export const rendererRenderedSchema = envelope('embed.rendered', z.object({ units: z.array(z.object({ nodeId: z.string() })) }));
|
|
82
|
+
export const rendererErrorSchema = envelope('embed.error', z.object({
|
|
83
|
+
code: z.enum(['parse', 'fetch', 'token', 'unsupported', 'internal']),
|
|
84
|
+
message: z.string(),
|
|
85
|
+
nodeId: z.string().optional(),
|
|
86
|
+
}));
|
|
87
|
+
export const rendererMessageSchema = z.discriminatedUnion('type', [
|
|
88
|
+
rendererReadySchema,
|
|
89
|
+
rendererHeightSchema,
|
|
90
|
+
rendererNodeClickedSchema,
|
|
91
|
+
rendererSelectionSchema,
|
|
92
|
+
rendererRenderedSchema,
|
|
93
|
+
rendererErrorSchema,
|
|
94
|
+
]);
|
|
95
|
+
/** Validate an inbound host→renderer message (renderer side). */
|
|
96
|
+
export function parseHostMessage(raw) {
|
|
97
|
+
return hostMessageSchema.safeParse(raw);
|
|
98
|
+
}
|
|
99
|
+
/** Validate an inbound renderer→host message (host side). */
|
|
100
|
+
export function parseRendererMessage(raw) {
|
|
101
|
+
return rendererMessageSchema.safeParse(raw);
|
|
102
|
+
}
|
|
103
|
+
//# sourceMappingURL=schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.js","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAA;AAErD,MAAM,OAAO,GAAG,CAAC,CAAC,OAAO,CAAC,qBAAqB,CAAC,CAAA;AAChD,+FAA+F;AAC/F,4FAA4F;AAC5F,MAAM,GAAG,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAA;AAC/B,MAAM,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAA;AAClE,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BAAgB,CAAC,GAAY;IAC3C,OAAO,iBAAiB,CAAC,SAAS,CAAC,GAAG,CAAC,CAAA;AACzC,CAAC;AAED,6DAA6D;AAC7D,MAAM,UAAU,oBAAoB,CAAC,GAAY;IAC/C,OAAO,qBAAqB,CAAC,SAAS,CAAC,GAAG,CAAC,CAAA;AAC7C,CAAC"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared data shapes for the render-embed protocol.
|
|
3
|
+
*
|
|
4
|
+
* The article-review app (the HOST) owns the canonical parse: `parseArticle()` emits a
|
|
5
|
+
* `RenderUnit[]` with app-assigned `nodeId`s + `sourceRange` byte offsets. The renderer is a
|
|
6
|
+
* projector — it renders the units we hand it and stamps `data-mdx-node-id` onto the DOM, keyed by
|
|
7
|
+
* OUR ids. One id space is shared by the live overlay AND the screenshot/structural fallback, so a
|
|
8
|
+
* comment survives a mode switch. Because ids are host-issued, the host can reject any id the
|
|
9
|
+
* renderer invents.
|
|
10
|
+
*/
|
|
11
|
+
/** Character offsets into the post-frontmatter body (`stripFrontmatter(content)`). */
|
|
12
|
+
export interface SourceRange {
|
|
13
|
+
start: number;
|
|
14
|
+
end: number;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* One render unit: a block of pre-rendered HTML or an MDX component node. Mirrors the
|
|
18
|
+
* `ParsedItem` shape `parseArticle` produces. `nodeId` is ASSIGNED BY THE HOST APP and is the
|
|
19
|
+
* shared anchor key across live + fallback rendering.
|
|
20
|
+
*/
|
|
21
|
+
export interface RenderUnit {
|
|
22
|
+
type: 'html' | 'component';
|
|
23
|
+
/** e.g. 'mdx-0', 'mdx-3/child-1' — assigned by the host's parser, not the renderer. */
|
|
24
|
+
nodeId: string;
|
|
25
|
+
/** Byte offsets into the post-frontmatter body. */
|
|
26
|
+
sourceRange: SourceRange;
|
|
27
|
+
/** type==='html': pre-sanitized HTML. The renderer RE-sanitizes regardless (never trusts this). */
|
|
28
|
+
html?: string;
|
|
29
|
+
/** type==='component': MDX component name. */
|
|
30
|
+
name?: string;
|
|
31
|
+
props?: Record<string, unknown>;
|
|
32
|
+
children?: string;
|
|
33
|
+
}
|
|
34
|
+
/** Result of `parseArticle`. */
|
|
35
|
+
export interface ParsedArticle {
|
|
36
|
+
/** 'mdx' when any MDX component is present; 'html' for pure markdown (informational). */
|
|
37
|
+
mode: 'html' | 'mdx';
|
|
38
|
+
/** Pre-rendered HTML for the whole-body fallback (only set when `items` is empty). */
|
|
39
|
+
html: string;
|
|
40
|
+
/** Block-level html + component units. */
|
|
41
|
+
items: RenderUnit[];
|
|
42
|
+
/** Post-frontmatter source the units' `sourceRange` offsets are relative to. */
|
|
43
|
+
body: string;
|
|
44
|
+
/** Offset at which `body` begins within the original `content` (`content.slice(bodyOffset, …)`). */
|
|
45
|
+
bodyOffset: number;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Renderer mode. `production` = inert passthrough (no protocol, no message listener, no reporting).
|
|
49
|
+
* `edit` = protocol active (annotate blocks, report clicks/selections, apply host messages).
|
|
50
|
+
*/
|
|
51
|
+
export type RenderMode = 'production' | 'edit';
|
|
52
|
+
/**
|
|
53
|
+
* A durable comment/selection anchor, host-derived. Stored as a W3C TextQuoteSelector (re-derived
|
|
54
|
+
* host-side from `sourceRange` — durable) + a TextPositionSelector (a hint). Renderer-supplied
|
|
55
|
+
* `text`/offsets are NEVER stored directly (see anchor.ts).
|
|
56
|
+
*/
|
|
57
|
+
export interface Anchor {
|
|
58
|
+
nodeId: string;
|
|
59
|
+
/** TextQuoteSelector — re-derived host-side from the raw body slice. */
|
|
60
|
+
quote: {
|
|
61
|
+
exact: string;
|
|
62
|
+
prefix?: string;
|
|
63
|
+
suffix?: string;
|
|
64
|
+
};
|
|
65
|
+
/** TextPositionSelector — body-relative offsets (clamped). */
|
|
66
|
+
position: {
|
|
67
|
+
start: number;
|
|
68
|
+
end: number;
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/** A viewport rect reported by the renderer (untrusted until clamped host-side). */
|
|
72
|
+
export interface Rect {
|
|
73
|
+
x: number;
|
|
74
|
+
y: number;
|
|
75
|
+
width: number;
|
|
76
|
+
height: number;
|
|
77
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared data shapes for the render-embed protocol.
|
|
3
|
+
*
|
|
4
|
+
* The article-review app (the HOST) owns the canonical parse: `parseArticle()` emits a
|
|
5
|
+
* `RenderUnit[]` with app-assigned `nodeId`s + `sourceRange` byte offsets. The renderer is a
|
|
6
|
+
* projector — it renders the units we hand it and stamps `data-mdx-node-id` onto the DOM, keyed by
|
|
7
|
+
* OUR ids. One id space is shared by the live overlay AND the screenshot/structural fallback, so a
|
|
8
|
+
* comment survives a mode switch. Because ids are host-issued, the host can reject any id the
|
|
9
|
+
* renderer invents.
|
|
10
|
+
*/
|
|
11
|
+
export {};
|
|
12
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG"}
|
package/package.json
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@blogmcp/render-embed",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Framework-agnostic render-embed protocol + parse for the headless-renderer review overlay (host + renderer postMessage bridges).",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"publishConfig": {
|
|
7
|
+
"access": "public"
|
|
8
|
+
},
|
|
9
|
+
"main": "./dist/index.js",
|
|
10
|
+
"module": "./dist/index.js",
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./src/index.ts",
|
|
15
|
+
"import": "./dist/index.js"
|
|
16
|
+
},
|
|
17
|
+
"./protocol": {
|
|
18
|
+
"types": "./src/protocol.ts",
|
|
19
|
+
"import": "./dist/protocol.js"
|
|
20
|
+
},
|
|
21
|
+
"./schema": {
|
|
22
|
+
"types": "./src/schema.ts",
|
|
23
|
+
"import": "./dist/schema.js"
|
|
24
|
+
},
|
|
25
|
+
"./parse": {
|
|
26
|
+
"types": "./src/parse.ts",
|
|
27
|
+
"import": "./dist/parse.js"
|
|
28
|
+
},
|
|
29
|
+
"./anchor": {
|
|
30
|
+
"types": "./src/anchor.ts",
|
|
31
|
+
"import": "./dist/anchor.js"
|
|
32
|
+
},
|
|
33
|
+
"./media": {
|
|
34
|
+
"types": "./src/media.ts",
|
|
35
|
+
"import": "./dist/media.js"
|
|
36
|
+
},
|
|
37
|
+
"./host": {
|
|
38
|
+
"types": "./src/host.ts",
|
|
39
|
+
"import": "./dist/host.js"
|
|
40
|
+
},
|
|
41
|
+
"./renderer": {
|
|
42
|
+
"types": "./src/renderer.ts",
|
|
43
|
+
"import": "./dist/renderer.js"
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
"files": [
|
|
47
|
+
"dist",
|
|
48
|
+
"src"
|
|
49
|
+
],
|
|
50
|
+
"scripts": {
|
|
51
|
+
"build": "tsc -p tsconfig.build.json",
|
|
52
|
+
"dev": "tsc -p tsconfig.build.json --watch",
|
|
53
|
+
"test": "vitest run",
|
|
54
|
+
"test:watch": "vitest",
|
|
55
|
+
"typecheck": "tsc --noEmit"
|
|
56
|
+
},
|
|
57
|
+
"dependencies": {
|
|
58
|
+
"@blogmcp/mdx-schema": "^0.1.0",
|
|
59
|
+
"@blogmcp/sanitize": "^0.1.0",
|
|
60
|
+
"marked": "^15.0.7",
|
|
61
|
+
"zod": "^3.23.8"
|
|
62
|
+
},
|
|
63
|
+
"devDependencies": {
|
|
64
|
+
"@types/node": "^20.10.0",
|
|
65
|
+
"@vitest/utils": "3.2.4",
|
|
66
|
+
"happy-dom": "^17.4.0",
|
|
67
|
+
"typescript": "^5.3.3",
|
|
68
|
+
"vitest": "^3.0.0"
|
|
69
|
+
},
|
|
70
|
+
"keywords": [
|
|
71
|
+
"mdx",
|
|
72
|
+
"render-embed",
|
|
73
|
+
"postmessage",
|
|
74
|
+
"headless"
|
|
75
|
+
],
|
|
76
|
+
"license": "MIT"
|
|
77
|
+
}
|
package/src/anchor.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host-side anchoring + the clamps applied to UNTRUSTED renderer→host geometry/selection.
|
|
3
|
+
*
|
|
4
|
+
* Security invariants (verify H5/D8): the renderer's `text`/offsets/rect are HINTS — never trusted
|
|
5
|
+
* for storage or overlay positioning without clamping. The DURABLE anchor's quote is re-derived
|
|
6
|
+
* host-side by slicing the raw body at the unit's `sourceRange` (the host holds the raw body), so a
|
|
7
|
+
* hostile renderer cannot poison the stored quote.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { Anchor, Rect, RenderUnit } from './types.js'
|
|
11
|
+
|
|
12
|
+
/** Clamp `n` into `[min, max]`; NaN → `min`. */
|
|
13
|
+
export function clamp(n: number, min: number, max: number): number {
|
|
14
|
+
if (!Number.isFinite(n)) return min
|
|
15
|
+
return Math.min(Math.max(n, min), max)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Clamp a renderer-reported rect into the iframe's own content box before it positions any host
|
|
20
|
+
* overlay element (anti-clickjack — a hostile renderer can't aim our pin at host chrome).
|
|
21
|
+
*/
|
|
22
|
+
export function clampRect(rect: Rect, bounds: { width: number; height: number }): Rect {
|
|
23
|
+
const x = clamp(rect.x, 0, bounds.width)
|
|
24
|
+
const y = clamp(rect.y, 0, bounds.height)
|
|
25
|
+
return {
|
|
26
|
+
x,
|
|
27
|
+
y,
|
|
28
|
+
width: clamp(rect.width, 0, bounds.width - x),
|
|
29
|
+
height: clamp(rect.height, 0, bounds.height - y),
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Is `nodeId` a member of the host-issued id set? Reject otherwise (authoritative mode). */
|
|
34
|
+
export function isKnownNode(nodeId: string, units: ReadonlyArray<Pick<RenderUnit, 'nodeId'>>): boolean {
|
|
35
|
+
return units.some((u) => u.nodeId === nodeId)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The durable, host-derived block anchor. `quote.exact` is the unit's whole SOURCE slice (durable +
|
|
40
|
+
* un-poisonable); `prefix`/`suffix` give a W3C TextQuoteSelector context window; `position` is the
|
|
41
|
+
* body-relative source range. The renderer's fine selection is NOT used here (see
|
|
42
|
+
* `clampSelectionHint` for the transient UI hint).
|
|
43
|
+
*/
|
|
44
|
+
export function resolveBlockAnchor(
|
|
45
|
+
rawBody: string,
|
|
46
|
+
unit: RenderUnit,
|
|
47
|
+
opts: { contextChars?: number } = {},
|
|
48
|
+
): Anchor {
|
|
49
|
+
const ctx = opts.contextChars ?? 32
|
|
50
|
+
const len = rawBody.length
|
|
51
|
+
const s = clamp(unit.sourceRange.start, 0, len)
|
|
52
|
+
const e = clamp(Math.max(unit.sourceRange.end, s), 0, len)
|
|
53
|
+
return {
|
|
54
|
+
nodeId: unit.nodeId,
|
|
55
|
+
quote: {
|
|
56
|
+
exact: rawBody.slice(s, e),
|
|
57
|
+
prefix: rawBody.slice(clamp(s - ctx, 0, len), s),
|
|
58
|
+
suffix: rawBody.slice(e, clamp(e + ctx, 0, len)),
|
|
59
|
+
},
|
|
60
|
+
position: { start: s, end: e },
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** A clamped, NON-durable selection hint (rendered-text relative) for the live highlight overlay. */
|
|
65
|
+
export interface SelectionHint {
|
|
66
|
+
nodeId: string
|
|
67
|
+
startOffset: number
|
|
68
|
+
endOffset: number
|
|
69
|
+
/** Renderer-supplied rendered text; capped + used only as a UI/agent hint, never as the anchor. */
|
|
70
|
+
text: string
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Clamp a renderer-reported selection to safe non-negative ordered ints + a capped text hint. */
|
|
74
|
+
export function clampSelectionHint(
|
|
75
|
+
nodeId: string,
|
|
76
|
+
sel: { startOffset: number; endOffset: number; text?: string },
|
|
77
|
+
): SelectionHint {
|
|
78
|
+
const lo = Number.isFinite(sel.startOffset) ? sel.startOffset : 0
|
|
79
|
+
const hi = Number.isFinite(sel.endOffset) ? sel.endOffset : 0
|
|
80
|
+
const start = Math.max(0, Math.floor(Math.min(lo, hi)))
|
|
81
|
+
const end = Math.max(start, Math.floor(Math.max(lo, hi)))
|
|
82
|
+
return { nodeId, startOffset: start, endOffset: end, text: typeof sel.text === 'string' ? sel.text.slice(0, 2000) : '' }
|
|
83
|
+
}
|
package/src/host.ts
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HostBridge — the host (article-review MCP-App / md-editor desktop) side of the protocol. Drives a
|
|
3
|
+
* renderer iframe: posts `init` on load (targetOrigin = the concrete renderer origin, never `"*"`,
|
|
4
|
+
* never a secret), validates every inbound message (`event.source` + nonce + seq + Zod), clamps all
|
|
5
|
+
* renderer geometry, and exposes typed callbacks. Three separated detectors decide fallback:
|
|
6
|
+
* instant `securitypolicyviolation` (frame-src blocked), a 3s silent `ready` timeout, or an explicit
|
|
7
|
+
* incompatible `ready`/`error`.
|
|
8
|
+
*
|
|
9
|
+
* Usage: create the iframe WITHOUT a src, `new HostBridge({iframe, rendererOrigin, handshakeNonce})`,
|
|
10
|
+
* then `await bridge.init({ src, theme })` — init attaches listeners BEFORE setting `iframe.src`, so
|
|
11
|
+
* the `load` event can't be missed.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
acceptEnvelope,
|
|
16
|
+
makeEnvelope,
|
|
17
|
+
negotiateVersion,
|
|
18
|
+
PROTOCOL_MAX_VERSION,
|
|
19
|
+
type RendererCapabilities,
|
|
20
|
+
type ThemeSpec,
|
|
21
|
+
} from './protocol.js'
|
|
22
|
+
import { parseRendererMessage } from './schema.js'
|
|
23
|
+
import { clampRect, clampSelectionHint, isKnownNode, type SelectionHint } from './anchor.js'
|
|
24
|
+
import type { Rect, RenderUnit } from './types.js'
|
|
25
|
+
|
|
26
|
+
export interface HostBridgeOptions {
|
|
27
|
+
iframe: HTMLIFrameElement
|
|
28
|
+
/** The renderer iframe's concrete origin (the `src` origin) — used as the outbound targetOrigin. */
|
|
29
|
+
rendererOrigin: string
|
|
30
|
+
/** Per-load handshake nonce (also embedded in the iframe `src` as `?n=`). */
|
|
31
|
+
handshakeNonce: string
|
|
32
|
+
/** Silent-ready timeout (ms) before falling back. Default 3000. */
|
|
33
|
+
readyTimeoutMs?: number
|
|
34
|
+
/** Window to bind the global `message`/`securitypolicyviolation` listeners on. Default `window`. */
|
|
35
|
+
win?: Window
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface HostInitOpts {
|
|
39
|
+
/** The full iframe src (e.g. `${rendererOrigin}/preview/${id}?mode=edit&n=${nonce}`). */
|
|
40
|
+
src: string
|
|
41
|
+
theme: ThemeSpec
|
|
42
|
+
capabilities?: { wantNodeEvents?: boolean; wantSelection?: boolean; wantHeight?: boolean }
|
|
43
|
+
safeAreaInsets?: { top: number; right: number; bottom: number; left: number }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface NodeClickedEvent {
|
|
47
|
+
nodeId: string
|
|
48
|
+
rect: Rect
|
|
49
|
+
scroll: { top: number; left: number }
|
|
50
|
+
modifiers?: { meta: boolean; shift: boolean }
|
|
51
|
+
/** false when `nodeId` was NOT in the host-issued set (still delivered, flagged). */
|
|
52
|
+
known: boolean
|
|
53
|
+
}
|
|
54
|
+
export interface SelectionEvent extends SelectionHint {
|
|
55
|
+
rect: Rect
|
|
56
|
+
scroll: { top: number; left: number }
|
|
57
|
+
known: boolean
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
type Handlers = {
|
|
61
|
+
nodeClicked: Set<(e: NodeClickedEvent) => void>
|
|
62
|
+
selection: Set<(e: SelectionEvent) => void>
|
|
63
|
+
height: Set<(px: number) => void>
|
|
64
|
+
rendered: Set<(ids: string[]) => void>
|
|
65
|
+
error: Set<(e: { code: string; message: string; nodeId?: string }) => void>
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export type FallbackReason = 'csp-blocked' | 'timeout' | 'incompatible'
|
|
69
|
+
|
|
70
|
+
export class HostBridge {
|
|
71
|
+
private readonly o: Required<Omit<HostBridgeOptions, 'win'>> & { win: Window }
|
|
72
|
+
private seqOut = 0
|
|
73
|
+
private lastSeqIn = -1
|
|
74
|
+
private version = 0
|
|
75
|
+
private peer: Window | null = null
|
|
76
|
+
private capabilities: RendererCapabilities | null = null
|
|
77
|
+
private units: RenderUnit[] = []
|
|
78
|
+
private destroyed = false
|
|
79
|
+
private readyTimer: ReturnType<typeof setTimeout> | null = null
|
|
80
|
+
private initTimer: ReturnType<typeof setInterval> | null = null
|
|
81
|
+
private initPayload: Record<string, unknown> | null = null
|
|
82
|
+
private settle: { resolve: (c: RendererCapabilities) => void; reject: (e: Error) => void } | null = null
|
|
83
|
+
private readonly handlers: Handlers = {
|
|
84
|
+
nodeClicked: new Set(),
|
|
85
|
+
selection: new Set(),
|
|
86
|
+
height: new Set(),
|
|
87
|
+
rendered: new Set(),
|
|
88
|
+
error: new Set(),
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
constructor(opts: HostBridgeOptions) {
|
|
92
|
+
this.o = {
|
|
93
|
+
iframe: opts.iframe,
|
|
94
|
+
rendererOrigin: opts.rendererOrigin,
|
|
95
|
+
handshakeNonce: opts.handshakeNonce,
|
|
96
|
+
readyTimeoutMs: opts.readyTimeoutMs ?? 3000,
|
|
97
|
+
win: opts.win ?? (globalThis as unknown as { window: Window }).window,
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Attach listeners, set the iframe src, post `init` on load, resolve on validated `ready`. */
|
|
102
|
+
init(opts: HostInitOpts): Promise<RendererCapabilities> {
|
|
103
|
+
return new Promise<RendererCapabilities>((resolve, reject) => {
|
|
104
|
+
this.settle = { resolve, reject }
|
|
105
|
+
this.o.win.addEventListener('message', this.onMessage)
|
|
106
|
+
this.o.win.addEventListener('securitypolicyviolation', this.onCspViolation as EventListener)
|
|
107
|
+
|
|
108
|
+
this.initPayload = {
|
|
109
|
+
maxVersion: PROTOCOL_MAX_VERSION,
|
|
110
|
+
theme: opts.theme,
|
|
111
|
+
hostOrigin: this.safeHostOrigin(),
|
|
112
|
+
capabilities: {
|
|
113
|
+
wantNodeEvents: opts.capabilities?.wantNodeEvents ?? true,
|
|
114
|
+
wantSelection: opts.capabilities?.wantSelection ?? true,
|
|
115
|
+
wantHeight: opts.capabilities?.wantHeight ?? true,
|
|
116
|
+
},
|
|
117
|
+
...(opts.safeAreaInsets ? { safeAreaInsets: opts.safeAreaInsets } : {}),
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const onLoad = (): void => {
|
|
121
|
+
this.peer = this.o.iframe.contentWindow
|
|
122
|
+
if (!this.peer) {
|
|
123
|
+
this.fail('incompatible', 'iframe has no contentWindow')
|
|
124
|
+
return
|
|
125
|
+
}
|
|
126
|
+
// Post init, then RE-POST on an interval until `ready`: a hydrating SPA renderer attaches
|
|
127
|
+
// its message listener AFTER the iframe `load` event, so a single init would be missed. The
|
|
128
|
+
// renderer's single-init latch + monotonic seq make the extra inits harmless once it replies.
|
|
129
|
+
this.post('embed.init', this.initPayload!)
|
|
130
|
+
this.initTimer = setInterval(() => {
|
|
131
|
+
if (this.peer && this.initPayload) this.post('embed.init', this.initPayload)
|
|
132
|
+
}, 150)
|
|
133
|
+
}
|
|
134
|
+
this.o.iframe.addEventListener('load', onLoad, { once: true })
|
|
135
|
+
|
|
136
|
+
this.readyTimer = setTimeout(() => this.fail('timeout', 'renderer did not become ready'), this.o.readyTimeoutMs)
|
|
137
|
+
|
|
138
|
+
// Attaching the load listener BEFORE setting src guarantees the event fires for us.
|
|
139
|
+
this.o.iframe.src = opts.src
|
|
140
|
+
})
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
render(blocks: RenderUnit[], language: string): void {
|
|
144
|
+
this.units = blocks
|
|
145
|
+
this.post('embed.render', { blocks, language })
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
scrollToNode(nodeId: string, behavior: 'smooth' | 'auto' = 'smooth'): void {
|
|
149
|
+
this.post('embed.scrollToNode', { nodeId, behavior })
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
highlight(nodeIds: string[], kind: 'comment' | 'selection' | 'clear'): void {
|
|
153
|
+
this.post('embed.highlight', { nodeIds, kind })
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
setTheme(theme: ThemeSpec): void {
|
|
157
|
+
this.post('embed.setTheme', theme)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
on<E extends keyof Handlers>(ev: E, cb: Parameters<Handlers[E]['add']>[0]): () => void {
|
|
161
|
+
;(this.handlers[ev] as Set<unknown>).add(cb)
|
|
162
|
+
return () => (this.handlers[ev] as Set<unknown>).delete(cb)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
destroy(): void {
|
|
166
|
+
this.destroyed = true
|
|
167
|
+
this.clearTimers()
|
|
168
|
+
this.o.win.removeEventListener('message', this.onMessage)
|
|
169
|
+
this.o.win.removeEventListener('securitypolicyviolation', this.onCspViolation as EventListener)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// ---- internals ----
|
|
173
|
+
|
|
174
|
+
private safeHostOrigin(): string {
|
|
175
|
+
try {
|
|
176
|
+
return this.o.win.location?.origin ?? ''
|
|
177
|
+
} catch {
|
|
178
|
+
return ''
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
private post(type: string, payload: unknown): void {
|
|
183
|
+
if (!this.peer) return
|
|
184
|
+
const env = makeEnvelope(type, payload, { nonce: this.o.handshakeNonce, seq: this.seqOut++, v: this.version })
|
|
185
|
+
// The renderer iframe is sandbox="allow-scripts allow-same-origin" → it runs at its OWN concrete
|
|
186
|
+
// origin (`rendererOrigin`), which a framework renderer (Nuxt/Next) NEEDS to hydrate (an opaque
|
|
187
|
+
// origin, from `allow-scripts` alone, breaks framework storage — verified by the cross-origin
|
|
188
|
+
// e2e). So target the concrete `rendererOrigin`: the message reaches the renderer ONLY while the
|
|
189
|
+
// iframe is still at that origin (tight — the init nonce can't leak to a navigated-away origin).
|
|
190
|
+
// allow-same-origin is safe because the renderer is a DIFFERENT origin than the host and so still
|
|
191
|
+
// cannot touch host state.
|
|
192
|
+
this.peer.postMessage(env, this.o.rendererOrigin)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
private clearTimers(): void {
|
|
196
|
+
if (this.readyTimer) {
|
|
197
|
+
clearTimeout(this.readyTimer)
|
|
198
|
+
this.readyTimer = null
|
|
199
|
+
}
|
|
200
|
+
if (this.initTimer) {
|
|
201
|
+
clearInterval(this.initTimer)
|
|
202
|
+
this.initTimer = null
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
private fail(reason: FallbackReason, message: string): void {
|
|
207
|
+
if (!this.settle) return
|
|
208
|
+
this.clearTimers()
|
|
209
|
+
// The handshake failed → the bridge is dead. Detach the global listeners so a late `ready`
|
|
210
|
+
// (or any further message) can't be processed and the listeners don't leak.
|
|
211
|
+
this.o.win.removeEventListener('message', this.onMessage)
|
|
212
|
+
this.o.win.removeEventListener('securitypolicyviolation', this.onCspViolation as EventListener)
|
|
213
|
+
const err = Object.assign(new Error(message), { reason })
|
|
214
|
+
const settle = this.settle
|
|
215
|
+
this.settle = null
|
|
216
|
+
settle.reject(err)
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private onCspViolation = (e: SecurityPolicyViolationEvent): void => {
|
|
220
|
+
if (this.destroyed || !this.settle) return
|
|
221
|
+
if (e.violatedDirective?.startsWith('frame-src') && e.blockedURI?.startsWith(this.o.rendererOrigin)) {
|
|
222
|
+
this.fail('csp-blocked', `frame-src blocked ${this.o.rendererOrigin}`)
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
private onMessage = (event: MessageEvent): void => {
|
|
227
|
+
if (this.destroyed) return
|
|
228
|
+
// Identity: source-window only (the renderer is opaque-origin → event.origin === "null"). Reject
|
|
229
|
+
// when there is no peer yet — we only ever expect messages from the renderer iframe, which is
|
|
230
|
+
// set on `load` BEFORE `init` is sent, so a pre-peer message is never legitimate.
|
|
231
|
+
if (!this.peer || event.source !== this.peer) return
|
|
232
|
+
const accepted = acceptEnvelope(event.data, { expectedNonce: this.o.handshakeNonce, lastSeq: this.lastSeqIn })
|
|
233
|
+
if (!accepted.ok) return
|
|
234
|
+
const parsed = parseRendererMessage(event.data)
|
|
235
|
+
if (!parsed.success) return
|
|
236
|
+
this.lastSeqIn = accepted.seq
|
|
237
|
+
const msg = parsed.data as { type: string; payload: Record<string, unknown> }
|
|
238
|
+
|
|
239
|
+
switch (msg.type) {
|
|
240
|
+
case 'embed.ready': {
|
|
241
|
+
const p = msg.payload as { version: number; capabilities: RendererCapabilities }
|
|
242
|
+
const v = negotiateVersion(PROTOCOL_MAX_VERSION, p.version)
|
|
243
|
+
if (v == null) {
|
|
244
|
+
this.fail('incompatible', `no common protocol version (renderer ${p.version})`)
|
|
245
|
+
return
|
|
246
|
+
}
|
|
247
|
+
this.clearTimers()
|
|
248
|
+
this.version = v
|
|
249
|
+
this.capabilities = p.capabilities
|
|
250
|
+
const settle = this.settle
|
|
251
|
+
this.settle = null
|
|
252
|
+
settle?.resolve(p.capabilities)
|
|
253
|
+
return
|
|
254
|
+
}
|
|
255
|
+
case 'embed.height':
|
|
256
|
+
this.emit('height', (msg.payload as { px: number }).px)
|
|
257
|
+
return
|
|
258
|
+
case 'embed.nodeClicked': {
|
|
259
|
+
const p = msg.payload as { nodeId: string; rect: Rect; scroll: { top: number; left: number }; modifiers?: { meta: boolean; shift: boolean } }
|
|
260
|
+
this.emit('nodeClicked', {
|
|
261
|
+
nodeId: p.nodeId,
|
|
262
|
+
rect: clampRect(p.rect, this.iframeBounds()),
|
|
263
|
+
scroll: p.scroll,
|
|
264
|
+
modifiers: p.modifiers,
|
|
265
|
+
known: isKnownNode(p.nodeId, this.units),
|
|
266
|
+
})
|
|
267
|
+
return
|
|
268
|
+
}
|
|
269
|
+
case 'embed.selection': {
|
|
270
|
+
const p = msg.payload as { nodeId: string; startOffset: number; endOffset: number; text: string; rect: Rect; scroll: { top: number; left: number } }
|
|
271
|
+
const hint = clampSelectionHint(p.nodeId, p)
|
|
272
|
+
this.emit('selection', {
|
|
273
|
+
...hint,
|
|
274
|
+
rect: clampRect(p.rect, this.iframeBounds()),
|
|
275
|
+
scroll: p.scroll,
|
|
276
|
+
known: isKnownNode(p.nodeId, this.units),
|
|
277
|
+
})
|
|
278
|
+
return
|
|
279
|
+
}
|
|
280
|
+
case 'embed.rendered':
|
|
281
|
+
this.emit('rendered', (msg.payload as { units: { nodeId: string }[] }).units.map((u) => u.nodeId))
|
|
282
|
+
return
|
|
283
|
+
case 'embed.error':
|
|
284
|
+
this.emit('error', msg.payload as { code: string; message: string; nodeId?: string })
|
|
285
|
+
return
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
private iframeBounds(): { width: number; height: number } {
|
|
290
|
+
return { width: this.o.iframe.clientWidth || 0, height: this.o.iframe.clientHeight || 0 }
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
private emit<E extends keyof Handlers>(ev: E, arg: Parameters<Parameters<Handlers[E]['add']>[0]>[0]): void {
|
|
294
|
+
;(this.handlers[ev] as Set<(a: unknown) => void>).forEach((cb) => {
|
|
295
|
+
try {
|
|
296
|
+
cb(arg)
|
|
297
|
+
} catch {
|
|
298
|
+
/* a listener throwing must not break the message loop */
|
|
299
|
+
}
|
|
300
|
+
})
|
|
301
|
+
}
|
|
302
|
+
}
|