social-embeds 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,290 @@
1
1
  "use client";
2
- import { a as escapeAttribute, i as x$1, n as matchUrl, o as parseHtml, r as platforms, s as rebuild, t as parseEmbed } from "./parser-HhmrfoYj.js";
2
+ import { a as escapeAttribute, i as x$1, n as matchUrl, o as parseHtml, r as platforms, s as rebuild, t as parseEmbed } from "./parser-D7a5KPhN.js";
3
3
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4
4
  import { jsx, jsxs } from "react/jsx-runtime";
5
+ // src/components/hooks.ts
6
+ const ROOT_MARGIN = "200px 0px";
7
+ /** False on the server and in the first client render, so the markup matches on hydration. */
8
+ function useNearViewport(ref, lazy) {
9
+ const [near, setNear] = useState(false);
10
+ useEffect(() => {
11
+ const element = ref.current;
12
+ if (!lazy || !element || typeof IntersectionObserver === "undefined") {
13
+ setNear(true);
14
+ return;
15
+ }
16
+ const observer = new IntersectionObserver((entries) => {
17
+ if (entries.some((entry) => entry.isIntersecting)) {
18
+ setNear(true);
19
+ observer.disconnect();
20
+ }
21
+ }, { rootMargin: ROOT_MARGIN });
22
+ observer.observe(element);
23
+ return () => {
24
+ observer.disconnect();
25
+ };
26
+ }, [ref, lazy]);
27
+ return near;
28
+ }
29
+ /** Calls `onError` from an effect, once per distinct message. */
30
+ function useReportError(message, onError) {
31
+ const latest = useRef(onError);
32
+ useEffect(() => {
33
+ latest.current = onError;
34
+ });
35
+ useEffect(() => {
36
+ if (message !== void 0) latest.current?.(new Error(message));
37
+ }, [message]);
38
+ }
39
+ // src/components/iframe-embed.tsx
40
+ const FILL = {
41
+ position: "absolute",
42
+ inset: 0
43
+ };
44
+ const HEIGHT_TIMEOUT_MS = 15e3;
45
+ const MAX_REPORTED_HEIGHT = 5e4;
46
+ function IframeEmbed({ src, title, allow, referrerPolicy, scrolling, sandbox, ratio, size, messageHeight, startHeight, hostParam, width = "100%", maxWidth, height, maxHeight, placeholder, lazy = true, onLoad, onError, style, ...rest }) {
47
+ const frame = useRef(null);
48
+ const iframe = useRef(null);
49
+ const near = useNearViewport(frame, lazy);
50
+ const [loaded, setLoaded] = useState(false);
51
+ const [reportedHeight, setReportedHeight] = useState();
52
+ const reported = useRef(false);
53
+ const callbacks = useRef({
54
+ onLoad,
55
+ onError
56
+ });
57
+ useEffect(() => {
58
+ callbacks.current = {
59
+ onLoad,
60
+ onError
61
+ };
62
+ });
63
+ const report = useCallback(() => {
64
+ setLoaded(true);
65
+ if (reported.current) return;
66
+ reported.current = true;
67
+ callbacks.current.onLoad?.();
68
+ }, []);
69
+ useEffect(() => {
70
+ if (!near || !messageHeight) return;
71
+ const { origin, read } = messageHeight;
72
+ let heard = false;
73
+ const listen = (event) => {
74
+ if (event.origin !== origin) return;
75
+ if (!iframe.current || event.source !== iframe.current.contentWindow) return;
76
+ let value;
77
+ try {
78
+ value = read(event.data);
79
+ } catch {
80
+ return;
81
+ }
82
+ if (typeof value !== "number" || !(value > 0 && value <= MAX_REPORTED_HEIGHT)) return;
83
+ heard = true;
84
+ setReportedHeight(Math.ceil(value));
85
+ report();
86
+ };
87
+ window.addEventListener("message", listen);
88
+ const timer = setTimeout(() => {
89
+ if (heard) return;
90
+ setLoaded(true);
91
+ callbacks.current.onError?.(/* @__PURE__ */ new Error(`social-embeds: ${title} did not report its height`));
92
+ }, HEIGHT_TIMEOUT_MS);
93
+ return () => {
94
+ window.removeEventListener("message", listen);
95
+ clearTimeout(timer);
96
+ };
97
+ }, [
98
+ near,
99
+ messageHeight,
100
+ title,
101
+ report
102
+ ]);
103
+ const aspectWidth = size?.width ?? ratio.width;
104
+ const aspectHeight = size?.height ?? ratio.height;
105
+ const widest = maxHeight === void 0 || height !== void 0 ? void 0 : Math.floor(maxHeight * aspectWidth / aspectHeight);
106
+ const wrapper = {
107
+ position: "relative",
108
+ width,
109
+ maxWidth: widest === void 0 || maxWidth !== void 0 && maxWidth < widest ? maxWidth : widest,
110
+ ...messageHeight ? { height: reportedHeight ?? startHeight } : height === void 0 ? { aspectRatio: `${String(aspectWidth)} / ${String(aspectHeight)}` } : {
111
+ height,
112
+ maxHeight
113
+ },
114
+ ...style
115
+ };
116
+ return /* @__PURE__ */ jsx("div", {
117
+ ...rest,
118
+ style: wrapper,
119
+ children: /* @__PURE__ */ jsxs("div", {
120
+ ref: frame,
121
+ style: FILL,
122
+ children: [near && /* @__PURE__ */ jsx("iframe", {
123
+ ref: iframe,
124
+ src: hostParam ? withHost(src, hostParam) : src,
125
+ title,
126
+ allow,
127
+ allowFullScreen: true,
128
+ referrerPolicy,
129
+ scrolling,
130
+ sandbox,
131
+ style: {
132
+ display: "block",
133
+ width: "100%",
134
+ height: "100%",
135
+ border: 0
136
+ },
137
+ onLoad: () => {
138
+ if (!messageHeight) report();
139
+ }
140
+ }), !loaded && /* @__PURE__ */ jsx("div", {
141
+ style: FILL,
142
+ children: placeholder ?? /* @__PURE__ */ jsx(Skeleton, {})
143
+ })]
144
+ })
145
+ });
146
+ }
147
+ function withHost(src, name) {
148
+ return `${src}${src.includes("?") ? "&" : "?"}${encodeURIComponent(name)}=${encodeURIComponent(window.location.hostname)}`;
149
+ }
150
+ function Skeleton({ minHeight }) {
151
+ return /* @__PURE__ */ jsx("div", {
152
+ "aria-hidden": "true",
153
+ style: {
154
+ width: "100%",
155
+ height: "100%",
156
+ minHeight,
157
+ background: "rgba(128, 128, 128, 0.12)"
158
+ }
159
+ });
160
+ }
161
+ // src/parser/verify.ts
162
+ const SHAPES = {
163
+ x: ["post sdk"],
164
+ instagram: ["post sdk"],
165
+ threads: ["post sdk"],
166
+ facebook: [
167
+ "post sdk",
168
+ "video sdk",
169
+ "video iframe"
170
+ ],
171
+ tiktok: ["video iframe"],
172
+ youtube: ["video iframe"],
173
+ telegram: ["post iframe"],
174
+ snapchat: ["post iframe", "video iframe"],
175
+ linkedin: ["post iframe"],
176
+ reddit: ["post iframe"],
177
+ pinterest: ["post sdk"],
178
+ spotify: ["post iframe", "video iframe"],
179
+ vimeo: ["video iframe"],
180
+ twitch: ["video iframe"],
181
+ dailymotion: ["video iframe"]
182
+ };
183
+ /**
184
+ * Security: the embed may be host-built, and its url, id and `fallbackHtml` are written
185
+ * into the page: only what this parser itself produces passes (docs/decisions.md D35).
186
+ */
187
+ function verifyEmbed(embed) {
188
+ const matched = matchUrl(embed.url);
189
+ if (matched?.platform !== embed.platform || matched.id !== embed.id) return null;
190
+ if (matched.url !== embed.url) return null;
191
+ if (!SHAPES[embed.platform].includes(`${embed.kind} ${embed.variant}`)) return null;
192
+ if (embed.fallbackHtml === void 0) return embed;
193
+ if (trustedFallback(embed, embed.fallbackHtml)) return embed;
194
+ const withoutFallback = { ...embed };
195
+ delete withoutFallback.fallbackHtml;
196
+ return withoutFallback;
197
+ }
198
+ function trustedFallback(embed, fallbackHtml) {
199
+ const whitelist = platforms.find((platform) => platform.platform === embed.platform)?.fallback;
200
+ const nodes = parseHtml(fallbackHtml);
201
+ if (!whitelist || !nodes || rebuild(nodes, whitelist) !== fallbackHtml) return false;
202
+ if (embed.platform !== "x") return true;
203
+ const [root] = parseHtml(`<blockquote class="twitter-tweet">${fallbackHtml}</blockquote>`) ?? [];
204
+ return root?.type === "element" && x$1.parse(root)?.id === embed.id;
205
+ }
206
+ // src/components/shared.ts
207
+ const NAMES = {
208
+ x: "X",
209
+ instagram: "Instagram",
210
+ facebook: "Facebook",
211
+ threads: "Threads",
212
+ tiktok: "TikTok",
213
+ youtube: "YouTube",
214
+ telegram: "Telegram",
215
+ snapchat: "Snapchat",
216
+ linkedin: "LinkedIn",
217
+ reddit: "Reddit",
218
+ pinterest: "Pinterest",
219
+ spotify: "Spotify",
220
+ vimeo: "Vimeo",
221
+ twitch: "Twitch",
222
+ dailymotion: "Dailymotion"
223
+ };
224
+ function resolveEmbed(url, given, platform) {
225
+ const embed = given ?? (url === void 0 ? null : matchUrl(url));
226
+ if (!embed) return { error: `social-embeds: not a ${NAMES[platform]} post URL: ${String(url)}` };
227
+ if (embed.platform !== platform) return { error: `social-embeds: expected a ${NAMES[platform]} embed, got ${NAMES[embed.platform]}` };
228
+ const verified = verifyEmbed(embed);
229
+ if (!verified) return { error: `social-embeds: the ${NAMES[platform]} embed's url and id do not match` };
230
+ return { embed: verified };
231
+ }
232
+ /**
233
+ * Security: options are not verified (docs/decisions.md D68). Keys that choose the content
234
+ * come only from the verified url and id.
235
+ */
236
+ function optionsWithout(options, reserved) {
237
+ return Object.entries(options).filter(([key]) => !reserved.includes(key));
238
+ }
239
+ /** Later entries replace earlier ones with the same name. */
240
+ function query(...sources) {
241
+ const params = /* @__PURE__ */ new Map();
242
+ for (const source of sources) for (const [key, value] of source ?? []) params.set(key, String(value));
243
+ const pairs = [...params].map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
244
+ return pairs.length > 0 ? `?${pairs.join("&")}` : "";
245
+ }
246
+ /** Player parameters take 0 and 1, so booleans become numbers. */
247
+ function playerParams(props, names) {
248
+ const params = [];
249
+ for (const [prop, name] of Object.entries(names)) {
250
+ const value = props[prop];
251
+ if (typeof value === "boolean") params.push([name, value ? 1 : 0]);
252
+ else if (typeof value === "string" || typeof value === "number") params.push([name, value]);
253
+ }
254
+ return params;
255
+ }
256
+ // src/components/dailymotion-embed.tsx
257
+ const PLAYER_ID = /^x[a-z0-9]{3,12}$/;
258
+ const ALLOW$7 = "autoplay; fullscreen; picture-in-picture; web-share";
259
+ /**
260
+ * Dailymotion refuses embeds without a Player ID: one from the embed code or the `playerId`
261
+ * prop, never another account's (docs/decisions.md D63).
262
+ */
263
+ function DailymotionEmbed(props) {
264
+ const { url, embed: given, onError, playerId, mute, startTime, loop, ...frame } = props;
265
+ const resolved = resolveEmbed(url, given, "dailymotion");
266
+ const { playerId: parsedPlayer, ...parsed } = resolved.embed?.options ?? {};
267
+ const player = playerId ?? parsedPlayer;
268
+ const error = resolved.error ?? (player === void 0 ? "social-embeds: a Dailymotion embed needs a Player ID: pass playerId to DailymotionEmbed" : typeof player !== "string" || !PLAYER_ID.test(player) ? `social-embeds: not a Dailymotion Player ID: ${String(player)}` : void 0);
269
+ useReportError(error, onError);
270
+ const { embed } = resolved;
271
+ if (!embed || error) return null;
272
+ const params = [];
273
+ if (mute !== void 0) params.push(["mute", String(mute)]);
274
+ if (startTime !== void 0) params.push(["startTime", startTime]);
275
+ if (loop !== void 0) params.push(["loop", String(loop)]);
276
+ return /* @__PURE__ */ jsx(IframeEmbed, {
277
+ ...frame,
278
+ src: `https://geo.dailymotion.com/player/${String(player)}.html${query([["video", embed.id]], optionsWithout(parsed, ["video", "playlist"]), params)}`,
279
+ title: "Dailymotion video player",
280
+ allow: ALLOW$7,
281
+ ratio: {
282
+ width: 16,
283
+ height: 9
284
+ },
285
+ size: embed.size
286
+ });
287
+ }
5
288
  // src/loader/load-script.ts
