@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.
@@ -0,0 +1,44 @@
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
+ import type { Anchor, Rect, RenderUnit } from './types.js';
10
+ /** Clamp `n` into `[min, max]`; NaN → `min`. */
11
+ export declare function clamp(n: number, min: number, max: number): number;
12
+ /**
13
+ * Clamp a renderer-reported rect into the iframe's own content box before it positions any host
14
+ * overlay element (anti-clickjack — a hostile renderer can't aim our pin at host chrome).
15
+ */
16
+ export declare function clampRect(rect: Rect, bounds: {
17
+ width: number;
18
+ height: number;
19
+ }): Rect;
20
+ /** Is `nodeId` a member of the host-issued id set? Reject otherwise (authoritative mode). */
21
+ export declare function isKnownNode(nodeId: string, units: ReadonlyArray<Pick<RenderUnit, 'nodeId'>>): boolean;
22
+ /**
23
+ * The durable, host-derived block anchor. `quote.exact` is the unit's whole SOURCE slice (durable +
24
+ * un-poisonable); `prefix`/`suffix` give a W3C TextQuoteSelector context window; `position` is the
25
+ * body-relative source range. The renderer's fine selection is NOT used here (see
26
+ * `clampSelectionHint` for the transient UI hint).
27
+ */
28
+ export declare function resolveBlockAnchor(rawBody: string, unit: RenderUnit, opts?: {
29
+ contextChars?: number;
30
+ }): Anchor;
31
+ /** A clamped, NON-durable selection hint (rendered-text relative) for the live highlight overlay. */
32
+ export interface SelectionHint {
33
+ nodeId: string;
34
+ startOffset: number;
35
+ endOffset: number;
36
+ /** Renderer-supplied rendered text; capped + used only as a UI/agent hint, never as the anchor. */
37
+ text: string;
38
+ }
39
+ /** Clamp a renderer-reported selection to safe non-negative ordered ints + a capped text hint. */
40
+ export declare function clampSelectionHint(nodeId: string, sel: {
41
+ startOffset: number;
42
+ endOffset: number;
43
+ text?: string;
44
+ }): SelectionHint;
package/dist/anchor.js ADDED
@@ -0,0 +1,62 @@
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
+ /** Clamp `n` into `[min, max]`; NaN → `min`. */
10
+ export function clamp(n, min, max) {
11
+ if (!Number.isFinite(n))
12
+ return min;
13
+ return Math.min(Math.max(n, min), max);
14
+ }
15
+ /**
16
+ * Clamp a renderer-reported rect into the iframe's own content box before it positions any host
17
+ * overlay element (anti-clickjack — a hostile renderer can't aim our pin at host chrome).
18
+ */
19
+ export function clampRect(rect, bounds) {
20
+ const x = clamp(rect.x, 0, bounds.width);
21
+ const y = clamp(rect.y, 0, bounds.height);
22
+ return {
23
+ x,
24
+ y,
25
+ width: clamp(rect.width, 0, bounds.width - x),
26
+ height: clamp(rect.height, 0, bounds.height - y),
27
+ };
28
+ }
29
+ /** Is `nodeId` a member of the host-issued id set? Reject otherwise (authoritative mode). */
30
+ export function isKnownNode(nodeId, units) {
31
+ return units.some((u) => u.nodeId === nodeId);
32
+ }
33
+ /**
34
+ * The durable, host-derived block anchor. `quote.exact` is the unit's whole SOURCE slice (durable +
35
+ * un-poisonable); `prefix`/`suffix` give a W3C TextQuoteSelector context window; `position` is the
36
+ * body-relative source range. The renderer's fine selection is NOT used here (see
37
+ * `clampSelectionHint` for the transient UI hint).
38
+ */
39
+ export function resolveBlockAnchor(rawBody, unit, opts = {}) {
40
+ const ctx = opts.contextChars ?? 32;
41
+ const len = rawBody.length;
42
+ const s = clamp(unit.sourceRange.start, 0, len);
43
+ const e = clamp(Math.max(unit.sourceRange.end, s), 0, len);
44
+ return {
45
+ nodeId: unit.nodeId,
46
+ quote: {
47
+ exact: rawBody.slice(s, e),
48
+ prefix: rawBody.slice(clamp(s - ctx, 0, len), s),
49
+ suffix: rawBody.slice(e, clamp(e + ctx, 0, len)),
50
+ },
51
+ position: { start: s, end: e },
52
+ };
53
+ }
54
+ /** Clamp a renderer-reported selection to safe non-negative ordered ints + a capped text hint. */
55
+ export function clampSelectionHint(nodeId, sel) {
56
+ const lo = Number.isFinite(sel.startOffset) ? sel.startOffset : 0;
57
+ const hi = Number.isFinite(sel.endOffset) ? sel.endOffset : 0;
58
+ const start = Math.max(0, Math.floor(Math.min(lo, hi)));
59
+ const end = Math.max(start, Math.floor(Math.max(lo, hi)));
60
+ return { nodeId, startOffset: start, endOffset: end, text: typeof sel.text === 'string' ? sel.text.slice(0, 2000) : '' };
61
+ }
62
+ //# sourceMappingURL=anchor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anchor.js","sourceRoot":"","sources":["../src/anchor.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,gDAAgD;AAChD,MAAM,UAAU,KAAK,CAAC,CAAS,EAAE,GAAW,EAAE,GAAW;IACvD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;QAAE,OAAO,GAAG,CAAA;IACnC,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,GAAG,CAAC,CAAA;AACxC,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAC,IAAU,EAAE,MAAyC;IAC7E,MAAM,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,KAAK,CAAC,CAAA;IACxC,MAAM,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,EAA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AK,CAAC,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;SACjD;QACD,QAAQ,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE;KAC/B,CAAA;AACH,CAAC;AAWD,kGAAkG;AAClG,MAAM,UAAU,kBAAkB,CAChC,MAAc,EACd,GAA8D;IAE9D,MAAM,EAAE,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAA;IACjE,MAAM,EAAE,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAA;IAC7D,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAA;IACvD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAA;IACzD,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,EAAE,IAAI,EAAE,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAA;AAC1H,CAAC"}
package/dist/host.d.ts ADDED
@@ -0,0 +1,109 @@
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
+ import { type RendererCapabilities, type ThemeSpec } from './protocol.js';
14
+ import { type SelectionHint } from './anchor.js';
15
+ import type { Rect, RenderUnit } from './types.js';
16
+ export interface HostBridgeOptions {
17
+ iframe: HTMLIFrameElement;
18
+ /** The renderer iframe's concrete origin (the `src` origin) — used as the outbound targetOrigin. */
19
+ rendererOrigin: string;
20
+ /** Per-load handshake nonce (also embedded in the iframe `src` as `?n=`). */
21
+ handshakeNonce: string;
22
+ /** Silent-ready timeout (ms) before falling back. Default 3000. */
23
+ readyTimeoutMs?: number;
24
+ /** Window to bind the global `message`/`securitypolicyviolation` listeners on. Default `window`. */
25
+ win?: Window;
26
+ }
27
+ export interface HostInitOpts {
28
+ /** The full iframe src (e.g. `${rendererOrigin}/preview/${id}?mode=edit&n=${nonce}`). */
29
+ src: string;
30
+ theme: ThemeSpec;
31
+ capabilities?: {
32
+ wantNodeEvents?: boolean;
33
+ wantSelection?: boolean;
34
+ wantHeight?: boolean;
35
+ };
36
+ safeAreaInsets?: {
37
+ top: number;
38
+ right: number;
39
+ bottom: number;
40
+ left: number;
41
+ };
42
+ }
43
+ export interface NodeClickedEvent {
44
+ nodeId: string;
45
+ rect: Rect;
46
+ scroll: {
47
+ top: number;
48
+ left: number;
49
+ };
50
+ modifiers?: {
51
+ meta: boolean;
52
+ shift: boolean;
53
+ };
54
+ /** false when `nodeId` was NOT in the host-issued set (still delivered, flagged). */
55
+ known: boolean;
56
+ }
57
+ export interface SelectionEvent extends SelectionHint {
58
+ rect: Rect;
59
+ scroll: {
60
+ top: number;
61
+ left: number;
62
+ };
63
+ known: boolean;
64
+ }
65
+ type Handlers = {
66
+ nodeClicked: Set<(e: NodeClickedEvent) => void>;
67
+ selection: Set<(e: SelectionEvent) => void>;
68
+ height: Set<(px: number) => void>;
69
+ rendered: Set<(ids: string[]) => void>;
70
+ error: Set<(e: {
71
+ code: string;
72
+ message: string;
73
+ nodeId?: string;
74
+ }) => void>;
75
+ };
76
+ export type FallbackReason = 'csp-blocked' | 'timeout' | 'incompatible';
77
+ export declare class HostBridge {
78
+ private readonly o;
79
+ private seqOut;
80
+ private lastSeqIn;
81
+ private version;
82
+ private peer;
83
+ private capabilities;
84
+ private units;
85
+ private destroyed;
86
+ private readyTimer;
87
+ private initTimer;
88
+ private initPayload;
89
+ private settle;
90
+ private readonly handlers;
91
+ constructor(opts: HostBridgeOptions);
92
+ /** Attach listeners, set the iframe src, post `init` on load, resolve on validated `ready`. */
93
+ init(opts: HostInitOpts): Promise<RendererCapabilities>;
94
+ render(blocks: RenderUnit[], language: string): void;
95
+ scrollToNode(nodeId: string, behavior?: 'smooth' | 'auto'): void;
96
+ highlight(nodeIds: string[], kind: 'comment' | 'selection' | 'clear'): void;
97
+ setTheme(theme: ThemeSpec): void;
98
+ on<E extends keyof Handlers>(ev: E, cb: Parameters<Handlers[E]['add']>[0]): () => void;
99
+ destroy(): void;
100
+ private safeHostOrigin;
101
+ private post;
102
+ private clearTimers;
103
+ private fail;
104
+ private onCspViolation;
105
+ private onMessage;
106
+ private iframeBounds;
107
+ private emit;
108
+ }
109
+ export {};
package/dist/host.js ADDED
@@ -0,0 +1,239 @@
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
+ import { acceptEnvelope, makeEnvelope, negotiateVersion, PROTOCOL_MAX_VERSION, } from './protocol.js';
14
+ import { parseRendererMessage } from './schema.js';
15
+ import { clampRect, clampSelectionHint, isKnownNode } from './anchor.js';
16
+ export class HostBridge {
17
+ o;
18
+ seqOut = 0;
19
+ lastSeqIn = -1;
20
+ version = 0;
21
+ peer = null;
22
+ capabilities = null;
23
+ units = [];
24
+ destroyed = false;
25
+ readyTimer = null;
26
+ initTimer = null;
27
+ initPayload = null;
28
+ settle = null;
29
+ handlers = {
30
+ nodeClicked: new Set(),
31
+ selection: new Set(),
32
+ height: new Set(),
33
+ rendered: new Set(),
34
+ error: new Set(),
35
+ };
36
+ constructor(opts) {
37
+ this.o = {
38
+ iframe: opts.iframe,
39
+ rendererOrigin: opts.rendererOrigin,
40
+ handshakeNonce: opts.handshakeNonce,
41
+ readyTimeoutMs: opts.readyTimeoutMs ?? 3000,
42
+ win: opts.win ?? globalThis.window,
43
+ };
44
+ }
45
+ /** Attach listeners, set the iframe src, post `init` on load, resolve on validated `ready`. */
46
+ init(opts) {
47
+ return new Promise((resolve, reject) => {
48
+ this.settle = { resolve, reject };
49
+ this.o.win.addEventListener('message', this.onMessage);
50
+ this.o.win.addEventListener('securitypolicyviolation', this.onCspViolation);
51
+ this.initPayload = {
52
+ maxVersion: PROTOCOL_MAX_VERSION,
53
+ theme: opts.theme,
54
+ hostOrigin: this.safeHostOrigin(),
55
+ capabilities: {
56
+ wantNodeEvents: opts.capabilities?.wantNodeEvents ?? true,
57
+ wantSelection: opts.capabilities?.wantSelection ?? true,
58
+ wantHeight: opts.capabilities?.wantHeight ?? true,
59
+ },
60
+ ...(opts.safeAreaInsets ? { safeAreaInsets: opts.safeAreaInsets } : {}),
61
+ };
62
+ const onLoad = () => {
63
+ this.peer = this.o.iframe.contentWindow;
64
+ if (!this.peer) {
65
+ this.fail('incompatible', 'iframe has no contentWindow');
66
+ return;
67
+ }
68
+ // Post init, then RE-POST on an interval until `ready`: a hydrating SPA renderer attaches
69
+ // its message listener AFTER the iframe `load` event, so a single init would be missed. The
70
+ // renderer's single-init latch + monotonic seq make the extra inits harmless once it replies.
71
+ this.post('embed.init', this.initPayload);
72
+ this.initTimer = setInterval(() => {
73
+ if (this.peer && this.initPayload)
74
+ this.post('embed.init', this.initPayload);
75
+ }, 150);
76
+ };
77
+ this.o.iframe.addEventListener('load', onLoad, { once: true });
78
+ this.readyTimer = setTimeout(() => this.fail('timeout', 'renderer did not become ready'), this.o.readyTimeoutMs);
79
+ // Attaching the load listener BEFORE setting src guarantees the event fires for us.
80
+ this.o.iframe.src = opts.src;
81
+ });
82
+ }
83
+ render(blocks, language) {
84
+ this.units = blocks;
85
+ this.post('embed.render', { blocks, language });
86
+ }
87
+ scrollToNode(nodeId, behavior = 'smooth') {
88
+ this.post('embed.scrollToNode', { nodeId, behavior });
89
+ }
90
+ highlight(nodeIds, kind) {
91
+ this.post('embed.highlight', { nodeIds, kind });
92
+ }
93
+ setTheme(theme) {
94
+ this.post('embed.setTheme', theme);
95
+ }
96
+ on(ev, cb) {
97
+ ;
98
+ this.handlers[ev].add(cb);
99
+ return () => this.handlers[ev].delete(cb);
100
+ }
101
+ destroy() {
102
+ this.destroyed = true;
103
+ this.clearTimers();
104
+ this.o.win.removeEventListener('message', this.onMessage);
105
+ this.o.win.removeEventListener('securitypolicyviolation', this.onCspViolation);
106
+ }
107
+ // ---- internals ----
108
+ safeHostOrigin() {
109
+ try {
110
+ return this.o.win.location?.origin ?? '';
111
+ }
112
+ catch {
113
+ return '';
114
+ }
115
+ }
116
+ post(type, payload) {
117
+ if (!this.peer)
118
+ return;
119
+ const env = makeEnvelope(type, payload, { nonce: this.o.handshakeNonce, seq: this.seqOut++, v: this.version });
120
+ // The renderer iframe is sandbox="allow-scripts allow-same-origin" → it runs at its OWN concrete
121
+ // origin (`rendererOrigin`), which a framework renderer (Nuxt/Next) NEEDS to hydrate (an opaque
122
+ // origin, from `allow-scripts` alone, breaks framework storage — verified by the cross-origin
123
+ // e2e). So target the concrete `rendererOrigin`: the message reaches the renderer ONLY while the
124
+ // iframe is still at that origin (tight — the init nonce can't leak to a navigated-away origin).
125
+ // allow-same-origin is safe because the renderer is a DIFFERENT origin than the host and so still
126
+ // cannot touch host state.
127
+ this.peer.postMessage(env, this.o.rendererOrigin);
128
+ }
129
+ clearTimers() {
130
+ if (this.readyTimer) {
131
+ clearTimeout(this.readyTimer);
132
+ this.readyTimer = null;
133
+ }
134
+ if (this.initTimer) {
135
+ clearInterval(this.initTimer);
136
+ this.initTimer = null;
137
+ }
138
+ }
139
+ fail(reason, message) {
140
+ if (!this.settle)
141
+ return;
142
+ this.clearTimers();
143
+ // The handshake failed → the bridge is dead. Detach the global listeners so a late `ready`
144
+ // (or any further message) can't be processed and the listeners don't leak.
145
+ this.o.win.removeEventListener('message', this.onMessage);
146
+ this.o.win.removeEventListener('securitypolicyviolation', this.onCspViolation);
147
+ const err = Object.assign(new Error(message), { reason });
148
+ const settle = this.settle;
149
+ this.settle = null;
150
+ settle.reject(err);
151
+ }
152
+ onCspViolation = (e) => {
153
+ if (this.destroyed || !this.settle)
154
+ return;
155
+ if (e.violatedDirective?.startsWith('frame-src') && e.blockedURI?.startsWith(this.o.rendererOrigin)) {
156
+ this.fail('csp-blocked', `frame-src blocked ${this.o.rendererOrigin}`);
157
+ }
158
+ };
159
+ onMessage = (event) => {
160
+ if (this.destroyed)
161
+ return;
162
+ // Identity: source-window only (the renderer is opaque-origin → event.origin === "null"). Reject
163
+ // when there is no peer yet — we only ever expect messages from the renderer iframe, which is
164
+ // set on `load` BEFORE `init` is sent, so a pre-peer message is never legitimate.
165
+ if (!this.peer || event.source !== this.peer)
166
+ return;
167
+ const accepted = acceptEnvelope(event.data, { expectedNonce: this.o.handshakeNonce, lastSeq: this.lastSeqIn });
168
+ if (!accepted.ok)
169
+ return;
170
+ const parsed = parseRendererMessage(event.data);
171
+ if (!parsed.success)
172
+ return;
173
+ this.lastSeqIn = accepted.seq;
174
+ const msg = parsed.data;
175
+ switch (msg.type) {
176
+ case 'embed.ready': {
177
+ const p = msg.payload;
178
+ const v = negotiateVersion(PROTOCOL_MAX_VERSION, p.version);
179
+ if (v == null) {
180
+ this.fail('incompatible', `no common protocol version (renderer ${p.version})`);
181
+ return;
182
+ }
183
+ this.clearTimers();
184
+ this.version = v;
185
+ this.capabilities = p.capabilities;
186
+ const settle = this.settle;
187
+ this.settle = null;
188
+ settle?.resolve(p.capabilities);
189
+ return;
190
+ }
191
+ case 'embed.height':
192
+ this.emit('height', msg.payload.px);
193
+ return;
194
+ case 'embed.nodeClicked': {
195
+ const p = msg.payload;
196
+ this.emit('nodeClicked', {
197
+ nodeId: p.nodeId,
198
+ rect: clampRect(p.rect, this.iframeBounds()),
199
+ scroll: p.scroll,
200
+ modifiers: p.modifiers,
201
+ known: isKnownNode(p.nodeId, this.units),
202
+ });
203
+ return;
204
+ }
205
+ case 'embed.selection': {
206
+ const p = msg.payload;
207
+ const hint = clampSelectionHint(p.nodeId, p);
208
+ this.emit('selection', {
209
+ ...hint,
210
+ rect: clampRect(p.rect, this.iframeBounds()),
211
+ scroll: p.scroll,
212
+ known: isKnownNode(p.nodeId, this.units),
213
+ });
214
+ return;
215
+ }
216
+ case 'embed.rendered':
217
+ this.emit('rendered', msg.payload.units.map((u) => u.nodeId));
218
+ return;
219
+ case 'embed.error':
220
+ this.emit('error', msg.payload);
221
+ return;
222
+ }
223
+ };
224
+ iframeBounds() {
225
+ return { width: this.o.iframe.clientWidth || 0, height: this.o.iframe.clientHeight || 0 };
226
+ }
227
+ emit(ev, arg) {
228
+ ;
229
+ this.handlers[ev].forEach((cb) => {
230
+ try {
231
+ cb(arg);
232
+ }
233
+ catch {
234
+ /* a listener throwing must not break the message loop */
235
+ }
236
+ });
237
+ }
238
+ }
239
+ //# sourceMappingURL=host.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.js","sourceRoot":"","sources":["../src/host.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EACL,cAAc,EACd,YAAY,EACZ,gBAAgB,EAChB,oBAAoB,GAGrB,MAAM,eAAe,CAAA;AACtB,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAClD,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,WAAW,EAAsB,MAAM,aAAa,CAAA;AA+C5F,MAAM,OAAO,UAAU;IACJ,CAAC,CAA4D;IACtE,MAAM,GAAG,CAAC,CAAA;IACV,SAAS,GAAG,CAAC,CAAC,CAAA;IACd,OAAO,GAAG,CAAC,CAAA;IACX,IAAI,GAAkB,IAAI,CAAA;IAC1B,YAAY,GAAgC,IAAI,CAAA;IAChD,KAAK,GAAiB,EAAE,CAAA;IACxB,SAAS,GAAG,KAAK,CAAA;IACjB,UAAU,GAAyC,IAAI,CAAA;IACvD,SAAS,GAA0C,IAAI,CAAA;IACvD,WAAW,GAAmC,IAAI,CAAA;IAClD,MAAM,GAAsF,IAAI,CAAA;IACvF,QAAQ,GAAa;QACpC,WAAW,EAAE,IAAI,GAAG,EAAE;QACtB,SAAS,EAAE,IAAI,GAAG,EAAE;QACpB,MAAM,EAAE,IAAI,GAAG,EAAE;QACjB,QAAQ,EAAE,IAAI,GAAG,EAAE;QACnB,KAAK,EAAE,IAAI,GAAG,EAAE;KACjB,CAAA;IAED,YAAY,IAAuB;QACjC,IAAI,CAAC,CAAC,GAAG;YACP,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,cAAc,EAAE,IAAI,CAAC,cAAc;YACnC,cAAc,EAAE,IAAI,CAAC,cAAc;YACnC,cAAc,EAAE,IAAI,CA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C5C,MAAM,EAAE,CAAC,CAAC,MAAM;oBAChB,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC;iBACzC,CAAC,CAAA;gBACF,OAAM;YACR,CAAC;YACD,KAAK,gBAAgB;gBACnB,IAAI,CAAC,IAAI,CAAC,UAAU,EAAG,GAAG,CAAC,OAA2C,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAA;gBAClG,OAAM;YACR,KAAK,aAAa;gBAChB,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,CAAC,OAA6D,CAAC,CAAA;gBACrF,OAAM;QACV,CAAC;IACH,CAAC,CAAA;IAEO,YAAY;QAClB,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,WAAW,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,YAAY,IAAI,CAAC,EAAE,CAAA;IAC3F,CAAC;IAEO,IAAI,CAA2B,EAAK,EAAE,GAAqD;QACjG,CAAC;QAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAA+B,CAAC,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE;YAC/D,IAAI,CAAC;gBACH,EAAE,CAAC,GAAG,CAAC,CAAA;YACT,CAAC;YAAC,MAAM,CAAC;gBACP,yDAAyD;YAC3D,CAAC;QACH,CAAC,CAAC,CAAA;IACJ,CAAC;CACF"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @blogmcp/render-embed
3
+ *
4
+ * Framework-agnostic core for the headless-renderer review overlay: the postMessage protocol
5
+ * (host ⇄ renderer), the canonical article parse (shared id space), host-side anchoring + untrusted-
6
+ * input clamps, and the two bridges. Framework wrappers (`@blogmcp/render-embed-vue` / `-react`)
7
+ * build on this; the host (article-review MCP-App / md-editor) uses `HostBridge`.
8
+ */
9
+ export * from './types.js';
10
+ export * from './protocol.js';
11
+ export * from './schema.js';
12
+ export * from './parse.js';
13
+ export * from './anchor.js';
14
+ export * from './media.js';
15
+ export { HostBridge } from './host.js';
16
+ export type { HostBridgeOptions, HostInitOpts, NodeClickedEvent, SelectionEvent, FallbackReason, } from './host.js';
17
+ export { RendererBridge } from './renderer.js';
18
+ export type { RendererBridgeOptions, RenderPayload } from './renderer.js';
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @blogmcp/render-embed
3
+ *
4
+ * Framework-agnostic core for the headless-renderer review overlay: the postMessage protocol
5
+ * (host ⇄ renderer), the canonical article parse (shared id space), host-side anchoring + untrusted-
6
+ * input clamps, and the two bridges. Framework wrappers (`@blogmcp/render-embed-vue` / `-react`)
7
+ * build on this; the host (article-review MCP-App / md-editor) uses `HostBridge`.
8
+ */
9
+ export * from './types.js';
10
+ export * from './protocol.js';
11
+ export * from './schema.js';
12
+ export * from './parse.js';
13
+ export * from './anchor.js';
14
+ export * from './media.js';
15
+ export { HostBridge } from './host.js';
16
+ export { RendererBridge } from './renderer.js';
17
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,cAAc,YAAY,CAAA;AAC1B,cAAc,eAAe,CAAA;AAC7B,cAAc,aAAa,CAAA;AAC3B,cAAc,YAAY,CAAA;AAC1B,cAAc,aAAa,CAAA;AAC3B,cAAc,YAAY,CAAA;AAC1B,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAA;AAQtC,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAA"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Media URL resolution. Per the design, media is absolutized exactly ONCE, host-side, before the
3
+ * blocks are pushed to the renderer (so the renderer never has to know the right base, and the
4
+ * browser makes no credentialed cross-origin fetch). Phase A ships the plain absolutize; the
5
+ * per-asset short-TTL signed-URL minting (the cross-domain capability) is wired in Phase C.
6
+ */
7
+ /** Absolutize a relative `/api/media/*` (or any root-relative) URL against the KB origin. */
8
+ export declare function resolveMediaUrl(src: string, kbOrigin: string): string;
9
+ /** Whether a URL points at the KB media delivery route (the only path that needs absolutizing/signing). */
10
+ export declare function isKbMediaUrl(src: string): boolean;
package/dist/media.js ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Media URL resolution. Per the design, media is absolutized exactly ONCE, host-side, before the
3
+ * blocks are pushed to the renderer (so the renderer never has to know the right base, and the
4
+ * browser makes no credentialed cross-origin fetch). Phase A ships the plain absolutize; the
5
+ * per-asset short-TTL signed-URL minting (the cross-domain capability) is wired in Phase C.
6
+ */
7
+ /** Absolutize a relative `/api/media/*` (or any root-relative) URL against the KB origin. */
8
+ export function resolveMediaUrl(src, kbOrigin) {
9
+ if (!kbOrigin || typeof src !== 'string' || !src.startsWith('/'))
10
+ return src;
11
+ return kbOrigin.replace(/\/$/, '') + src;
12
+ }
13
+ /** Whether a URL points at the KB media delivery route (the only path that needs absolutizing/signing). */
14
+ export function isKbMediaUrl(src) {
15
+ return typeof src === 'string' && /\/api\/media\/(file|thumb|poster)\//.test(src);
16
+ }
17
+ //# sourceMappingURL=media.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"media.js","sourceRoot":"","sources":["../src/media.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,6FAA6F;AAC7F,MAAM,UAAU,eAAe,CAAC,GAAW,EAAE,QAAgB;IAC3D,IAAI,CAAC,QAAQ,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,OAAO,GAAG,CAAA;IAC5E,OAAO,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,GAAG,CAAA;AAC1C,CAAC;AAED,2GAA2G;AAC3G,MAAM,UAAU,YAAY,CAAC,GAAW;IACtC,OAAO,OAAO,GAAG,KAAK,QAAQ,IAAI,qCAAqC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;AACnF,CAAC"}
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The canonical article parse — the single source of the markdown-block + MDX-component split that
3
+ * the article-review app's `mdx.ts` pioneered (lifted here so host + renderer + the screenshot
4
+ * fallback all share ONE id space). Pure (no Vue/React); the host injects its own `marked` (so the
5
+ * review app keeps its thumbnail image renderer; the blog passes its own).
6
+ *
7
+ * Each emitted `RenderUnit` carries `nodeId` ('mdx-<n>') + `sourceRange` (byte offsets into the
8
+ * post-frontmatter body) — host-assigned, the shared anchor key across live + fallback rendering.
9
+ */
10
+ import { Marked } from 'marked';
11
+ import type { ParsedArticle, SourceRange } from './types.js';
12
+ /**
13
+ * A GFM `marked` instance whose `walkTokens` hook runs every link/image URL through `sanitizeUrl`
14
+ * (→ 'about:blank' for javascript:/data:/etc) ON THE TOKEN, leaving marked's DEFAULT renderer to
15
+ * emit the safe href with correct inner rendering + HTML escaping. This URL gate is the SECURITY
16
+ * PAIR for `renderMarkdownSafe`'s pre-scan skip: a pure-markdown source like `[x](javascript:alert(1))`
17
+ * carries no raw-HTML marker, so the skip bypasses DOMPurify — the sanitized token therefore can't
18
+ * emit a hostile href. Hosts passing their OWN marked to `parseArticle` MUST likewise emit safe
19
+ * URLs, or the pre-scan is unsafe for them.
20
+ *
21
+ * NB: this uses `walkTokens`, NOT custom link/image renderers — in marked v15 a renderer's token
22
+ * `text` is RAW markdown (not rendered HTML), so overriding the renderer emits literal `**bold**`
23
+ * and unescaped `&`/`<`. Mutating `token.href` preserves marked's correct rendering + escaping.
24
+ *
25
+ * Dependency-light (NO `@blogmcp/sdk`) to avoid a render-embed → blog-sdk cycle + the SSR
26
+ * src-resolution failure it caused; URL safety reuses `sanitizeUrl` from @blogmcp/sanitize.
27
+ */
28
+ export declare function createDefaultMarked(): Marked;
29
+ /**
30
+ * Exact start offset of the trimmed body within `content` (mirrors `stripFrontmatter`: substring
31
+ * after the closing `---`, then `.trim()`). Lets a splice map a body-relative range to a
32
+ * full-content slice without an ambiguous `indexOf`.
33
+ */
34
+ export declare function computeBodyOffset(content: string): number;
35
+ /**
36
+ * Split a markdown span into top-level BLOCK units, each with its source range within `src`. Uses
37
+ * marked's block lexer (whose token `raw` values concatenate back to the input); GUARDS on that
38
+ * exact reconstruction (e.g. CRLF normalization breaks it) → returns `[]` so the caller falls back
39
+ * to one whole-span block and a splice can never write the wrong byte range. Each range is trimmed
40
+ * of trailing whitespace (editable slice = block text; the full token length still advances offset).
41
+ */
42
+ export declare function splitMarkdownBlocks(src: string, marked: Marked): Array<{
43
+ html: string;
44
+ sourceRange: SourceRange;
45
+ }>;
46
+ /**
47
+ * Parse article source into a `RenderUnit[]` (block-level html units + MDX component nodes), plus
48
+ * the post-frontmatter `body` and its `bodyOffset` within `content`.
49
+ */
50
+ export declare function parseArticle(content: string, marked?: Marked): ParsedArticle;