social-embeds 0.7.1 → 0.8.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.
Files changed (176) hide show
  1. package/README.md +63 -51
  2. package/dist/components/apple-embed.d.ts +7 -0
  3. package/dist/components/apple-embed.js +39 -0
  4. package/dist/components/bluesky-embed.d.ts +10 -0
  5. package/dist/components/bluesky-embed.js +27 -0
  6. package/dist/components/dailymotion-embed.d.ts +9 -0
  7. package/dist/components/dailymotion-embed.js +30 -0
  8. package/dist/components/facebook-embed.d.ts +6 -0
  9. package/dist/components/facebook-embed.js +40 -0
  10. package/dist/components/flickr-embed.d.ts +6 -0
  11. package/dist/components/flickr-embed.js +27 -0
  12. package/dist/components/generic-iframe-embed.d.ts +11 -0
  13. package/dist/components/generic-iframe-embed.js +26 -0
  14. package/dist/components/giphy-embed.d.ts +4 -0
  15. package/dist/components/giphy-embed.js +22 -0
  16. package/dist/components/hooks.js +38 -0
  17. package/dist/components/iframe-embed.js +169 -0
  18. package/dist/components/imgur-embed.d.ts +6 -0
  19. package/dist/components/imgur-embed.js +23 -0
  20. package/dist/components/instagram-embed.d.ts +5 -0
  21. package/dist/components/instagram-embed.js +25 -0
  22. package/dist/components/kick-embed.d.ts +6 -0
  23. package/dist/components/kick-embed.js +25 -0
  24. package/dist/components/linkedin-embed.d.ts +6 -0
  25. package/dist/components/linkedin-embed.js +23 -0
  26. package/dist/components/pinterest-embed.d.ts +5 -0
  27. package/dist/components/pinterest-embed.js +25 -0
  28. package/dist/components/reddit-embed.d.ts +6 -0
  29. package/dist/components/reddit-embed.js +29 -0
  30. package/dist/components/rumble-embed.d.ts +4 -0
  31. package/dist/components/rumble-embed.js +22 -0
  32. package/dist/components/script-embed.js +108 -0
  33. package/dist/components/shared.d.ts +29 -0
  34. package/dist/components/snapchat-embed.d.ts +4 -0
  35. package/dist/components/snapchat-embed.js +22 -0
  36. package/dist/components/social-embed.d.ts +60 -0
  37. package/dist/components/social-embed.js +221 -0
  38. package/dist/components/soundcloud-embed.d.ts +6 -0
  39. package/dist/components/soundcloud-embed.js +33 -0
  40. package/dist/components/spotify-embed.d.ts +9 -0
  41. package/dist/components/spotify-embed.js +25 -0
  42. package/dist/components/strava-embed.d.ts +6 -0
  43. package/dist/components/strava-embed.js +26 -0
  44. package/dist/components/streamable-embed.d.ts +6 -0
  45. package/dist/components/streamable-embed.js +28 -0
  46. package/dist/components/telegram-embed.d.ts +6 -0
  47. package/dist/components/telegram-embed.js +27 -0
  48. package/dist/components/tenor-embed.d.ts +4 -0
  49. package/dist/components/tenor-embed.js +22 -0
  50. package/dist/components/threads-embed.d.ts +5 -0
  51. package/dist/components/threads-embed.js +25 -0
  52. package/dist/components/tiktok-embed.d.ts +6 -0
  53. package/dist/components/tiktok-embed.js +37 -0
  54. package/dist/components/truthsocial-embed.d.ts +4 -0
  55. package/dist/components/truthsocial-embed.js +22 -0
  56. package/dist/components/tumblr-embed.d.ts +4 -0
  57. package/dist/components/tumblr-embed.js +22 -0
  58. package/dist/components/twitch-embed.d.ts +6 -0
  59. package/dist/components/twitch-embed.js +26 -0
  60. package/dist/components/vimeo-embed.d.ts +5 -0
  61. package/dist/components/vimeo-embed.js +40 -0
  62. package/dist/components/x-embed.d.ts +5 -0
  63. package/dist/components/x-embed.js +32 -0
  64. package/dist/components/youtube-embed.d.ts +5 -0
  65. package/dist/components/youtube-embed.js +43 -0
  66. package/dist/core/drivers.js +125 -0
  67. package/dist/core/layout.js +73 -0
  68. package/dist/core/markup.js +30 -0
  69. package/dist/core/params.js +26 -0
  70. package/dist/core/plans/apple.js +44 -0
  71. package/dist/core/plans/bluesky.d.ts +3 -0
  72. package/dist/core/plans/bluesky.js +34 -0
  73. package/dist/core/plans/dailymotion.d.ts +8 -0
  74. package/dist/core/plans/dailymotion.js +37 -0
  75. package/dist/core/plans/facebook.d.ts +15 -0
  76. package/dist/core/plans/facebook.js +79 -0
  77. package/dist/core/plans/flickr.d.ts +7 -0
  78. package/dist/core/plans/flickr.js +37 -0
  79. package/dist/core/plans/generic.js +44 -0
  80. package/dist/core/plans/giphy.js +16 -0
  81. package/dist/core/plans/imgur.d.ts +4 -0
  82. package/dist/core/plans/imgur.js +34 -0
  83. package/dist/core/plans/instagram.d.ts +4 -0
  84. package/dist/core/plans/instagram.js +26 -0
  85. package/dist/core/plans/kick.d.ts +5 -0
  86. package/dist/core/plans/kick.js +22 -0
  87. package/dist/core/plans/linkedin.d.ts +4 -0
  88. package/dist/core/plans/linkedin.js +23 -0
  89. package/dist/core/plans/pinterest.d.ts +4 -0
  90. package/dist/core/plans/pinterest.js +31 -0
  91. package/dist/core/plans/reddit.d.ts +11 -0
  92. package/dist/core/plans/reddit.js +46 -0
  93. package/dist/core/plans/rumble.js +21 -0
  94. package/dist/core/plans/snapchat.js +20 -0
  95. package/dist/core/plans/soundcloud.d.ts +14 -0
  96. package/dist/core/plans/soundcloud.js +37 -0
  97. package/dist/core/plans/spotify.d.ts +4 -0
  98. package/dist/core/plans/spotify.js +29 -0
  99. package/dist/core/plans/strava.d.ts +8 -0
  100. package/dist/core/plans/strava.js +38 -0
  101. package/dist/core/plans/streamable.d.ts +8 -0
  102. package/dist/core/plans/streamable.js +31 -0
  103. package/dist/core/plans/telegram.d.ts +10 -0
  104. package/dist/core/plans/telegram.js +59 -0
  105. package/dist/core/plans/tenor.js +16 -0
  106. package/dist/core/plans/threads.d.ts +4 -0
  107. package/dist/core/plans/threads.js +25 -0
  108. package/dist/core/plans/tiktok.d.ts +17 -0
  109. package/dist/core/plans/tiktok.js +36 -0
  110. package/dist/core/plans/truthsocial.js +43 -0
  111. package/dist/core/plans/tumblr.js +29 -0
  112. package/dist/core/plans/twitch.d.ts +7 -0
  113. package/dist/core/plans/twitch.js +38 -0
  114. package/dist/core/plans/vimeo.d.ts +23 -0
  115. package/dist/core/plans/vimeo.js +42 -0
  116. package/dist/core/plans/x.d.ts +12 -0
  117. package/dist/core/plans/x.js +31 -0
  118. package/dist/core/plans/youtube.d.ts +25 -0
  119. package/dist/core/plans/youtube.js +59 -0
  120. package/dist/core/post-link.js +19 -0
  121. package/dist/core/resolve.js +57 -0
  122. package/dist/core/timing.js +7 -0
  123. package/dist/element.d.ts +1 -1
  124. package/dist/element.js +1 -1
  125. package/dist/index.d.ts +53 -344
  126. package/dist/index.js +30 -2575
  127. package/dist/loader/load-script.js +116 -0
  128. package/dist/loader/platform-scripts.js +89 -0
  129. package/dist/parser/frames.js +70 -0
  130. package/dist/parser/html.js +172 -0
  131. package/dist/parser/iframe.d.ts +24 -0
  132. package/dist/parser/iframe.js +151 -0
  133. package/dist/parser/lookup.js +20 -0
  134. package/dist/parser/match-url.d.ts +3 -0
  135. package/dist/parser/match-url.js +22 -0
  136. package/dist/parser/parse-embed.d.ts +7 -0
  137. package/dist/parser/parse-embed.js +69 -0
  138. package/dist/parser/platform.js +60 -0
  139. package/dist/parser/platforms/applemusic.js +45 -0
  140. package/dist/parser/platforms/applepodcasts.js +41 -0
  141. package/dist/parser/platforms/bluesky.js +64 -0
  142. package/dist/parser/platforms/dailymotion.js +57 -0
  143. package/dist/parser/platforms/facebook.js +181 -0
  144. package/dist/parser/platforms/flickr.js +134 -0
  145. package/dist/parser/platforms/giphy.js +68 -0
  146. package/dist/parser/platforms/imgur.js +107 -0
  147. package/dist/parser/platforms/index.js +62 -0
  148. package/dist/parser/platforms/instagram.js +59 -0
  149. package/dist/parser/platforms/kick.js +61 -0
  150. package/dist/parser/platforms/linkedin.js +42 -0
  151. package/dist/parser/platforms/pinterest.js +59 -0
  152. package/dist/parser/platforms/reddit.js +69 -0
  153. package/dist/parser/platforms/rumble.js +44 -0
  154. package/dist/parser/platforms/snapchat.js +87 -0
  155. package/dist/parser/platforms/soundcloud.js +128 -0
  156. package/dist/parser/platforms/spotify.js +51 -0
  157. package/dist/parser/platforms/strava.js +55 -0
  158. package/dist/parser/platforms/streamable.js +95 -0
  159. package/dist/parser/platforms/telegram.js +61 -0
  160. package/dist/parser/platforms/tenor.js +79 -0
  161. package/dist/parser/platforms/threads.js +51 -0
  162. package/dist/parser/platforms/tiktok.js +48 -0
  163. package/dist/parser/platforms/truthsocial.js +50 -0
  164. package/dist/parser/platforms/tumblr.js +72 -0
  165. package/dist/parser/platforms/twitch.js +128 -0
  166. package/dist/parser/platforms/vimeo.js +95 -0
  167. package/dist/parser/platforms/x.js +65 -0
  168. package/dist/parser/platforms/youtube.js +140 -0
  169. package/dist/parser/types.d.ts +14 -0
  170. package/dist/parser/url.js +41 -0
  171. package/dist/parser/verify.js +63 -0
  172. package/dist/parser.d.ts +4 -1
  173. package/dist/parser.js +4 -1
  174. package/package.json +1 -1
  175. package/dist/index-DrMHAkyG.d.ts +0 -46
  176. package/dist/parser-CovaPg5T.js +0 -2585