6
289
  const ATTEMPTS$1 = 3;
7
290
  const RETRY_DELAY_MS$1 = 1e3;
@@ -185,355 +468,122 @@ function watch(container, rendered, done) {
185
468
  }
186
469
  const observer = new MutationObserver(() => {
187
470
  if (!rendered(container)) return;
188
- observer.disconnect();
189
- done();
190
- });
191
- observer.observe(container, {
192
- subtree: true,
193
- childList: true,
194
- attributes: true,
195
- attributeFilter: [
196
- "class",
197
- "style",
198
- "height"
199
- ]
200
- });
201
- return () => {
202
- observer.disconnect();
203
- };
204
- }
205
- function reveal(container, className) {
206
- const blockquote = container.querySelector("blockquote");
207
- if (blockquote && !blockquote.hasAttribute("class")) blockquote.classList.add(className);
208
- }
209
- function hasSizedIframe(container) {
210
- return [...container.querySelectorAll("iframe")].some((iframe) => Number.parseFloat(iframe.style.height) > 0);
211
- }
212
- const xDriver = {
213
- load: () => loadPlatformScript("x"),
214
- render(container, done) {
215
- const twttr = globals().twttr;
216
- const onRendered = (event) => {
217
- if (event.target instanceof Node && container.contains(event.target)) done();
218
- };
219
- twttr?.events?.bind?.("rendered", onRendered);
220
- const stop = watch(container, hasSizedIframe, done);
221
- reveal(container, "twitter-tweet");
222
- twttr?.widgets?.load?.(container);
223
- return () => {
224
- twttr?.events?.unbind?.("rendered", onRendered);
225
- stop();
226
- };
227
- }
228
- };
229
- /** Instagram and Threads share `instgrm.Embeds.process()`, which renders both. */
230
- function processEmbeds() {
231
- const process = globals().instgrm?.Embeds?.process;
232
- if (!process) throw new Error("social-embeds: instgrm.Embeds.process is missing");
233
- process();
234
- }
235
- const instagramDriver = {
236
- load: () => loadPlatformScript("instagram"),
237
- render(container, done) {
238
- const stop = watch(container, (element) => element.querySelector("iframe.instagram-media-rendered") !== null, done);
239
- reveal(container, "instagram-media");
240
- processEmbeds();
241
- return stop;
242
- }
243
- };
244
- const threadsDriver = {
245
- load: () => loadPlatformScript("threads"),
246
- render(container, done) {
247
- const stop = watch(container, (element) => element.querySelector("iframe") !== null && element.querySelector("blockquote") === null, done);
248
- reveal(container, "text-post-media");
249
- processEmbeds();
250
- return stop;
251
- }
252
- };
253
- const facebookDrivers = /* @__PURE__ */ new Map();
254
- function facebookDriver(locale) {
255
- let driver = facebookDrivers.get(locale);
256
- if (!driver) {
257
- driver = {
258
- load: () => loadPlatformScript("facebook", { locale }),
259
- render(container, done) {
260
- const fb = globals().FB;
261
- const parse = fb?.XFBML?.parse;
262
- if (!fb || !parse) throw new Error("social-embeds: FB.XFBML.parse is missing");
263
- const run = () => {
264
- parse(container, done);
265
- };
266
- try {
267
- run();
268
- } catch (error) {
269
- if (!(error instanceof Error) || !/init not called/.test(error.message)) throw error;
270
- fb.init?.({
271
- xfbml: false,
272
- version: FACEBOOK_SDK_VERSION
273
- });
274
- run();
275
- }
276
- return () => {};
277
- }
278
- };
279
- facebookDrivers.set(locale, driver);
280
- }
281
- return driver;
282
- }
283
- const pinterestDriver = {
284
- load: () => loadPlatformScript("pinterest"),
285
- render(container, done) {
286
- const build = globals().PinUtils?.build;
287
- if (!build) throw new Error("social-embeds: PinUtils.build is missing");
288
- const stop = watch(container, (element) => element.querySelector("span[data-pin-id]") !== null, done);
289
- const link = container.querySelector("a");
290
- if (link && !link.hasAttribute("data-pin-do")) link.setAttribute("data-pin-do", "embedPin");
291
- build(container);
292
- return stop;
293
- }
294
- };
295
- // src/components/hooks.ts
296
- const ROOT_MARGIN = "200px 0px";
297
- /** False on the server and in the first client render, so the markup matches on hydration. */
298
- function useNearViewport(ref, lazy) {
299
- const [near, setNear] = useState(false);
300
- useEffect(() => {
301
- const element = ref.current;
302
- if (!lazy || !element || typeof IntersectionObserver === "undefined") {
303
- setNear(true);
304
- return;
305
- }
306
- const observer = new IntersectionObserver((entries) => {
307
- if (entries.some((entry) => entry.isIntersecting)) {
308
- setNear(true);
309
- observer.disconnect();
310
- }
311
- }, { rootMargin: ROOT_MARGIN });
312
- observer.observe(element);
313
- return () => {
314
- observer.disconnect();
315
- };
316
- }, [ref, lazy]);
317
- return near;
318
- }
319
- /** Calls `onError` from an effect, once per distinct message. */
320
- function useReportError(message, onError) {
321
- const latest = useRef(onError);
322
- useEffect(() => {
323
- latest.current = onError;
324
- });
325
- useEffect(() => {
326
- if (message !== void 0) latest.current?.(new Error(message));
327
- }, [message]);
328
- }
329
- // src/components/iframe-embed.tsx
330
- const FILL = {
331
- position: "absolute",
332
- inset: 0
333
- };
334
- const HEIGHT_TIMEOUT_MS = 15e3;
335
- const MAX_REPORTED_HEIGHT = 5e4;
336
- function IframeEmbed({ src, title, allow, referrerPolicy, scrolling, sandbox, ratio, size, messageHeight, startHeight, width = "100%", maxWidth, height, maxHeight, placeholder, lazy = true, onLoad, onError, style, ...rest }) {
337
- const frame = useRef(null);
338
- const iframe = useRef(null);
339
- const near = useNearViewport(frame, lazy);
340
- const [loaded, setLoaded] = useState(false);
341
- const [reportedHeight, setReportedHeight] = useState();
342
- const reported = useRef(false);
343
- const callbacks = useRef({
344
- onLoad,
345
- onError
346
- });
347
- useEffect(() => {
348
- callbacks.current = {
349
- onLoad,
350
- onError
351
- };
352
- });
353
- const report = useCallback(() => {
354
- setLoaded(true);
355
- if (reported.current) return;
356
- reported.current = true;
357
- callbacks.current.onLoad?.();
358
- }, []);
359
- useEffect(() => {
360
- if (!near || !messageHeight) return;
361
- const { origin, read } = messageHeight;
362
- let heard = false;
363
- const listen = (event) => {
364
- if (event.origin !== origin) return;
365
- if (!iframe.current || event.source !== iframe.current.contentWindow) return;
366
- let value;
367
- try {
368
- value = read(event.data);
369
- } catch {
370
- return;
371
- }
372
- if (typeof value !== "number" || !(value > 0 && value <= MAX_REPORTED_HEIGHT)) return;
373
- heard = true;
374
- setReportedHeight(Math.ceil(value));
375
- report();
376
- };
377
- window.addEventListener("message", listen);
378
- const timer = setTimeout(() => {
379
- if (heard) return;
380
- setLoaded(true);
381
- callbacks.current.onError?.(/* @__PURE__ */ new Error(`social-embeds: ${title} did not report its height`));
382
- }, HEIGHT_TIMEOUT_MS);
383
- return () => {
384
- window.removeEventListener("message", listen);
385
- clearTimeout(timer);
386
- };
387
- }, [
388
- near,
389
- messageHeight,
390
- title,
391
- report
392
- ]);
393
- const aspectWidth = size?.width ?? ratio.width;
394
- const aspectHeight = size?.height ?? ratio.height;
395
- const widest = maxHeight === void 0 || height !== void 0 ? void 0 : Math.floor(maxHeight * aspectWidth / aspectHeight);
396
- const wrapper = {
397
- position: "relative",
398
- width,
399
- maxWidth: widest === void 0 || maxWidth !== void 0 && maxWidth < widest ? maxWidth : widest,
400
- ...messageHeight ? { height: reportedHeight ?? startHeight } : height === void 0 ? { aspectRatio: `${String(aspectWidth)} / ${String(aspectHeight)}` } : {
401
- height,
402
- maxHeight
403
- },
404
- ...style
405
- };
406
- return /* @__PURE__ */ jsx("div", {
407
- ...rest,
408
- style: wrapper,
409
- children: /* @__PURE__ */ jsxs("div", {
410
- ref: frame,
411
- style: FILL,
412
- children: [near && /* @__PURE__ */ jsx("iframe", {
413
- ref: iframe,
414
- src,
415
- title,
416
- allow,
417
- allowFullScreen: true,
418
- referrerPolicy,
419
- scrolling,
420
- sandbox,
421
- style: {
422
- display: "block",
423
- width: "100%",
424
- height: "100%",
425
- border: 0
426
- },
427
- onLoad: () => {
428
- if (!messageHeight) report();
429
- }
430
- }), !loaded && /* @__PURE__ */ jsx("div", {
431
- style: FILL,
432
- children: placeholder ?? /* @__PURE__ */ jsx(Skeleton, {})
433
- })]
434
- })
435
- });
436
- }
437
- function Skeleton({ minHeight }) {
438
- return /* @__PURE__ */ jsx("div", {
439
- "aria-hidden": "true",
440
- style: {
441
- width: "100%",
442
- height: "100%",
443
- minHeight,
444
- background: "rgba(128, 128, 128, 0.12)"
445
- }
471
+ observer.disconnect();
472
+ done();
473
+ });
474
+ observer.observe(container, {
475
+ subtree: true,
476
+ childList: true,
477
+ attributes: true,
478
+ attributeFilter: [
479
+ "class",
480
+ "style",
481
+ "height"
482
+ ]
446
483
  });
484
+ return () => {
485
+ observer.disconnect();
486
+ };
447
487
  }
