uiport 0.0.0-bootstrap.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,412 @@
1
+ // Runs inside the source browser. No Node state is captured by this function.
2
+ export function extractSection({
3
+ selector: targetSelector,
4
+ omitScripts = false,
5
+ }) {
6
+ const target = document.querySelector(targetSelector);
7
+ if (!target) throw new Error("Target disappeared before capture.");
8
+ if (
9
+ [
10
+ "HEAD",
11
+ "SCRIPT",
12
+ "STYLE",
13
+ "LINK",
14
+ "META",
15
+ "BASE",
16
+ "IFRAME",
17
+ "OBJECT",
18
+ "EMBED",
19
+ ].includes(target.tagName)
20
+ )
21
+ throw new Error("Select a section container such as main, section or div.");
22
+ let removedExecutable = 0;
23
+ let canvasFailures = 0;
24
+ // Ignore control characters when checking executable URL schemes.
25
+ const unsafe = (value) =>
26
+ /^(javascript:|vbscript:|data:)/i.test(
27
+ // eslint-disable-next-line no-control-regex
28
+ value.replace(/[\u0000-\u0020]/g, ""),
29
+ );
30
+ const clean = (element) => {
31
+ for (const attr of [...element.attributes]) {
32
+ if (
33
+ (omitScripts && /^on/i.test(attr.name)) ||
34
+ ["srcdoc", "autofocus", "ping"].includes(attr.name) ||
35
+ (["href", "xlink:href", "action", "formaction"].includes(attr.name) &&
36
+ omitScripts &&
37
+ unsafe(attr.value))
38
+ ) {
39
+ element.removeAttribute(attr.name);
40
+ removedExecutable++;
41
+ }
42
+ }
43
+ if (element.tagName === "FORM") element.setAttribute("action", "#");
44
+ if (element.hasAttribute("formaction"))
45
+ element.setAttribute("formaction", "#");
46
+ if (["IFRAME", "OBJECT", "EMBED"].includes(element.tagName)) {
47
+ element.removeAttribute("src");
48
+ element.removeAttribute("data");
49
+ element.setAttribute("sandbox", "");
50
+ }
51
+ return element;
52
+ };
53
+
54
+ const deepElements = [];
55
+ const visit = (element) => {
56
+ if (!(element instanceof Element)) return;
57
+ deepElements.push(element);
58
+ if (element.shadowRoot)
59
+ for (const child of element.shadowRoot.children) visit(child);
60
+ for (const child of element.children) visit(child);
61
+ };
62
+ visit(target);
63
+ deepElements.forEach((element, index) =>
64
+ element.setAttribute("data-uiport-id", `up-${index}`),
65
+ );
66
+ target.setAttribute("data-uiport-root", "true");
67
+ let parent = target.parentElement;
68
+ let ancestorId = 0;
69
+ while (parent) {
70
+ parent.setAttribute("data-uiport-id", `up-ancestor-${ancestorId++}`);
71
+ parent = parent.parentElement;
72
+ }
73
+ let preservedScripts = 0;
74
+
75
+ const absoluteUrl = (value, base = document.baseURI) => {
76
+ if (
77
+ !value ||
78
+ /^(data:|blob:|#|javascript:|mailto:|tel:)/i.test(value.trim())
79
+ )
80
+ return value;
81
+ try {
82
+ return new URL(value, base).href;
83
+ } catch {
84
+ return value;
85
+ }
86
+ };
87
+ const absolutizeCssUrls = (cssText, base) =>
88
+ String(cssText || "").replace(
89
+ /url\(\s*(['"]?)([^'")]+)\1\s*\)/gi,
90
+ (full, quote, raw) => {
91
+ const value = raw.trim();
92
+ if (/^(data:|blob:|#)/i.test(value)) return full;
93
+ return `url("${absoluteUrl(value, base)}")`;
94
+ },
95
+ );
96
+
97
+ const cloneDeep = (source) => {
98
+ if (!(source instanceof Element)) return source.cloneNode(true);
99
+ if (
100
+ ["BASE", "META", "LINK"].includes(source.tagName.toUpperCase()) ||
101
+ (omitScripts && source.tagName.toUpperCase() === "SCRIPT")
102
+ ) {
103
+ removedExecutable++;
104
+ return document.createTextNode("");
105
+ }
106
+ if (source.tagName.toUpperCase() === "SCRIPT") preservedScripts++;
107
+ const clone = clean(source.cloneNode(false));
108
+ for (const name of [
109
+ "src",
110
+ "href",
111
+ "xlink:href",
112
+ "poster",
113
+ "data-src",
114
+ "data-background-image",
115
+ ]) {
116
+ if (clone.hasAttribute(name))
117
+ clone.setAttribute(
118
+ name,
119
+ absoluteUrl(clone.getAttribute(name), source.baseURI),
120
+ );
121
+ }
122
+ if (source.hasAttribute("style"))
123
+ clone.setAttribute(
124
+ "style",
125
+ absolutizeCssUrls(source.getAttribute("style"), source.baseURI),
126
+ );
127
+ if (source instanceof HTMLImageElement && source.currentSrc)
128
+ clone.setAttribute("src", source.currentSrc);
129
+ if (source instanceof HTMLInputElement) {
130
+ clone.setAttribute(
131
+ "value",
132
+ ["password", "hidden"].includes(source.type) ? "" : source.value,
133
+ );
134
+ if (source.checked) clone.setAttribute("checked", "");
135
+ else clone.removeAttribute("checked");
136
+ }
137
+ if (source instanceof HTMLTextAreaElement) {
138
+ clone.textContent = source.value;
139
+ return clone;
140
+ }
141
+ if (source instanceof HTMLOptionElement) {
142
+ if (source.selected) clone.setAttribute("selected", "");
143
+ else clone.removeAttribute("selected");
144
+ }
145
+ if (source instanceof HTMLCanvasElement) {
146
+ try {
147
+ const image = document.createElement("img");
148
+ for (const attribute of clone.attributes)
149
+ image.setAttribute(attribute.name, attribute.value);
150
+ image.setAttribute("src", source.toDataURL("image/png"));
151
+ image.setAttribute("data-extracted-canvas-frame", "true");
152
+ image.width = source.width;
153
+ image.height = source.height;
154
+ return image;
155
+ } catch {
156
+ canvasFailures++;
157
+ }
158
+ }
159
+ if (source.tagName === "STYLE") {
160
+ clone.textContent = absolutizeCssUrls(source.textContent, source.baseURI);
161
+ return clone;
162
+ }
163
+ if (source.shadowRoot) {
164
+ const template = document.createElement("template");
165
+ template.setAttribute("shadowrootmode", "open");
166
+ for (const sheet of source.shadowRoot.adoptedStyleSheets || []) {
167
+ try {
168
+ const style = document.createElement("style");
169
+ style.textContent = [...sheet.cssRules]
170
+ .map((rule) => rule.cssText)
171
+ .join("\n");
172
+ template.content.append(style);
173
+ } catch {}
174
+ }
175
+ for (const child of source.shadowRoot.childNodes)
176
+ template.content.append(cloneDeep(child));
177
+ clone.append(template);
178
+ }
179
+ if (source.tagName === "TEMPLATE") {
180
+ for (const child of source.content.childNodes)
181
+ clone.content.append(cloneDeep(child));
182
+ } else
183
+ for (const child of source.childNodes) clone.append(cloneDeep(child));
184
+ return clone;
185
+ };
186
+
187
+ const attributesOf = (element) =>
188
+ [...clean(element.cloneNode(false)).attributes].map((attribute) => ({
189
+ name: attribute.name,
190
+ value: attribute.value,
191
+ }));
192
+
193
+ const ancestors = [];
194
+ let ancestor = target.parentElement;
195
+ while (
196
+ ancestor &&
197
+ ancestor !== document.body &&
198
+ ancestor !== document.documentElement
199
+ ) {
200
+ ancestors.unshift({
201
+ tag: ancestor.tagName.toLowerCase(),
202
+ attributes: attributesOf(ancestor),
203
+ });
204
+ ancestor = ancestor.parentElement;
205
+ }
206
+
207
+ const references = [];
208
+ const referenceKeys = new Set();
209
+ const addReference = (kind, value, ownerId, base = document.baseURI) => {
210
+ if (!value || /^(data:|#|javascript:|mailto:|tel:)/i.test(value.trim()))
211
+ return;
212
+ const url = absoluteUrl(value, base);
213
+ const key = `${kind}|${url}`;
214
+ if (!referenceKeys.has(key)) {
215
+ referenceKeys.add(key);
216
+ references.push({ kind, url, ownerId });
217
+ }
218
+ };
219
+ const urlsFromCss = (kind, value, ownerId) => {
220
+ for (const match of String(value || "").matchAll(
221
+ /url\(\s*['"]?([^'")]+)['"]?\s*\)/gi,
222
+ ))
223
+ addReference(kind, match[1], ownerId);
224
+ };
225
+
226
+ const usedFontFamilies = new Set();
227
+ for (const element of deepElements) {
228
+ const ownerId = element.getAttribute("data-uiport-id");
229
+ if (["SCRIPT", "IFRAME", "OBJECT", "EMBED"].includes(element.tagName))
230
+ continue;
231
+ if (element.hasAttribute("srcset")) {
232
+ const srcset = element.getAttribute("srcset");
233
+ if (!srcset.trim().startsWith("data:"))
234
+ for (const candidate of srcset.split(","))
235
+ addReference(
236
+ "srcset",
237
+ candidate.trim().split(/\s+/)[0],
238
+ ownerId,
239
+ element.baseURI,
240
+ );
241
+ }
242
+ for (const attribute of [
243
+ "src",
244
+ "poster",
245
+ "data-src",
246
+ "data-background-image",
247
+ ])
248
+ addReference(
249
+ attribute,
250
+ element.getAttribute(attribute),
251
+ ownerId,
252
+ element.baseURI,
253
+ );
254
+ if (element instanceof HTMLImageElement && element.currentSrc)
255
+ addReference("currentSrc", element.currentSrc, ownerId);
256
+ if (element instanceof SVGUseElement)
257
+ addReference(
258
+ "svg-use",
259
+ element.getAttribute("href") || element.getAttribute("xlink:href"),
260
+ ownerId,
261
+ element.baseURI,
262
+ );
263
+ const style = getComputedStyle(element);
264
+ usedFontFamilies.add(style.fontFamily);
265
+ for (const property of [
266
+ "background-image",
267
+ "mask-image",
268
+ "border-image-source",
269
+ "list-style-image",
270
+ "cursor",
271
+ ]) {
272
+ urlsFromCss(property, style.getPropertyValue(property), ownerId);
273
+ }
274
+ for (const pseudoName of ["::before", "::after", "::marker"]) {
275
+ const pseudo = getComputedStyle(element, pseudoName);
276
+ for (const property of ["background-image", "mask-image", "content"]) {
277
+ urlsFromCss(
278
+ `${pseudoName}:${property}`,
279
+ pseudo.getPropertyValue(property),
280
+ ownerId,
281
+ );
282
+ }
283
+ }
284
+ }
285
+
286
+ const stylesheets = [
287
+ ...document.styleSheets,
288
+ ...document.adoptedStyleSheets,
289
+ ].map((sheet, order) => {
290
+ const owner = sheet.ownerNode;
291
+ let text = null;
292
+ try {
293
+ text = [...sheet.cssRules].map((rule) => rule.cssText).join("\n");
294
+ } catch {
295
+ if (!sheet.href && owner?.tagName === "STYLE") text = owner.textContent;
296
+ }
297
+ return {
298
+ order,
299
+ href: sheet.href || null,
300
+ baseUrl: sheet.href || owner?.baseURI || document.baseURI,
301
+ media: sheet.media?.mediaText || "",
302
+ disabled: sheet.disabled,
303
+ text,
304
+ };
305
+ });
306
+
307
+ const customProperties = {};
308
+ const rootStyle = getComputedStyle(target);
309
+ for (const property of rootStyle) {
310
+ if (property.startsWith("--"))
311
+ customProperties[property] = rootStyle.getPropertyValue(property);
312
+ }
313
+
314
+ const animations = [];
315
+ const seen = new Set();
316
+ for (const element of deepElements) {
317
+ for (const animation of element.getAnimations({ subtree: false })) {
318
+ if (seen.has(animation)) continue;
319
+ seen.add(animation);
320
+ const effect = animation.effect;
321
+ let keyframes = null;
322
+ let timing = null;
323
+ try {
324
+ keyframes = effect?.getKeyframes?.() || null;
325
+ } catch {}
326
+ try {
327
+ timing = effect?.getTiming?.() || null;
328
+ if (timing?.iterations === Infinity) timing.iterations = "Infinity";
329
+ } catch {}
330
+ animations.push({
331
+ kind: animation.constructor?.name || "Animation",
332
+ targetId: effect?.target?.getAttribute?.("data-uiport-id") || null,
333
+ pseudoElement: effect?.pseudoElement || null,
334
+ keyframes,
335
+ timing,
336
+ timeline: animation.timeline?.constructor?.name || null,
337
+ currentTime:
338
+ typeof animation.currentTime === "number"
339
+ ? animation.currentTime
340
+ : null,
341
+ playbackRate: animation.playbackRate,
342
+ playState: animation.playState,
343
+ });
344
+ }
345
+ }
346
+
347
+ const rootTag = target.tagName.toLowerCase();
348
+ const wholeDocument = rootTag === "html";
349
+ const fullPage = wholeDocument || rootTag === "body";
350
+ const content = cloneDeep(fullPage ? document.body : target);
351
+ const html = fullPage ? content.innerHTML : content.outerHTML;
352
+ // A full-document selection also preserves original head scripts/data. CSS,
353
+ // base URLs and the viewport are handled by the export's document builder.
354
+ const headHtml = wholeDocument
355
+ ? [...document.head.children]
356
+ .filter((node) => ["SCRIPT", "NOSCRIPT"].includes(node.tagName))
357
+ .map((node) => cloneDeep(node).outerHTML || "")
358
+ .join("\n")
359
+ : "";
360
+ const visualLibraryPattern =
361
+ /(gsap|scrolltrigger|lottie|aos(?:\.|-|\/)|swiper|splide|lenis|anime(?:\.min)?\.js|motion(?:\.min)?\.js|three(?:\.min)?\.js|pixi|webflow)/i;
362
+ const runtimeScripts =
363
+ omitScripts || wholeDocument
364
+ ? []
365
+ : [...document.scripts]
366
+ .filter(
367
+ (script) =>
368
+ script.src &&
369
+ !target.contains(script) &&
370
+ visualLibraryPattern.test(script.src),
371
+ )
372
+ .map((script) => ({
373
+ src: script.src,
374
+ type: script.type || "",
375
+ async: script.async,
376
+ defer: script.defer,
377
+ noModule: script.noModule,
378
+ }));
379
+ return {
380
+ html,
381
+ rootTag,
382
+ headHtml,
383
+ title: document.title,
384
+ preservedScripts,
385
+ runtimeScripts,
386
+ structure: deepElements
387
+ .map((el) => `${el.tagName}:${el.id}:${el.children.length}`)
388
+ .join("|"),
389
+ baseUrl: document.baseURI,
390
+ sourceScripts: document.scripts.length,
391
+ removedExecutable,
392
+ canvasFailures,
393
+ ancestors,
394
+ htmlAttributes: attributesOf(document.documentElement).filter(
395
+ (attribute) => attribute.name !== "lang",
396
+ ),
397
+ bodyAttributes: attributesOf(document.body),
398
+ references,
399
+ usedFontFamilies: [...usedFontFamilies],
400
+ stylesheets,
401
+ customProperties,
402
+ animations,
403
+ featureCounts: {
404
+ elements: deepElements.length,
405
+ canvas: deepElements.filter((el) => el.tagName === "CANVAS").length,
406
+ iframe: deepElements.filter((el) =>
407
+ ["IFRAME", "OBJECT", "EMBED"].includes(el.tagName),
408
+ ).length,
409
+ video: target.querySelectorAll("video").length,
410
+ },
411
+ };
412
+ }