@@ -0,0 +1,116 @@
1
+ // src/loader/load-script.ts
2
+ const ATTEMPTS = 3;
3
+ const RETRY_DELAY_MS = 1e3;
4
+ const TIMEOUT_MS = 15e3;
5
+ const HOST_GRACE_MS = 3e3;
6
+ const POLL_MS = 50;
7
+ const loading = /* @__PURE__ */ new Map();
8
+ function loadScript(script) {
9
+ if (typeof document === "undefined") return Promise.reject(/* @__PURE__ */ new Error("social-embeds: platform scripts load only in the browser"));
10
+ let promise = loading.get(script.key);
11
+ if (!promise) {
12
+ promise = load(script).catch((error) => {
13
+ loading.delete(script.key);
14
+ throw error;
15
+ });
16
+ loading.set(script.key, promise);
17
+ }
18
+ return promise;
19
+ }
20
+ async function load(script) {
21
+ if (!script.isPresent()) {
22
+ const hostTags = [...document.querySelectorAll("script[src]")].filter((element) => script.isOwn(element.src));
23
+ if (hostTags.length === 0 || !await hostRan(script, hostTags)) await add(script);
24
+ }
25
+ await script.whenPresent?.();
26
+ }
27
+ function hostRan(script, tags) {
28
+ return new Promise((resolve) => {
29
+ let deadline = Date.now() + (document.readyState === "complete" ? HOST_GRACE_MS : TIMEOUT_MS);
30
+ let timer;
31
+ const pageLoaded = () => {
32
+ deadline = Date.now() + HOST_GRACE_MS;
33
+ };
34
+ const done = () => {
35
+ clearTimeout(timer);
36
+ window.removeEventListener("load", pageLoaded);
37
+ for (const tag of tags) tag.removeEventListener("error", done);
38
+ resolve(script.isPresent());
39
+ };
40
+ const check = () => {
41
+ if (script.isPresent() || Date.now() >= deadline) done();
42
+ else timer = setTimeout(check, POLL_MS);
43
+ };
44
+ window.addEventListener("load", pageLoaded);
45
+ for (const tag of tags) tag.addEventListener("error", done);
46
+ check();
47
+ });
48
+ }
49
+ /** The browser reported the script as failed; its tag has been removed. */
50
+ var LoadError = class extends Error {};
51
+ async function add(script) {
52
+ const ready = script.readyCallback?.();
53
+ for (let attempt = 1;; attempt++) try {
54
+ const element = await insert(script);
55
+ if (attempt >= ATTEMPTS || !script.skipped?.()) break;
56
+ element.remove();
57
+ } catch (error) {
58
+ if (!(error instanceof LoadError) || attempt >= ATTEMPTS) throw error;
59
+ await delay(RETRY_DELAY_MS * 2 ** (attempt - 1));
60
+ }
61
+ await (ready ? timeout(ready, `${script.url} did not report ready`) : poll(script));
62
+ }
63
+ async function insert(script) {
64
+ const restore = script.prepare?.();
65
+ const element = document.createElement("script");
66
+ const loaded = new Promise((resolve, reject) => {
67
+ element.src = script.url;
68
+ element.async = true;
69
+ if (script.crossOrigin) element.crossOrigin = script.crossOrigin;
70
+ const nonce = document.querySelector("script[nonce]")?.nonce;
71
+ if (nonce) element.setAttribute("nonce", nonce);
72
+ element.addEventListener("load", () => {
73
+ resolve();
74
+ });
75
+ element.addEventListener("error", () => {
76
+ element.remove();
77
+ reject(new LoadError(`social-embeds: could not load ${script.url}`));
78
+ });
79
+ document.head.appendChild(element);
80
+ });
81
+ try {
82
+ await timeout(loaded, `${script.url} did not load`);
83
+ } finally {
84
+ restore?.();
85
+ }
86
+ return element;
87
+ }
88
+ function poll(script) {
89
+ return new Promise((resolve, reject) => {
90
+ const deadline = Date.now() + TIMEOUT_MS;
91
+ const check = () => {
92
+ if (script.isPresent()) resolve();
93
+ else if (Date.now() >= deadline) reject(/* @__PURE__ */ new Error(`social-embeds: ${script.url} did not initialise`));
94
+ else setTimeout(check, POLL_MS);
95
+ };
96
+ check();
97
+ });
98
+ }
99
+ function timeout(promise, message) {
100
+ return new Promise((resolve, reject) => {
101
+ const timer = setTimeout(() => {
102
+ reject(/* @__PURE__ */ new Error(`social-embeds: ${message}`));
103
+ }, TIMEOUT_MS);
104
+ promise.then(() => {
105
+ clearTimeout(timer);
106
+ resolve();
107
+ }, (error) => {
108
+ clearTimeout(timer);
109
+ reject(error instanceof Error ? error : new Error(String(error)));
110
+ });
111
+ });
112
+ }
113
+ function delay(ms) {
114
+ return new Promise((resolve) => setTimeout(resolve, ms));
115
+ }
116
+ export { loadScript };
@@ -0,0 +1,89 @@
1
+ import { loadScript } from "./load-script.js";
2
+ // src/loader/platform-scripts.ts
3
+ const globals = () => window;
4
+ /** The SDK refuses to parse without a Graph API version (docs/decisions.md D26). */
5
+ const FACEBOOK_SDK_VERSION = "v26.0";
6
+ const LOCALE = /^[a-z]{2,3}_[A-Z]{2}$/;
7
+ /** Instagram and Threads share `instgrm.Embeds`; each registers its name when loaded. */
8
+ function embedSdkRegistered(name) {
9
+ return () => {
10
+ const embeds = globals().instgrm?.Embeds;
11
+ return embeds?.registeredEmbedSDKs?.[name] === true && typeof embeds.process === "function";
12
+ };
13
+ }
14
+ const x = {
15
+ key: "x",
16
+ url: "https://platform.twitter.com/widgets.js",
17
+ isOwn: (src) => /^https?:\/\/platform\.(?:twitter|x)\.com\/widgets\.js(?:[?#]|$)/.test(src),
18
+ isPresent: () => typeof globals().twttr?.widgets?.load === "function",
19
+ whenPresent: () => new Promise((resolve) => {
20
+ const ready = globals().twttr?.ready;
21
+ if (ready) ready(() => {
22
+ resolve();
23
+ });
24
+ else resolve();
25
+ })
26
+ };
27
+ function besideFacebookSdk() {
28
+ const fb = globals().FB;
29
+ if (!fb || fb.__buffer) return () => {};
30
+ fb.__buffer = true;
31
+ return () => {
32
+ delete fb.__buffer;
33
+ };
34
+ }
35
+ function skippedBesideFacebookSdk(name) {
36
+ const registered = embedSdkRegistered(name);
37
+ return () => {
38
+ const fb = globals().FB;
39
+ return !registered() && fb !== void 0 && !fb.__buffer;
40
+ };
41
+ }
42
+ const instagram = {
43
+ key: "instagram",
44
+ url: "https://www.instagram.com/embed.js",
45
+ isOwn: (src) => /^https?:\/\/www\.instagram\.com\/embed\.js(?:[?#]|$)/.test(src),
46
+ isPresent: embedSdkRegistered("instagram"),
47
+ prepare: besideFacebookSdk,
48
+ skipped: skippedBesideFacebookSdk("instagram")
49
+ };
50
+ const threads = {
51
+ key: "threads",
52
+ url: "https://www.threads.com/embed.js",
53
+ isOwn: (src) => /^https?:\/\/www\.threads\.(?:com|net)\/embed\.js(?:[?#]|$)/.test(src),
54
+ isPresent: embedSdkRegistered("threads"),
55
+ prepare: besideFacebookSdk,
56
+ skipped: skippedBesideFacebookSdk("threads")
57
+ };
58
+ function facebook(locale) {
59
+ return {
60
+ key: "facebook",
61
+ url: `https://connect.facebook.net/${locale}/sdk.js#xfbml=0&version=${FACEBOOK_SDK_VERSION}`,
62
+ crossOrigin: "anonymous",
63
+ isOwn: (src) => /^https?:\/\/connect\.facebook\.net\/[a-z]{2,3}_[A-Z]{2}\/(?:sdk(?:\/debug)?|all)\.js(?:[?#]|$)/.test(src),
64
+ isPresent: () => typeof globals().FB?.XFBML?.parse === "function",
65
+ readyCallback: () => new Promise((resolve) => {
66
+ const previous = globals().fbAsyncInit;
67
+ globals().fbAsyncInit = () => {
68
+ previous?.();
69
+ resolve();
70
+ };
71
+ })
72
+ };
73
+ }
74
+ const pinterest = {
75
+ key: "pinterest",
76
+ url: "https://assets.pinterest.com/js/pinit_main.js",
77
+ isOwn: (src) => /^https?:\/\/assets\.pinterest\.com\/js\/pinit(?:_main)?\.js(?:[?#]|$)/.test(src),
78
+ isPresent: () => typeof globals().PinUtils?.build === "function"
79
+ };
80
+ function loadPlatformScript(platform, { locale = "en_US" } = {}) {
81
+ switch (platform) {
82
+ case "x": return loadScript(x);
83
+ case "instagram": return loadScript(instagram);
84
+ case "threads": return loadScript(threads);
85
+ case "pinterest": return loadScript(pinterest);
86
+ case "facebook": return LOCALE.test(locale) ? loadScript(facebook(locale)) : Promise.reject(/* @__PURE__ */ new Error(`social-embeds: invalid Facebook locale "${locale}"`));
87
+ }
88
+ }
89
+ export { FACEBOOK_SDK_VERSION, loadPlatformScript };
@@ -0,0 +1,70 @@
1
+ import { underPath } from "./platform.js";
2
+ // src/parser/frames.ts
3
+ const YOUTUBE_HOSTS = /* @__PURE__ */ new Set([
4
+ "youtube.com",
5
+ "www.youtube.com",
6
+ "m.youtube.com"
7
+ ]);
8
+ const YOUTUBE_NOCOOKIE_HOSTS = /* @__PURE__ */ new Set(["youtube-nocookie.com", "www.youtube-nocookie.com"]);
9
+ const DAILYMOTION_HOSTS = /* @__PURE__ */ new Set(["dailymotion.com", "www.dailymotion.com"]);
10
+ const DAILYMOTION_PLAYER_HOST = "geo.dailymotion.com";
11
+ const DAILYMOTION_SHORT_HOST = "dai.ly";
12
+ const TIKTOK_HOSTS = /* @__PURE__ */ new Set(["tiktok.com", "www.tiktok.com"]);
13
+ const TWITCH_PLAYER_HOST = "player.twitch.tv";
14
+ const TWITCH_CLIPS_HOST = "clips.twitch.tv";
15
+ const VIMEO_PLAYER_HOST = "player.vimeo.com";
16
+ const FACEBOOK_PLUGIN_HOSTS = /* @__PURE__ */ new Set([
17
+ "facebook.com",
18
+ "www.facebook.com",
19
+ "web.facebook.com"
20
+ ]);
21
+ const GIPHY_PAGE_HOSTS = /* @__PURE__ */ new Set(["giphy.com", "www.giphy.com"]);
22
+ const KICK_PLAYER_HOSTS = /* @__PURE__ */ new Set(["player.kick.com"]);
23
+ const LINKEDIN_FRAME_HOST = "www.linkedin.com";
24
+ const PINTEREST_FRAME_HOST = "assets.pinterest.com";
25
+ const APPLE_MUSIC_FRAME_HOST = "embed.music.apple.com";
26
+ const APPLE_PODCASTS_FRAME_HOST = "embed.podcasts.apple.com";
27
+ const SOUNDCLOUD_WIDGET_HOST = "w.soundcloud.com";
28
+ const SPOTIFY_HOST = "open.spotify.com";
29
+ const youtubeFrame = (src) => YOUTUBE_NOCOOKIE_HOSTS.has(src.host) || YOUTUBE_HOSTS.has(src.host) && underPath(src.path, "/embed");
30
+ const dailymotionFrame = (src) => src.host === "geo.dailymotion.com" || src.host === "dai.ly" || DAILYMOTION_HOSTS.has(src.host) && (underPath(src.path, "/embed") || underPath(src.path, "/video"));
31
+ const tiktokFrame = (src) => TIKTOK_HOSTS.has(src.host) && underPath(src.path, "/player");
32
+ const twitchFrame = (src) => src.host === "player.twitch.tv" || src.host === "clips.twitch.tv" && underPath(src.path, "/embed");
33
+ const vimeoFrame = (src) => src.host === VIMEO_PLAYER_HOST;
34
+ const facebookFrame = (src) => FACEBOOK_PLUGIN_HOSTS.has(src.host) && underPath(src.path, "/plugins");
35
+ const giphyFrame = (src) => GIPHY_PAGE_HOSTS.has(src.host) && underPath(src.path, "/embed");
36
+ const kickFrame = (src) => KICK_PLAYER_HOSTS.has(src.host);
37
+ const linkedinFrame = (src) => src.host === "www.linkedin.com" && underPath(src.path, "/embed");
38
+ const pinterestFrame = (src) => src.host === PINTEREST_FRAME_HOST;
39
+ const appleMusicFrame = (src) => src.host === APPLE_MUSIC_FRAME_HOST;
40
+ const applePodcastsFrame = (src) => src.host === APPLE_PODCASTS_FRAME_HOST;
41
+ const soundcloudFrame = (src) => src.host === SOUNDCLOUD_WIDGET_HOST;
42
+ const spotifyFrame = (src) => src.host === "open.spotify.com" && underPath(src.path, "/embed");
43
+ const rumbleFrame = (src) => src.host === "rumble.com" && underPath(src.path, "/embed");
44
+ const streamableFrame = (src) => src.host === "streamable.com" && (underPath(src.path, "/e") || underPath(src.path, "/o"));
45
+ const tenorFrame = (src) => src.host === "tenor.com" && underPath(src.path, "/embed");
46
+ const truthsocialFrame = (src) => src.host === "truthsocial.com" && src.path.startsWith("/@");
47
+ /** True for a frame a named platform serves, which the generic iframe path must refuse. */
48
+ function ownedFrame(src) {
49
+ return [
50
+ youtubeFrame,
51
+ dailymotionFrame,
52
+ tiktokFrame,
53
+ twitchFrame,
54
+ vimeoFrame,
55
+ facebookFrame,
56
+ giphyFrame,
57
+ kickFrame,
58
+ linkedinFrame,
59
+ pinterestFrame,
60
+ appleMusicFrame,
61
+ applePodcastsFrame,
62
+ soundcloudFrame,
63
+ spotifyFrame,
64
+ rumbleFrame,
65
+ streamableFrame,
66
+ tenorFrame,
67
+ truthsocialFrame
68
+ ].some((owns) => owns(src));
69
+ }
70
+ export { APPLE_MUSIC_FRAME_HOST, APPLE_PODCASTS_FRAME_HOST, DAILYMOTION_HOSTS, DAILYMOTION_PLAYER_HOST, DAILYMOTION_SHORT_HOST, FACEBOOK_PLUGIN_HOSTS, GIPHY_PAGE_HOSTS, KICK_PLAYER_HOSTS, LINKEDIN_FRAME_HOST, PINTEREST_FRAME_HOST, SOUNDCLOUD_WIDGET_HOST, SPOTIFY_HOST, TIKTOK_HOSTS, TWITCH_CLIPS_HOST, TWITCH_PLAYER_HOST, VIMEO_PLAYER_HOST, YOUTUBE_HOSTS, YOUTUBE_NOCOOKIE_HOSTS, appleMusicFrame, applePodcastsFrame, dailymotionFrame, facebookFrame, giphyFrame, kickFrame, linkedinFrame, ownedFrame, pinterestFrame, rumbleFrame, soundcloudFrame, spotifyFrame, streamableFrame, tenorFrame, tiktokFrame, truthsocialFrame, twitchFrame, vimeoFrame, youtubeFrame };
@@ -0,0 +1,172 @@
1
+ // src/parser/html.ts
2
+ const VOID_TAGS = /* @__PURE__ */ new Set([
3
+ "area",
4
+ "base",
5
+ "br",
6
+ "col",
7
+ "embed",
8
+ "hr",
9
+ "img",
10
+ "input",
11
+ "link",
12
+ "meta",
13
+ "source",
14
+ "track",
15
+ "wbr"
16
+ ]);
17
+ const RAW_TEXT_END = /* @__PURE__ */ new Map([["script", /<\/script\s*>/giu], ["style", /<\/style\s*>/giu]]);
18
+ const MAX_DEPTH = 100;
19
+ const START_TAG = /<([a-zA-Z][a-zA-Z0-9-]*)/y;
20
+ const ATTRIBUTE = /\s+([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/y;
21
+ const START_TAG_END = /\s*(\/?)>/y;
22
+ const END_TAG = /<\/([a-zA-Z][a-zA-Z0-9-]*)\s*>/y;
23
+ const NAMED_ENTITIES = /* @__PURE__ */ new Map([
24
+ ["amp", "&"],
25
+ ["lt", "<"],
26
+ ["gt", ">"],
27
+ ["quot", "\""],
28
+ ["apos", "'"],
29
+ ["nbsp", "\xA0"]
30
+ ]);
31
+ function parseHtml(input) {
32
+ const root = {
33
+ type: "element",
34
+ tag: "",
35
+ attrs: /* @__PURE__ */ new Map(),
36
+ children: []
37
+ };
38
+ const open = [root];
39
+ let pos = 0;
40
+ while (pos < input.length) {
41
+ const parent = open[open.length - 1] ?? root;
42
+ const lt = input.indexOf("<", pos);
43
+ const textEnd = lt === -1 ? input.length : lt;
44
+ if (textEnd > pos) parent.children.push({
45
+ type: "text",
46
+ raw: input.slice(pos, textEnd)
47
+ });
48
+ if (lt === -1) break;
49
+ if (input.startsWith("<!--", lt)) {
50
+ const close = input.indexOf("-->", lt + 4);
51
+ if (close === -1) return null;
52
+ parent.children.push({ type: "comment" });
53
+ pos = close + 3;
54
+ continue;
55
+ }
56
+ END_TAG.lastIndex = lt;
57
+ const end = END_TAG.exec(input);
58
+ if (end) {
59
+ if (parent === root || parent.tag !== end[1]?.toLowerCase()) return null;
60
+ open.pop();
61
+ pos = END_TAG.lastIndex;
62
+ continue;
63
+ }
64
+ const start = readStartTag(input, lt);
65
+ if (!start) return null;
66
+ const { element } = start;
67
+ parent.children.push(element);
68
+ pos = start.end;
69
+ const rawTextEnd = start.selfClosing ? void 0 : RAW_TEXT_END.get(element.tag);
70
+ if (rawTextEnd) {
71
+ rawTextEnd.lastIndex = pos;
72
+ const close = rawTextEnd.exec(input);
73
+ if (!close) return null;
74
+ if (close.index > pos) element.children.push({
75
+ type: "text",
76
+ raw: input.slice(pos, close.index)
77
+ });
78
+ pos = rawTextEnd.lastIndex;
79
+ } else if (!start.selfClosing && !VOID_TAGS.has(element.tag)) {
80
+ if (open.length > MAX_DEPTH) return null;
81
+ open.push(element);
82
+ }
83
+ }
84
+ return open.length === 1 ? root.children : null;
85
+ }
86
+ function readStartTag(input, at) {
87
+ START_TAG.lastIndex = at;
88
+ const name = START_TAG.exec(input)?.[1];
89
+ if (name === void 0) return null;
90
+ const attrs = /* @__PURE__ */ new Map();
91
+ let pos = START_TAG.lastIndex;
92
+ for (;;) {
93
+ START_TAG_END.lastIndex = pos;
94
+ const close = START_TAG_END.exec(input);
95
+ if (close) return {
96
+ element: {
97
+ type: "element",
98
+ tag: name.toLowerCase(),
99
+ attrs,
100
+ children: []
101
+ },
102
+ selfClosing: close[1] === "/",
103
+ end: START_TAG_END.lastIndex
104
+ };
105
+ ATTRIBUTE.lastIndex = pos;
106
+ const attribute = ATTRIBUTE.exec(input);
107
+ if (!attribute) return null;
108
+ const [, attributeName = "", doubleQuoted, singleQuoted, unquoted] = attribute;
109
+ const key = attributeName.toLowerCase();
110
+ if (!attrs.has(key)) attrs.set(key, decodeEntities(doubleQuoted ?? singleQuoted ?? unquoted ?? ""));
111
+ pos = ATTRIBUTE.lastIndex;
112
+ }
113
+ }
114
+ /** Decodes numeric references and the few named entities that appear in embed attributes. */
115
+ function decodeEntities(value) {
116
+ return value.replace(/&(#[0-9]{1,7}|#[xX][0-9a-fA-F]{1,6}|[a-zA-Z]+);/g, (reference, body) => {
117
+ if (!body.startsWith("#")) return NAMED_ENTITIES.get(body) ?? reference;
118
+ const hex = body[1] === "x" || body[1] === "X";
119
+ const codePoint = Number.parseInt(body.slice(hex ? 2 : 1), hex ? 16 : 10);
120
+ return codePoint > 0 && codePoint <= 1114111 && (codePoint < 55296 || codePoint > 57343) ? String.fromCodePoint(codePoint) : reference;
121
+ });
122
+ }
123
+ function hasClass(element, name) {
124
+ return (element.attrs.get("class") ?? "").split(/\s+/).includes(name);
125
+ }
126
+ /** In document order. */
127
+ function descendants(nodes) {
128
+ const found = [];
129
+ collect(nodes, found);
130
+ return found;
131
+ }
132
+ function collect(nodes, found) {
133
+ for (const node of nodes) {
134
+ if (node.type !== "element") continue;
135
+ found.push(node);
136
+ collect(node.children, found);
137
+ }
138
+ }
139
+ const URL_ATTRIBUTES = /* @__PURE__ */ new Set(["href", "cite"]);
140
+ const HTTP_URL = /^https?:\/\//i;
141
+ /**
142
+ * Security: the result reaches `dangerouslySetInnerHTML`. Elements off the list are dropped
143
+ * with their content, `href` and `cite` must be http(s) URLs, and text never holds a `<`.
144
+ */
145
+ function rebuild(nodes, whitelist) {
146
+ let html = "";
147
+ for (const node of nodes) {
148
+ if (node.type === "text") {
149
+ html += node.raw;
150
+ continue;
151
+ }
152
+ if (node.type !== "element") continue;
153
+ const allowed = whitelist.get(node.tag);
154
+ if (!allowed) continue;
155
+ html += `<${node.tag}`;
156
+ for (const rule of allowed) {
157
+ const name = typeof rule === "string" ? rule : rule.name;
158
+ const value = node.attrs.get(name);
159
+ if (value === void 0) continue;
160
+ if (typeof rule !== "string" && !rule.value.test(value)) continue;
161
+ if (URL_ATTRIBUTES.has(name) && !HTTP_URL.test(value)) continue;
162
+ html += ` ${name}="${escapeAttribute(value)}"`;
163
+ }
164
+ html += ">";
165
+ if (!VOID_TAGS.has(node.tag)) html += `${rebuild(node.children, whitelist)}</${node.tag}>`;
166
+ }
167
+ return html;
168
+ }
169
+ function escapeAttribute(value) {
170
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
171
+ }
172
+ export { decodeEntities, descendants, escapeAttribute, hasClass, parseHtml, rebuild };
@@ -0,0 +1,24 @@
1
+ declare const REFERRER_POLICIES: readonly ["no-referrer", "origin", "same-origin", "strict-origin", "strict-origin-when-cross-origin"];
2
+ export type ParsedIframe = {
3
+ src: string;
4
+ title?: string;
5
+ allow: string;
6
+ allowFullscreen: boolean;
7
+ referrerPolicy?: (typeof REFERRER_POLICIES)[number];
8
+ sandbox?: string;
9
+ scrolling?: 'no';
10
+ size: {
11
+ width?: number;
12
+ height?: number;
13
+ };
14
+ ratio?: {
15
+ width: number;
16
+ height: number;
17
+ };
18
+ };
19
+ /**
20
+ * Never throws. `null` unless the code holds exactly one `<iframe>` with an https `src` that no
21
+ * named platform owns; everything around the iframe is dropped.
22
+ */
23
+ export declare function parseIframe(html: string): ParsedIframe | null;
24
+ export {};
@@ -0,0 +1,151 @@
1
+ import { descendants, parseHtml } from "./html.js";
2
+ import { sizeOf, unwrapRatio } from "./platform.js";
3
+ import { ownedFrame } from "./frames.js";
4
+ import { parseUrl, pixels } from "./url.js";
5
+ // src/parser/iframe.ts
6
+ const REFERRER_POLICIES = [
7
+ "no-referrer",
8
+ "origin",
9
+ "same-origin",
10
+ "strict-origin",
11
+ "strict-origin-when-cross-origin"
12
+ ];
13
+ const SANDBOX_KEYWORDS = /* @__PURE__ */ new Set([
14
+ "allow-downloads",
15
+ "allow-forms",
16
+ "allow-modals",
17
+ "allow-orientation-lock",
18
+ "allow-pointer-lock",
19
+ "allow-popups",
20
+ "allow-popups-to-escape-sandbox",
21
+ "allow-presentation",
22
+ "allow-same-origin",
23
+ "allow-scripts",
24
+ "allow-top-navigation",
25
+ "allow-top-navigation-by-user-activation",
26
+ "allow-top-navigation-to-custom-protocols"
27
+ ]);
28
+ const FEATURES = /* @__PURE__ */ new Set([
29
+ "autoplay",
30
+ "fullscreen",
31
+ "encrypted-media",
32
+ "picture-in-picture",
33
+ "clipboard-write",
34
+ "web-share"
35
+ ]);
36
+ const HOST = "[a-z0-9-]+(?:\\.[a-z0-9-]+)*(?::\\d{1,5})?";
37
+ const SRC = new RegExp(`^(?:https:)?//${HOST}(?:[/?#]|$)`, "i");
38
+ const ORIGIN = new RegExp(`^(?:\\*|'self'|'src'|'none'|https://${HOST})$`, "i");
39
+ const REWRITTEN_PATH = /\/\.{1,2}(?:\/|$)|\/\/|%(?:2[de]|3\d|[46][1-9a-f]|[57][\da]|5f|7e)/i;
40
+ const ASCII_WHITESPACE = /[\t\n\f\r ]+/;
41
+ const STYLE_SIZE = /^\s*(width|height)\s*:(.*)$/is;
42
+ const PX = /^(\d+)px$/i;
43
+ const WRAPPER = /(?:^|;)\s*padding-bottom:\s*(\d{1,3}(?:\.\d{1,20})?)%\s*(?:;|$)/i;
44
+ /**
45
+ * Never throws. `null` unless the code holds exactly one `<iframe>` with an https `src` that no
46
+ * named platform owns; everything around the iframe is dropped.
47
+ */
48
+ function parseIframe(html) {
49
+ if (typeof html !== "string") return null;
50
+ const nodes = parseHtml(html);
51
+ if (!nodes) return null;
52
+ const elements = descendants(nodes);
53
+ const [iframe, ...others] = elements.filter((element) => element.tag === "iframe");
54
+ if (!iframe || others.length > 0) return null;
55
+ const parent = elements.find((element) => element.children.includes(iframe));
56
+ const { attrs } = iframe;
57
+ const size = sizeOf(iframe) ?? styleSize(iframe);
58
+ return check({
59
+ src: attrs.get("src"),
60
+ title: attrs.get("title"),
61
+ allow: attrs.get("allow"),
62
+ allowFullscreen: attrs.has("allowfullscreen"),
63
+ referrerPolicy: attrs.get("referrerpolicy"),
64
+ sandbox: attrs.get("sandbox"),
65
+ scrolling: attrs.get("scrolling"),
66
+ size: size ?? {},
67
+ ratio: size ? void 0 : parent && unwrapRatio(parent, WRAPPER)?.size
68
+ });
69
+ }
70
+ /** Re-checks a value a host built or stored; `null` when its `src` is unsafe or a named platform's. */
71
+ function checkIframe(embed) {
72
+ return check(embed);
73
+ }
74
+ function check(value) {
75
+ if (typeof value !== "object" || value === null) return null;
76
+ const raw = value;
77
+ const src = checkSrc(raw.src);
78
+ if (src === null) return null;
79
+ const title = typeof raw.title === "string" ? raw.title.trim() : "";
80
+ const policy = typeof raw.referrerPolicy === "string" ? raw.referrerPolicy.toLowerCase() : void 0;
81
+ const referrerPolicy = REFERRER_POLICIES.find((keyword) => keyword === policy);
82
+ const ratio = checkRatio(raw.ratio);
83
+ return {
84
+ src,
85
+ ...title ? { title } : {},
86
+ allow: typeof raw.allow === "string" ? checkAllow(raw.allow) : "",
87
+ allowFullscreen: raw.allowFullscreen === true,
88
+ ...referrerPolicy ? { referrerPolicy } : {},
89
+ ...typeof raw.sandbox === "string" ? { sandbox: checkSandbox(raw.sandbox) } : {},
90
+ ...typeof raw.scrolling === "string" && raw.scrolling.toLowerCase() === "no" ? { scrolling: "no" } : {},
91
+ size: checkSize(raw.size),
92
+ ...ratio ? { ratio } : {}
93
+ };
94
+ }
95
+ function checkSrc(value) {
96
+ if (typeof value !== "string") return null;
97
+ const src = value.trim();
98
+ const url = SRC.test(src) && !src.includes("\\") ? parseUrl(src) : null;
99
+ if (!url || REWRITTEN_PATH.test(url.path)) return null;
100
+ const frame = {
101
+ ...url,
102
+ host: url.host.replace(/:\d+$/, ""),
103
+ path: (url.path.toLowerCase().split(";")[0] ?? "").replaceAll("%2f", "/")
104
+ };
105
+ if (ownedFrame(frame)) return null;
106
+ return src.startsWith("//") ? `https:${src}` : src;
107
+ }
108
+ /** A feature keeps its origin list as written, or is dropped whole when one origin is not safe. */
109
+ function checkAllow(value) {
110
+ return value.split(";").map((directive) => directive.split(ASCII_WHITESPACE).filter(Boolean)).filter(([feature, ...origins]) => feature !== void 0 && FEATURES.has(feature) && origins.every((origin) => ORIGIN.test(origin))).map((tokens) => tokens.join(" ")).join("; ");
111
+ }
112
+ function checkSandbox(value) {
113
+ const keywords = value.split(ASCII_WHITESPACE).map((token) => token.toLowerCase()).filter((token) => SANDBOX_KEYWORDS.has(token));
114
+ return [...new Set(keywords)].join(" ");
115
+ }
116
+ function checkRatio(value) {
117
+ if (typeof value !== "object" || value === null) return void 0;
118
+ const { width, height } = value;
119
+ return isPositive(width) && isPositive(height) ? {
120
+ width,
121
+ height
122
+ } : void 0;
123
+ }
124
+ function isPositive(value) {
125
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
126
+ }
127
+ function checkSize(value) {
128
+ if (typeof value !== "object" || value === null) return {};
129
+ const { width, height } = value;
130
+ const checkedWidth = typeof width === "number" ? pixels(String(width)) : void 0;
131
+ const checkedHeight = typeof height === "number" ? pixels(String(height)) : void 0;
132
+ return {
133
+ ...checkedWidth === void 0 ? {} : { width: checkedWidth },
134
+ ...checkedHeight === void 0 ? {} : { height: checkedHeight }
135
+ };
136
+ }
137
+ function styleSize(iframe) {
138
+ let width;
139
+ let height;
140
+ for (const declaration of (iframe.attrs.get("style") ?? "").split(";")) {
141
+ const [, name = "", value = ""] = STYLE_SIZE.exec(declaration) ?? [];
142
+ const px = pixels(PX.exec(value.trim())?.[1]);
143
+ if (name.toLowerCase() === "width") width = px;
144
+ if (name.toLowerCase() === "height") height = px;
145
+ }
146
+ return width === void 0 && height === void 0 ? void 0 : {
147
+ width,
148
+ height
149
+ };
150
+ }
151
+ export { checkIframe, parseIframe };
@@ -0,0 +1,20 @@
1
+ import { parseUrl } from "./url.js";
2
+ // src/parser/lookup.ts
3
+ const BLUESKY_HOSTS = /* @__PURE__ */ new Set(["bsky.app", "www.bsky.app"]);
4
+ const HANDLE_POST = /^\/profile\/([^/]{1,253})\/post\/[A-Za-z0-9._~:-]{1,512}\/?$/;
5
+ const HANDLE = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
6
+ const RUMBLE_HOSTS = /* @__PURE__ */ new Set(["rumble.com", "www.rumble.com"]);
7
+ const RUMBLE_PAGE = /^\/v[a-z0-9]{1,12}-[^/]{1,300}\.html$/;
8
+ /**
9
+ * The platform of a post URL that only a network lookup could turn into an embed: a Bluesky
10
+ * URL with a handle instead of a DID, or a Rumble page URL. Internal; the parser entry does not export it.
11
+ */
12
+ function needsLookup(url) {
13
+ const parsed = typeof url === "string" ? parseUrl(url) : null;
14
+ if (!parsed) return null;
15
+ if (RUMBLE_HOSTS.has(parsed.host)) return RUMBLE_PAGE.test(parsed.path) ? "rumble" : null;
16
+ if (!BLUESKY_HOSTS.has(parsed.host)) return null;
17
+ const [, profile] = HANDLE_POST.exec(parsed.path) ?? [];
18
+ return profile !== void 0 && HANDLE.test(profile) ? "bluesky" : null;
19
+ }
20
+ export { needsLookup };
@@ -0,0 +1,3 @@
1
+ import { ParsedEmbed } from "./types.js";
2
+ /** Never throws. Options hold only what the URL itself carries (docs/decisions.md D13). */
3
+ export declare function matchUrl(url: string): ParsedEmbed | null;
@@ -0,0 +1,22 @@
1
+ import { platforms } from "./platforms/index.js";
2
+ import { parseUrl } from "./url.js";
3
+ // src/parser/match-url.ts
4
+ /** Never throws. Options hold only what the URL itself carries (docs/decisions.md D13). */
5
+ function matchUrl(url) {
6
+ const parsed = parse(url);
7
+ if (!parsed) return null;
8
+ for (const platform of platforms) {
9
+ const embed = platform.match(parsed);
10
+ if (embed) return embed;
11
+ }
12
+ return null;
13
+ }
14
+ /** `matchUrl` for one platform. */
15
+ function matchWith(parser, url) {
16
+ const parsed = parse(url);
17
+ return parsed && parser.match(parsed);
18
+ }
19
+ function parse(url) {
20
+ return typeof url === "string" ? parseUrl(url) : null;
21
+ }
22
+ export { matchUrl, matchWith };
@@ -0,0 +1,7 @@
1
+ import { ParsedEmbed } from "./types.js";
2
+ /**
3
+ * Never throws. `null` unless the input is one embed element plus, at most, the platform's
4
+ * own scripts, `<div id="fb-root">`, one platform-owned extra such as a credit, whitespace and
5
+ * comments (docs/decisions.md D14).
6
+ */
7
+ export declare function parseEmbed(html: string): ParsedEmbed | null;