448
- // src/parser/verify.ts
449
- const SHAPES = {
450
- x: ["post sdk"],
451
- instagram: ["post sdk"],
452
- threads: ["post sdk"],
453
- facebook: [
454
- "post sdk",
455
- "video sdk",
456
- "video iframe"
457
- ],
458
- tiktok: ["video iframe"],
459
- youtube: ["video iframe"],
460
- telegram: ["post iframe"],
461
- snapchat: ["post iframe", "video iframe"],
462
- linkedin: ["post iframe"],
463
- reddit: ["post iframe"],
464
- pinterest: ["post sdk"]
465
- };
466
- /**
467
- * Security: the embed may be host-built, and its url, id and `fallbackHtml` are written
468
- * into the page: only what this parser itself produces passes (docs/decisions.md D35).
469
- */
470
- function verifyEmbed(embed) {
471
- const matched = matchUrl(embed.url);
472
- if (matched?.platform !== embed.platform || matched.id !== embed.id) return null;
473
- if (matched.url !== embed.url) return null;
474
- if (!SHAPES[embed.platform].includes(`${embed.kind} ${embed.variant}`)) return null;
475
- if (embed.fallbackHtml === void 0) return embed;
476
- if (trustedFallback(embed, embed.fallbackHtml)) return embed;
477
- const withoutFallback = { ...embed };
478
- delete withoutFallback.fallbackHtml;
479
- return withoutFallback;
488
+ function reveal(container, className) {
489
+ const blockquote = container.querySelector("blockquote");
490
+ if (blockquote && !blockquote.hasAttribute("class")) blockquote.classList.add(className);
480
491
  }
481
- function trustedFallback(embed, fallbackHtml) {
482
- const whitelist = platforms.find((platform) => platform.platform === embed.platform)?.fallback;
483
- const nodes = parseHtml(fallbackHtml);
484
- if (!whitelist || !nodes || rebuild(nodes, whitelist) !== fallbackHtml) return false;
485
- if (embed.platform !== "x") return true;
486
- const [root] = parseHtml(`<blockquote class="twitter-tweet">${fallbackHtml}</blockquote>`) ?? [];
487
- return root?.type === "element" && x$1.parse(root)?.id === embed.id;
492
+ function hasSizedIframe(container) {
493
+ return [...container.querySelectorAll("iframe")].some((iframe) => Number.parseFloat(iframe.style.height) > 0);
488
494
  }
489
- // src/components/shared.ts
490
- const NAMES = {
491
- x: "X",
492
- instagram: "Instagram",
493
- facebook: "Facebook",
494
- threads: "Threads",
495
- tiktok: "TikTok",
496
- youtube: "YouTube",
497
- telegram: "Telegram",
498
- snapchat: "Snapchat",
499
- linkedin: "LinkedIn",
500
- reddit: "Reddit",
501
- pinterest: "Pinterest"
495
+ const xDriver = {
496
+ load: () => loadPlatformScript("x"),
497
+ render(container, done) {
498
+ const twttr = globals().twttr;
499
+ const onRendered = (event) => {
500
+ if (event.target instanceof Node && container.contains(event.target)) done();
501
+ };
502
+ twttr?.events?.bind?.("rendered", onRendered);
503
+ const stop = watch(container, hasSizedIframe, done);
504
+ reveal(container, "twitter-tweet");
505
+ twttr?.widgets?.load?.(container);
506
+ return () => {
507
+ twttr?.events?.unbind?.("rendered", onRendered);
508
+ stop();
509
+ };
510
+ }
502
511
  };
503
- function resolveEmbed(url, given, platform) {
504
- const embed = given ?? (url === void 0 ? null : matchUrl(url));
505
- if (!embed) return { error: `social-embeds: not a ${NAMES[platform]} post URL: ${String(url)}` };
506
- if (embed.platform !== platform) return { error: `social-embeds: expected a ${NAMES[platform]} embed, got ${NAMES[embed.platform]}` };
507
- const verified = verifyEmbed(embed);
508
- if (!verified) return { error: `social-embeds: the ${NAMES[platform]} embed's url and id do not match` };
509
- return { embed: verified };
510
- }
511
- /** Later entries replace earlier ones with the same name. */
512
- function query(...sources) {
513
- const params = /* @__PURE__ */ new Map();
514
- for (const source of sources) for (const [key, value] of source ?? []) params.set(key, String(value));
515
- const pairs = [...params].map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
516
- return pairs.length > 0 ? `?${pairs.join("&")}` : "";
512
+ /** Instagram and Threads share `instgrm.Embeds.process()`, which renders both. */
513
+ function processEmbeds() {
514
+ const process = globals().instgrm?.Embeds?.process;
515
+ if (!process) throw new Error("social-embeds: instgrm.Embeds.process is missing");
516
+ process();
517
517
  }
518
- /** Player parameters take 0 and 1, so booleans become numbers. */
519
- function playerParams(props, names) {
520
- const params = [];
521
- for (const [prop, name] of Object.entries(names)) {
522
- const value = props[prop];
523
- if (typeof value === "boolean") params.push([name, value ? 1 : 0]);
524
- else if (typeof value === "string" || typeof value === "number") params.push([name, value]);
518
+ const instagramDriver = {
519
+ load: () => loadPlatformScript("instagram"),
520
+ render(container, done) {
521
+ const stop = watch(container, (element) => element.querySelector("iframe.instagram-media-rendered") !== null, done);
522
+ reveal(container, "instagram-media");
523
+ processEmbeds();
524
+ return stop;
525
525
  }
526
- return params;
526
+ };
527
+ const threadsDriver = {
528
+ load: () => loadPlatformScript("threads"),
529
+ render(container, done) {
530
+ const stop = watch(container, (element) => element.querySelector("iframe") !== null && element.querySelector("blockquote") === null, done);
531
+ reveal(container, "text-post-media");
532
+ processEmbeds();
533
+ return stop;
534
+ }
535
+ };
536
+ const facebookDrivers = /* @__PURE__ */ new Map();
537
+ function facebookDriver(locale) {
538
+ let driver = facebookDrivers.get(locale);
539
+ if (!driver) {
540
+ driver = {
541
+ load: () => loadPlatformScript("facebook", { locale }),
542
+ render(container, done) {
543
+ const fb = globals().FB;
544
+ const parse = fb?.XFBML?.parse;
545
+ if (!fb || !parse) throw new Error("social-embeds: FB.XFBML.parse is missing");
546
+ const run = () => {
547
+ parse(container, done);
548
+ };
549
+ try {
550
+ run();
551
+ } catch (error) {
552
+ if (!(error instanceof Error) || !/init not called/.test(error.message)) throw error;
553
+ fb.init?.({
554
+ xfbml: false,
555
+ version: FACEBOOK_SDK_VERSION
556
+ });
557
+ run();
558
+ }
559
+ return () => {};
560
+ }
561
+ };
562
+ facebookDrivers.set(locale, driver);
563
+ }
564
+ return driver;
527
565
  }
566
+ const pinterestDriver = {
567
+ load: () => loadPlatformScript("pinterest"),
568
+ render(container, done) {
569
+ const build = globals().PinUtils?.build;
570
+ if (!build) throw new Error("social-embeds: PinUtils.build is missing");
571
+ const stop = watch(container, (element) => element.querySelector("span[data-pin-id]") !== null, done);
572
+ const link = container.querySelector("a");
573
+ if (link && !link.hasAttribute("data-pin-do")) link.setAttribute("data-pin-do", "embedPin");
574
+ build(container);
575
+ return stop;
576
+ }
577
+ };
528
578
  // src/components/facebook-video-iframe.tsx
529
- const ALLOW$4 = "autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share";
579
+ const ALLOW$6 = "autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share";
530
580
  function FacebookVideoIframe({ embed, ...frame }) {
531
581
  const params = Object.entries(embed.options).filter(([key]) => key !== "href");
532
582
  return /* @__PURE__ */ jsx(IframeEmbed, {
533
583
  ...frame,
534
584
  src: `https://www.facebook.com/plugins/video.php${query([["href", embed.url]], params)}`,
535
585
  title: "Facebook video player",
536
- allow: ALLOW$4,
586
+ allow: ALLOW$6,
537
587
  scrolling: "no",
538
588
  ratio: {
539
589
  width: 16,
@@ -818,7 +868,7 @@ function PinterestEmbed(props) {
818
868
  }, markup);
819
869
  }
820
870
  // src/components/reddit-embed.tsx
821
- const PARAMS$3 = {
871
+ const PARAMS$4 = {
822
872
  theme: "theme",
823
873
  showMedia: "showmedia",
824
874
  showTitle: "showtitle",
@@ -827,7 +877,7 @@ const PARAMS$3 = {
827
877
  depth: "depth"
828
878
  };
829
879
  const SANDBOX = "allow-scripts allow-same-origin allow-popups";
830
- const ALLOW$3 = "clipboard-read; clipboard-write";
880
+ const ALLOW$5 = "clipboard-read; clipboard-write";
831
881
  const START_HEIGHT = 316;
832
882
  /** docs/decisions.md D52. */
833
883
  const REDDIT_HEIGHT = {
@@ -853,7 +903,7 @@ function RedditEmbed(props) {
853
903
  locale,
854
904
  depth
855
905
  };
856
- for (const [prop, name] of Object.entries(PARAMS$3)) {
906
+ for (const [prop, name] of Object.entries(PARAMS$4)) {
857
907
  const value = values[prop];
858
908
  if (value !== void 0) fromProps.push([name, value]);
859
909
  }
@@ -864,7 +914,7 @@ function RedditEmbed(props) {
864
914
  maxWidth,
865
915
  src: `https://embed.reddit.com${path}${query([["embed", true]], Object.entries(embed.options), fromProps)}`,
866
916
  title: "Reddit post",
867
- allow: ALLOW$3,
917
+ allow: ALLOW$5,
868
918
  sandbox: SANDBOX,
869
919
  scrolling: "no",
870
920
  ratio: {
@@ -876,7 +926,7 @@ function RedditEmbed(props) {
876
926
  });
877
927
  }
878
928
  // src/components/snapchat-embed.tsx
879
- const ALLOW$2 = "autoplay; camera; microphone; clipboard-write;";
929
+ const ALLOW$4 = "autoplay; camera; microphone; clipboard-write;";
880
930
  /** At most 416px wide by default, the size of Snapchat's own embed code (docs/decisions.md D50). */
881
931
  function SnapchatEmbed(props) {
882
932
  const { url, embed: given, onError, maxWidth = 416, ...frame } = props;
@@ -889,7 +939,7 @@ function SnapchatEmbed(props) {
889
939
  maxWidth,
890
940
  src: `${embed.url}/embed`,
891
941
  title: typeof title === "string" && title !== "" ? title : "Snapchat",
892
- allow: ALLOW$2,
942
+ allow: ALLOW$4,
893
943
  scrolling: "no",
894
944
  ratio: {
895
945
  width: 416,
@@ -898,8 +948,43 @@ function SnapchatEmbed(props) {
898
948
  size: embed.size
899
949
  });
900
950
  }
951
+ // src/components/spotify-embed.tsx
952
+ const ALLOW$3 = "autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture";
953
+ const COMPACT = /* @__PURE__ */ new Set(["track", "episode"]);
954
+ const COMPACT_HEIGHT = 152;
955
+ const FULL_HEIGHT = 352;
956
+ /**
957
+ * A fixed height: the `height` prop, else the embed code's, else 152px for a track or episode
958
+ * and 352px for the rest. A video show keeps its 16:9 aspect ratio instead.
959
+ */
960
+ function SpotifyEmbed(props) {
961
+ const { url, embed: given, onError, height, theme, style, ...frame } = props;
962
+ const { embed, error } = resolveEmbed(url, given, "spotify");
963
+ useReportError(error, onError);
964
+ if (!embed) return null;
965
+ const type = new URL(embed.url).pathname.split("/")[1] ?? "";
966
+ const video = embed.kind === "video";
967
+ const params = query(Object.entries(embed.options), theme === void 0 ? void 0 : [["theme", theme]]);
968
+ return /* @__PURE__ */ jsx(IframeEmbed, {
969
+ ...frame,
970
+ style: {
971
+ borderRadius: 12,
972
+ overflow: "hidden",
973
+ ...style
974
+ },
975
+ height: video ? height : height ?? embed.size?.height ?? (COMPACT.has(type) ? COMPACT_HEIGHT : FULL_HEIGHT),
976
+ src: `https://open.spotify.com/embed/${type}/${embed.id}${video ? "/video" : ""}${params}`,
977
+ title: "Spotify Embed",
978
+ allow: ALLOW$3,
979
+ ratio: {
980
+ width: 16,
981
+ height: 9
982
+ },
983
+ size: video ? embed.size : void 0
984
+ });
985
+ }
901
986
  // src/components/telegram-embed.tsx
902
- const PARAMS$2 = [
987
+ const PARAMS$3 = [
903
988
  ["comment", "comment"],
904
989
  ["userpic", "userpic"],
905
990
  ["mode", "mode"],
@@ -939,7 +1024,7 @@ function TelegramEmbed(props) {
939
1024
  ...darkColor === void 0 ? {} : { darkColor }
940
1025
  };
941
1026
  const params = [["embed", 1]];
942
- for (const [option, name] of PARAMS$2) {
1027
+ for (const [option, name] of PARAMS$3) {
943
1028
  const value = param(name, values[option]);
944
1029
  if (value !== void 0) params.push([name, value]);
945
1030
  }
@@ -986,7 +1071,7 @@ function ThreadsEmbed(props) {
986
1071
  }, markup);
987
1072
  }
988
1073
  // src/components/tiktok-embed.tsx
989
- const PARAMS$1 = {
1074
+ const PARAMS$2 = {
990
1075
  controls: "controls",
991
1076
  progressBar: "progress_bar",
992
1077
  playButton: "play_button",
@@ -1002,7 +1087,7 @@ const PARAMS$1 = {
1002
1087
  closedCaption: "closed_caption",
1003
1088
  forceMuted: "force_muted"
1004
1089
  };
1005
- const ALLOW$1 = "accelerometer; autoplay; clipboard-write; encrypted-media; fullscreen; gyroscope; picture-in-picture; web-share";
1090
+ const ALLOW$2 = "accelerometer; autoplay; clipboard-write; encrypted-media; fullscreen; gyroscope; picture-in-picture; web-share";
1006
1091
  /** At most 325px wide by default, the size of TikTok's own embed code (docs/decisions.md D40). */
1007
1092
  function TikTokEmbed(props) {
1008
1093
  const { url, embed: given, onError, maxWidth = 325, controls, progressBar, playButton, volumeControl, fullscreenButton, timestamp, loop, autoplay, musicInfo, description, rel, nativeContextMenu, closedCaption, forceMuted, ...frame } = props;
@@ -1024,13 +1109,13 @@ function TikTokEmbed(props) {
1024
1109
  nativeContextMenu,
1025
1110
  closedCaption,
1026
1111
  forceMuted
1027
- }, PARAMS$1);
1112
+ }, PARAMS$2);
1028
1113
  return /* @__PURE__ */ jsx(IframeEmbed, {
1029
1114
  ...frame,
1030
1115
  maxWidth,
1031
1116
  src: `https://www.tiktok.com/player/v1/${embed.id}${query(Object.entries(embed.options), params)}`,
1032
1117
  title: "TikTok video player",
1033
- allow: ALLOW$1,
1118
+ allow: ALLOW$2,
1034
1119
  ratio: {
1035
1120
  width: 9,
1036
1121
  height: 16
@@ -1038,6 +1123,106 @@ function TikTokEmbed(props) {
1038
1123
  size: embed.size
1039
1124
  });
1040
1125
  }
1126
+ // src/components/twitch-embed.tsx
1127
+ const RESERVED = [
1128
+ "channel",
1129
+ "video",
1130
+ "collection",
1131
+ "clip",
1132
+ "parent"
1133
+ ];
1134
+ /** The player and its content parameter for the embed's canonical URL (docs/decisions.md D64). */
1135
+ function player(url, id) {
1136
+ const { hostname, pathname } = new URL(url);
1137
+ if (hostname === "clips.twitch.tv") return ["https://clips.twitch.tv/embed", ["clip", id]];
1138
+ const section = pathname.split("/")[1];
1139
+ return ["https://player.twitch.tv/", section === "videos" ? ["video", `v${id}`] : section === "collections" ? ["collection", id] : ["channel", id]];
1140
+ }
1141
+ /** `parent` is the page's own host, added on the client (docs/decisions.md D62, D65). */
1142
+ function TwitchEmbed(props) {
1143
+ const { url, embed: given, onError, autoplay, muted, time, ...frame } = props;
1144
+ const { embed, error } = resolveEmbed(url, given, "twitch");
1145
+ useReportError(error, onError);
1146
+ if (!embed) return null;
1147
+ const params = [];
1148
+ if (autoplay !== void 0) params.push(["autoplay", String(autoplay)]);
1149
+ if (muted !== void 0) params.push(["muted", String(muted)]);
1150
+ if (time !== void 0) params.push(["time", time]);
1151
+ const [base, content] = player(embed.url, embed.id);
1152
+ return /* @__PURE__ */ jsx(IframeEmbed, {
1153
+ ...frame,
1154
+ src: `${base}${query([content], optionsWithout(embed.options, RESERVED), params)}`,
1155
+ title: "Twitch player",
1156
+ allow: "",
1157
+ ratio: {
1158
+ width: 16,
1159
+ height: 9
1160
+ },
1161
+ size: embed.size,
1162
+ hostParam: "parent"
1163
+ });
1164
+ }
1165
+ // src/components/vimeo-embed.tsx
1166
+ const PARAMS$1 = {
1167
+ autopause: "autopause",
1168
+ autoplay: "autoplay",
1169
+ background: "background",
1170
+ byline: "byline",
1171
+ color: "color",
1172
+ controls: "controls",
1173
+ dnt: "dnt",
1174
+ keyboard: "keyboard",
1175
+ loop: "loop",
1176
+ muted: "muted",
1177
+ pip: "pip",
1178
+ playsinline: "playsinline",
1179
+ portrait: "portrait",
1180
+ quality: "quality",
1181
+ speed: "speed",
1182
+ title: "title",
1183
+ transparent: "transparent"
1184
+ };
1185
+ const ALLOW$1 = "autoplay; fullscreen; picture-in-picture; clipboard-write; encrypted-media; web-share";
1186
+ function VimeoEmbed(props) {
1187
+ const { url, embed: given, onError, autopause, autoplay, background, byline, color, controls, dnt, keyboard, loop, muted, pip, playsinline, portrait, quality, speed, title, transparent, t, ...frame } = props;
1188
+ const { embed, error } = resolveEmbed(url, given, "vimeo");
1189
+ useReportError(error, onError);
1190
+ if (!embed) return null;
1191
+ const { t: parsedStart, ...parsed } = embed.options;
1192
+ const hash = new URL(embed.url).pathname.split("/")[2];
1193
+ const params = playerParams({
1194
+ autopause,
1195
+ autoplay,
1196
+ background,
1197
+ byline,
1198
+ color,
1199
+ controls,
1200
+ dnt,
1201
+ keyboard,
1202
+ loop,
1203
+ muted,
1204
+ pip,
1205
+ playsinline,
1206
+ portrait,
1207
+ quality,
1208
+ speed,
1209
+ title,
1210
+ transparent
1211
+ }, PARAMS$1);
1212
+ const start = t ?? parsedStart;
1213
+ return /* @__PURE__ */ jsx(IframeEmbed, {
1214
+ ...frame,
1215
+ src: `https://player.vimeo.com/video/${embed.id}${query(hash ? [["h", hash]] : void 0, optionsWithout(parsed, ["h"]), params)}${start === void 0 ? "" : `#t=${encodeURIComponent(String(start))}`}`,
1216
+ title: "Vimeo video player",
1217
+ allow: ALLOW$1,
1218
+ referrerPolicy: "strict-origin-when-cross-origin",
1219
+ ratio: {
1220
+ width: 16,
1221
+ height: 9
1222
+ },
1223
+ size: embed.size
1224
+ });
1225
+ }
1041
1226
  // src/components/x-embed.tsx
1042
1227
  const ATTRIBUTES = {
1043
1228
  theme: "data-theme",
@@ -1217,6 +1402,30 @@ function SocialEmbed(props) {
1217
1402
  onError,
1218
1403
  embed
1219
1404
  });
1405
+ case "spotify": return /* @__PURE__ */ jsx(SpotifyEmbed, {
1406
+ ...shared,
1407
+ ...frame,
1408
+ onError,
1409
+ embed
1410
+ });
1411
+ case "vimeo": return /* @__PURE__ */ jsx(VimeoEmbed, {
1412
+ ...shared,
1413
+ ...frame,
1414
+ onError,
1415
+ embed
1416
+ });
1417
+ case "twitch": return /* @__PURE__ */ jsx(TwitchEmbed, {
1418
+ ...shared,
1419
+ ...frame,
1420
+ onError,
1421
+ embed
1422
+ });
1423
+ case "dailymotion": return /* @__PURE__ */ jsx(DailymotionEmbed, {
1424
+ ...shared,
1425
+ ...frame,
1426
+ onError,
1427
+ embed
1428
+ });
1220
1429
  }
1221
1430
  }
1222
- export { FacebookEmbed, InstagramEmbed, LinkedInEmbed, PinterestEmbed, RedditEmbed, SnapchatEmbed, SocialEmbed, TelegramEmbed, ThreadsEmbed, TikTokEmbed, XEmbed, YouTubeEmbed };
1431
+ export { DailymotionEmbed, FacebookEmbed, InstagramEmbed, LinkedInEmbed, PinterestEmbed, RedditEmbed, SnapchatEmbed, SocialEmbed, SpotifyEmbed, TelegramEmbed, ThreadsEmbed, TikTokEmbed, TwitchEmbed, VimeoEmbed, XEmbed, YouTubeEmbed };