@ox-content/vite-plugin 2.8.0 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ogp2.mjs DELETED
@@ -1,299 +0,0 @@
1
- import { unified } from "unified";
2
- import rehypeParse from "rehype-parse";
3
- import rehypeStringify from "rehype-stringify";
4
- //#region src/plugins/ogp.ts
5
- /**
6
- * OGP Card Plugin - Link card embedding
7
- *
8
- * Transforms <OgCard> components into static link preview cards
9
- * by fetching OGP metadata at build time.
10
- */
11
- const defaultOptions = {
12
- timeout: 1e4,
13
- cache: true,
14
- cacheTTL: 36e5,
15
- userAgent: "ox-content-ogp-bot/1.0 (compatible; +https://github.com/ubugeeei/ox-content)"
16
- };
17
- const ogpCache = /* @__PURE__ */ new Map();
18
- function isPrivateIPv4(hostname) {
19
- const parts = hostname.split(".").map(Number);
20
- if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return false;
21
- const [a, b] = parts;
22
- return a === 10 || a === 127 || a === 0 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 169 && b === 254;
23
- }
24
- function isSafeOgpUrl(value) {
25
- try {
26
- const url = new URL(value);
27
- const host = url.hostname.toLowerCase();
28
- const ipv6 = host.replace(/^\[|\]$/g, "");
29
- if (url.protocol !== "http:" && url.protocol !== "https:") return false;
30
- if (host === "localhost" || host.endsWith(".localhost")) return false;
31
- if (ipv6.includes(":") && (ipv6 === "::1" || ipv6.startsWith("fc") || ipv6.startsWith("fd") || ipv6.startsWith("fe80"))) return false;
32
- return !isPrivateIPv4(host);
33
- } catch {
34
- return false;
35
- }
36
- }
37
- /**
38
- * Get element attribute value.
39
- */
40
- function getAttribute(el, name) {
41
- const value = el.properties?.[name];
42
- if (typeof value === "string") return value;
43
- if (Array.isArray(value)) return value.join(" ");
44
- }
45
- /**
46
- * Extract domain from URL.
47
- */
48
- function extractDomain(url) {
49
- try {
50
- return new URL(url).hostname;
51
- } catch {
52
- return url;
53
- }
54
- }
55
- /**
56
- * Get favicon URL for a domain.
57
- */
58
- function getFaviconUrl(url) {
59
- try {
60
- return `https://www.google.com/s2/favicons?domain=${new URL(url).hostname}&sz=32`;
61
- } catch {
62
- return "";
63
- }
64
- }
65
- /**
66
- * Parse OGP metadata from HTML.
67
- */
68
- function parseOgpFromHtml(html, url) {
69
- const result = {
70
- url,
71
- title: ""
72
- };
73
- const titleMatch = html.match(/<title[^>]*>([^<]+)<\/title>/i);
74
- result.title = (html.match(/<meta[^>]*property=["']og:title["'][^>]*content=["']([^"']+)["']/i) || html.match(/<meta[^>]*content=["']([^"']+)["'][^>]*property=["']og:title["']/i))?.[1] || titleMatch?.[1] || extractDomain(url);
75
- const descMatch = html.match(/<meta[^>]*property=["']og:description["'][^>]*content=["']([^"']+)["']/i) || html.match(/<meta[^>]*content=["']([^"']+)["'][^>]*property=["']og:description["']/i) || html.match(/<meta[^>]*name=["']description["'][^>]*content=["']([^"']+)["']/i) || html.match(/<meta[^>]*content=["']([^"']+)["'][^>]*name=["']description["']/i);
76
- if (descMatch) result.description = descMatch[1];
77
- const imageMatch = html.match(/<meta[^>]*property=["']og:image["'][^>]*content=["']([^"']+)["']/i) || html.match(/<meta[^>]*content=["']([^"']+)["'][^>]*property=["']og:image["']/i);
78
- if (imageMatch) {
79
- let imageUrl = imageMatch[1];
80
- if (imageUrl.startsWith("/")) try {
81
- const urlObj = new URL(url);
82
- imageUrl = `${urlObj.protocol}//${urlObj.host}${imageUrl}`;
83
- } catch {}
84
- result.image = imageUrl;
85
- }
86
- const siteNameMatch = html.match(/<meta[^>]*property=["']og:site_name["'][^>]*content=["']([^"']+)["']/i) || html.match(/<meta[^>]*content=["']([^"']+)["'][^>]*property=["']og:site_name["']/i);
87
- if (siteNameMatch) result.siteName = siteNameMatch[1];
88
- result.favicon = getFaviconUrl(url);
89
- return result;
90
- }
91
- /**
92
- * Fetch OGP data for a URL.
93
- */
94
- async function fetchOgpData(url, options) {
95
- if (!isSafeOgpUrl(url)) return null;
96
- if (options.cache) {
97
- const cached = ogpCache.get(url);
98
- if (cached && Date.now() - cached.timestamp < options.cacheTTL) return cached.data;
99
- }
100
- try {
101
- const controller = new AbortController();
102
- const timeoutId = setTimeout(() => controller.abort(), options.timeout);
103
- const response = await fetch(url, {
104
- headers: {
105
- "User-Agent": options.userAgent,
106
- Accept: "text/html,application/xhtml+xml"
107
- },
108
- signal: controller.signal
109
- });
110
- clearTimeout(timeoutId);
111
- if (!response.ok) {
112
- console.warn(`Failed to fetch OGP for ${url}: ${response.status}`);
113
- return null;
114
- }
115
- const data = parseOgpFromHtml(await response.text(), url);
116
- if (options.cache) ogpCache.set(url, {
117
- data,
118
- timestamp: Date.now()
119
- });
120
- return data;
121
- } catch (error) {
122
- if (error instanceof Error && error.name === "AbortError") console.warn(`Timeout fetching OGP for ${url}`);
123
- else console.warn(`Error fetching OGP for ${url}:`, error);
124
- return null;
125
- }
126
- }
127
- /**
128
- * Create OGP card element.
129
- */
130
- function createOgpCard(data) {
131
- const children = [];
132
- const contentChildren = [];
133
- contentChildren.push({
134
- type: "element",
135
- tagName: "div",
136
- properties: { className: ["ox-ogp-title"] },
137
- children: [{
138
- type: "text",
139
- value: data.title
140
- }]
141
- });
142
- if (data.description) contentChildren.push({
143
- type: "element",
144
- tagName: "div",
145
- properties: { className: ["ox-ogp-description"] },
146
- children: [{
147
- type: "text",
148
- value: data.description
149
- }]
150
- });
151
- const metaChildren = [];
152
- if (data.favicon) metaChildren.push({
153
- type: "element",
154
- tagName: "img",
155
- properties: {
156
- className: ["ox-ogp-favicon"],
157
- src: data.favicon,
158
- alt: "",
159
- loading: "lazy"
160
- },
161
- children: []
162
- });
163
- metaChildren.push({
164
- type: "element",
165
- tagName: "span",
166
- properties: { className: ["ox-ogp-domain"] },
167
- children: [{
168
- type: "text",
169
- value: data.siteName || extractDomain(data.url)
170
- }]
171
- });
172
- contentChildren.push({
173
- type: "element",
174
- tagName: "div",
175
- properties: { className: ["ox-ogp-meta"] },
176
- children: metaChildren
177
- });
178
- children.push({
179
- type: "element",
180
- tagName: "div",
181
- properties: { className: ["ox-ogp-content"] },
182
- children: contentChildren
183
- });
184
- if (data.image) children.push({
185
- type: "element",
186
- tagName: "img",
187
- properties: {
188
- className: ["ox-ogp-image"],
189
- src: data.image,
190
- alt: "",
191
- loading: "lazy"
192
- },
193
- children: []
194
- });
195
- return {
196
- type: "element",
197
- tagName: "a",
198
- properties: {
199
- className: ["ox-ogp-card"],
200
- href: isSafeOgpUrl(data.url) ? data.url : "#",
201
- target: "_blank",
202
- rel: "noopener noreferrer"
203
- },
204
- children
205
- };
206
- }
207
- /**
208
- * Create fallback element when OGP data is unavailable.
209
- */
210
- function createFallbackCard(url) {
211
- return {
212
- type: "element",
213
- tagName: "a",
214
- properties: {
215
- className: ["ox-ogp-simple"],
216
- href: isSafeOgpUrl(url) ? url : "#",
217
- target: "_blank",
218
- rel: "noopener noreferrer"
219
- },
220
- children: [{
221
- type: "element",
222
- tagName: "svg",
223
- properties: {
224
- viewBox: "0 0 24 24",
225
- fill: "none",
226
- stroke: "currentColor",
227
- "stroke-width": "2"
228
- },
229
- children: [{
230
- type: "element",
231
- tagName: "path",
232
- properties: { d: "M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14L21 3" },
233
- children: []
234
- }]
235
- }, {
236
- type: "text",
237
- value: extractDomain(url)
238
- }]
239
- };
240
- }
241
- /**
242
- * Collect all OGP URLs from HTML for pre-fetching.
243
- */
244
- async function collectOgpUrls(html) {
245
- const urls = [];
246
- const urlPattern = /<ogcard[^>]*\s+url=["']([^"']+)["']/gi;
247
- let match;
248
- while ((match = urlPattern.exec(html)) !== null) if (isSafeOgpUrl(match[1])) urls.push(match[1]);
249
- return urls;
250
- }
251
- /**
252
- * Pre-fetch all OGP data.
253
- */
254
- async function prefetchOgpData(urls, options) {
255
- const mergedOptions = {
256
- ...defaultOptions,
257
- ...options
258
- };
259
- const results = /* @__PURE__ */ new Map();
260
- await Promise.all(urls.map(async (url) => {
261
- const data = await fetchOgpData(url, mergedOptions);
262
- results.set(url, data);
263
- }));
264
- return results;
265
- }
266
- /**
267
- * Rehype plugin to transform OgCard components.
268
- */
269
- function rehypeOgp(ogpDataMap) {
270
- return (tree) => {
271
- const visit = (node) => {
272
- if ("children" in node) for (let i = 0; i < node.children.length; i++) {
273
- const child = node.children[i];
274
- if (child.type === "element") if (child.tagName.toLowerCase() === "ogcard") {
275
- const url = getAttribute(child, "url");
276
- if (url) {
277
- const ogpData = ogpDataMap.get(url);
278
- const cardElement = ogpData ? createOgpCard(ogpData) : createFallbackCard(url);
279
- node.children[i] = cardElement;
280
- }
281
- } else visit(child);
282
- }
283
- };
284
- visit(tree);
285
- };
286
- }
287
- /**
288
- * Transform OgCard components in HTML.
289
- */
290
- async function transformOgp(html, ogpDataMap, options) {
291
- let dataMap = ogpDataMap;
292
- if (!dataMap) dataMap = await prefetchOgpData(await collectOgpUrls(html), options);
293
- const result = await unified().use(rehypeParse, { fragment: true }).use(rehypeOgp, dataMap).use(rehypeStringify).process(html);
294
- return String(result);
295
- }
296
- //#endregion
297
- export { transformOgp as a, prefetchOgpData as i, fetchOgpData as n, isSafeOgpUrl as r, collectOgpUrls as t };
298
-
299
- //# sourceMappingURL=ogp2.mjs.map
package/dist/ogp2.mjs.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"ogp2.mjs","names":[],"sources":["../src/plugins/ogp.ts"],"sourcesContent":["/**\n * OGP Card Plugin - Link card embedding\n *\n * Transforms <OgCard> components into static link preview cards\n * by fetching OGP metadata at build time.\n */\n\nimport { unified } from \"unified\";\nimport rehypeParse from \"rehype-parse\";\nimport rehypeStringify from \"rehype-stringify\";\nimport type { Root, Element } from \"hast\";\n\nexport interface OgpData {\n url: string;\n title: string;\n description?: string;\n image?: string;\n siteName?: string;\n favicon?: string;\n}\n\nexport interface OgpOptions {\n /** Request timeout in milliseconds. Default: 10000 */\n timeout?: number;\n /** Cache fetched data. Default: true */\n cache?: boolean;\n /** Cache TTL in milliseconds. Default: 3600000 (1 hour) */\n cacheTTL?: number;\n /** User agent for requests */\n userAgent?: string;\n}\n\nconst defaultOptions: Required<OgpOptions> = {\n timeout: 10000,\n cache: true,\n cacheTTL: 3600000,\n userAgent: \"ox-content-ogp-bot/1.0 (compatible; +https://github.com/ubugeeei/ox-content)\",\n};\n\n// Simple in-memory cache\nconst ogpCache = new Map<string, { data: OgpData; timestamp: number }>();\n\nfunction isPrivateIPv4(hostname: string): boolean {\n const parts = hostname.split(\".\").map(Number);\n if (\n parts.length !== 4 ||\n parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)\n ) {\n return false;\n }\n const [a, b] = parts;\n return (\n a === 10 ||\n a === 127 ||\n a === 0 ||\n (a === 172 && b >= 16 && b <= 31) ||\n (a === 192 && b === 168) ||\n (a === 169 && b === 254)\n );\n}\n\nexport function isSafeOgpUrl(value: string): boolean {\n try {\n const url = new URL(value);\n const host = url.hostname.toLowerCase();\n const ipv6 = host.replace(/^\\[|\\]$/g, \"\");\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") return false;\n if (host === \"localhost\" || host.endsWith(\".localhost\")) return false;\n if (\n ipv6.includes(\":\") &&\n (ipv6 === \"::1\" || ipv6.startsWith(\"fc\") || ipv6.startsWith(\"fd\") || ipv6.startsWith(\"fe80\"))\n )\n return false;\n return !isPrivateIPv4(host);\n } catch {\n return false;\n }\n}\n\n/**\n * Get element attribute value.\n */\nfunction getAttribute(el: Element, name: string): string | undefined {\n const value = el.properties?.[name];\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) return value.join(\" \");\n return undefined;\n}\n\n/**\n * Extract domain from URL.\n */\nfunction extractDomain(url: string): string {\n try {\n const urlObj = new URL(url);\n return urlObj.hostname;\n } catch {\n return url;\n }\n}\n\n/**\n * Get favicon URL for a domain.\n */\nfunction getFaviconUrl(url: string): string {\n try {\n const urlObj = new URL(url);\n // Use Google's favicon service as fallback\n return `https://www.google.com/s2/favicons?domain=${urlObj.hostname}&sz=32`;\n } catch {\n return \"\";\n }\n}\n\n/**\n * Parse OGP metadata from HTML.\n */\nfunction parseOgpFromHtml(html: string, url: string): OgpData {\n const result: OgpData = {\n url,\n title: \"\",\n };\n\n // Extract title\n const titleMatch = html.match(/<title[^>]*>([^<]+)<\\/title>/i);\n const ogTitleMatch =\n html.match(/<meta[^>]*property=[\"']og:title[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:title[\"']/i);\n\n result.title = ogTitleMatch?.[1] || titleMatch?.[1] || extractDomain(url);\n\n // Extract description\n const descMatch =\n html.match(/<meta[^>]*property=[\"']og:description[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:description[\"']/i) ||\n html.match(/<meta[^>]*name=[\"']description[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*name=[\"']description[\"']/i);\n\n if (descMatch) {\n result.description = descMatch[1];\n }\n\n // Extract image\n const imageMatch =\n html.match(/<meta[^>]*property=[\"']og:image[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:image[\"']/i);\n\n if (imageMatch) {\n let imageUrl = imageMatch[1];\n // Handle relative URLs\n if (imageUrl.startsWith(\"/\")) {\n try {\n const urlObj = new URL(url);\n imageUrl = `${urlObj.protocol}//${urlObj.host}${imageUrl}`;\n } catch {\n // Keep as is\n }\n }\n result.image = imageUrl;\n }\n\n // Extract site name\n const siteNameMatch =\n html.match(/<meta[^>]*property=[\"']og:site_name[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:site_name[\"']/i);\n\n if (siteNameMatch) {\n result.siteName = siteNameMatch[1];\n }\n\n // Get favicon\n result.favicon = getFaviconUrl(url);\n\n return result;\n}\n\n/**\n * Fetch OGP data for a URL.\n */\nexport async function fetchOgpData(\n url: string,\n options: Required<OgpOptions>,\n): Promise<OgpData | null> {\n if (!isSafeOgpUrl(url)) {\n return null;\n }\n\n // Check cache\n if (options.cache) {\n const cached = ogpCache.get(url);\n if (cached && Date.now() - cached.timestamp < options.cacheTTL) {\n return cached.data;\n }\n }\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), options.timeout);\n\n const response = await fetch(url, {\n headers: {\n \"User-Agent\": options.userAgent,\n Accept: \"text/html,application/xhtml+xml\",\n },\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`Failed to fetch OGP for ${url}: ${response.status}`);\n return null;\n }\n\n const html = await response.text();\n const data = parseOgpFromHtml(html, url);\n\n // Cache the result\n if (options.cache) {\n ogpCache.set(url, { data, timestamp: Date.now() });\n }\n\n return data;\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n console.warn(`Timeout fetching OGP for ${url}`);\n } else {\n console.warn(`Error fetching OGP for ${url}:`, error);\n }\n return null;\n }\n}\n\n/**\n * Create OGP card element.\n */\nfunction createOgpCard(data: OgpData): Element {\n const children: Element[\"children\"] = [];\n\n // Content section\n const contentChildren: Element[\"children\"] = [];\n\n // Title\n contentChildren.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-title\"] },\n children: [{ type: \"text\", value: data.title }],\n });\n\n // Description\n if (data.description) {\n contentChildren.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-description\"] },\n children: [{ type: \"text\", value: data.description }],\n });\n }\n\n // Meta (favicon + domain)\n const metaChildren: Element[\"children\"] = [];\n\n if (data.favicon) {\n metaChildren.push({\n type: \"element\",\n tagName: \"img\",\n properties: {\n className: [\"ox-ogp-favicon\"],\n src: data.favicon,\n alt: \"\",\n loading: \"lazy\",\n },\n children: [],\n });\n }\n\n metaChildren.push({\n type: \"element\",\n tagName: \"span\",\n properties: { className: [\"ox-ogp-domain\"] },\n children: [{ type: \"text\", value: data.siteName || extractDomain(data.url) }],\n });\n\n contentChildren.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-meta\"] },\n children: metaChildren,\n });\n\n children.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-content\"] },\n children: contentChildren,\n });\n\n // Image\n if (data.image) {\n children.push({\n type: \"element\",\n tagName: \"img\",\n properties: {\n className: [\"ox-ogp-image\"],\n src: data.image,\n alt: \"\",\n loading: \"lazy\",\n },\n children: [],\n });\n }\n\n return {\n type: \"element\",\n tagName: \"a\",\n properties: {\n className: [\"ox-ogp-card\"],\n href: isSafeOgpUrl(data.url) ? data.url : \"#\",\n target: \"_blank\",\n rel: \"noopener noreferrer\",\n },\n children,\n };\n}\n\n/**\n * Create fallback element when OGP data is unavailable.\n */\nfunction createFallbackCard(url: string): Element {\n return {\n type: \"element\",\n tagName: \"a\",\n properties: {\n className: [\"ox-ogp-simple\"],\n href: isSafeOgpUrl(url) ? url : \"#\",\n target: \"_blank\",\n rel: \"noopener noreferrer\",\n },\n children: [\n {\n type: \"element\",\n tagName: \"svg\",\n properties: {\n viewBox: \"0 0 24 24\",\n fill: \"none\",\n stroke: \"currentColor\",\n \"stroke-width\": \"2\",\n },\n children: [\n {\n type: \"element\",\n tagName: \"path\",\n properties: {\n d: \"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14L21 3\",\n },\n children: [],\n },\n ],\n },\n { type: \"text\", value: extractDomain(url) },\n ],\n };\n}\n\n/**\n * Collect all OGP URLs from HTML for pre-fetching.\n */\nexport async function collectOgpUrls(html: string): Promise<string[]> {\n const urls: string[] = [];\n const urlPattern = /<ogcard[^>]*\\s+url=[\"']([^\"']+)[\"']/gi;\n\n let match;\n while ((match = urlPattern.exec(html)) !== null) {\n if (isSafeOgpUrl(match[1])) {\n urls.push(match[1]);\n }\n }\n\n return urls;\n}\n\n/**\n * Pre-fetch all OGP data.\n */\nexport async function prefetchOgpData(\n urls: string[],\n options?: OgpOptions,\n): Promise<Map<string, OgpData | null>> {\n const mergedOptions = { ...defaultOptions, ...options };\n const results = new Map<string, OgpData | null>();\n\n await Promise.all(\n urls.map(async (url) => {\n const data = await fetchOgpData(url, mergedOptions);\n results.set(url, data);\n }),\n );\n\n return results;\n}\n\n/**\n * Rehype plugin to transform OgCard components.\n */\nfunction rehypeOgp(ogpDataMap: Map<string, OgpData | null>) {\n return (tree: Root) => {\n const visit = (node: Root | Element) => {\n if (\"children\" in node) {\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n\n if (child.type === \"element\") {\n // Check for <OgCard> component\n if (child.tagName.toLowerCase() === \"ogcard\") {\n const url = getAttribute(child, \"url\");\n\n if (url) {\n const ogpData = ogpDataMap.get(url);\n const cardElement = ogpData ? createOgpCard(ogpData) : createFallbackCard(url);\n node.children[i] = cardElement;\n }\n } else {\n visit(child);\n }\n }\n }\n }\n };\n\n visit(tree);\n };\n}\n\n/**\n * Transform OgCard components in HTML.\n */\nexport async function transformOgp(\n html: string,\n ogpDataMap?: Map<string, OgpData | null>,\n options?: OgpOptions,\n): Promise<string> {\n // If no pre-fetched data, collect and fetch\n let dataMap = ogpDataMap;\n if (!dataMap) {\n const urls = await collectOgpUrls(html);\n dataMap = await prefetchOgpData(urls, options);\n }\n\n const result = await unified()\n .use(rehypeParse, { fragment: true })\n .use(rehypeOgp, dataMap)\n .use(rehypeStringify)\n .process(html);\n\n return String(result);\n}\n"],"mappings":";;;;;;;;;;AAgCA,MAAM,iBAAuC;CAC3C,SAAS;CACT,OAAO;CACP,UAAU;CACV,WAAW;CACZ;AAGD,MAAM,2BAAW,IAAI,KAAmD;AAExE,SAAS,cAAc,UAA2B;CAChD,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AAM,aAAa,KAAK,cAAc;AACnD,UAAQ,IAAI,KAAK,KAAK;GACtB,CACH;AAED,QAAO;;;;;AAMT,SAAS,UAAU,YAAyC;AAC1D,SAAQ,SAAe;EACrB,MAAM,SAAS,SAAyB;AACtC,OAAI,cAAc,KAChB,MAAK,IAAI,IAAI,GAAG,IAAI,KAAK,SAAS,QAAQ,KAAK;IAC7C,MAAM,QAAQ,KAAK,SAAS;AAE5B,QAAI,MAAM,SAAS,UAEjB,KAAI,MAAM,QAAQ,aAAa,KAAK,UAAU;KAC5C,MAAM,MAAM,aAAa,OAAO,MAAM;AAEtC,SAAI,KAAK;MACP,MAAM,UAAU,WAAW,IAAI,IAAI;MACnC,MAAM,cAAc,UAAU,cAAc,QAAQ,GAAG,mBAAmB,IAAI;AAC9E,WAAK,SAAS,KAAK;;UAGrB,OAAM,MAAM;;;AAOtB,QAAM,KAAK;;;;;;AAOf,eAAsB,aACpB,MACA,YACA,SACiB;CAEjB,IAAI,UAAU;AACd,KAAI,CAAC,QAEH,WAAU,MAAM,gBADH,MAAM,eAAe,KAAK,EACD,QAAQ;CAGhD,MAAM,SAAS,MAAM,SAAS,CAC3B,IAAI,aAAa,EAAE,UAAU,MAAM,CAAC,CACpC,IAAI,WAAW,QAAQ,CACvB,IAAI,gBAAgB,CACpB,QAAQ,KAAK;AAEhB,QAAO,OAAO,OAAO"}
package/dist/tabs2.mjs DELETED
@@ -1,182 +0,0 @@
1
- import { unified } from "unified";
2
- import rehypeParse from "rehype-parse";
3
- import rehypeStringify from "rehype-stringify";
4
- //#region src/plugins/tabs.ts
5
- /**
6
- * Tabs Plugin - Pure CSS implementation
7
- *
8
- * Transforms <Tabs>/<Tab> components into accessible HTML
9
- * with CSS :has() based tab switching (no JavaScript required).
10
- */
11
- let tabGroupCounter = 0;
12
- /**
13
- * Reset tab group counter (for testing).
14
- */
15
- function resetTabGroupCounter() {
16
- tabGroupCounter = 0;
17
- }
18
- /**
19
- * Get element attribute value.
20
- */
21
- function getAttribute(el, name) {
22
- const value = el.properties?.[name];
23
- if (typeof value === "string") return value;
24
- if (Array.isArray(value)) return value.join(" ");
25
- }
26
- /**
27
- * Parse Tab elements from Tabs children.
28
- */
29
- function parseTabChildren(children) {
30
- const tabs = [];
31
- for (const child of children) {
32
- if (child.type !== "element") continue;
33
- if (child.tagName.toLowerCase() === "tab") {
34
- const label = getAttribute(child, "label") || `Tab ${tabs.length + 1}`;
35
- tabs.push({
36
- label,
37
- content: child.children.filter((c) => c.type === "element" || c.type === "text")
38
- });
39
- }
40
- }
41
- return tabs;
42
- }
43
- /**
44
- * Create the HTML structure for tabs.
45
- */
46
- function createTabsElement(tabs, groupId) {
47
- const children = [];
48
- const headerChildren = [];
49
- tabs.forEach((tab, index) => {
50
- const inputId = `ox-tab-${groupId}-${index}`;
51
- headerChildren.push({
52
- type: "element",
53
- tagName: "input",
54
- properties: {
55
- type: "radio",
56
- name: `ox-tabs-${groupId}`,
57
- id: inputId,
58
- checked: index === 0 ? true : void 0
59
- },
60
- children: []
61
- });
62
- headerChildren.push({
63
- type: "element",
64
- tagName: "label",
65
- properties: { htmlFor: inputId },
66
- children: [{
67
- type: "text",
68
- value: tab.label
69
- }]
70
- });
71
- });
72
- children.push({
73
- type: "element",
74
- tagName: "div",
75
- properties: { className: ["ox-tabs-header"] },
76
- children: headerChildren
77
- });
78
- tabs.forEach((tab, index) => {
79
- children.push({
80
- type: "element",
81
- tagName: "div",
82
- properties: {
83
- className: ["ox-tab-panel"],
84
- "data-tab": String(index)
85
- },
86
- children: tab.content
87
- });
88
- });
89
- return {
90
- type: "element",
91
- tagName: "div",
92
- properties: {
93
- className: ["ox-tabs"],
94
- "data-group": groupId
95
- },
96
- children
97
- };
98
- }
99
- /**
100
- * Create fallback HTML using <details> elements.
101
- */
102
- function createFallbackElement(tabs) {
103
- const children = [];
104
- tabs.forEach((tab, index) => {
105
- children.push({
106
- type: "element",
107
- tagName: "details",
108
- properties: { open: index === 0 ? true : void 0 },
109
- children: [{
110
- type: "element",
111
- tagName: "summary",
112
- properties: {},
113
- children: [{
114
- type: "text",
115
- value: tab.label
116
- }]
117
- }, {
118
- type: "element",
119
- tagName: "div",
120
- properties: { className: ["ox-tabs-fallback-content"] },
121
- children: tab.content
122
- }]
123
- });
124
- });
125
- return {
126
- type: "element",
127
- tagName: "noscript",
128
- properties: {},
129
- children: [{
130
- type: "element",
131
- tagName: "div",
132
- properties: { className: ["ox-tabs-fallback"] },
133
- children
134
- }]
135
- };
136
- }
137
- /**
138
- * Rehype plugin to transform Tabs components.
139
- */
140
- function rehypeTabs() {
141
- return (tree) => {
142
- const visit = (node) => {
143
- if ("children" in node) for (let i = 0; i < node.children.length; i++) {
144
- const child = node.children[i];
145
- if (child.type === "element") if (child.tagName.toLowerCase() === "tabs") {
146
- const tabs = parseTabChildren(child.children);
147
- if (tabs.length > 0) {
148
- const wrapper = {
149
- type: "element",
150
- tagName: "div",
151
- properties: { className: ["ox-tabs-container"] },
152
- children: [createTabsElement(tabs, String(tabGroupCounter++)), createFallbackElement(tabs)]
153
- };
154
- node.children[i] = wrapper;
155
- }
156
- } else visit(child);
157
- }
158
- };
159
- visit(tree);
160
- };
161
- }
162
- /**
163
- * Transform Tabs components in HTML.
164
- */
165
- async function transformTabs(html) {
166
- const result = await unified().use(rehypeParse, { fragment: true }).use(rehypeTabs).use(rehypeStringify).process(html);
167
- return String(result);
168
- }
169
- /**
170
- * Generate dynamic CSS for :has() based tab switching.
171
- * This is needed because :has() selectors need unique IDs.
172
- */
173
- function generateTabsCSS(groupCount) {
174
- if (groupCount === 0) return "";
175
- let css = "/* Dynamic Tabs CSS */\n";
176
- for (let g = 0; g < groupCount; g++) for (let t = 0; t < 8; t++) css += `.ox-tabs[data-group="${g}"]:has(#ox-tab-${g}-${t}:checked) .ox-tab-panel[data-tab="${t}"] { display: block; }\n`;
177
- return css;
178
- }
179
- //#endregion
180
- export { resetTabGroupCounter as n, transformTabs as r, generateTabsCSS as t };
181
-
182
- //# sourceMappingURL=tabs2.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"tabs2.mjs","names":[],"sources":["../src/plugins/tabs.ts"],"sourcesContent":["/**\n * Tabs Plugin - Pure CSS implementation\n *\n * Transforms <Tabs>/<Tab> components into accessible HTML\n * with CSS :has() based tab switching (no JavaScript required).\n */\n\nimport { unified } from \"unified\";\nimport rehypeParse from \"rehype-parse\";\nimport rehypeStringify from \"rehype-stringify\";\nimport type { Root, Element } from \"hast\";\n\nlet tabGroupCounter = 0;\n\n/**\n * Reset tab group counter (for testing).\n */\nexport function resetTabGroupCounter(): void {\n tabGroupCounter = 0;\n}\n\n/**\n * Get element attribute value.\n */\nfunction getAttribute(el: Element, name: string): string | undefined {\n const value = el.properties?.[name];\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) return value.join(\" \");\n return undefined;\n}\n\ninterface TabData {\n label: string;\n content: Element[];\n}\n\n/**\n * Parse Tab elements from Tabs children.\n */\nfunction parseTabChildren(children: Element[\"children\"]): TabData[] {\n const tabs: TabData[] = [];\n\n for (const child of children) {\n if (child.type !== \"element\") continue;\n\n // Handle <Tab label=\"...\">\n if (child.tagName.toLowerCase() === \"tab\") {\n const label = getAttribute(child, \"label\") || `Tab ${tabs.length + 1}`;\n tabs.push({\n label,\n content: child.children.filter(\n (c): c is Element => c.type === \"element\" || c.type === \"text\",\n ) as Element[],\n });\n }\n }\n\n return tabs;\n}\n\n/**\n * Create the HTML structure for tabs.\n */\nfunction createTabsElement(tabs: TabData[], groupId: string): Element {\n const children: Element[\"children\"] = [];\n\n // Create header with radio inputs and labels\n const headerChildren: Element[\"children\"] = [];\n\n tabs.forEach((tab, index) => {\n const inputId = `ox-tab-${groupId}-${index}`;\n\n // Radio input\n headerChildren.push({\n type: \"element\",\n tagName: \"input\",\n properties: {\n type: \"radio\",\n name: `ox-tabs-${groupId}`,\n id: inputId,\n checked: index === 0 ? true : undefined,\n },\n children: [],\n });\n\n // Label\n headerChildren.push({\n type: \"element\",\n tagName: \"label\",\n properties: {\n htmlFor: inputId,\n },\n children: [{ type: \"text\", value: tab.label }],\n });\n });\n\n // Tabs header\n children.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-tabs-header\"] },\n children: headerChildren,\n });\n\n // Tab panels\n tabs.forEach((tab, index) => {\n children.push({\n type: \"element\",\n tagName: \"div\",\n properties: {\n className: [\"ox-tab-panel\"],\n \"data-tab\": String(index),\n },\n children: tab.content,\n });\n });\n\n return {\n type: \"element\",\n tagName: \"div\",\n properties: {\n className: [\"ox-tabs\"],\n \"data-group\": groupId,\n },\n children,\n };\n}\n\n/**\n * Create fallback HTML using <details> elements.\n */\nfunction createFallbackElement(tabs: TabData[]): Element {\n const children: Element[\"children\"] = [];\n\n tabs.forEach((tab, index) => {\n children.push({\n type: \"element\",\n tagName: \"details\",\n properties: {\n open: index === 0 ? true : undefined,\n },\n children: [\n {\n type: \"element\",\n tagName: \"summary\",\n properties: {},\n children: [{ type: \"text\", value: tab.label }],\n },\n {\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-tabs-fallback-content\"] },\n children: tab.content,\n },\n ],\n });\n });\n\n return {\n type: \"element\",\n tagName: \"noscript\",\n properties: {},\n children: [\n {\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-tabs-fallback\"] },\n children,\n },\n ],\n };\n}\n\n/**\n * Rehype plugin to transform Tabs components.\n */\nfunction rehypeTabs() {\n return (tree: Root) => {\n const visit = (node: Root | Element) => {\n if (\"children\" in node) {\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n\n if (child.type === \"element\") {\n // Check for <Tabs> component\n if (child.tagName.toLowerCase() === \"tabs\") {\n const tabs = parseTabChildren(child.children);\n\n if (tabs.length > 0) {\n const groupId = String(tabGroupCounter++);\n const tabsElement = createTabsElement(tabs, groupId);\n const fallbackElement = createFallbackElement(tabs);\n\n // Replace <Tabs> with new structure\n // Keep main tabs and add noscript fallback\n const wrapper: Element = {\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-tabs-container\"] },\n children: [tabsElement, fallbackElement],\n };\n\n node.children[i] = wrapper;\n }\n } else {\n visit(child);\n }\n }\n }\n }\n };\n\n visit(tree);\n };\n}\n\n/**\n * Transform Tabs components in HTML.\n */\nexport async function transformTabs(html: string): Promise<string> {\n const result = await unified()\n .use(rehypeParse, { fragment: true })\n .use(rehypeTabs)\n .use(rehypeStringify)\n .process(html);\n\n return String(result);\n}\n\n/**\n * Generate dynamic CSS for :has() based tab switching.\n * This is needed because :has() selectors need unique IDs.\n */\nexport function generateTabsCSS(groupCount: number): string {\n if (groupCount === 0) return \"\";\n\n let css = \"/* Dynamic Tabs CSS */\\n\";\n\n for (let g = 0; g < groupCount; g++) {\n for (let t = 0; t < 8; t++) {\n css += `.ox-tabs[data-group=\"${g}\"]:has(#ox-tab-${g}-${t}:checked) .ox-tab-panel[data-tab=\"${t}\"] { display: block; }\\n`;\n }\n }\n\n return css;\n}\n"],"mappings":";;;;;;;;;;AAYA,IAAI,kBAAkB;;;;AAKtB,SAAgB,uBAA6B;AAC3C,mBAAkB;;;;;AAMpB,SAAS,aAAa,IAAa,MAAkC;CACnE,MAAM,QAAQ,GAAG,aAAa;AAC9B,KAAI,OAAO,UAAU,SAAU,QAAO;AACtC,KAAI,MAAM,QAAQ,MAAM,CAAE,QAAO,MAAM,KAAK,IAAI;;;;;AAYlD,SAAS,iBAAiB,UAA0C;CAClE,MAAM,OAAkB,EAAE;AAE1B,MAAK,MAAM,SAAS,UAAU;AAC5B,MAAI,MAAM,SAAS,UAAW;AAG9B,MAAI,MAAM,QAAQ,aAAa,KAAK,OAAO;GACzC,MAAM,QAAQ,aAAa,OAAO,QAAQ,IAAI,OAAO,KAAK,SAAS;AACnE,QAAK,KAAK;IACR;IACA,SAAS,MAAM,SAAS,QACrB,MAAoB,EAAE,SAAS,aAAa,EAAE,SAAS,OACzD;IACF,CAAC;;;AAIN,QAAO;;;;;AAMT,SAAS,kBAAkB,MAAiB,SAA0B;CACpE,MAAM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AAM;EACN,SAAS;EACT,YAAY,EAAE;EACd,UAAU,CACR;GACE,MAAM;GACN,SAAS;GACT,YAAY,EAAE,WAAW,CAAC,mBAAmB,EAAE;GAC/C;GACD,CACF;EACF;;;;;AAMH,SAAS,aAAa;AACpB,SAAQ,SAAe;EACrB,MAAM,SAAS,SAAyB;AACtC,OAAI,cAAc,KAChB,MAAK,IAAI,IAAI,GAAG,IAAI,KAAK,SAAS,QAAQ,KAAK;IAC7C,MAAM,QAAQ,KAAK,SAAS;AAE5B,QAAI,MAAM,SAAS,UAEjB,KAAI,MAAM,QAAQ,aAAa,KAAK,QAAQ;KAC1C,MAAM,OAAO,iBAAiB,MAAM,SAAS;AAE7C,SAAI,KAAK,SAAS,GAAG;MAOnB,MAAM,UAAmB;OACvB,MAAM;OACN,SAAS;OACT,YAAY,EAAE,WAAW,CAAC,oBAAoB,EAAE;OAChD,UAAU,CATQ,kBAAkB,MADtB,OAAO,kBAAkB,CACW,EAC5B,sBAAsB,KAAK,CAQT;OACzC;AAED,WAAK,SAAS,KAAK;;UAGrB,OAAM,MAAM;;;AAOtB,QAAM,KAAK;;;;;;AAOf,eAAsB,cAAc,MAA+B;CACjE,MAAM,SAAS,MAAM,SAAS,CAC3B,IAAI,aAAa,EAAE,UAAU,MAAM,CAAC,CACpC,IAAI,WAAW,CACf,IAAI,gBAAgB,CACpB,QAAQ,KAAK;AAEhB,QAAO,OAAO,OAAO;;;;;;AAOvB,SAAgB,gBAAgB,YAA4B;AAC1D,KAAI,eAAe,EAAG,QAAO;CAE7B,IAAI,MAAM;AAEV,MAAK,IAAI,IAAI,GAAG,IAAI,YAAY,IAC9B,MAAK,IAAI,IAAI,GAAG,IAAI,GAAG,IACrB,QAAO,wBAAwB,EAAE,iBAAiB,EAAE,GAAG,EAAE,oCAAoC,EAAE;AAInG,QAAO"}
package/dist/youtube2.mjs DELETED
@@ -1,112 +0,0 @@
1
- import { unified } from "unified";
2
- import rehypeParse from "rehype-parse";
3
- import rehypeStringify from "rehype-stringify";
4
- //#region src/plugins/youtube.ts
5
- /**
6
- * YouTube Plugin - Privacy-enhanced iframe embedding
7
- *
8
- * Transforms <YouTube> components into responsive iframe embeds
9
- * using youtube-nocookie.com for enhanced privacy.
10
- */
11
- const defaultOptions = {
12
- privacyEnhanced: true,
13
- aspectRatio: "16/9",
14
- allowFullscreen: true,
15
- lazyLoad: true
16
- };
17
- /**
18
- * Get element attribute value.
19
- */
20
- function getAttribute(el, name) {
21
- const value = el.properties?.[name];
22
- if (typeof value === "string") return value;
23
- if (Array.isArray(value)) return value.join(" ");
24
- }
25
- /**
26
- * Extract YouTube video ID from various URL formats.
27
- */
28
- function extractVideoId(input) {
29
- if (/^[a-zA-Z0-9_-]{11}$/.test(input)) return input;
30
- for (const pattern of [/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/v\/)([a-zA-Z0-9_-]{11})/, /youtube\.com\/shorts\/([a-zA-Z0-9_-]{11})/]) {
31
- const match = input.match(pattern);
32
- if (match) return match[1];
33
- }
34
- return null;
35
- }
36
- /**
37
- * Build YouTube embed URL with parameters.
38
- */
39
- function buildEmbedUrl(videoId, options, params) {
40
- const domain = options.privacyEnhanced ? "www.youtube-nocookie.com" : "www.youtube.com";
41
- const url = new URL(`https://${domain}/embed/${videoId}`);
42
- if (params) for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
43
- return url.toString();
44
- }
45
- /**
46
- * Create YouTube embed element.
47
- */
48
- function createYouTubeElement(videoId, options, title, start) {
49
- const params = {};
50
- if (start) params.start = start;
51
- const iframe = {
52
- type: "element",
53
- tagName: "iframe",
54
- properties: {
55
- src: buildEmbedUrl(videoId, options, params),
56
- title: title || `YouTube video ${videoId}`,
57
- allow: "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share",
58
- referrerpolicy: "strict-origin-when-cross-origin",
59
- allowfullscreen: options.allowFullscreen || void 0,
60
- loading: options.lazyLoad ? "lazy" : void 0
61
- },
62
- children: []
63
- };
64
- return {
65
- type: "element",
66
- tagName: "div",
67
- properties: {
68
- className: ["ox-youtube"],
69
- style: `aspect-ratio: ${options.aspectRatio};`
70
- },
71
- children: [iframe]
72
- };
73
- }
74
- /**
75
- * Rehype plugin to transform YouTube components.
76
- */
77
- function rehypeYouTube(options) {
78
- return (tree) => {
79
- const visit = (node) => {
80
- if ("children" in node) for (let i = 0; i < node.children.length; i++) {
81
- const child = node.children[i];
82
- if (child.type === "element") if (child.tagName.toLowerCase() === "youtube") {
83
- const id = getAttribute(child, "id");
84
- const url = getAttribute(child, "url");
85
- const title = getAttribute(child, "title");
86
- const start = getAttribute(child, "start");
87
- const videoId = id ? extractVideoId(id) : url ? extractVideoId(url) : null;
88
- if (videoId) {
89
- const youtubeElement = createYouTubeElement(videoId, options, title, start);
90
- node.children[i] = youtubeElement;
91
- }
92
- } else visit(child);
93
- }
94
- };
95
- visit(tree);
96
- };
97
- }
98
- /**
99
- * Transform YouTube components in HTML.
100
- */
101
- async function transformYouTube(html, options) {
102
- const mergedOptions = {
103
- ...defaultOptions,
104
- ...options
105
- };
106
- const result = await unified().use(rehypeParse, { fragment: true }).use(rehypeYouTube, mergedOptions).use(rehypeStringify).process(html);
107
- return String(result);
108
- }
109
- //#endregion
110
- export { transformYouTube as n, extractVideoId as t };
111
-
112
- //# sourceMappingURL=youtube2.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"youtube2.mjs","names":[],"sources":["../src/plugins/youtube.ts"],"sourcesContent":["/**\n * YouTube Plugin - Privacy-enhanced iframe embedding\n *\n * Transforms <YouTube> components into responsive iframe embeds\n * using youtube-nocookie.com for enhanced privacy.\n */\n\nimport { unified } from \"unified\";\nimport rehypeParse from \"rehype-parse\";\nimport rehypeStringify from \"rehype-stringify\";\nimport type { Root, Element, Properties } from \"hast\";\n\nexport interface YouTubeOptions {\n /** Use privacy-enhanced mode (youtube-nocookie.com). Default: true */\n privacyEnhanced?: boolean;\n /** Default aspect ratio. Default: \"16/9\" */\n aspectRatio?: string;\n /** Allow fullscreen. Default: true */\n allowFullscreen?: boolean;\n /** Lazy load iframe. Default: true */\n lazyLoad?: boolean;\n}\n\nconst defaultOptions: Required<YouTubeOptions> = {\n privacyEnhanced: true,\n aspectRatio: \"16/9\",\n allowFullscreen: true,\n lazyLoad: true,\n};\n\n/**\n * Get element attribute value.\n */\nfunction getAttribute(el: Element, name: string): string | undefined {\n const value = el.properties?.[name];\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) return value.join(\" \");\n return undefined;\n}\n\n/**\n * Extract YouTube video ID from various URL formats.\n */\nexport function extractVideoId(input: string): string | null {\n // Already a video ID (11 characters, alphanumeric + _ -)\n if (/^[a-zA-Z0-9_-]{11}$/.test(input)) {\n return input;\n }\n\n // Full URL patterns\n const patterns = [\n /(?:youtube\\.com\\/watch\\?v=|youtu\\.be\\/|youtube\\.com\\/embed\\/|youtube\\.com\\/v\\/)([a-zA-Z0-9_-]{11})/,\n /youtube\\.com\\/shorts\\/([a-zA-Z0-9_-]{11})/,\n ];\n\n for (const pattern of patterns) {\n const match = input.match(pattern);\n if (match) return match[1];\n }\n\n return null;\n}\n\n/**\n * Build YouTube embed URL with parameters.\n */\nfunction buildEmbedUrl(\n videoId: string,\n options: Required<YouTubeOptions>,\n params?: Record<string, string>,\n): string {\n const domain = options.privacyEnhanced ? \"www.youtube-nocookie.com\" : \"www.youtube.com\";\n const url = new URL(`https://${domain}/embed/${videoId}`);\n\n // Add any custom parameters\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n url.searchParams.set(key, value);\n }\n }\n\n return url.toString();\n}\n\n/**\n * Create YouTube embed element.\n */\nfunction createYouTubeElement(\n videoId: string,\n options: Required<YouTubeOptions>,\n title?: string,\n start?: string,\n): Element {\n const params: Record<string, string> = {};\n if (start) {\n params.start = start;\n }\n\n const embedUrl = buildEmbedUrl(videoId, options, params);\n\n const iframeProps: Properties = {\n src: embedUrl,\n title: title || `YouTube video ${videoId}`,\n allow:\n \"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\",\n referrerpolicy: \"strict-origin-when-cross-origin\",\n allowfullscreen: options.allowFullscreen || undefined,\n loading: options.lazyLoad ? \"lazy\" : undefined,\n };\n\n const iframe: Element = {\n type: \"element\",\n tagName: \"iframe\",\n properties: iframeProps,\n children: [],\n };\n\n return {\n type: \"element\",\n tagName: \"div\",\n properties: {\n className: [\"ox-youtube\"],\n style: `aspect-ratio: ${options.aspectRatio};`,\n },\n children: [iframe],\n };\n}\n\n/**\n * Rehype plugin to transform YouTube components.\n */\nfunction rehypeYouTube(options: Required<YouTubeOptions>) {\n return (tree: Root) => {\n const visit = (node: Root | Element) => {\n if (\"children\" in node) {\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n\n if (child.type === \"element\") {\n // Check for <YouTube> component\n if (child.tagName.toLowerCase() === \"youtube\") {\n const id = getAttribute(child, \"id\");\n const url = getAttribute(child, \"url\");\n const title = getAttribute(child, \"title\");\n const start = getAttribute(child, \"start\");\n\n // Extract video ID from id or url attribute\n const videoId = id ? extractVideoId(id) : url ? extractVideoId(url) : null;\n\n if (videoId) {\n const youtubeElement = createYouTubeElement(videoId, options, title, start);\n node.children[i] = youtubeElement;\n }\n } else {\n visit(child);\n }\n }\n }\n }\n };\n\n visit(tree);\n };\n}\n\n/**\n * Transform YouTube components in HTML.\n */\nexport async function transformYouTube(html: string, options?: YouTubeOptions): Promise<string> {\n const mergedOptions = { ...defaultOptions, ...options };\n\n const result = await unified()\n .use(rehypeParse, { fragment: true })\n .use(rehypeYouTube, mergedOptions)\n .use(rehypeStringify)\n .process(html);\n\n return String(result);\n}\n"],"mappings":";;;;;;;;;;AAuBA,MAAM,iBAA2C;CAC/C,iBAAiB;CACjB,aAAa;CACb,iBAAiB;CACjB,UAAU;CACX;;;;AAKD,SAAS,aAAa,IAAa,MAAkC;CACnE,MAAM,QAAQ,GAAG,aAAa;AAC9B,KAAI,OAAO,UAAU,SAAU,QA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